@twinklerg/coden 0.1.5 → 0.1.6

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/index.js CHANGED
@@ -1,190 +1,330 @@
1
1
  #!/usr/bin/env node
2
2
  // @bun
3
- import{createRequire as VQ}from"node:module";var fQ=Object.create;var{getPrototypeOf:QQ,defineProperty:u3,getOwnPropertyNames:NQ}=Object;var zQ=Object.prototype.hasOwnProperty;function KQ($){return this[$]}var PQ,BQ,c$=($,w,G)=>{var W=$!=null&&typeof $==="object";if(W){var Y=w?PQ??=new WeakMap:BQ??=new WeakMap,Z=Y.get($);if(Z)return Z}G=$!=null?fQ(QQ($)):{};let X=w||!$||!$.__esModule?u3(G,"default",{value:$,enumerable:!0}):G;for(let J of NQ($))if(!zQ.call(X,J))u3(X,J,{get:KQ.bind($,J),enumerable:!0});if(W)Y.set($,X);return X};var L=($,w)=>()=>(w||$((w={exports:{}}).exports,w),w.exports);var nw=VQ(import.meta.url);var pw=L((qQ)=>{class U5 extends Error{constructor($,w,G){super(G);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=w,this.exitCode=$,this.nestedError=void 0}}class h3 extends U5{constructor($){super(1,"commander.invalidArgument",$);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}qQ.CommanderError=U5;qQ.InvalidArgumentError=h3});var Z8=L((OQ)=>{var{InvalidArgumentError:HQ}=pw();class i3{constructor($,w){switch(this.description=w||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,$[0]){case"<":this.required=!0,this._name=$.slice(1,-1);break;case"[":this.required=!1,this._name=$.slice(1,-1);break;default:this.required=!0,this._name=$;break}if(this._name.endsWith("..."))this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_collectValue($,w){if(w===this.defaultValue||!Array.isArray(w))return[$];return w.push($),w}default($,w){return this.defaultValue=$,this.defaultValueDescription=w,this}argParser($){return this.parseArg=$,this}choices($){return this.argChoices=$.slice(),this.parseArg=(w,G)=>{if(!this.argChoices.includes(w))throw new HQ(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(w,G);return w},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function FQ($){let w=$.name()+($.variadic===!0?"...":"");return $.required?"<"+w+">":"["+w+"]"}OQ.Argument=i3;OQ.humanReadableArgName=FQ});var H5=L((AQ)=>{var{humanReadableArgName:kQ}=Z8();class m3{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext($){this.helpWidth=this.helpWidth??$.helpWidth??80}visibleCommands($){let w=$.commands.filter((W)=>!W._hidden),G=$._getHelpCommand();if(G&&!G._hidden)w.push(G);if(this.sortSubcommands)w.sort((W,Y)=>{return W.name().localeCompare(Y.name())});return w}compareOptions($,w){let G=(W)=>{return W.short?W.short.replace(/^-/,""):W.long.replace(/^--/,"")};return G($).localeCompare(G(w))}visibleOptions($){let w=$.options.filter((W)=>!W.hidden),G=$._getHelpOption();if(G&&!G.hidden){let W=G.short&&$._findOption(G.short),Y=G.long&&$._findOption(G.long);if(!W&&!Y)w.push(G);else if(G.long&&!Y)w.push($.createOption(G.long,G.description));else if(G.short&&!W)w.push($.createOption(G.short,G.description))}if(this.sortOptions)w.sort(this.compareOptions);return w}visibleGlobalOptions($){if(!this.showGlobalOptions)return[];let w=[];for(let G=$.parent;G;G=G.parent){let W=G.options.filter((Y)=>!Y.hidden);w.push(...W)}if(this.sortOptions)w.sort(this.compareOptions);return w}visibleArguments($){if($._argsDescription)$.registeredArguments.forEach((w)=>{w.description=w.description||$._argsDescription[w.name()]||""});if($.registeredArguments.find((w)=>w.description))return $.registeredArguments;return[]}subcommandTerm($){let w=$.registeredArguments.map((G)=>kQ(G)).join(" ");return $._name+($._aliases[0]?"|"+$._aliases[0]:"")+($.options.length?" [options]":"")+(w?" "+w:"")}optionTerm($){return $.flags}argumentTerm($){return $.name()}longestSubcommandTermLength($,w){return w.visibleCommands($).reduce((G,W)=>{return Math.max(G,this.displayWidth(w.styleSubcommandTerm(w.subcommandTerm(W))))},0)}longestOptionTermLength($,w){return w.visibleOptions($).reduce((G,W)=>{return Math.max(G,this.displayWidth(w.styleOptionTerm(w.optionTerm(W))))},0)}longestGlobalOptionTermLength($,w){return w.visibleGlobalOptions($).reduce((G,W)=>{return Math.max(G,this.displayWidth(w.styleOptionTerm(w.optionTerm(W))))},0)}longestArgumentTermLength($,w){return w.visibleArguments($).reduce((G,W)=>{return Math.max(G,this.displayWidth(w.styleArgumentTerm(w.argumentTerm(W))))},0)}commandUsage($){let w=$._name;if($._aliases[0])w=w+"|"+$._aliases[0];let G="";for(let W=$.parent;W;W=W.parent)G=W.name()+" "+G;return G+w+" "+$.usage()}commandDescription($){return $.description()}subcommandDescription($){return $.summary()||$.description()}optionDescription($){let w=[];if($.argChoices)w.push(`choices: ${$.argChoices.map((G)=>JSON.stringify(G)).join(", ")}`);if($.defaultValue!==void 0){if($.required||$.optional||$.isBoolean()&&typeof $.defaultValue==="boolean")w.push(`default: ${$.defaultValueDescription||JSON.stringify($.defaultValue)}`)}if($.presetArg!==void 0&&$.optional)w.push(`preset: ${JSON.stringify($.presetArg)}`);if($.envVar!==void 0)w.push(`env: ${$.envVar}`);if(w.length>0){let G=`(${w.join(", ")})`;if($.description)return`${$.description} ${G}`;return G}return $.description}argumentDescription($){let w=[];if($.argChoices)w.push(`choices: ${$.argChoices.map((G)=>JSON.stringify(G)).join(", ")}`);if($.defaultValue!==void 0)w.push(`default: ${$.defaultValueDescription||JSON.stringify($.defaultValue)}`);if(w.length>0){let G=`(${w.join(", ")})`;if($.description)return`${$.description} ${G}`;return G}return $.description}formatItemList($,w,G){if(w.length===0)return[];return[G.styleTitle($),...w,""]}groupItems($,w,G){let W=new Map;return $.forEach((Y)=>{let Z=G(Y);if(!W.has(Z))W.set(Z,[])}),w.forEach((Y)=>{let Z=G(Y);if(!W.has(Z))W.set(Z,[]);W.get(Z).push(Y)}),W}formatHelp($,w){let G=w.padWidth($,w),W=w.helpWidth??80;function Y(f,Q){return w.formatItem(f,G,Q,w)}let Z=[`${w.styleTitle("Usage:")} ${w.styleUsage(w.commandUsage($))}`,""],X=w.commandDescription($);if(X.length>0)Z=Z.concat([w.boxWrap(w.styleCommandDescription(X),W),""]);let J=w.visibleArguments($).map((f)=>{return Y(w.styleArgumentTerm(w.argumentTerm(f)),w.styleArgumentDescription(w.argumentDescription(f)))});if(Z=Z.concat(this.formatItemList("Arguments:",J,w)),this.groupItems($.options,w.visibleOptions($),(f)=>f.helpGroupHeading??"Options:").forEach((f,Q)=>{let N=f.map((z)=>{return Y(w.styleOptionTerm(w.optionTerm(z)),w.styleOptionDescription(w.optionDescription(z)))});Z=Z.concat(this.formatItemList(Q,N,w))}),w.showGlobalOptions){let f=w.visibleGlobalOptions($).map((Q)=>{return Y(w.styleOptionTerm(w.optionTerm(Q)),w.styleOptionDescription(w.optionDescription(Q)))});Z=Z.concat(this.formatItemList("Global Options:",f,w))}return this.groupItems($.commands,w.visibleCommands($),(f)=>f.helpGroup()||"Commands:").forEach((f,Q)=>{let N=f.map((z)=>{return Y(w.styleSubcommandTerm(w.subcommandTerm(z)),w.styleSubcommandDescription(w.subcommandDescription(z)))});Z=Z.concat(this.formatItemList(Q,N,w))}),Z.join(`
4
- `)}displayWidth($){return l3($).length}styleTitle($){return $}styleUsage($){return $.split(" ").map((w)=>{if(w==="[options]")return this.styleOptionText(w);if(w==="[command]")return this.styleSubcommandText(w);if(w[0]==="["||w[0]==="<")return this.styleArgumentText(w);return this.styleCommandText(w)}).join(" ")}styleCommandDescription($){return this.styleDescriptionText($)}styleOptionDescription($){return this.styleDescriptionText($)}styleSubcommandDescription($){return this.styleDescriptionText($)}styleArgumentDescription($){return this.styleDescriptionText($)}styleDescriptionText($){return $}styleOptionTerm($){return this.styleOptionText($)}styleSubcommandTerm($){return $.split(" ").map((w)=>{if(w==="[options]")return this.styleOptionText(w);if(w[0]==="["||w[0]==="<")return this.styleArgumentText(w);return this.styleSubcommandText(w)}).join(" ")}styleArgumentTerm($){return this.styleArgumentText($)}styleOptionText($){return $}styleArgumentText($){return $}styleSubcommandText($){return $}styleCommandText($){return $}padWidth($,w){return Math.max(w.longestOptionTermLength($,w),w.longestGlobalOptionTermLength($,w),w.longestSubcommandTermLength($,w),w.longestArgumentTermLength($,w))}preformatted($){return/\n[^\S\r\n]/.test($)}formatItem($,w,G,W){let Z=" ".repeat(2);if(!G)return Z+$;let X=$.padEnd(w+$.length-W.displayWidth($)),J=2,M=(this.helpWidth??80)-w-J-2,f;if(M<this.minWidthToWrap||W.preformatted(G))f=G;else f=W.boxWrap(G,M).replace(/\n/g,`
5
- `+" ".repeat(w+J));return Z+X+" ".repeat(J)+f.replace(/\n/g,`
6
- ${Z}`)}boxWrap($,w){if(w<this.minWidthToWrap)return $;let G=$.split(/\r\n|\n/),W=/[\s]*[^\s]+/g,Y=[];return G.forEach((Z)=>{let X=Z.match(W);if(X===null){Y.push("");return}let J=[X.shift()],T=this.displayWidth(J[0]);X.forEach((M)=>{let f=this.displayWidth(M);if(T+f<=w){J.push(M),T+=f;return}Y.push(J.join(""));let Q=M.trimStart();J=[Q],T=this.displayWidth(Q)}),Y.push(J.join(""))}),Y.join(`
7
- `)}}function l3($){let w=/\x1b\[\d*(;\d*)*m/g;return $.replace(w,"")}AQ.Help=m3;AQ.stripColor=l3});var F5=L((yQ)=>{var{InvalidArgumentError:jQ}=pw();class d3{constructor($,w){this.flags=$,this.description=w||"",this.required=$.includes("<"),this.optional=$.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test($),this.mandatory=!1;let G=CQ($);if(this.short=G.shortFlag,this.long=G.longFlag,this.negate=!1,this.long)this.negate=this.long.startsWith("--no-");this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default($,w){return this.defaultValue=$,this.defaultValueDescription=w,this}preset($){return this.presetArg=$,this}conflicts($){return this.conflictsWith=this.conflictsWith.concat($),this}implies($){let w=$;if(typeof $==="string")w={[$]:!0};return this.implied=Object.assign(this.implied||{},w),this}env($){return this.envVar=$,this}argParser($){return this.parseArg=$,this}makeOptionMandatory($=!0){return this.mandatory=!!$,this}hideHelp($=!0){return this.hidden=!!$,this}_collectValue($,w){if(w===this.defaultValue||!Array.isArray(w))return[$];return w.push($),w}choices($){return this.argChoices=$.slice(),this.parseArg=(w,G)=>{if(!this.argChoices.includes(w))throw new jQ(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(w,G);return w},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){if(this.negate)return c3(this.name().replace(/^no-/,""));return c3(this.name())}helpGroup($){return this.helpGroupHeading=$,this}is($){return this.short===$||this.long===$}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class n3{constructor($){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,$.forEach((w)=>{if(w.negate)this.negativeOptions.set(w.attributeName(),w);else this.positiveOptions.set(w.attributeName(),w)}),this.negativeOptions.forEach((w,G)=>{if(this.positiveOptions.has(G))this.dualOptions.add(G)})}valueFromOption($,w){let G=w.attributeName();if(!this.dualOptions.has(G))return!0;let W=this.negativeOptions.get(G).presetArg,Y=W!==void 0?W:!1;return w.negate===(Y===$)}}function c3($){return $.split("-").reduce((w,G)=>{return w+G[0].toUpperCase()+G.slice(1)})}function CQ($){let w,G,W=/^-[^-]$/,Y=/^--[^-]/,Z=$.split(/[ |,]+/).concat("guard");if(W.test(Z[0]))w=Z.shift();if(Y.test(Z[0]))G=Z.shift();if(!w&&W.test(Z[0]))w=Z.shift();if(!w&&Y.test(Z[0]))w=G,G=Z.shift();if(Z[0].startsWith("-")){let X=Z[0],J=`option creation failed due to '${X}' in option flags '${$}'`;if(/^-[^-][^-]/.test(X))throw Error(`${J}
3
+ import{createRequire as wK}from"node:module";var rV=Object.create;var{getPrototypeOf:sV,defineProperty:YJ,getOwnPropertyNames:aV}=Object;var tV=Object.prototype.hasOwnProperty;function oV($){return this[$]}var eV,$K,A1=($,w,G)=>{var Z=$!=null&&typeof $==="object";if(Z){var X=w?eV??=new WeakMap:$K??=new WeakMap,Y=X.get($);if(Y)return Y}G=$!=null?rV(sV($)):{};let J=w||!$||!$.__esModule?YJ(G,"default",{value:$,enumerable:!0}):G;for(let W of aV($))if(!tV.call(J,W))YJ(J,W,{get:oV.bind($,W),enumerable:!0});if(Z)X.set($,J);return J};var F=($,w)=>()=>(w||$((w={exports:{}}).exports,w),w.exports);var D$=wK(import.meta.url);var _4=F((GK)=>{class D3 extends Error{constructor($,w,G){super(G);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=w,this.exitCode=$,this.nestedError=void 0}}class JJ extends D3{constructor($){super(1,"commander.invalidArgument",$);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}GK.CommanderError=D3;GK.InvalidArgumentError=JJ});var F6=F((WK)=>{var{InvalidArgumentError:YK}=_4();class WJ{constructor($,w){switch(this.description=w||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,$[0]){case"<":this.required=!0,this._name=$.slice(1,-1);break;case"[":this.required=!1,this._name=$.slice(1,-1);break;default:this.required=!0,this._name=$;break}if(this._name.endsWith("..."))this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_collectValue($,w){if(w===this.defaultValue||!Array.isArray(w))return[$];return w.push($),w}default($,w){return this.defaultValue=$,this.defaultValueDescription=w,this}argParser($){return this.parseArg=$,this}choices($){return this.argChoices=$.slice(),this.parseArg=(w,G)=>{if(!this.argChoices.includes(w))throw new YK(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(w,G);return w},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function JK($){let w=$.name()+($.variadic===!0?"...":"");return $.required?"<"+w+">":"["+w+"]"}WK.Argument=WJ;WK.humanReadableArgName=JK});var E3=F((MK)=>{var{humanReadableArgName:zK}=F6();class TJ{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext($){this.helpWidth=this.helpWidth??$.helpWidth??80}visibleCommands($){let w=$.commands.filter((Z)=>!Z._hidden),G=$._getHelpCommand();if(G&&!G._hidden)w.push(G);if(this.sortSubcommands)w.sort((Z,X)=>{return Z.name().localeCompare(X.name())});return w}compareOptions($,w){let G=(Z)=>{return Z.short?Z.short.replace(/^-/,""):Z.long.replace(/^--/,"")};return G($).localeCompare(G(w))}visibleOptions($){let w=$.options.filter((Z)=>!Z.hidden),G=$._getHelpOption();if(G&&!G.hidden){let Z=G.short&&$._findOption(G.short),X=G.long&&$._findOption(G.long);if(!Z&&!X)w.push(G);else if(G.long&&!X)w.push($.createOption(G.long,G.description));else if(G.short&&!Z)w.push($.createOption(G.short,G.description))}if(this.sortOptions)w.sort(this.compareOptions);return w}visibleGlobalOptions($){if(!this.showGlobalOptions)return[];let w=[];for(let G=$.parent;G;G=G.parent){let Z=G.options.filter((X)=>!X.hidden);w.push(...Z)}if(this.sortOptions)w.sort(this.compareOptions);return w}visibleArguments($){if($._argsDescription)$.registeredArguments.forEach((w)=>{w.description=w.description||$._argsDescription[w.name()]||""});if($.registeredArguments.find((w)=>w.description))return $.registeredArguments;return[]}subcommandTerm($){let w=$.registeredArguments.map((G)=>zK(G)).join(" ");return $._name+($._aliases[0]?"|"+$._aliases[0]:"")+($.options.length?" [options]":"")+(w?" "+w:"")}optionTerm($){return $.flags}argumentTerm($){return $.name()}longestSubcommandTermLength($,w){return w.visibleCommands($).reduce((G,Z)=>{return Math.max(G,this.displayWidth(w.styleSubcommandTerm(w.subcommandTerm(Z))))},0)}longestOptionTermLength($,w){return w.visibleOptions($).reduce((G,Z)=>{return Math.max(G,this.displayWidth(w.styleOptionTerm(w.optionTerm(Z))))},0)}longestGlobalOptionTermLength($,w){return w.visibleGlobalOptions($).reduce((G,Z)=>{return Math.max(G,this.displayWidth(w.styleOptionTerm(w.optionTerm(Z))))},0)}longestArgumentTermLength($,w){return w.visibleArguments($).reduce((G,Z)=>{return Math.max(G,this.displayWidth(w.styleArgumentTerm(w.argumentTerm(Z))))},0)}commandUsage($){let w=$._name;if($._aliases[0])w=w+"|"+$._aliases[0];let G="";for(let Z=$.parent;Z;Z=Z.parent)G=Z.name()+" "+G;return G+w+" "+$.usage()}commandDescription($){return $.description()}subcommandDescription($){return $.summary()||$.description()}optionDescription($){let w=[];if($.argChoices)w.push(`choices: ${$.argChoices.map((G)=>JSON.stringify(G)).join(", ")}`);if($.defaultValue!==void 0){if($.required||$.optional||$.isBoolean()&&typeof $.defaultValue==="boolean")w.push(`default: ${$.defaultValueDescription||JSON.stringify($.defaultValue)}`)}if($.presetArg!==void 0&&$.optional)w.push(`preset: ${JSON.stringify($.presetArg)}`);if($.envVar!==void 0)w.push(`env: ${$.envVar}`);if(w.length>0){let G=`(${w.join(", ")})`;if($.description)return`${$.description} ${G}`;return G}return $.description}argumentDescription($){let w=[];if($.argChoices)w.push(`choices: ${$.argChoices.map((G)=>JSON.stringify(G)).join(", ")}`);if($.defaultValue!==void 0)w.push(`default: ${$.defaultValueDescription||JSON.stringify($.defaultValue)}`);if(w.length>0){let G=`(${w.join(", ")})`;if($.description)return`${$.description} ${G}`;return G}return $.description}formatItemList($,w,G){if(w.length===0)return[];return[G.styleTitle($),...w,""]}groupItems($,w,G){let Z=new Map;return $.forEach((X)=>{let Y=G(X);if(!Z.has(Y))Z.set(Y,[])}),w.forEach((X)=>{let Y=G(X);if(!Z.has(Y))Z.set(Y,[]);Z.get(Y).push(X)}),Z}formatHelp($,w){let G=w.padWidth($,w),Z=w.helpWidth??80;function X(z,M){return w.formatItem(z,G,M,w)}let Y=[`${w.styleTitle("Usage:")} ${w.styleUsage(w.commandUsage($))}`,""],J=w.commandDescription($);if(J.length>0)Y=Y.concat([w.boxWrap(w.styleCommandDescription(J),Z),""]);let W=w.visibleArguments($).map((z)=>{return X(w.styleArgumentTerm(w.argumentTerm(z)),w.styleArgumentDescription(w.argumentDescription(z)))});if(Y=Y.concat(this.formatItemList("Arguments:",W,w)),this.groupItems($.options,w.visibleOptions($),(z)=>z.helpGroupHeading??"Options:").forEach((z,M)=>{let P=z.map((q)=>{return X(w.styleOptionTerm(w.optionTerm(q)),w.styleOptionDescription(w.optionDescription(q)))});Y=Y.concat(this.formatItemList(M,P,w))}),w.showGlobalOptions){let z=w.visibleGlobalOptions($).map((M)=>{return X(w.styleOptionTerm(w.optionTerm(M)),w.styleOptionDescription(w.optionDescription(M)))});Y=Y.concat(this.formatItemList("Global Options:",z,w))}return this.groupItems($.commands,w.visibleCommands($),(z)=>z.helpGroup()||"Commands:").forEach((z,M)=>{let P=z.map((q)=>{return X(w.styleSubcommandTerm(w.subcommandTerm(q)),w.styleSubcommandDescription(w.subcommandDescription(q)))});Y=Y.concat(this.formatItemList(M,P,w))}),Y.join(`
4
+ `)}displayWidth($){return QJ($).length}styleTitle($){return $}styleUsage($){return $.split(" ").map((w)=>{if(w==="[options]")return this.styleOptionText(w);if(w==="[command]")return this.styleSubcommandText(w);if(w[0]==="["||w[0]==="<")return this.styleArgumentText(w);return this.styleCommandText(w)}).join(" ")}styleCommandDescription($){return this.styleDescriptionText($)}styleOptionDescription($){return this.styleDescriptionText($)}styleSubcommandDescription($){return this.styleDescriptionText($)}styleArgumentDescription($){return this.styleDescriptionText($)}styleDescriptionText($){return $}styleOptionTerm($){return this.styleOptionText($)}styleSubcommandTerm($){return $.split(" ").map((w)=>{if(w==="[options]")return this.styleOptionText(w);if(w[0]==="["||w[0]==="<")return this.styleArgumentText(w);return this.styleSubcommandText(w)}).join(" ")}styleArgumentTerm($){return this.styleArgumentText($)}styleOptionText($){return $}styleArgumentText($){return $}styleSubcommandText($){return $}styleCommandText($){return $}padWidth($,w){return Math.max(w.longestOptionTermLength($,w),w.longestGlobalOptionTermLength($,w),w.longestSubcommandTermLength($,w),w.longestArgumentTermLength($,w))}preformatted($){return/\n[^\S\r\n]/.test($)}formatItem($,w,G,Z){let Y=" ".repeat(2);if(!G)return Y+$;let J=$.padEnd(w+$.length-Z.displayWidth($)),W=2,Q=(this.helpWidth??80)-w-W-2,z;if(Q<this.minWidthToWrap||Z.preformatted(G))z=G;else z=Z.boxWrap(G,Q).replace(/\n/g,`
5
+ `+" ".repeat(w+W));return Y+J+" ".repeat(W)+z.replace(/\n/g,`
6
+ ${Y}`)}boxWrap($,w){if(w<this.minWidthToWrap)return $;let G=$.split(/\r\n|\n/),Z=/[\s]*[^\s]+/g,X=[];return G.forEach((Y)=>{let J=Y.match(Z);if(J===null){X.push("");return}let W=[J.shift()],T=this.displayWidth(W[0]);J.forEach((Q)=>{let z=this.displayWidth(Q);if(T+z<=w){W.push(Q),T+=z;return}X.push(W.join(""));let M=Q.trimStart();W=[M],T=this.displayWidth(M)}),X.push(W.join(""))}),X.join(`
7
+ `)}}function QJ($){let w=/\x1b\[\d*(;\d*)*m/g;return $.replace(w,"")}MK.Help=TJ;MK.stripColor=QJ});var A3=F((VK)=>{var{InvalidArgumentError:BK}=_4();class MJ{constructor($,w){this.flags=$,this.description=w||"",this.required=$.includes("<"),this.optional=$.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test($),this.mandatory=!1;let G=NK($);if(this.short=G.shortFlag,this.long=G.longFlag,this.negate=!1,this.long)this.negate=this.long.startsWith("--no-");this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default($,w){return this.defaultValue=$,this.defaultValueDescription=w,this}preset($){return this.presetArg=$,this}conflicts($){return this.conflictsWith=this.conflictsWith.concat($),this}implies($){let w=$;if(typeof $==="string")w={[$]:!0};return this.implied=Object.assign(this.implied||{},w),this}env($){return this.envVar=$,this}argParser($){return this.parseArg=$,this}makeOptionMandatory($=!0){return this.mandatory=!!$,this}hideHelp($=!0){return this.hidden=!!$,this}_collectValue($,w){if(w===this.defaultValue||!Array.isArray(w))return[$];return w.push($),w}choices($){return this.argChoices=$.slice(),this.parseArg=(w,G)=>{if(!this.argChoices.includes(w))throw new BK(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(w,G);return w},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){if(this.negate)return zJ(this.name().replace(/^no-/,""));return zJ(this.name())}helpGroup($){return this.helpGroupHeading=$,this}is($){return this.short===$||this.long===$}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class PJ{constructor($){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,$.forEach((w)=>{if(w.negate)this.negativeOptions.set(w.attributeName(),w);else this.positiveOptions.set(w.attributeName(),w)}),this.negativeOptions.forEach((w,G)=>{if(this.positiveOptions.has(G))this.dualOptions.add(G)})}valueFromOption($,w){let G=w.attributeName();if(!this.dualOptions.has(G))return!0;let Z=this.negativeOptions.get(G).presetArg,X=Z!==void 0?Z:!1;return w.negate===(X===$)}}function zJ($){return $.split("-").reduce((w,G)=>{return w+G[0].toUpperCase()+G.slice(1)})}function NK($){let w,G,Z=/^-[^-]$/,X=/^--[^-]/,Y=$.split(/[ |,]+/).concat("guard");if(Z.test(Y[0]))w=Y.shift();if(X.test(Y[0]))G=Y.shift();if(!w&&Z.test(Y[0]))w=Y.shift();if(!w&&X.test(Y[0]))w=G,G=Y.shift();if(Y[0].startsWith("-")){let J=Y[0],W=`option creation failed due to '${J}' in option flags '${$}'`;if(/^-[^-][^-]/.test(J))throw Error(`${W}
8
8
  - a short flag is a single dash and a single character
9
9
  - either use a single dash and a single character (for a short flag)
10
- - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(W.test(X))throw Error(`${J}
11
- - too many short flags`);if(Y.test(X))throw Error(`${J}
12
- - too many long flags`);throw Error(`${J}
13
- - unrecognised flag format`)}if(w===void 0&&G===void 0)throw Error(`option creation failed due to no flags found in '${$}'.`);return{shortFlag:w,longFlag:G}}yQ.Option=d3;yQ.DualOptions=n3});var p3=L((gQ)=>{function xQ($,w){if(Math.abs($.length-w.length)>3)return Math.max($.length,w.length);let G=[];for(let W=0;W<=$.length;W++)G[W]=[W];for(let W=0;W<=w.length;W++)G[0][W]=W;for(let W=1;W<=w.length;W++)for(let Y=1;Y<=$.length;Y++){let Z=1;if($[Y-1]===w[W-1])Z=0;else Z=1;if(G[Y][W]=Math.min(G[Y-1][W]+1,G[Y][W-1]+1,G[Y-1][W-1]+Z),Y>1&&W>1&&$[Y-1]===w[W-2]&&$[Y-2]===w[W-1])G[Y][W]=Math.min(G[Y][W],G[Y-2][W-2]+1)}return G[$.length][w.length]}function _Q($,w){if(!w||w.length===0)return"";w=Array.from(new Set(w));let G=$.startsWith("--");if(G)$=$.slice(2),w=w.map((X)=>X.slice(2));let W=[],Y=3,Z=0.4;if(w.forEach((X)=>{if(X.length<=1)return;let J=xQ($,X),T=Math.max($.length,X.length);if((T-J)/T>Z){if(J<Y)Y=J,W=[X];else if(J===Y)W.push(X)}}),W.sort((X,J)=>X.localeCompare(J)),G)W=W.map((X)=>`--${X}`);if(W.length>1)return`
14
- (Did you mean one of ${W.join(", ")}?)`;if(W.length===1)return`
15
- (Did you mean ${W[0]}?)`;return""}gQ.suggestSimilar=_Q});var a3=L((dQ)=>{var uQ=nw("node:events").EventEmitter,O5=nw("node:child_process"),K1=nw("node:path"),X8=nw("node:fs"),p=nw("node:process"),{Argument:hQ,humanReadableArgName:iQ}=Z8(),{CommanderError:L5}=pw(),{Help:mQ,stripColor:lQ}=H5(),{Option:t3,DualOptions:cQ}=F5(),{suggestSimilar:r3}=p3();class k5 extends uQ{constructor($){super();this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=$||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:(w)=>p.stdout.write(w),writeErr:(w)=>p.stderr.write(w),outputError:(w,G)=>G(w),getOutHelpWidth:()=>p.stdout.isTTY?p.stdout.columns:void 0,getErrHelpWidth:()=>p.stderr.isTTY?p.stderr.columns:void 0,getOutHasColors:()=>D5()??(p.stdout.isTTY&&p.stdout.hasColors?.()),getErrHasColors:()=>D5()??(p.stderr.isTTY&&p.stderr.hasColors?.()),stripColor:(w)=>lQ(w)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings($){return this._outputConfiguration=$._outputConfiguration,this._helpOption=$._helpOption,this._helpCommand=$._helpCommand,this._helpConfiguration=$._helpConfiguration,this._exitCallback=$._exitCallback,this._storeOptionsAsProperties=$._storeOptionsAsProperties,this._combineFlagAndOptionalValue=$._combineFlagAndOptionalValue,this._allowExcessArguments=$._allowExcessArguments,this._enablePositionalOptions=$._enablePositionalOptions,this._showHelpAfterError=$._showHelpAfterError,this._showSuggestionAfterError=$._showSuggestionAfterError,this}_getCommandAndAncestors(){let $=[];for(let w=this;w;w=w.parent)$.push(w);return $}command($,w,G){let W=w,Y=G;if(typeof W==="object"&&W!==null)Y=W,W=null;Y=Y||{};let[,Z,X]=$.match(/([^ ]+) *(.*)/),J=this.createCommand(Z);if(W)J.description(W),J._executableHandler=!0;if(Y.isDefault)this._defaultCommandName=J._name;if(J._hidden=!!(Y.noHelp||Y.hidden),J._executableFile=Y.executableFile||null,X)J.arguments(X);if(this._registerCommand(J),J.parent=this,J.copyInheritedSettings(this),W)return this;return J}createCommand($){return new k5($)}createHelp(){return Object.assign(new mQ,this.configureHelp())}configureHelp($){if($===void 0)return this._helpConfiguration;return this._helpConfiguration=$,this}configureOutput($){if($===void 0)return this._outputConfiguration;return this._outputConfiguration={...this._outputConfiguration,...$},this}showHelpAfterError($=!0){if(typeof $!=="string")$=!!$;return this._showHelpAfterError=$,this}showSuggestionAfterError($=!0){return this._showSuggestionAfterError=!!$,this}addCommand($,w){if(!$._name)throw Error(`Command passed to .addCommand() must have a name
16
- - specify the name in Command constructor or using .name()`);if(w=w||{},w.isDefault)this._defaultCommandName=$._name;if(w.noHelp||w.hidden)$._hidden=!0;return this._registerCommand($),$.parent=this,$._checkForBrokenPassThrough(),this}createArgument($,w){return new hQ($,w)}argument($,w,G,W){let Y=this.createArgument($,w);if(typeof G==="function")Y.default(W).argParser(G);else Y.default(G);return this.addArgument(Y),this}arguments($){return $.trim().split(/ +/).forEach((w)=>{this.argument(w)}),this}addArgument($){let w=this.registeredArguments.slice(-1)[0];if(w?.variadic)throw Error(`only the last argument can be variadic '${w.name()}'`);if($.required&&$.defaultValue!==void 0&&$.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${$.name()}'`);return this.registeredArguments.push($),this}helpCommand($,w){if(typeof $==="boolean"){if(this._addImplicitHelpCommand=$,$&&this._defaultCommandGroup)this._initCommandGroup(this._getHelpCommand());return this}let G=$??"help [command]",[,W,Y]=G.match(/([^ ]+) *(.*)/),Z=w??"display help for command",X=this.createCommand(W);if(X.helpOption(!1),Y)X.arguments(Y);if(Z)X.description(Z);if(this._addImplicitHelpCommand=!0,this._helpCommand=X,$||w)this._initCommandGroup(X);return this}addHelpCommand($,w){if(typeof $!=="object")return this.helpCommand($,w),this;return this._addImplicitHelpCommand=!0,this._helpCommand=$,this._initCommandGroup($),this}_getHelpCommand(){if(this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))){if(this._helpCommand===void 0)this.helpCommand(void 0,void 0);return this._helpCommand}return null}hook($,w){let G=["preSubcommand","preAction","postAction"];if(!G.includes($))throw Error(`Unexpected value for event passed to hook : '${$}'.
17
- Expecting one of '${G.join("', '")}'`);if(this._lifeCycleHooks[$])this._lifeCycleHooks[$].push(w);else this._lifeCycleHooks[$]=[w];return this}exitOverride($){if($)this._exitCallback=$;else this._exitCallback=(w)=>{if(w.code!=="commander.executeSubCommandAsync")throw w};return this}_exit($,w,G){if(this._exitCallback)this._exitCallback(new L5($,w,G));p.exit($)}action($){let w=(G)=>{let W=this.registeredArguments.length,Y=G.slice(0,W);if(this._storeOptionsAsProperties)Y[W]=this;else Y[W]=this.opts();return Y.push(this),$.apply(this,Y)};return this._actionHandler=w,this}createOption($,w){return new t3($,w)}_callParseArg($,w,G,W){try{return $.parseArg(w,G)}catch(Y){if(Y.code==="commander.invalidArgument"){let Z=`${W} ${Y.message}`;this.error(Z,{exitCode:Y.exitCode,code:Y.code})}throw Y}}_registerOption($){let w=$.short&&this._findOption($.short)||$.long&&this._findOption($.long);if(w){let G=$.long&&this._findOption($.long)?$.long:$.short;throw Error(`Cannot add option '${$.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${G}'
18
- - already used by option '${w.flags}'`)}this._initOptionGroup($),this.options.push($)}_registerCommand($){let w=(W)=>{return[W.name()].concat(W.aliases())},G=w($).find((W)=>this._findCommand(W));if(G){let W=w(this._findCommand(G)).join("|"),Y=w($).join("|");throw Error(`cannot add command '${Y}' as already have command '${W}'`)}this._initCommandGroup($),this.commands.push($)}addOption($){this._registerOption($);let w=$.name(),G=$.attributeName();if($.negate){let Y=$.long.replace(/^--no-/,"--");if(!this._findOption(Y))this.setOptionValueWithSource(G,$.defaultValue===void 0?!0:$.defaultValue,"default")}else if($.defaultValue!==void 0)this.setOptionValueWithSource(G,$.defaultValue,"default");let W=(Y,Z,X)=>{if(Y==null&&$.presetArg!==void 0)Y=$.presetArg;let J=this.getOptionValue(G);if(Y!==null&&$.parseArg)Y=this._callParseArg($,Y,J,Z);else if(Y!==null&&$.variadic)Y=$._collectValue(Y,J);if(Y==null)if($.negate)Y=!1;else if($.isBoolean()||$.optional)Y=!0;else Y="";this.setOptionValueWithSource(G,Y,X)};if(this.on("option:"+w,(Y)=>{let Z=`error: option '${$.flags}' argument '${Y}' is invalid.`;W(Y,Z,"cli")}),$.envVar)this.on("optionEnv:"+w,(Y)=>{let Z=`error: option '${$.flags}' value '${Y}' from env '${$.envVar}' is invalid.`;W(Y,Z,"env")});return this}_optionEx($,w,G,W,Y){if(typeof w==="object"&&w instanceof t3)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let Z=this.createOption(w,G);if(Z.makeOptionMandatory(!!$.mandatory),typeof W==="function")Z.default(Y).argParser(W);else if(W instanceof RegExp){let X=W;W=(J,T)=>{let M=X.exec(J);return M?M[0]:T},Z.default(Y).argParser(W)}else Z.default(W);return this.addOption(Z)}option($,w,G,W){return this._optionEx({},$,w,G,W)}requiredOption($,w,G,W){return this._optionEx({mandatory:!0},$,w,G,W)}combineFlagAndOptionalValue($=!0){return this._combineFlagAndOptionalValue=!!$,this}allowUnknownOption($=!0){return this._allowUnknownOption=!!$,this}allowExcessArguments($=!0){return this._allowExcessArguments=!!$,this}enablePositionalOptions($=!0){return this._enablePositionalOptions=!!$,this}passThroughOptions($=!0){return this._passThroughOptions=!!$,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties($=!0){if(this.options.length)throw Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!$,this}getOptionValue($){if(this._storeOptionsAsProperties)return this[$];return this._optionValues[$]}setOptionValue($,w){return this.setOptionValueWithSource($,w,void 0)}setOptionValueWithSource($,w,G){if(this._storeOptionsAsProperties)this[$]=w;else this._optionValues[$]=w;return this._optionValueSources[$]=G,this}getOptionValueSource($){return this._optionValueSources[$]}getOptionValueSourceWithGlobals($){let w;return this._getCommandAndAncestors().forEach((G)=>{if(G.getOptionValueSource($)!==void 0)w=G.getOptionValueSource($)}),w}_prepareUserArgs($,w){if($!==void 0&&!Array.isArray($))throw Error("first parameter to parse must be array or undefined");if(w=w||{},$===void 0&&w.from===void 0){if(p.versions?.electron)w.from="electron";let W=p.execArgv??[];if(W.includes("-e")||W.includes("--eval")||W.includes("-p")||W.includes("--print"))w.from="eval"}if($===void 0)$=p.argv;this.rawArgs=$.slice();let G;switch(w.from){case void 0:case"node":this._scriptPath=$[1],G=$.slice(2);break;case"electron":if(p.defaultApp)this._scriptPath=$[1],G=$.slice(2);else G=$.slice(1);break;case"user":G=$.slice(0);break;case"eval":G=$.slice(1);break;default:throw Error(`unexpected parse option { from: '${w.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);return this._name=this._name||"program",G}parse($,w){this._prepareForParse();let G=this._prepareUserArgs($,w);return this._parseCommand([],G),this}async parseAsync($,w){this._prepareForParse();let G=this._prepareUserArgs($,w);return await this._parseCommand([],G),this}_prepareForParse(){if(this._savedState===null)this.saveStateBeforeParse();else this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw Error(`Can not call parse again when storeOptionsAsProperties is true.
19
- - either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable($,w,G){if(X8.existsSync($))return;let W=w?`searched for local subcommand relative to directory '${w}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",Y=`'${$}' does not exist
10
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(Z.test(J))throw Error(`${W}
11
+ - too many short flags`);if(X.test(J))throw Error(`${W}
12
+ - too many long flags`);throw Error(`${W}
13
+ - unrecognised flag format`)}if(w===void 0&&G===void 0)throw Error(`option creation failed due to no flags found in '${$}'.`);return{shortFlag:w,longFlag:G}}VK.Option=MJ;VK.DualOptions=PJ});var qJ=F((OK)=>{function HK($,w){if(Math.abs($.length-w.length)>3)return Math.max($.length,w.length);let G=[];for(let Z=0;Z<=$.length;Z++)G[Z]=[Z];for(let Z=0;Z<=w.length;Z++)G[0][Z]=Z;for(let Z=1;Z<=w.length;Z++)for(let X=1;X<=$.length;X++){let Y=1;if($[X-1]===w[Z-1])Y=0;else Y=1;if(G[X][Z]=Math.min(G[X-1][Z]+1,G[X][Z-1]+1,G[X-1][Z-1]+Y),X>1&&Z>1&&$[X-1]===w[Z-2]&&$[X-2]===w[Z-1])G[X][Z]=Math.min(G[X][Z],G[X-2][Z-2]+1)}return G[$.length][w.length]}function FK($,w){if(!w||w.length===0)return"";w=Array.from(new Set(w));let G=$.startsWith("--");if(G)$=$.slice(2),w=w.map((J)=>J.slice(2));let Z=[],X=3,Y=0.4;if(w.forEach((J)=>{if(J.length<=1)return;let W=HK($,J),T=Math.max($.length,J.length);if((T-W)/T>Y){if(W<X)X=W,Z=[J];else if(W===X)Z.push(J)}}),Z.sort((J,W)=>J.localeCompare(W)),G)Z=Z.map((J)=>`--${J}`);if(Z.length>1)return`
14
+ (Did you mean one of ${Z.join(", ")}?)`;if(Z.length===1)return`
15
+ (Did you mean ${Z[0]}?)`;return""}OK.suggestSimilar=FK});var KJ=F((IK)=>{var LK=D$("node:events").EventEmitter,R3=D$("node:child_process"),E$=D$("node:path"),O6=D$("node:fs"),a=D$("node:process"),{Argument:DK,humanReadableArgName:EK}=F6(),{CommanderError:S3}=_4(),{Help:AK,stripColor:RK}=E3(),{Option:BJ,DualOptions:SK}=A3(),{suggestSimilar:NJ}=qJ();class j3 extends LK{constructor($){super();this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=$||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:(w)=>a.stdout.write(w),writeErr:(w)=>a.stderr.write(w),outputError:(w,G)=>G(w),getOutHelpWidth:()=>a.stdout.isTTY?a.stdout.columns:void 0,getErrHelpWidth:()=>a.stderr.isTTY?a.stderr.columns:void 0,getOutHasColors:()=>I3()??(a.stdout.isTTY&&a.stdout.hasColors?.()),getErrHasColors:()=>I3()??(a.stderr.isTTY&&a.stderr.hasColors?.()),stripColor:(w)=>RK(w)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings($){return this._outputConfiguration=$._outputConfiguration,this._helpOption=$._helpOption,this._helpCommand=$._helpCommand,this._helpConfiguration=$._helpConfiguration,this._exitCallback=$._exitCallback,this._storeOptionsAsProperties=$._storeOptionsAsProperties,this._combineFlagAndOptionalValue=$._combineFlagAndOptionalValue,this._allowExcessArguments=$._allowExcessArguments,this._enablePositionalOptions=$._enablePositionalOptions,this._showHelpAfterError=$._showHelpAfterError,this._showSuggestionAfterError=$._showSuggestionAfterError,this}_getCommandAndAncestors(){let $=[];for(let w=this;w;w=w.parent)$.push(w);return $}command($,w,G){let Z=w,X=G;if(typeof Z==="object"&&Z!==null)X=Z,Z=null;X=X||{};let[,Y,J]=$.match(/([^ ]+) *(.*)/),W=this.createCommand(Y);if(Z)W.description(Z),W._executableHandler=!0;if(X.isDefault)this._defaultCommandName=W._name;if(W._hidden=!!(X.noHelp||X.hidden),W._executableFile=X.executableFile||null,J)W.arguments(J);if(this._registerCommand(W),W.parent=this,W.copyInheritedSettings(this),Z)return this;return W}createCommand($){return new j3($)}createHelp(){return Object.assign(new AK,this.configureHelp())}configureHelp($){if($===void 0)return this._helpConfiguration;return this._helpConfiguration=$,this}configureOutput($){if($===void 0)return this._outputConfiguration;return this._outputConfiguration={...this._outputConfiguration,...$},this}showHelpAfterError($=!0){if(typeof $!=="string")$=!!$;return this._showHelpAfterError=$,this}showSuggestionAfterError($=!0){return this._showSuggestionAfterError=!!$,this}addCommand($,w){if(!$._name)throw Error(`Command passed to .addCommand() must have a name
16
+ - specify the name in Command constructor or using .name()`);if(w=w||{},w.isDefault)this._defaultCommandName=$._name;if(w.noHelp||w.hidden)$._hidden=!0;return this._registerCommand($),$.parent=this,$._checkForBrokenPassThrough(),this}createArgument($,w){return new DK($,w)}argument($,w,G,Z){let X=this.createArgument($,w);if(typeof G==="function")X.default(Z).argParser(G);else X.default(G);return this.addArgument(X),this}arguments($){return $.trim().split(/ +/).forEach((w)=>{this.argument(w)}),this}addArgument($){let w=this.registeredArguments.slice(-1)[0];if(w?.variadic)throw Error(`only the last argument can be variadic '${w.name()}'`);if($.required&&$.defaultValue!==void 0&&$.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${$.name()}'`);return this.registeredArguments.push($),this}helpCommand($,w){if(typeof $==="boolean"){if(this._addImplicitHelpCommand=$,$&&this._defaultCommandGroup)this._initCommandGroup(this._getHelpCommand());return this}let G=$??"help [command]",[,Z,X]=G.match(/([^ ]+) *(.*)/),Y=w??"display help for command",J=this.createCommand(Z);if(J.helpOption(!1),X)J.arguments(X);if(Y)J.description(Y);if(this._addImplicitHelpCommand=!0,this._helpCommand=J,$||w)this._initCommandGroup(J);return this}addHelpCommand($,w){if(typeof $!=="object")return this.helpCommand($,w),this;return this._addImplicitHelpCommand=!0,this._helpCommand=$,this._initCommandGroup($),this}_getHelpCommand(){if(this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))){if(this._helpCommand===void 0)this.helpCommand(void 0,void 0);return this._helpCommand}return null}hook($,w){let G=["preSubcommand","preAction","postAction"];if(!G.includes($))throw Error(`Unexpected value for event passed to hook : '${$}'.
17
+ Expecting one of '${G.join("', '")}'`);if(this._lifeCycleHooks[$])this._lifeCycleHooks[$].push(w);else this._lifeCycleHooks[$]=[w];return this}exitOverride($){if($)this._exitCallback=$;else this._exitCallback=(w)=>{if(w.code!=="commander.executeSubCommandAsync")throw w};return this}_exit($,w,G){if(this._exitCallback)this._exitCallback(new S3($,w,G));a.exit($)}action($){let w=(G)=>{let Z=this.registeredArguments.length,X=G.slice(0,Z);if(this._storeOptionsAsProperties)X[Z]=this;else X[Z]=this.opts();return X.push(this),$.apply(this,X)};return this._actionHandler=w,this}createOption($,w){return new BJ($,w)}_callParseArg($,w,G,Z){try{return $.parseArg(w,G)}catch(X){if(X.code==="commander.invalidArgument"){let Y=`${Z} ${X.message}`;this.error(Y,{exitCode:X.exitCode,code:X.code})}throw X}}_registerOption($){let w=$.short&&this._findOption($.short)||$.long&&this._findOption($.long);if(w){let G=$.long&&this._findOption($.long)?$.long:$.short;throw Error(`Cannot add option '${$.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${G}'
18
+ - already used by option '${w.flags}'`)}this._initOptionGroup($),this.options.push($)}_registerCommand($){let w=(Z)=>{return[Z.name()].concat(Z.aliases())},G=w($).find((Z)=>this._findCommand(Z));if(G){let Z=w(this._findCommand(G)).join("|"),X=w($).join("|");throw Error(`cannot add command '${X}' as already have command '${Z}'`)}this._initCommandGroup($),this.commands.push($)}addOption($){this._registerOption($);let w=$.name(),G=$.attributeName();if($.negate){let X=$.long.replace(/^--no-/,"--");if(!this._findOption(X))this.setOptionValueWithSource(G,$.defaultValue===void 0?!0:$.defaultValue,"default")}else if($.defaultValue!==void 0)this.setOptionValueWithSource(G,$.defaultValue,"default");let Z=(X,Y,J)=>{if(X==null&&$.presetArg!==void 0)X=$.presetArg;let W=this.getOptionValue(G);if(X!==null&&$.parseArg)X=this._callParseArg($,X,W,Y);else if(X!==null&&$.variadic)X=$._collectValue(X,W);if(X==null)if($.negate)X=!1;else if($.isBoolean()||$.optional)X=!0;else X="";this.setOptionValueWithSource(G,X,J)};if(this.on("option:"+w,(X)=>{let Y=`error: option '${$.flags}' argument '${X}' is invalid.`;Z(X,Y,"cli")}),$.envVar)this.on("optionEnv:"+w,(X)=>{let Y=`error: option '${$.flags}' value '${X}' from env '${$.envVar}' is invalid.`;Z(X,Y,"env")});return this}_optionEx($,w,G,Z,X){if(typeof w==="object"&&w instanceof BJ)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let Y=this.createOption(w,G);if(Y.makeOptionMandatory(!!$.mandatory),typeof Z==="function")Y.default(X).argParser(Z);else if(Z instanceof RegExp){let J=Z;Z=(W,T)=>{let Q=J.exec(W);return Q?Q[0]:T},Y.default(X).argParser(Z)}else Y.default(Z);return this.addOption(Y)}option($,w,G,Z){return this._optionEx({},$,w,G,Z)}requiredOption($,w,G,Z){return this._optionEx({mandatory:!0},$,w,G,Z)}combineFlagAndOptionalValue($=!0){return this._combineFlagAndOptionalValue=!!$,this}allowUnknownOption($=!0){return this._allowUnknownOption=!!$,this}allowExcessArguments($=!0){return this._allowExcessArguments=!!$,this}enablePositionalOptions($=!0){return this._enablePositionalOptions=!!$,this}passThroughOptions($=!0){return this._passThroughOptions=!!$,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties($=!0){if(this.options.length)throw Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!$,this}getOptionValue($){if(this._storeOptionsAsProperties)return this[$];return this._optionValues[$]}setOptionValue($,w){return this.setOptionValueWithSource($,w,void 0)}setOptionValueWithSource($,w,G){if(this._storeOptionsAsProperties)this[$]=w;else this._optionValues[$]=w;return this._optionValueSources[$]=G,this}getOptionValueSource($){return this._optionValueSources[$]}getOptionValueSourceWithGlobals($){let w;return this._getCommandAndAncestors().forEach((G)=>{if(G.getOptionValueSource($)!==void 0)w=G.getOptionValueSource($)}),w}_prepareUserArgs($,w){if($!==void 0&&!Array.isArray($))throw Error("first parameter to parse must be array or undefined");if(w=w||{},$===void 0&&w.from===void 0){if(a.versions?.electron)w.from="electron";let Z=a.execArgv??[];if(Z.includes("-e")||Z.includes("--eval")||Z.includes("-p")||Z.includes("--print"))w.from="eval"}if($===void 0)$=a.argv;this.rawArgs=$.slice();let G;switch(w.from){case void 0:case"node":this._scriptPath=$[1],G=$.slice(2);break;case"electron":if(a.defaultApp)this._scriptPath=$[1],G=$.slice(2);else G=$.slice(1);break;case"user":G=$.slice(0);break;case"eval":G=$.slice(1);break;default:throw Error(`unexpected parse option { from: '${w.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);return this._name=this._name||"program",G}parse($,w){this._prepareForParse();let G=this._prepareUserArgs($,w);return this._parseCommand([],G),this}async parseAsync($,w){this._prepareForParse();let G=this._prepareUserArgs($,w);return await this._parseCommand([],G),this}_prepareForParse(){if(this._savedState===null)this.saveStateBeforeParse();else this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw Error(`Can not call parse again when storeOptionsAsProperties is true.
19
+ - either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable($,w,G){if(O6.existsSync($))return;let Z=w?`searched for local subcommand relative to directory '${w}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",X=`'${$}' does not exist
20
20
  - if '${G}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
21
21
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
22
- - ${W}`;throw Error(Y)}_executeSubCommand($,w){w=w.slice();let G=!1,W=[".js",".ts",".tsx",".mjs",".cjs"];function Y(M,f){let Q=K1.resolve(M,f);if(X8.existsSync(Q))return Q;if(W.includes(K1.extname(f)))return;let N=W.find((z)=>X8.existsSync(`${Q}${z}`));if(N)return`${Q}${N}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let Z=$._executableFile||`${this._name}-${$._name}`,X=this._executableDir||"";if(this._scriptPath){let M;try{M=X8.realpathSync(this._scriptPath)}catch{M=this._scriptPath}X=K1.resolve(K1.dirname(M),X)}if(X){let M=Y(X,Z);if(!M&&!$._executableFile&&this._scriptPath){let f=K1.basename(this._scriptPath,K1.extname(this._scriptPath));if(f!==this._name)M=Y(X,`${f}-${$._name}`)}Z=M||Z}G=W.includes(K1.extname(Z));let J;if(p.platform!=="win32")if(G)w.unshift(Z),w=s3(p.execArgv).concat(w),J=O5.spawn(p.argv[0],w,{stdio:"inherit"});else J=O5.spawn(Z,w,{stdio:"inherit"});else this._checkForMissingExecutable(Z,X,$._name),w.unshift(Z),w=s3(p.execArgv).concat(w),J=O5.spawn(p.execPath,w,{stdio:"inherit"});if(!J.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((f)=>{p.on(f,()=>{if(J.killed===!1&&J.exitCode===null)J.kill(f)})});let T=this._exitCallback;J.on("close",(M)=>{if(M=M??1,!T)p.exit(M);else T(new L5(M,"commander.executeSubCommandAsync","(close)"))}),J.on("error",(M)=>{if(M.code==="ENOENT")this._checkForMissingExecutable(Z,X,$._name);else if(M.code==="EACCES")throw Error(`'${Z}' not executable`);if(!T)p.exit(1);else{let f=new L5(1,"commander.executeSubCommandAsync","(error)");f.nestedError=M,T(f)}}),this.runningCommand=J}_dispatchSubcommand($,w,G){let W=this._findCommand($);if(!W)this.help({error:!0});W._prepareForParse();let Y;return Y=this._chainOrCallSubCommandHook(Y,W,"preSubcommand"),Y=this._chainOrCall(Y,()=>{if(W._executableHandler)this._executeSubCommand(W,w.concat(G));else return W._parseCommand(w,G)}),Y}_dispatchHelpCommand($){if(!$)this.help();let w=this._findCommand($);if(w&&!w._executableHandler)w.help();return this._dispatchSubcommand($,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){if(this.registeredArguments.forEach(($,w)=>{if($.required&&this.args[w]==null)this.missingArgument($.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)return;if(this.args.length>this.registeredArguments.length)this._excessArguments(this.args)}_processArguments(){let $=(G,W,Y)=>{let Z=W;if(W!==null&&G.parseArg){let X=`error: command-argument value '${W}' is invalid for argument '${G.name()}'.`;Z=this._callParseArg(G,W,Y,X)}return Z};this._checkNumberOfArguments();let w=[];this.registeredArguments.forEach((G,W)=>{let Y=G.defaultValue;if(G.variadic){if(W<this.args.length){if(Y=this.args.slice(W),G.parseArg)Y=Y.reduce((Z,X)=>{return $(G,X,Z)},G.defaultValue)}else if(Y===void 0)Y=[]}else if(W<this.args.length){if(Y=this.args[W],G.parseArg)Y=$(G,Y,G.defaultValue)}w[W]=Y}),this.processedArgs=w}_chainOrCall($,w){if($?.then&&typeof $.then==="function")return $.then(()=>w());return w()}_chainOrCallHooks($,w){let G=$,W=[];if(this._getCommandAndAncestors().reverse().filter((Y)=>Y._lifeCycleHooks[w]!==void 0).forEach((Y)=>{Y._lifeCycleHooks[w].forEach((Z)=>{W.push({hookedCommand:Y,callback:Z})})}),w==="postAction")W.reverse();return W.forEach((Y)=>{G=this._chainOrCall(G,()=>{return Y.callback(Y.hookedCommand,this)})}),G}_chainOrCallSubCommandHook($,w,G){let W=$;if(this._lifeCycleHooks[G]!==void 0)this._lifeCycleHooks[G].forEach((Y)=>{W=this._chainOrCall(W,()=>{return Y(this,w)})});return W}_parseCommand($,w){let G=this.parseOptions(w);if(this._parseOptionsEnv(),this._parseOptionsImplied(),$=$.concat(G.operands),w=G.unknown,this.args=$.concat(w),$&&this._findCommand($[0]))return this._dispatchSubcommand($[0],$.slice(1),w);if(this._getHelpCommand()&&$[0]===this._getHelpCommand().name())return this._dispatchHelpCommand($[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(w),this._dispatchSubcommand(this._defaultCommandName,$,w);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});this._outputHelpIfRequested(G.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let W=()=>{if(G.unknown.length>0)this.unknownOption(G.unknown[0])},Y=`command:${this.name()}`;if(this._actionHandler){W(),this._processArguments();let Z;if(Z=this._chainOrCallHooks(Z,"preAction"),Z=this._chainOrCall(Z,()=>this._actionHandler(this.processedArgs)),this.parent)Z=this._chainOrCall(Z,()=>{this.parent.emit(Y,$,w)});return Z=this._chainOrCallHooks(Z,"postAction"),Z}if(this.parent?.listenerCount(Y))W(),this._processArguments(),this.parent.emit(Y,$,w);else if($.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",$,w);if(this.listenerCount("command:*"))this.emit("command:*",$,w);else if(this.commands.length)this.unknownCommand();else W(),this._processArguments()}else if(this.commands.length)W(),this.help({error:!0});else W(),this._processArguments()}_findCommand($){if(!$)return;return this.commands.find((w)=>w._name===$||w._aliases.includes($))}_findOption($){return this.options.find((w)=>w.is($))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(($)=>{$.options.forEach((w)=>{if(w.mandatory&&$.getOptionValue(w.attributeName())===void 0)$.missingMandatoryOptionValue(w)})})}_checkForConflictingLocalOptions(){let $=this.options.filter((G)=>{let W=G.attributeName();if(this.getOptionValue(W)===void 0)return!1;return this.getOptionValueSource(W)!=="default"});$.filter((G)=>G.conflictsWith.length>0).forEach((G)=>{let W=$.find((Y)=>G.conflictsWith.includes(Y.attributeName()));if(W)this._conflictingOption(G,W)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(($)=>{$._checkForConflictingLocalOptions()})}parseOptions($){let w=[],G=[],W=w;function Y(M){return M.length>1&&M[0]==="-"}let Z=(M)=>{if(!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(M))return!1;return!this._getCommandAndAncestors().some((f)=>f.options.map((Q)=>Q.short).some((Q)=>/^-\d$/.test(Q)))},X=null,J=null,T=0;while(T<$.length||J){let M=J??$[T++];if(J=null,M==="--"){if(W===G)W.push(M);W.push(...$.slice(T));break}if(X&&(!Y(M)||Z(M))){this.emit(`option:${X.name()}`,M);continue}if(X=null,Y(M)){let f=this._findOption(M);if(f){if(f.required){let Q=$[T++];if(Q===void 0)this.optionMissingArgument(f);this.emit(`option:${f.name()}`,Q)}else if(f.optional){let Q=null;if(T<$.length&&(!Y($[T])||Z($[T])))Q=$[T++];this.emit(`option:${f.name()}`,Q)}else this.emit(`option:${f.name()}`);X=f.variadic?f:null;continue}}if(M.length>2&&M[0]==="-"&&M[1]!=="-"){let f=this._findOption(`-${M[1]}`);if(f){if(f.required||f.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${f.name()}`,M.slice(2));else this.emit(`option:${f.name()}`),J=`-${M.slice(2)}`;continue}}if(/^--[^=]+=/.test(M)){let f=M.indexOf("="),Q=this._findOption(M.slice(0,f));if(Q&&(Q.required||Q.optional)){this.emit(`option:${Q.name()}`,M.slice(f+1));continue}}if(W===w&&Y(M)&&!(this.commands.length===0&&Z(M)))W=G;if((this._enablePositionalOptions||this._passThroughOptions)&&w.length===0&&G.length===0){if(this._findCommand(M)){w.push(M),G.push(...$.slice(T));break}else if(this._getHelpCommand()&&M===this._getHelpCommand().name()){w.push(M,...$.slice(T));break}else if(this._defaultCommandName){G.push(M,...$.slice(T));break}}if(this._passThroughOptions){W.push(M,...$.slice(T));break}W.push(M)}return{operands:w,unknown:G}}opts(){if(this._storeOptionsAsProperties){let $={},w=this.options.length;for(let G=0;G<w;G++){let W=this.options[G].attributeName();$[W]=W===this._versionOptionName?this._version:this[W]}return $}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce(($,w)=>Object.assign($,w.opts()),{})}error($,w){if(this._outputConfiguration.outputError(`${$}
22
+ - ${Z}`;throw Error(X)}_executeSubCommand($,w){w=w.slice();let G=!1,Z=[".js",".ts",".tsx",".mjs",".cjs"];function X(Q,z){let M=E$.resolve(Q,z);if(O6.existsSync(M))return M;if(Z.includes(E$.extname(z)))return;let P=Z.find((q)=>O6.existsSync(`${M}${q}`));if(P)return`${M}${P}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let Y=$._executableFile||`${this._name}-${$._name}`,J=this._executableDir||"";if(this._scriptPath){let Q;try{Q=O6.realpathSync(this._scriptPath)}catch{Q=this._scriptPath}J=E$.resolve(E$.dirname(Q),J)}if(J){let Q=X(J,Y);if(!Q&&!$._executableFile&&this._scriptPath){let z=E$.basename(this._scriptPath,E$.extname(this._scriptPath));if(z!==this._name)Q=X(J,`${z}-${$._name}`)}Y=Q||Y}G=Z.includes(E$.extname(Y));let W;if(a.platform!=="win32")if(G)w.unshift(Y),w=VJ(a.execArgv).concat(w),W=R3.spawn(a.argv[0],w,{stdio:"inherit"});else W=R3.spawn(Y,w,{stdio:"inherit"});else this._checkForMissingExecutable(Y,J,$._name),w.unshift(Y),w=VJ(a.execArgv).concat(w),W=R3.spawn(a.execPath,w,{stdio:"inherit"});if(!W.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((z)=>{a.on(z,()=>{if(W.killed===!1&&W.exitCode===null)W.kill(z)})});let T=this._exitCallback;W.on("close",(Q)=>{if(Q=Q??1,!T)a.exit(Q);else T(new S3(Q,"commander.executeSubCommandAsync","(close)"))}),W.on("error",(Q)=>{if(Q.code==="ENOENT")this._checkForMissingExecutable(Y,J,$._name);else if(Q.code==="EACCES")throw Error(`'${Y}' not executable`);if(!T)a.exit(1);else{let z=new S3(1,"commander.executeSubCommandAsync","(error)");z.nestedError=Q,T(z)}}),this.runningCommand=W}_dispatchSubcommand($,w,G){let Z=this._findCommand($);if(!Z)this.help({error:!0});Z._prepareForParse();let X;return X=this._chainOrCallSubCommandHook(X,Z,"preSubcommand"),X=this._chainOrCall(X,()=>{if(Z._executableHandler)this._executeSubCommand(Z,w.concat(G));else return Z._parseCommand(w,G)}),X}_dispatchHelpCommand($){if(!$)this.help();let w=this._findCommand($);if(w&&!w._executableHandler)w.help();return this._dispatchSubcommand($,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){if(this.registeredArguments.forEach(($,w)=>{if($.required&&this.args[w]==null)this.missingArgument($.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)return;if(this.args.length>this.registeredArguments.length)this._excessArguments(this.args)}_processArguments(){let $=(G,Z,X)=>{let Y=Z;if(Z!==null&&G.parseArg){let J=`error: command-argument value '${Z}' is invalid for argument '${G.name()}'.`;Y=this._callParseArg(G,Z,X,J)}return Y};this._checkNumberOfArguments();let w=[];this.registeredArguments.forEach((G,Z)=>{let X=G.defaultValue;if(G.variadic){if(Z<this.args.length){if(X=this.args.slice(Z),G.parseArg)X=X.reduce((Y,J)=>{return $(G,J,Y)},G.defaultValue)}else if(X===void 0)X=[]}else if(Z<this.args.length){if(X=this.args[Z],G.parseArg)X=$(G,X,G.defaultValue)}w[Z]=X}),this.processedArgs=w}_chainOrCall($,w){if($?.then&&typeof $.then==="function")return $.then(()=>w());return w()}_chainOrCallHooks($,w){let G=$,Z=[];if(this._getCommandAndAncestors().reverse().filter((X)=>X._lifeCycleHooks[w]!==void 0).forEach((X)=>{X._lifeCycleHooks[w].forEach((Y)=>{Z.push({hookedCommand:X,callback:Y})})}),w==="postAction")Z.reverse();return Z.forEach((X)=>{G=this._chainOrCall(G,()=>{return X.callback(X.hookedCommand,this)})}),G}_chainOrCallSubCommandHook($,w,G){let Z=$;if(this._lifeCycleHooks[G]!==void 0)this._lifeCycleHooks[G].forEach((X)=>{Z=this._chainOrCall(Z,()=>{return X(this,w)})});return Z}_parseCommand($,w){let G=this.parseOptions(w);if(this._parseOptionsEnv(),this._parseOptionsImplied(),$=$.concat(G.operands),w=G.unknown,this.args=$.concat(w),$&&this._findCommand($[0]))return this._dispatchSubcommand($[0],$.slice(1),w);if(this._getHelpCommand()&&$[0]===this._getHelpCommand().name())return this._dispatchHelpCommand($[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(w),this._dispatchSubcommand(this._defaultCommandName,$,w);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});this._outputHelpIfRequested(G.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let Z=()=>{if(G.unknown.length>0)this.unknownOption(G.unknown[0])},X=`command:${this.name()}`;if(this._actionHandler){Z(),this._processArguments();let Y;if(Y=this._chainOrCallHooks(Y,"preAction"),Y=this._chainOrCall(Y,()=>this._actionHandler(this.processedArgs)),this.parent)Y=this._chainOrCall(Y,()=>{this.parent.emit(X,$,w)});return Y=this._chainOrCallHooks(Y,"postAction"),Y}if(this.parent?.listenerCount(X))Z(),this._processArguments(),this.parent.emit(X,$,w);else if($.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",$,w);if(this.listenerCount("command:*"))this.emit("command:*",$,w);else if(this.commands.length)this.unknownCommand();else Z(),this._processArguments()}else if(this.commands.length)Z(),this.help({error:!0});else Z(),this._processArguments()}_findCommand($){if(!$)return;return this.commands.find((w)=>w._name===$||w._aliases.includes($))}_findOption($){return this.options.find((w)=>w.is($))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(($)=>{$.options.forEach((w)=>{if(w.mandatory&&$.getOptionValue(w.attributeName())===void 0)$.missingMandatoryOptionValue(w)})})}_checkForConflictingLocalOptions(){let $=this.options.filter((G)=>{let Z=G.attributeName();if(this.getOptionValue(Z)===void 0)return!1;return this.getOptionValueSource(Z)!=="default"});$.filter((G)=>G.conflictsWith.length>0).forEach((G)=>{let Z=$.find((X)=>G.conflictsWith.includes(X.attributeName()));if(Z)this._conflictingOption(G,Z)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(($)=>{$._checkForConflictingLocalOptions()})}parseOptions($){let w=[],G=[],Z=w;function X(Q){return Q.length>1&&Q[0]==="-"}let Y=(Q)=>{if(!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(Q))return!1;return!this._getCommandAndAncestors().some((z)=>z.options.map((M)=>M.short).some((M)=>/^-\d$/.test(M)))},J=null,W=null,T=0;while(T<$.length||W){let Q=W??$[T++];if(W=null,Q==="--"){if(Z===G)Z.push(Q);Z.push(...$.slice(T));break}if(J&&(!X(Q)||Y(Q))){this.emit(`option:${J.name()}`,Q);continue}if(J=null,X(Q)){let z=this._findOption(Q);if(z){if(z.required){let M=$[T++];if(M===void 0)this.optionMissingArgument(z);this.emit(`option:${z.name()}`,M)}else if(z.optional){let M=null;if(T<$.length&&(!X($[T])||Y($[T])))M=$[T++];this.emit(`option:${z.name()}`,M)}else this.emit(`option:${z.name()}`);J=z.variadic?z:null;continue}}if(Q.length>2&&Q[0]==="-"&&Q[1]!=="-"){let z=this._findOption(`-${Q[1]}`);if(z){if(z.required||z.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${z.name()}`,Q.slice(2));else this.emit(`option:${z.name()}`),W=`-${Q.slice(2)}`;continue}}if(/^--[^=]+=/.test(Q)){let z=Q.indexOf("="),M=this._findOption(Q.slice(0,z));if(M&&(M.required||M.optional)){this.emit(`option:${M.name()}`,Q.slice(z+1));continue}}if(Z===w&&X(Q)&&!(this.commands.length===0&&Y(Q)))Z=G;if((this._enablePositionalOptions||this._passThroughOptions)&&w.length===0&&G.length===0){if(this._findCommand(Q)){w.push(Q),G.push(...$.slice(T));break}else if(this._getHelpCommand()&&Q===this._getHelpCommand().name()){w.push(Q,...$.slice(T));break}else if(this._defaultCommandName){G.push(Q,...$.slice(T));break}}if(this._passThroughOptions){Z.push(Q,...$.slice(T));break}Z.push(Q)}return{operands:w,unknown:G}}opts(){if(this._storeOptionsAsProperties){let $={},w=this.options.length;for(let G=0;G<w;G++){let Z=this.options[G].attributeName();$[Z]=Z===this._versionOptionName?this._version:this[Z]}return $}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce(($,w)=>Object.assign($,w.opts()),{})}error($,w){if(this._outputConfiguration.outputError(`${$}
23
23
  `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==="string")this._outputConfiguration.writeErr(`${this._showHelpAfterError}
24
24
  `);else if(this._showHelpAfterError)this._outputConfiguration.writeErr(`
25
- `),this.outputHelp({error:!0});let G=w||{},W=G.exitCode||1,Y=G.code||"commander.error";this._exit(W,Y,$)}_parseOptionsEnv(){this.options.forEach(($)=>{if($.envVar&&$.envVar in p.env){let w=$.attributeName();if(this.getOptionValue(w)===void 0||["default","config","env"].includes(this.getOptionValueSource(w)))if($.required||$.optional)this.emit(`optionEnv:${$.name()}`,p.env[$.envVar]);else this.emit(`optionEnv:${$.name()}`)}})}_parseOptionsImplied(){let $=new cQ(this.options),w=(G)=>{return this.getOptionValue(G)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(G))};this.options.filter((G)=>G.implied!==void 0&&w(G.attributeName())&&$.valueFromOption(this.getOptionValue(G.attributeName()),G)).forEach((G)=>{Object.keys(G.implied).filter((W)=>!w(W)).forEach((W)=>{this.setOptionValueWithSource(W,G.implied[W],"implied")})})}missingArgument($){let w=`error: missing required argument '${$}'`;this.error(w,{code:"commander.missingArgument"})}optionMissingArgument($){let w=`error: option '${$.flags}' argument missing`;this.error(w,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue($){let w=`error: required option '${$.flags}' not specified`;this.error(w,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption($,w){let G=(Z)=>{let X=Z.attributeName(),J=this.getOptionValue(X),T=this.options.find((f)=>f.negate&&X===f.attributeName()),M=this.options.find((f)=>!f.negate&&X===f.attributeName());if(T&&(T.presetArg===void 0&&J===!1||T.presetArg!==void 0&&J===T.presetArg))return T;return M||Z},W=(Z)=>{let X=G(Z),J=X.attributeName();if(this.getOptionValueSource(J)==="env")return`environment variable '${X.envVar}'`;return`option '${X.flags}'`},Y=`error: ${W($)} cannot be used with ${W(w)}`;this.error(Y,{code:"commander.conflictingOption"})}unknownOption($){if(this._allowUnknownOption)return;let w="";if($.startsWith("--")&&this._showSuggestionAfterError){let W=[],Y=this;do{let Z=Y.createHelp().visibleOptions(Y).filter((X)=>X.long).map((X)=>X.long);W=W.concat(Z),Y=Y.parent}while(Y&&!Y._enablePositionalOptions);w=r3($,W)}let G=`error: unknown option '${$}'${w}`;this.error(G,{code:"commander.unknownOption"})}_excessArguments($){if(this._allowExcessArguments)return;let w=this.registeredArguments.length,G=w===1?"":"s",Y=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${w} argument${G} but got ${$.length}.`;this.error(Y,{code:"commander.excessArguments"})}unknownCommand(){let $=this.args[0],w="";if(this._showSuggestionAfterError){let W=[];this.createHelp().visibleCommands(this).forEach((Y)=>{if(W.push(Y.name()),Y.alias())W.push(Y.alias())}),w=r3($,W)}let G=`error: unknown command '${$}'${w}`;this.error(G,{code:"commander.unknownCommand"})}version($,w,G){if($===void 0)return this._version;this._version=$,w=w||"-V, --version",G=G||"output the version number";let W=this.createOption(w,G);return this._versionOptionName=W.attributeName(),this._registerOption(W),this.on("option:"+W.name(),()=>{this._outputConfiguration.writeOut(`${$}
26
- `),this._exit(0,"commander.version",$)}),this}description($,w){if($===void 0&&w===void 0)return this._description;if(this._description=$,w)this._argsDescription=w;return this}summary($){if($===void 0)return this._summary;return this._summary=$,this}alias($){if($===void 0)return this._aliases[0];let w=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)w=this.commands[this.commands.length-1];if($===w._name)throw Error("Command alias can't be the same as its name");let G=this.parent?._findCommand($);if(G){let W=[G.name()].concat(G.aliases()).join("|");throw Error(`cannot add alias '${$}' to command '${this.name()}' as already have command '${W}'`)}return w._aliases.push($),this}aliases($){if($===void 0)return this._aliases;return $.forEach((w)=>this.alias(w)),this}usage($){if($===void 0){if(this._usage)return this._usage;let w=this.registeredArguments.map((G)=>{return iQ(G)});return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?w:[]).join(" ")}return this._usage=$,this}name($){if($===void 0)return this._name;return this._name=$,this}helpGroup($){if($===void 0)return this._helpGroupHeading??"";return this._helpGroupHeading=$,this}commandsGroup($){if($===void 0)return this._defaultCommandGroup??"";return this._defaultCommandGroup=$,this}optionsGroup($){if($===void 0)return this._defaultOptionGroup??"";return this._defaultOptionGroup=$,this}_initOptionGroup($){if(this._defaultOptionGroup&&!$.helpGroupHeading)$.helpGroup(this._defaultOptionGroup)}_initCommandGroup($){if(this._defaultCommandGroup&&!$.helpGroup())$.helpGroup(this._defaultCommandGroup)}nameFromFilename($){return this._name=K1.basename($,K1.extname($)),this}executableDir($){if($===void 0)return this._executableDir;return this._executableDir=$,this}helpInformation($){let w=this.createHelp(),G=this._getOutputContext($);w.prepareContext({error:G.error,helpWidth:G.helpWidth,outputHasColors:G.hasColors});let W=w.formatHelp(this,w);if(G.hasColors)return W;return this._outputConfiguration.stripColor(W)}_getOutputContext($){$=$||{};let w=!!$.error,G,W,Y;if(w)G=(X)=>this._outputConfiguration.writeErr(X),W=this._outputConfiguration.getErrHasColors(),Y=this._outputConfiguration.getErrHelpWidth();else G=(X)=>this._outputConfiguration.writeOut(X),W=this._outputConfiguration.getOutHasColors(),Y=this._outputConfiguration.getOutHelpWidth();return{error:w,write:(X)=>{if(!W)X=this._outputConfiguration.stripColor(X);return G(X)},hasColors:W,helpWidth:Y}}outputHelp($){let w;if(typeof $==="function")w=$,$=void 0;let G=this._getOutputContext($),W={error:G.error,write:G.write,command:this};this._getCommandAndAncestors().reverse().forEach((Z)=>Z.emit("beforeAllHelp",W)),this.emit("beforeHelp",W);let Y=this.helpInformation({error:G.error});if(w){if(Y=w(Y),typeof Y!=="string"&&!Buffer.isBuffer(Y))throw Error("outputHelp callback must return a string or a Buffer")}if(G.write(Y),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",W),this._getCommandAndAncestors().forEach((Z)=>Z.emit("afterAllHelp",W))}helpOption($,w){if(typeof $==="boolean"){if($){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($??"-h, --help",w??"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($){return this._helpOption=$,this._initOptionGroup($),this}help($){this.outputHelp($);let w=Number(p.exitCode??0);if(w===0&&$&&typeof $!=="function"&&$.error)w=1;this._exit(w,"commander.help","(outputHelp)")}addHelpText($,w){let G=["beforeAll","before","after","afterAll"];if(!G.includes($))throw Error(`Unexpected value for position to addHelpText.
27
- Expecting one of '${G.join("', '")}'`);let W=`${$}Help`;return this.on(W,(Y)=>{let Z;if(typeof w==="function")Z=w({error:Y.error,command:Y.command});else Z=w;if(Z)Y.write(`${Z}
28
- `)}),this}_outputHelpIfRequested($){let w=this._getHelpOption();if(w&&$.find((W)=>w.is(W)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function s3($){return $.map((w)=>{if(!w.startsWith("--inspect"))return w;let G,W="127.0.0.1",Y="9229",Z;if((Z=w.match(/^(--inspect(-brk)?)$/))!==null)G=Z[1];else if((Z=w.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(G=Z[1],/^\d+$/.test(Z[3]))Y=Z[3];else W=Z[3];else if((Z=w.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)G=Z[1],W=Z[3],Y=Z[4];if(G&&Y!=="0")return`${G}=${W}:${parseInt(Y)+1}`;return w})}function D5(){if(p.env.NO_COLOR||p.env.FORCE_COLOR==="0"||p.env.FORCE_COLOR==="false")return!1;if(p.env.FORCE_COLOR||p.env.CLICOLOR_FORCE!==void 0)return!0;return}dQ.Command=k5;dQ.useColor=D5});var S5=L((sQ)=>{var{Argument:o3}=Z8(),{Command:A5}=a3(),{CommanderError:tQ,InvalidArgumentError:e3}=pw(),{Help:rQ}=H5(),{Option:$Y}=F5();sQ.program=new A5;sQ.createCommand=($)=>new A5($);sQ.createOption=($,w)=>new $Y($,w);sQ.createArgument=($,w)=>new o3($,w);sQ.Command=A5;sQ.Option=$Y;sQ.Argument=o3;sQ.Help=rQ;sQ.CommanderError=tQ;sQ.InvalidArgumentError=e3;sQ.InvalidOptionArgumentError=e3});var rw=L((MY)=>{Object.defineProperty(MY,"__esModule",{value:!0});MY.regexpCode=MY.getEsmExportName=MY.getProperty=MY.safeStringify=MY.stringify=MY.strConcat=MY.addCodeArg=MY.str=MY._=MY.nil=MY._Code=MY.Name=MY.IDENTIFIER=MY._CodeOrName=void 0;class M8{}MY._CodeOrName=M8;MY.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class n$ extends M8{constructor($){super();if(!MY.IDENTIFIER.test($))throw Error("CodeGen: name must be a valid identifier");this.str=$}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}MY.Name=n$;class n0 extends M8{constructor($){super();this._items=typeof $==="string"?[$]:$}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let $=this._items[0];return $===""||$==='""'}get str(){var $;return($=this._str)!==null&&$!==void 0?$:this._str=this._items.reduce((w,G)=>`${w}${G}`,"")}get names(){var $;return($=this._names)!==null&&$!==void 0?$:this._names=this._items.reduce((w,G)=>{if(G instanceof n$)w[G.str]=(w[G.str]||0)+1;return w},{})}}MY._Code=n0;MY.nil=new n0("");function JY($,...w){let G=[$[0]],W=0;while(W<w.length)I5(G,w[W]),G.push($[++W]);return new n0(G)}MY._=JY;var y5=new n0("+");function TY($,...w){let G=[tw($[0])],W=0;while(W<w.length)G.push(y5),I5(G,w[W]),G.push(y5,tw($[++W]));return KN(G),new n0(G)}MY.str=TY;function I5($,w){if(w instanceof n0)$.push(...w._items);else if(w instanceof n$)$.push(w);else $.push(VN(w))}MY.addCodeArg=I5;function KN($){let w=1;while(w<$.length-1){if($[w]===y5){let G=PN($[w-1],$[w+1]);if(G!==void 0){$.splice(w-1,3,G);continue}$[w++]="+"}w++}}function PN($,w){if(w==='""')return $;if($==='""')return w;if(typeof $=="string"){if(w instanceof n$||$[$.length-1]!=='"')return;if(typeof w!="string")return`${$.slice(0,-1)}${w}"`;if(w[0]==='"')return $.slice(0,-1)+w.slice(1);return}if(typeof w=="string"&&w[0]==='"'&&!($ instanceof n$))return`"${$}${w.slice(1)}`;return}function BN($,w){return w.emptyStr()?$:$.emptyStr()?w:TY`${$}${w}`}MY.strConcat=BN;function VN($){return typeof $=="number"||typeof $=="boolean"||$===null?$:tw(Array.isArray($)?$.join(","):$)}function qN($){return new n0(tw($))}MY.stringify=qN;function tw($){return JSON.stringify($).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}MY.safeStringify=tw;function EN($){return typeof $=="string"&&MY.IDENTIFIER.test($)?new n0(`.${$}`):JY`[${$}]`}MY.getProperty=EN;function UN($){if(typeof $=="string"&&MY.IDENTIFIER.test($))return new n0(`${$}`);throw Error(`CodeGen: invalid export name: ${$}, use explicit $id name mapping`)}MY.getEsmExportName=UN;function HN($){return new n0($.toString())}MY.regexpCode=HN});var g5=L((zY)=>{Object.defineProperty(zY,"__esModule",{value:!0});zY.ValueScope=zY.ValueScopeName=zY.Scope=zY.varKinds=zY.UsedValueState=void 0;var D0=rw();class QY extends Error{constructor($){super(`CodeGen: "code" for ${$} not defined`);this.value=$.value}}var Q8;(function($){$[$.Started=0]="Started",$[$.Completed=1]="Completed"})(Q8||(zY.UsedValueState=Q8={}));zY.varKinds={const:new D0.Name("const"),let:new D0.Name("let"),var:new D0.Name("var")};class x5{constructor({prefixes:$,parent:w}={}){this._names={},this._prefixes=$,this._parent=w}toName($){return $ instanceof D0.Name?$:this.name($)}name($){return new D0.Name(this._newName($))}_newName($){let w=this._names[$]||this._nameGroup($);return`${$}${w.index++}`}_nameGroup($){var w,G;if(((G=(w=this._parent)===null||w===void 0?void 0:w._prefixes)===null||G===void 0?void 0:G.has($))||this._prefixes&&!this._prefixes.has($))throw Error(`CodeGen: prefix "${$}" is not allowed in this scope`);return this._names[$]={prefix:$,index:0}}}zY.Scope=x5;class _5 extends D0.Name{constructor($,w){super(w);this.prefix=$}setValue($,{property:w,itemIndex:G}){this.value=$,this.scopePath=D0._`.${new D0.Name(w)}[${G}]`}}zY.ValueScopeName=_5;var bN=D0._`\n`;class NY extends x5{constructor($){super($);this._values={},this._scope=$.scope,this.opts={...$,_n:$.lines?bN:D0.nil}}get(){return this._scope}name($){return new _5($,this._newName($))}value($,w){var G;if(w.ref===void 0)throw Error("CodeGen: ref must be passed in value");let W=this.toName($),{prefix:Y}=W,Z=(G=w.key)!==null&&G!==void 0?G:w.ref,X=this._values[Y];if(X){let M=X.get(Z);if(M)return M}else X=this._values[Y]=new Map;X.set(Z,W);let J=this._scope[Y]||(this._scope[Y]=[]),T=J.length;return J[T]=w.ref,W.setValue(w,{property:Y,itemIndex:T}),W}getValue($,w){let G=this._values[$];if(!G)return;return G.get(w)}scopeRefs($,w=this._values){return this._reduceValues(w,(G)=>{if(G.scopePath===void 0)throw Error(`CodeGen: name "${G}" has no value`);return D0._`${$}${G.scopePath}`})}scopeCode($=this._values,w,G){return this._reduceValues($,(W)=>{if(W.value===void 0)throw Error(`CodeGen: name "${W}" has no value`);return W.value.code},w,G)}_reduceValues($,w,G={},W){let Y=D0.nil;for(let Z in $){let X=$[Z];if(!X)continue;let J=G[Z]=G[Z]||new Map;X.forEach((T)=>{if(J.has(T))return;J.set(T,Q8.Started);let M=w(T);if(M){let f=this.opts.es5?zY.varKinds.var:zY.varKinds.const;Y=D0._`${Y}${f} ${T} = ${M};${this.opts._n}`}else if(M=W===null||W===void 0?void 0:W(T))Y=D0._`${Y}${M}${this.opts._n}`;else throw new QY(T);J.set(T,Q8.Completed)})}return Y}}zY.ValueScope=NY});var i=L((k0)=>{Object.defineProperty(k0,"__esModule",{value:!0});k0.or=k0.and=k0.not=k0.CodeGen=k0.operators=k0.varKinds=k0.ValueScopeName=k0.ValueScope=k0.Scope=k0.Name=k0.regexpCode=k0.stringify=k0.getProperty=k0.nil=k0.strConcat=k0.str=k0._=void 0;var l=rw(),p0=g5(),_1=rw();Object.defineProperty(k0,"_",{enumerable:!0,get:function(){return _1._}});Object.defineProperty(k0,"str",{enumerable:!0,get:function(){return _1.str}});Object.defineProperty(k0,"strConcat",{enumerable:!0,get:function(){return _1.strConcat}});Object.defineProperty(k0,"nil",{enumerable:!0,get:function(){return _1.nil}});Object.defineProperty(k0,"getProperty",{enumerable:!0,get:function(){return _1.getProperty}});Object.defineProperty(k0,"stringify",{enumerable:!0,get:function(){return _1.stringify}});Object.defineProperty(k0,"regexpCode",{enumerable:!0,get:function(){return _1.regexpCode}});Object.defineProperty(k0,"Name",{enumerable:!0,get:function(){return _1.Name}});var V8=g5();Object.defineProperty(k0,"Scope",{enumerable:!0,get:function(){return V8.Scope}});Object.defineProperty(k0,"ValueScope",{enumerable:!0,get:function(){return V8.ValueScope}});Object.defineProperty(k0,"ValueScopeName",{enumerable:!0,get:function(){return V8.ValueScopeName}});Object.defineProperty(k0,"varKinds",{enumerable:!0,get:function(){return V8.varKinds}});k0.operators={GT:new l._Code(">"),GTE:new l._Code(">="),LT:new l._Code("<"),LTE:new l._Code("<="),EQ:new l._Code("==="),NEQ:new l._Code("!=="),NOT:new l._Code("!"),OR:new l._Code("||"),AND:new l._Code("&&"),ADD:new l._Code("+")};class g1{optimizeNodes(){return this}optimizeNames($,w){return this}}class PY extends g1{constructor($,w,G){super();this.varKind=$,this.name=w,this.rhs=G}render({es5:$,_n:w}){let G=$?p0.varKinds.var:this.varKind,W=this.rhs===void 0?"":` = ${this.rhs}`;return`${G} ${this.name}${W};`+w}optimizeNames($,w){if(!$[this.name.str])return;if(this.rhs)this.rhs=t$(this.rhs,$,w);return this}get names(){return this.rhs instanceof l._CodeOrName?this.rhs.names:{}}}class h5 extends g1{constructor($,w,G){super();this.lhs=$,this.rhs=w,this.sideEffects=G}render({_n:$}){return`${this.lhs} = ${this.rhs};`+$}optimizeNames($,w){if(this.lhs instanceof l.Name&&!$[this.lhs.str]&&!this.sideEffects)return;return this.rhs=t$(this.rhs,$,w),this}get names(){let $=this.lhs instanceof l.Name?{}:{...this.lhs.names};return B8($,this.rhs)}}class BY extends h5{constructor($,w,G,W){super($,G,W);this.op=w}render({_n:$}){return`${this.lhs} ${this.op}= ${this.rhs};`+$}}class VY extends g1{constructor($){super();this.label=$,this.names={}}render({_n:$}){return`${this.label}:`+$}}class qY extends g1{constructor($){super();this.label=$,this.names={}}render({_n:$}){return`break${this.label?` ${this.label}`:""};`+$}}class EY extends g1{constructor($){super();this.error=$}render({_n:$}){return`throw ${this.error};`+$}get names(){return this.error.names}}class UY extends g1{constructor($){super();this.code=$}render({_n:$}){return`${this.code};`+$}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames($,w){return this.code=t$(this.code,$,w),this}get names(){return this.code instanceof l._CodeOrName?this.code.names:{}}}class q8 extends g1{constructor($=[]){super();this.nodes=$}render($){return this.nodes.reduce((w,G)=>w+G.render($),"")}optimizeNodes(){let{nodes:$}=this,w=$.length;while(w--){let G=$[w].optimizeNodes();if(Array.isArray(G))$.splice(w,1,...G);else if(G)$[w]=G;else $.splice(w,1)}return $.length>0?this:void 0}optimizeNames($,w){let{nodes:G}=this,W=G.length;while(W--){let Y=G[W];if(Y.optimizeNames($,w))continue;vN($,Y.names),G.splice(W,1)}return G.length>0?this:void 0}get names(){return this.nodes.reduce(($,w)=>Y$($,w.names),{})}}class v1 extends q8{render($){return"{"+$._n+super.render($)+"}"+$._n}}class HY extends q8{}class sw extends v1{}sw.kind="else";class P1 extends v1{constructor($,w){super(w);this.condition=$}render($){let w=`if(${this.condition})`+super.render($);if(this.else)w+="else "+this.else.render($);return w}optimizeNodes(){super.optimizeNodes();let $=this.condition;if($===!0)return this.nodes;let w=this.else;if(w){let G=w.optimizeNodes();w=this.else=Array.isArray(G)?new sw(G):G}if(w){if($===!1)return w instanceof P1?w:w.nodes;if(this.nodes.length)return this;return new P1(kY($),w instanceof P1?[w]:w.nodes)}if($===!1||!this.nodes.length)return;return this}optimizeNames($,w){var G;if(this.else=(G=this.else)===null||G===void 0?void 0:G.optimizeNames($,w),!(super.optimizeNames($,w)||this.else))return;return this.condition=t$(this.condition,$,w),this}get names(){let $=super.names;if(B8($,this.condition),this.else)Y$($,this.else.names);return $}}P1.kind="if";class p$ extends v1{}p$.kind="for";class FY extends p${constructor($){super();this.iteration=$}render($){return`for(${this.iteration})`+super.render($)}optimizeNames($,w){if(!super.optimizeNames($,w))return;return this.iteration=t$(this.iteration,$,w),this}get names(){return Y$(super.names,this.iteration.names)}}class OY extends p${constructor($,w,G,W){super();this.varKind=$,this.name=w,this.from=G,this.to=W}render($){let w=$.es5?p0.varKinds.var:this.varKind,{name:G,from:W,to:Y}=this;return`for(${w} ${G}=${W}; ${G}<${Y}; ${G}++)`+super.render($)}get names(){let $=B8(super.names,this.from);return B8($,this.to)}}class v5 extends p${constructor($,w,G,W){super();this.loop=$,this.varKind=w,this.name=G,this.iterable=W}render($){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render($)}optimizeNames($,w){if(!super.optimizeNames($,w))return;return this.iterable=t$(this.iterable,$,w),this}get names(){return Y$(super.names,this.iterable.names)}}class N8 extends v1{constructor($,w,G){super();this.name=$,this.args=w,this.async=G}render($){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render($)}}N8.kind="func";class z8 extends q8{render($){return"return "+super.render($)}}z8.kind="return";class LY extends v1{render($){let w="try"+super.render($);if(this.catch)w+=this.catch.render($);if(this.finally)w+=this.finally.render($);return w}optimizeNodes(){var $,w;return super.optimizeNodes(),($=this.catch)===null||$===void 0||$.optimizeNodes(),(w=this.finally)===null||w===void 0||w.optimizeNodes(),this}optimizeNames($,w){var G,W;return super.optimizeNames($,w),(G=this.catch)===null||G===void 0||G.optimizeNames($,w),(W=this.finally)===null||W===void 0||W.optimizeNames($,w),this}get names(){let $=super.names;if(this.catch)Y$($,this.catch.names);if(this.finally)Y$($,this.finally.names);return $}}class K8 extends v1{constructor($){super();this.error=$}render($){return`catch(${this.error})`+super.render($)}}K8.kind="catch";class P8 extends v1{render($){return"finally"+super.render($)}}P8.kind="finally";class DY{constructor($,w={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...w,_n:w.lines?`
29
- `:""},this._extScope=$,this._scope=new p0.Scope({parent:$}),this._nodes=[new HY]}toString(){return this._root.render(this.opts)}name($){return this._scope.name($)}scopeName($){return this._extScope.name($)}scopeValue($,w){let G=this._extScope.value($,w);return(this._values[G.prefix]||(this._values[G.prefix]=new Set)).add(G),G}getScopeValue($,w){return this._extScope.getValue($,w)}scopeRefs($){return this._extScope.scopeRefs($,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def($,w,G,W){let Y=this._scope.toName(w);if(G!==void 0&&W)this._constants[Y.str]=G;return this._leafNode(new PY($,Y,G)),Y}const($,w,G){return this._def(p0.varKinds.const,$,w,G)}let($,w,G){return this._def(p0.varKinds.let,$,w,G)}var($,w,G){return this._def(p0.varKinds.var,$,w,G)}assign($,w,G){return this._leafNode(new h5($,w,G))}add($,w){return this._leafNode(new BY($,k0.operators.ADD,w))}code($){if(typeof $=="function")$();else if($!==l.nil)this._leafNode(new UY($));return this}object(...$){let w=["{"];for(let[G,W]of $){if(w.length>1)w.push(",");if(w.push(G),G!==W||this.opts.es5)w.push(":"),(0,l.addCodeArg)(w,W)}return w.push("}"),new l._Code(w)}if($,w,G){if(this._blockNode(new P1($)),w&&G)this.code(w).else().code(G).endIf();else if(w)this.code(w).endIf();else if(G)throw Error('CodeGen: "else" body without "then" body');return this}elseIf($){return this._elseNode(new P1($))}else(){return this._elseNode(new sw)}endIf(){return this._endBlockNode(P1,sw)}_for($,w){if(this._blockNode($),w)this.code(w).endFor();return this}for($,w){return this._for(new FY($),w)}forRange($,w,G,W,Y=this.opts.es5?p0.varKinds.var:p0.varKinds.let){let Z=this._scope.toName($);return this._for(new OY(Y,Z,w,G),()=>W(Z))}forOf($,w,G,W=p0.varKinds.const){let Y=this._scope.toName($);if(this.opts.es5){let Z=w instanceof l.Name?w:this.var("_arr",w);return this.forRange("_i",0,l._`${Z}.length`,(X)=>{this.var(Y,l._`${Z}[${X}]`),G(Y)})}return this._for(new v5("of",W,Y,w),()=>G(Y))}forIn($,w,G,W=this.opts.es5?p0.varKinds.var:p0.varKinds.const){if(this.opts.ownProperties)return this.forOf($,l._`Object.keys(${w})`,G);let Y=this._scope.toName($);return this._for(new v5("in",W,Y,w),()=>G(Y))}endFor(){return this._endBlockNode(p$)}label($){return this._leafNode(new VY($))}break($){return this._leafNode(new qY($))}return($){let w=new z8;if(this._blockNode(w),this.code($),w.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(z8)}try($,w,G){if(!w&&!G)throw Error('CodeGen: "try" without "catch" and "finally"');let W=new LY;if(this._blockNode(W),this.code($),w){let Y=this.name("e");this._currNode=W.catch=new K8(Y),w(Y)}if(G)this._currNode=W.finally=new P8,this.code(G);return this._endBlockNode(K8,P8)}throw($){return this._leafNode(new EY($))}block($,w){if(this._blockStarts.push(this._nodes.length),$)this.code($).endBlock(w);return this}endBlock($){let w=this._blockStarts.pop();if(w===void 0)throw Error("CodeGen: not in self-balancing block");let G=this._nodes.length-w;if(G<0||$!==void 0&&G!==$)throw Error(`CodeGen: wrong number of nodes: ${G} vs ${$} expected`);return this._nodes.length=w,this}func($,w=l.nil,G,W){if(this._blockNode(new N8($,w,G)),W)this.code(W).endFunc();return this}endFunc(){return this._endBlockNode(N8)}optimize($=1){while($-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode($){return this._currNode.nodes.push($),this}_blockNode($){this._currNode.nodes.push($),this._nodes.push($)}_endBlockNode($,w){let G=this._currNode;if(G instanceof $||w&&G instanceof w)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${w?`${$.kind}/${w.kind}`:$.kind}"`)}_elseNode($){let w=this._currNode;if(!(w instanceof P1))throw Error('CodeGen: "else" without "if"');return this._currNode=w.else=$,this}get _root(){return this._nodes[0]}get _currNode(){let $=this._nodes;return $[$.length-1]}set _currNode($){let w=this._nodes;w[w.length-1]=$}}k0.CodeGen=DY;function Y$($,w){for(let G in w)$[G]=($[G]||0)+(w[G]||0);return $}function B8($,w){return w instanceof l._CodeOrName?Y$($,w.names):$}function t$($,w,G){if($ instanceof l.Name)return W($);if(!Y($))return $;return new l._Code($._items.reduce((Z,X)=>{if(X instanceof l.Name)X=W(X);if(X instanceof l._Code)Z.push(...X._items);else Z.push(X);return Z},[]));function W(Z){let X=G[Z.str];if(X===void 0||w[Z.str]!==1)return Z;return delete w[Z.str],X}function Y(Z){return Z instanceof l._Code&&Z._items.some((X)=>X instanceof l.Name&&w[X.str]===1&&G[X.str]!==void 0)}}function vN($,w){for(let G in w)$[G]=($[G]||0)-(w[G]||0)}function kY($){return typeof $=="boolean"||typeof $=="number"||$===null?!$:l._`!${u5($)}`}k0.not=kY;var uN=AY(k0.operators.AND);function hN(...$){return $.reduce(uN)}k0.and=hN;var iN=AY(k0.operators.OR);function mN(...$){return $.reduce(iN)}k0.or=mN;function AY($){return(w,G)=>w===l.nil?G:G===l.nil?w:l._`${u5(w)} ${$} ${u5(G)}`}function u5($){return $ instanceof l.Name?$:l._`(${$})`}});var c=L((_Y)=>{Object.defineProperty(_Y,"__esModule",{value:!0});_Y.checkStrictMode=_Y.getErrorPath=_Y.Type=_Y.useFunc=_Y.setEvaluated=_Y.evaluatedPropsToName=_Y.mergeEvaluated=_Y.eachItem=_Y.unescapeJsonPointer=_Y.escapeJsonPointer=_Y.escapeFragment=_Y.unescapeFragment=_Y.schemaRefOrVal=_Y.schemaHasRulesButRef=_Y.schemaHasRules=_Y.checkUnknownRules=_Y.alwaysValidSchema=_Y.toHash=void 0;var r=i(),nN=rw();function pN($){let w={};for(let G of $)w[G]=!0;return w}_Y.toHash=pN;function tN($,w){if(typeof w=="boolean")return w;if(Object.keys(w).length===0)return!0;return CY($,w),!yY(w,$.self.RULES.all)}_Y.alwaysValidSchema=tN;function CY($,w=$.schema){let{opts:G,self:W}=$;if(!G.strictSchema)return;if(typeof w==="boolean")return;let Y=W.RULES.keywords;for(let Z in w)if(!Y[Z])xY($,`unknown keyword: "${Z}"`)}_Y.checkUnknownRules=CY;function yY($,w){if(typeof $=="boolean")return!$;for(let G in $)if(w[G])return!0;return!1}_Y.schemaHasRules=yY;function rN($,w){if(typeof $=="boolean")return!$;for(let G in $)if(G!=="$ref"&&w.all[G])return!0;return!1}_Y.schemaHasRulesButRef=rN;function sN({topSchemaRef:$,schemaPath:w},G,W,Y){if(!Y){if(typeof G=="number"||typeof G=="boolean")return G;if(typeof G=="string")return r._`${G}`}return r._`${$}${w}${(0,r.getProperty)(W)}`}_Y.schemaRefOrVal=sN;function aN($){return IY(decodeURIComponent($))}_Y.unescapeFragment=aN;function oN($){return encodeURIComponent(m5($))}_Y.escapeFragment=oN;function m5($){if(typeof $=="number")return`${$}`;return $.replace(/~/g,"~0").replace(/\//g,"~1")}_Y.escapeJsonPointer=m5;function IY($){return $.replace(/~1/g,"/").replace(/~0/g,"~")}_Y.unescapeJsonPointer=IY;function eN($,w){if(Array.isArray($))for(let G of $)w(G);else w($)}_Y.eachItem=eN;function RY({mergeNames:$,mergeToName:w,mergeValues:G,resultToName:W}){return(Y,Z,X,J)=>{let T=X===void 0?Z:X instanceof r.Name?(Z instanceof r.Name?$(Y,Z,X):w(Y,Z,X),X):Z instanceof r.Name?(w(Y,X,Z),Z):G(Z,X);return J===r.Name&&!(T instanceof r.Name)?W(Y,T):T}}_Y.mergeEvaluated={props:RY({mergeNames:($,w,G)=>$.if(r._`${G} !== true && ${w} !== undefined`,()=>{$.if(r._`${w} === true`,()=>$.assign(G,!0),()=>$.assign(G,r._`${G} || {}`).code(r._`Object.assign(${G}, ${w})`))}),mergeToName:($,w,G)=>$.if(r._`${G} !== true`,()=>{if(w===!0)$.assign(G,!0);else $.assign(G,r._`${G} || {}`),l5($,G,w)}),mergeValues:($,w)=>$===!0?!0:{...$,...w},resultToName:bY}),items:RY({mergeNames:($,w,G)=>$.if(r._`${G} !== true && ${w} !== undefined`,()=>$.assign(G,r._`${w} === true ? true : ${G} > ${w} ? ${G} : ${w}`)),mergeToName:($,w,G)=>$.if(r._`${G} !== true`,()=>$.assign(G,w===!0?!0:r._`${G} > ${w} ? ${G} : ${w}`)),mergeValues:($,w)=>$===!0?!0:Math.max($,w),resultToName:($,w)=>$.var("items",w)})};function bY($,w){if(w===!0)return $.var("props",!0);let G=$.var("props",r._`{}`);if(w!==void 0)l5($,G,w);return G}_Y.evaluatedPropsToName=bY;function l5($,w,G){Object.keys(G).forEach((W)=>$.assign(r._`${w}${(0,r.getProperty)(W)}`,!0))}_Y.setEvaluated=l5;var jY={};function $z($,w){return $.scopeValue("func",{ref:w,code:jY[w.code]||(jY[w.code]=new nN._Code(w.code))})}_Y.useFunc=$z;var i5;(function($){$[$.Num=0]="Num",$[$.Str=1]="Str"})(i5||(_Y.Type=i5={}));function wz($,w,G){if($ instanceof r.Name){let W=w===i5.Num;return G?W?r._`"[" + ${$} + "]"`:r._`"['" + ${$} + "']"`:W?r._`"/" + ${$}`:r._`"/" + ${$}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return G?(0,r.getProperty)($).toString():"/"+m5($)}_Y.getErrorPath=wz;function xY($,w,G=$.opts.strictSchema){if(!G)return;if(w=`strict mode: ${w}`,G===!0)throw Error(w);$.self.logger.warn(w)}_Y.checkStrictMode=xY});var B1=L((vY)=>{Object.defineProperty(vY,"__esModule",{value:!0});var P0=i(),Ez={data:new P0.Name("data"),valCxt:new P0.Name("valCxt"),instancePath:new P0.Name("instancePath"),parentData:new P0.Name("parentData"),parentDataProperty:new P0.Name("parentDataProperty"),rootData:new P0.Name("rootData"),dynamicAnchors:new P0.Name("dynamicAnchors"),vErrors:new P0.Name("vErrors"),errors:new P0.Name("errors"),this:new P0.Name("this"),self:new P0.Name("self"),scope:new P0.Name("scope"),json:new P0.Name("json"),jsonPos:new P0.Name("jsonPos"),jsonLen:new P0.Name("jsonLen"),jsonPart:new P0.Name("jsonPart")};vY.default=Ez});var aw=L((mY)=>{Object.defineProperty(mY,"__esModule",{value:!0});mY.extendErrors=mY.resetErrorsCount=mY.reportExtraError=mY.reportError=mY.keyword$DataError=mY.keywordError=void 0;var d=i(),U8=c(),F0=B1();mY.keywordError={message:({keyword:$})=>d.str`must pass "${$}" keyword validation`};mY.keyword$DataError={message:({keyword:$,schemaType:w})=>w?d.str`"${$}" keyword must be ${w} ($data)`:d.str`"${$}" keyword is invalid ($data)`};function Hz($,w=mY.keywordError,G,W){let{it:Y}=$,{gen:Z,compositeRule:X,allErrors:J}=Y,T=iY($,w,G);if(W!==null&&W!==void 0?W:X||J)uY(Z,T);else hY(Y,d._`[${T}]`)}mY.reportError=Hz;function Fz($,w=mY.keywordError,G){let{it:W}=$,{gen:Y,compositeRule:Z,allErrors:X}=W,J=iY($,w,G);if(uY(Y,J),!(Z||X))hY(W,F0.default.vErrors)}mY.reportExtraError=Fz;function Oz($,w){$.assign(F0.default.errors,w),$.if(d._`${F0.default.vErrors} !== null`,()=>$.if(w,()=>$.assign(d._`${F0.default.vErrors}.length`,w),()=>$.assign(F0.default.vErrors,null)))}mY.resetErrorsCount=Oz;function Lz({gen:$,keyword:w,schemaValue:G,data:W,errsCount:Y,it:Z}){if(Y===void 0)throw Error("ajv implementation error");let X=$.name("err");$.forRange("i",Y,F0.default.errors,(J)=>{if($.const(X,d._`${F0.default.vErrors}[${J}]`),$.if(d._`${X}.instancePath === undefined`,()=>$.assign(d._`${X}.instancePath`,(0,d.strConcat)(F0.default.instancePath,Z.errorPath))),$.assign(d._`${X}.schemaPath`,d.str`${Z.errSchemaPath}/${w}`),Z.opts.verbose)$.assign(d._`${X}.schema`,G),$.assign(d._`${X}.data`,W)})}mY.extendErrors=Lz;function uY($,w){let G=$.const("err",w);$.if(d._`${F0.default.vErrors} === null`,()=>$.assign(F0.default.vErrors,d._`[${G}]`),d._`${F0.default.vErrors}.push(${G})`),$.code(d._`${F0.default.errors}++`)}function hY($,w){let{gen:G,validateName:W,schemaEnv:Y}=$;if(Y.$async)G.throw(d._`new ${$.ValidationError}(${w})`);else G.assign(d._`${W}.errors`,w),G.return(!1)}var Z$={keyword:new d.Name("keyword"),schemaPath:new d.Name("schemaPath"),params:new d.Name("params"),propertyName:new d.Name("propertyName"),message:new d.Name("message"),schema:new d.Name("schema"),parentSchema:new d.Name("parentSchema")};function iY($,w,G){let{createErrors:W}=$.it;if(W===!1)return d._`{}`;return Dz($,w,G)}function Dz($,w,G={}){let{gen:W,it:Y}=$,Z=[kz(Y,G),Az($,G)];return Sz($,w,Z),W.object(...Z)}function kz({errorPath:$},{instancePath:w}){let G=w?d.str`${$}${(0,U8.getErrorPath)(w,U8.Type.Str)}`:$;return[F0.default.instancePath,(0,d.strConcat)(F0.default.instancePath,G)]}function Az({keyword:$,it:{errSchemaPath:w}},{schemaPath:G,parentSchema:W}){let Y=W?w:d.str`${w}/${$}`;if(G)Y=d.str`${Y}${(0,U8.getErrorPath)(G,U8.Type.Str)}`;return[Z$.schemaPath,Y]}function Sz($,{params:w,message:G},W){let{keyword:Y,data:Z,schemaValue:X,it:J}=$,{opts:T,propertyName:M,topSchemaRef:f,schemaPath:Q}=J;if(W.push([Z$.keyword,Y],[Z$.params,typeof w=="function"?w($):w||d._`{}`]),T.messages)W.push([Z$.message,typeof G=="function"?G($):G]);if(T.verbose)W.push([Z$.schema,X],[Z$.parentSchema,d._`${f}${Q}`],[F0.default.data,Z]);if(M)W.push([Z$.propertyName,M])}});var pY=L((dY)=>{Object.defineProperty(dY,"__esModule",{value:!0});dY.boolOrEmptySchema=dY.topBoolOrEmptySchema=void 0;var Iz=aw(),bz=i(),xz=B1(),_z={message:"boolean schema is false"};function gz($){let{gen:w,schema:G,validateName:W}=$;if(G===!1)cY($,!1);else if(typeof G=="object"&&G.$async===!0)w.return(xz.default.data);else w.assign(bz._`${W}.errors`,null),w.return(!0)}dY.topBoolOrEmptySchema=gz;function vz($,w){let{gen:G,schema:W}=$;if(W===!1)G.var(w,!1),cY($);else G.var(w,!0)}dY.boolOrEmptySchema=vz;function cY($,w){let{gen:G,data:W}=$,Y={gen:G,keyword:"false schema",data:W,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:$};(0,Iz.reportError)(Y,_z,void 0,w)}});var d5=L((tY)=>{Object.defineProperty(tY,"__esModule",{value:!0});tY.getRules=tY.isJSONType=void 0;var hz=["string","number","integer","boolean","null","object","array"],iz=new Set(hz);function mz($){return typeof $=="string"&&iz.has($)}tY.isJSONType=mz;function lz(){let $={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...$,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},$.number,$.string,$.array,$.object],post:{rules:[]},all:{},keywords:{}}}tY.getRules=lz});var n5=L((oY)=>{Object.defineProperty(oY,"__esModule",{value:!0});oY.shouldUseRule=oY.shouldUseGroup=oY.schemaHasRulesForType=void 0;function dz({schema:$,self:w},G){let W=w.RULES.types[G];return W&&W!==!0&&sY($,W)}oY.schemaHasRulesForType=dz;function sY($,w){return w.rules.some((G)=>aY($,G))}oY.shouldUseGroup=sY;function aY($,w){var G;return $[w.keyword]!==void 0||((G=w.definition.implements)===null||G===void 0?void 0:G.some((W)=>$[W]!==void 0))}oY.shouldUseRule=aY});var ow=L((WZ)=>{Object.defineProperty(WZ,"__esModule",{value:!0});WZ.reportTypeError=WZ.checkDataTypes=WZ.checkDataType=WZ.coerceAndCheckDataType=WZ.getJSONTypes=WZ.getSchemaTypes=WZ.DataType=void 0;var tz=d5(),rz=n5(),sz=aw(),u=i(),$Z=c(),r$;(function($){$[$.Correct=0]="Correct",$[$.Wrong=1]="Wrong"})(r$||(WZ.DataType=r$={}));function az($){let w=wZ($.type);if(w.includes("null")){if($.nullable===!1)throw Error("type: null contradicts nullable: false")}else{if(!w.length&&$.nullable!==void 0)throw Error('"nullable" cannot be used without "type"');if($.nullable===!0)w.push("null")}return w}WZ.getSchemaTypes=az;function wZ($){let w=Array.isArray($)?$:$?[$]:[];if(w.every(tz.isJSONType))return w;throw Error("type must be JSONType or JSONType[]: "+w.join(","))}WZ.getJSONTypes=wZ;function oz($,w){let{gen:G,data:W,opts:Y}=$,Z=ez(w,Y.coerceTypes),X=w.length>0&&!(Z.length===0&&w.length===1&&(0,rz.schemaHasRulesForType)($,w[0]));if(X){let J=t5(w,W,Y.strictNumbers,r$.Wrong);G.if(J,()=>{if(Z.length)$K($,w,Z);else r5($)})}return X}WZ.coerceAndCheckDataType=oz;var GZ=new Set(["string","number","integer","boolean","null"]);function ez($,w){return w?$.filter((G)=>GZ.has(G)||w==="array"&&G==="array"):[]}function $K($,w,G){let{gen:W,data:Y,opts:Z}=$,X=W.let("dataType",u._`typeof ${Y}`),J=W.let("coerced",u._`undefined`);if(Z.coerceTypes==="array")W.if(u._`${X} == 'object' && Array.isArray(${Y}) && ${Y}.length == 1`,()=>W.assign(Y,u._`${Y}[0]`).assign(X,u._`typeof ${Y}`).if(t5(w,Y,Z.strictNumbers),()=>W.assign(J,Y)));W.if(u._`${J} !== undefined`);for(let M of G)if(GZ.has(M)||M==="array"&&Z.coerceTypes==="array")T(M);W.else(),r5($),W.endIf(),W.if(u._`${J} !== undefined`,()=>{W.assign(Y,J),wK($,J)});function T(M){switch(M){case"string":W.elseIf(u._`${X} == "number" || ${X} == "boolean"`).assign(J,u._`"" + ${Y}`).elseIf(u._`${Y} === null`).assign(J,u._`""`);return;case"number":W.elseIf(u._`${X} == "boolean" || ${Y} === null
30
- || (${X} == "string" && ${Y} && ${Y} == +${Y})`).assign(J,u._`+${Y}`);return;case"integer":W.elseIf(u._`${X} === "boolean" || ${Y} === null
31
- || (${X} === "string" && ${Y} && ${Y} == +${Y} && !(${Y} % 1))`).assign(J,u._`+${Y}`);return;case"boolean":W.elseIf(u._`${Y} === "false" || ${Y} === 0 || ${Y} === null`).assign(J,!1).elseIf(u._`${Y} === "true" || ${Y} === 1`).assign(J,!0);return;case"null":W.elseIf(u._`${Y} === "" || ${Y} === 0 || ${Y} === false`),W.assign(J,null);return;case"array":W.elseIf(u._`${X} === "string" || ${X} === "number"
32
- || ${X} === "boolean" || ${Y} === null`).assign(J,u._`[${Y}]`)}}}function wK({gen:$,parentData:w,parentDataProperty:G},W){$.if(u._`${w} !== undefined`,()=>$.assign(u._`${w}[${G}]`,W))}function p5($,w,G,W=r$.Correct){let Y=W===r$.Correct?u.operators.EQ:u.operators.NEQ,Z;switch($){case"null":return u._`${w} ${Y} null`;case"array":Z=u._`Array.isArray(${w})`;break;case"object":Z=u._`${w} && typeof ${w} == "object" && !Array.isArray(${w})`;break;case"integer":Z=X(u._`!(${w} % 1) && !isNaN(${w})`);break;case"number":Z=X();break;default:return u._`typeof ${w} ${Y} ${$}`}return W===r$.Correct?Z:(0,u.not)(Z);function X(J=u.nil){return(0,u.and)(u._`typeof ${w} == "number"`,J,G?u._`isFinite(${w})`:u.nil)}}WZ.checkDataType=p5;function t5($,w,G,W){if($.length===1)return p5($[0],w,G,W);let Y,Z=(0,$Z.toHash)($);if(Z.array&&Z.object){let X=u._`typeof ${w} != "object"`;Y=Z.null?X:u._`!${w} || ${X}`,delete Z.null,delete Z.array,delete Z.object}else Y=u.nil;if(Z.number)delete Z.integer;for(let X in Z)Y=(0,u.and)(Y,p5(X,w,G,W));return Y}WZ.checkDataTypes=t5;var GK={message:({schema:$})=>`must be ${$}`,params:({schema:$,schemaValue:w})=>typeof $=="string"?u._`{type: ${$}}`:u._`{type: ${w}}`};function r5($){let w=WK($);(0,sz.reportError)(w,GK)}WZ.reportTypeError=r5;function WK($){let{gen:w,data:G,schema:W}=$,Y=(0,$Z.schemaRefOrVal)($,W,"type");return{gen:w,keyword:"type",data:G,schema:W.type,schemaCode:Y,schemaValue:Y,parentSchema:W,params:{},it:$}}});var TZ=L((XZ)=>{Object.defineProperty(XZ,"__esModule",{value:!0});XZ.assignDefaults=void 0;var s$=i(),fK=c();function QK($,w){let{properties:G,items:W}=$.schema;if(w==="object"&&G)for(let Y in G)ZZ($,Y,G[Y].default);else if(w==="array"&&Array.isArray(W))W.forEach((Y,Z)=>ZZ($,Z,Y.default))}XZ.assignDefaults=QK;function ZZ($,w,G){let{gen:W,compositeRule:Y,data:Z,opts:X}=$;if(G===void 0)return;let J=s$._`${Z}${(0,s$.getProperty)(w)}`;if(Y){(0,fK.checkStrictMode)($,`default is ignored for: ${J}`);return}let T=s$._`${J} === undefined`;if(X.useDefaults==="empty")T=s$._`${T} || ${J} === null || ${J} === ""`;W.if(T,s$._`${J} = ${(0,s$.stringify)(G)}`)}});var i0=L((QZ)=>{Object.defineProperty(QZ,"__esModule",{value:!0});QZ.validateUnion=QZ.validateArray=QZ.usePattern=QZ.callValidateCode=QZ.schemaProperties=QZ.allSchemaProperties=QZ.noPropertyInData=QZ.propertyInData=QZ.isOwnProperty=QZ.hasPropFunc=QZ.reportMissingProp=QZ.checkMissingProp=QZ.checkReportMissingProp=void 0;var o=i(),s5=c(),u1=B1(),NK=c();function zK($,w){let{gen:G,data:W,it:Y}=$;G.if(o5(G,W,w,Y.opts.ownProperties),()=>{$.setParams({missingProperty:o._`${w}`},!0),$.error()})}QZ.checkReportMissingProp=zK;function KK({gen:$,data:w,it:{opts:G}},W,Y){return(0,o.or)(...W.map((Z)=>(0,o.and)(o5($,w,Z,G.ownProperties),o._`${Y} = ${Z}`)))}QZ.checkMissingProp=KK;function PK($,w){$.setParams({missingProperty:w},!0),$.error()}QZ.reportMissingProp=PK;function MZ($){return $.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:o._`Object.prototype.hasOwnProperty`})}QZ.hasPropFunc=MZ;function a5($,w,G){return o._`${MZ($)}.call(${w}, ${G})`}QZ.isOwnProperty=a5;function BK($,w,G,W){let Y=o._`${w}${(0,o.getProperty)(G)} !== undefined`;return W?o._`${Y} && ${a5($,w,G)}`:Y}QZ.propertyInData=BK;function o5($,w,G,W){let Y=o._`${w}${(0,o.getProperty)(G)} === undefined`;return W?(0,o.or)(Y,(0,o.not)(a5($,w,G))):Y}QZ.noPropertyInData=o5;function fZ($){return $?Object.keys($).filter((w)=>w!=="__proto__"):[]}QZ.allSchemaProperties=fZ;function VK($,w){return fZ(w).filter((G)=>!(0,s5.alwaysValidSchema)($,w[G]))}QZ.schemaProperties=VK;function qK({schemaCode:$,data:w,it:{gen:G,topSchemaRef:W,schemaPath:Y,errorPath:Z},it:X},J,T,M){let f=M?o._`${$}, ${w}, ${W}${Y}`:w,Q=[[u1.default.instancePath,(0,o.strConcat)(u1.default.instancePath,Z)],[u1.default.parentData,X.parentData],[u1.default.parentDataProperty,X.parentDataProperty],[u1.default.rootData,u1.default.rootData]];if(X.opts.dynamicRef)Q.push([u1.default.dynamicAnchors,u1.default.dynamicAnchors]);let N=o._`${f}, ${G.object(...Q)}`;return T!==o.nil?o._`${J}.call(${T}, ${N})`:o._`${J}(${N})`}QZ.callValidateCode=qK;var EK=o._`new RegExp`;function UK({gen:$,it:{opts:w}},G){let W=w.unicodeRegExp?"u":"",{regExp:Y}=w.code,Z=Y(G,W);return $.scopeValue("pattern",{key:Z.toString(),ref:Z,code:o._`${Y.code==="new RegExp"?EK:(0,NK.useFunc)($,Y)}(${G}, ${W})`})}QZ.usePattern=UK;function HK($){let{gen:w,data:G,keyword:W,it:Y}=$,Z=w.name("valid");if(Y.allErrors){let J=w.let("valid",!0);return X(()=>w.assign(J,!1)),J}return w.var(Z,!0),X(()=>w.break()),Z;function X(J){let T=w.const("len",o._`${G}.length`);w.forRange("i",0,T,(M)=>{$.subschema({keyword:W,dataProp:M,dataPropType:s5.Type.Num},Z),w.if((0,o.not)(Z),J)})}}QZ.validateArray=HK;function FK($){let{gen:w,schema:G,keyword:W,it:Y}=$;if(!Array.isArray(G))throw Error("ajv implementation error");if(G.some((T)=>(0,s5.alwaysValidSchema)(Y,T))&&!Y.opts.unevaluated)return;let X=w.let("valid",!1),J=w.name("_valid");w.block(()=>G.forEach((T,M)=>{let f=$.subschema({keyword:W,schemaProp:M,compositeRule:!0},J);if(w.assign(X,o._`${X} || ${J}`),!$.mergeValidEvaluated(f,J))w.if((0,o.not)(X))})),$.result(X,()=>$.reset(),()=>$.error(!0))}QZ.validateUnion=FK});var VZ=L((PZ)=>{Object.defineProperty(PZ,"__esModule",{value:!0});PZ.validateKeywordUsage=PZ.validSchemaType=PZ.funcKeywordCode=PZ.macroKeywordCode=void 0;var O0=i(),X$=B1(),xK=i0(),_K=aw();function gK($,w){let{gen:G,keyword:W,schema:Y,parentSchema:Z,it:X}=$,J=w.macro.call(X.self,Y,Z,X),T=KZ(G,W,J);if(X.opts.validateSchema!==!1)X.self.validateSchema(J,!0);let M=G.name("valid");$.subschema({schema:J,schemaPath:O0.nil,errSchemaPath:`${X.errSchemaPath}/${W}`,topSchemaRef:T,compositeRule:!0},M),$.pass(M,()=>$.error(!0))}PZ.macroKeywordCode=gK;function vK($,w){var G;let{gen:W,keyword:Y,schema:Z,parentSchema:X,$data:J,it:T}=$;hK(T,w);let M=!J&&w.compile?w.compile.call(T.self,Z,X,T):w.validate,f=KZ(W,Y,M),Q=W.let("valid");$.block$data(Q,N),$.ok((G=w.valid)!==null&&G!==void 0?G:Q);function N(){if(w.errors===!1){if(P(),w.modifying)zZ($);q(()=>$.error())}else{let V=w.async?z():K();if(w.modifying)zZ($);q(()=>uK($,V))}}function z(){let V=W.let("ruleErrs",null);return W.try(()=>P(O0._`await `),(E)=>W.assign(Q,!1).if(O0._`${E} instanceof ${T.ValidationError}`,()=>W.assign(V,O0._`${E}.errors`),()=>W.throw(E))),V}function K(){let V=O0._`${f}.errors`;return W.assign(V,null),P(O0.nil),V}function P(V=w.async?O0._`await `:O0.nil){let E=T.opts.passContext?X$.default.this:X$.default.self,O=!(("compile"in w)&&!J||w.schema===!1);W.assign(Q,O0._`${V}${(0,xK.callValidateCode)($,f,E,O)}`,w.modifying)}function q(V){var E;W.if((0,O0.not)((E=w.valid)!==null&&E!==void 0?E:Q),V)}}PZ.funcKeywordCode=vK;function zZ($){let{gen:w,data:G,it:W}=$;w.if(W.parentData,()=>w.assign(G,O0._`${W.parentData}[${W.parentDataProperty}]`))}function uK($,w){let{gen:G}=$;G.if(O0._`Array.isArray(${w})`,()=>{G.assign(X$.default.vErrors,O0._`${X$.default.vErrors} === null ? ${w} : ${X$.default.vErrors}.concat(${w})`).assign(X$.default.errors,O0._`${X$.default.vErrors}.length`),(0,_K.extendErrors)($)},()=>$.error())}function hK({schemaEnv:$},w){if(w.async&&!$.$async)throw Error("async keyword in sync schema")}function KZ($,w,G){if(G===void 0)throw Error(`keyword "${w}" failed to compile`);return $.scopeValue("keyword",typeof G=="function"?{ref:G}:{ref:G,code:(0,O0.stringify)(G)})}function iK($,w,G=!1){return!w.length||w.some((W)=>W==="array"?Array.isArray($):W==="object"?$&&typeof $=="object"&&!Array.isArray($):typeof $==W||G&&typeof $>"u")}PZ.validSchemaType=iK;function mK({schema:$,opts:w,self:G,errSchemaPath:W},Y,Z){if(Array.isArray(Y.keyword)?!Y.keyword.includes(Z):Y.keyword!==Z)throw Error("ajv implementation error");let X=Y.dependencies;if(X===null||X===void 0?void 0:X.some((J)=>!Object.prototype.hasOwnProperty.call($,J)))throw Error(`parent schema must have dependencies of ${Z}: ${X.join(",")}`);if(Y.validateSchema){if(!Y.validateSchema($[Z])){let T=`keyword "${Z}" value is invalid at path "${W}": `+G.errorsText(Y.validateSchema.errors);if(w.validateSchema==="log")G.logger.error(T);else throw Error(T)}}}PZ.validateKeywordUsage=mK});var HZ=L((EZ)=>{Object.defineProperty(EZ,"__esModule",{value:!0});EZ.extendSubschemaMode=EZ.extendSubschemaData=EZ.getSubschema=void 0;var Y1=i(),qZ=c();function nK($,{keyword:w,schemaProp:G,schema:W,schemaPath:Y,errSchemaPath:Z,topSchemaRef:X}){if(w!==void 0&&W!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(w!==void 0){let J=$.schema[w];return G===void 0?{schema:J,schemaPath:Y1._`${$.schemaPath}${(0,Y1.getProperty)(w)}`,errSchemaPath:`${$.errSchemaPath}/${w}`}:{schema:J[G],schemaPath:Y1._`${$.schemaPath}${(0,Y1.getProperty)(w)}${(0,Y1.getProperty)(G)}`,errSchemaPath:`${$.errSchemaPath}/${w}/${(0,qZ.escapeFragment)(G)}`}}if(W!==void 0){if(Y===void 0||Z===void 0||X===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:W,schemaPath:Y,topSchemaRef:X,errSchemaPath:Z}}throw Error('either "keyword" or "schema" must be passed')}EZ.getSubschema=nK;function pK($,w,{dataProp:G,dataPropType:W,data:Y,dataTypes:Z,propertyName:X}){if(Y!==void 0&&G!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:J}=w;if(G!==void 0){let{errorPath:M,dataPathArr:f,opts:Q}=w,N=J.let("data",Y1._`${w.data}${(0,Y1.getProperty)(G)}`,!0);T(N),$.errorPath=Y1.str`${M}${(0,qZ.getErrorPath)(G,W,Q.jsPropertySyntax)}`,$.parentDataProperty=Y1._`${G}`,$.dataPathArr=[...f,$.parentDataProperty]}if(Y!==void 0){let M=Y instanceof Y1.Name?Y:J.let("data",Y,!0);if(T(M),X!==void 0)$.propertyName=X}if(Z)$.dataTypes=Z;function T(M){$.data=M,$.dataLevel=w.dataLevel+1,$.dataTypes=[],w.definedProperties=new Set,$.parentData=w.data,$.dataNames=[...w.dataNames,M]}}EZ.extendSubschemaData=pK;function tK($,{jtdDiscriminator:w,jtdMetadata:G,compositeRule:W,createErrors:Y,allErrors:Z}){if(W!==void 0)$.compositeRule=W;if(Y!==void 0)$.createErrors=Y;if(Z!==void 0)$.allErrors=Z;$.jtdDiscriminator=w,$.jtdMetadata=G}EZ.extendSubschemaMode=tK});var e5=L((nk,FZ)=>{FZ.exports=function $(w,G){if(w===G)return!0;if(w&&G&&typeof w=="object"&&typeof G=="object"){if(w.constructor!==G.constructor)return!1;var W,Y,Z;if(Array.isArray(w)){if(W=w.length,W!=G.length)return!1;for(Y=W;Y--!==0;)if(!$(w[Y],G[Y]))return!1;return!0}if(w.constructor===RegExp)return w.source===G.source&&w.flags===G.flags;if(w.valueOf!==Object.prototype.valueOf)return w.valueOf()===G.valueOf();if(w.toString!==Object.prototype.toString)return w.toString()===G.toString();if(Z=Object.keys(w),W=Z.length,W!==Object.keys(G).length)return!1;for(Y=W;Y--!==0;)if(!Object.prototype.hasOwnProperty.call(G,Z[Y]))return!1;for(Y=W;Y--!==0;){var X=Z[Y];if(!$(w[X],G[X]))return!1}return!0}return w!==w&&G!==G}});var LZ=L((pk,OZ)=>{var h1=OZ.exports=function($,w,G){if(typeof w=="function")G=w,w={};G=w.cb||G;var W=typeof G=="function"?G:G.pre||function(){},Y=G.post||function(){};H8(w,W,Y,$,"",$)};h1.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};h1.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};h1.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};h1.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function H8($,w,G,W,Y,Z,X,J,T,M){if(W&&typeof W=="object"&&!Array.isArray(W)){w(W,Y,Z,X,J,T,M);for(var f in W){var Q=W[f];if(Array.isArray(Q)){if(f in h1.arrayKeywords)for(var N=0;N<Q.length;N++)H8($,w,G,Q[N],Y+"/"+f+"/"+N,Z,Y,f,W,N)}else if(f in h1.propsKeywords){if(Q&&typeof Q=="object")for(var z in Q)H8($,w,G,Q[z],Y+"/"+f+"/"+aK(z),Z,Y,f,W,z)}else if(f in h1.keywords||$.allKeys&&!(f in h1.skipKeywords))H8($,w,G,Q,Y+"/"+f,Z,Y,f,W)}G(W,Y,Z,X,J,T,M)}}function aK($){return $.replace(/~/g,"~0").replace(/\//g,"~1")}});var ew=L((SZ)=>{Object.defineProperty(SZ,"__esModule",{value:!0});SZ.getSchemaRefs=SZ.resolveUrl=SZ.normalizeId=SZ._getFullPath=SZ.getFullPath=SZ.inlineRef=void 0;var oK=c(),eK=e5(),$P=LZ(),wP=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function GP($,w=!0){if(typeof $=="boolean")return!0;if(w===!0)return!$G($);if(!w)return!1;return DZ($)<=w}SZ.inlineRef=GP;var WP=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function $G($){for(let w in $){if(WP.has(w))return!0;let G=$[w];if(Array.isArray(G)&&G.some($G))return!0;if(typeof G=="object"&&$G(G))return!0}return!1}function DZ($){let w=0;for(let G in $){if(G==="$ref")return 1/0;if(w++,wP.has(G))continue;if(typeof $[G]=="object")(0,oK.eachItem)($[G],(W)=>w+=DZ(W));if(w===1/0)return 1/0}return w}function kZ($,w="",G){if(G!==!1)w=a$(w);let W=$.parse(w);return AZ($,W)}SZ.getFullPath=kZ;function AZ($,w){return $.serialize(w).split("#")[0]+"#"}SZ._getFullPath=AZ;var YP=/#\/?$/;function a$($){return $?$.replace(YP,""):""}SZ.normalizeId=a$;function ZP($,w,G){return G=a$(G),$.resolve(w,G)}SZ.resolveUrl=ZP;var XP=/^[a-z_][-a-z0-9._]*$/i;function JP($,w){if(typeof $=="boolean")return{};let{schemaId:G,uriResolver:W}=this.opts,Y=a$($[G]||w),Z={"":Y},X=kZ(W,Y,!1),J={},T=new Set;return $P($,{allKeys:!0},(Q,N,z,K)=>{if(K===void 0)return;let P=X+N,q=Z[K];if(typeof Q[G]=="string")q=V.call(this,Q[G]);E.call(this,Q.$anchor),E.call(this,Q.$dynamicAnchor),Z[N]=q;function V(O){let A=this.opts.uriResolver.resolve;if(O=a$(q?A(q,O):O),T.has(O))throw f(O);T.add(O);let R=this.refs[O];if(typeof R=="string")R=this.refs[R];if(typeof R=="object")M(Q,R.schema,O);else if(O!==a$(P))if(O[0]==="#")M(Q,J[O],O),J[O]=Q;else this.refs[O]=P;return O}function E(O){if(typeof O=="string"){if(!XP.test(O))throw Error(`invalid anchor "${O}"`);V.call(this,`#${O}`)}}}),J;function M(Q,N,z){if(N!==void 0&&!eK(Q,N))throw f(z)}function f(Q){return Error(`reference "${Q}" resolves to more than one schema`)}}SZ.getSchemaRefs=JP});var G4=L((cZ)=>{Object.defineProperty(cZ,"__esModule",{value:!0});cZ.getData=cZ.KeywordCxt=cZ.validateFunctionCode=void 0;var bZ=pY(),jZ=ow(),GG=n5(),F8=ow(),zP=TZ(),w4=VZ(),wG=HZ(),j=i(),x=B1(),KP=ew(),V1=c(),$4=aw();function PP($){if(gZ($)){if(vZ($),_Z($)){qP($);return}}xZ($,()=>(0,bZ.topBoolOrEmptySchema)($))}cZ.validateFunctionCode=PP;function xZ({gen:$,validateName:w,schema:G,schemaEnv:W,opts:Y},Z){if(Y.code.es5)$.func(w,j._`${x.default.data}, ${x.default.valCxt}`,W.$async,()=>{$.code(j._`"use strict"; ${CZ(G,Y)}`),VP($,Y),$.code(Z)});else $.func(w,j._`${x.default.data}, ${BP(Y)}`,W.$async,()=>$.code(CZ(G,Y)).code(Z))}function BP($){return j._`{${x.default.instancePath}="", ${x.default.parentData}, ${x.default.parentDataProperty}, ${x.default.rootData}=${x.default.data}${$.dynamicRef?j._`, ${x.default.dynamicAnchors}={}`:j.nil}}={}`}function VP($,w){$.if(x.default.valCxt,()=>{if($.var(x.default.instancePath,j._`${x.default.valCxt}.${x.default.instancePath}`),$.var(x.default.parentData,j._`${x.default.valCxt}.${x.default.parentData}`),$.var(x.default.parentDataProperty,j._`${x.default.valCxt}.${x.default.parentDataProperty}`),$.var(x.default.rootData,j._`${x.default.valCxt}.${x.default.rootData}`),w.dynamicRef)$.var(x.default.dynamicAnchors,j._`${x.default.valCxt}.${x.default.dynamicAnchors}`)},()=>{if($.var(x.default.instancePath,j._`""`),$.var(x.default.parentData,j._`undefined`),$.var(x.default.parentDataProperty,j._`undefined`),$.var(x.default.rootData,x.default.data),w.dynamicRef)$.var(x.default.dynamicAnchors,j._`{}`)})}function qP($){let{schema:w,opts:G,gen:W}=$;xZ($,()=>{if(G.$comment&&w.$comment)hZ($);if(OP($),W.let(x.default.vErrors,null),W.let(x.default.errors,0),G.unevaluated)EP($);uZ($),kP($)});return}function EP($){let{gen:w,validateName:G}=$;$.evaluated=w.const("evaluated",j._`${G}.evaluated`),w.if(j._`${$.evaluated}.dynamicProps`,()=>w.assign(j._`${$.evaluated}.props`,j._`undefined`)),w.if(j._`${$.evaluated}.dynamicItems`,()=>w.assign(j._`${$.evaluated}.items`,j._`undefined`))}function CZ($,w){let G=typeof $=="object"&&$[w.schemaId];return G&&(w.code.source||w.code.process)?j._`/*# sourceURL=${G} */`:j.nil}function UP($,w){if(gZ($)){if(vZ($),_Z($)){HP($,w);return}}(0,bZ.boolOrEmptySchema)($,w)}function _Z({schema:$,self:w}){if(typeof $=="boolean")return!$;for(let G in $)if(w.RULES.all[G])return!0;return!1}function gZ($){return typeof $.schema!="boolean"}function HP($,w){let{schema:G,gen:W,opts:Y}=$;if(Y.$comment&&G.$comment)hZ($);LP($),DP($);let Z=W.const("_errs",x.default.errors);uZ($,Z),W.var(w,j._`${Z} === ${x.default.errors}`)}function vZ($){(0,V1.checkUnknownRules)($),FP($)}function uZ($,w){if($.opts.jtd)return yZ($,[],!1,w);let G=(0,jZ.getSchemaTypes)($.schema),W=(0,jZ.coerceAndCheckDataType)($,G);yZ($,G,!W,w)}function FP($){let{schema:w,errSchemaPath:G,opts:W,self:Y}=$;if(w.$ref&&W.ignoreKeywordsWithRef&&(0,V1.schemaHasRulesButRef)(w,Y.RULES))Y.logger.warn(`$ref: keywords ignored in schema at path "${G}"`)}function OP($){let{schema:w,opts:G}=$;if(w.default!==void 0&&G.useDefaults&&G.strictSchema)(0,V1.checkStrictMode)($,"default is ignored in the schema root")}function LP($){let w=$.schema[$.opts.schemaId];if(w)$.baseId=(0,KP.resolveUrl)($.opts.uriResolver,$.baseId,w)}function DP($){if($.schema.$async&&!$.schemaEnv.$async)throw Error("async schema in sync schema")}function hZ({gen:$,schemaEnv:w,schema:G,errSchemaPath:W,opts:Y}){let Z=G.$comment;if(Y.$comment===!0)$.code(j._`${x.default.self}.logger.log(${Z})`);else if(typeof Y.$comment=="function"){let X=j.str`${W}/$comment`,J=$.scopeValue("root",{ref:w.root});$.code(j._`${x.default.self}.opts.$comment(${Z}, ${X}, ${J}.schema)`)}}function kP($){let{gen:w,schemaEnv:G,validateName:W,ValidationError:Y,opts:Z}=$;if(G.$async)w.if(j._`${x.default.errors} === 0`,()=>w.return(x.default.data),()=>w.throw(j._`new ${Y}(${x.default.vErrors})`));else{if(w.assign(j._`${W}.errors`,x.default.vErrors),Z.unevaluated)AP($);w.return(j._`${x.default.errors} === 0`)}}function AP({gen:$,evaluated:w,props:G,items:W}){if(G instanceof j.Name)$.assign(j._`${w}.props`,G);if(W instanceof j.Name)$.assign(j._`${w}.items`,W)}function yZ($,w,G,W){let{gen:Y,schema:Z,data:X,allErrors:J,opts:T,self:M}=$,{RULES:f}=M;if(Z.$ref&&(T.ignoreKeywordsWithRef||!(0,V1.schemaHasRulesButRef)(Z,f))){Y.block(()=>mZ($,"$ref",f.all.$ref.definition));return}if(!T.jtd)SP($,w);Y.block(()=>{for(let N of f.rules)Q(N);Q(f.post)});function Q(N){if(!(0,GG.shouldUseGroup)(Z,N))return;if(N.type){if(Y.if((0,F8.checkDataType)(N.type,X,T.strictNumbers)),IZ($,N),w.length===1&&w[0]===N.type&&G)Y.else(),(0,F8.reportTypeError)($);Y.endIf()}else IZ($,N);if(!J)Y.if(j._`${x.default.errors} === ${W||0}`)}}function IZ($,w){let{gen:G,schema:W,opts:{useDefaults:Y}}=$;if(Y)(0,zP.assignDefaults)($,w.type);G.block(()=>{for(let Z of w.rules)if((0,GG.shouldUseRule)(W,Z))mZ($,Z.keyword,Z.definition,w.type)})}function SP($,w){if($.schemaEnv.meta||!$.opts.strictTypes)return;if(RP($,w),!$.opts.allowUnionTypes)jP($,w);CP($,$.dataTypes)}function RP($,w){if(!w.length)return;if(!$.dataTypes.length){$.dataTypes=w;return}w.forEach((G)=>{if(!iZ($.dataTypes,G))WG($,`type "${G}" not allowed by context "${$.dataTypes.join(",")}"`)}),IP($,w)}function jP($,w){if(w.length>1&&!(w.length===2&&w.includes("null")))WG($,"use allowUnionTypes to allow union type keyword")}function CP($,w){let G=$.self.RULES.all;for(let W in G){let Y=G[W];if(typeof Y=="object"&&(0,GG.shouldUseRule)($.schema,Y)){let{type:Z}=Y.definition;if(Z.length&&!Z.some((X)=>yP(w,X)))WG($,`missing type "${Z.join(",")}" for keyword "${W}"`)}}}function yP($,w){return $.includes(w)||w==="number"&&$.includes("integer")}function iZ($,w){return $.includes(w)||w==="integer"&&$.includes("number")}function IP($,w){let G=[];for(let W of $.dataTypes)if(iZ(w,W))G.push(W);else if(w.includes("integer")&&W==="number")G.push("integer");$.dataTypes=G}function WG($,w){let G=$.schemaEnv.baseId+$.errSchemaPath;w+=` at "${G}" (strictTypes)`,(0,V1.checkStrictMode)($,w,$.opts.strictTypes)}class YG{constructor($,w,G){if((0,w4.validateKeywordUsage)($,w,G),this.gen=$.gen,this.allErrors=$.allErrors,this.keyword=G,this.data=$.data,this.schema=$.schema[G],this.$data=w.$data&&$.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,V1.schemaRefOrVal)($,this.schema,G,this.$data),this.schemaType=w.schemaType,this.parentSchema=$.schema,this.params={},this.it=$,this.def=w,this.$data)this.schemaCode=$.gen.const("vSchema",lZ(this.$data,$));else if(this.schemaCode=this.schemaValue,!(0,w4.validSchemaType)(this.schema,w.schemaType,w.allowUndefined))throw Error(`${G} value must be ${JSON.stringify(w.schemaType)}`);if("code"in w?w.trackErrors:w.errors!==!1)this.errsCount=$.gen.const("_errs",x.default.errors)}result($,w,G){this.failResult((0,j.not)($),w,G)}failResult($,w,G){if(this.gen.if($),G)G();else this.error();if(w){if(this.gen.else(),w(),this.allErrors)this.gen.endIf()}else if(this.allErrors)this.gen.endIf();else this.gen.else()}pass($,w){this.failResult((0,j.not)($),void 0,w)}fail($){if($===void 0){if(this.error(),!this.allErrors)this.gen.if(!1);return}if(this.gen.if($),this.error(),this.allErrors)this.gen.endIf();else this.gen.else()}fail$data($){if(!this.$data)return this.fail($);let{schemaCode:w}=this;this.fail(j._`${w} !== undefined && (${(0,j.or)(this.invalid$data(),$)})`)}error($,w,G){if(w){this.setParams(w),this._error($,G),this.setParams({});return}this._error($,G)}_error($,w){($?$4.reportExtraError:$4.reportError)(this,this.def.error,w)}$dataError(){(0,$4.reportError)(this,this.def.$dataError||$4.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,$4.resetErrorsCount)(this.gen,this.errsCount)}ok($){if(!this.allErrors)this.gen.if($)}setParams($,w){if(w)Object.assign(this.params,$);else this.params=$}block$data($,w,G=j.nil){this.gen.block(()=>{this.check$data($,G),w()})}check$data($=j.nil,w=j.nil){if(!this.$data)return;let{gen:G,schemaCode:W,schemaType:Y,def:Z}=this;if(G.if((0,j.or)(j._`${W} === undefined`,w)),$!==j.nil)G.assign($,!0);if(Y.length||Z.validateSchema){if(G.elseIf(this.invalid$data()),this.$dataError(),$!==j.nil)G.assign($,!1)}G.else()}invalid$data(){let{gen:$,schemaCode:w,schemaType:G,def:W,it:Y}=this;return(0,j.or)(Z(),X());function Z(){if(G.length){if(!(w instanceof j.Name))throw Error("ajv implementation error");let J=Array.isArray(G)?G:[G];return j._`${(0,F8.checkDataTypes)(J,w,Y.opts.strictNumbers,F8.DataType.Wrong)}`}return j.nil}function X(){if(W.validateSchema){let J=$.scopeValue("validate$data",{ref:W.validateSchema});return j._`!${J}(${w})`}return j.nil}}subschema($,w){let G=(0,wG.getSubschema)(this.it,$);(0,wG.extendSubschemaData)(G,this.it,$),(0,wG.extendSubschemaMode)(G,$);let W={...this.it,...G,items:void 0,props:void 0};return UP(W,w),W}mergeEvaluated($,w){let{it:G,gen:W}=this;if(!G.opts.unevaluated)return;if(G.props!==!0&&$.props!==void 0)G.props=V1.mergeEvaluated.props(W,$.props,G.props,w);if(G.items!==!0&&$.items!==void 0)G.items=V1.mergeEvaluated.items(W,$.items,G.items,w)}mergeValidEvaluated($,w){let{it:G,gen:W}=this;if(G.opts.unevaluated&&(G.props!==!0||G.items!==!0))return W.if(w,()=>this.mergeEvaluated($,j.Name)),!0}}cZ.KeywordCxt=YG;function mZ($,w,G,W){let Y=new YG($,G,w);if("code"in G)G.code(Y,W);else if(Y.$data&&G.validate)(0,w4.funcKeywordCode)(Y,G);else if("macro"in G)(0,w4.macroKeywordCode)(Y,G);else if(G.compile||G.validate)(0,w4.funcKeywordCode)(Y,G)}var bP=/^\/(?:[^~]|~0|~1)*$/,xP=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function lZ($,{dataLevel:w,dataNames:G,dataPathArr:W}){let Y,Z;if($==="")return x.default.rootData;if($[0]==="/"){if(!bP.test($))throw Error(`Invalid JSON-pointer: ${$}`);Y=$,Z=x.default.rootData}else{let M=xP.exec($);if(!M)throw Error(`Invalid JSON-pointer: ${$}`);let f=+M[1];if(Y=M[2],Y==="#"){if(f>=w)throw Error(T("property/index",f));return W[w-f]}if(f>w)throw Error(T("data",f));if(Z=G[w-f],!Y)return Z}let X=Z,J=Y.split("/");for(let M of J)if(M)Z=j._`${Z}${(0,j.getProperty)((0,V1.unescapeJsonPointer)(M))}`,X=j._`${X} && ${Z}`;return X;function T(M,f){return`Cannot access ${M} ${f} levels up, current level is ${w}`}}cZ.getData=lZ});var O8=L((pZ)=>{Object.defineProperty(pZ,"__esModule",{value:!0});class nZ extends Error{constructor($){super("validation failed");this.errors=$,this.ajv=this.validation=!0}}pZ.default=nZ});var W4=L((rZ)=>{Object.defineProperty(rZ,"__esModule",{value:!0});var ZG=ew();class tZ extends Error{constructor($,w,G,W){super(W||`can't resolve reference ${G} from id ${w}`);this.missingRef=(0,ZG.resolveUrl)($,w,G),this.missingSchema=(0,ZG.normalizeId)((0,ZG.getFullPath)($,this.missingRef))}}rZ.default=tZ});var D8=L((oZ)=>{Object.defineProperty(oZ,"__esModule",{value:!0});oZ.resolveSchema=oZ.getCompilingSchema=oZ.resolveRef=oZ.compileSchema=oZ.SchemaEnv=void 0;var t0=i(),hP=O8(),J$=B1(),r0=ew(),sZ=c(),iP=G4();class Y4{constructor($){var w;this.refs={},this.dynamicAnchors={};let G;if(typeof $.schema=="object")G=$.schema;this.schema=$.schema,this.schemaId=$.schemaId,this.root=$.root||this,this.baseId=(w=$.baseId)!==null&&w!==void 0?w:(0,r0.normalizeId)(G===null||G===void 0?void 0:G[$.schemaId||"$id"]),this.schemaPath=$.schemaPath,this.localRefs=$.localRefs,this.meta=$.meta,this.$async=G===null||G===void 0?void 0:G.$async,this.refs={}}}oZ.SchemaEnv=Y4;function JG($){let w=aZ.call(this,$);if(w)return w;let G=(0,r0.getFullPath)(this.opts.uriResolver,$.root.baseId),{es5:W,lines:Y}=this.opts.code,{ownProperties:Z}=this.opts,X=new t0.CodeGen(this.scope,{es5:W,lines:Y,ownProperties:Z}),J;if($.$async)J=X.scopeValue("Error",{ref:hP.default,code:t0._`require("ajv/dist/runtime/validation_error").default`});let T=X.scopeName("validate");$.validateName=T;let M={gen:X,allErrors:this.opts.allErrors,data:J$.default.data,parentData:J$.default.parentData,parentDataProperty:J$.default.parentDataProperty,dataNames:[J$.default.data],dataPathArr:[t0.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:X.scopeValue("schema",this.opts.code.source===!0?{ref:$.schema,code:(0,t0.stringify)($.schema)}:{ref:$.schema}),validateName:T,ValidationError:J,schema:$.schema,schemaEnv:$,rootId:G,baseId:$.baseId||G,schemaPath:t0.nil,errSchemaPath:$.schemaPath||(this.opts.jtd?"":"#"),errorPath:t0._`""`,opts:this.opts,self:this},f;try{this._compilations.add($),(0,iP.validateFunctionCode)(M),X.optimize(this.opts.code.optimize);let Q=X.toString();if(f=`${X.scopeRefs(J$.default.scope)}return ${Q}`,this.opts.code.process)f=this.opts.code.process(f,$);let z=Function(`${J$.default.self}`,`${J$.default.scope}`,f)(this,this.scope.get());if(this.scope.value(T,{ref:z}),z.errors=null,z.schema=$.schema,z.schemaEnv=$,$.$async)z.$async=!0;if(this.opts.code.source===!0)z.source={validateName:T,validateCode:Q,scopeValues:X._values};if(this.opts.unevaluated){let{props:K,items:P}=M;if(z.evaluated={props:K instanceof t0.Name?void 0:K,items:P instanceof t0.Name?void 0:P,dynamicProps:K instanceof t0.Name,dynamicItems:P instanceof t0.Name},z.source)z.source.evaluated=(0,t0.stringify)(z.evaluated)}return $.validate=z,$}catch(Q){if(delete $.validate,delete $.validateName,f)this.logger.error("Error compiling schema, function code:",f);throw Q}finally{this._compilations.delete($)}}oZ.compileSchema=JG;function mP($,w,G){var W;G=(0,r0.resolveUrl)(this.opts.uriResolver,w,G);let Y=$.refs[G];if(Y)return Y;let Z=dP.call(this,$,G);if(Z===void 0){let X=(W=$.localRefs)===null||W===void 0?void 0:W[G],{schemaId:J}=this.opts;if(X)Z=new Y4({schema:X,schemaId:J,root:$,baseId:w})}if(Z===void 0)return;return $.refs[G]=lP.call(this,Z)}oZ.resolveRef=mP;function lP($){if((0,r0.inlineRef)($.schema,this.opts.inlineRefs))return $.schema;return $.validate?$:JG.call(this,$)}function aZ($){for(let w of this._compilations)if(cP(w,$))return w}oZ.getCompilingSchema=aZ;function cP($,w){return $.schema===w.schema&&$.root===w.root&&$.baseId===w.baseId}function dP($,w){let G;while(typeof(G=this.refs[w])=="string")w=G;return G||this.schemas[w]||L8.call(this,$,w)}function L8($,w){let G=this.opts.uriResolver.parse(w),W=(0,r0._getFullPath)(this.opts.uriResolver,G),Y=(0,r0.getFullPath)(this.opts.uriResolver,$.baseId,void 0);if(Object.keys($.schema).length>0&&W===Y)return XG.call(this,G,$);let Z=(0,r0.normalizeId)(W),X=this.refs[Z]||this.schemas[Z];if(typeof X=="string"){let J=L8.call(this,$,X);if(typeof(J===null||J===void 0?void 0:J.schema)!=="object")return;return XG.call(this,G,J)}if(typeof(X===null||X===void 0?void 0:X.schema)!=="object")return;if(!X.validate)JG.call(this,X);if(Z===(0,r0.normalizeId)(w)){let{schema:J}=X,{schemaId:T}=this.opts,M=J[T];if(M)Y=(0,r0.resolveUrl)(this.opts.uriResolver,Y,M);return new Y4({schema:J,schemaId:T,root:$,baseId:Y})}return XG.call(this,G,X)}oZ.resolveSchema=L8;var nP=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function XG($,{baseId:w,schema:G,root:W}){var Y;if(((Y=$.fragment)===null||Y===void 0?void 0:Y[0])!=="/")return;for(let J of $.fragment.slice(1).split("/")){if(typeof G==="boolean")return;let T=G[(0,sZ.unescapeFragment)(J)];if(T===void 0)return;G=T;let M=typeof G==="object"&&G[this.opts.schemaId];if(!nP.has(J)&&M)w=(0,r0.resolveUrl)(this.opts.uriResolver,w,M)}let Z;if(typeof G!="boolean"&&G.$ref&&!(0,sZ.schemaHasRulesButRef)(G,this.RULES)){let J=(0,r0.resolveUrl)(this.opts.uriResolver,w,G.$ref);Z=L8.call(this,W,J)}let{schemaId:X}=this.opts;if(Z=Z||new Y4({schema:G,schemaId:X,root:W,baseId:w}),Z.schema!==Z.root.schema)return Z;return}});var $X=L((ek,aP)=>{aP.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var zG=L(($A,JX)=>{var oP=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),MG=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),T$=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),fG=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),GX=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),QG=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),eP=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),A0=Array(256);for(let w=0;w<256;w++)A0[w]="%"+"0123456789ABCDEF"[w>>4]+"0123456789ABCDEF"[w&15];function B0($){if($<2048)return A0[192|$>>6]+A0[128|$&63];if($<65536)return A0[224|$>>12]+A0[128|$>>6&63]+A0[128|$&63];return A0[240|$>>18]+A0[128|$>>12&63]+A0[128|$>>6&63]+A0[128|$&63]}function $B($){let w="",G=0,W=0;for(W=0;W<$.length;W++){if(G=$[W].charCodeAt(0),G===48)continue;if(!(G>=48&&G<=57||G>=65&&G<=70||G>=97&&G<=102))return"";w+=$[W];break}for(W+=1;W<$.length;W++){if(G=$[W].charCodeAt(0),!(G>=48&&G<=57||G>=65&&G<=70||G>=97&&G<=102))return"";w+=$[W]}return w}var wB=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),GB=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),WB=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),YB=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function ZB($){if($.length===0)return!1;for(let w=0;w<$.length;w++){if(WB($[w]))continue;if($[w]==="%"&&w+2<$.length&&T$($.slice(w+1,w+3))){w+=2;continue}return!1}return!0}function wX($){let w=-1,G=0,W=-1,Y=0;for(let J=0;J<$.length;J++)if($[J]==="0"){if(W===-1)W=J;if(Y++,Y>G)G=Y,w=W}else W=-1,Y=0;if(G<2)return $.join(":");let Z=$.slice(0,w).join(":"),X=$.slice(w+G).join(":");return Z+"::"+X}function XB($){let w=$.indexOf("::");if(w!==-1&&$.indexOf("::",w+1)!==-1)return;let G=w===-1?$.split(":"):$.slice(0,w).split(":"),W=w===-1?[]:$.slice(w+2).split(":");if(w!==-1){if(G.length===1&&G[0]==="")G.length=0;if(W.length===1&&W[0]==="")W.length=0}let Y=G.concat(W),Z=0;for(let J=0;J<Y.length;J++){let T=Y[J];if(T==="")return;if(T.indexOf(".")!==-1){if(J!==Y.length-1||w!==-1&&W.length===0||!MG(T))return;Z+=2;continue}if(!wB(T))return;Y[J]=parseInt(T,16).toString(16),Z++}if(w===-1){if(Z!==8)return;return wX(Y)}if(Z>=8)return;let X=Y.slice(0,G.length);for(let J=Z;J<8;J++)X.push("0");for(let J=G.length;J<Y.length;J++)X.push(Y[J]);return wX(X)}function TG($){let w=$[0]==="["&&$[$.length-1]==="]";if(($[0]==="["||$[$.length-1]==="]")&&!w)return{host:$,isIPV6:!1,error:!0};let W=w?$.slice(1,-1):$;if(w&&GB(W))return W=W.toLowerCase(),{host:`[${W}]`,escapedHost:W,isIPV6:!1,isIPVFuture:!0};if(JB(W,":")<2)return{host:$,isIPV6:!1,error:w};let Y="",Z=W.indexOf("%");if(Z!==-1){let J=W.slice(Z,Z+3).toLowerCase()==="%25"?3:1;if(Y=W.slice(Z+J),!ZB(Y))return{host:$,isIPV6:!1,error:!0};W=W.slice(0,Z)}let X=XB(W);if(X===void 0)return{host:$,isIPV6:!1,error:!0};return{host:X+(Y?"%"+Y:""),escapedHost:X+(Y?"%25"+Y:""),isIPV6:!0}}function JB($,w){let G=0;for(let W=0;W<$.length;W++)if($[W]===w)G++;return G}function TB($){let w=$,G=[],W=-1,Y=0;while(Y=w.length){if(Y===1)if(w===".")break;else if(w==="/"){G.push("/");break}else{G.push(w);break}else if(Y===2){if(w[0]==="."){if(w[1]===".")break;else if(w[1]==="/"){w=w.slice(2);continue}}else if(w[0]==="/"){if(w[1]==="."||w[1]==="/"){G.push("/");break}}}else if(Y===3){if(w==="/.."){if(G.length!==0)G.pop();G.push("/");break}}if(w[0]==="."){if(w[1]==="."){if(w[2]==="/"){w=w.slice(3);continue}}else if(w[1]==="/"){w=w.slice(2);continue}}else if(w[0]==="/"){if(w[1]==="."){if(w[2]==="/"){w=w.slice(2);continue}else if(w[2]==="."){if(w[3]==="/"){if(w=w.slice(3),G.length!==0)G.pop();continue}}}}if((W=w.indexOf("/",1))===-1){G.push(w);break}else G.push(w.slice(0,W)),w=w.slice(W)}return G.join("")}var MB={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},fB=/[@/?#:]/g,QB=/[@/?#]/g;function WX($,w){let G=w?QB:fB;return G.lastIndex=0,$.replace(G,(W)=>MB[W])}function YX($,w=!1){if($.indexOf("%")===-1)return $;let G="";for(let W=0;W<$.length;W++){if($[W]==="%"&&W+2<$.length){let Y=$.slice(W+1,W+3);if(T$(Y)){let Z=Y.toUpperCase(),X=String.fromCharCode(parseInt(Z,16));if(w&&fG(X))G+=X;else G+="%"+Z;W+=2;continue}}G+=$[W]}return G}function NB($){let w="";for(let G=0;G<$.length;G++){let W=$[G];if(W==="%"&&G+2<$.length){let Y=$.slice(G+1,G+3);if(T$(Y)){let Z=Y.toUpperCase(),X=String.fromCharCode(parseInt(Z,16));if(X!=="."&&fG(X))w+=X;else w+="%"+Z;G+=2;continue}}if(GX(W))w+=W;else{let Y=$.charCodeAt(G);if(Y<128)w+=XX(Y)?W:A0[Y];else if(Y<55296||Y>57343)w+=B0(Y);else if(Y<=56319&&G+1<$.length){let Z=$.charCodeAt(G+1);if(Z>=56320&&Z<=57343)w+=B0(65536+(Y-55296<<10)+(Z-56320)),G++;else w+=B0(65533)}else w+=B0(65533)}}return w}function zB($,w=!1){let G="",W=w&&$[0]!=="/";for(let Y=0;Y<$.length;Y++){let Z=$[Y];if(Z==="%"&&Y+2<$.length){let X=$.slice(Y+1,Y+3);if(T$(X)){G+="%"+X.toUpperCase(),Y+=2;continue}}if(Z==="/")W=!1;if(GX(Z)&&(Z!==":"||!W))G+=Z;else{let X=$.charCodeAt(Y);if(X<128)G+=A0[X];else if(X<55296||X>57343)G+=B0(X);else if(X<=56319&&Y+1<$.length){let J=$.charCodeAt(Y+1);if(J>=56320&&J<=57343)G+=B0(65536+(X-55296<<10)+(J-56320)),Y++;else G+=B0(65533)}else G+=B0(65533)}}return G}function NG($,w){let G="";for(let W=0;W<$.length;W++){let Y=$[W];if(Y==="%"&&W+2<$.length){let Z=$.slice(W+1,W+3);if(T$(Z)){G+="%"+Z.toUpperCase(),W+=2;continue}}if(w(Y))G+=Y;else{let Z=$.charCodeAt(W);if(Z<128)G+=A0[Z];else if(Z<55296||Z>57343)G+=B0(Z);else if(Z<=56319&&W+1<$.length){let X=$.charCodeAt(W+1);if(X>=56320&&X<=57343)G+=B0(65536+(Z-55296<<10)+(X-56320)),W++;else G+=B0(65533)}else G+=B0(65533)}}return G}function ZX($){return NG($,eP)}function KB($){return NG($,QG)}function PB($){return NG($,QG)}function XX($){return $>=48&&$<=57||$>=65&&$<=90||$>=97&&$<=122||$===42||$===43||$===45||$===46||$===47||$===64||$===95}function BB($){let w="";for(let G=0;G<$.length;G++){let W=$[G];if(W==="%"&&G+2<$.length){let Y=$.slice(G+1,G+3);if(T$(Y)){let Z=Y.toUpperCase(),X=String.fromCharCode(parseInt(Z,16));if(fG(X))w+=X;else w+="%"+Z;G+=2;continue}}if(QG(W))w+=W;else{let Y=$.charCodeAt(G);if(Y<128)w+=XX(Y)?W:A0[Y];else if(Y<55296||Y>57343)w+=B0(Y);else if(Y<=56319&&G+1<$.length){let Z=$.charCodeAt(G+1);if(Z>=56320&&Z<=57343)w+=B0(65536+(Y-55296<<10)+(Z-56320)),G++;else w+=B0(65533)}else w+=B0(65533)}}return w}function VB($){let w="";for(let G=0;G<$.length;G++){if($[G]==="%"&&G+2<$.length){let W=$.slice(G+1,G+3);if(T$(W)){w+="%"+W.toUpperCase(),G+=2;continue}}w+=escape($[G])}return w}function qB($){let w=[];if($.userinfo!==void 0)w.push(ZX($.userinfo)),w.push("@");if($.host!==void 0){let G=$.host;if(!MG(G)){let W=TG(G);if(W.isIPV6!==!0&&W.isIPVFuture!==!0)G=YX(G,!0),W=TG(G);if(W.isIPV6===!0||W.isIPVFuture===!0)G=`[${W.escapedHost}]`;else G=WX(G,!1)}w.push(G)}if(typeof $.port==="number"||typeof $.port==="string")w.push(":"),w.push(String($.port));return w.length?w.join(""):void 0}JX.exports={nonSimpleDomain:YB,recomposeAuthority:qB,reescapeHostDelimiters:WX,normalizePercentEncoding:YX,normalizePathEncoding:NB,serializePathEncoding:zB,normalizeQueryFragmentEncoding:BB,encodeUserinfo:ZX,encodeQuery:KB,encodeFragment:PB,escapePreservingEscapes:VB,removeDotSegments:TB,isIPv4:MG,isUUID:oP,normalizeIPv6:TG,stringArrayToHexStripped:$B}});var NX=L((wA,QX)=>{var{isUUID:EB}=zG(),UB=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,HB=["http","https","ws","wss","urn","urn:uuid"];function FB($){return HB.indexOf($)!==-1}function KG($){if($.secure===!0)return!0;else if($.secure===!1)return!1;else if($.scheme)return $.scheme.length===3&&($.scheme[0]==="w"||$.scheme[0]==="W")&&($.scheme[1]==="s"||$.scheme[1]==="S")&&($.scheme[2]==="s"||$.scheme[2]==="S");else return!1}function TX($){if(!$.host)$.error=$.error||"HTTP URIs must have a host.";return $}function MX($){let w=String($.scheme).toLowerCase()==="https";if($.port===(w?443:80)||$.port==="")$.port=void 0;if(!$.path)$.path="/";return $}function OB($){return $.secure=KG($),$.resourceName=($.path||"/")+($.query?"?"+$.query:""),$.path=void 0,$.query=void 0,$}function LB($){if($.port===(KG($)?443:80)||$.port==="")$.port=void 0;if(typeof $.secure==="boolean")$.scheme=$.secure?"wss":"ws",$.secure=void 0;if($.resourceName){let w=$.resourceName.indexOf("?"),G=w===-1?$.resourceName:$.resourceName.slice(0,w);$.path=G&&G!=="/"?G:void 0,$.query=w===-1?void 0:$.resourceName.slice(w+1),$.resourceName=void 0}return $.fragment=void 0,$}function DB($,w){if(!$.path)return $.error="URN can not be parsed",$;let G=$.path.match(UB);if(G&&G[0]===$.path){let W=w.scheme||$.scheme||"urn";$.nid=G[1].toLowerCase(),$.nss=G[2];let Y=`${W}:${w.nid||$.nid}`,Z=PG(Y);if($.path=void 0,Z)$=Z.parse($,w)}else $.error=$.error||"URN can not be parsed.";return $}function kB($,w){if($.nid===void 0)throw Error("URN without nid cannot be serialized");let G=w.scheme||$.scheme||"urn",W=$.nid.toLowerCase(),Y=`${G}:${w.nid||W}`,Z=PG(Y);if(Z)$=Z.serialize($,w);let X=$,J=$.nss;return X.path=`${W||w.nid}:${J}`,w.skipEscape=!0,X}function AB($,w){let G=$;if(G.uuid=G.nss,G.nss=void 0,!w.tolerant&&(!G.uuid||!EB(G.uuid)))G.error=G.error||"UUID is not valid.";return G}function SB($){let w=$;return w.nss=($.uuid||"").toLowerCase(),w}var fX={scheme:"http",domainHost:!0,parse:TX,serialize:MX},RB={scheme:"https",domainHost:fX.domainHost,parse:TX,serialize:MX},k8={scheme:"ws",domainHost:!0,parse:OB,serialize:LB},jB={scheme:"wss",domainHost:k8.domainHost,parse:k8.parse,serialize:k8.serialize},CB={scheme:"urn",parse:DB,serialize:kB,skipNormalize:!0},yB={scheme:"urn:uuid",parse:AB,serialize:SB,skipNormalize:!0},A8={http:fX,https:RB,ws:k8,wss:jB,urn:CB,"urn:uuid":yB};Object.setPrototypeOf(A8,null);function PG($){return $&&(A8[$]||A8[$.toLowerCase()])||void 0}QX.exports={wsIsSecure:KG,SCHEMES:A8,isValidSchemeName:FB,getSchemeHandler:PG}});var DX=L((GA,j8)=>{var{normalizeIPv6:VX,removeDotSegments:X4,recomposeAuthority:IB,normalizePercentEncoding:qX,normalizePathEncoding:bB,serializePathEncoding:zX,normalizeQueryFragmentEncoding:KX,encodeQuery:xB,encodeFragment:_B,reescapeHostDelimiters:gB,isIPv4:EX,nonSimpleDomain:vB}=zG(),{SCHEMES:UX,getSchemeHandler:BG}=NX(),HX=/^[A-Za-z][A-Za-z0-9+.-]*$/u;function PX($){let w=unescape(String($));if(!HX.test(w))throw TypeError("URI scheme is malformed.");return w}function uB($,w){if(typeof $==="string")$=pB($,w);else if(typeof $==="object")$=R8(M$($,w),w);return $}function hB($,w,G){let W=G?Object.assign({scheme:"null"},G):{scheme:"null"},{parsed:Y,malformedAuthorityOrPort:Z,malformedPercentEncoding:X,malformedSchemeSpecific:J,malformedHost:T,malformedScheme:M}=S8($,W),{parsed:f,malformedAuthorityOrPort:Q,malformedPercentEncoding:N,malformedSchemeSpecific:z,malformedHost:K,malformedScheme:P}=S8(w,W);if(Z||Q||X||N||J||z||T||K||M||P)throw Error(Y.error||f.error||"URI is malformed.");let q=FX(Y,f,W,!0),V=BG(G&&G.scheme||q.scheme),E=q.host,O=E!==void 0&&E!==""&&(EX(E)||VX(E).isIPV6);OX(q,G||{},V,O);let A=E&&E.indexOf("%")!==-1&&!/\P{ASCII}/u.test(E);if(q.error&&!A)throw Error(q.error);return W.skipEscape=!0,M$(q,W)}function FX($,w,G,W){let Y={};if(!W)$=R8(M$($,G),G),w=R8(M$(w,G),G);if(G=G||{},!G.tolerant&&w.scheme)Y.scheme=w.scheme,Y.userinfo=w.userinfo,Y.host=w.host,Y.port=w.port,Y.path=X4(w.path||""),Y.query=w.query;else{if(w.userinfo!==void 0||w.host!==void 0||w.port!==void 0)Y.userinfo=w.userinfo,Y.host=w.host,Y.port=w.port,Y.path=X4(w.path||""),Y.query=w.query;else{if(!w.path)if(Y.path=$.path,w.query!==void 0)Y.query=w.query;else Y.query=$.query;else{if(w.path[0]==="/")Y.path=X4(w.path);else{if(($.userinfo!==void 0||$.host!==void 0||$.port!==void 0)&&!$.path)Y.path="/"+w.path;else if(!$.path)Y.path=w.path;else Y.path=$.path.slice(0,$.path.lastIndexOf("/")+1)+w.path;Y.path=X4(Y.path)}Y.query=w.query}Y.userinfo=$.userinfo,Y.host=$.host,Y.port=$.port}Y.scheme=$.scheme}return Y.fragment=w.fragment,Y}function iB($,w,G){let W=BX($,G),Y=BX(w,G);return W!==void 0&&Y!==void 0&&W===Y}function M$($,w){let G={host:$.host,scheme:$.scheme,userinfo:$.userinfo,port:$.port,path:$.path,query:$.query,nid:$.nid,nss:$.nss,uuid:$.uuid,fragment:$.fragment,reference:$.reference,resourceName:$.resourceName,secure:$.secure,error:""},W=Object.assign({},w),Y=[];if(G.scheme)G.scheme=PX(G.scheme);let Z=BG(W.scheme||G.scheme);if(Z&&Z.serialize)Z.serialize(G,W);let X=G.userinfo!==void 0||G.host!==void 0||G.port!==void 0,J=!W.skipEscape&&G.scheme===void 0&&!X;if(G.path!==void 0)if(!W.skipEscape)G.path=zX(G.path,J);else G.path=qX(G.path);if(W.reference!=="suffix"&&G.scheme)G.scheme=PX(G.scheme),Y.push(G.scheme,":");let T=IB(G);if(T!==void 0){if(W.reference!=="suffix")Y.push("//");if(Y.push(T),G.path&&G.path[0]!=="/")Y.push("/")}if(G.path!==void 0){let M=G.path;if(!W.absolutePath&&(!Z||!Z.absolutePath))M=X4(M);if(J)M=zX(M,!0);if(T===void 0&&M[0]==="/"&&M[1]==="/")M="/%2F"+M.slice(2);Y.push(M)}if(G.query!==void 0)Y.push("?",xB(G.query));if(G.fragment!==void 0)Y.push("#",_B(G.fragment));return Y.join("")}var mB=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,lB=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,cB=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function dB($,w){if(w[2]!==void 0&&$.path&&$.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof $.port==="number"&&($.port<0||$.port>65535))return"URI port is malformed.";return}function Z4($){if($===void 0)return!1;let w=$.indexOf("%");while(w!==-1){if(w+2>=$.length||!/^[\da-f]{2}$/iu.test($.slice(w+1,w+3)))return!0;w=$.indexOf("%",w+3)}return!1}function nB($){let w=$[4];return Z4($[3])||w!==void 0&&!(w[0]==="["&&w[w.length-1]==="]")&&Z4(w)||Z4($[6])||Z4($[7])||Z4($[8])}function OX($,w,G,W){if(!w.unicodeSupport&&(!G||!G.unicodeSupport)&&$.host&&$.host[0]!=="["&&(w.domainHost||G&&G.domainHost)&&W===!1&&vB($.host))try{$.host=new URL("http://"+$.host).hostname}catch(Y){return $.error=$.error||"Host's domain name can not be converted to ASCII: "+Y,!0}return!1}function S8($,w){let G=Object.assign({},w),W={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},Y=!1,Z=!1,X=!1,J=!1,T=!1,M=!1,f=!1;if(G.reference==="suffix")if(G.scheme)$=G.scheme+":"+$;else $="//"+$;let Q=$.match(lB);if(Q!==null&&Q[1].indexOf("\\")!==-1)W.error="URI authority must not contain a literal backslash.",Y=!0;let N=$.match(cB);if(N!==null){let K=N[1],P=K.replace(/[\t\n\r]/g,"");if(P.length>=2){if(P.slice(0,2)!=="//")W.error=W.error||"URI authority must not contain a literal backslash.",Y=!0;else if(K.length!==P.length)W.error=W.error||"URI authority introducer must not contain whitespace.",Y=!0}}let z=$.match(mB);if(z){if(W.scheme=z[1],W.userinfo=z[3],W.host=z[4],W.port=parseInt(z[5],10),W.path=z[6]||"",W.query=z[7],W.fragment=z[8],W.scheme!==void 0){let q=unescape(W.scheme);if(HX.test(q))W.scheme=q.toLowerCase();else W.error=W.error||"URI scheme is malformed.",M=!0}if(Z=nB(z),Z)W.error=W.error||"URI contains malformed percent-encoding.";if(isNaN(W.port))W.port=z[5];let K=dB(W,z);if(K!==void 0)W.error=W.error||K,Y=!0;if(W.host)if(EX(W.host)===!1){let V=W.host[0]==="["&&W.host[W.host.length-1]==="]",E=VX(W.host);if(f=E.isIPV6||E.isIPVFuture===!0,T=V&&E.error===!0,W.host=f?E.host:E.host.toLowerCase(),T)W.error=W.error||"URI host is malformed.",Y=!0}else f=!0;if(W.scheme===void 0&&W.userinfo===void 0&&W.host===void 0&&W.port===void 0&&W.query===void 0&&!W.path)W.reference="same-document";else if(W.scheme===void 0)W.reference="relative";else if(W.fragment===void 0)W.reference="absolute";else W.reference="uri";if(G.reference&&G.reference!=="suffix"&&G.reference!==W.reference)W.error=W.error||"URI is not a "+G.reference+" reference.";let P=BG(G.scheme||W.scheme);if(J=OX(W,G,P,f),!P||P&&!P.skipNormalize){if($.indexOf("%")!==-1){if(W.host!==void 0&&!T){let q=f?W.host:qX(W.host,!0);W.host=gB(q,f)}}if(W.path)W.path=bB(W.path);if(W.query)W.query=KX(W.query);if(W.fragment)W.fragment=KX(W.fragment)}if(P&&P.parse){if(P.parse(W,G),P===UX.urn&&W.nid===void 0)X=!0}}else W.error=W.error||"URI can not be parsed.";return{parsed:W,malformedAuthorityOrPort:Y,malformedPercentEncoding:Z,malformedSchemeSpecific:X,malformedHost:J,malformedScheme:M}}function R8($,w){return S8($,w).parsed}function pB($,w){return LX($,w).normalized}function LX($,w){let{parsed:G,malformedAuthorityOrPort:W,malformedPercentEncoding:Y,malformedSchemeSpecific:Z,malformedHost:X,malformedScheme:J}=S8($,w);return{normalized:W||Y||Z||X||J?$:M$(G,w),malformedAuthorityOrPort:W,malformedPercentEncoding:Y,malformedSchemeSpecific:Z,malformedHost:X,malformedScheme:J}}function BX($,w){if(typeof $!=="string"&&typeof $!=="object")return;let G;try{G=typeof $==="string"?$:M$($,w)}catch{return}let{normalized:W,malformedAuthorityOrPort:Y,malformedPercentEncoding:Z,malformedSchemeSpecific:X,malformedHost:J,malformedScheme:T}=LX(G,w);return Y||Z||X||J||T?void 0:W}var VG={SCHEMES:UX,normalize:uB,resolve:hB,resolveComponent:FX,equal:iB,serialize:M$,parse:R8};j8.exports=VG;j8.exports.default=VG;j8.exports.fastUri=VG});var SX=L((AX)=>{Object.defineProperty(AX,"__esModule",{value:!0});var kX=DX();kX.code='require("ajv/dist/runtime/uri").default';AX.default=kX});var _X=L((q1)=>{Object.defineProperty(q1,"__esModule",{value:!0});q1.CodeGen=q1.Name=q1.nil=q1.stringify=q1.str=q1._=q1.KeywordCxt=void 0;var rB=G4();Object.defineProperty(q1,"KeywordCxt",{enumerable:!0,get:function(){return rB.KeywordCxt}});var o$=i();Object.defineProperty(q1,"_",{enumerable:!0,get:function(){return o$._}});Object.defineProperty(q1,"str",{enumerable:!0,get:function(){return o$.str}});Object.defineProperty(q1,"stringify",{enumerable:!0,get:function(){return o$.stringify}});Object.defineProperty(q1,"nil",{enumerable:!0,get:function(){return o$.nil}});Object.defineProperty(q1,"Name",{enumerable:!0,get:function(){return o$.Name}});Object.defineProperty(q1,"CodeGen",{enumerable:!0,get:function(){return o$.CodeGen}});var sB=O8(),IX=W4(),aB=d5(),J4=D8(),oB=i(),T4=ew(),C8=ow(),EG=c(),RX=$X(),eB=SX(),bX=($,w)=>new RegExp($,w);bX.code="new RegExp";var $V=["removeAdditional","useDefaults","coerceTypes"],wV=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),GV={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},WV={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},jX=200;function YV($){var w,G,W,Y,Z,X,J,T,M,f,Q,N,z,K,P,q,V,E,O,A,R,S,_,s,e;let v=$.strict,H0=(w=$.code)===null||w===void 0?void 0:w.optimize,x1=H0===!0||H0===void 0?1:H0||0,W1=(W=(G=$.code)===null||G===void 0?void 0:G.regExp)!==null&&W!==void 0?W:bX,lw=(Y=$.uriResolver)!==null&&Y!==void 0?Y:eB.default;return{strictSchema:(X=(Z=$.strictSchema)!==null&&Z!==void 0?Z:v)!==null&&X!==void 0?X:!0,strictNumbers:(T=(J=$.strictNumbers)!==null&&J!==void 0?J:v)!==null&&T!==void 0?T:!0,strictTypes:(f=(M=$.strictTypes)!==null&&M!==void 0?M:v)!==null&&f!==void 0?f:"log",strictTuples:(N=(Q=$.strictTuples)!==null&&Q!==void 0?Q:v)!==null&&N!==void 0?N:"log",strictRequired:(K=(z=$.strictRequired)!==null&&z!==void 0?z:v)!==null&&K!==void 0?K:!1,code:$.code?{...$.code,optimize:x1,regExp:W1}:{optimize:x1,regExp:W1},loopRequired:(P=$.loopRequired)!==null&&P!==void 0?P:jX,loopEnum:(q=$.loopEnum)!==null&&q!==void 0?q:jX,meta:(V=$.meta)!==null&&V!==void 0?V:!0,messages:(E=$.messages)!==null&&E!==void 0?E:!0,inlineRefs:(O=$.inlineRefs)!==null&&O!==void 0?O:!0,schemaId:(A=$.schemaId)!==null&&A!==void 0?A:"$id",addUsedSchema:(R=$.addUsedSchema)!==null&&R!==void 0?R:!0,validateSchema:(S=$.validateSchema)!==null&&S!==void 0?S:!0,validateFormats:(_=$.validateFormats)!==null&&_!==void 0?_:!0,unicodeRegExp:(s=$.unicodeRegExp)!==null&&s!==void 0?s:!0,int32range:(e=$.int32range)!==null&&e!==void 0?e:!0,uriResolver:lw}}class y8{constructor($={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,$=this.opts={...$,...YV($)};let{es5:w,lines:G}=this.opts.code;this.scope=new oB.ValueScope({scope:{},prefixes:wV,es5:w,lines:G}),this.logger=fV($.logger);let W=$.validateFormats;if($.validateFormats=!1,this.RULES=(0,aB.getRules)(),CX.call(this,GV,$,"NOT SUPPORTED"),CX.call(this,WV,$,"DEPRECATED","warn"),this._metaOpts=TV.call(this),$.formats)XV.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),$.keywords)JV.call(this,$.keywords);if(typeof $.meta=="object")this.addMetaSchema($.meta);ZV.call(this),$.validateFormats=W}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:$,meta:w,schemaId:G}=this.opts,W=RX;if(G==="id")W={...RX},W.id=W.$id,delete W.$id;if(w&&$)this.addMetaSchema(W,W[G],!1)}defaultMeta(){let{meta:$,schemaId:w}=this.opts;return this.opts.defaultMeta=typeof $=="object"?$[w]||$:void 0}validate($,w){let G;if(typeof $=="string"){if(G=this.getSchema($),!G)throw Error(`no schema with key or ref "${$}"`)}else G=this.compile($);let W=G(w);if(!("$async"in G))this.errors=G.errors;return W}compile($,w){let G=this._addSchema($,w);return G.validate||this._compileSchemaEnv(G)}compileAsync($,w){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema:G}=this.opts;return W.call(this,$,w);async function W(M,f){await Y.call(this,M.$schema);let Q=this._addSchema(M,f);return Q.validate||Z.call(this,Q)}async function Y(M){if(M&&!this.getSchema(M))await W.call(this,{$ref:M},!0)}async function Z(M){try{return this._compileSchemaEnv(M)}catch(f){if(!(f instanceof IX.default))throw f;return X.call(this,f),await J.call(this,f.missingSchema),Z.call(this,M)}}function X({missingSchema:M,missingRef:f}){if(this.refs[M])throw Error(`AnySchema ${M} is loaded but ${f} cannot be resolved`)}async function J(M){let f=await T.call(this,M);if(!this.refs[M])await Y.call(this,f.$schema);if(!this.refs[M])this.addSchema(f,M,w)}async function T(M){let f=this._loading[M];if(f)return f;try{return await(this._loading[M]=G(M))}finally{delete this._loading[M]}}}addSchema($,w,G,W=this.opts.validateSchema){if(Array.isArray($)){for(let Z of $)this.addSchema(Z,void 0,G,W);return this}let Y;if(typeof $==="object"){let{schemaId:Z}=this.opts;if(Y=$[Z],Y!==void 0&&typeof Y!="string")throw Error(`schema ${Z} must be string`)}return w=(0,T4.normalizeId)(w||Y),this._checkUnique(w),this.schemas[w]=this._addSchema($,G,w,W,!0),this}addMetaSchema($,w,G=this.opts.validateSchema){return this.addSchema($,w,!0,G),this}validateSchema($,w){if(typeof $=="boolean")return!0;let G;if(G=$.$schema,G!==void 0&&typeof G!="string")throw Error("$schema must be a string");if(G=G||this.opts.defaultMeta||this.defaultMeta(),!G)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let W=this.validate(G,$);if(!W&&w){let Y="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(Y);else throw Error(Y)}return W}getSchema($){let w;while(typeof(w=yX.call(this,$))=="string")$=w;if(w===void 0){let{schemaId:G}=this.opts,W=new J4.SchemaEnv({schema:{},schemaId:G});if(w=J4.resolveSchema.call(this,W,$),!w)return;this.refs[$]=w}return w.validate||this._compileSchemaEnv(w)}removeSchema($){if($ instanceof RegExp)return this._removeAllSchemas(this.schemas,$),this._removeAllSchemas(this.refs,$),this;switch(typeof $){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let w=yX.call(this,$);if(typeof w=="object")this._cache.delete(w.schema);return delete this.schemas[$],delete this.refs[$],this}case"object":{let w=$;this._cache.delete(w);let G=$[this.opts.schemaId];if(G)G=(0,T4.normalizeId)(G),delete this.schemas[G],delete this.refs[G];return this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary($){for(let w of $)this.addKeyword(w);return this}addKeyword($,w){let G;if(typeof $=="string"){if(G=$,typeof w=="object")this.logger.warn("these parameters are deprecated, see docs for addKeyword"),w.keyword=G}else if(typeof $=="object"&&w===void 0){if(w=$,G=w.keyword,Array.isArray(G)&&!G.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(NV.call(this,G,w),!w)return(0,EG.eachItem)(G,(Y)=>qG.call(this,Y)),this;KV.call(this,w);let W={...w,type:(0,C8.getJSONTypes)(w.type),schemaType:(0,C8.getJSONTypes)(w.schemaType)};return(0,EG.eachItem)(G,W.type.length===0?(Y)=>qG.call(this,Y,W):(Y)=>W.type.forEach((Z)=>qG.call(this,Y,W,Z))),this}getKeyword($){let w=this.RULES.all[$];return typeof w=="object"?w.definition:!!w}removeKeyword($){let{RULES:w}=this;delete w.keywords[$],delete w.all[$];for(let G of w.rules){let W=G.rules.findIndex((Y)=>Y.keyword===$);if(W>=0)G.rules.splice(W,1)}return this}addFormat($,w){if(typeof w=="string")w=new RegExp(w);return this.formats[$]=w,this}errorsText($=this.errors,{separator:w=", ",dataVar:G="data"}={}){if(!$||$.length===0)return"No errors";return $.map((W)=>`${G}${W.instancePath} ${W.message}`).reduce((W,Y)=>W+w+Y)}$dataMetaSchema($,w){let G=this.RULES.all;$=JSON.parse(JSON.stringify($));for(let W of w){let Y=W.split("/").slice(1),Z=$;for(let X of Y)Z=Z[X];for(let X in G){let J=G[X];if(typeof J!="object")continue;let{$data:T}=J.definition,M=Z[X];if(T&&M)Z[X]=xX(M)}}return $}_removeAllSchemas($,w){for(let G in $){let W=$[G];if(!w||w.test(G)){if(typeof W=="string")delete $[G];else if(W&&!W.meta)this._cache.delete(W.schema),delete $[G]}}}_addSchema($,w,G,W=this.opts.validateSchema,Y=this.opts.addUsedSchema){let Z,{schemaId:X}=this.opts;if(typeof $=="object")Z=$[X];else if(this.opts.jtd)throw Error("schema must be object");else if(typeof $!="boolean")throw Error("schema must be object or boolean");let J=this._cache.get($);if(J!==void 0)return J;G=(0,T4.normalizeId)(Z||G);let T=T4.getSchemaRefs.call(this,$,G);if(J=new J4.SchemaEnv({schema:$,schemaId:X,meta:w,baseId:G,localRefs:T}),this._cache.set(J.schema,J),Y&&!G.startsWith("#")){if(G)this._checkUnique(G);this.refs[G]=J}if(W)this.validateSchema($,!0);return J}_checkUnique($){if(this.schemas[$]||this.refs[$])throw Error(`schema with key or id "${$}" already exists`)}_compileSchemaEnv($){if($.meta)this._compileMetaSchema($);else J4.compileSchema.call(this,$);if(!$.validate)throw Error("ajv implementation error");return $.validate}_compileMetaSchema($){let w=this.opts;this.opts=this._metaOpts;try{J4.compileSchema.call(this,$)}finally{this.opts=w}}}y8.ValidationError=sB.default;y8.MissingRefError=IX.default;q1.default=y8;function CX($,w,G,W="error"){for(let Y in $){let Z=Y;if(Z in w)this.logger[W](`${G}: option ${Y}. ${$[Z]}`)}}function yX($){return $=(0,T4.normalizeId)($),this.schemas[$]||this.refs[$]}function ZV(){let $=this.opts.schemas;if(!$)return;if(Array.isArray($))this.addSchema($);else for(let w in $)this.addSchema($[w],w)}function XV(){for(let $ in this.opts.formats){let w=this.opts.formats[$];if(w)this.addFormat($,w)}}function JV($){if(Array.isArray($)){this.addVocabulary($);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let w in $){let G=$[w];if(!G.keyword)G.keyword=w;this.addKeyword(G)}}function TV(){let $={...this.opts};for(let w of $V)delete $[w];return $}var MV={log(){},warn(){},error(){}};function fV($){if($===!1)return MV;if($===void 0)return console;if($.log&&$.warn&&$.error)return $;throw Error("logger must implement log, warn and error methods")}var QV=/^[a-z_$][a-z0-9_$:-]*$/i;function NV($,w){let{RULES:G}=this;if((0,EG.eachItem)($,(W)=>{if(G.keywords[W])throw Error(`Keyword ${W} is already defined`);if(!QV.test(W))throw Error(`Keyword ${W} has invalid name`)}),!w)return;if(w.$data&&!(("code"in w)||("validate"in w)))throw Error('$data keyword must have "code" or "validate" function')}function qG($,w,G){var W;let Y=w===null||w===void 0?void 0:w.post;if(G&&Y)throw Error('keyword with "post" flag cannot have "type"');let{RULES:Z}=this,X=Y?Z.post:Z.rules.find(({type:T})=>T===G);if(!X)X={type:G,rules:[]},Z.rules.push(X);if(Z.keywords[$]=!0,!w)return;let J={keyword:$,definition:{...w,type:(0,C8.getJSONTypes)(w.type),schemaType:(0,C8.getJSONTypes)(w.schemaType)}};if(w.before)zV.call(this,X,J,w.before);else X.rules.push(J);Z.all[$]=J,(W=w.implements)===null||W===void 0||W.forEach((T)=>this.addKeyword(T))}function zV($,w,G){let W=$.rules.findIndex((Y)=>Y.keyword===G);if(W>=0)$.rules.splice(W,0,w);else $.rules.push(w),this.logger.warn(`rule ${G} is not defined`)}function KV($){let{metaSchema:w}=$;if(w===void 0)return;if($.$data&&this.opts.$data)w=xX(w);$.validateSchema=this.compile(w,!0)}var PV={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function xX($){return{anyOf:[$,PV]}}});var vX=L((gX)=>{Object.defineProperty(gX,"__esModule",{value:!0});var qV={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};gX.default=qV});var cX=L((mX)=>{Object.defineProperty(mX,"__esModule",{value:!0});mX.callRef=mX.getValidate=void 0;var UV=W4(),uX=i0(),S0=i(),e$=B1(),hX=D8(),I8=c(),HV={keyword:"$ref",schemaType:"string",code($){let{gen:w,schema:G,it:W}=$,{baseId:Y,schemaEnv:Z,validateName:X,opts:J,self:T}=W,{root:M}=Z;if((G==="#"||G==="#/")&&Y===M.baseId)return Q();let f=hX.resolveRef.call(T,M,Y,G);if(f===void 0)throw new UV.default(W.opts.uriResolver,Y,G);if(f instanceof hX.SchemaEnv)return N(f);return z(f);function Q(){if(Z===M)return b8($,X,Z,Z.$async);let K=w.scopeValue("root",{ref:M});return b8($,S0._`${K}.validate`,M,M.$async)}function N(K){let P=iX($,K);b8($,P,K,K.$async)}function z(K){let P=w.scopeValue("schema",J.code.source===!0?{ref:K,code:(0,S0.stringify)(K)}:{ref:K}),q=w.name("valid"),V=$.subschema({schema:K,dataTypes:[],schemaPath:S0.nil,topSchemaRef:P,errSchemaPath:G},q);$.mergeEvaluated(V),$.ok(q)}}};function iX($,w){let{gen:G}=$;return w.validate?G.scopeValue("validate",{ref:w.validate}):S0._`${G.scopeValue("wrapper",{ref:w})}.validate`}mX.getValidate=iX;function b8($,w,G,W){let{gen:Y,it:Z}=$,{allErrors:X,schemaEnv:J,opts:T}=Z,M=T.passContext?e$.default.this:S0.nil;if(W)f();else Q();function f(){if(!J.$async)throw Error("async schema referenced by sync schema");let K=Y.let("valid");Y.try(()=>{if(Y.code(S0._`await ${(0,uX.callValidateCode)($,w,M)}`),z(w),!X)Y.assign(K,!0)},(P)=>{if(Y.if(S0._`!(${P} instanceof ${Z.ValidationError})`,()=>Y.throw(P)),N(P),!X)Y.assign(K,!1)}),$.ok(K)}function Q(){$.result((0,uX.callValidateCode)($,w,M),()=>z(w),()=>N(w))}function N(K){let P=S0._`${K}.errors`;Y.assign(e$.default.vErrors,S0._`${e$.default.vErrors} === null ? ${P} : ${e$.default.vErrors}.concat(${P})`),Y.assign(e$.default.errors,S0._`${e$.default.vErrors}.length`)}function z(K){var P;if(!Z.opts.unevaluated)return;let q=(P=G===null||G===void 0?void 0:G.validate)===null||P===void 0?void 0:P.evaluated;if(Z.props!==!0)if(q&&!q.dynamicProps){if(q.props!==void 0)Z.props=I8.mergeEvaluated.props(Y,q.props,Z.props)}else{let V=Y.var("props",S0._`${K}.evaluated.props`);Z.props=I8.mergeEvaluated.props(Y,V,Z.props,S0.Name)}if(Z.items!==!0)if(q&&!q.dynamicItems){if(q.items!==void 0)Z.items=I8.mergeEvaluated.items(Y,q.items,Z.items)}else{let V=Y.var("items",S0._`${K}.evaluated.items`);Z.items=I8.mergeEvaluated.items(Y,V,Z.items,S0.Name)}}}mX.callRef=b8;mX.default=HV});var nX=L((dX)=>{Object.defineProperty(dX,"__esModule",{value:!0});var LV=vX(),DV=cX(),kV=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",LV.default,DV.default];dX.default=kV});var tX=L((pX)=>{Object.defineProperty(pX,"__esModule",{value:!0});var x8=i(),i1=x8.operators,_8={maximum:{okStr:"<=",ok:i1.LTE,fail:i1.GT},minimum:{okStr:">=",ok:i1.GTE,fail:i1.LT},exclusiveMaximum:{okStr:"<",ok:i1.LT,fail:i1.GTE},exclusiveMinimum:{okStr:">",ok:i1.GT,fail:i1.LTE}},SV={message:({keyword:$,schemaCode:w})=>x8.str`must be ${_8[$].okStr} ${w}`,params:({keyword:$,schemaCode:w})=>x8._`{comparison: ${_8[$].okStr}, limit: ${w}}`},RV={keyword:Object.keys(_8),type:"number",schemaType:"number",$data:!0,error:SV,code($){let{keyword:w,data:G,schemaCode:W}=$;$.fail$data(x8._`${G} ${_8[w].fail} ${W} || isNaN(${G})`)}};pX.default=RV});var sX=L((rX)=>{Object.defineProperty(rX,"__esModule",{value:!0});var M4=i(),CV={message:({schemaCode:$})=>M4.str`must be multiple of ${$}`,params:({schemaCode:$})=>M4._`{multipleOf: ${$}}`},yV={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:CV,code($){let{gen:w,data:G,schemaCode:W,it:Y}=$,Z=Y.opts.multipleOfPrecision,X=w.let("res"),J=Z?M4._`Math.abs(Math.round(${X}) - ${X}) > 1e-${Z}`:M4._`${X} !== parseInt(${X})`;$.fail$data(M4._`(${W} === 0 || (${X} = ${G}/${W}, ${J}))`)}};rX.default=yV});var eX=L((oX)=>{Object.defineProperty(oX,"__esModule",{value:!0});function aX($){let w=$.length,G=0,W=0,Y;while(W<w)if(G++,Y=$.charCodeAt(W++),Y>=55296&&Y<=56319&&W<w){if(Y=$.charCodeAt(W),(Y&64512)===56320)W++}return G}oX.default=aX;aX.code='require("ajv/dist/runtime/ucs2length").default'});var w7=L(($7)=>{Object.defineProperty($7,"__esModule",{value:!0});var f$=i(),xV=c(),_V=eX(),gV={message({keyword:$,schemaCode:w}){let G=$==="maxLength"?"more":"fewer";return f$.str`must NOT have ${G} than ${w} characters`},params:({schemaCode:$})=>f$._`{limit: ${$}}`},vV={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:gV,code($){let{keyword:w,data:G,schemaCode:W,it:Y}=$,Z=w==="maxLength"?f$.operators.GT:f$.operators.LT,X=Y.opts.unicode===!1?f$._`${G}.length`:f$._`${(0,xV.useFunc)($.gen,_V.default)}(${G})`;$.fail$data(f$._`${X} ${Z} ${W}`)}};$7.default=vV});var W7=L((G7)=>{Object.defineProperty(G7,"__esModule",{value:!0});var hV=i0(),iV=c(),$w=i(),mV={message:({schemaCode:$})=>$w.str`must match pattern "${$}"`,params:({schemaCode:$})=>$w._`{pattern: ${$}}`},lV={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:mV,code($){let{gen:w,data:G,$data:W,schema:Y,schemaCode:Z,it:X}=$,J=X.opts.unicodeRegExp?"u":"";if(W){let{regExp:T}=X.opts.code,M=T.code==="new RegExp"?$w._`new RegExp`:(0,iV.useFunc)(w,T),f=w.let("valid");w.try(()=>w.assign(f,$w._`${M}(${Z}, ${J}).test(${G})`),()=>w.assign(f,!1)),$.fail$data($w._`!${f}`)}else{let T=(0,hV.usePattern)($,Y);$.fail$data($w._`!${T}.test(${G})`)}}};G7.default=lV});var Z7=L((Y7)=>{Object.defineProperty(Y7,"__esModule",{value:!0});var f4=i(),dV={message({keyword:$,schemaCode:w}){let G=$==="maxProperties"?"more":"fewer";return f4.str`must NOT have ${G} than ${w} properties`},params:({schemaCode:$})=>f4._`{limit: ${$}}`},nV={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:dV,code($){let{keyword:w,data:G,schemaCode:W}=$,Y=w==="maxProperties"?f4.operators.GT:f4.operators.LT;$.fail$data(f4._`Object.keys(${G}).length ${Y} ${W}`)}};Y7.default=nV});var J7=L((X7)=>{Object.defineProperty(X7,"__esModule",{value:!0});var Q4=i0(),N4=i(),tV=c(),rV={message:({params:{missingProperty:$}})=>N4.str`must have required property '${$}'`,params:({params:{missingProperty:$}})=>N4._`{missingProperty: ${$}}`},sV={keyword:"required",type:"object",schemaType:"array",$data:!0,error:rV,code($){let{gen:w,schema:G,schemaCode:W,data:Y,$data:Z,it:X}=$,{opts:J}=X;if(!Z&&G.length===0)return;let T=G.length>=J.loopRequired;if(X.allErrors)M();else f();if(J.strictRequired){let z=$.parentSchema.properties,{definedProperties:K}=$.it;for(let P of G)if((z===null||z===void 0?void 0:z[P])===void 0&&!K.has(P)){let q=X.schemaEnv.baseId+X.errSchemaPath,V=`required property "${P}" is not defined at "${q}" (strictRequired)`;(0,tV.checkStrictMode)(X,V,X.opts.strictRequired)}}function M(){if(T||Z)$.block$data(N4.nil,Q);else for(let z of G)(0,Q4.checkReportMissingProp)($,z)}function f(){let z=w.let("missing");if(T||Z){let K=w.let("valid",!0);$.block$data(K,()=>N(z,K)),$.ok(K)}else w.if((0,Q4.checkMissingProp)($,G,z)),(0,Q4.reportMissingProp)($,z),w.else()}function Q(){w.forOf("prop",W,(z)=>{$.setParams({missingProperty:z}),w.if((0,Q4.noPropertyInData)(w,Y,z,J.ownProperties),()=>$.error())})}function N(z,K){$.setParams({missingProperty:z}),w.forOf(z,W,()=>{w.assign(K,(0,Q4.propertyInData)(w,Y,z,J.ownProperties)),w.if((0,N4.not)(K),()=>{$.error(),w.break()})},N4.nil)}}};X7.default=sV});var M7=L((T7)=>{Object.defineProperty(T7,"__esModule",{value:!0});var z4=i(),oV={message({keyword:$,schemaCode:w}){let G=$==="maxItems"?"more":"fewer";return z4.str`must NOT have ${G} than ${w} items`},params:({schemaCode:$})=>z4._`{limit: ${$}}`},eV={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:oV,code($){let{keyword:w,data:G,schemaCode:W}=$,Y=w==="maxItems"?z4.operators.GT:z4.operators.LT;$.fail$data(z4._`${G}.length ${Y} ${W}`)}};T7.default=eV});var g8=L((Q7)=>{Object.defineProperty(Q7,"__esModule",{value:!0});var f7=e5();f7.code='require("ajv/dist/runtime/equal").default';Q7.default=f7});var z7=L((N7)=>{Object.defineProperty(N7,"__esModule",{value:!0});var UG=ow(),z0=i(),Gq=c(),Wq=g8(),Yq={message:({params:{i:$,j:w}})=>z0.str`must NOT have duplicate items (items ## ${w} and ${$} are identical)`,params:({params:{i:$,j:w}})=>z0._`{i: ${$}, j: ${w}}`},Zq={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:Yq,code($){let{gen:w,data:G,$data:W,schema:Y,parentSchema:Z,schemaCode:X,it:J}=$;if(!W&&!Y)return;let T=w.let("valid"),M=Z.items?(0,UG.getSchemaTypes)(Z.items):[];$.block$data(T,f,z0._`${X} === false`),$.ok(T);function f(){let K=w.let("i",z0._`${G}.length`),P=w.let("j");$.setParams({i:K,j:P}),w.assign(T,!0),w.if(z0._`${K} > 1`,()=>(Q()?N:z)(K,P))}function Q(){return M.length>0&&!M.some((K)=>K==="object"||K==="array")}function N(K,P){let q=w.name("item"),V=(0,UG.checkDataTypes)(M,q,J.opts.strictNumbers,UG.DataType.Wrong),E=w.const("indices",z0._`{}`);w.for(z0._`;${K}--;`,()=>{if(w.let(q,z0._`${G}[${K}]`),w.if(V,z0._`continue`),M.length>1)w.if(z0._`typeof ${q} == "string"`,z0._`${q} += "_"`);w.if(z0._`typeof ${E}[${q}] == "number"`,()=>{w.assign(P,z0._`${E}[${q}]`),$.error(),w.assign(T,!1).break()}).code(z0._`${E}[${q}] = ${K}`)})}function z(K,P){let q=(0,Gq.useFunc)(w,Wq.default),V=w.name("outer");w.label(V).for(z0._`;${K}--;`,()=>w.for(z0._`${P} = ${K}; ${P}--;`,()=>w.if(z0._`${q}(${G}[${K}], ${G}[${P}])`,()=>{$.error(),w.assign(T,!1).break(V)})))}}};N7.default=Zq});var P7=L((K7)=>{Object.defineProperty(K7,"__esModule",{value:!0});var HG=i(),Jq=c(),Tq=g8(),Mq={message:"must be equal to constant",params:({schemaCode:$})=>HG._`{allowedValue: ${$}}`},fq={keyword:"const",$data:!0,error:Mq,code($){let{gen:w,data:G,$data:W,schemaCode:Y,schema:Z}=$;if(W||Z&&typeof Z=="object")$.fail$data(HG._`!${(0,Jq.useFunc)(w,Tq.default)}(${G}, ${Y})`);else $.fail(HG._`${Z} !== ${G}`)}};K7.default=fq});var V7=L((B7)=>{Object.defineProperty(B7,"__esModule",{value:!0});var K4=i(),Nq=c(),zq=g8(),Kq={message:"must be equal to one of the allowed values",params:({schemaCode:$})=>K4._`{allowedValues: ${$}}`},Pq={keyword:"enum",schemaType:"array",$data:!0,error:Kq,code($){let{gen:w,data:G,$data:W,schema:Y,schemaCode:Z,it:X}=$;if(!W&&Y.length===0)throw Error("enum must have non-empty array");let J=Y.length>=X.opts.loopEnum,T,M=()=>T!==null&&T!==void 0?T:T=(0,Nq.useFunc)(w,zq.default),f;if(J||W)f=w.let("valid"),$.block$data(f,Q);else{if(!Array.isArray(Y))throw Error("ajv implementation error");let z=w.const("vSchema",Z);f=(0,K4.or)(...Y.map((K,P)=>N(z,P)))}$.pass(f);function Q(){w.assign(f,!1),w.forOf("v",Z,(z)=>w.if(K4._`${M()}(${G}, ${z})`,()=>w.assign(f,!0).break()))}function N(z,K){let P=Y[K];return typeof P==="object"&&P!==null?K4._`${M()}(${G}, ${z}[${K}])`:K4._`${G} === ${P}`}}};B7.default=Pq});var E7=L((q7)=>{Object.defineProperty(q7,"__esModule",{value:!0});var Vq=tX(),qq=sX(),Eq=w7(),Uq=W7(),Hq=Z7(),Fq=J7(),Oq=M7(),Lq=z7(),Dq=P7(),kq=V7(),Aq=[Vq.default,qq.default,Eq.default,Uq.default,Hq.default,Fq.default,Oq.default,Lq.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Dq.default,kq.default];q7.default=Aq});var OG=L((H7)=>{Object.defineProperty(H7,"__esModule",{value:!0});H7.validateAdditionalItems=void 0;var Q$=i(),FG=c(),Rq={message:({params:{len:$}})=>Q$.str`must NOT have more than ${$} items`,params:({params:{len:$}})=>Q$._`{limit: ${$}}`},jq={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Rq,code($){let{parentSchema:w,it:G}=$,{items:W}=w;if(!Array.isArray(W)){(0,FG.checkStrictMode)(G,'"additionalItems" is ignored when "items" is not an array of schemas');return}U7($,W)}};function U7($,w){let{gen:G,schema:W,data:Y,keyword:Z,it:X}=$;X.items=!0;let J=G.const("len",Q$._`${Y}.length`);if(W===!1)$.setParams({len:w.length}),$.pass(Q$._`${J} <= ${w.length}`);else if(typeof W=="object"&&!(0,FG.alwaysValidSchema)(X,W)){let M=G.var("valid",Q$._`${J} <= ${w.length}`);G.if((0,Q$.not)(M),()=>T(M)),$.ok(M)}function T(M){G.forRange("i",w.length,J,(f)=>{if($.subschema({keyword:Z,dataProp:f,dataPropType:FG.Type.Num},M),!X.allErrors)G.if((0,Q$.not)(M),()=>G.break())})}}H7.validateAdditionalItems=U7;H7.default=jq});var LG=L((D7)=>{Object.defineProperty(D7,"__esModule",{value:!0});D7.validateTuple=void 0;var O7=i(),v8=c(),yq=i0(),Iq={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code($){let{schema:w,it:G}=$;if(Array.isArray(w))return L7($,"additionalItems",w);if(G.items=!0,(0,v8.alwaysValidSchema)(G,w))return;$.ok((0,yq.validateArray)($))}};function L7($,w,G=$.schema){let{gen:W,parentSchema:Y,data:Z,keyword:X,it:J}=$;if(f(Y),J.opts.unevaluated&&G.length&&J.items!==!0)J.items=v8.mergeEvaluated.items(W,G.length,J.items);let T=W.name("valid"),M=W.const("len",O7._`${Z}.length`);G.forEach((Q,N)=>{if((0,v8.alwaysValidSchema)(J,Q))return;W.if(O7._`${M} > ${N}`,()=>$.subschema({keyword:X,schemaProp:N,dataProp:N},T)),$.ok(T)});function f(Q){let{opts:N,errSchemaPath:z}=J,K=G.length,P=K===Q.minItems&&(K===Q.maxItems||Q[w]===!1);if(N.strictTuples&&!P){let q=`"${X}" is ${K}-tuple, but minItems or maxItems/${w} are not specified or different at path "${z}"`;(0,v8.checkStrictMode)(J,q,N.strictTuples)}}}D7.validateTuple=L7;D7.default=Iq});var S7=L((A7)=>{Object.defineProperty(A7,"__esModule",{value:!0});var xq=LG(),_q={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:($)=>(0,xq.validateTuple)($,"items")};A7.default=_q});var C7=L((j7)=>{Object.defineProperty(j7,"__esModule",{value:!0});var R7=i(),vq=c(),uq=i0(),hq=OG(),iq={message:({params:{len:$}})=>R7.str`must NOT have more than ${$} items`,params:({params:{len:$}})=>R7._`{limit: ${$}}`},mq={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:iq,code($){let{schema:w,parentSchema:G,it:W}=$,{prefixItems:Y}=G;if(W.items=!0,(0,vq.alwaysValidSchema)(W,w))return;if(Y)(0,hq.validateAdditionalItems)($,Y);else $.ok((0,uq.validateArray)($))}};j7.default=mq});var I7=L((y7)=>{Object.defineProperty(y7,"__esModule",{value:!0});var m0=i(),u8=c(),cq={message:({params:{min:$,max:w}})=>w===void 0?m0.str`must contain at least ${$} valid item(s)`:m0.str`must contain at least ${$} and no more than ${w} valid item(s)`,params:({params:{min:$,max:w}})=>w===void 0?m0._`{minContains: ${$}}`:m0._`{minContains: ${$}, maxContains: ${w}}`},dq={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:cq,code($){let{gen:w,schema:G,parentSchema:W,data:Y,it:Z}=$,X,J,{minContains:T,maxContains:M}=W;if(Z.opts.next)X=T===void 0?1:T,J=M;else X=1;let f=w.const("len",m0._`${Y}.length`);if($.setParams({min:X,max:J}),J===void 0&&X===0){(0,u8.checkStrictMode)(Z,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(J!==void 0&&X>J){(0,u8.checkStrictMode)(Z,'"minContains" > "maxContains" is always invalid'),$.fail();return}if((0,u8.alwaysValidSchema)(Z,G)){let P=m0._`${f} >= ${X}`;if(J!==void 0)P=m0._`${P} && ${f} <= ${J}`;$.pass(P);return}Z.items=!0;let Q=w.name("valid");if(J===void 0&&X===1)z(Q,()=>w.if(Q,()=>w.break()));else if(X===0){if(w.let(Q,!0),J!==void 0)w.if(m0._`${Y}.length > 0`,N)}else w.let(Q,!1),N();$.result(Q,()=>$.reset());function N(){let P=w.name("_valid"),q=w.let("count",0);z(P,()=>w.if(P,()=>K(q)))}function z(P,q){w.forRange("i",0,f,(V)=>{$.subschema({keyword:"contains",dataProp:V,dataPropType:u8.Type.Num,compositeRule:!0},P),q()})}function K(P){if(w.code(m0._`${P}++`),J===void 0)w.if(m0._`${P} >= ${X}`,()=>w.assign(Q,!0).break());else if(w.if(m0._`${P} > ${J}`,()=>w.assign(Q,!1).break()),X===1)w.assign(Q,!0);else w.if(m0._`${P} >= ${X}`,()=>w.assign(Q,!0))}}};y7.default=dq});var u7=L((_7)=>{Object.defineProperty(_7,"__esModule",{value:!0});_7.validateSchemaDeps=_7.validatePropertyDeps=_7.error=void 0;var DG=i(),pq=c(),P4=i0();_7.error={message:({params:{property:$,depsCount:w,deps:G}})=>{let W=w===1?"property":"properties";return DG.str`must have ${W} ${G} when property ${$} is present`},params:({params:{property:$,depsCount:w,deps:G,missingProperty:W}})=>DG._`{property: ${$},
33
- missingProperty: ${W},
25
+ `),this.outputHelp({error:!0});let G=w||{},Z=G.exitCode||1,X=G.code||"commander.error";this._exit(Z,X,$)}_parseOptionsEnv(){this.options.forEach(($)=>{if($.envVar&&$.envVar in a.env){let w=$.attributeName();if(this.getOptionValue(w)===void 0||["default","config","env"].includes(this.getOptionValueSource(w)))if($.required||$.optional)this.emit(`optionEnv:${$.name()}`,a.env[$.envVar]);else this.emit(`optionEnv:${$.name()}`)}})}_parseOptionsImplied(){let $=new SK(this.options),w=(G)=>{return this.getOptionValue(G)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(G))};this.options.filter((G)=>G.implied!==void 0&&w(G.attributeName())&&$.valueFromOption(this.getOptionValue(G.attributeName()),G)).forEach((G)=>{Object.keys(G.implied).filter((Z)=>!w(Z)).forEach((Z)=>{this.setOptionValueWithSource(Z,G.implied[Z],"implied")})})}missingArgument($){let w=`error: missing required argument '${$}'`;this.error(w,{code:"commander.missingArgument"})}optionMissingArgument($){let w=`error: option '${$.flags}' argument missing`;this.error(w,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue($){let w=`error: required option '${$.flags}' not specified`;this.error(w,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption($,w){let G=(Y)=>{let J=Y.attributeName(),W=this.getOptionValue(J),T=this.options.find((z)=>z.negate&&J===z.attributeName()),Q=this.options.find((z)=>!z.negate&&J===z.attributeName());if(T&&(T.presetArg===void 0&&W===!1||T.presetArg!==void 0&&W===T.presetArg))return T;return Q||Y},Z=(Y)=>{let J=G(Y),W=J.attributeName();if(this.getOptionValueSource(W)==="env")return`environment variable '${J.envVar}'`;return`option '${J.flags}'`},X=`error: ${Z($)} cannot be used with ${Z(w)}`;this.error(X,{code:"commander.conflictingOption"})}unknownOption($){if(this._allowUnknownOption)return;let w="";if($.startsWith("--")&&this._showSuggestionAfterError){let Z=[],X=this;do{let Y=X.createHelp().visibleOptions(X).filter((J)=>J.long).map((J)=>J.long);Z=Z.concat(Y),X=X.parent}while(X&&!X._enablePositionalOptions);w=NJ($,Z)}let G=`error: unknown option '${$}'${w}`;this.error(G,{code:"commander.unknownOption"})}_excessArguments($){if(this._allowExcessArguments)return;let w=this.registeredArguments.length,G=w===1?"":"s",X=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${w} argument${G} but got ${$.length}.`;this.error(X,{code:"commander.excessArguments"})}unknownCommand(){let $=this.args[0],w="";if(this._showSuggestionAfterError){let Z=[];this.createHelp().visibleCommands(this).forEach((X)=>{if(Z.push(X.name()),X.alias())Z.push(X.alias())}),w=NJ($,Z)}let G=`error: unknown command '${$}'${w}`;this.error(G,{code:"commander.unknownCommand"})}version($,w,G){if($===void 0)return this._version;this._version=$,w=w||"-V, --version",G=G||"output the version number";let Z=this.createOption(w,G);return this._versionOptionName=Z.attributeName(),this._registerOption(Z),this.on("option:"+Z.name(),()=>{this._outputConfiguration.writeOut(`${$}
26
+ `),this._exit(0,"commander.version",$)}),this}description($,w){if($===void 0&&w===void 0)return this._description;if(this._description=$,w)this._argsDescription=w;return this}summary($){if($===void 0)return this._summary;return this._summary=$,this}alias($){if($===void 0)return this._aliases[0];let w=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)w=this.commands[this.commands.length-1];if($===w._name)throw Error("Command alias can't be the same as its name");let G=this.parent?._findCommand($);if(G){let Z=[G.name()].concat(G.aliases()).join("|");throw Error(`cannot add alias '${$}' to command '${this.name()}' as already have command '${Z}'`)}return w._aliases.push($),this}aliases($){if($===void 0)return this._aliases;return $.forEach((w)=>this.alias(w)),this}usage($){if($===void 0){if(this._usage)return this._usage;let w=this.registeredArguments.map((G)=>{return EK(G)});return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?w:[]).join(" ")}return this._usage=$,this}name($){if($===void 0)return this._name;return this._name=$,this}helpGroup($){if($===void 0)return this._helpGroupHeading??"";return this._helpGroupHeading=$,this}commandsGroup($){if($===void 0)return this._defaultCommandGroup??"";return this._defaultCommandGroup=$,this}optionsGroup($){if($===void 0)return this._defaultOptionGroup??"";return this._defaultOptionGroup=$,this}_initOptionGroup($){if(this._defaultOptionGroup&&!$.helpGroupHeading)$.helpGroup(this._defaultOptionGroup)}_initCommandGroup($){if(this._defaultCommandGroup&&!$.helpGroup())$.helpGroup(this._defaultCommandGroup)}nameFromFilename($){return this._name=E$.basename($,E$.extname($)),this}executableDir($){if($===void 0)return this._executableDir;return this._executableDir=$,this}helpInformation($){let w=this.createHelp(),G=this._getOutputContext($);w.prepareContext({error:G.error,helpWidth:G.helpWidth,outputHasColors:G.hasColors});let Z=w.formatHelp(this,w);if(G.hasColors)return Z;return this._outputConfiguration.stripColor(Z)}_getOutputContext($){$=$||{};let w=!!$.error,G,Z,X;if(w)G=(J)=>this._outputConfiguration.writeErr(J),Z=this._outputConfiguration.getErrHasColors(),X=this._outputConfiguration.getErrHelpWidth();else G=(J)=>this._outputConfiguration.writeOut(J),Z=this._outputConfiguration.getOutHasColors(),X=this._outputConfiguration.getOutHelpWidth();return{error:w,write:(J)=>{if(!Z)J=this._outputConfiguration.stripColor(J);return G(J)},hasColors:Z,helpWidth:X}}outputHelp($){let w;if(typeof $==="function")w=$,$=void 0;let G=this._getOutputContext($),Z={error:G.error,write:G.write,command:this};this._getCommandAndAncestors().reverse().forEach((Y)=>Y.emit("beforeAllHelp",Z)),this.emit("beforeHelp",Z);let X=this.helpInformation({error:G.error});if(w){if(X=w(X),typeof X!=="string"&&!Buffer.isBuffer(X))throw Error("outputHelp callback must return a string or a Buffer")}if(G.write(X),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",Z),this._getCommandAndAncestors().forEach((Y)=>Y.emit("afterAllHelp",Z))}helpOption($,w){if(typeof $==="boolean"){if($){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($??"-h, --help",w??"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($){return this._helpOption=$,this._initOptionGroup($),this}help($){this.outputHelp($);let w=Number(a.exitCode??0);if(w===0&&$&&typeof $!=="function"&&$.error)w=1;this._exit(w,"commander.help","(outputHelp)")}addHelpText($,w){let G=["beforeAll","before","after","afterAll"];if(!G.includes($))throw Error(`Unexpected value for position to addHelpText.
27
+ Expecting one of '${G.join("', '")}'`);let Z=`${$}Help`;return this.on(Z,(X)=>{let Y;if(typeof w==="function")Y=w({error:X.error,command:X.command});else Y=w;if(Y)X.write(`${Y}
28
+ `)}),this}_outputHelpIfRequested($){let w=this._getHelpOption();if(w&&$.find((Z)=>w.is(Z)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function VJ($){return $.map((w)=>{if(!w.startsWith("--inspect"))return w;let G,Z="127.0.0.1",X="9229",Y;if((Y=w.match(/^(--inspect(-brk)?)$/))!==null)G=Y[1];else if((Y=w.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(G=Y[1],/^\d+$/.test(Y[3]))X=Y[3];else Z=Y[3];else if((Y=w.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)G=Y[1],Z=Y[3],X=Y[4];if(G&&X!=="0")return`${G}=${Z}:${parseInt(X)+1}`;return w})}function I3(){if(a.env.NO_COLOR||a.env.FORCE_COLOR==="0"||a.env.FORCE_COLOR==="false")return!1;if(a.env.FORCE_COLOR||a.env.CLICOLOR_FORCE!==void 0)return!0;return}IK.Command=j3;IK.useColor=I3});var b3=F((yK)=>{var{Argument:UJ}=F6(),{Command:C3}=KJ(),{CommanderError:bK,InvalidArgumentError:HJ}=_4(),{Help:kK}=E3(),{Option:FJ}=A3();yK.program=new C3;yK.createCommand=($)=>new C3($);yK.createOption=($,w)=>new FJ($,w);yK.createArgument=($,w)=>new UJ($,w);yK.Command=C3;yK.Option=FJ;yK.Argument=UJ;yK.Help=kK;yK.CommanderError=bK;yK.InvalidArgumentError=HJ;yK.InvalidOptionArgumentError=HJ});var g4=F((IJ)=>{Object.defineProperty(IJ,"__esModule",{value:!0});IJ.regexpCode=IJ.getEsmExportName=IJ.getProperty=IJ.safeStringify=IJ.stringify=IJ.strConcat=IJ.addCodeArg=IJ.str=IJ._=IJ.nil=IJ._Code=IJ.Name=IJ.IDENTIFIER=IJ._CodeOrName=void 0;class D6{}IJ._CodeOrName=D6;IJ.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class Aw extends D6{constructor($){super();if(!IJ.IDENTIFIER.test($))throw Error("CodeGen: name must be a valid identifier");this.str=$}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}IJ.Name=Aw;class e0 extends D6{constructor($){super();this._items=typeof $==="string"?[$]:$}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let $=this._items[0];return $===""||$==='""'}get str(){var $;return($=this._str)!==null&&$!==void 0?$:this._str=this._items.reduce((w,G)=>`${w}${G}`,"")}get names(){var $;return($=this._names)!==null&&$!==void 0?$:this._names=this._items.reduce((w,G)=>{if(G instanceof Aw)w[G.str]=(w[G.str]||0)+1;return w},{})}}IJ._Code=e0;IJ.nil=new e0("");function RJ($,...w){let G=[$[0]],Z=0;while(Z<w.length)g3(G,w[Z]),G.push($[++Z]);return new e0(G)}IJ._=RJ;var x3=new e0("+");function SJ($,...w){let G=[x4($[0])],Z=0;while(Z<w.length)G.push(x3),g3(G,w[Z]),G.push(x3,x4($[++Z]));return oK(G),new e0(G)}IJ.str=SJ;function g3($,w){if(w instanceof e0)$.push(...w._items);else if(w instanceof Aw)$.push(w);else $.push(wU(w))}IJ.addCodeArg=g3;function oK($){let w=1;while(w<$.length-1){if($[w]===x3){let G=eK($[w-1],$[w+1]);if(G!==void 0){$.splice(w-1,3,G);continue}$[w++]="+"}w++}}function eK($,w){if(w==='""')return $;if($==='""')return w;if(typeof $=="string"){if(w instanceof Aw||$[$.length-1]!=='"')return;if(typeof w!="string")return`${$.slice(0,-1)}${w}"`;if(w[0]==='"')return $.slice(0,-1)+w.slice(1);return}if(typeof w=="string"&&w[0]==='"'&&!($ instanceof Aw))return`"${$}${w.slice(1)}`;return}function $U($,w){return w.emptyStr()?$:$.emptyStr()?w:SJ`${$}${w}`}IJ.strConcat=$U;function wU($){return typeof $=="number"||typeof $=="boolean"||$===null?$:x4(Array.isArray($)?$.join(","):$)}function GU($){return new e0(x4($))}IJ.stringify=GU;function x4($){return JSON.stringify($).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}IJ.safeStringify=x4;function ZU($){return typeof $=="string"&&IJ.IDENTIFIER.test($)?new e0(`.${$}`):RJ`[${$}]`}IJ.getProperty=ZU;function XU($){if(typeof $=="string"&&IJ.IDENTIFIER.test($))return new e0(`${$}`);throw Error(`CodeGen: invalid export name: ${$}, use explicit $id name mapping`)}IJ.getEsmExportName=XU;function YU($){return new e0($.toString())}IJ.regexpCode=YU});var i3=F((kJ)=>{Object.defineProperty(kJ,"__esModule",{value:!0});kJ.ValueScope=kJ.ValueScopeName=kJ.Scope=kJ.varKinds=kJ.UsedValueState=void 0;var I0=g4();class CJ extends Error{constructor($){super(`CodeGen: "code" for ${$} not defined`);this.value=$.value}}var A6;(function($){$[$.Started=0]="Started",$[$.Completed=1]="Completed"})(A6||(kJ.UsedValueState=A6={}));kJ.varKinds={const:new I0.Name("const"),let:new I0.Name("let"),var:new I0.Name("var")};class h3{constructor({prefixes:$,parent:w}={}){this._names={},this._prefixes=$,this._parent=w}toName($){return $ instanceof I0.Name?$:this.name($)}name($){return new I0.Name(this._newName($))}_newName($){let w=this._names[$]||this._nameGroup($);return`${$}${w.index++}`}_nameGroup($){var w,G;if(((G=(w=this._parent)===null||w===void 0?void 0:w._prefixes)===null||G===void 0?void 0:G.has($))||this._prefixes&&!this._prefixes.has($))throw Error(`CodeGen: prefix "${$}" is not allowed in this scope`);return this._names[$]={prefix:$,index:0}}}kJ.Scope=h3;class v3 extends I0.Name{constructor($,w){super(w);this.prefix=$}setValue($,{property:w,itemIndex:G}){this.value=$,this.scopePath=I0._`.${new I0.Name(w)}[${G}]`}}kJ.ValueScopeName=v3;var UU=I0._`\n`;class bJ extends h3{constructor($){super($);this._values={},this._scope=$.scope,this.opts={...$,_n:$.lines?UU:I0.nil}}get(){return this._scope}name($){return new v3($,this._newName($))}value($,w){var G;if(w.ref===void 0)throw Error("CodeGen: ref must be passed in value");let Z=this.toName($),{prefix:X}=Z,Y=(G=w.key)!==null&&G!==void 0?G:w.ref,J=this._values[X];if(J){let Q=J.get(Y);if(Q)return Q}else J=this._values[X]=new Map;J.set(Y,Z);let W=this._scope[X]||(this._scope[X]=[]),T=W.length;return W[T]=w.ref,Z.setValue(w,{property:X,itemIndex:T}),Z}getValue($,w){let G=this._values[$];if(!G)return;return G.get(w)}scopeRefs($,w=this._values){return this._reduceValues(w,(G)=>{if(G.scopePath===void 0)throw Error(`CodeGen: name "${G}" has no value`);return I0._`${$}${G.scopePath}`})}scopeCode($=this._values,w,G){return this._reduceValues($,(Z)=>{if(Z.value===void 0)throw Error(`CodeGen: name "${Z}" has no value`);return Z.value.code},w,G)}_reduceValues($,w,G={},Z){let X=I0.nil;for(let Y in $){let J=$[Y];if(!J)continue;let W=G[Y]=G[Y]||new Map;J.forEach((T)=>{if(W.has(T))return;W.set(T,A6.Started);let Q=w(T);if(Q){let z=this.opts.es5?kJ.varKinds.var:kJ.varKinds.const;X=I0._`${X}${z} ${T} = ${Q};${this.opts._n}`}else if(Q=Z===null||Z===void 0?void 0:Z(T))X=I0._`${X}${Q}${this.opts._n}`;else throw new CJ(T);W.set(T,A6.Completed)})}return X}}kJ.ValueScope=bJ});var l=F((j0)=>{Object.defineProperty(j0,"__esModule",{value:!0});j0.or=j0.and=j0.not=j0.CodeGen=j0.operators=j0.varKinds=j0.ValueScopeName=j0.ValueScope=j0.Scope=j0.Name=j0.regexpCode=j0.stringify=j0.getProperty=j0.nil=j0.strConcat=j0.str=j0._=void 0;var c=g4(),$$=i3(),r$=g4();Object.defineProperty(j0,"_",{enumerable:!0,get:function(){return r$._}});Object.defineProperty(j0,"str",{enumerable:!0,get:function(){return r$.str}});Object.defineProperty(j0,"strConcat",{enumerable:!0,get:function(){return r$.strConcat}});Object.defineProperty(j0,"nil",{enumerable:!0,get:function(){return r$.nil}});Object.defineProperty(j0,"getProperty",{enumerable:!0,get:function(){return r$.getProperty}});Object.defineProperty(j0,"stringify",{enumerable:!0,get:function(){return r$.stringify}});Object.defineProperty(j0,"regexpCode",{enumerable:!0,get:function(){return r$.regexpCode}});Object.defineProperty(j0,"Name",{enumerable:!0,get:function(){return r$.Name}});var b6=i3();Object.defineProperty(j0,"Scope",{enumerable:!0,get:function(){return b6.Scope}});Object.defineProperty(j0,"ValueScope",{enumerable:!0,get:function(){return b6.ValueScope}});Object.defineProperty(j0,"ValueScopeName",{enumerable:!0,get:function(){return b6.ValueScopeName}});Object.defineProperty(j0,"varKinds",{enumerable:!0,get:function(){return b6.varKinds}});j0.operators={GT:new c._Code(">"),GTE:new c._Code(">="),LT:new c._Code("<"),LTE:new c._Code("<="),EQ:new c._Code("==="),NEQ:new c._Code("!=="),NOT:new c._Code("!"),OR:new c._Code("||"),AND:new c._Code("&&"),ADD:new c._Code("+")};class s${optimizeNodes(){return this}optimizeNames($,w){return this}}class _J extends s${constructor($,w,G){super();this.varKind=$,this.name=w,this.rhs=G}render({es5:$,_n:w}){let G=$?$$.varKinds.var:this.varKind,Z=this.rhs===void 0?"":` = ${this.rhs}`;return`${G} ${this.name}${Z};`+w}optimizeNames($,w){if(!$[this.name.str])return;if(this.rhs)this.rhs=Sw(this.rhs,$,w);return this}get names(){return this.rhs instanceof c._CodeOrName?this.rhs.names:{}}}class d3 extends s${constructor($,w,G){super();this.lhs=$,this.rhs=w,this.sideEffects=G}render({_n:$}){return`${this.lhs} = ${this.rhs};`+$}optimizeNames($,w){if(this.lhs instanceof c.Name&&!$[this.lhs.str]&&!this.sideEffects)return;return this.rhs=Sw(this.rhs,$,w),this}get names(){let $=this.lhs instanceof c.Name?{}:{...this.lhs.names};return C6($,this.rhs)}}class xJ extends d3{constructor($,w,G,Z){super($,G,Z);this.op=w}render({_n:$}){return`${this.lhs} ${this.op}= ${this.rhs};`+$}}class gJ extends s${constructor($){super();this.label=$,this.names={}}render({_n:$}){return`${this.label}:`+$}}class uJ extends s${constructor($){super();this.label=$,this.names={}}render({_n:$}){return`break${this.label?` ${this.label}`:""};`+$}}class hJ extends s${constructor($){super();this.error=$}render({_n:$}){return`throw ${this.error};`+$}get names(){return this.error.names}}class vJ extends s${constructor($){super();this.code=$}render({_n:$}){return`${this.code};`+$}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames($,w){return this.code=Sw(this.code,$,w),this}get names(){return this.code instanceof c._CodeOrName?this.code.names:{}}}class k6 extends s${constructor($=[]){super();this.nodes=$}render($){return this.nodes.reduce((w,G)=>w+G.render($),"")}optimizeNodes(){let{nodes:$}=this,w=$.length;while(w--){let G=$[w].optimizeNodes();if(Array.isArray(G))$.splice(w,1,...G);else if(G)$[w]=G;else $.splice(w,1)}return $.length>0?this:void 0}optimizeNames($,w){let{nodes:G}=this,Z=G.length;while(Z--){let X=G[Z];if(X.optimizeNames($,w))continue;fU($,X.names),G.splice(Z,1)}return G.length>0?this:void 0}get names(){return this.nodes.reduce(($,w)=>R1($,w.names),{})}}class a$ extends k6{render($){return"{"+$._n+super.render($)+"}"+$._n}}class iJ extends k6{}class u4 extends a${}u4.kind="else";class A$ extends a${constructor($,w){super(w);this.condition=$}render($){let w=`if(${this.condition})`+super.render($);if(this.else)w+="else "+this.else.render($);return w}optimizeNodes(){super.optimizeNodes();let $=this.condition;if($===!0)return this.nodes;let w=this.else;if(w){let G=w.optimizeNodes();w=this.else=Array.isArray(G)?new u4(G):G}if(w){if($===!1)return w instanceof A$?w:w.nodes;if(this.nodes.length)return this;return new A$(pJ($),w instanceof A$?[w]:w.nodes)}if($===!1||!this.nodes.length)return;return this}optimizeNames($,w){var G;if(this.else=(G=this.else)===null||G===void 0?void 0:G.optimizeNames($,w),!(super.optimizeNames($,w)||this.else))return;return this.condition=Sw(this.condition,$,w),this}get names(){let $=super.names;if(C6($,this.condition),this.else)R1($,this.else.names);return $}}A$.kind="if";class Rw extends a${}Rw.kind="for";class mJ extends Rw{constructor($){super();this.iteration=$}render($){return`for(${this.iteration})`+super.render($)}optimizeNames($,w){if(!super.optimizeNames($,w))return;return this.iteration=Sw(this.iteration,$,w),this}get names(){return R1(super.names,this.iteration.names)}}class lJ extends Rw{constructor($,w,G,Z){super();this.varKind=$,this.name=w,this.from=G,this.to=Z}render($){let w=$.es5?$$.varKinds.var:this.varKind,{name:G,from:Z,to:X}=this;return`for(${w} ${G}=${Z}; ${G}<${X}; ${G}++)`+super.render($)}get names(){let $=C6(super.names,this.from);return C6($,this.to)}}class m3 extends Rw{constructor($,w,G,Z){super();this.loop=$,this.varKind=w,this.name=G,this.iterable=Z}render($){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render($)}optimizeNames($,w){if(!super.optimizeNames($,w))return;return this.iterable=Sw(this.iterable,$,w),this}get names(){return R1(super.names,this.iterable.names)}}class R6 extends a${constructor($,w,G){super();this.name=$,this.args=w,this.async=G}render($){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render($)}}R6.kind="func";class S6 extends k6{render($){return"return "+super.render($)}}S6.kind="return";class dJ extends a${render($){let w="try"+super.render($);if(this.catch)w+=this.catch.render($);if(this.finally)w+=this.finally.render($);return w}optimizeNodes(){var $,w;return super.optimizeNodes(),($=this.catch)===null||$===void 0||$.optimizeNodes(),(w=this.finally)===null||w===void 0||w.optimizeNodes(),this}optimizeNames($,w){var G,Z;return super.optimizeNames($,w),(G=this.catch)===null||G===void 0||G.optimizeNames($,w),(Z=this.finally)===null||Z===void 0||Z.optimizeNames($,w),this}get names(){let $=super.names;if(this.catch)R1($,this.catch.names);if(this.finally)R1($,this.finally.names);return $}}class I6 extends a${constructor($){super();this.error=$}render($){return`catch(${this.error})`+super.render($)}}I6.kind="catch";class j6 extends a${render($){return"finally"+super.render($)}}j6.kind="finally";class cJ{constructor($,w={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...w,_n:w.lines?`
29
+ `:""},this._extScope=$,this._scope=new $$.Scope({parent:$}),this._nodes=[new iJ]}toString(){return this._root.render(this.opts)}name($){return this._scope.name($)}scopeName($){return this._extScope.name($)}scopeValue($,w){let G=this._extScope.value($,w);return(this._values[G.prefix]||(this._values[G.prefix]=new Set)).add(G),G}getScopeValue($,w){return this._extScope.getValue($,w)}scopeRefs($){return this._extScope.scopeRefs($,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def($,w,G,Z){let X=this._scope.toName(w);if(G!==void 0&&Z)this._constants[X.str]=G;return this._leafNode(new _J($,X,G)),X}const($,w,G){return this._def($$.varKinds.const,$,w,G)}let($,w,G){return this._def($$.varKinds.let,$,w,G)}var($,w,G){return this._def($$.varKinds.var,$,w,G)}assign($,w,G){return this._leafNode(new d3($,w,G))}add($,w){return this._leafNode(new xJ($,j0.operators.ADD,w))}code($){if(typeof $=="function")$();else if($!==c.nil)this._leafNode(new vJ($));return this}object(...$){let w=["{"];for(let[G,Z]of $){if(w.length>1)w.push(",");if(w.push(G),G!==Z||this.opts.es5)w.push(":"),(0,c.addCodeArg)(w,Z)}return w.push("}"),new c._Code(w)}if($,w,G){if(this._blockNode(new A$($)),w&&G)this.code(w).else().code(G).endIf();else if(w)this.code(w).endIf();else if(G)throw Error('CodeGen: "else" body without "then" body');return this}elseIf($){return this._elseNode(new A$($))}else(){return this._elseNode(new u4)}endIf(){return this._endBlockNode(A$,u4)}_for($,w){if(this._blockNode($),w)this.code(w).endFor();return this}for($,w){return this._for(new mJ($),w)}forRange($,w,G,Z,X=this.opts.es5?$$.varKinds.var:$$.varKinds.let){let Y=this._scope.toName($);return this._for(new lJ(X,Y,w,G),()=>Z(Y))}forOf($,w,G,Z=$$.varKinds.const){let X=this._scope.toName($);if(this.opts.es5){let Y=w instanceof c.Name?w:this.var("_arr",w);return this.forRange("_i",0,c._`${Y}.length`,(J)=>{this.var(X,c._`${Y}[${J}]`),G(X)})}return this._for(new m3("of",Z,X,w),()=>G(X))}forIn($,w,G,Z=this.opts.es5?$$.varKinds.var:$$.varKinds.const){if(this.opts.ownProperties)return this.forOf($,c._`Object.keys(${w})`,G);let X=this._scope.toName($);return this._for(new m3("in",Z,X,w),()=>G(X))}endFor(){return this._endBlockNode(Rw)}label($){return this._leafNode(new gJ($))}break($){return this._leafNode(new uJ($))}return($){let w=new S6;if(this._blockNode(w),this.code($),w.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(S6)}try($,w,G){if(!w&&!G)throw Error('CodeGen: "try" without "catch" and "finally"');let Z=new dJ;if(this._blockNode(Z),this.code($),w){let X=this.name("e");this._currNode=Z.catch=new I6(X),w(X)}if(G)this._currNode=Z.finally=new j6,this.code(G);return this._endBlockNode(I6,j6)}throw($){return this._leafNode(new hJ($))}block($,w){if(this._blockStarts.push(this._nodes.length),$)this.code($).endBlock(w);return this}endBlock($){let w=this._blockStarts.pop();if(w===void 0)throw Error("CodeGen: not in self-balancing block");let G=this._nodes.length-w;if(G<0||$!==void 0&&G!==$)throw Error(`CodeGen: wrong number of nodes: ${G} vs ${$} expected`);return this._nodes.length=w,this}func($,w=c.nil,G,Z){if(this._blockNode(new R6($,w,G)),Z)this.code(Z).endFunc();return this}endFunc(){return this._endBlockNode(R6)}optimize($=1){while($-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode($){return this._currNode.nodes.push($),this}_blockNode($){this._currNode.nodes.push($),this._nodes.push($)}_endBlockNode($,w){let G=this._currNode;if(G instanceof $||w&&G instanceof w)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${w?`${$.kind}/${w.kind}`:$.kind}"`)}_elseNode($){let w=this._currNode;if(!(w instanceof A$))throw Error('CodeGen: "else" without "if"');return this._currNode=w.else=$,this}get _root(){return this._nodes[0]}get _currNode(){let $=this._nodes;return $[$.length-1]}set _currNode($){let w=this._nodes;w[w.length-1]=$}}j0.CodeGen=cJ;function R1($,w){for(let G in w)$[G]=($[G]||0)+(w[G]||0);return $}function C6($,w){return w instanceof c._CodeOrName?R1($,w.names):$}function Sw($,w,G){if($ instanceof c.Name)return Z($);if(!X($))return $;return new c._Code($._items.reduce((Y,J)=>{if(J instanceof c.Name)J=Z(J);if(J instanceof c._Code)Y.push(...J._items);else Y.push(J);return Y},[]));function Z(Y){let J=G[Y.str];if(J===void 0||w[Y.str]!==1)return Y;return delete w[Y.str],J}function X(Y){return Y instanceof c._Code&&Y._items.some((J)=>J instanceof c.Name&&w[J.str]===1&&G[J.str]!==void 0)}}function fU($,w){for(let G in w)$[G]=($[G]||0)-(w[G]||0)}function pJ($){return typeof $=="boolean"||typeof $=="number"||$===null?!$:c._`!${l3($)}`}j0.not=pJ;var LU=nJ(j0.operators.AND);function DU(...$){return $.reduce(LU)}j0.and=DU;var EU=nJ(j0.operators.OR);function AU(...$){return $.reduce(EU)}j0.or=AU;function nJ($){return(w,G)=>w===c.nil?G:G===c.nil?w:c._`${l3(w)} ${$} ${l3(G)}`}function l3($){return $ instanceof c.Name?$:c._`(${$})`}});var p=F((GW)=>{Object.defineProperty(GW,"__esModule",{value:!0});GW.checkStrictMode=GW.getErrorPath=GW.Type=GW.useFunc=GW.setEvaluated=GW.evaluatedPropsToName=GW.mergeEvaluated=GW.eachItem=GW.unescapeJsonPointer=GW.escapeJsonPointer=GW.escapeFragment=GW.unescapeFragment=GW.schemaRefOrVal=GW.schemaHasRulesButRef=GW.schemaHasRules=GW.checkUnknownRules=GW.alwaysValidSchema=GW.toHash=void 0;var $0=l(),jU=g4();function CU($){let w={};for(let G of $)w[G]=!0;return w}GW.toHash=CU;function bU($,w){if(typeof w=="boolean")return w;if(Object.keys(w).length===0)return!0;return tJ($,w),!oJ(w,$.self.RULES.all)}GW.alwaysValidSchema=bU;function tJ($,w=$.schema){let{opts:G,self:Z}=$;if(!G.strictSchema)return;if(typeof w==="boolean")return;let X=Z.RULES.keywords;for(let Y in w)if(!X[Y])wW($,`unknown keyword: "${Y}"`)}GW.checkUnknownRules=tJ;function oJ($,w){if(typeof $=="boolean")return!$;for(let G in $)if(w[G])return!0;return!1}GW.schemaHasRules=oJ;function kU($,w){if(typeof $=="boolean")return!$;for(let G in $)if(G!=="$ref"&&w.all[G])return!0;return!1}GW.schemaHasRulesButRef=kU;function yU({topSchemaRef:$,schemaPath:w},G,Z,X){if(!X){if(typeof G=="number"||typeof G=="boolean")return G;if(typeof G=="string")return $0._`${G}`}return $0._`${$}${w}${(0,$0.getProperty)(Z)}`}GW.schemaRefOrVal=yU;function _U($){return eJ(decodeURIComponent($))}GW.unescapeFragment=_U;function xU($){return encodeURIComponent(p3($))}GW.escapeFragment=xU;function p3($){if(typeof $=="number")return`${$}`;return $.replace(/~/g,"~0").replace(/\//g,"~1")}GW.escapeJsonPointer=p3;function eJ($){return $.replace(/~1/g,"/").replace(/~0/g,"~")}GW.unescapeJsonPointer=eJ;function gU($,w){if(Array.isArray($))for(let G of $)w(G);else w($)}GW.eachItem=gU;function sJ({mergeNames:$,mergeToName:w,mergeValues:G,resultToName:Z}){return(X,Y,J,W)=>{let T=J===void 0?Y:J instanceof $0.Name?(Y instanceof $0.Name?$(X,Y,J):w(X,Y,J),J):Y instanceof $0.Name?(w(X,J,Y),Y):G(Y,J);return W===$0.Name&&!(T instanceof $0.Name)?Z(X,T):T}}GW.mergeEvaluated={props:sJ({mergeNames:($,w,G)=>$.if($0._`${G} !== true && ${w} !== undefined`,()=>{$.if($0._`${w} === true`,()=>$.assign(G,!0),()=>$.assign(G,$0._`${G} || {}`).code($0._`Object.assign(${G}, ${w})`))}),mergeToName:($,w,G)=>$.if($0._`${G} !== true`,()=>{if(w===!0)$.assign(G,!0);else $.assign(G,$0._`${G} || {}`),n3($,G,w)}),mergeValues:($,w)=>$===!0?!0:{...$,...w},resultToName:$W}),items:sJ({mergeNames:($,w,G)=>$.if($0._`${G} !== true && ${w} !== undefined`,()=>$.assign(G,$0._`${w} === true ? true : ${G} > ${w} ? ${G} : ${w}`)),mergeToName:($,w,G)=>$.if($0._`${G} !== true`,()=>$.assign(G,w===!0?!0:$0._`${G} > ${w} ? ${G} : ${w}`)),mergeValues:($,w)=>$===!0?!0:Math.max($,w),resultToName:($,w)=>$.var("items",w)})};function $W($,w){if(w===!0)return $.var("props",!0);let G=$.var("props",$0._`{}`);if(w!==void 0)n3($,G,w);return G}GW.evaluatedPropsToName=$W;function n3($,w,G){Object.keys(G).forEach((Z)=>$.assign($0._`${w}${(0,$0.getProperty)(Z)}`,!0))}GW.setEvaluated=n3;var aJ={};function uU($,w){return $.scopeValue("func",{ref:w,code:aJ[w.code]||(aJ[w.code]=new jU._Code(w.code))})}GW.useFunc=uU;var c3;(function($){$[$.Num=0]="Num",$[$.Str=1]="Str"})(c3||(GW.Type=c3={}));function hU($,w,G){if($ instanceof $0.Name){let Z=w===c3.Num;return G?Z?$0._`"[" + ${$} + "]"`:$0._`"['" + ${$} + "']"`:Z?$0._`"/" + ${$}`:$0._`"/" + ${$}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return G?(0,$0.getProperty)($).toString():"/"+p3($)}GW.getErrorPath=hU;function wW($,w,G=$.opts.strictSchema){if(!G)return;if(w=`strict mode: ${w}`,G===!0)throw Error(w);$.self.logger.warn(w)}GW.checkStrictMode=wW});var R$=F((XW)=>{Object.defineProperty(XW,"__esModule",{value:!0});var F0=l(),ZH={data:new F0.Name("data"),valCxt:new F0.Name("valCxt"),instancePath:new F0.Name("instancePath"),parentData:new F0.Name("parentData"),parentDataProperty:new F0.Name("parentDataProperty"),rootData:new F0.Name("rootData"),dynamicAnchors:new F0.Name("dynamicAnchors"),vErrors:new F0.Name("vErrors"),errors:new F0.Name("errors"),this:new F0.Name("this"),self:new F0.Name("self"),scope:new F0.Name("scope"),json:new F0.Name("json"),jsonPos:new F0.Name("jsonPos"),jsonLen:new F0.Name("jsonLen"),jsonPart:new F0.Name("jsonPart")};XW.default=ZH});var h4=F((TW)=>{Object.defineProperty(TW,"__esModule",{value:!0});TW.extendErrors=TW.resetErrorsCount=TW.reportExtraError=TW.reportError=TW.keyword$DataError=TW.keywordError=void 0;var n=l(),_6=p(),A0=R$();TW.keywordError={message:({keyword:$})=>n.str`must pass "${$}" keyword validation`};TW.keyword$DataError={message:({keyword:$,schemaType:w})=>w?n.str`"${$}" keyword must be ${w} ($data)`:n.str`"${$}" keyword is invalid ($data)`};function YH($,w=TW.keywordError,G,Z){let{it:X}=$,{gen:Y,compositeRule:J,allErrors:W}=X,T=WW($,w,G);if(Z!==null&&Z!==void 0?Z:J||W)YW(Y,T);else JW(X,n._`[${T}]`)}TW.reportError=YH;function JH($,w=TW.keywordError,G){let{it:Z}=$,{gen:X,compositeRule:Y,allErrors:J}=Z,W=WW($,w,G);if(YW(X,W),!(Y||J))JW(Z,A0.default.vErrors)}TW.reportExtraError=JH;function WH($,w){$.assign(A0.default.errors,w),$.if(n._`${A0.default.vErrors} !== null`,()=>$.if(w,()=>$.assign(n._`${A0.default.vErrors}.length`,w),()=>$.assign(A0.default.vErrors,null)))}TW.resetErrorsCount=WH;function TH({gen:$,keyword:w,schemaValue:G,data:Z,errsCount:X,it:Y}){if(X===void 0)throw Error("ajv implementation error");let J=$.name("err");$.forRange("i",X,A0.default.errors,(W)=>{if($.const(J,n._`${A0.default.vErrors}[${W}]`),$.if(n._`${J}.instancePath === undefined`,()=>$.assign(n._`${J}.instancePath`,(0,n.strConcat)(A0.default.instancePath,Y.errorPath))),$.assign(n._`${J}.schemaPath`,n.str`${Y.errSchemaPath}/${w}`),Y.opts.verbose)$.assign(n._`${J}.schema`,G),$.assign(n._`${J}.data`,Z)})}TW.extendErrors=TH;function YW($,w){let G=$.const("err",w);$.if(n._`${A0.default.vErrors} === null`,()=>$.assign(A0.default.vErrors,n._`[${G}]`),n._`${A0.default.vErrors}.push(${G})`),$.code(n._`${A0.default.errors}++`)}function JW($,w){let{gen:G,validateName:Z,schemaEnv:X}=$;if(X.$async)G.throw(n._`new ${$.ValidationError}(${w})`);else G.assign(n._`${Z}.errors`,w),G.return(!1)}var S1={keyword:new n.Name("keyword"),schemaPath:new n.Name("schemaPath"),params:new n.Name("params"),propertyName:new n.Name("propertyName"),message:new n.Name("message"),schema:new n.Name("schema"),parentSchema:new n.Name("parentSchema")};function WW($,w,G){let{createErrors:Z}=$.it;if(Z===!1)return n._`{}`;return QH($,w,G)}function QH($,w,G={}){let{gen:Z,it:X}=$,Y=[zH(X,G),MH($,G)];return PH($,w,Y),Z.object(...Y)}function zH({errorPath:$},{instancePath:w}){let G=w?n.str`${$}${(0,_6.getErrorPath)(w,_6.Type.Str)}`:$;return[A0.default.instancePath,(0,n.strConcat)(A0.default.instancePath,G)]}function MH({keyword:$,it:{errSchemaPath:w}},{schemaPath:G,parentSchema:Z}){let X=Z?w:n.str`${w}/${$}`;if(G)X=n.str`${X}${(0,_6.getErrorPath)(G,_6.Type.Str)}`;return[S1.schemaPath,X]}function PH($,{params:w,message:G},Z){let{keyword:X,data:Y,schemaValue:J,it:W}=$,{opts:T,propertyName:Q,topSchemaRef:z,schemaPath:M}=W;if(Z.push([S1.keyword,X],[S1.params,typeof w=="function"?w($):w||n._`{}`]),T.messages)Z.push([S1.message,typeof G=="function"?G($):G]);if(T.verbose)Z.push([S1.schema,J],[S1.parentSchema,n._`${z}${M}`],[A0.default.data,Y]);if(Q)Z.push([S1.propertyName,Q])}});var qW=F((MW)=>{Object.defineProperty(MW,"__esModule",{value:!0});MW.boolOrEmptySchema=MW.topBoolOrEmptySchema=void 0;var KH=h4(),UH=l(),HH=R$(),FH={message:"boolean schema is false"};function OH($){let{gen:w,schema:G,validateName:Z}=$;if(G===!1)zW($,!1);else if(typeof G=="object"&&G.$async===!0)w.return(HH.default.data);else w.assign(UH._`${Z}.errors`,null),w.return(!0)}MW.topBoolOrEmptySchema=OH;function fH($,w){let{gen:G,schema:Z}=$;if(Z===!1)G.var(w,!1),zW($);else G.var(w,!0)}MW.boolOrEmptySchema=fH;function zW($,w){let{gen:G,data:Z}=$,X={gen:G,keyword:"false schema",data:Z,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:$};(0,KH.reportError)(X,FH,void 0,w)}});var s3=F((BW)=>{Object.defineProperty(BW,"__esModule",{value:!0});BW.getRules=BW.isJSONType=void 0;var DH=["string","number","integer","boolean","null","object","array"],EH=new Set(DH);function AH($){return typeof $=="string"&&EH.has($)}BW.isJSONType=AH;function RH(){let $={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...$,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},$.number,$.string,$.array,$.object],post:{rules:[]},all:{},keywords:{}}}BW.getRules=RH});var a3=F((UW)=>{Object.defineProperty(UW,"__esModule",{value:!0});UW.shouldUseRule=UW.shouldUseGroup=UW.schemaHasRulesForType=void 0;function IH({schema:$,self:w},G){let Z=w.RULES.types[G];return Z&&Z!==!0&&VW($,Z)}UW.schemaHasRulesForType=IH;function VW($,w){return w.rules.some((G)=>KW($,G))}UW.shouldUseGroup=VW;function KW($,w){var G;return $[w.keyword]!==void 0||((G=w.definition.implements)===null||G===void 0?void 0:G.some((Z)=>$[Z]!==void 0))}UW.shouldUseRule=KW});var v4=F((LW)=>{Object.defineProperty(LW,"__esModule",{value:!0});LW.reportTypeError=LW.checkDataTypes=LW.checkDataType=LW.coerceAndCheckDataType=LW.getJSONTypes=LW.getSchemaTypes=LW.DataType=void 0;var bH=s3(),kH=a3(),yH=h4(),i=l(),FW=p(),Iw;(function($){$[$.Correct=0]="Correct",$[$.Wrong=1]="Wrong"})(Iw||(LW.DataType=Iw={}));function _H($){let w=OW($.type);if(w.includes("null")){if($.nullable===!1)throw Error("type: null contradicts nullable: false")}else{if(!w.length&&$.nullable!==void 0)throw Error('"nullable" cannot be used without "type"');if($.nullable===!0)w.push("null")}return w}LW.getSchemaTypes=_H;function OW($){let w=Array.isArray($)?$:$?[$]:[];if(w.every(bH.isJSONType))return w;throw Error("type must be JSONType or JSONType[]: "+w.join(","))}LW.getJSONTypes=OW;function xH($,w){let{gen:G,data:Z,opts:X}=$,Y=gH(w,X.coerceTypes),J=w.length>0&&!(Y.length===0&&w.length===1&&(0,kH.schemaHasRulesForType)($,w[0]));if(J){let W=o3(w,Z,X.strictNumbers,Iw.Wrong);G.if(W,()=>{if(Y.length)uH($,w,Y);else e3($)})}return J}LW.coerceAndCheckDataType=xH;var fW=new Set(["string","number","integer","boolean","null"]);function gH($,w){return w?$.filter((G)=>fW.has(G)||w==="array"&&G==="array"):[]}function uH($,w,G){let{gen:Z,data:X,opts:Y}=$,J=Z.let("dataType",i._`typeof ${X}`),W=Z.let("coerced",i._`undefined`);if(Y.coerceTypes==="array")Z.if(i._`${J} == 'object' && Array.isArray(${X}) && ${X}.length == 1`,()=>Z.assign(X,i._`${X}[0]`).assign(J,i._`typeof ${X}`).if(o3(w,X,Y.strictNumbers),()=>Z.assign(W,X)));Z.if(i._`${W} !== undefined`);for(let Q of G)if(fW.has(Q)||Q==="array"&&Y.coerceTypes==="array")T(Q);Z.else(),e3($),Z.endIf(),Z.if(i._`${W} !== undefined`,()=>{Z.assign(X,W),hH($,W)});function T(Q){switch(Q){case"string":Z.elseIf(i._`${J} == "number" || ${J} == "boolean"`).assign(W,i._`"" + ${X}`).elseIf(i._`${X} === null`).assign(W,i._`""`);return;case"number":Z.elseIf(i._`${J} == "boolean" || ${X} === null
30
+ || (${J} == "string" && ${X} && ${X} == +${X})`).assign(W,i._`+${X}`);return;case"integer":Z.elseIf(i._`${J} === "boolean" || ${X} === null
31
+ || (${J} === "string" && ${X} && ${X} == +${X} && !(${X} % 1))`).assign(W,i._`+${X}`);return;case"boolean":Z.elseIf(i._`${X} === "false" || ${X} === 0 || ${X} === null`).assign(W,!1).elseIf(i._`${X} === "true" || ${X} === 1`).assign(W,!0);return;case"null":Z.elseIf(i._`${X} === "" || ${X} === 0 || ${X} === false`),Z.assign(W,null);return;case"array":Z.elseIf(i._`${J} === "string" || ${J} === "number"
32
+ || ${J} === "boolean" || ${X} === null`).assign(W,i._`[${X}]`)}}}function hH({gen:$,parentData:w,parentDataProperty:G},Z){$.if(i._`${w} !== undefined`,()=>$.assign(i._`${w}[${G}]`,Z))}function t3($,w,G,Z=Iw.Correct){let X=Z===Iw.Correct?i.operators.EQ:i.operators.NEQ,Y;switch($){case"null":return i._`${w} ${X} null`;case"array":Y=i._`Array.isArray(${w})`;break;case"object":Y=i._`${w} && typeof ${w} == "object" && !Array.isArray(${w})`;break;case"integer":Y=J(i._`!(${w} % 1) && !isNaN(${w})`);break;case"number":Y=J();break;default:return i._`typeof ${w} ${X} ${$}`}return Z===Iw.Correct?Y:(0,i.not)(Y);function J(W=i.nil){return(0,i.and)(i._`typeof ${w} == "number"`,W,G?i._`isFinite(${w})`:i.nil)}}LW.checkDataType=t3;function o3($,w,G,Z){if($.length===1)return t3($[0],w,G,Z);let X,Y=(0,FW.toHash)($);if(Y.array&&Y.object){let J=i._`typeof ${w} != "object"`;X=Y.null?J:i._`!${w} || ${J}`,delete Y.null,delete Y.array,delete Y.object}else X=i.nil;if(Y.number)delete Y.integer;for(let J in Y)X=(0,i.and)(X,t3(J,w,G,Z));return X}LW.checkDataTypes=o3;var vH={message:({schema:$})=>`must be ${$}`,params:({schema:$,schemaValue:w})=>typeof $=="string"?i._`{type: ${$}}`:i._`{type: ${w}}`};function e3($){let w=iH($);(0,yH.reportError)(w,vH)}LW.reportTypeError=e3;function iH($){let{gen:w,data:G,schema:Z}=$,X=(0,FW.schemaRefOrVal)($,Z,"type");return{gen:w,keyword:"type",data:G,schema:Z.type,schemaCode:X,schemaValue:X,parentSchema:Z,params:{},it:$}}});var SW=F((AW)=>{Object.defineProperty(AW,"__esModule",{value:!0});AW.assignDefaults=void 0;var jw=l(),rH=p();function sH($,w){let{properties:G,items:Z}=$.schema;if(w==="object"&&G)for(let X in G)EW($,X,G[X].default);else if(w==="array"&&Array.isArray(Z))Z.forEach((X,Y)=>EW($,Y,X.default))}AW.assignDefaults=sH;function EW($,w,G){let{gen:Z,compositeRule:X,data:Y,opts:J}=$;if(G===void 0)return;let W=jw._`${Y}${(0,jw.getProperty)(w)}`;if(X){(0,rH.checkStrictMode)($,`default is ignored for: ${W}`);return}let T=jw._`${W} === undefined`;if(J.useDefaults==="empty")T=jw._`${T} || ${W} === null || ${W} === ""`;Z.if(T,jw._`${W} = ${(0,jw.stringify)(G)}`)}});var n0=F((CW)=>{Object.defineProperty(CW,"__esModule",{value:!0});CW.validateUnion=CW.validateArray=CW.usePattern=CW.callValidateCode=CW.schemaProperties=CW.allSchemaProperties=CW.noPropertyInData=CW.propertyInData=CW.isOwnProperty=CW.hasPropFunc=CW.reportMissingProp=CW.checkMissingProp=CW.checkReportMissingProp=void 0;var w0=l(),$Z=p(),t$=R$(),aH=p();function tH($,w){let{gen:G,data:Z,it:X}=$;G.if(GZ(G,Z,w,X.opts.ownProperties),()=>{$.setParams({missingProperty:w0._`${w}`},!0),$.error()})}CW.checkReportMissingProp=tH;function oH({gen:$,data:w,it:{opts:G}},Z,X){return(0,w0.or)(...Z.map((Y)=>(0,w0.and)(GZ($,w,Y,G.ownProperties),w0._`${X} = ${Y}`)))}CW.checkMissingProp=oH;function eH($,w){$.setParams({missingProperty:w},!0),$.error()}CW.reportMissingProp=eH;function IW($){return $.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:w0._`Object.prototype.hasOwnProperty`})}CW.hasPropFunc=IW;function wZ($,w,G){return w0._`${IW($)}.call(${w}, ${G})`}CW.isOwnProperty=wZ;function $F($,w,G,Z){let X=w0._`${w}${(0,w0.getProperty)(G)} !== undefined`;return Z?w0._`${X} && ${wZ($,w,G)}`:X}CW.propertyInData=$F;function GZ($,w,G,Z){let X=w0._`${w}${(0,w0.getProperty)(G)} === undefined`;return Z?(0,w0.or)(X,(0,w0.not)(wZ($,w,G))):X}CW.noPropertyInData=GZ;function jW($){return $?Object.keys($).filter((w)=>w!=="__proto__"):[]}CW.allSchemaProperties=jW;function wF($,w){return jW(w).filter((G)=>!(0,$Z.alwaysValidSchema)($,w[G]))}CW.schemaProperties=wF;function GF({schemaCode:$,data:w,it:{gen:G,topSchemaRef:Z,schemaPath:X,errorPath:Y},it:J},W,T,Q){let z=Q?w0._`${$}, ${w}, ${Z}${X}`:w,M=[[t$.default.instancePath,(0,w0.strConcat)(t$.default.instancePath,Y)],[t$.default.parentData,J.parentData],[t$.default.parentDataProperty,J.parentDataProperty],[t$.default.rootData,t$.default.rootData]];if(J.opts.dynamicRef)M.push([t$.default.dynamicAnchors,t$.default.dynamicAnchors]);let P=w0._`${z}, ${G.object(...M)}`;return T!==w0.nil?w0._`${W}.call(${T}, ${P})`:w0._`${W}(${P})`}CW.callValidateCode=GF;var ZF=w0._`new RegExp`;function XF({gen:$,it:{opts:w}},G){let Z=w.unicodeRegExp?"u":"",{regExp:X}=w.code,Y=X(G,Z);return $.scopeValue("pattern",{key:Y.toString(),ref:Y,code:w0._`${X.code==="new RegExp"?ZF:(0,aH.useFunc)($,X)}(${G}, ${Z})`})}CW.usePattern=XF;function YF($){let{gen:w,data:G,keyword:Z,it:X}=$,Y=w.name("valid");if(X.allErrors){let W=w.let("valid",!0);return J(()=>w.assign(W,!1)),W}return w.var(Y,!0),J(()=>w.break()),Y;function J(W){let T=w.const("len",w0._`${G}.length`);w.forRange("i",0,T,(Q)=>{$.subschema({keyword:Z,dataProp:Q,dataPropType:$Z.Type.Num},Y),w.if((0,w0.not)(Y),W)})}}CW.validateArray=YF;function JF($){let{gen:w,schema:G,keyword:Z,it:X}=$;if(!Array.isArray(G))throw Error("ajv implementation error");if(G.some((T)=>(0,$Z.alwaysValidSchema)(X,T))&&!X.opts.unevaluated)return;let J=w.let("valid",!1),W=w.name("_valid");w.block(()=>G.forEach((T,Q)=>{let z=$.subschema({keyword:Z,schemaProp:Q,compositeRule:!0},W);if(w.assign(J,w0._`${J} || ${W}`),!$.mergeValidEvaluated(z,W))w.if((0,w0.not)(J))})),$.result(J,()=>$.reset(),()=>$.error(!0))}CW.validateUnion=JF});var gW=F((_W)=>{Object.defineProperty(_W,"__esModule",{value:!0});_W.validateKeywordUsage=_W.validSchemaType=_W.funcKeywordCode=_W.macroKeywordCode=void 0;var R0=l(),I1=R$(),HF=n0(),FF=h4();function OF($,w){let{gen:G,keyword:Z,schema:X,parentSchema:Y,it:J}=$,W=w.macro.call(J.self,X,Y,J),T=yW(G,Z,W);if(J.opts.validateSchema!==!1)J.self.validateSchema(W,!0);let Q=G.name("valid");$.subschema({schema:W,schemaPath:R0.nil,errSchemaPath:`${J.errSchemaPath}/${Z}`,topSchemaRef:T,compositeRule:!0},Q),$.pass(Q,()=>$.error(!0))}_W.macroKeywordCode=OF;function fF($,w){var G;let{gen:Z,keyword:X,schema:Y,parentSchema:J,$data:W,it:T}=$;DF(T,w);let Q=!W&&w.compile?w.compile.call(T.self,Y,J,T):w.validate,z=yW(Z,X,Q),M=Z.let("valid");$.block$data(M,P),$.ok((G=w.valid)!==null&&G!==void 0?G:M);function P(){if(w.errors===!1){if(B(),w.modifying)kW($);V(()=>$.error())}else{let K=w.async?q():N();if(w.modifying)kW($);V(()=>LF($,K))}}function q(){let K=Z.let("ruleErrs",null);return Z.try(()=>B(R0._`await `),(U)=>Z.assign(M,!1).if(R0._`${U} instanceof ${T.ValidationError}`,()=>Z.assign(K,R0._`${U}.errors`),()=>Z.throw(U))),K}function N(){let K=R0._`${z}.errors`;return Z.assign(K,null),B(R0.nil),K}function B(K=w.async?R0._`await `:R0.nil){let U=T.opts.passContext?I1.default.this:I1.default.self,O=!(("compile"in w)&&!W||w.schema===!1);Z.assign(M,R0._`${K}${(0,HF.callValidateCode)($,z,U,O)}`,w.modifying)}function V(K){var U;Z.if((0,R0.not)((U=w.valid)!==null&&U!==void 0?U:M),K)}}_W.funcKeywordCode=fF;function kW($){let{gen:w,data:G,it:Z}=$;w.if(Z.parentData,()=>w.assign(G,R0._`${Z.parentData}[${Z.parentDataProperty}]`))}function LF($,w){let{gen:G}=$;G.if(R0._`Array.isArray(${w})`,()=>{G.assign(I1.default.vErrors,R0._`${I1.default.vErrors} === null ? ${w} : ${I1.default.vErrors}.concat(${w})`).assign(I1.default.errors,R0._`${I1.default.vErrors}.length`),(0,FF.extendErrors)($)},()=>$.error())}function DF({schemaEnv:$},w){if(w.async&&!$.$async)throw Error("async keyword in sync schema")}function yW($,w,G){if(G===void 0)throw Error(`keyword "${w}" failed to compile`);return $.scopeValue("keyword",typeof G=="function"?{ref:G}:{ref:G,code:(0,R0.stringify)(G)})}function EF($,w,G=!1){return!w.length||w.some((Z)=>Z==="array"?Array.isArray($):Z==="object"?$&&typeof $=="object"&&!Array.isArray($):typeof $==Z||G&&typeof $>"u")}_W.validSchemaType=EF;function AF({schema:$,opts:w,self:G,errSchemaPath:Z},X,Y){if(Array.isArray(X.keyword)?!X.keyword.includes(Y):X.keyword!==Y)throw Error("ajv implementation error");let J=X.dependencies;if(J===null||J===void 0?void 0:J.some((W)=>!Object.prototype.hasOwnProperty.call($,W)))throw Error(`parent schema must have dependencies of ${Y}: ${J.join(",")}`);if(X.validateSchema){if(!X.validateSchema($[Y])){let T=`keyword "${Y}" value is invalid at path "${Z}": `+G.errorsText(X.validateSchema.errors);if(w.validateSchema==="log")G.logger.error(T);else throw Error(T)}}}_W.validateKeywordUsage=AF});var iW=F((hW)=>{Object.defineProperty(hW,"__esModule",{value:!0});hW.extendSubschemaMode=hW.extendSubschemaData=hW.getSubschema=void 0;var P$=l(),uW=p();function jF($,{keyword:w,schemaProp:G,schema:Z,schemaPath:X,errSchemaPath:Y,topSchemaRef:J}){if(w!==void 0&&Z!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(w!==void 0){let W=$.schema[w];return G===void 0?{schema:W,schemaPath:P$._`${$.schemaPath}${(0,P$.getProperty)(w)}`,errSchemaPath:`${$.errSchemaPath}/${w}`}:{schema:W[G],schemaPath:P$._`${$.schemaPath}${(0,P$.getProperty)(w)}${(0,P$.getProperty)(G)}`,errSchemaPath:`${$.errSchemaPath}/${w}/${(0,uW.escapeFragment)(G)}`}}if(Z!==void 0){if(X===void 0||Y===void 0||J===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:Z,schemaPath:X,topSchemaRef:J,errSchemaPath:Y}}throw Error('either "keyword" or "schema" must be passed')}hW.getSubschema=jF;function CF($,w,{dataProp:G,dataPropType:Z,data:X,dataTypes:Y,propertyName:J}){if(X!==void 0&&G!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:W}=w;if(G!==void 0){let{errorPath:Q,dataPathArr:z,opts:M}=w,P=W.let("data",P$._`${w.data}${(0,P$.getProperty)(G)}`,!0);T(P),$.errorPath=P$.str`${Q}${(0,uW.getErrorPath)(G,Z,M.jsPropertySyntax)}`,$.parentDataProperty=P$._`${G}`,$.dataPathArr=[...z,$.parentDataProperty]}if(X!==void 0){let Q=X instanceof P$.Name?X:W.let("data",X,!0);if(T(Q),J!==void 0)$.propertyName=J}if(Y)$.dataTypes=Y;function T(Q){$.data=Q,$.dataLevel=w.dataLevel+1,$.dataTypes=[],w.definedProperties=new Set,$.parentData=w.data,$.dataNames=[...w.dataNames,Q]}}hW.extendSubschemaData=CF;function bF($,{jtdDiscriminator:w,jtdMetadata:G,compositeRule:Z,createErrors:X,allErrors:Y}){if(Z!==void 0)$.compositeRule=Z;if(X!==void 0)$.createErrors=X;if(Y!==void 0)$.allErrors=Y;$.jtdDiscriminator=w,$.jtdMetadata=G}hW.extendSubschemaMode=bF});var ZZ=F((uv,mW)=>{mW.exports=function $(w,G){if(w===G)return!0;if(w&&G&&typeof w=="object"&&typeof G=="object"){if(w.constructor!==G.constructor)return!1;var Z,X,Y;if(Array.isArray(w)){if(Z=w.length,Z!=G.length)return!1;for(X=Z;X--!==0;)if(!$(w[X],G[X]))return!1;return!0}if(w.constructor===RegExp)return w.source===G.source&&w.flags===G.flags;if(w.valueOf!==Object.prototype.valueOf)return w.valueOf()===G.valueOf();if(w.toString!==Object.prototype.toString)return w.toString()===G.toString();if(Y=Object.keys(w),Z=Y.length,Z!==Object.keys(G).length)return!1;for(X=Z;X--!==0;)if(!Object.prototype.hasOwnProperty.call(G,Y[X]))return!1;for(X=Z;X--!==0;){var J=Y[X];if(!$(w[J],G[J]))return!1}return!0}return w!==w&&G!==G}});var dW=F((hv,lW)=>{var o$=lW.exports=function($,w,G){if(typeof w=="function")G=w,w={};G=w.cb||G;var Z=typeof G=="function"?G:G.pre||function(){},X=G.post||function(){};x6(w,Z,X,$,"",$)};o$.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};o$.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};o$.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};o$.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function x6($,w,G,Z,X,Y,J,W,T,Q){if(Z&&typeof Z=="object"&&!Array.isArray(Z)){w(Z,X,Y,J,W,T,Q);for(var z in Z){var M=Z[z];if(Array.isArray(M)){if(z in o$.arrayKeywords)for(var P=0;P<M.length;P++)x6($,w,G,M[P],X+"/"+z+"/"+P,Y,X,z,Z,P)}else if(z in o$.propsKeywords){if(M&&typeof M=="object")for(var q in M)x6($,w,G,M[q],X+"/"+z+"/"+_F(q),Y,X,z,Z,q)}else if(z in o$.keywords||$.allKeys&&!(z in o$.skipKeywords))x6($,w,G,M,X+"/"+z,Y,X,z,Z)}G(Z,X,Y,J,W,T,Q)}}function _F($){return $.replace(/~/g,"~0").replace(/\//g,"~1")}});var i4=F((rW)=>{Object.defineProperty(rW,"__esModule",{value:!0});rW.getSchemaRefs=rW.resolveUrl=rW.normalizeId=rW._getFullPath=rW.getFullPath=rW.inlineRef=void 0;var xF=p(),gF=ZZ(),uF=dW(),hF=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function vF($,w=!0){if(typeof $=="boolean")return!0;if(w===!0)return!XZ($);if(!w)return!1;return cW($)<=w}rW.inlineRef=vF;var iF=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function XZ($){for(let w in $){if(iF.has(w))return!0;let G=$[w];if(Array.isArray(G)&&G.some(XZ))return!0;if(typeof G=="object"&&XZ(G))return!0}return!1}function cW($){let w=0;for(let G in $){if(G==="$ref")return 1/0;if(w++,hF.has(G))continue;if(typeof $[G]=="object")(0,xF.eachItem)($[G],(Z)=>w+=cW(Z));if(w===1/0)return 1/0}return w}function pW($,w="",G){if(G!==!1)w=Cw(w);let Z=$.parse(w);return nW($,Z)}rW.getFullPath=pW;function nW($,w){return $.serialize(w).split("#")[0]+"#"}rW._getFullPath=nW;var mF=/#\/?$/;function Cw($){return $?$.replace(mF,""):""}rW.normalizeId=Cw;function lF($,w,G){return G=Cw(G),$.resolve(w,G)}rW.resolveUrl=lF;var dF=/^[a-z_][-a-z0-9._]*$/i;function cF($,w){if(typeof $=="boolean")return{};let{schemaId:G,uriResolver:Z}=this.opts,X=Cw($[G]||w),Y={"":X},J=pW(Z,X,!1),W={},T=new Set;return uF($,{allKeys:!0},(M,P,q,N)=>{if(N===void 0)return;let B=J+P,V=Y[N];if(typeof M[G]=="string")V=K.call(this,M[G]);U.call(this,M.$anchor),U.call(this,M.$dynamicAnchor),Y[P]=V;function K(O){let D=this.opts.uriResolver.resolve;if(O=Cw(V?D(V,O):O),T.has(O))throw z(O);T.add(O);let f=this.refs[O];if(typeof f=="string")f=this.refs[f];if(typeof f=="object")Q(M,f.schema,O);else if(O!==Cw(B))if(O[0]==="#")Q(M,W[O],O),W[O]=M;else this.refs[O]=B;return O}function U(O){if(typeof O=="string"){if(!dF.test(O))throw Error(`invalid anchor "${O}"`);K.call(this,`#${O}`)}}}),W;function Q(M,P,q){if(P!==void 0&&!gF(M,P))throw z(q)}function z(M){return Error(`reference "${M}" resolves to more than one schema`)}}rW.getSchemaRefs=cF});var d4=F((zT)=>{Object.defineProperty(zT,"__esModule",{value:!0});zT.getData=zT.KeywordCxt=zT.validateFunctionCode=void 0;var $T=qW(),aW=v4(),JZ=a3(),g6=v4(),tF=SW(),l4=gW(),YZ=iW(),b=l(),u=R$(),oF=i4(),S$=p(),m4=h4();function eF($){if(ZT($)){if(XT($),GT($)){GO($);return}}wT($,()=>(0,$T.topBoolOrEmptySchema)($))}zT.validateFunctionCode=eF;function wT({gen:$,validateName:w,schema:G,schemaEnv:Z,opts:X},Y){if(X.code.es5)$.func(w,b._`${u.default.data}, ${u.default.valCxt}`,Z.$async,()=>{$.code(b._`"use strict"; ${tW(G,X)}`),wO($,X),$.code(Y)});else $.func(w,b._`${u.default.data}, ${$O(X)}`,Z.$async,()=>$.code(tW(G,X)).code(Y))}function $O($){return b._`{${u.default.instancePath}="", ${u.default.parentData}, ${u.default.parentDataProperty}, ${u.default.rootData}=${u.default.data}${$.dynamicRef?b._`, ${u.default.dynamicAnchors}={}`:b.nil}}={}`}function wO($,w){$.if(u.default.valCxt,()=>{if($.var(u.default.instancePath,b._`${u.default.valCxt}.${u.default.instancePath}`),$.var(u.default.parentData,b._`${u.default.valCxt}.${u.default.parentData}`),$.var(u.default.parentDataProperty,b._`${u.default.valCxt}.${u.default.parentDataProperty}`),$.var(u.default.rootData,b._`${u.default.valCxt}.${u.default.rootData}`),w.dynamicRef)$.var(u.default.dynamicAnchors,b._`${u.default.valCxt}.${u.default.dynamicAnchors}`)},()=>{if($.var(u.default.instancePath,b._`""`),$.var(u.default.parentData,b._`undefined`),$.var(u.default.parentDataProperty,b._`undefined`),$.var(u.default.rootData,u.default.data),w.dynamicRef)$.var(u.default.dynamicAnchors,b._`{}`)})}function GO($){let{schema:w,opts:G,gen:Z}=$;wT($,()=>{if(G.$comment&&w.$comment)JT($);if(WO($),Z.let(u.default.vErrors,null),Z.let(u.default.errors,0),G.unevaluated)ZO($);YT($),zO($)});return}function ZO($){let{gen:w,validateName:G}=$;$.evaluated=w.const("evaluated",b._`${G}.evaluated`),w.if(b._`${$.evaluated}.dynamicProps`,()=>w.assign(b._`${$.evaluated}.props`,b._`undefined`)),w.if(b._`${$.evaluated}.dynamicItems`,()=>w.assign(b._`${$.evaluated}.items`,b._`undefined`))}function tW($,w){let G=typeof $=="object"&&$[w.schemaId];return G&&(w.code.source||w.code.process)?b._`/*# sourceURL=${G} */`:b.nil}function XO($,w){if(ZT($)){if(XT($),GT($)){YO($,w);return}}(0,$T.boolOrEmptySchema)($,w)}function GT({schema:$,self:w}){if(typeof $=="boolean")return!$;for(let G in $)if(w.RULES.all[G])return!0;return!1}function ZT($){return typeof $.schema!="boolean"}function YO($,w){let{schema:G,gen:Z,opts:X}=$;if(X.$comment&&G.$comment)JT($);TO($),QO($);let Y=Z.const("_errs",u.default.errors);YT($,Y),Z.var(w,b._`${Y} === ${u.default.errors}`)}function XT($){(0,S$.checkUnknownRules)($),JO($)}function YT($,w){if($.opts.jtd)return oW($,[],!1,w);let G=(0,aW.getSchemaTypes)($.schema),Z=(0,aW.coerceAndCheckDataType)($,G);oW($,G,!Z,w)}function JO($){let{schema:w,errSchemaPath:G,opts:Z,self:X}=$;if(w.$ref&&Z.ignoreKeywordsWithRef&&(0,S$.schemaHasRulesButRef)(w,X.RULES))X.logger.warn(`$ref: keywords ignored in schema at path "${G}"`)}function WO($){let{schema:w,opts:G}=$;if(w.default!==void 0&&G.useDefaults&&G.strictSchema)(0,S$.checkStrictMode)($,"default is ignored in the schema root")}function TO($){let w=$.schema[$.opts.schemaId];if(w)$.baseId=(0,oF.resolveUrl)($.opts.uriResolver,$.baseId,w)}function QO($){if($.schema.$async&&!$.schemaEnv.$async)throw Error("async schema in sync schema")}function JT({gen:$,schemaEnv:w,schema:G,errSchemaPath:Z,opts:X}){let Y=G.$comment;if(X.$comment===!0)$.code(b._`${u.default.self}.logger.log(${Y})`);else if(typeof X.$comment=="function"){let J=b.str`${Z}/$comment`,W=$.scopeValue("root",{ref:w.root});$.code(b._`${u.default.self}.opts.$comment(${Y}, ${J}, ${W}.schema)`)}}function zO($){let{gen:w,schemaEnv:G,validateName:Z,ValidationError:X,opts:Y}=$;if(G.$async)w.if(b._`${u.default.errors} === 0`,()=>w.return(u.default.data),()=>w.throw(b._`new ${X}(${u.default.vErrors})`));else{if(w.assign(b._`${Z}.errors`,u.default.vErrors),Y.unevaluated)MO($);w.return(b._`${u.default.errors} === 0`)}}function MO({gen:$,evaluated:w,props:G,items:Z}){if(G instanceof b.Name)$.assign(b._`${w}.props`,G);if(Z instanceof b.Name)$.assign(b._`${w}.items`,Z)}function oW($,w,G,Z){let{gen:X,schema:Y,data:J,allErrors:W,opts:T,self:Q}=$,{RULES:z}=Q;if(Y.$ref&&(T.ignoreKeywordsWithRef||!(0,S$.schemaHasRulesButRef)(Y,z))){X.block(()=>TT($,"$ref",z.all.$ref.definition));return}if(!T.jtd)PO($,w);X.block(()=>{for(let P of z.rules)M(P);M(z.post)});function M(P){if(!(0,JZ.shouldUseGroup)(Y,P))return;if(P.type){if(X.if((0,g6.checkDataType)(P.type,J,T.strictNumbers)),eW($,P),w.length===1&&w[0]===P.type&&G)X.else(),(0,g6.reportTypeError)($);X.endIf()}else eW($,P);if(!W)X.if(b._`${u.default.errors} === ${Z||0}`)}}function eW($,w){let{gen:G,schema:Z,opts:{useDefaults:X}}=$;if(X)(0,tF.assignDefaults)($,w.type);G.block(()=>{for(let Y of w.rules)if((0,JZ.shouldUseRule)(Z,Y))TT($,Y.keyword,Y.definition,w.type)})}function PO($,w){if($.schemaEnv.meta||!$.opts.strictTypes)return;if(qO($,w),!$.opts.allowUnionTypes)BO($,w);NO($,$.dataTypes)}function qO($,w){if(!w.length)return;if(!$.dataTypes.length){$.dataTypes=w;return}w.forEach((G)=>{if(!WT($.dataTypes,G))WZ($,`type "${G}" not allowed by context "${$.dataTypes.join(",")}"`)}),KO($,w)}function BO($,w){if(w.length>1&&!(w.length===2&&w.includes("null")))WZ($,"use allowUnionTypes to allow union type keyword")}function NO($,w){let G=$.self.RULES.all;for(let Z in G){let X=G[Z];if(typeof X=="object"&&(0,JZ.shouldUseRule)($.schema,X)){let{type:Y}=X.definition;if(Y.length&&!Y.some((J)=>VO(w,J)))WZ($,`missing type "${Y.join(",")}" for keyword "${Z}"`)}}}function VO($,w){return $.includes(w)||w==="number"&&$.includes("integer")}function WT($,w){return $.includes(w)||w==="integer"&&$.includes("number")}function KO($,w){let G=[];for(let Z of $.dataTypes)if(WT(w,Z))G.push(Z);else if(w.includes("integer")&&Z==="number")G.push("integer");$.dataTypes=G}function WZ($,w){let G=$.schemaEnv.baseId+$.errSchemaPath;w+=` at "${G}" (strictTypes)`,(0,S$.checkStrictMode)($,w,$.opts.strictTypes)}class TZ{constructor($,w,G){if((0,l4.validateKeywordUsage)($,w,G),this.gen=$.gen,this.allErrors=$.allErrors,this.keyword=G,this.data=$.data,this.schema=$.schema[G],this.$data=w.$data&&$.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,S$.schemaRefOrVal)($,this.schema,G,this.$data),this.schemaType=w.schemaType,this.parentSchema=$.schema,this.params={},this.it=$,this.def=w,this.$data)this.schemaCode=$.gen.const("vSchema",QT(this.$data,$));else if(this.schemaCode=this.schemaValue,!(0,l4.validSchemaType)(this.schema,w.schemaType,w.allowUndefined))throw Error(`${G} value must be ${JSON.stringify(w.schemaType)}`);if("code"in w?w.trackErrors:w.errors!==!1)this.errsCount=$.gen.const("_errs",u.default.errors)}result($,w,G){this.failResult((0,b.not)($),w,G)}failResult($,w,G){if(this.gen.if($),G)G();else this.error();if(w){if(this.gen.else(),w(),this.allErrors)this.gen.endIf()}else if(this.allErrors)this.gen.endIf();else this.gen.else()}pass($,w){this.failResult((0,b.not)($),void 0,w)}fail($){if($===void 0){if(this.error(),!this.allErrors)this.gen.if(!1);return}if(this.gen.if($),this.error(),this.allErrors)this.gen.endIf();else this.gen.else()}fail$data($){if(!this.$data)return this.fail($);let{schemaCode:w}=this;this.fail(b._`${w} !== undefined && (${(0,b.or)(this.invalid$data(),$)})`)}error($,w,G){if(w){this.setParams(w),this._error($,G),this.setParams({});return}this._error($,G)}_error($,w){($?m4.reportExtraError:m4.reportError)(this,this.def.error,w)}$dataError(){(0,m4.reportError)(this,this.def.$dataError||m4.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,m4.resetErrorsCount)(this.gen,this.errsCount)}ok($){if(!this.allErrors)this.gen.if($)}setParams($,w){if(w)Object.assign(this.params,$);else this.params=$}block$data($,w,G=b.nil){this.gen.block(()=>{this.check$data($,G),w()})}check$data($=b.nil,w=b.nil){if(!this.$data)return;let{gen:G,schemaCode:Z,schemaType:X,def:Y}=this;if(G.if((0,b.or)(b._`${Z} === undefined`,w)),$!==b.nil)G.assign($,!0);if(X.length||Y.validateSchema){if(G.elseIf(this.invalid$data()),this.$dataError(),$!==b.nil)G.assign($,!1)}G.else()}invalid$data(){let{gen:$,schemaCode:w,schemaType:G,def:Z,it:X}=this;return(0,b.or)(Y(),J());function Y(){if(G.length){if(!(w instanceof b.Name))throw Error("ajv implementation error");let W=Array.isArray(G)?G:[G];return b._`${(0,g6.checkDataTypes)(W,w,X.opts.strictNumbers,g6.DataType.Wrong)}`}return b.nil}function J(){if(Z.validateSchema){let W=$.scopeValue("validate$data",{ref:Z.validateSchema});return b._`!${W}(${w})`}return b.nil}}subschema($,w){let G=(0,YZ.getSubschema)(this.it,$);(0,YZ.extendSubschemaData)(G,this.it,$),(0,YZ.extendSubschemaMode)(G,$);let Z={...this.it,...G,items:void 0,props:void 0};return XO(Z,w),Z}mergeEvaluated($,w){let{it:G,gen:Z}=this;if(!G.opts.unevaluated)return;if(G.props!==!0&&$.props!==void 0)G.props=S$.mergeEvaluated.props(Z,$.props,G.props,w);if(G.items!==!0&&$.items!==void 0)G.items=S$.mergeEvaluated.items(Z,$.items,G.items,w)}mergeValidEvaluated($,w){let{it:G,gen:Z}=this;if(G.opts.unevaluated&&(G.props!==!0||G.items!==!0))return Z.if(w,()=>this.mergeEvaluated($,b.Name)),!0}}zT.KeywordCxt=TZ;function TT($,w,G,Z){let X=new TZ($,G,w);if("code"in G)G.code(X,Z);else if(X.$data&&G.validate)(0,l4.funcKeywordCode)(X,G);else if("macro"in G)(0,l4.macroKeywordCode)(X,G);else if(G.compile||G.validate)(0,l4.funcKeywordCode)(X,G)}var UO=/^\/(?:[^~]|~0|~1)*$/,HO=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function QT($,{dataLevel:w,dataNames:G,dataPathArr:Z}){let X,Y;if($==="")return u.default.rootData;if($[0]==="/"){if(!UO.test($))throw Error(`Invalid JSON-pointer: ${$}`);X=$,Y=u.default.rootData}else{let Q=HO.exec($);if(!Q)throw Error(`Invalid JSON-pointer: ${$}`);let z=+Q[1];if(X=Q[2],X==="#"){if(z>=w)throw Error(T("property/index",z));return Z[w-z]}if(z>w)throw Error(T("data",z));if(Y=G[w-z],!X)return Y}let J=Y,W=X.split("/");for(let Q of W)if(Q)Y=b._`${Y}${(0,b.getProperty)((0,S$.unescapeJsonPointer)(Q))}`,J=b._`${J} && ${Y}`;return J;function T(Q,z){return`Cannot access ${Q} ${z} levels up, current level is ${w}`}}zT.getData=QT});var u6=F((qT)=>{Object.defineProperty(qT,"__esModule",{value:!0});class PT extends Error{constructor($){super("validation failed");this.errors=$,this.ajv=this.validation=!0}}qT.default=PT});var c4=F((NT)=>{Object.defineProperty(NT,"__esModule",{value:!0});var QZ=i4();class BT extends Error{constructor($,w,G,Z){super(Z||`can't resolve reference ${G} from id ${w}`);this.missingRef=(0,QZ.resolveUrl)($,w,G),this.missingSchema=(0,QZ.normalizeId)((0,QZ.getFullPath)($,this.missingRef))}}NT.default=BT});var v6=F((UT)=>{Object.defineProperty(UT,"__esModule",{value:!0});UT.resolveSchema=UT.getCompilingSchema=UT.resolveRef=UT.compileSchema=UT.SchemaEnv=void 0;var w$=l(),DO=u6(),j1=R$(),G$=i4(),VT=p(),EO=d4();class p4{constructor($){var w;this.refs={},this.dynamicAnchors={};let G;if(typeof $.schema=="object")G=$.schema;this.schema=$.schema,this.schemaId=$.schemaId,this.root=$.root||this,this.baseId=(w=$.baseId)!==null&&w!==void 0?w:(0,G$.normalizeId)(G===null||G===void 0?void 0:G[$.schemaId||"$id"]),this.schemaPath=$.schemaPath,this.localRefs=$.localRefs,this.meta=$.meta,this.$async=G===null||G===void 0?void 0:G.$async,this.refs={}}}UT.SchemaEnv=p4;function MZ($){let w=KT.call(this,$);if(w)return w;let G=(0,G$.getFullPath)(this.opts.uriResolver,$.root.baseId),{es5:Z,lines:X}=this.opts.code,{ownProperties:Y}=this.opts,J=new w$.CodeGen(this.scope,{es5:Z,lines:X,ownProperties:Y}),W;if($.$async)W=J.scopeValue("Error",{ref:DO.default,code:w$._`require("ajv/dist/runtime/validation_error").default`});let T=J.scopeName("validate");$.validateName=T;let Q={gen:J,allErrors:this.opts.allErrors,data:j1.default.data,parentData:j1.default.parentData,parentDataProperty:j1.default.parentDataProperty,dataNames:[j1.default.data],dataPathArr:[w$.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:J.scopeValue("schema",this.opts.code.source===!0?{ref:$.schema,code:(0,w$.stringify)($.schema)}:{ref:$.schema}),validateName:T,ValidationError:W,schema:$.schema,schemaEnv:$,rootId:G,baseId:$.baseId||G,schemaPath:w$.nil,errSchemaPath:$.schemaPath||(this.opts.jtd?"":"#"),errorPath:w$._`""`,opts:this.opts,self:this},z;try{this._compilations.add($),(0,EO.validateFunctionCode)(Q),J.optimize(this.opts.code.optimize);let M=J.toString();if(z=`${J.scopeRefs(j1.default.scope)}return ${M}`,this.opts.code.process)z=this.opts.code.process(z,$);let q=Function(`${j1.default.self}`,`${j1.default.scope}`,z)(this,this.scope.get());if(this.scope.value(T,{ref:q}),q.errors=null,q.schema=$.schema,q.schemaEnv=$,$.$async)q.$async=!0;if(this.opts.code.source===!0)q.source={validateName:T,validateCode:M,scopeValues:J._values};if(this.opts.unevaluated){let{props:N,items:B}=Q;if(q.evaluated={props:N instanceof w$.Name?void 0:N,items:B instanceof w$.Name?void 0:B,dynamicProps:N instanceof w$.Name,dynamicItems:B instanceof w$.Name},q.source)q.source.evaluated=(0,w$.stringify)(q.evaluated)}return $.validate=q,$}catch(M){if(delete $.validate,delete $.validateName,z)this.logger.error("Error compiling schema, function code:",z);throw M}finally{this._compilations.delete($)}}UT.compileSchema=MZ;function AO($,w,G){var Z;G=(0,G$.resolveUrl)(this.opts.uriResolver,w,G);let X=$.refs[G];if(X)return X;let Y=IO.call(this,$,G);if(Y===void 0){let J=(Z=$.localRefs)===null||Z===void 0?void 0:Z[G],{schemaId:W}=this.opts;if(J)Y=new p4({schema:J,schemaId:W,root:$,baseId:w})}if(Y===void 0)return;return $.refs[G]=RO.call(this,Y)}UT.resolveRef=AO;function RO($){if((0,G$.inlineRef)($.schema,this.opts.inlineRefs))return $.schema;return $.validate?$:MZ.call(this,$)}function KT($){for(let w of this._compilations)if(SO(w,$))return w}UT.getCompilingSchema=KT;function SO($,w){return $.schema===w.schema&&$.root===w.root&&$.baseId===w.baseId}function IO($,w){let G;while(typeof(G=this.refs[w])=="string")w=G;return G||this.schemas[w]||h6.call(this,$,w)}function h6($,w){let G=this.opts.uriResolver.parse(w),Z=(0,G$._getFullPath)(this.opts.uriResolver,G),X=(0,G$.getFullPath)(this.opts.uriResolver,$.baseId,void 0);if(Object.keys($.schema).length>0&&Z===X)return zZ.call(this,G,$);let Y=(0,G$.normalizeId)(Z),J=this.refs[Y]||this.schemas[Y];if(typeof J=="string"){let W=h6.call(this,$,J);if(typeof(W===null||W===void 0?void 0:W.schema)!=="object")return;return zZ.call(this,G,W)}if(typeof(J===null||J===void 0?void 0:J.schema)!=="object")return;if(!J.validate)MZ.call(this,J);if(Y===(0,G$.normalizeId)(w)){let{schema:W}=J,{schemaId:T}=this.opts,Q=W[T];if(Q)X=(0,G$.resolveUrl)(this.opts.uriResolver,X,Q);return new p4({schema:W,schemaId:T,root:$,baseId:X})}return zZ.call(this,G,J)}UT.resolveSchema=h6;var jO=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function zZ($,{baseId:w,schema:G,root:Z}){var X;if(((X=$.fragment)===null||X===void 0?void 0:X[0])!=="/")return;for(let W of $.fragment.slice(1).split("/")){if(typeof G==="boolean")return;let T=G[(0,VT.unescapeFragment)(W)];if(T===void 0)return;G=T;let Q=typeof G==="object"&&G[this.opts.schemaId];if(!jO.has(W)&&Q)w=(0,G$.resolveUrl)(this.opts.uriResolver,w,Q)}let Y;if(typeof G!="boolean"&&G.$ref&&!(0,VT.schemaHasRulesButRef)(G,this.RULES)){let W=(0,G$.resolveUrl)(this.opts.uriResolver,w,G.$ref);Y=h6.call(this,Z,W)}let{schemaId:J}=this.opts;if(Y=Y||new p4({schema:G,schemaId:J,root:Z,baseId:w}),Y.schema!==Y.root.schema)return Y;return}});var FT=F((cv,_O)=>{_O.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var KZ=F((pv,RT)=>{var xO=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),qZ=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),C1=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),BZ=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),fT=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),NZ=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),gO=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),C0=Array(256);for(let w=0;w<256;w++)C0[w]="%"+"0123456789ABCDEF"[w>>4]+"0123456789ABCDEF"[w&15];function O0($){if($<2048)return C0[192|$>>6]+C0[128|$&63];if($<65536)return C0[224|$>>12]+C0[128|$>>6&63]+C0[128|$&63];return C0[240|$>>18]+C0[128|$>>12&63]+C0[128|$>>6&63]+C0[128|$&63]}function uO($){let w="",G=0,Z=0;for(Z=0;Z<$.length;Z++){if(G=$[Z].charCodeAt(0),G===48)continue;if(!(G>=48&&G<=57||G>=65&&G<=70||G>=97&&G<=102))return"";w+=$[Z];break}for(Z+=1;Z<$.length;Z++){if(G=$[Z].charCodeAt(0),!(G>=48&&G<=57||G>=65&&G<=70||G>=97&&G<=102))return"";w+=$[Z]}return w}var hO=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),vO=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),iO=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),mO=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function lO($){if($.length===0)return!1;for(let w=0;w<$.length;w++){if(iO($[w]))continue;if($[w]==="%"&&w+2<$.length&&C1($.slice(w+1,w+3))){w+=2;continue}return!1}return!0}function OT($){let w=-1,G=0,Z=-1,X=0;for(let W=0;W<$.length;W++)if($[W]==="0"){if(Z===-1)Z=W;if(X++,X>G)G=X,w=Z}else Z=-1,X=0;if(G<2)return $.join(":");let Y=$.slice(0,w).join(":"),J=$.slice(w+G).join(":");return Y+"::"+J}function dO($){let w=$.indexOf("::");if(w!==-1&&$.indexOf("::",w+1)!==-1)return;let G=w===-1?$.split(":"):$.slice(0,w).split(":"),Z=w===-1?[]:$.slice(w+2).split(":");if(w!==-1){if(G.length===1&&G[0]==="")G.length=0;if(Z.length===1&&Z[0]==="")Z.length=0}let X=G.concat(Z),Y=0;for(let W=0;W<X.length;W++){let T=X[W];if(T==="")return;if(T.indexOf(".")!==-1){if(W!==X.length-1||w!==-1&&Z.length===0||!qZ(T))return;Y+=2;continue}if(!hO(T))return;X[W]=parseInt(T,16).toString(16),Y++}if(w===-1){if(Y!==8)return;return OT(X)}if(Y>=8)return;let J=X.slice(0,G.length);for(let W=Y;W<8;W++)J.push("0");for(let W=G.length;W<X.length;W++)J.push(X[W]);return OT(J)}function PZ($){let w=$[0]==="["&&$[$.length-1]==="]";if(($[0]==="["||$[$.length-1]==="]")&&!w)return{host:$,isIPV6:!1,error:!0};let Z=w?$.slice(1,-1):$;if(w&&vO(Z))return Z=Z.toLowerCase(),{host:`[${Z}]`,escapedHost:Z,isIPV6:!1,isIPVFuture:!0};if(cO(Z,":")<2)return{host:$,isIPV6:!1,error:w};let X="",Y=Z.indexOf("%");if(Y!==-1){let W=Z.slice(Y,Y+3).toLowerCase()==="%25"?3:1;if(X=Z.slice(Y+W),!lO(X))return{host:$,isIPV6:!1,error:!0};Z=Z.slice(0,Y)}let J=dO(Z);if(J===void 0)return{host:$,isIPV6:!1,error:!0};return{host:J+(X?"%"+X:""),escapedHost:J+(X?"%25"+X:""),isIPV6:!0}}function cO($,w){let G=0;for(let Z=0;Z<$.length;Z++)if($[Z]===w)G++;return G}function pO($){let w=$,G=[],Z=-1,X=0;while(X=w.length){if(X===1)if(w===".")break;else if(w==="/"){G.push("/");break}else{G.push(w);break}else if(X===2){if(w[0]==="."){if(w[1]===".")break;else if(w[1]==="/"){w=w.slice(2);continue}}else if(w[0]==="/"){if(w[1]==="."||w[1]==="/"){G.push("/");break}}}else if(X===3){if(w==="/.."){if(G.length!==0)G.pop();G.push("/");break}}if(w[0]==="."){if(w[1]==="."){if(w[2]==="/"){w=w.slice(3);continue}}else if(w[1]==="/"){w=w.slice(2);continue}}else if(w[0]==="/"){if(w[1]==="."){if(w[2]==="/"){w=w.slice(2);continue}else if(w[2]==="."){if(w[3]==="/"){if(w=w.slice(3),G.length!==0)G.pop();continue}}}}if((Z=w.indexOf("/",1))===-1){G.push(w);break}else G.push(w.slice(0,Z)),w=w.slice(Z)}return G.join("")}var nO={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},rO=/[@/?#:]/g,sO=/[@/?#]/g;function LT($,w){let G=w?sO:rO;return G.lastIndex=0,$.replace(G,(Z)=>nO[Z])}function DT($,w=!1){if($.indexOf("%")===-1)return $;let G="";for(let Z=0;Z<$.length;Z++){if($[Z]==="%"&&Z+2<$.length){let X=$.slice(Z+1,Z+3);if(C1(X)){let Y=X.toUpperCase(),J=String.fromCharCode(parseInt(Y,16));if(w&&BZ(J))G+=J;else G+="%"+Y;Z+=2;continue}}G+=$[Z]}return G}function aO($){let w="";for(let G=0;G<$.length;G++){let Z=$[G];if(Z==="%"&&G+2<$.length){let X=$.slice(G+1,G+3);if(C1(X)){let Y=X.toUpperCase(),J=String.fromCharCode(parseInt(Y,16));if(J!=="."&&BZ(J))w+=J;else w+="%"+Y;G+=2;continue}}if(fT(Z))w+=Z;else{let X=$.charCodeAt(G);if(X<128)w+=AT(X)?Z:C0[X];else if(X<55296||X>57343)w+=O0(X);else if(X<=56319&&G+1<$.length){let Y=$.charCodeAt(G+1);if(Y>=56320&&Y<=57343)w+=O0(65536+(X-55296<<10)+(Y-56320)),G++;else w+=O0(65533)}else w+=O0(65533)}}return w}function tO($,w=!1){let G="",Z=w&&$[0]!=="/";for(let X=0;X<$.length;X++){let Y=$[X];if(Y==="%"&&X+2<$.length){let J=$.slice(X+1,X+3);if(C1(J)){G+="%"+J.toUpperCase(),X+=2;continue}}if(Y==="/")Z=!1;if(fT(Y)&&(Y!==":"||!Z))G+=Y;else{let J=$.charCodeAt(X);if(J<128)G+=C0[J];else if(J<55296||J>57343)G+=O0(J);else if(J<=56319&&X+1<$.length){let W=$.charCodeAt(X+1);if(W>=56320&&W<=57343)G+=O0(65536+(J-55296<<10)+(W-56320)),X++;else G+=O0(65533)}else G+=O0(65533)}}return G}function VZ($,w){let G="";for(let Z=0;Z<$.length;Z++){let X=$[Z];if(X==="%"&&Z+2<$.length){let Y=$.slice(Z+1,Z+3);if(C1(Y)){G+="%"+Y.toUpperCase(),Z+=2;continue}}if(w(X))G+=X;else{let Y=$.charCodeAt(Z);if(Y<128)G+=C0[Y];else if(Y<55296||Y>57343)G+=O0(Y);else if(Y<=56319&&Z+1<$.length){let J=$.charCodeAt(Z+1);if(J>=56320&&J<=57343)G+=O0(65536+(Y-55296<<10)+(J-56320)),Z++;else G+=O0(65533)}else G+=O0(65533)}}return G}function ET($){return VZ($,gO)}function oO($){return VZ($,NZ)}function eO($){return VZ($,NZ)}function AT($){return $>=48&&$<=57||$>=65&&$<=90||$>=97&&$<=122||$===42||$===43||$===45||$===46||$===47||$===64||$===95}function $f($){let w="";for(let G=0;G<$.length;G++){let Z=$[G];if(Z==="%"&&G+2<$.length){let X=$.slice(G+1,G+3);if(C1(X)){let Y=X.toUpperCase(),J=String.fromCharCode(parseInt(Y,16));if(BZ(J))w+=J;else w+="%"+Y;G+=2;continue}}if(NZ(Z))w+=Z;else{let X=$.charCodeAt(G);if(X<128)w+=AT(X)?Z:C0[X];else if(X<55296||X>57343)w+=O0(X);else if(X<=56319&&G+1<$.length){let Y=$.charCodeAt(G+1);if(Y>=56320&&Y<=57343)w+=O0(65536+(X-55296<<10)+(Y-56320)),G++;else w+=O0(65533)}else w+=O0(65533)}}return w}function wf($){let w="";for(let G=0;G<$.length;G++){if($[G]==="%"&&G+2<$.length){let Z=$.slice(G+1,G+3);if(C1(Z)){w+="%"+Z.toUpperCase(),G+=2;continue}}w+=escape($[G])}return w}function Gf($){let w=[];if($.userinfo!==void 0)w.push(ET($.userinfo)),w.push("@");if($.host!==void 0){let G=$.host;if(!qZ(G)){let Z=PZ(G);if(Z.isIPV6!==!0&&Z.isIPVFuture!==!0)G=DT(G,!0),Z=PZ(G);if(Z.isIPV6===!0||Z.isIPVFuture===!0)G=`[${Z.escapedHost}]`;else G=LT(G,!1)}w.push(G)}if(typeof $.port==="number"||typeof $.port==="string")w.push(":"),w.push(String($.port));return w.length?w.join(""):void 0}RT.exports={nonSimpleDomain:mO,recomposeAuthority:Gf,reescapeHostDelimiters:LT,normalizePercentEncoding:DT,normalizePathEncoding:aO,serializePathEncoding:tO,normalizeQueryFragmentEncoding:$f,encodeUserinfo:ET,encodeQuery:oO,encodeFragment:eO,escapePreservingEscapes:wf,removeDotSegments:pO,isIPv4:qZ,isUUID:xO,normalizeIPv6:PZ,stringArrayToHexStripped:uO}});var bT=F((nv,CT)=>{var{isUUID:Zf}=KZ(),Xf=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,Yf=["http","https","ws","wss","urn","urn:uuid"];function Jf($){return Yf.indexOf($)!==-1}function UZ($){if($.secure===!0)return!0;else if($.secure===!1)return!1;else if($.scheme)return $.scheme.length===3&&($.scheme[0]==="w"||$.scheme[0]==="W")&&($.scheme[1]==="s"||$.scheme[1]==="S")&&($.scheme[2]==="s"||$.scheme[2]==="S");else return!1}function ST($){if(!$.host)$.error=$.error||"HTTP URIs must have a host.";return $}function IT($){let w=String($.scheme).toLowerCase()==="https";if($.port===(w?443:80)||$.port==="")$.port=void 0;if(!$.path)$.path="/";return $}function Wf($){return $.secure=UZ($),$.resourceName=($.path||"/")+($.query?"?"+$.query:""),$.path=void 0,$.query=void 0,$}function Tf($){if($.port===(UZ($)?443:80)||$.port==="")$.port=void 0;if(typeof $.secure==="boolean")$.scheme=$.secure?"wss":"ws",$.secure=void 0;if($.resourceName){let w=$.resourceName.indexOf("?"),G=w===-1?$.resourceName:$.resourceName.slice(0,w);$.path=G&&G!=="/"?G:void 0,$.query=w===-1?void 0:$.resourceName.slice(w+1),$.resourceName=void 0}return $.fragment=void 0,$}function Qf($,w){if(!$.path)return $.error="URN can not be parsed",$;let G=$.path.match(Xf);if(G&&G[0]===$.path){let Z=w.scheme||$.scheme||"urn";$.nid=G[1].toLowerCase(),$.nss=G[2];let X=`${Z}:${w.nid||$.nid}`,Y=HZ(X);if($.path=void 0,Y)$=Y.parse($,w)}else $.error=$.error||"URN can not be parsed.";return $}function zf($,w){if($.nid===void 0)throw Error("URN without nid cannot be serialized");let G=w.scheme||$.scheme||"urn",Z=$.nid.toLowerCase(),X=`${G}:${w.nid||Z}`,Y=HZ(X);if(Y)$=Y.serialize($,w);let J=$,W=$.nss;return J.path=`${Z||w.nid}:${W}`,w.skipEscape=!0,J}function Mf($,w){let G=$;if(G.uuid=G.nss,G.nss=void 0,!w.tolerant&&(!G.uuid||!Zf(G.uuid)))G.error=G.error||"UUID is not valid.";return G}function Pf($){let w=$;return w.nss=($.uuid||"").toLowerCase(),w}var jT={scheme:"http",domainHost:!0,parse:ST,serialize:IT},qf={scheme:"https",domainHost:jT.domainHost,parse:ST,serialize:IT},i6={scheme:"ws",domainHost:!0,parse:Wf,serialize:Tf},Bf={scheme:"wss",domainHost:i6.domainHost,parse:i6.parse,serialize:i6.serialize},Nf={scheme:"urn",parse:Qf,serialize:zf,skipNormalize:!0},Vf={scheme:"urn:uuid",parse:Mf,serialize:Pf,skipNormalize:!0},m6={http:jT,https:qf,ws:i6,wss:Bf,urn:Nf,"urn:uuid":Vf};Object.setPrototypeOf(m6,null);function HZ($){return $&&(m6[$]||m6[$.toLowerCase()])||void 0}CT.exports={wsIsSecure:UZ,SCHEMES:m6,isValidSchemeName:Jf,getSchemeHandler:HZ}});var cT=F((rv,c6)=>{var{normalizeIPv6:gT,removeDotSegments:r4,recomposeAuthority:Kf,normalizePercentEncoding:uT,normalizePathEncoding:Uf,serializePathEncoding:kT,normalizeQueryFragmentEncoding:yT,encodeQuery:Hf,encodeFragment:Ff,reescapeHostDelimiters:Of,isIPv4:hT,nonSimpleDomain:ff}=KZ(),{SCHEMES:vT,getSchemeHandler:FZ}=bT(),iT=/^[A-Za-z][A-Za-z0-9+.-]*$/u;function _T($){let w=unescape(String($));if(!iT.test(w))throw TypeError("URI scheme is malformed.");return w}function Lf($,w){if(typeof $==="string")$=Cf($,w);else if(typeof $==="object")$=d6(b1($,w),w);return $}function Df($,w,G){let Z=G?Object.assign({scheme:"null"},G):{scheme:"null"},{parsed:X,malformedAuthorityOrPort:Y,malformedPercentEncoding:J,malformedSchemeSpecific:W,malformedHost:T,malformedScheme:Q}=l6($,Z),{parsed:z,malformedAuthorityOrPort:M,malformedPercentEncoding:P,malformedSchemeSpecific:q,malformedHost:N,malformedScheme:B}=l6(w,Z);if(Y||M||J||P||W||q||T||N||Q||B)throw Error(X.error||z.error||"URI is malformed.");let V=mT(X,z,Z,!0),K=FZ(G&&G.scheme||V.scheme),U=V.host,O=U!==void 0&&U!==""&&(hT(U)||gT(U).isIPV6);lT(V,G||{},K,O);let D=U&&U.indexOf("%")!==-1&&!/\P{ASCII}/u.test(U);if(V.error&&!D)throw Error(V.error);return Z.skipEscape=!0,b1(V,Z)}function mT($,w,G,Z){let X={};if(!Z)$=d6(b1($,G),G),w=d6(b1(w,G),G);if(G=G||{},!G.tolerant&&w.scheme)X.scheme=w.scheme,X.userinfo=w.userinfo,X.host=w.host,X.port=w.port,X.path=r4(w.path||""),X.query=w.query;else{if(w.userinfo!==void 0||w.host!==void 0||w.port!==void 0)X.userinfo=w.userinfo,X.host=w.host,X.port=w.port,X.path=r4(w.path||""),X.query=w.query;else{if(!w.path)if(X.path=$.path,w.query!==void 0)X.query=w.query;else X.query=$.query;else{if(w.path[0]==="/")X.path=r4(w.path);else{if(($.userinfo!==void 0||$.host!==void 0||$.port!==void 0)&&!$.path)X.path="/"+w.path;else if(!$.path)X.path=w.path;else X.path=$.path.slice(0,$.path.lastIndexOf("/")+1)+w.path;X.path=r4(X.path)}X.query=w.query}X.userinfo=$.userinfo,X.host=$.host,X.port=$.port}X.scheme=$.scheme}return X.fragment=w.fragment,X}function Ef($,w,G){let Z=xT($,G),X=xT(w,G);return Z!==void 0&&X!==void 0&&Z===X}function b1($,w){let G={host:$.host,scheme:$.scheme,userinfo:$.userinfo,port:$.port,path:$.path,query:$.query,nid:$.nid,nss:$.nss,uuid:$.uuid,fragment:$.fragment,reference:$.reference,resourceName:$.resourceName,secure:$.secure,error:""},Z=Object.assign({},w),X=[];if(G.scheme)G.scheme=_T(G.scheme);let Y=FZ(Z.scheme||G.scheme);if(Y&&Y.serialize)Y.serialize(G,Z);let J=G.userinfo!==void 0||G.host!==void 0||G.port!==void 0,W=!Z.skipEscape&&G.scheme===void 0&&!J;if(G.path!==void 0)if(!Z.skipEscape)G.path=kT(G.path,W);else G.path=uT(G.path);if(Z.reference!=="suffix"&&G.scheme)G.scheme=_T(G.scheme),X.push(G.scheme,":");let T=Kf(G);if(T!==void 0){if(Z.reference!=="suffix")X.push("//");if(X.push(T),G.path&&G.path[0]!=="/")X.push("/")}if(G.path!==void 0){let Q=G.path;if(!Z.absolutePath&&(!Y||!Y.absolutePath))Q=r4(Q);if(W)Q=kT(Q,!0);if(T===void 0&&Q[0]==="/"&&Q[1]==="/")Q="/%2F"+Q.slice(2);X.push(Q)}if(G.query!==void 0)X.push("?",Hf(G.query));if(G.fragment!==void 0)X.push("#",Ff(G.fragment));return X.join("")}var Af=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,Rf=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,Sf=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function If($,w){if(w[2]!==void 0&&$.path&&$.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof $.port==="number"&&($.port<0||$.port>65535))return"URI port is malformed.";return}function n4($){if($===void 0)return!1;let w=$.indexOf("%");while(w!==-1){if(w+2>=$.length||!/^[\da-f]{2}$/iu.test($.slice(w+1,w+3)))return!0;w=$.indexOf("%",w+3)}return!1}function jf($){let w=$[4];return n4($[3])||w!==void 0&&!(w[0]==="["&&w[w.length-1]==="]")&&n4(w)||n4($[6])||n4($[7])||n4($[8])}function lT($,w,G,Z){if(!w.unicodeSupport&&(!G||!G.unicodeSupport)&&$.host&&$.host[0]!=="["&&(w.domainHost||G&&G.domainHost)&&Z===!1&&ff($.host))try{$.host=new URL("http://"+$.host).hostname}catch(X){return $.error=$.error||"Host's domain name can not be converted to ASCII: "+X,!0}return!1}function l6($,w){let G=Object.assign({},w),Z={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},X=!1,Y=!1,J=!1,W=!1,T=!1,Q=!1,z=!1;if(G.reference==="suffix")if(G.scheme)$=G.scheme+":"+$;else $="//"+$;let M=$.match(Rf);if(M!==null&&M[1].indexOf("\\")!==-1)Z.error="URI authority must not contain a literal backslash.",X=!0;let P=$.match(Sf);if(P!==null){let N=P[1],B=N.replace(/[\t\n\r]/g,"");if(B.length>=2){if(B.slice(0,2)!=="//")Z.error=Z.error||"URI authority must not contain a literal backslash.",X=!0;else if(N.length!==B.length)Z.error=Z.error||"URI authority introducer must not contain whitespace.",X=!0}}let q=$.match(Af);if(q){if(Z.scheme=q[1],Z.userinfo=q[3],Z.host=q[4],Z.port=parseInt(q[5],10),Z.path=q[6]||"",Z.query=q[7],Z.fragment=q[8],Z.scheme!==void 0){let V=unescape(Z.scheme);if(iT.test(V))Z.scheme=V.toLowerCase();else Z.error=Z.error||"URI scheme is malformed.",Q=!0}if(Y=jf(q),Y)Z.error=Z.error||"URI contains malformed percent-encoding.";if(isNaN(Z.port))Z.port=q[5];let N=If(Z,q);if(N!==void 0)Z.error=Z.error||N,X=!0;if(Z.host)if(hT(Z.host)===!1){let K=Z.host[0]==="["&&Z.host[Z.host.length-1]==="]",U=gT(Z.host);if(z=U.isIPV6||U.isIPVFuture===!0,T=K&&U.error===!0,Z.host=z?U.host:U.host.toLowerCase(),T)Z.error=Z.error||"URI host is malformed.",X=!0}else z=!0;if(Z.scheme===void 0&&Z.userinfo===void 0&&Z.host===void 0&&Z.port===void 0&&Z.query===void 0&&!Z.path)Z.reference="same-document";else if(Z.scheme===void 0)Z.reference="relative";else if(Z.fragment===void 0)Z.reference="absolute";else Z.reference="uri";if(G.reference&&G.reference!=="suffix"&&G.reference!==Z.reference)Z.error=Z.error||"URI is not a "+G.reference+" reference.";let B=FZ(G.scheme||Z.scheme);if(W=lT(Z,G,B,z),!B||B&&!B.skipNormalize){if($.indexOf("%")!==-1){if(Z.host!==void 0&&!T){let V=z?Z.host:uT(Z.host,!0);Z.host=Of(V,z)}}if(Z.path)Z.path=Uf(Z.path);if(Z.query)Z.query=yT(Z.query);if(Z.fragment)Z.fragment=yT(Z.fragment)}if(B&&B.parse){if(B.parse(Z,G),B===vT.urn&&Z.nid===void 0)J=!0}}else Z.error=Z.error||"URI can not be parsed.";return{parsed:Z,malformedAuthorityOrPort:X,malformedPercentEncoding:Y,malformedSchemeSpecific:J,malformedHost:W,malformedScheme:Q}}function d6($,w){return l6($,w).parsed}function Cf($,w){return dT($,w).normalized}function dT($,w){let{parsed:G,malformedAuthorityOrPort:Z,malformedPercentEncoding:X,malformedSchemeSpecific:Y,malformedHost:J,malformedScheme:W}=l6($,w);return{normalized:Z||X||Y||J||W?$:b1(G,w),malformedAuthorityOrPort:Z,malformedPercentEncoding:X,malformedSchemeSpecific:Y,malformedHost:J,malformedScheme:W}}function xT($,w){if(typeof $!=="string"&&typeof $!=="object")return;let G;try{G=typeof $==="string"?$:b1($,w)}catch{return}let{normalized:Z,malformedAuthorityOrPort:X,malformedPercentEncoding:Y,malformedSchemeSpecific:J,malformedHost:W,malformedScheme:T}=dT(G,w);return X||Y||J||W||T?void 0:Z}var OZ={SCHEMES:vT,normalize:Lf,resolve:Df,resolveComponent:mT,equal:Ef,serialize:b1,parse:d6};c6.exports=OZ;c6.exports.default=OZ;c6.exports.fastUri=OZ});var rT=F((nT)=>{Object.defineProperty(nT,"__esModule",{value:!0});var pT=cT();pT.code='require("ajv/dist/runtime/uri").default';nT.default=pT});var GQ=F((I$)=>{Object.defineProperty(I$,"__esModule",{value:!0});I$.CodeGen=I$.Name=I$.nil=I$.stringify=I$.str=I$._=I$.KeywordCxt=void 0;var kf=d4();Object.defineProperty(I$,"KeywordCxt",{enumerable:!0,get:function(){return kf.KeywordCxt}});var bw=l();Object.defineProperty(I$,"_",{enumerable:!0,get:function(){return bw._}});Object.defineProperty(I$,"str",{enumerable:!0,get:function(){return bw.str}});Object.defineProperty(I$,"stringify",{enumerable:!0,get:function(){return bw.stringify}});Object.defineProperty(I$,"nil",{enumerable:!0,get:function(){return bw.nil}});Object.defineProperty(I$,"Name",{enumerable:!0,get:function(){return bw.Name}});Object.defineProperty(I$,"CodeGen",{enumerable:!0,get:function(){return bw.CodeGen}});var yf=u6(),eT=c4(),_f=s3(),s4=v6(),xf=l(),a4=i4(),p6=v4(),LZ=p(),sT=FT(),gf=rT(),$Q=($,w)=>new RegExp($,w);$Q.code="new RegExp";var uf=["removeAdditional","useDefaults","coerceTypes"],hf=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),vf={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},mf={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},aT=200;function lf($){var w,G,Z,X,Y,J,W,T,Q,z,M,P,q,N,B,V,K,U,O,D,f,L,C,S,h;let g=$.strict,G0=(w=$.code)===null||w===void 0?void 0:w.optimize,e=G0===!0||G0===void 0?1:G0||0,c0=(Z=(G=$.code)===null||G===void 0?void 0:G.regExp)!==null&&Z!==void 0?Z:$Q,fw=(X=$.uriResolver)!==null&&X!==void 0?X:gf.default;return{strictSchema:(J=(Y=$.strictSchema)!==null&&Y!==void 0?Y:g)!==null&&J!==void 0?J:!0,strictNumbers:(T=(W=$.strictNumbers)!==null&&W!==void 0?W:g)!==null&&T!==void 0?T:!0,strictTypes:(z=(Q=$.strictTypes)!==null&&Q!==void 0?Q:g)!==null&&z!==void 0?z:"log",strictTuples:(P=(M=$.strictTuples)!==null&&M!==void 0?M:g)!==null&&P!==void 0?P:"log",strictRequired:(N=(q=$.strictRequired)!==null&&q!==void 0?q:g)!==null&&N!==void 0?N:!1,code:$.code?{...$.code,optimize:e,regExp:c0}:{optimize:e,regExp:c0},loopRequired:(B=$.loopRequired)!==null&&B!==void 0?B:aT,loopEnum:(V=$.loopEnum)!==null&&V!==void 0?V:aT,meta:(K=$.meta)!==null&&K!==void 0?K:!0,messages:(U=$.messages)!==null&&U!==void 0?U:!0,inlineRefs:(O=$.inlineRefs)!==null&&O!==void 0?O:!0,schemaId:(D=$.schemaId)!==null&&D!==void 0?D:"$id",addUsedSchema:(f=$.addUsedSchema)!==null&&f!==void 0?f:!0,validateSchema:(L=$.validateSchema)!==null&&L!==void 0?L:!0,validateFormats:(C=$.validateFormats)!==null&&C!==void 0?C:!0,unicodeRegExp:(S=$.unicodeRegExp)!==null&&S!==void 0?S:!0,int32range:(h=$.int32range)!==null&&h!==void 0?h:!0,uriResolver:fw}}class n6{constructor($={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,$=this.opts={...$,...lf($)};let{es5:w,lines:G}=this.opts.code;this.scope=new xf.ValueScope({scope:{},prefixes:hf,es5:w,lines:G}),this.logger=sf($.logger);let Z=$.validateFormats;if($.validateFormats=!1,this.RULES=(0,_f.getRules)(),tT.call(this,vf,$,"NOT SUPPORTED"),tT.call(this,mf,$,"DEPRECATED","warn"),this._metaOpts=nf.call(this),$.formats)cf.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),$.keywords)pf.call(this,$.keywords);if(typeof $.meta=="object")this.addMetaSchema($.meta);df.call(this),$.validateFormats=Z}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:$,meta:w,schemaId:G}=this.opts,Z=sT;if(G==="id")Z={...sT},Z.id=Z.$id,delete Z.$id;if(w&&$)this.addMetaSchema(Z,Z[G],!1)}defaultMeta(){let{meta:$,schemaId:w}=this.opts;return this.opts.defaultMeta=typeof $=="object"?$[w]||$:void 0}validate($,w){let G;if(typeof $=="string"){if(G=this.getSchema($),!G)throw Error(`no schema with key or ref "${$}"`)}else G=this.compile($);let Z=G(w);if(!("$async"in G))this.errors=G.errors;return Z}compile($,w){let G=this._addSchema($,w);return G.validate||this._compileSchemaEnv(G)}compileAsync($,w){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema:G}=this.opts;return Z.call(this,$,w);async function Z(Q,z){await X.call(this,Q.$schema);let M=this._addSchema(Q,z);return M.validate||Y.call(this,M)}async function X(Q){if(Q&&!this.getSchema(Q))await Z.call(this,{$ref:Q},!0)}async function Y(Q){try{return this._compileSchemaEnv(Q)}catch(z){if(!(z instanceof eT.default))throw z;return J.call(this,z),await W.call(this,z.missingSchema),Y.call(this,Q)}}function J({missingSchema:Q,missingRef:z}){if(this.refs[Q])throw Error(`AnySchema ${Q} is loaded but ${z} cannot be resolved`)}async function W(Q){let z=await T.call(this,Q);if(!this.refs[Q])await X.call(this,z.$schema);if(!this.refs[Q])this.addSchema(z,Q,w)}async function T(Q){let z=this._loading[Q];if(z)return z;try{return await(this._loading[Q]=G(Q))}finally{delete this._loading[Q]}}}addSchema($,w,G,Z=this.opts.validateSchema){if(Array.isArray($)){for(let Y of $)this.addSchema(Y,void 0,G,Z);return this}let X;if(typeof $==="object"){let{schemaId:Y}=this.opts;if(X=$[Y],X!==void 0&&typeof X!="string")throw Error(`schema ${Y} must be string`)}return w=(0,a4.normalizeId)(w||X),this._checkUnique(w),this.schemas[w]=this._addSchema($,G,w,Z,!0),this}addMetaSchema($,w,G=this.opts.validateSchema){return this.addSchema($,w,!0,G),this}validateSchema($,w){if(typeof $=="boolean")return!0;let G;if(G=$.$schema,G!==void 0&&typeof G!="string")throw Error("$schema must be a string");if(G=G||this.opts.defaultMeta||this.defaultMeta(),!G)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let Z=this.validate(G,$);if(!Z&&w){let X="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(X);else throw Error(X)}return Z}getSchema($){let w;while(typeof(w=oT.call(this,$))=="string")$=w;if(w===void 0){let{schemaId:G}=this.opts,Z=new s4.SchemaEnv({schema:{},schemaId:G});if(w=s4.resolveSchema.call(this,Z,$),!w)return;this.refs[$]=w}return w.validate||this._compileSchemaEnv(w)}removeSchema($){if($ instanceof RegExp)return this._removeAllSchemas(this.schemas,$),this._removeAllSchemas(this.refs,$),this;switch(typeof $){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let w=oT.call(this,$);if(typeof w=="object")this._cache.delete(w.schema);return delete this.schemas[$],delete this.refs[$],this}case"object":{let w=$;this._cache.delete(w);let G=$[this.opts.schemaId];if(G)G=(0,a4.normalizeId)(G),delete this.schemas[G],delete this.refs[G];return this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary($){for(let w of $)this.addKeyword(w);return this}addKeyword($,w){let G;if(typeof $=="string"){if(G=$,typeof w=="object")this.logger.warn("these parameters are deprecated, see docs for addKeyword"),w.keyword=G}else if(typeof $=="object"&&w===void 0){if(w=$,G=w.keyword,Array.isArray(G)&&!G.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(tf.call(this,G,w),!w)return(0,LZ.eachItem)(G,(X)=>fZ.call(this,X)),this;ef.call(this,w);let Z={...w,type:(0,p6.getJSONTypes)(w.type),schemaType:(0,p6.getJSONTypes)(w.schemaType)};return(0,LZ.eachItem)(G,Z.type.length===0?(X)=>fZ.call(this,X,Z):(X)=>Z.type.forEach((Y)=>fZ.call(this,X,Z,Y))),this}getKeyword($){let w=this.RULES.all[$];return typeof w=="object"?w.definition:!!w}removeKeyword($){let{RULES:w}=this;delete w.keywords[$],delete w.all[$];for(let G of w.rules){let Z=G.rules.findIndex((X)=>X.keyword===$);if(Z>=0)G.rules.splice(Z,1)}return this}addFormat($,w){if(typeof w=="string")w=new RegExp(w);return this.formats[$]=w,this}errorsText($=this.errors,{separator:w=", ",dataVar:G="data"}={}){if(!$||$.length===0)return"No errors";return $.map((Z)=>`${G}${Z.instancePath} ${Z.message}`).reduce((Z,X)=>Z+w+X)}$dataMetaSchema($,w){let G=this.RULES.all;$=JSON.parse(JSON.stringify($));for(let Z of w){let X=Z.split("/").slice(1),Y=$;for(let J of X)Y=Y[J];for(let J in G){let W=G[J];if(typeof W!="object")continue;let{$data:T}=W.definition,Q=Y[J];if(T&&Q)Y[J]=wQ(Q)}}return $}_removeAllSchemas($,w){for(let G in $){let Z=$[G];if(!w||w.test(G)){if(typeof Z=="string")delete $[G];else if(Z&&!Z.meta)this._cache.delete(Z.schema),delete $[G]}}}_addSchema($,w,G,Z=this.opts.validateSchema,X=this.opts.addUsedSchema){let Y,{schemaId:J}=this.opts;if(typeof $=="object")Y=$[J];else if(this.opts.jtd)throw Error("schema must be object");else if(typeof $!="boolean")throw Error("schema must be object or boolean");let W=this._cache.get($);if(W!==void 0)return W;G=(0,a4.normalizeId)(Y||G);let T=a4.getSchemaRefs.call(this,$,G);if(W=new s4.SchemaEnv({schema:$,schemaId:J,meta:w,baseId:G,localRefs:T}),this._cache.set(W.schema,W),X&&!G.startsWith("#")){if(G)this._checkUnique(G);this.refs[G]=W}if(Z)this.validateSchema($,!0);return W}_checkUnique($){if(this.schemas[$]||this.refs[$])throw Error(`schema with key or id "${$}" already exists`)}_compileSchemaEnv($){if($.meta)this._compileMetaSchema($);else s4.compileSchema.call(this,$);if(!$.validate)throw Error("ajv implementation error");return $.validate}_compileMetaSchema($){let w=this.opts;this.opts=this._metaOpts;try{s4.compileSchema.call(this,$)}finally{this.opts=w}}}n6.ValidationError=yf.default;n6.MissingRefError=eT.default;I$.default=n6;function tT($,w,G,Z="error"){for(let X in $){let Y=X;if(Y in w)this.logger[Z](`${G}: option ${X}. ${$[Y]}`)}}function oT($){return $=(0,a4.normalizeId)($),this.schemas[$]||this.refs[$]}function df(){let $=this.opts.schemas;if(!$)return;if(Array.isArray($))this.addSchema($);else for(let w in $)this.addSchema($[w],w)}function cf(){for(let $ in this.opts.formats){let w=this.opts.formats[$];if(w)this.addFormat($,w)}}function pf($){if(Array.isArray($)){this.addVocabulary($);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let w in $){let G=$[w];if(!G.keyword)G.keyword=w;this.addKeyword(G)}}function nf(){let $={...this.opts};for(let w of uf)delete $[w];return $}var rf={log(){},warn(){},error(){}};function sf($){if($===!1)return rf;if($===void 0)return console;if($.log&&$.warn&&$.error)return $;throw Error("logger must implement log, warn and error methods")}var af=/^[a-z_$][a-z0-9_$:-]*$/i;function tf($,w){let{RULES:G}=this;if((0,LZ.eachItem)($,(Z)=>{if(G.keywords[Z])throw Error(`Keyword ${Z} is already defined`);if(!af.test(Z))throw Error(`Keyword ${Z} has invalid name`)}),!w)return;if(w.$data&&!(("code"in w)||("validate"in w)))throw Error('$data keyword must have "code" or "validate" function')}function fZ($,w,G){var Z;let X=w===null||w===void 0?void 0:w.post;if(G&&X)throw Error('keyword with "post" flag cannot have "type"');let{RULES:Y}=this,J=X?Y.post:Y.rules.find(({type:T})=>T===G);if(!J)J={type:G,rules:[]},Y.rules.push(J);if(Y.keywords[$]=!0,!w)return;let W={keyword:$,definition:{...w,type:(0,p6.getJSONTypes)(w.type),schemaType:(0,p6.getJSONTypes)(w.schemaType)}};if(w.before)of.call(this,J,W,w.before);else J.rules.push(W);Y.all[$]=W,(Z=w.implements)===null||Z===void 0||Z.forEach((T)=>this.addKeyword(T))}function of($,w,G){let Z=$.rules.findIndex((X)=>X.keyword===G);if(Z>=0)$.rules.splice(Z,0,w);else $.rules.push(w),this.logger.warn(`rule ${G} is not defined`)}function ef($){let{metaSchema:w}=$;if(w===void 0)return;if($.$data&&this.opts.$data)w=wQ(w);$.validateSchema=this.compile(w,!0)}var $L={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function wQ($){return{anyOf:[$,$L]}}});var XQ=F((ZQ)=>{Object.defineProperty(ZQ,"__esModule",{value:!0});var ZL={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};ZQ.default=ZL});var zQ=F((TQ)=>{Object.defineProperty(TQ,"__esModule",{value:!0});TQ.callRef=TQ.getValidate=void 0;var YL=c4(),YQ=n0(),b0=l(),kw=R$(),JQ=v6(),r6=p(),JL={keyword:"$ref",schemaType:"string",code($){let{gen:w,schema:G,it:Z}=$,{baseId:X,schemaEnv:Y,validateName:J,opts:W,self:T}=Z,{root:Q}=Y;if((G==="#"||G==="#/")&&X===Q.baseId)return M();let z=JQ.resolveRef.call(T,Q,X,G);if(z===void 0)throw new YL.default(Z.opts.uriResolver,X,G);if(z instanceof JQ.SchemaEnv)return P(z);return q(z);function M(){if(Y===Q)return s6($,J,Y,Y.$async);let N=w.scopeValue("root",{ref:Q});return s6($,b0._`${N}.validate`,Q,Q.$async)}function P(N){let B=WQ($,N);s6($,B,N,N.$async)}function q(N){let B=w.scopeValue("schema",W.code.source===!0?{ref:N,code:(0,b0.stringify)(N)}:{ref:N}),V=w.name("valid"),K=$.subschema({schema:N,dataTypes:[],schemaPath:b0.nil,topSchemaRef:B,errSchemaPath:G},V);$.mergeEvaluated(K),$.ok(V)}}};function WQ($,w){let{gen:G}=$;return w.validate?G.scopeValue("validate",{ref:w.validate}):b0._`${G.scopeValue("wrapper",{ref:w})}.validate`}TQ.getValidate=WQ;function s6($,w,G,Z){let{gen:X,it:Y}=$,{allErrors:J,schemaEnv:W,opts:T}=Y,Q=T.passContext?kw.default.this:b0.nil;if(Z)z();else M();function z(){if(!W.$async)throw Error("async schema referenced by sync schema");let N=X.let("valid");X.try(()=>{if(X.code(b0._`await ${(0,YQ.callValidateCode)($,w,Q)}`),q(w),!J)X.assign(N,!0)},(B)=>{if(X.if(b0._`!(${B} instanceof ${Y.ValidationError})`,()=>X.throw(B)),P(B),!J)X.assign(N,!1)}),$.ok(N)}function M(){$.result((0,YQ.callValidateCode)($,w,Q),()=>q(w),()=>P(w))}function P(N){let B=b0._`${N}.errors`;X.assign(kw.default.vErrors,b0._`${kw.default.vErrors} === null ? ${B} : ${kw.default.vErrors}.concat(${B})`),X.assign(kw.default.errors,b0._`${kw.default.vErrors}.length`)}function q(N){var B;if(!Y.opts.unevaluated)return;let V=(B=G===null||G===void 0?void 0:G.validate)===null||B===void 0?void 0:B.evaluated;if(Y.props!==!0)if(V&&!V.dynamicProps){if(V.props!==void 0)Y.props=r6.mergeEvaluated.props(X,V.props,Y.props)}else{let K=X.var("props",b0._`${N}.evaluated.props`);Y.props=r6.mergeEvaluated.props(X,K,Y.props,b0.Name)}if(Y.items!==!0)if(V&&!V.dynamicItems){if(V.items!==void 0)Y.items=r6.mergeEvaluated.items(X,V.items,Y.items)}else{let K=X.var("items",b0._`${N}.evaluated.items`);Y.items=r6.mergeEvaluated.items(X,K,Y.items,b0.Name)}}}TQ.callRef=s6;TQ.default=JL});var PQ=F((MQ)=>{Object.defineProperty(MQ,"__esModule",{value:!0});var QL=XQ(),zL=zQ(),ML=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",QL.default,zL.default];MQ.default=ML});var BQ=F((qQ)=>{Object.defineProperty(qQ,"__esModule",{value:!0});var a6=l(),e$=a6.operators,t6={maximum:{okStr:"<=",ok:e$.LTE,fail:e$.GT},minimum:{okStr:">=",ok:e$.GTE,fail:e$.LT},exclusiveMaximum:{okStr:"<",ok:e$.LT,fail:e$.GTE},exclusiveMinimum:{okStr:">",ok:e$.GT,fail:e$.LTE}},qL={message:({keyword:$,schemaCode:w})=>a6.str`must be ${t6[$].okStr} ${w}`,params:({keyword:$,schemaCode:w})=>a6._`{comparison: ${t6[$].okStr}, limit: ${w}}`},BL={keyword:Object.keys(t6),type:"number",schemaType:"number",$data:!0,error:qL,code($){let{keyword:w,data:G,schemaCode:Z}=$;$.fail$data(a6._`${G} ${t6[w].fail} ${Z} || isNaN(${G})`)}};qQ.default=BL});var VQ=F((NQ)=>{Object.defineProperty(NQ,"__esModule",{value:!0});var t4=l(),VL={message:({schemaCode:$})=>t4.str`must be multiple of ${$}`,params:({schemaCode:$})=>t4._`{multipleOf: ${$}}`},KL={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:VL,code($){let{gen:w,data:G,schemaCode:Z,it:X}=$,Y=X.opts.multipleOfPrecision,J=w.let("res"),W=Y?t4._`Math.abs(Math.round(${J}) - ${J}) > 1e-${Y}`:t4._`${J} !== parseInt(${J})`;$.fail$data(t4._`(${Z} === 0 || (${J} = ${G}/${Z}, ${W}))`)}};NQ.default=KL});var HQ=F((UQ)=>{Object.defineProperty(UQ,"__esModule",{value:!0});function KQ($){let w=$.length,G=0,Z=0,X;while(Z<w)if(G++,X=$.charCodeAt(Z++),X>=55296&&X<=56319&&Z<w){if(X=$.charCodeAt(Z),(X&64512)===56320)Z++}return G}UQ.default=KQ;KQ.code='require("ajv/dist/runtime/ucs2length").default'});var OQ=F((FQ)=>{Object.defineProperty(FQ,"__esModule",{value:!0});var k1=l(),FL=p(),OL=HQ(),fL={message({keyword:$,schemaCode:w}){let G=$==="maxLength"?"more":"fewer";return k1.str`must NOT have ${G} than ${w} characters`},params:({schemaCode:$})=>k1._`{limit: ${$}}`},LL={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:fL,code($){let{keyword:w,data:G,schemaCode:Z,it:X}=$,Y=w==="maxLength"?k1.operators.GT:k1.operators.LT,J=X.opts.unicode===!1?k1._`${G}.length`:k1._`${(0,FL.useFunc)($.gen,OL.default)}(${G})`;$.fail$data(k1._`${J} ${Y} ${Z}`)}};FQ.default=LL});var LQ=F((fQ)=>{Object.defineProperty(fQ,"__esModule",{value:!0});var EL=n0(),AL=p(),yw=l(),RL={message:({schemaCode:$})=>yw.str`must match pattern "${$}"`,params:({schemaCode:$})=>yw._`{pattern: ${$}}`},SL={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:RL,code($){let{gen:w,data:G,$data:Z,schema:X,schemaCode:Y,it:J}=$,W=J.opts.unicodeRegExp?"u":"";if(Z){let{regExp:T}=J.opts.code,Q=T.code==="new RegExp"?yw._`new RegExp`:(0,AL.useFunc)(w,T),z=w.let("valid");w.try(()=>w.assign(z,yw._`${Q}(${Y}, ${W}).test(${G})`),()=>w.assign(z,!1)),$.fail$data(yw._`!${z}`)}else{let T=(0,EL.usePattern)($,X);$.fail$data(yw._`!${T}.test(${G})`)}}};fQ.default=SL});var EQ=F((DQ)=>{Object.defineProperty(DQ,"__esModule",{value:!0});var o4=l(),jL={message({keyword:$,schemaCode:w}){let G=$==="maxProperties"?"more":"fewer";return o4.str`must NOT have ${G} than ${w} properties`},params:({schemaCode:$})=>o4._`{limit: ${$}}`},CL={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:jL,code($){let{keyword:w,data:G,schemaCode:Z}=$,X=w==="maxProperties"?o4.operators.GT:o4.operators.LT;$.fail$data(o4._`Object.keys(${G}).length ${X} ${Z}`)}};DQ.default=CL});var RQ=F((AQ)=>{Object.defineProperty(AQ,"__esModule",{value:!0});var e4=n0(),$9=l(),kL=p(),yL={message:({params:{missingProperty:$}})=>$9.str`must have required property '${$}'`,params:({params:{missingProperty:$}})=>$9._`{missingProperty: ${$}}`},_L={keyword:"required",type:"object",schemaType:"array",$data:!0,error:yL,code($){let{gen:w,schema:G,schemaCode:Z,data:X,$data:Y,it:J}=$,{opts:W}=J;if(!Y&&G.length===0)return;let T=G.length>=W.loopRequired;if(J.allErrors)Q();else z();if(W.strictRequired){let q=$.parentSchema.properties,{definedProperties:N}=$.it;for(let B of G)if((q===null||q===void 0?void 0:q[B])===void 0&&!N.has(B)){let V=J.schemaEnv.baseId+J.errSchemaPath,K=`required property "${B}" is not defined at "${V}" (strictRequired)`;(0,kL.checkStrictMode)(J,K,J.opts.strictRequired)}}function Q(){if(T||Y)$.block$data($9.nil,M);else for(let q of G)(0,e4.checkReportMissingProp)($,q)}function z(){let q=w.let("missing");if(T||Y){let N=w.let("valid",!0);$.block$data(N,()=>P(q,N)),$.ok(N)}else w.if((0,e4.checkMissingProp)($,G,q)),(0,e4.reportMissingProp)($,q),w.else()}function M(){w.forOf("prop",Z,(q)=>{$.setParams({missingProperty:q}),w.if((0,e4.noPropertyInData)(w,X,q,W.ownProperties),()=>$.error())})}function P(q,N){$.setParams({missingProperty:q}),w.forOf(q,Z,()=>{w.assign(N,(0,e4.propertyInData)(w,X,q,W.ownProperties)),w.if((0,$9.not)(N),()=>{$.error(),w.break()})},$9.nil)}}};AQ.default=_L});var IQ=F((SQ)=>{Object.defineProperty(SQ,"__esModule",{value:!0});var w9=l(),gL={message({keyword:$,schemaCode:w}){let G=$==="maxItems"?"more":"fewer";return w9.str`must NOT have ${G} than ${w} items`},params:({schemaCode:$})=>w9._`{limit: ${$}}`},uL={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:gL,code($){let{keyword:w,data:G,schemaCode:Z}=$,X=w==="maxItems"?w9.operators.GT:w9.operators.LT;$.fail$data(w9._`${G}.length ${X} ${Z}`)}};SQ.default=uL});var o6=F((CQ)=>{Object.defineProperty(CQ,"__esModule",{value:!0});var jQ=ZZ();jQ.code='require("ajv/dist/runtime/equal").default';CQ.default=jQ});var kQ=F((bQ)=>{Object.defineProperty(bQ,"__esModule",{value:!0});var DZ=v4(),U0=l(),iL=p(),mL=o6(),lL={message:({params:{i:$,j:w}})=>U0.str`must NOT have duplicate items (items ## ${w} and ${$} are identical)`,params:({params:{i:$,j:w}})=>U0._`{i: ${$}, j: ${w}}`},dL={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:lL,code($){let{gen:w,data:G,$data:Z,schema:X,parentSchema:Y,schemaCode:J,it:W}=$;if(!Z&&!X)return;let T=w.let("valid"),Q=Y.items?(0,DZ.getSchemaTypes)(Y.items):[];$.block$data(T,z,U0._`${J} === false`),$.ok(T);function z(){let N=w.let("i",U0._`${G}.length`),B=w.let("j");$.setParams({i:N,j:B}),w.assign(T,!0),w.if(U0._`${N} > 1`,()=>(M()?P:q)(N,B))}function M(){return Q.length>0&&!Q.some((N)=>N==="object"||N==="array")}function P(N,B){let V=w.name("item"),K=(0,DZ.checkDataTypes)(Q,V,W.opts.strictNumbers,DZ.DataType.Wrong),U=w.const("indices",U0._`{}`);w.for(U0._`;${N}--;`,()=>{if(w.let(V,U0._`${G}[${N}]`),w.if(K,U0._`continue`),Q.length>1)w.if(U0._`typeof ${V} == "string"`,U0._`${V} += "_"`);w.if(U0._`typeof ${U}[${V}] == "number"`,()=>{w.assign(B,U0._`${U}[${V}]`),$.error(),w.assign(T,!1).break()}).code(U0._`${U}[${V}] = ${N}`)})}function q(N,B){let V=(0,iL.useFunc)(w,mL.default),K=w.name("outer");w.label(K).for(U0._`;${N}--;`,()=>w.for(U0._`${B} = ${N}; ${B}--;`,()=>w.if(U0._`${V}(${G}[${N}], ${G}[${B}])`,()=>{$.error(),w.assign(T,!1).break(K)})))}}};bQ.default=dL});var _Q=F((yQ)=>{Object.defineProperty(yQ,"__esModule",{value:!0});var EZ=l(),pL=p(),nL=o6(),rL={message:"must be equal to constant",params:({schemaCode:$})=>EZ._`{allowedValue: ${$}}`},sL={keyword:"const",$data:!0,error:rL,code($){let{gen:w,data:G,$data:Z,schemaCode:X,schema:Y}=$;if(Z||Y&&typeof Y=="object")$.fail$data(EZ._`!${(0,pL.useFunc)(w,nL.default)}(${G}, ${X})`);else $.fail(EZ._`${Y} !== ${G}`)}};yQ.default=sL});var gQ=F((xQ)=>{Object.defineProperty(xQ,"__esModule",{value:!0});var G9=l(),tL=p(),oL=o6(),eL={message:"must be equal to one of the allowed values",params:({schemaCode:$})=>G9._`{allowedValues: ${$}}`},$D={keyword:"enum",schemaType:"array",$data:!0,error:eL,code($){let{gen:w,data:G,$data:Z,schema:X,schemaCode:Y,it:J}=$;if(!Z&&X.length===0)throw Error("enum must have non-empty array");let W=X.length>=J.opts.loopEnum,T,Q=()=>T!==null&&T!==void 0?T:T=(0,tL.useFunc)(w,oL.default),z;if(W||Z)z=w.let("valid"),$.block$data(z,M);else{if(!Array.isArray(X))throw Error("ajv implementation error");let q=w.const("vSchema",Y);z=(0,G9.or)(...X.map((N,B)=>P(q,B)))}$.pass(z);function M(){w.assign(z,!1),w.forOf("v",Y,(q)=>w.if(G9._`${Q()}(${G}, ${q})`,()=>w.assign(z,!0).break()))}function P(q,N){let B=X[N];return typeof B==="object"&&B!==null?G9._`${Q()}(${G}, ${q}[${N}])`:G9._`${G} === ${B}`}}};xQ.default=$D});var hQ=F((uQ)=>{Object.defineProperty(uQ,"__esModule",{value:!0});var GD=BQ(),ZD=VQ(),XD=OQ(),YD=LQ(),JD=EQ(),WD=RQ(),TD=IQ(),QD=kQ(),zD=_Q(),MD=gQ(),PD=[GD.default,ZD.default,XD.default,YD.default,JD.default,WD.default,TD.default,QD.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},zD.default,MD.default];uQ.default=PD});var RZ=F((iQ)=>{Object.defineProperty(iQ,"__esModule",{value:!0});iQ.validateAdditionalItems=void 0;var y1=l(),AZ=p(),BD={message:({params:{len:$}})=>y1.str`must NOT have more than ${$} items`,params:({params:{len:$}})=>y1._`{limit: ${$}}`},ND={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:BD,code($){let{parentSchema:w,it:G}=$,{items:Z}=w;if(!Array.isArray(Z)){(0,AZ.checkStrictMode)(G,'"additionalItems" is ignored when "items" is not an array of schemas');return}vQ($,Z)}};function vQ($,w){let{gen:G,schema:Z,data:X,keyword:Y,it:J}=$;J.items=!0;let W=G.const("len",y1._`${X}.length`);if(Z===!1)$.setParams({len:w.length}),$.pass(y1._`${W} <= ${w.length}`);else if(typeof Z=="object"&&!(0,AZ.alwaysValidSchema)(J,Z)){let Q=G.var("valid",y1._`${W} <= ${w.length}`);G.if((0,y1.not)(Q),()=>T(Q)),$.ok(Q)}function T(Q){G.forRange("i",w.length,W,(z)=>{if($.subschema({keyword:Y,dataProp:z,dataPropType:AZ.Type.Num},Q),!J.allErrors)G.if((0,y1.not)(Q),()=>G.break())})}}iQ.validateAdditionalItems=vQ;iQ.default=ND});var SZ=F((cQ)=>{Object.defineProperty(cQ,"__esModule",{value:!0});cQ.validateTuple=void 0;var lQ=l(),e6=p(),KD=n0(),UD={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code($){let{schema:w,it:G}=$;if(Array.isArray(w))return dQ($,"additionalItems",w);if(G.items=!0,(0,e6.alwaysValidSchema)(G,w))return;$.ok((0,KD.validateArray)($))}};function dQ($,w,G=$.schema){let{gen:Z,parentSchema:X,data:Y,keyword:J,it:W}=$;if(z(X),W.opts.unevaluated&&G.length&&W.items!==!0)W.items=e6.mergeEvaluated.items(Z,G.length,W.items);let T=Z.name("valid"),Q=Z.const("len",lQ._`${Y}.length`);G.forEach((M,P)=>{if((0,e6.alwaysValidSchema)(W,M))return;Z.if(lQ._`${Q} > ${P}`,()=>$.subschema({keyword:J,schemaProp:P,dataProp:P},T)),$.ok(T)});function z(M){let{opts:P,errSchemaPath:q}=W,N=G.length,B=N===M.minItems&&(N===M.maxItems||M[w]===!1);if(P.strictTuples&&!B){let V=`"${J}" is ${N}-tuple, but minItems or maxItems/${w} are not specified or different at path "${q}"`;(0,e6.checkStrictMode)(W,V,P.strictTuples)}}}cQ.validateTuple=dQ;cQ.default=UD});var rQ=F((nQ)=>{Object.defineProperty(nQ,"__esModule",{value:!0});var FD=SZ(),OD={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:($)=>(0,FD.validateTuple)($,"items")};nQ.default=OD});var tQ=F((aQ)=>{Object.defineProperty(aQ,"__esModule",{value:!0});var sQ=l(),LD=p(),DD=n0(),ED=RZ(),AD={message:({params:{len:$}})=>sQ.str`must NOT have more than ${$} items`,params:({params:{len:$}})=>sQ._`{limit: ${$}}`},RD={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:AD,code($){let{schema:w,parentSchema:G,it:Z}=$,{prefixItems:X}=G;if(Z.items=!0,(0,LD.alwaysValidSchema)(Z,w))return;if(X)(0,ED.validateAdditionalItems)($,X);else $.ok((0,DD.validateArray)($))}};aQ.default=RD});var eQ=F((oQ)=>{Object.defineProperty(oQ,"__esModule",{value:!0});var r0=l(),$5=p(),ID={message:({params:{min:$,max:w}})=>w===void 0?r0.str`must contain at least ${$} valid item(s)`:r0.str`must contain at least ${$} and no more than ${w} valid item(s)`,params:({params:{min:$,max:w}})=>w===void 0?r0._`{minContains: ${$}}`:r0._`{minContains: ${$}, maxContains: ${w}}`},jD={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:ID,code($){let{gen:w,schema:G,parentSchema:Z,data:X,it:Y}=$,J,W,{minContains:T,maxContains:Q}=Z;if(Y.opts.next)J=T===void 0?1:T,W=Q;else J=1;let z=w.const("len",r0._`${X}.length`);if($.setParams({min:J,max:W}),W===void 0&&J===0){(0,$5.checkStrictMode)(Y,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(W!==void 0&&J>W){(0,$5.checkStrictMode)(Y,'"minContains" > "maxContains" is always invalid'),$.fail();return}if((0,$5.alwaysValidSchema)(Y,G)){let B=r0._`${z} >= ${J}`;if(W!==void 0)B=r0._`${B} && ${z} <= ${W}`;$.pass(B);return}Y.items=!0;let M=w.name("valid");if(W===void 0&&J===1)q(M,()=>w.if(M,()=>w.break()));else if(J===0){if(w.let(M,!0),W!==void 0)w.if(r0._`${X}.length > 0`,P)}else w.let(M,!1),P();$.result(M,()=>$.reset());function P(){let B=w.name("_valid"),V=w.let("count",0);q(B,()=>w.if(B,()=>N(V)))}function q(B,V){w.forRange("i",0,z,(K)=>{$.subschema({keyword:"contains",dataProp:K,dataPropType:$5.Type.Num,compositeRule:!0},B),V()})}function N(B){if(w.code(r0._`${B}++`),W===void 0)w.if(r0._`${B} >= ${J}`,()=>w.assign(M,!0).break());else if(w.if(r0._`${B} > ${W}`,()=>w.assign(M,!1).break()),J===1)w.assign(M,!0);else w.if(r0._`${B} >= ${J}`,()=>w.assign(M,!0))}}};oQ.default=jD});var Yz=F((Gz)=>{Object.defineProperty(Gz,"__esModule",{value:!0});Gz.validateSchemaDeps=Gz.validatePropertyDeps=Gz.error=void 0;var IZ=l(),bD=p(),Z9=n0();Gz.error={message:({params:{property:$,depsCount:w,deps:G}})=>{let Z=w===1?"property":"properties";return IZ.str`must have ${Z} ${G} when property ${$} is present`},params:({params:{property:$,depsCount:w,deps:G,missingProperty:Z}})=>IZ._`{property: ${$},
33
+ missingProperty: ${Z},
34
34
  depsCount: ${w},
35
- deps: ${G}}`};var tq={keyword:"dependencies",type:"object",schemaType:"object",error:_7.error,code($){let[w,G]=rq($);b7($,w),x7($,G)}};function rq({schema:$}){let w={},G={};for(let W in $){if(W==="__proto__")continue;let Y=Array.isArray($[W])?w:G;Y[W]=$[W]}return[w,G]}function b7($,w=$.schema){let{gen:G,data:W,it:Y}=$;if(Object.keys(w).length===0)return;let Z=G.let("missing");for(let X in w){let J=w[X];if(J.length===0)continue;let T=(0,P4.propertyInData)(G,W,X,Y.opts.ownProperties);if($.setParams({property:X,depsCount:J.length,deps:J.join(", ")}),Y.allErrors)G.if(T,()=>{for(let M of J)(0,P4.checkReportMissingProp)($,M)});else G.if(DG._`${T} && (${(0,P4.checkMissingProp)($,J,Z)})`),(0,P4.reportMissingProp)($,Z),G.else()}}_7.validatePropertyDeps=b7;function x7($,w=$.schema){let{gen:G,data:W,keyword:Y,it:Z}=$,X=G.name("valid");for(let J in w){if((0,pq.alwaysValidSchema)(Z,w[J]))continue;G.if((0,P4.propertyInData)(G,W,J,Z.opts.ownProperties),()=>{let T=$.subschema({keyword:Y,schemaProp:J},X);$.mergeValidEvaluated(T,X)},()=>G.var(X,!0)),$.ok(X)}}_7.validateSchemaDeps=x7;_7.default=tq});var m7=L((i7)=>{Object.defineProperty(i7,"__esModule",{value:!0});var h7=i(),oq=c(),eq={message:"property name must be valid",params:({params:$})=>h7._`{propertyName: ${$.propertyName}}`},$E={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:eq,code($){let{gen:w,schema:G,data:W,it:Y}=$;if((0,oq.alwaysValidSchema)(Y,G))return;let Z=w.name("valid");w.forIn("key",W,(X)=>{$.setParams({propertyName:X}),$.subschema({keyword:"propertyNames",data:X,dataTypes:["string"],propertyName:X,compositeRule:!0},Z),w.if((0,h7.not)(Z),()=>{if($.error(!0),!Y.allErrors)w.break()})}),$.ok(Z)}};i7.default=$E});var kG=L((l7)=>{Object.defineProperty(l7,"__esModule",{value:!0});var h8=i0(),s0=i(),GE=B1(),i8=c(),WE={message:"must NOT have additional properties",params:({params:$})=>s0._`{additionalProperty: ${$.additionalProperty}}`},YE={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:WE,code($){let{gen:w,schema:G,parentSchema:W,data:Y,errsCount:Z,it:X}=$;if(!Z)throw Error("ajv implementation error");let{allErrors:J,opts:T}=X;if(X.props=!0,T.removeAdditional!=="all"&&(0,i8.alwaysValidSchema)(X,G))return;let M=(0,h8.allSchemaProperties)(W.properties),f=(0,h8.allSchemaProperties)(W.patternProperties);Q(),$.ok(s0._`${Z} === ${GE.default.errors}`);function Q(){w.forIn("key",Y,(q)=>{if(!M.length&&!f.length)K(q);else w.if(N(q),()=>K(q))})}function N(q){let V;if(M.length>8){let E=(0,i8.schemaRefOrVal)(X,W.properties,"properties");V=(0,h8.isOwnProperty)(w,E,q)}else if(M.length)V=(0,s0.or)(...M.map((E)=>s0._`${q} === ${E}`));else V=s0.nil;if(f.length)V=(0,s0.or)(V,...f.map((E)=>s0._`${(0,h8.usePattern)($,E)}.test(${q})`));return(0,s0.not)(V)}function z(q){w.code(s0._`delete ${Y}[${q}]`)}function K(q){if(T.removeAdditional==="all"||T.removeAdditional&&G===!1){z(q);return}if(G===!1){if($.setParams({additionalProperty:q}),$.error(),!J)w.break();return}if(typeof G=="object"&&!(0,i8.alwaysValidSchema)(X,G)){let V=w.name("valid");if(T.removeAdditional==="failing")P(q,V,!1),w.if((0,s0.not)(V),()=>{$.reset(),z(q)});else if(P(q,V),!J)w.if((0,s0.not)(V),()=>w.break())}}function P(q,V,E){let O={keyword:"additionalProperties",dataProp:q,dataPropType:i8.Type.Str};if(E===!1)Object.assign(O,{compositeRule:!0,createErrors:!1,allErrors:!1});$.subschema(O,V)}}};l7.default=YE});var p7=L((n7)=>{Object.defineProperty(n7,"__esModule",{value:!0});var XE=G4(),c7=i0(),AG=c(),d7=kG(),JE={keyword:"properties",type:"object",schemaType:"object",code($){let{gen:w,schema:G,parentSchema:W,data:Y,it:Z}=$;if(Z.opts.removeAdditional==="all"&&W.additionalProperties===void 0)d7.default.code(new XE.KeywordCxt(Z,d7.default,"additionalProperties"));let X=(0,c7.allSchemaProperties)(G);for(let Q of X)Z.definedProperties.add(Q);if(Z.opts.unevaluated&&X.length&&Z.props!==!0)Z.props=AG.mergeEvaluated.props(w,(0,AG.toHash)(X),Z.props);let J=X.filter((Q)=>!(0,AG.alwaysValidSchema)(Z,G[Q]));if(J.length===0)return;let T=w.name("valid");for(let Q of J){if(M(Q))f(Q);else{if(w.if((0,c7.propertyInData)(w,Y,Q,Z.opts.ownProperties)),f(Q),!Z.allErrors)w.else().var(T,!0);w.endIf()}$.it.definedProperties.add(Q),$.ok(T)}function M(Q){return Z.opts.useDefaults&&!Z.compositeRule&&G[Q].default!==void 0}function f(Q){$.subschema({keyword:"properties",schemaProp:Q,dataProp:Q},T)}}};n7.default=JE});var o7=L((a7)=>{Object.defineProperty(a7,"__esModule",{value:!0});var t7=i0(),m8=i(),r7=c(),s7=c(),ME={keyword:"patternProperties",type:"object",schemaType:"object",code($){let{gen:w,schema:G,data:W,parentSchema:Y,it:Z}=$,{opts:X}=Z,J=(0,t7.allSchemaProperties)(G),T=J.filter((P)=>(0,r7.alwaysValidSchema)(Z,G[P]));if(J.length===0||T.length===J.length&&(!Z.opts.unevaluated||Z.props===!0))return;let M=X.strictSchema&&!X.allowMatchingProperties&&Y.properties,f=w.name("valid");if(Z.props!==!0&&!(Z.props instanceof m8.Name))Z.props=(0,s7.evaluatedPropsToName)(w,Z.props);let{props:Q}=Z;N();function N(){for(let P of J){if(M)z(P);if(Z.allErrors)K(P);else w.var(f,!0),K(P),w.if(f)}}function z(P){for(let q in M)if(new RegExp(P).test(q))(0,r7.checkStrictMode)(Z,`property ${q} matches pattern ${P} (use allowMatchingProperties)`)}function K(P){w.forIn("key",W,(q)=>{w.if(m8._`${(0,t7.usePattern)($,P)}.test(${q})`,()=>{let V=T.includes(P);if(!V)$.subschema({keyword:"patternProperties",schemaProp:P,dataProp:q,dataPropType:s7.Type.Str},f);if(Z.opts.unevaluated&&Q!==!0)w.assign(m8._`${Q}[${q}]`,!0);else if(!V&&!Z.allErrors)w.if((0,m8.not)(f),()=>w.break())})})}}};a7.default=ME});var $J=L((e7)=>{Object.defineProperty(e7,"__esModule",{value:!0});var QE=c(),NE={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code($){let{gen:w,schema:G,it:W}=$;if((0,QE.alwaysValidSchema)(W,G)){$.fail();return}let Y=w.name("valid");$.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},Y),$.failResult(Y,()=>$.reset(),()=>$.error())},error:{message:"must NOT be valid"}};e7.default=NE});var GJ=L((wJ)=>{Object.defineProperty(wJ,"__esModule",{value:!0});var KE=i0(),PE={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:KE.validateUnion,error:{message:"must match a schema in anyOf"}};wJ.default=PE});var YJ=L((WJ)=>{Object.defineProperty(WJ,"__esModule",{value:!0});var l8=i(),VE=c(),qE={message:"must match exactly one schema in oneOf",params:({params:$})=>l8._`{passingSchemas: ${$.passing}}`},EE={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:qE,code($){let{gen:w,schema:G,parentSchema:W,it:Y}=$;if(!Array.isArray(G))throw Error("ajv implementation error");if(Y.opts.discriminator&&W.discriminator)return;let Z=G,X=w.let("valid",!1),J=w.let("passing",null),T=w.name("_valid");$.setParams({passing:J}),w.block(M),$.result(X,()=>$.reset(),()=>$.error(!0));function M(){Z.forEach((f,Q)=>{let N;if((0,VE.alwaysValidSchema)(Y,f))w.var(T,!0);else N=$.subschema({keyword:"oneOf",schemaProp:Q,compositeRule:!0},T);if(Q>0)w.if(l8._`${T} && ${X}`).assign(X,!1).assign(J,l8._`[${J}, ${Q}]`).else();w.if(T,()=>{if(w.assign(X,!0),w.assign(J,Q),N)$.mergeEvaluated(N,l8.Name)})})}}};WJ.default=EE});var XJ=L((ZJ)=>{Object.defineProperty(ZJ,"__esModule",{value:!0});var HE=c(),FE={keyword:"allOf",schemaType:"array",code($){let{gen:w,schema:G,it:W}=$;if(!Array.isArray(G))throw Error("ajv implementation error");let Y=w.name("valid");G.forEach((Z,X)=>{if((0,HE.alwaysValidSchema)(W,Z))return;let J=$.subschema({keyword:"allOf",schemaProp:X},Y);$.ok(Y),$.mergeEvaluated(J)})}};ZJ.default=FE});var fJ=L((MJ)=>{Object.defineProperty(MJ,"__esModule",{value:!0});var c8=i(),TJ=c(),LE={message:({params:$})=>c8.str`must match "${$.ifClause}" schema`,params:({params:$})=>c8._`{failingKeyword: ${$.ifClause}}`},DE={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:LE,code($){let{gen:w,parentSchema:G,it:W}=$;if(G.then===void 0&&G.else===void 0)(0,TJ.checkStrictMode)(W,'"if" without "then" and "else" is ignored');let Y=JJ(W,"then"),Z=JJ(W,"else");if(!Y&&!Z)return;let X=w.let("valid",!0),J=w.name("_valid");if(T(),$.reset(),Y&&Z){let f=w.let("ifClause");$.setParams({ifClause:f}),w.if(J,M("then",f),M("else",f))}else if(Y)w.if(J,M("then"));else w.if((0,c8.not)(J),M("else"));$.pass(X,()=>$.error(!0));function T(){let f=$.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},J);$.mergeEvaluated(f)}function M(f,Q){return()=>{let N=$.subschema({keyword:f},J);if(w.assign(X,J),$.mergeValidEvaluated(N,X),Q)w.assign(Q,c8._`${f}`);else $.setParams({ifClause:f})}}}};function JJ($,w){let G=$.schema[w];return G!==void 0&&!(0,TJ.alwaysValidSchema)($,G)}MJ.default=DE});var NJ=L((QJ)=>{Object.defineProperty(QJ,"__esModule",{value:!0});var AE=c(),SE={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:$,parentSchema:w,it:G}){if(w.if===void 0)(0,AE.checkStrictMode)(G,`"${$}" without "if" is ignored`)}};QJ.default=SE});var KJ=L((zJ)=>{Object.defineProperty(zJ,"__esModule",{value:!0});var jE=OG(),CE=S7(),yE=LG(),IE=C7(),bE=I7(),xE=u7(),_E=m7(),gE=kG(),vE=p7(),uE=o7(),hE=$J(),iE=GJ(),mE=YJ(),lE=XJ(),cE=fJ(),dE=NJ();function nE($=!1){let w=[hE.default,iE.default,mE.default,lE.default,cE.default,dE.default,_E.default,gE.default,xE.default,vE.default,uE.default];if($)w.push(CE.default,IE.default);else w.push(jE.default,yE.default);return w.push(bE.default),w}zJ.default=nE});var BJ=L((PJ)=>{Object.defineProperty(PJ,"__esModule",{value:!0});var w0=i(),tE={message:({schemaCode:$})=>w0.str`must match format "${$}"`,params:({schemaCode:$})=>w0._`{format: ${$}}`},rE={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:tE,code($,w){let{gen:G,data:W,$data:Y,schema:Z,schemaCode:X,it:J}=$,{opts:T,errSchemaPath:M,schemaEnv:f,self:Q}=J;if(!T.validateFormats)return;if(Y)N();else z();function N(){let K=G.scopeValue("formats",{ref:Q.formats,code:T.code.formats}),P=G.const("fDef",w0._`${K}[${X}]`),q=G.let("fType"),V=G.let("format");G.if(w0._`typeof ${P} == "object" && !(${P} instanceof RegExp)`,()=>G.assign(q,w0._`${P}.type || "string"`).assign(V,w0._`${P}.validate`),()=>G.assign(q,w0._`"string"`).assign(V,P)),$.fail$data((0,w0.or)(E(),O()));function E(){if(T.strictSchema===!1)return w0.nil;return w0._`${X} && !${V}`}function O(){let A=f.$async?w0._`(${P}.async ? await ${V}(${W}) : ${V}(${W}))`:w0._`${V}(${W})`,R=w0._`(typeof ${V} == "function" ? ${A} : ${V}.test(${W}))`;return w0._`${V} && ${V} !== true && ${q} === ${w} && !${R}`}}function z(){let K=Q.formats[Z];if(!K){E();return}if(K===!0)return;let[P,q,V]=O(K);if(P===w)$.pass(A());function E(){if(T.strictSchema===!1){Q.logger.warn(R());return}throw Error(R());function R(){return`unknown format "${Z}" ignored in schema at path "${M}"`}}function O(R){let S=R instanceof RegExp?(0,w0.regexpCode)(R):T.code.formats?w0._`${T.code.formats}${(0,w0.getProperty)(Z)}`:void 0,_=G.scopeValue("formats",{key:Z,ref:R,code:S});if(typeof R=="object"&&!(R instanceof RegExp))return[R.type||"string",R.validate,w0._`${_}.validate`];return["string",R,_]}function A(){if(typeof K=="object"&&!(K instanceof RegExp)&&K.async){if(!f.$async)throw Error("async format in sync schema");return w0._`await ${V}(${W})`}return typeof q=="function"?w0._`${V}(${W})`:w0._`${V}.test(${W})`}}}};PJ.default=rE});var qJ=L((VJ)=>{Object.defineProperty(VJ,"__esModule",{value:!0});var aE=BJ(),oE=[aE.default];VJ.default=oE});var HJ=L((EJ)=>{Object.defineProperty(EJ,"__esModule",{value:!0});EJ.contentVocabulary=EJ.metadataVocabulary=void 0;EJ.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];EJ.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var LJ=L((OJ)=>{Object.defineProperty(OJ,"__esModule",{value:!0});var wU=nX(),GU=E7(),WU=KJ(),YU=qJ(),FJ=HJ(),ZU=[wU.default,GU.default,(0,WU.default)(),YU.default,FJ.metadataVocabulary,FJ.contentVocabulary];OJ.default=ZU});var SJ=L((kJ)=>{Object.defineProperty(kJ,"__esModule",{value:!0});kJ.DiscrError=void 0;var DJ;(function($){$.Tag="tag",$.Mapping="mapping"})(DJ||(kJ.DiscrError=DJ={}))});var CJ=L((jJ)=>{Object.defineProperty(jJ,"__esModule",{value:!0});var ww=i(),SG=SJ(),RJ=D8(),JU=W4(),TU=c(),MU={message:({params:{discrError:$,tagName:w}})=>$===SG.DiscrError.Tag?`tag "${w}" must be string`:`value of tag "${w}" must be in oneOf`,params:({params:{discrError:$,tag:w,tagName:G}})=>ww._`{error: ${$}, tag: ${G}, tagValue: ${w}}`},fU={keyword:"discriminator",type:"object",schemaType:"object",error:MU,code($){let{gen:w,data:G,schema:W,parentSchema:Y,it:Z}=$,{oneOf:X}=Y;if(!Z.opts.discriminator)throw Error("discriminator: requires discriminator option");let J=W.propertyName;if(typeof J!="string")throw Error("discriminator: requires propertyName");if(W.mapping)throw Error("discriminator: mapping is not supported");if(!X)throw Error("discriminator: requires oneOf keyword");let T=w.let("valid",!1),M=w.const("tag",ww._`${G}${(0,ww.getProperty)(J)}`);w.if(ww._`typeof ${M} == "string"`,()=>f(),()=>$.error(!1,{discrError:SG.DiscrError.Tag,tag:M,tagName:J})),$.ok(T);function f(){let z=N();w.if(!1);for(let K in z)w.elseIf(ww._`${M} === ${K}`),w.assign(T,Q(z[K]));w.else(),$.error(!1,{discrError:SG.DiscrError.Mapping,tag:M,tagName:J}),w.endIf()}function Q(z){let K=w.name("valid"),P=$.subschema({keyword:"oneOf",schemaProp:z},K);return $.mergeEvaluated(P,ww.Name),K}function N(){var z;let K={},P=V(Y),q=!0;for(let A=0;A<X.length;A++){let R=X[A];if((R===null||R===void 0?void 0:R.$ref)&&!(0,TU.schemaHasRulesButRef)(R,Z.self.RULES)){let _=R.$ref;if(R=RJ.resolveRef.call(Z.self,Z.schemaEnv.root,Z.baseId,_),R instanceof RJ.SchemaEnv)R=R.schema;if(R===void 0)throw new JU.default(Z.opts.uriResolver,Z.baseId,_)}let S=(z=R===null||R===void 0?void 0:R.properties)===null||z===void 0?void 0:z[J];if(typeof S!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${J}"`);q=q&&(P||V(R)),E(S,A)}if(!q)throw Error(`discriminator: "${J}" must be required`);return K;function V({required:A}){return Array.isArray(A)&&A.includes(J)}function E(A,R){if(A.const)O(A.const,R);else if(A.enum)for(let S of A.enum)O(S,R);else throw Error(`discriminator: "properties/${J}" must have "const" or "enum"`)}function O(A,R){if(typeof A!="string"||A in K)throw Error(`discriminator: "${J}" values must be unique strings`);K[A]=R}}}};jJ.default=fU});var yJ=L((sA,NU)=>{NU.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var bJ=L((R0,RG)=>{Object.defineProperty(R0,"__esModule",{value:!0});R0.MissingRefError=R0.ValidationError=R0.CodeGen=R0.Name=R0.nil=R0.stringify=R0.str=R0._=R0.KeywordCxt=R0.Ajv=void 0;var zU=_X(),KU=LJ(),PU=CJ(),IJ=yJ(),BU=["/properties"],d8="http://json-schema.org/draft-07/schema";class B4 extends zU.default{_addVocabularies(){if(super._addVocabularies(),KU.default.forEach(($)=>this.addVocabulary($)),this.opts.discriminator)this.addKeyword(PU.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let $=this.opts.$data?this.$dataMetaSchema(IJ,BU):IJ;this.addMetaSchema($,d8,!1),this.refs["http://json-schema.org/schema"]=d8}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(d8)?d8:void 0)}}R0.Ajv=B4;RG.exports=R0=B4;RG.exports.Ajv=B4;Object.defineProperty(R0,"__esModule",{value:!0});R0.default=B4;var VU=G4();Object.defineProperty(R0,"KeywordCxt",{enumerable:!0,get:function(){return VU.KeywordCxt}});var Gw=i();Object.defineProperty(R0,"_",{enumerable:!0,get:function(){return Gw._}});Object.defineProperty(R0,"str",{enumerable:!0,get:function(){return Gw.str}});Object.defineProperty(R0,"stringify",{enumerable:!0,get:function(){return Gw.stringify}});Object.defineProperty(R0,"nil",{enumerable:!0,get:function(){return Gw.nil}});Object.defineProperty(R0,"Name",{enumerable:!0,get:function(){return Gw.Name}});Object.defineProperty(R0,"CodeGen",{enumerable:!0,get:function(){return Gw.CodeGen}});var qU=O8();Object.defineProperty(R0,"ValidationError",{enumerable:!0,get:function(){return qU.default}});var EU=W4();Object.defineProperty(R0,"MissingRefError",{enumerable:!0,get:function(){return EU.default}})});var X6=L((Gj,sG)=>{var Z6=process||{},KT=Z6.argv||[],Y6=Z6.env||{},qH=!(!!Y6.NO_COLOR||KT.includes("--no-color"))&&(!!Y6.FORCE_COLOR||KT.includes("--color")||Z6.platform==="win32"||(Z6.stdout||{}).isTTY&&Y6.TERM!=="dumb"||!!Y6.CI),EH=($,w,G=$)=>(W)=>{let Y=""+W,Z=Y.indexOf(w,$.length);return~Z?$+UH(Y,w,G,Z)+w:$+Y+w},UH=($,w,G,W)=>{let Y="",Z=0;do Y+=$.substring(Z,W)+G,Z=W+w.length,W=$.indexOf(w,Z);while(~W);return Y+$.substring(Z)},PT=($=qH)=>{let w=$?EH:()=>String;return{isColorSupported:$,reset:w("\x1B[0m","\x1B[0m"),bold:w("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:w("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:w("\x1B[3m","\x1B[23m"),underline:w("\x1B[4m","\x1B[24m"),inverse:w("\x1B[7m","\x1B[27m"),hidden:w("\x1B[8m","\x1B[28m"),strikethrough:w("\x1B[9m","\x1B[29m"),black:w("\x1B[30m","\x1B[39m"),red:w("\x1B[31m","\x1B[39m"),green:w("\x1B[32m","\x1B[39m"),yellow:w("\x1B[33m","\x1B[39m"),blue:w("\x1B[34m","\x1B[39m"),magenta:w("\x1B[35m","\x1B[39m"),cyan:w("\x1B[36m","\x1B[39m"),white:w("\x1B[37m","\x1B[39m"),gray:w("\x1B[90m","\x1B[39m"),bgBlack:w("\x1B[40m","\x1B[49m"),bgRed:w("\x1B[41m","\x1B[49m"),bgGreen:w("\x1B[42m","\x1B[49m"),bgYellow:w("\x1B[43m","\x1B[49m"),bgBlue:w("\x1B[44m","\x1B[49m"),bgMagenta:w("\x1B[45m","\x1B[49m"),bgCyan:w("\x1B[46m","\x1B[49m"),bgWhite:w("\x1B[47m","\x1B[49m"),blackBright:w("\x1B[90m","\x1B[39m"),redBright:w("\x1B[91m","\x1B[39m"),greenBright:w("\x1B[92m","\x1B[39m"),yellowBright:w("\x1B[93m","\x1B[39m"),blueBright:w("\x1B[94m","\x1B[39m"),magentaBright:w("\x1B[95m","\x1B[39m"),cyanBright:w("\x1B[96m","\x1B[39m"),whiteBright:w("\x1B[97m","\x1B[39m"),bgBlackBright:w("\x1B[100m","\x1B[49m"),bgRedBright:w("\x1B[101m","\x1B[49m"),bgGreenBright:w("\x1B[102m","\x1B[49m"),bgYellowBright:w("\x1B[103m","\x1B[49m"),bgBlueBright:w("\x1B[104m","\x1B[49m"),bgMagentaBright:w("\x1B[105m","\x1B[49m"),bgCyanBright:w("\x1B[106m","\x1B[49m"),bgWhiteBright:w("\x1B[107m","\x1B[49m")}};sG.exports=PT();sG.exports.createColors=PT});import{realpathSync as XQ}from"fs";import{realpath as yD}from"fs/promises";import ID from"path";import{createInterface as bD}from"readline/promises";import{fileURLToPath as xD}from"url";var wY=c$(S5(),1),{program:rD,createCommand:sD,createArgument:aD,createOption:oD,CommanderError:eD,InvalidArgumentError:$k,InvalidOptionArgumentError:wk,Command:GY,Argument:Gk,Option:Wk,Help:Yk}=wY.default;import WY from"node:os";import J8 from"node:path";function YY(){return process.env.XDG_CONFIG_HOME?J8.join(process.env.XDG_CONFIG_HOME,"coden"):J8.join(WY.homedir(),".config","coden")}function ZY(){return process.env.XDG_DATA_HOME?J8.join(process.env.XDG_DATA_HOME,"coden"):J8.join(WY.homedir(),".local","share","coden")}import{mkdir as TN,readFile as MN,realpath as XY,writeFile as fN}from"node:fs/promises";import QN from"node:path";class R5{file;constructor($){this.file=$}async isTrusted($){return(await this.read()).includes($)}async isWorkspaceTrusted($){return this.isTrusted(await XY($))}async trustWorkspace($){return this.trust(await XY($))}async trust($){let w=await this.read();if(!w.includes($))w.push($);await TN(QN.dirname(this.file),{recursive:!0}),await fN(this.file,`${JSON.stringify(w,null,2)}
36
- `,{encoding:"utf8",mode:384})}async read(){try{let $=JSON.parse(await MN(this.file,"utf8"));return Array.isArray($)?$.filter((w)=>typeof w==="string"):[]}catch($){if($.code==="ENOENT")return[];throw $}}}function d$($,w){if($.length<=w)return $;let W=Math.max(0,w-80),Y=Math.ceil(W/2),Z=Math.floor(W/2),X=$.length-Y-Z;return`${$.slice(0,Y)}
37
- ... [${X} characters omitted] ...
38
- ${$.slice($.length-Z)}`}class y extends Error{category;code;retryable;details;constructor($,w,G,W=!1,Y,Z){super(G,Z);this.category=$;this.code=w;this.retryable=W;this.details=Y;this.name="CodeNError"}}import{spawn as NN}from"node:child_process";class j5{headLimit;tailLimit;head="";tail="";total=0;constructor($){this.headLimit=Math.ceil($*0.6),this.tailLimit=Math.floor($*0.4)}add($){this.total+=$.length;let w=Math.max(0,this.headLimit-this.head.length);this.head+=$.slice(0,w);let G=$.slice(w);if(G)this.tail=`${this.tail}${G}`.slice(-this.tailLimit)}value(){let $=this.total-this.head.length-this.tail.length;return $>0?`${this.head}
35
+ deps: ${G}}`};var kD={keyword:"dependencies",type:"object",schemaType:"object",error:Gz.error,code($){let[w,G]=yD($);$z($,w),wz($,G)}};function yD({schema:$}){let w={},G={};for(let Z in $){if(Z==="__proto__")continue;let X=Array.isArray($[Z])?w:G;X[Z]=$[Z]}return[w,G]}function $z($,w=$.schema){let{gen:G,data:Z,it:X}=$;if(Object.keys(w).length===0)return;let Y=G.let("missing");for(let J in w){let W=w[J];if(W.length===0)continue;let T=(0,Z9.propertyInData)(G,Z,J,X.opts.ownProperties);if($.setParams({property:J,depsCount:W.length,deps:W.join(", ")}),X.allErrors)G.if(T,()=>{for(let Q of W)(0,Z9.checkReportMissingProp)($,Q)});else G.if(IZ._`${T} && (${(0,Z9.checkMissingProp)($,W,Y)})`),(0,Z9.reportMissingProp)($,Y),G.else()}}Gz.validatePropertyDeps=$z;function wz($,w=$.schema){let{gen:G,data:Z,keyword:X,it:Y}=$,J=G.name("valid");for(let W in w){if((0,bD.alwaysValidSchema)(Y,w[W]))continue;G.if((0,Z9.propertyInData)(G,Z,W,Y.opts.ownProperties),()=>{let T=$.subschema({keyword:X,schemaProp:W},J);$.mergeValidEvaluated(T,J)},()=>G.var(J,!0)),$.ok(J)}}Gz.validateSchemaDeps=wz;Gz.default=kD});var Tz=F((Wz)=>{Object.defineProperty(Wz,"__esModule",{value:!0});var Jz=l(),gD=p(),uD={message:"property name must be valid",params:({params:$})=>Jz._`{propertyName: ${$.propertyName}}`},hD={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:uD,code($){let{gen:w,schema:G,data:Z,it:X}=$;if((0,gD.alwaysValidSchema)(X,G))return;let Y=w.name("valid");w.forIn("key",Z,(J)=>{$.setParams({propertyName:J}),$.subschema({keyword:"propertyNames",data:J,dataTypes:["string"],propertyName:J,compositeRule:!0},Y),w.if((0,Jz.not)(Y),()=>{if($.error(!0),!X.allErrors)w.break()})}),$.ok(Y)}};Wz.default=hD});var jZ=F((Qz)=>{Object.defineProperty(Qz,"__esModule",{value:!0});var w5=n0(),Z$=l(),iD=R$(),G5=p(),mD={message:"must NOT have additional properties",params:({params:$})=>Z$._`{additionalProperty: ${$.additionalProperty}}`},lD={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:mD,code($){let{gen:w,schema:G,parentSchema:Z,data:X,errsCount:Y,it:J}=$;if(!Y)throw Error("ajv implementation error");let{allErrors:W,opts:T}=J;if(J.props=!0,T.removeAdditional!=="all"&&(0,G5.alwaysValidSchema)(J,G))return;let Q=(0,w5.allSchemaProperties)(Z.properties),z=(0,w5.allSchemaProperties)(Z.patternProperties);M(),$.ok(Z$._`${Y} === ${iD.default.errors}`);function M(){w.forIn("key",X,(V)=>{if(!Q.length&&!z.length)N(V);else w.if(P(V),()=>N(V))})}function P(V){let K;if(Q.length>8){let U=(0,G5.schemaRefOrVal)(J,Z.properties,"properties");K=(0,w5.isOwnProperty)(w,U,V)}else if(Q.length)K=(0,Z$.or)(...Q.map((U)=>Z$._`${V} === ${U}`));else K=Z$.nil;if(z.length)K=(0,Z$.or)(K,...z.map((U)=>Z$._`${(0,w5.usePattern)($,U)}.test(${V})`));return(0,Z$.not)(K)}function q(V){w.code(Z$._`delete ${X}[${V}]`)}function N(V){if(T.removeAdditional==="all"||T.removeAdditional&&G===!1){q(V);return}if(G===!1){if($.setParams({additionalProperty:V}),$.error(),!W)w.break();return}if(typeof G=="object"&&!(0,G5.alwaysValidSchema)(J,G)){let K=w.name("valid");if(T.removeAdditional==="failing")B(V,K,!1),w.if((0,Z$.not)(K),()=>{$.reset(),q(V)});else if(B(V,K),!W)w.if((0,Z$.not)(K),()=>w.break())}}function B(V,K,U){let O={keyword:"additionalProperties",dataProp:V,dataPropType:G5.Type.Str};if(U===!1)Object.assign(O,{compositeRule:!0,createErrors:!1,allErrors:!1});$.subschema(O,K)}}};Qz.default=lD});var qz=F((Pz)=>{Object.defineProperty(Pz,"__esModule",{value:!0});var cD=d4(),zz=n0(),CZ=p(),Mz=jZ(),pD={keyword:"properties",type:"object",schemaType:"object",code($){let{gen:w,schema:G,parentSchema:Z,data:X,it:Y}=$;if(Y.opts.removeAdditional==="all"&&Z.additionalProperties===void 0)Mz.default.code(new cD.KeywordCxt(Y,Mz.default,"additionalProperties"));let J=(0,zz.allSchemaProperties)(G);for(let M of J)Y.definedProperties.add(M);if(Y.opts.unevaluated&&J.length&&Y.props!==!0)Y.props=CZ.mergeEvaluated.props(w,(0,CZ.toHash)(J),Y.props);let W=J.filter((M)=>!(0,CZ.alwaysValidSchema)(Y,G[M]));if(W.length===0)return;let T=w.name("valid");for(let M of W){if(Q(M))z(M);else{if(w.if((0,zz.propertyInData)(w,X,M,Y.opts.ownProperties)),z(M),!Y.allErrors)w.else().var(T,!0);w.endIf()}$.it.definedProperties.add(M),$.ok(T)}function Q(M){return Y.opts.useDefaults&&!Y.compositeRule&&G[M].default!==void 0}function z(M){$.subschema({keyword:"properties",schemaProp:M,dataProp:M},T)}}};Pz.default=pD});var Uz=F((Kz)=>{Object.defineProperty(Kz,"__esModule",{value:!0});var Bz=n0(),Z5=l(),Nz=p(),Vz=p(),rD={keyword:"patternProperties",type:"object",schemaType:"object",code($){let{gen:w,schema:G,data:Z,parentSchema:X,it:Y}=$,{opts:J}=Y,W=(0,Bz.allSchemaProperties)(G),T=W.filter((B)=>(0,Nz.alwaysValidSchema)(Y,G[B]));if(W.length===0||T.length===W.length&&(!Y.opts.unevaluated||Y.props===!0))return;let Q=J.strictSchema&&!J.allowMatchingProperties&&X.properties,z=w.name("valid");if(Y.props!==!0&&!(Y.props instanceof Z5.Name))Y.props=(0,Vz.evaluatedPropsToName)(w,Y.props);let{props:M}=Y;P();function P(){for(let B of W){if(Q)q(B);if(Y.allErrors)N(B);else w.var(z,!0),N(B),w.if(z)}}function q(B){for(let V in Q)if(new RegExp(B).test(V))(0,Nz.checkStrictMode)(Y,`property ${V} matches pattern ${B} (use allowMatchingProperties)`)}function N(B){w.forIn("key",Z,(V)=>{w.if(Z5._`${(0,Bz.usePattern)($,B)}.test(${V})`,()=>{let K=T.includes(B);if(!K)$.subschema({keyword:"patternProperties",schemaProp:B,dataProp:V,dataPropType:Vz.Type.Str},z);if(Y.opts.unevaluated&&M!==!0)w.assign(Z5._`${M}[${V}]`,!0);else if(!K&&!Y.allErrors)w.if((0,Z5.not)(z),()=>w.break())})})}}};Kz.default=rD});var Fz=F((Hz)=>{Object.defineProperty(Hz,"__esModule",{value:!0});var aD=p(),tD={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code($){let{gen:w,schema:G,it:Z}=$;if((0,aD.alwaysValidSchema)(Z,G)){$.fail();return}let X=w.name("valid");$.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},X),$.failResult(X,()=>$.reset(),()=>$.error())},error:{message:"must NOT be valid"}};Hz.default=tD});var fz=F((Oz)=>{Object.defineProperty(Oz,"__esModule",{value:!0});var eD=n0(),$E={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:eD.validateUnion,error:{message:"must match a schema in anyOf"}};Oz.default=$E});var Dz=F((Lz)=>{Object.defineProperty(Lz,"__esModule",{value:!0});var X5=l(),GE=p(),ZE={message:"must match exactly one schema in oneOf",params:({params:$})=>X5._`{passingSchemas: ${$.passing}}`},XE={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:ZE,code($){let{gen:w,schema:G,parentSchema:Z,it:X}=$;if(!Array.isArray(G))throw Error("ajv implementation error");if(X.opts.discriminator&&Z.discriminator)return;let Y=G,J=w.let("valid",!1),W=w.let("passing",null),T=w.name("_valid");$.setParams({passing:W}),w.block(Q),$.result(J,()=>$.reset(),()=>$.error(!0));function Q(){Y.forEach((z,M)=>{let P;if((0,GE.alwaysValidSchema)(X,z))w.var(T,!0);else P=$.subschema({keyword:"oneOf",schemaProp:M,compositeRule:!0},T);if(M>0)w.if(X5._`${T} && ${J}`).assign(J,!1).assign(W,X5._`[${W}, ${M}]`).else();w.if(T,()=>{if(w.assign(J,!0),w.assign(W,M),P)$.mergeEvaluated(P,X5.Name)})})}}};Lz.default=XE});var Az=F((Ez)=>{Object.defineProperty(Ez,"__esModule",{value:!0});var JE=p(),WE={keyword:"allOf",schemaType:"array",code($){let{gen:w,schema:G,it:Z}=$;if(!Array.isArray(G))throw Error("ajv implementation error");let X=w.name("valid");G.forEach((Y,J)=>{if((0,JE.alwaysValidSchema)(Z,Y))return;let W=$.subschema({keyword:"allOf",schemaProp:J},X);$.ok(X),$.mergeEvaluated(W)})}};Ez.default=WE});var jz=F((Iz)=>{Object.defineProperty(Iz,"__esModule",{value:!0});var Y5=l(),Sz=p(),QE={message:({params:$})=>Y5.str`must match "${$.ifClause}" schema`,params:({params:$})=>Y5._`{failingKeyword: ${$.ifClause}}`},zE={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:QE,code($){let{gen:w,parentSchema:G,it:Z}=$;if(G.then===void 0&&G.else===void 0)(0,Sz.checkStrictMode)(Z,'"if" without "then" and "else" is ignored');let X=Rz(Z,"then"),Y=Rz(Z,"else");if(!X&&!Y)return;let J=w.let("valid",!0),W=w.name("_valid");if(T(),$.reset(),X&&Y){let z=w.let("ifClause");$.setParams({ifClause:z}),w.if(W,Q("then",z),Q("else",z))}else if(X)w.if(W,Q("then"));else w.if((0,Y5.not)(W),Q("else"));$.pass(J,()=>$.error(!0));function T(){let z=$.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},W);$.mergeEvaluated(z)}function Q(z,M){return()=>{let P=$.subschema({keyword:z},W);if(w.assign(J,W),$.mergeValidEvaluated(P,J),M)w.assign(M,Y5._`${z}`);else $.setParams({ifClause:z})}}}};function Rz($,w){let G=$.schema[w];return G!==void 0&&!(0,Sz.alwaysValidSchema)($,G)}Iz.default=zE});var bz=F((Cz)=>{Object.defineProperty(Cz,"__esModule",{value:!0});var PE=p(),qE={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:$,parentSchema:w,it:G}){if(w.if===void 0)(0,PE.checkStrictMode)(G,`"${$}" without "if" is ignored`)}};Cz.default=qE});var yz=F((kz)=>{Object.defineProperty(kz,"__esModule",{value:!0});var NE=RZ(),VE=rQ(),KE=SZ(),UE=tQ(),HE=eQ(),FE=Yz(),OE=Tz(),fE=jZ(),LE=qz(),DE=Uz(),EE=Fz(),AE=fz(),RE=Dz(),SE=Az(),IE=jz(),jE=bz();function CE($=!1){let w=[EE.default,AE.default,RE.default,SE.default,IE.default,jE.default,OE.default,fE.default,FE.default,LE.default,DE.default];if($)w.push(VE.default,UE.default);else w.push(NE.default,KE.default);return w.push(HE.default),w}kz.default=CE});var xz=F((_z)=>{Object.defineProperty(_z,"__esModule",{value:!0});var X0=l(),kE={message:({schemaCode:$})=>X0.str`must match format "${$}"`,params:({schemaCode:$})=>X0._`{format: ${$}}`},yE={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:kE,code($,w){let{gen:G,data:Z,$data:X,schema:Y,schemaCode:J,it:W}=$,{opts:T,errSchemaPath:Q,schemaEnv:z,self:M}=W;if(!T.validateFormats)return;if(X)P();else q();function P(){let N=G.scopeValue("formats",{ref:M.formats,code:T.code.formats}),B=G.const("fDef",X0._`${N}[${J}]`),V=G.let("fType"),K=G.let("format");G.if(X0._`typeof ${B} == "object" && !(${B} instanceof RegExp)`,()=>G.assign(V,X0._`${B}.type || "string"`).assign(K,X0._`${B}.validate`),()=>G.assign(V,X0._`"string"`).assign(K,B)),$.fail$data((0,X0.or)(U(),O()));function U(){if(T.strictSchema===!1)return X0.nil;return X0._`${J} && !${K}`}function O(){let D=z.$async?X0._`(${B}.async ? await ${K}(${Z}) : ${K}(${Z}))`:X0._`${K}(${Z})`,f=X0._`(typeof ${K} == "function" ? ${D} : ${K}.test(${Z}))`;return X0._`${K} && ${K} !== true && ${V} === ${w} && !${f}`}}function q(){let N=M.formats[Y];if(!N){U();return}if(N===!0)return;let[B,V,K]=O(N);if(B===w)$.pass(D());function U(){if(T.strictSchema===!1){M.logger.warn(f());return}throw Error(f());function f(){return`unknown format "${Y}" ignored in schema at path "${Q}"`}}function O(f){let L=f instanceof RegExp?(0,X0.regexpCode)(f):T.code.formats?X0._`${T.code.formats}${(0,X0.getProperty)(Y)}`:void 0,C=G.scopeValue("formats",{key:Y,ref:f,code:L});if(typeof f=="object"&&!(f instanceof RegExp))return[f.type||"string",f.validate,X0._`${C}.validate`];return["string",f,C]}function D(){if(typeof N=="object"&&!(N instanceof RegExp)&&N.async){if(!z.$async)throw Error("async format in sync schema");return X0._`await ${K}(${Z})`}return typeof V=="function"?X0._`${K}(${Z})`:X0._`${K}.test(${Z})`}}}};_z.default=yE});var uz=F((gz)=>{Object.defineProperty(gz,"__esModule",{value:!0});var xE=xz(),gE=[xE.default];gz.default=gE});var iz=F((hz)=>{Object.defineProperty(hz,"__esModule",{value:!0});hz.contentVocabulary=hz.metadataVocabulary=void 0;hz.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];hz.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var dz=F((lz)=>{Object.defineProperty(lz,"__esModule",{value:!0});var vE=PQ(),iE=hQ(),mE=yz(),lE=uz(),mz=iz(),dE=[vE.default,iE.default,(0,mE.default)(),lE.default,mz.metadataVocabulary,mz.contentVocabulary];lz.default=dE});var rz=F((pz)=>{Object.defineProperty(pz,"__esModule",{value:!0});pz.DiscrError=void 0;var cz;(function($){$.Tag="tag",$.Mapping="mapping"})(cz||(pz.DiscrError=cz={}))});var tz=F((az)=>{Object.defineProperty(az,"__esModule",{value:!0});var _w=l(),bZ=rz(),sz=v6(),pE=c4(),nE=p(),rE={message:({params:{discrError:$,tagName:w}})=>$===bZ.DiscrError.Tag?`tag "${w}" must be string`:`value of tag "${w}" must be in oneOf`,params:({params:{discrError:$,tag:w,tagName:G}})=>_w._`{error: ${$}, tag: ${G}, tagValue: ${w}}`},sE={keyword:"discriminator",type:"object",schemaType:"object",error:rE,code($){let{gen:w,data:G,schema:Z,parentSchema:X,it:Y}=$,{oneOf:J}=X;if(!Y.opts.discriminator)throw Error("discriminator: requires discriminator option");let W=Z.propertyName;if(typeof W!="string")throw Error("discriminator: requires propertyName");if(Z.mapping)throw Error("discriminator: mapping is not supported");if(!J)throw Error("discriminator: requires oneOf keyword");let T=w.let("valid",!1),Q=w.const("tag",_w._`${G}${(0,_w.getProperty)(W)}`);w.if(_w._`typeof ${Q} == "string"`,()=>z(),()=>$.error(!1,{discrError:bZ.DiscrError.Tag,tag:Q,tagName:W})),$.ok(T);function z(){let q=P();w.if(!1);for(let N in q)w.elseIf(_w._`${Q} === ${N}`),w.assign(T,M(q[N]));w.else(),$.error(!1,{discrError:bZ.DiscrError.Mapping,tag:Q,tagName:W}),w.endIf()}function M(q){let N=w.name("valid"),B=$.subschema({keyword:"oneOf",schemaProp:q},N);return $.mergeEvaluated(B,_w.Name),N}function P(){var q;let N={},B=K(X),V=!0;for(let D=0;D<J.length;D++){let f=J[D];if((f===null||f===void 0?void 0:f.$ref)&&!(0,nE.schemaHasRulesButRef)(f,Y.self.RULES)){let C=f.$ref;if(f=sz.resolveRef.call(Y.self,Y.schemaEnv.root,Y.baseId,C),f instanceof sz.SchemaEnv)f=f.schema;if(f===void 0)throw new pE.default(Y.opts.uriResolver,Y.baseId,C)}let L=(q=f===null||f===void 0?void 0:f.properties)===null||q===void 0?void 0:q[W];if(typeof L!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${W}"`);V=V&&(B||K(f)),U(L,D)}if(!V)throw Error(`discriminator: "${W}" must be required`);return N;function K({required:D}){return Array.isArray(D)&&D.includes(W)}function U(D,f){if(D.const)O(D.const,f);else if(D.enum)for(let L of D.enum)O(L,f);else throw Error(`discriminator: "properties/${W}" must have "const" or "enum"`)}function O(D,f){if(typeof D!="string"||D in N)throw Error(`discriminator: "${W}" values must be unique strings`);N[D]=f}}}};az.default=sE});var oz=F((mi,tE)=>{tE.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var $M=F((k0,kZ)=>{Object.defineProperty(k0,"__esModule",{value:!0});k0.MissingRefError=k0.ValidationError=k0.CodeGen=k0.Name=k0.nil=k0.stringify=k0.str=k0._=k0.KeywordCxt=k0.Ajv=void 0;var oE=GQ(),eE=dz(),$A=tz(),ez=oz(),wA=["/properties"],J5="http://json-schema.org/draft-07/schema";class X9 extends oE.default{_addVocabularies(){if(super._addVocabularies(),eE.default.forEach(($)=>this.addVocabulary($)),this.opts.discriminator)this.addKeyword($A.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let $=this.opts.$data?this.$dataMetaSchema(ez,wA):ez;this.addMetaSchema($,J5,!1),this.refs["http://json-schema.org/schema"]=J5}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(J5)?J5:void 0)}}k0.Ajv=X9;kZ.exports=k0=X9;kZ.exports.Ajv=X9;Object.defineProperty(k0,"__esModule",{value:!0});k0.default=X9;var GA=d4();Object.defineProperty(k0,"KeywordCxt",{enumerable:!0,get:function(){return GA.KeywordCxt}});var xw=l();Object.defineProperty(k0,"_",{enumerable:!0,get:function(){return xw._}});Object.defineProperty(k0,"str",{enumerable:!0,get:function(){return xw.str}});Object.defineProperty(k0,"stringify",{enumerable:!0,get:function(){return xw.stringify}});Object.defineProperty(k0,"nil",{enumerable:!0,get:function(){return xw.nil}});Object.defineProperty(k0,"Name",{enumerable:!0,get:function(){return xw.Name}});Object.defineProperty(k0,"CodeGen",{enumerable:!0,get:function(){return xw.CodeGen}});var ZA=u6();Object.defineProperty(k0,"ValidationError",{enumerable:!0,get:function(){return ZA.default}});var XA=c4();Object.defineProperty(k0,"MissingRefError",{enumerable:!0,get:function(){return XA.default}})});var r=F((nA)=>{var rZ=Symbol.for("yaml.alias"),UM=Symbol.for("yaml.document"),P5=Symbol.for("yaml.map"),HM=Symbol.for("yaml.pair"),sZ=Symbol.for("yaml.scalar"),q5=Symbol.for("yaml.seq"),C$=Symbol.for("yaml.node.type"),vA=($)=>!!$&&typeof $==="object"&&$[C$]===rZ,iA=($)=>!!$&&typeof $==="object"&&$[C$]===UM,mA=($)=>!!$&&typeof $==="object"&&$[C$]===P5,lA=($)=>!!$&&typeof $==="object"&&$[C$]===HM,FM=($)=>!!$&&typeof $==="object"&&$[C$]===sZ,dA=($)=>!!$&&typeof $==="object"&&$[C$]===q5;function OM($){if($&&typeof $==="object")switch($[C$]){case P5:case q5:return!0}return!1}function cA($){if($&&typeof $==="object")switch($[C$]){case rZ:case P5:case sZ:case q5:return!0}return!1}var pA=($)=>(FM($)||OM($))&&!!$.anchor;nA.ALIAS=rZ;nA.DOC=UM;nA.MAP=P5;nA.NODE_TYPE=C$;nA.PAIR=HM;nA.SCALAR=sZ;nA.SEQ=q5;nA.hasAnchor=pA;nA.isAlias=vA;nA.isCollection=OM;nA.isDocument=iA;nA.isMap=mA;nA.isNode=cA;nA.isPair=lA;nA.isScalar=FM;nA.isSeq=dA});var T9=F((zR)=>{var z0=r(),y0=Symbol("break visit"),fM=Symbol("skip children"),N$=Symbol("remove node");function B5($,w){let G=LM(w);if(z0.isDocument($)){if(hw(null,$.contents,G,Object.freeze([$]))===N$)$.contents=null}else hw(null,$,G,Object.freeze([]))}B5.BREAK=y0;B5.SKIP=fM;B5.REMOVE=N$;function hw($,w,G,Z){let X=DM($,w,G,Z);if(z0.isNode(X)||z0.isPair(X))return EM($,Z,X),hw($,X,G,Z);if(typeof X!=="symbol"){if(z0.isCollection(w)){Z=Object.freeze(Z.concat(w));for(let Y=0;Y<w.items.length;++Y){let J=hw(Y,w.items[Y],G,Z);if(typeof J==="number")Y=J-1;else if(J===y0)return y0;else if(J===N$)w.items.splice(Y,1),Y-=1}}else if(z0.isPair(w)){Z=Object.freeze(Z.concat(w));let Y=hw("key",w.key,G,Z);if(Y===y0)return y0;else if(Y===N$)w.key=null;let J=hw("value",w.value,G,Z);if(J===y0)return y0;else if(J===N$)w.value=null}}return X}async function N5($,w){let G=LM(w);if(z0.isDocument($)){if(await vw(null,$.contents,G,Object.freeze([$]))===N$)$.contents=null}else await vw(null,$,G,Object.freeze([]))}N5.BREAK=y0;N5.SKIP=fM;N5.REMOVE=N$;async function vw($,w,G,Z){let X=await DM($,w,G,Z);if(z0.isNode(X)||z0.isPair(X))return EM($,Z,X),vw($,X,G,Z);if(typeof X!=="symbol"){if(z0.isCollection(w)){Z=Object.freeze(Z.concat(w));for(let Y=0;Y<w.items.length;++Y){let J=await vw(Y,w.items[Y],G,Z);if(typeof J==="number")Y=J-1;else if(J===y0)return y0;else if(J===N$)w.items.splice(Y,1),Y-=1}}else if(z0.isPair(w)){Z=Object.freeze(Z.concat(w));let Y=await vw("key",w.key,G,Z);if(Y===y0)return y0;else if(Y===N$)w.key=null;let J=await vw("value",w.value,G,Z);if(J===y0)return y0;else if(J===N$)w.value=null}}return X}function LM($){if(typeof $==="object"&&($.Collection||$.Node||$.Value))return Object.assign({Alias:$.Node,Map:$.Node,Scalar:$.Node,Seq:$.Node},$.Value&&{Map:$.Value,Scalar:$.Value,Seq:$.Value},$.Collection&&{Map:$.Collection,Seq:$.Collection},$);return $}function DM($,w,G,Z){if(typeof G==="function")return G($,w,Z);if(z0.isMap(w))return G.Map?.($,w,Z);if(z0.isSeq(w))return G.Seq?.($,w,Z);if(z0.isPair(w))return G.Pair?.($,w,Z);if(z0.isScalar(w))return G.Scalar?.($,w,Z);if(z0.isAlias(w))return G.Alias?.($,w,Z);return}function EM($,w,G){let Z=w[w.length-1];if(z0.isCollection(Z))Z.items[$]=G;else if(z0.isPair(Z))if($==="key")Z.key=G;else Z.value=G;else if(z0.isDocument(Z))Z.contents=G;else{let X=z0.isAlias(Z)?"alias":"scalar";throw Error(`Cannot replace node with ${X} parent`)}}zR.visit=B5;zR.visitAsync=N5});var aZ=F((VR)=>{var AM=r(),qR=T9(),BR={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},NR=($)=>$.replace(/[!,[\]{}]/g,(w)=>BR[w]);class s0{constructor($,w){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},s0.defaultYaml,$),this.tags=Object.assign({},s0.defaultTags,w)}clone(){let $=new s0(this.yaml,this.tags);return $.docStart=this.docStart,$}atDocument(){let $=new s0(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:s0.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},s0.defaultTags);break}return $}add($,w){if(this.atNextDocument)this.yaml={explicit:s0.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},s0.defaultTags),this.atNextDocument=!1;let G=$.trim().split(/[ \t]+/),Z=G.shift();switch(Z){case"%TAG":{if(G.length!==2){if(w(0,"%TAG directive should contain exactly two parts"),G.length<2)return!1}let[X,Y]=G;return this.tags[X]=Y,!0}case"%YAML":{if(this.yaml.explicit=!0,G.length!==1)return w(0,"%YAML directive should contain exactly one part"),!1;let[X]=G;if(X==="1.1"||X==="1.2")return this.yaml.version=X,!0;else{let Y=/^\d+\.\d+$/.test(X);return w(6,`Unsupported YAML version ${X}`,Y),!1}}default:return w(0,`Unknown directive ${Z}`,!0),!1}}tagName($,w){if($==="!")return"!";if($[0]!=="!")return w(`Not a valid tag: ${$}`),null;if($[1]==="<"){let Y=$.slice(2,-1);if(Y==="!"||Y==="!!")return w(`Verbatim tags aren't resolved, so ${$} is invalid.`),null;if($[$.length-1]!==">")w("Verbatim tags must end with a >");return Y}let[,G,Z]=$.match(/^(.*!)([^!]*)$/s);if(!Z)w(`The ${$} tag has no suffix`);let X=this.tags[G];if(X)try{return X+decodeURIComponent(Z)}catch(Y){return w(String(Y)),null}if(G==="!")return $;return w(`Could not resolve tag: ${$}`),null}tagString($){for(let[w,G]of Object.entries(this.tags))if($.startsWith(G))return w+NR($.substring(G.length));return $[0]==="!"?$:`!<${$}>`}toString($){let w=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],G=Object.entries(this.tags),Z;if($&&G.length>0&&AM.isNode($.contents)){let X={};qR.visit($.contents,(Y,J)=>{if(AM.isNode(J)&&J.tag)X[J.tag]=!0}),Z=Object.keys(X)}else Z=[];for(let[X,Y]of G){if(X==="!!"&&Y==="tag:yaml.org,2002:")continue;if(!$||Z.some((J)=>J.startsWith(Y)))w.push(`%TAG ${X} ${Y}`)}return w.join(`
36
+ `)}}s0.defaultYaml={explicit:!1,version:"1.2"};s0.defaultTags={"!!":"tag:yaml.org,2002:"};VR.Directives=s0});var V5=F((OR)=>{var RM=r(),UR=T9();function HR($){if(/[\x00-\x19\s,[\]{}]/.test($)){let G=`Anchor must not contain whitespace or control characters: ${JSON.stringify($)}`;throw Error(G)}return!0}function SM($){let w=new Set;return UR.visit($,{Value(G,Z){if(Z.anchor)w.add(Z.anchor)}}),w}function IM($,w){for(let G=1;;++G){let Z=`${$}${G}`;if(!w.has(Z))return Z}}function FR($,w){let G=[],Z=new Map,X=null;return{onAnchor:(Y)=>{G.push(Y),X??(X=SM($));let J=IM(w,X);return X.add(J),J},setAnchors:()=>{for(let Y of G){let J=Z.get(Y);if(typeof J==="object"&&J.anchor&&(RM.isScalar(J.node)||RM.isCollection(J.node)))J.node.anchor=J.anchor;else{let W=Error("Failed to resolve repeated object (this should not happen)");throw W.source=Y,W}}},sourceObjects:Z}}OR.anchorIsValid=HR;OR.anchorNames=SM;OR.createNodeAnchors=FR;OR.findNewAnchor=IM});var tZ=F((AR)=>{function Q9($,w,G,Z){if(Z&&typeof Z==="object")if(Array.isArray(Z))for(let X=0,Y=Z.length;X<Y;++X){let J=Z[X],W=Q9($,Z,String(X),J);if(W===void 0)delete Z[X];else if(W!==J)Z[X]=W}else if(Z instanceof Map)for(let X of Array.from(Z.keys())){let Y=Z.get(X),J=Q9($,Z,X,Y);if(J===void 0)Z.delete(X);else if(J!==Y)Z.set(X,J)}else if(Z instanceof Set)for(let X of Array.from(Z)){let Y=Q9($,Z,X,X);if(Y===void 0)Z.delete(X);else if(Y!==X)Z.delete(X),Z.add(Y)}else for(let[X,Y]of Object.entries(Z)){let J=Q9($,Z,X,Y);if(J===void 0)delete Z[X];else if(J!==Y)Z[X]=J}return $.call(w,G,Z)}AR.applyReviver=Q9});var Z1=F((IR)=>{var SR=r();function jM($,w,G){if(Array.isArray($))return $.map((Z,X)=>jM(Z,String(X),G));if($&&typeof $.toJSON==="function"){if(!G||!SR.hasAnchor($))return $.toJSON(w,G);let Z={aliasCount:0,count:1,res:void 0};G.anchors.set($,Z),G.onCreate=(Y)=>{Z.res=Y,delete G.onCreate};let X=$.toJSON(w,G);if(G.onCreate)G.onCreate(X);return X}if(typeof $==="bigint"&&!G?.keep)return Number($);return $}IR.toJS=jM});var K5=F((kR)=>{var CR=tZ(),CM=r(),bR=Z1();class bM{constructor($){Object.defineProperty(this,CM.NODE_TYPE,{value:$})}clone(){let $=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));if(this.range)$.range=this.range.slice();return $}toJS($,{mapAsMap:w,maxAliasCount:G,onAnchor:Z,reviver:X}={}){if(!CM.isDocument($))throw TypeError("A document argument is required");let Y={anchors:new Map,doc:$,keep:!0,mapAsMap:w===!0,mapKeyWarned:!1,maxAliasCount:typeof G==="number"?G:100},J=bR.toJS(this,"",Y);if(typeof Z==="function")for(let{count:W,res:T}of Y.anchors.values())Z(T,W);return typeof X==="function"?CR.applyReviver(X,{"":J},"",J):J}}kR.NodeBase=bM});var z9=F((hR)=>{var _R=V5(),xR=T9(),iw=r(),gR=K5(),uR=Z1();class kM extends gR.NodeBase{constructor($){super(iw.ALIAS);this.source=$,Object.defineProperty(this,"tag",{set(){throw Error("Alias nodes cannot have tags")}})}resolve($,w){if(w?.maxAliasCount===0)throw ReferenceError("Alias resolution is disabled");let G;if(w?.aliasResolveCache)G=w.aliasResolveCache;else if(G=[],xR.visit($,{Node:(X,Y)=>{if(iw.isAlias(Y)||iw.hasAnchor(Y))G.push(Y)}}),w)w.aliasResolveCache=G;let Z=void 0;for(let X of G){if(X===this)break;if(X.anchor===this.source)Z=X}return Z}toJSON($,w){if(!w)return{source:this.source};let{anchors:G,doc:Z,maxAliasCount:X}=w,Y=this.resolve(Z,w);if(!Y){let W=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(W)}let J=G.get(Y);if(!J)uR.toJS(Y,null,w),J=G.get(Y);if(J?.res===void 0)throw ReferenceError("This should not happen: Alias anchor was not resolved?");if(X>=0){if(J.count+=1,J.aliasCount===0)J.aliasCount=U5(Z,Y,G);if(J.count*J.aliasCount>X)throw ReferenceError("Excessive alias count indicates a resource exhaustion attack")}return J.res}toString($,w,G){let Z=`*${this.source}`;if($){if(_R.anchorIsValid(this.source),$.options.verifyAliasOrder&&!$.anchors.has(this.source)){let X=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(X)}if($.implicitKey)return`${Z} `}return Z}}function U5($,w,G){if(iw.isAlias(w)){let Z=w.resolve($),X=G&&Z&&G.get(Z);return X?X.count*X.aliasCount:0}else if(iw.isCollection(w)){let Z=0;for(let X of w.items){let Y=U5($,X,G);if(Y>Z)Z=Y}return Z}else if(iw.isPair(w)){let Z=U5($,w.key,G),X=U5($,w.value,G);return Math.max(Z,X)}return 1}hR.Alias=kM});var W0=F((cR)=>{var iR=r(),mR=K5(),lR=Z1(),dR=($)=>!$||typeof $!=="function"&&typeof $!=="object";class u1 extends mR.NodeBase{constructor($){super(iR.SCALAR);this.value=$}toJSON($,w){return w?.keep?this.value:lR.toJS(this.value,$,w)}toString(){return String(this.value)}}u1.BLOCK_FOLDED="BLOCK_FOLDED";u1.BLOCK_LITERAL="BLOCK_LITERAL";u1.PLAIN="PLAIN";u1.QUOTE_DOUBLE="QUOTE_DOUBLE";u1.QUOTE_SINGLE="QUOTE_SINGLE";cR.Scalar=u1;cR.isScalarValue=dR});var M9=F((oR)=>{var rR=z9(),h1=r(),yM=W0(),sR="tag:yaml.org,2002:";function aR($,w,G){if(w){let Z=G.filter((Y)=>Y.tag===w),X=Z.find((Y)=>!Y.format)??Z[0];if(!X)throw Error(`Tag ${w} not found`);return X}return G.find((Z)=>Z.identify?.($)&&!Z.format)}function tR($,w,G){if(h1.isDocument($))$=$.contents;if(h1.isNode($))return $;if(h1.isPair($)){let M=G.schema[h1.MAP].createNode?.(G.schema,null,G);return M.items.push($),M}if($ instanceof String||$ instanceof Number||$ instanceof Boolean||typeof BigInt<"u"&&$ instanceof BigInt)$=$.valueOf();let{aliasDuplicateObjects:Z,onAnchor:X,onTagObj:Y,schema:J,sourceObjects:W}=G,T=void 0;if(Z&&$&&typeof $==="object")if(T=W.get($),T)return T.anchor??(T.anchor=X($)),new rR.Alias(T.anchor);else T={anchor:null,node:null},W.set($,T);if(w?.startsWith("!!"))w=sR+w.slice(2);let Q=aR($,w,J.tags);if(!Q){if($&&typeof $.toJSON==="function")$=$.toJSON();if(!$||typeof $!=="object"){let M=new yM.Scalar($);if(T)T.node=M;return M}Q=$ instanceof Map?J[h1.MAP]:(Symbol.iterator in Object($))?J[h1.SEQ]:J[h1.MAP]}if(Y)Y(Q),delete G.onTagObj;let z=Q?.createNode?Q.createNode(G.schema,$,G):typeof Q?.nodeClass?.from==="function"?Q.nodeClass.from(G.schema,$,G):new yM.Scalar($);if(w)z.tag=w;else if(!Q.default)z.tag=Q.tag;if(T)T.node=z;return z}oR.createNode=tR});var H5=F((GS)=>{var $S=M9(),V$=r(),wS=K5();function oZ($,w,G){let Z=G;for(let X=w.length-1;X>=0;--X){let Y=w[X];if(typeof Y==="number"&&Number.isInteger(Y)&&Y>=0){let J=[];J[Y]=Z,Z=J}else Z=new Map([[Y,Z]])}return $S.createNode(Z,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error("This should not happen, please report a bug.")},schema:$,sourceObjects:new Map})}var _M=($)=>$==null||typeof $==="object"&&!!$[Symbol.iterator]().next().done;class xM extends wS.NodeBase{constructor($,w){super($);Object.defineProperty(this,"schema",{value:w,configurable:!0,enumerable:!1,writable:!0})}clone($){let w=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));if($)w.schema=$;if(w.items=w.items.map((G)=>V$.isNode(G)||V$.isPair(G)?G.clone($):G),this.range)w.range=this.range.slice();return w}addIn($,w){if(_M($))this.add(w);else{let[G,...Z]=$,X=this.get(G,!0);if(V$.isCollection(X))X.addIn(Z,w);else if(X===void 0&&this.schema)this.set(G,oZ(this.schema,Z,w));else throw Error(`Expected YAML collection at ${G}. Remaining path: ${Z}`)}}deleteIn($){let[w,...G]=$;if(G.length===0)return this.delete(w);let Z=this.get(w,!0);if(V$.isCollection(Z))return Z.deleteIn(G);else throw Error(`Expected YAML collection at ${w}. Remaining path: ${G}`)}getIn($,w){let[G,...Z]=$,X=this.get(G,!0);if(Z.length===0)return!w&&V$.isScalar(X)?X.value:X;else return V$.isCollection(X)?X.getIn(Z,w):void 0}hasAllNullValues($){return this.items.every((w)=>{if(!V$.isPair(w))return!1;let G=w.value;return G==null||$&&V$.isScalar(G)&&G.value==null&&!G.commentBefore&&!G.comment&&!G.tag})}hasIn($){let[w,...G]=$;if(G.length===0)return this.has(w);let Z=this.get(w,!0);return V$.isCollection(Z)?Z.hasIn(G):!1}setIn($,w){let[G,...Z]=$;if(Z.length===0)this.set(G,w);else{let X=this.get(G,!0);if(V$.isCollection(X))X.setIn(Z,w);else if(X===void 0&&this.schema)this.set(G,oZ(this.schema,Z,w));else throw Error(`Expected YAML collection at ${G}. Remaining path: ${Z}`)}}}GS.Collection=xM;GS.collectionFromPath=oZ;GS.isEmptyPath=_M});var P9=F((TS)=>{var JS=($)=>$.replace(/^(?!$)(?: $)?/gm,"#");function eZ($,w){if(/^\n+$/.test($))return $.substring(1);return w?$.replace(/^(?! *$)/gm,w):$}var WS=($,w,G)=>$.endsWith(`
37
+ `)?eZ(G,w):G.includes(`
38
+ `)?`
39
+ `+eZ(G,w):($.endsWith(" ")?"":" ")+G;TS.indentComment=eZ;TS.lineComment=WS;TS.stringifyComment=JS});var uM=F((qS)=>{function PS($,w,G="flow",{indentAtStart:Z,lineWidth:X=80,minContentWidth:Y=20,onFold:J,onOverflow:W}={}){if(!X||X<0)return $;if(X<Y)Y=0;let T=Math.max(1+Y,1+X-w.length);if($.length<=T)return $;let Q=[],z={},M=X-w.length;if(typeof Z==="number")if(Z>X-Math.max(2,Y))Q.push(0);else M=X-Z;let P=void 0,q=void 0,N=!1,B=-1,V=-1,K=-1;if(G==="block"){if(B=gM($,B,w.length),B!==-1)M=B+T}for(let O;O=$[B+=1];){if(G==="quoted"&&O==="\\"){switch(V=B,$[B+1]){case"x":B+=3;break;case"u":B+=5;break;case"U":B+=9;break;default:B+=1}K=B}if(O===`
40
+ `){if(G==="block")B=gM($,B,w.length);M=B+w.length+T,P=void 0}else{if(O===" "&&q&&q!==" "&&q!==`
41
+ `&&q!=="\t"){let D=$[B+1];if(D&&D!==" "&&D!==`
42
+ `&&D!=="\t")P=B}if(B>=M)if(P)Q.push(P),M=P+T,P=void 0;else if(G==="quoted"){while(q===" "||q==="\t")q=O,O=$[B+=1],N=!0;let D=B>K+1?B-2:V-1;if(z[D])return $;Q.push(D),z[D]=!0,M=D+T,P=void 0}else N=!0}q=O}if(N&&W)W();if(Q.length===0)return $;if(J)J();let U=$.slice(0,Q[0]);for(let O=0;O<Q.length;++O){let D=Q[O],f=Q[O+1]||$.length;if(D===0)U=`
43
+ ${w}${$.slice(0,f)}`;else{if(G==="quoted"&&z[D])U+=`${$[D]}\\`;U+=`
44
+ ${w}${$.slice(D+1,f)}`}}return U}function gM($,w,G){let Z=w,X=w+1,Y=$[X];while(Y===" "||Y==="\t")if(w<X+G)Y=$[++w];else{do Y=$[++w];while(Y&&Y!==`
45
+ `);Z=w,X=w+1,Y=$[X]}return Z}qS.FOLD_BLOCK="block";qS.FOLD_FLOW="flow";qS.FOLD_QUOTED="quoted";qS.foldFlowLines=PS});var B9=F((OS)=>{var X$=W0(),X1=uM(),O5=($,w)=>({indentAtStart:w?$.indent.length:$.indentAtStart,lineWidth:$.options.lineWidth,minContentWidth:$.options.minContentWidth}),f5=($)=>/^(%|---|\.\.\.)/m.test($);function US($,w,G){if(!w||w<0)return!1;let Z=w-G,X=$.length;if(X<=Z)return!1;for(let Y=0,J=0;Y<X;++Y)if($[Y]===`
46
+ `){if(Y-J>Z)return!0;if(J=Y+1,X-J<=Z)return!1}return!0}function q9($,w){let G=JSON.stringify($);if(w.options.doubleQuotedAsJSON)return G;let{implicitKey:Z}=w,X=w.options.doubleQuotedMinMultiLineLength,Y=w.indent||(f5($)?" ":""),J="",W=0;for(let T=0,Q=G[T];Q;Q=G[++T]){if(Q===" "&&G[T+1]==="\\"&&G[T+2]==="n")J+=G.slice(W,T)+"\\ ",T+=1,W=T,Q="\\";if(Q==="\\")switch(G[T+1]){case"u":{J+=G.slice(W,T);let z=G.substr(T+2,4);switch(z){case"0000":J+="\\0";break;case"0007":J+="\\a";break;case"000b":J+="\\v";break;case"001b":J+="\\e";break;case"0085":J+="\\N";break;case"00a0":J+="\\_";break;case"2028":J+="\\L";break;case"2029":J+="\\P";break;default:if(z.substr(0,2)==="00")J+="\\x"+z.substr(2);else J+=G.substr(T,6)}T+=5,W=T+1}break;case"n":if(Z||G[T+2]==='"'||G.length<X)T+=1;else{J+=G.slice(W,T)+`
47
+
48
+ `;while(G[T+2]==="\\"&&G[T+3]==="n"&&G[T+4]!=='"')J+=`
49
+ `,T+=2;if(J+=Y,G[T+2]===" ")J+="\\";T+=1,W=T+1}break;default:T+=1}}return J=W?J+G.slice(W):G,Z?J:X1.foldFlowLines(J,Y,X1.FOLD_QUOTED,O5(w,!1))}function $X($,w){if(w.options.singleQuote===!1||w.implicitKey&&$.includes(`
50
+ `)||/[ \t]\n|\n[ \t]/.test($))return q9($,w);let G=w.indent||(f5($)?" ":""),Z="'"+$.replace(/'/g,"''").replace(/\n+/g,`$&
51
+ ${G}`)+"'";return w.implicitKey?Z:X1.foldFlowLines(Z,G,X1.FOLD_FLOW,O5(w,!1))}function mw($,w){let{singleQuote:G}=w.options,Z;if(G===!1)Z=q9;else{let X=$.includes('"'),Y=$.includes("'");if(X&&!Y)Z=$X;else if(Y&&!X)Z=q9;else Z=G?$X:q9}return Z($,w)}var wX;try{wX=new RegExp(`(^|(?<!
52
+ ))
53
+ +(?!
54
+ |$)`,"g")}catch{wX=/\n+(?!\n|$)/g}function F5({comment:$,type:w,value:G},Z,X,Y){let{blockQuote:J,commentString:W,lineWidth:T}=Z.options;if(!J||/\n[\t ]+$/.test(G))return mw(G,Z);let Q=Z.indent||(Z.forceBlockIndent||f5(G)?" ":""),z=J==="literal"?!0:J==="folded"||w===X$.Scalar.BLOCK_FOLDED?!1:w===X$.Scalar.BLOCK_LITERAL?!0:!US(G,T,Q.length);if(!G)return z?`|
55
+ `:`>
56
+ `;let M,P;for(P=G.length;P>0;--P){let f=G[P-1];if(f!==`
57
+ `&&f!=="\t"&&f!==" ")break}let q=G.substring(P),N=q.indexOf(`
58
+ `);if(N===-1)M="-";else if(G===q||N!==q.length-1){if(M="+",Y)Y()}else M="";if(q){if(G=G.slice(0,-q.length),q[q.length-1]===`
59
+ `)q=q.slice(0,-1);q=q.replace(wX,`$&${Q}`)}let B=!1,V,K=-1;for(V=0;V<G.length;++V){let f=G[V];if(f===" ")B=!0;else if(f===`
60
+ `)K=V;else break}let U=G.substring(0,K<V?K+1:V);if(U)G=G.substring(U.length),U=U.replace(/\n+/g,`$&${Q}`);let D=(B?Q?"2":"1":"")+M;if($){if(D+=" "+W($.replace(/ ?[\r\n]+/g," ")),X)X()}if(!z){let f=G.replace(/\n+/g,`
61
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${Q}`),L=!1,C=O5(Z,!0);if(J!=="folded"&&w!==X$.Scalar.BLOCK_FOLDED)C.onOverflow=()=>{L=!0};let S=X1.foldFlowLines(`${U}${f}${q}`,Q,X1.FOLD_BLOCK,C);if(!L)return`>${D}
62
+ ${Q}${S}`}return G=G.replace(/\n+/g,`$&${Q}`),`|${D}
63
+ ${Q}${U}${G}${q}`}function HS($,w,G,Z){let{type:X,value:Y}=$,{actualString:J,implicitKey:W,indent:T,indentStep:Q,inFlow:z}=w;if(W&&Y.includes(`
64
+ `)||z&&/[[\]{},]/.test(Y))return mw(Y,w);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(Y))return W||z||!Y.includes(`
65
+ `)?mw(Y,w):F5($,w,G,Z);if(!W&&!z&&X!==X$.Scalar.PLAIN&&Y.includes(`
66
+ `))return F5($,w,G,Z);if(f5(Y)){if(T==="")return w.forceBlockIndent=!0,F5($,w,G,Z);else if(W&&T===Q)return mw(Y,w)}let M=Y.replace(/\n+/g,`$&
67
+ ${T}`);if(J){let P=(B)=>B.default&&B.tag!=="tag:yaml.org,2002:str"&&B.test?.test(M),{compat:q,tags:N}=w.doc.schema;if(N.some(P)||q?.some(P))return mw(Y,w)}return W?M:X1.foldFlowLines(M,T,X1.FOLD_FLOW,O5(w,!1))}function FS($,w,G,Z){let{implicitKey:X,inFlow:Y}=w,J=typeof $.value==="string"?$:Object.assign({},$,{value:String($.value)}),{type:W}=$;if(W!==X$.Scalar.QUOTE_DOUBLE){if(/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(J.value))W=X$.Scalar.QUOTE_DOUBLE}let T=(z)=>{switch(z){case X$.Scalar.BLOCK_FOLDED:case X$.Scalar.BLOCK_LITERAL:return X||Y?mw(J.value,w):F5(J,w,G,Z);case X$.Scalar.QUOTE_DOUBLE:return q9(J.value,w);case X$.Scalar.QUOTE_SINGLE:return $X(J.value,w);case X$.Scalar.PLAIN:return HS(J,w,G,Z);default:return null}},Q=T(W);if(Q===null){let{defaultKeyType:z,defaultStringType:M}=w.options,P=X&&z||M;if(Q=T(P),Q===null)throw Error(`Unsupported default string type ${P}`)}return Q}OS.stringifyString=FS});var N9=F((jS)=>{var LS=V5(),Y1=r(),DS=P9(),ES=B9();function AS($,w){let G=Object.assign({blockQuote:!0,commentString:DS.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},$.schema.toStringOptions,w),Z;switch(G.collectionStyle){case"block":Z=!1;break;case"flow":Z=!0;break;default:Z=null}return{anchors:new Set,doc:$,flowCollectionPadding:G.flowCollectionPadding?" ":"",indent:"",indentStep:typeof G.indent==="number"?" ".repeat(G.indent):" ",inFlow:Z,options:G}}function RS($,w){if(w.tag){let X=$.filter((Y)=>Y.tag===w.tag);if(X.length>0)return X.find((Y)=>Y.format===w.format)??X[0]}let G=void 0,Z;if(Y1.isScalar(w)){Z=w.value;let X=$.filter((Y)=>Y.identify?.(Z));if(X.length>1){let Y=X.filter((J)=>J.test);if(Y.length>0)X=Y}G=X.find((Y)=>Y.format===w.format)??X.find((Y)=>!Y.format)}else Z=w,G=$.find((X)=>X.nodeClass&&Z instanceof X.nodeClass);if(!G){let X=Z?.constructor?.name??(Z===null?"null":typeof Z);throw Error(`Tag not resolved for ${X} value`)}return G}function SS($,w,{anchors:G,doc:Z}){if(!Z.directives)return"";let X=[],Y=(Y1.isScalar($)||Y1.isCollection($))&&$.anchor;if(Y&&LS.anchorIsValid(Y))G.add(Y),X.push(`&${Y}`);let J=$.tag??(w.default?null:w.tag);if(J)X.push(Z.directives.tagString(J));return X.join(" ")}function IS($,w,G,Z){if(Y1.isPair($))return $.toString(w,G,Z);if(Y1.isAlias($)){if(w.doc.directives)return $.toString(w);if(w.resolvedAliases?.has($))throw TypeError("Cannot stringify circular structure without alias nodes");else{if(w.resolvedAliases)w.resolvedAliases.add($);else w.resolvedAliases=new Set([$]);$=$.resolve(w.doc)}}let X=void 0,Y=Y1.isNode($)?$:w.doc.createNode($,{onTagObj:(T)=>X=T});X??(X=RS(w.doc.schema.tags,Y));let J=SS(Y,X,w);if(J.length>0)w.indentAtStart=(w.indentAtStart??0)+J.length+1;let W=typeof X.stringify==="function"?X.stringify(Y,w,G,Z):Y1.isScalar(Y)?ES.stringifyString(Y,w,G,Z):Y.toString(w,G,Z);if(!J)return W;return Y1.isScalar(Y)||W[0]==="{"||W[0]==="["?`${J} ${W}`:`${J}
68
+ ${w.indent}${W}`}jS.createStringifyContext=AS;jS.stringify=IS});var iM=F((yS)=>{var b$=r(),hM=W0(),vM=N9(),V9=P9();function kS({key:$,value:w},G,Z,X){let{allNullValues:Y,doc:J,indent:W,indentStep:T,options:{commentString:Q,indentSeq:z,simpleKeys:M}}=G,P=b$.isNode($)&&$.comment||null;if(M){if(P)throw Error("With simple keys, key nodes cannot have comments");if(b$.isCollection($)||!b$.isNode($)&&typeof $==="object")throw Error("With simple keys, collection cannot be used as a key value")}let q=!M&&(!$||P&&w==null&&!G.inFlow||b$.isCollection($)||(b$.isScalar($)?$.type===hM.Scalar.BLOCK_FOLDED||$.type===hM.Scalar.BLOCK_LITERAL:typeof $==="object"));G=Object.assign({},G,{allNullValues:!1,implicitKey:!q&&(M||!Y),indent:W+T});let N=!1,B=!1,V=vM.stringify($,G,()=>N=!0,()=>B=!0);if(!q&&!G.inFlow&&V.length>1024){if(M)throw Error("With simple keys, single line scalar must not span more than 1024 characters");q=!0}if(G.inFlow){if(Y||w==null){if(N&&Z)Z();return V===""?"?":q?`? ${V}`:V}}else if(Y&&!M||w==null&&q){if(V=`? ${V}`,P&&!N)V+=V9.lineComment(V,G.indent,Q(P));else if(B&&X)X();return V}if(N)P=null;if(q){if(P)V+=V9.lineComment(V,G.indent,Q(P));V=`? ${V}
69
+ ${W}:`}else if(V=`${V}:`,P)V+=V9.lineComment(V,G.indent,Q(P));let K,U,O;if(b$.isNode(w))K=!!w.spaceBefore,U=w.commentBefore,O=w.comment;else if(K=!1,U=null,O=null,w&&typeof w==="object")w=J.createNode(w);if(G.implicitKey=!1,!q&&!P&&b$.isScalar(w))G.indentAtStart=V.length+1;if(B=!1,!z&&T.length>=2&&!G.inFlow&&!q&&b$.isSeq(w)&&!w.flow&&!w.tag&&!w.anchor)G.indent=G.indent.substring(2);let D=!1,f=vM.stringify(w,G,()=>D=!0,()=>B=!0),L=" ";if(P||K||U){if(L=K?`
70
+ `:"",U){let C=Q(U);L+=`
71
+ ${V9.indentComment(C,G.indent)}`}if(f===""&&!G.inFlow){if(L===`
72
+ `&&O)L=`
73
+
74
+ `}else L+=`
75
+ ${G.indent}`}else if(!q&&b$.isCollection(w)){let C=f[0],S=f.indexOf(`
76
+ `),h=S!==-1,g=G.inFlow??w.flow??w.items.length===0;if(h||!g){let G0=!1;if(h&&(C==="&"||C==="!")){let e=f.indexOf(" ");if(C==="&"&&e!==-1&&e<S&&f[e+1]==="!")e=f.indexOf(" ",e+1);if(e===-1||S<e)G0=!0}if(!G0)L=`
77
+ ${G.indent}`}}else if(f===""||f[0]===`
78
+ `)L="";if(V+=L+f,G.inFlow){if(D&&Z)Z()}else if(O&&!D)V+=V9.lineComment(V,G.indent,Q(O));else if(B&&X)X();return V}yS.stringifyPair=kS});var GX=F((uS)=>{var mM=D$("process");function xS($,...w){if($==="debug")console.log(...w)}function gS($,w){if($==="debug"||$==="warn")if(typeof mM.emitWarning==="function")mM.emitWarning(w);else console.warn(w)}uS.debug=xS;uS.warn=gS});var A5=F((mS)=>{var E5=r(),lM=W0(),L5="<<",D5={identify:($)=>$===L5||typeof $==="symbol"&&$.description===L5,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new lM.Scalar(Symbol(L5)),{addToJSMap:dM}),stringify:()=>L5},iS=($,w)=>(D5.identify(w)||E5.isScalar(w)&&(!w.type||w.type===lM.Scalar.PLAIN)&&D5.identify(w.value))&&$?.doc.schema.tags.some((G)=>G.tag===D5.tag&&G.default);function dM($,w,G){let Z=cM($,G);if(E5.isSeq(Z))for(let X of Z.items)ZX($,w,X);else if(Array.isArray(Z))for(let X of Z)ZX($,w,X);else ZX($,w,Z)}function ZX($,w,G){let Z=cM($,G);if(!E5.isMap(Z))throw Error("Merge sources must be maps or map aliases");let X=Z.toJSON(null,$,Map);for(let[Y,J]of X)if(w instanceof Map){if(!w.has(Y))w.set(Y,J)}else if(w instanceof Set)w.add(Y);else if(!Object.prototype.hasOwnProperty.call(w,Y))Object.defineProperty(w,Y,{value:J,writable:!0,enumerable:!0,configurable:!0});return w}function cM($,w){return $&&E5.isAlias(w)?w.resolve($.doc,$):w}mS.addMergeToJSMap=dM;mS.isMergeKey=iS;mS.merge=D5});var YX=F((aS)=>{var pS=GX(),pM=A5(),nS=N9(),nM=r(),XX=Z1();function rS($,w,{key:G,value:Z}){if(nM.isNode(G)&&G.addToJSMap)G.addToJSMap($,w,Z);else if(pM.isMergeKey($,G))pM.addMergeToJSMap($,w,Z);else{let X=XX.toJS(G,"",$);if(w instanceof Map)w.set(X,XX.toJS(Z,X,$));else if(w instanceof Set)w.add(X);else{let Y=sS(G,X,$),J=XX.toJS(Z,Y,$);if(Y in w)Object.defineProperty(w,Y,{value:J,writable:!0,enumerable:!0,configurable:!0});else w[Y]=J}}return w}function sS($,w,G){if(w===null)return"";if(typeof w!=="object")return String(w);if(nM.isNode($)&&G?.doc){let Z=nS.createStringifyContext(G.doc,{});Z.anchors=new Set;for(let Y of G.anchors.keys())Z.anchors.add(Y.anchor);Z.inFlow=!0,Z.inStringifyKey=!0;let X=$.toString(Z);if(!G.mapKeyWarned){let Y=JSON.stringify(X);if(Y.length>40)Y=Y.substring(0,36)+'..."';pS.warn(G.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${Y}. Set mapAsMap: true to use object keys.`),G.mapKeyWarned=!0}return X}return JSON.stringify(w)}aS.addPairToJSMap=rS});var J1=F((w2)=>{var rM=M9(),oS=iM(),eS=YX(),R5=r();function $2($,w,G){let Z=rM.createNode($,void 0,G),X=rM.createNode(w,void 0,G);return new S5(Z,X)}class S5{constructor($,w=null){Object.defineProperty(this,R5.NODE_TYPE,{value:R5.PAIR}),this.key=$,this.value=w}clone($){let{key:w,value:G}=this;if(R5.isNode(w))w=w.clone($);if(R5.isNode(G))G=G.clone($);return new S5(w,G)}toJSON($,w){let G=w?.mapAsMap?new Map:{};return eS.addPairToJSMap(w,G,this)}toString($,w,G){return $?.doc?oS.stringifyPair(this,$,w,G):JSON.stringify(this)}}w2.Pair=S5;w2.createPair=$2});var JX=F((W2)=>{var v1=r(),sM=N9(),I5=P9();function X2($,w,G){return(w.inFlow??$.flow?J2:Y2)($,w,G)}function Y2({comment:$,items:w},G,{blockItemPrefix:Z,flowChars:X,itemIndent:Y,onChompKeep:J,onComment:W}){let{indent:T,options:{commentString:Q}}=G,z=Object.assign({},G,{indent:Y,type:null}),M=!1,P=[];for(let N=0;N<w.length;++N){let B=w[N],V=null;if(v1.isNode(B)){if(!M&&B.spaceBefore)P.push("");if(j5(G,P,B.commentBefore,M),B.comment)V=B.comment}else if(v1.isPair(B)){let U=v1.isNode(B.key)?B.key:null;if(U){if(!M&&U.spaceBefore)P.push("");j5(G,P,U.commentBefore,M)}}M=!1;let K=sM.stringify(B,z,()=>V=null,()=>M=!0);if(V)K+=I5.lineComment(K,Y,Q(V));if(M&&V)M=!1;P.push(Z+K)}let q;if(P.length===0)q=X.start+X.end;else{q=P[0];for(let N=1;N<P.length;++N){let B=P[N];q+=B?`
79
+ ${T}${B}`:`
80
+ `}}if($){if(q+=`
81
+ `+I5.indentComment(Q($),T),W)W()}else if(M&&J)J();return q}function J2({items:$},w,{flowChars:G,itemIndent:Z}){let{indent:X,indentStep:Y,flowCollectionPadding:J,options:{commentString:W}}=w;Z+=Y;let T=Object.assign({},w,{indent:Z,inFlow:!0,type:null}),Q=!1,z=0,M=[];for(let N=0;N<$.length;++N){let B=$[N],V=null;if(v1.isNode(B)){if(B.spaceBefore)M.push("");if(j5(w,M,B.commentBefore,!1),B.comment)V=B.comment}else if(v1.isPair(B)){let U=v1.isNode(B.key)?B.key:null;if(U){if(U.spaceBefore)M.push("");if(j5(w,M,U.commentBefore,!1),U.comment)Q=!0}let O=v1.isNode(B.value)?B.value:null;if(O){if(O.comment)V=O.comment;if(O.commentBefore)Q=!0}else if(B.value==null&&U?.comment)V=U.comment}if(V)Q=!0;let K=sM.stringify(B,T,()=>V=null);if(Q||(Q=M.length>z||K.includes(`
82
+ `)),N<$.length-1)K+=",";else if(w.options.trailingComma){if(w.options.lineWidth>0)Q||(Q=M.reduce((U,O)=>U+O.length+2,2)+(K.length+2)>w.options.lineWidth);if(Q)K+=","}if(V)K+=I5.lineComment(K,Z,W(V));M.push(K),z=M.length}let{start:P,end:q}=G;if(M.length===0)return P+q;else{if(!Q){let N=M.reduce((B,V)=>B+V.length+2,2);Q=w.options.lineWidth>0&&N>w.options.lineWidth}if(Q){let N=P;for(let B of M)N+=B?`
83
+ ${Y}${X}${B}`:`
84
+ `;return`${N}
85
+ ${X}${q}`}else return`${P}${J}${M.join(" ")}${J}${q}`}}function j5({indent:$,options:{commentString:w}},G,Z,X){if(Z&&X)Z=Z.replace(/^\n+/,"");if(Z){let Y=I5.indentComment(w(Z),$);G.push(Y.trimStart())}}W2.stringifyCollection=X2});var T1=F((q2)=>{var Q2=JX(),z2=YX(),M2=H5(),W1=r(),C5=J1(),P2=W0();function K9($,w){let G=W1.isScalar(w)?w.value:w;for(let Z of $)if(W1.isPair(Z)){if(Z.key===w||Z.key===G)return Z;if(W1.isScalar(Z.key)&&Z.key.value===G)return Z}return}class aM extends M2.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor($){super(W1.MAP,$);this.items=[]}static from($,w,G){let{keepUndefined:Z,replacer:X}=G,Y=new this($),J=(W,T)=>{if(typeof X==="function")T=X.call(w,W,T);else if(Array.isArray(X)&&!X.includes(W))return;if(T!==void 0||Z)Y.items.push(C5.createPair(W,T,G))};if(w instanceof Map)for(let[W,T]of w)J(W,T);else if(w&&typeof w==="object")for(let W of Object.keys(w))J(W,w[W]);if(typeof $.sortMapEntries==="function")Y.items.sort($.sortMapEntries);return Y}add($,w){let G;if(W1.isPair($))G=$;else if(!$||typeof $!=="object"||!("key"in $))G=new C5.Pair($,$?.value);else G=new C5.Pair($.key,$.value);let Z=K9(this.items,G.key),X=this.schema?.sortMapEntries;if(Z){if(!w)throw Error(`Key ${G.key} already set`);if(W1.isScalar(Z.value)&&P2.isScalarValue(G.value))Z.value.value=G.value;else Z.value=G.value}else if(X){let Y=this.items.findIndex((J)=>X(G,J)<0);if(Y===-1)this.items.push(G);else this.items.splice(Y,0,G)}else this.items.push(G)}delete($){let w=K9(this.items,$);if(!w)return!1;return this.items.splice(this.items.indexOf(w),1).length>0}get($,w){let Z=K9(this.items,$)?.value;return(!w&&W1.isScalar(Z)?Z.value:Z)??void 0}has($){return!!K9(this.items,$)}set($,w){this.add(new C5.Pair($,w),!0)}toJSON($,w,G){let Z=G?new G:w?.mapAsMap?new Map:{};if(w?.onCreate)w.onCreate(Z);for(let X of this.items)z2.addPairToJSMap(w,Z,X);return Z}toString($,w,G){if(!$)return JSON.stringify(this);for(let Z of this.items)if(!W1.isPair(Z))throw Error(`Map items must all be pairs; found ${JSON.stringify(Z)} instead`);if(!$.allNullValues&&this.hasAllNullValues(!1))$=Object.assign({},$,{allNullValues:!0});return Q2.stringifyCollection(this,$,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:$.indent||"",onChompKeep:G,onComment:w})}}q2.YAMLMap=aM;q2.findPair=K9});var lw=F((U2)=>{var V2=r(),tM=T1(),K2={collection:"map",default:!0,nodeClass:tM.YAMLMap,tag:"tag:yaml.org,2002:map",resolve($,w){if(!V2.isMap($))w("Expected a mapping for this tag");return $},createNode:($,w,G)=>tM.YAMLMap.from($,w,G)};U2.map=K2});var Q1=F((E2)=>{var F2=M9(),O2=JX(),f2=H5(),k5=r(),L2=W0(),D2=Z1();class oM extends f2.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor($){super(k5.SEQ,$);this.items=[]}add($){this.items.push($)}delete($){let w=b5($);if(typeof w!=="number")return!1;return this.items.splice(w,1).length>0}get($,w){let G=b5($);if(typeof G!=="number")return;let Z=this.items[G];return!w&&k5.isScalar(Z)?Z.value:Z}has($){let w=b5($);return typeof w==="number"&&w<this.items.length}set($,w){let G=b5($);if(typeof G!=="number")throw Error(`Expected a valid index, not ${$}.`);let Z=this.items[G];if(k5.isScalar(Z)&&L2.isScalarValue(w))Z.value=w;else this.items[G]=w}toJSON($,w){let G=[];if(w?.onCreate)w.onCreate(G);let Z=0;for(let X of this.items)G.push(D2.toJS(X,String(Z++),w));return G}toString($,w,G){if(!$)return JSON.stringify(this);return O2.stringifyCollection(this,$,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:($.indent||"")+" ",onChompKeep:G,onComment:w})}static from($,w,G){let{replacer:Z}=G,X=new this($);if(w&&Symbol.iterator in Object(w)){let Y=0;for(let J of w){if(typeof Z==="function"){let W=w instanceof Set?J:String(Y++);J=Z.call(w,W,J)}X.items.push(F2.createNode(J,void 0,G))}}return X}}function b5($){let w=k5.isScalar($)?$.value:$;if(w&&typeof w==="string")w=Number(w);return typeof w==="number"&&Number.isInteger(w)&&w>=0?w:null}E2.YAMLSeq=oM});var dw=F((I2)=>{var R2=r(),eM=Q1(),S2={collection:"seq",default:!0,nodeClass:eM.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve($,w){if(!R2.isSeq($))w("Expected a sequence for this tag");return $},createNode:($,w,G)=>eM.YAMLSeq.from($,w,G)};I2.seq=S2});var U9=F((k2)=>{var C2=B9(),b2={identify:($)=>typeof $==="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:($)=>$,stringify($,w,G,Z){return w=Object.assign({actualString:!0},w),C2.stringifyString($,w,G,Z)}};k2.string=b2});var y5=F((_2)=>{var $P=W0(),wP={identify:($)=>$==null,createNode:()=>new $P.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new $P.Scalar(null),stringify:({source:$},w)=>typeof $==="string"&&wP.test.test($)?$:w.options.nullStr};_2.nullTag=wP});var WX=F((u2)=>{var g2=W0(),GP={identify:($)=>typeof $==="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:($)=>new g2.Scalar($[0]==="t"||$[0]==="T"),stringify({source:$,value:w},G){if($&&GP.test.test($)){let Z=$[0]==="t"||$[0]==="T";if(w===Z)return $}return w?G.options.trueStr:G.options.falseStr}};u2.boolTag=GP});var cw=F((i2)=>{function v2({format:$,minFractionDigits:w,tag:G,value:Z}){if(typeof Z==="bigint")return String(Z);let X=typeof Z==="number"?Z:Number(Z);if(!isFinite(X))return isNaN(X)?".nan":X<0?"-.inf":".inf";let Y=Object.is(Z,-0)?"-0":JSON.stringify(Z);if(!$&&w&&(!G||G==="tag:yaml.org,2002:float")&&/^-?\d/.test(Y)&&!Y.includes("e")){let J=Y.indexOf(".");if(J<0)J=Y.length,Y+=".";let W=w-(Y.length-J-1);while(W-- >0)Y+="0"}return Y}i2.stringifyNumber=v2});var QX=F((n2)=>{var l2=W0(),TX=cw(),d2={identify:($)=>typeof $==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:($)=>$.slice(-3).toLowerCase()==="nan"?NaN:$[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:TX.stringifyNumber},c2={identify:($)=>typeof $==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:($)=>parseFloat($),stringify($){let w=Number($.value);return isFinite(w)?w.toExponential():TX.stringifyNumber($)}},p2={identify:($)=>typeof $==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve($){let w=new l2.Scalar(parseFloat($)),G=$.indexOf(".");if(G!==-1&&$[$.length-1]==="0")w.minFractionDigits=$.length-G-1;return w},stringify:TX.stringifyNumber};n2.float=p2;n2.floatExp=c2;n2.floatNaN=d2});var MX=F(($I)=>{var ZP=cw(),_5=($)=>typeof $==="bigint"||Number.isInteger($),zX=($,w,G,{intAsBigInt:Z})=>Z?BigInt($):parseInt($.substring(w),G);function XP($,w,G){let{value:Z}=$;if(_5(Z)&&Z>=0)return G+Z.toString(w);return ZP.stringifyNumber($)}var t2={identify:($)=>_5($)&&$>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:($,w,G)=>zX($,2,8,G),stringify:($)=>XP($,8,"0o")},o2={identify:_5,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:($,w,G)=>zX($,0,10,G),stringify:ZP.stringifyNumber},e2={identify:($)=>_5($)&&$>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:($,w,G)=>zX($,2,16,G),stringify:($)=>XP($,16,"0x")};$I.int=o2;$I.intHex=e2;$I.intOct=t2});var YP=F((zI)=>{var XI=lw(),YI=y5(),JI=dw(),WI=U9(),TI=WX(),PX=QX(),qX=MX(),QI=[XI.map,JI.seq,WI.string,YI.nullTag,TI.boolTag,qX.intOct,qX.int,qX.intHex,PX.floatNaN,PX.floatExp,PX.float];zI.schema=QI});var WP=F((UI)=>{var PI=W0(),qI=lw(),BI=dw();function JP($){return typeof $==="bigint"||Number.isInteger($)}var x5=({value:$})=>JSON.stringify($),NI=[{identify:($)=>typeof $==="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:($)=>$,stringify:x5},{identify:($)=>$==null,createNode:()=>new PI.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:x5},{identify:($)=>typeof $==="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:($)=>$==="true",stringify:x5},{identify:JP,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:($,w,{intAsBigInt:G})=>G?BigInt($):parseInt($,10),stringify:({value:$})=>JP($)?$.toString():JSON.stringify($)},{identify:($)=>typeof $==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:($)=>parseFloat($),stringify:x5}],VI={default:!0,tag:"",test:/^/,resolve($,w){return w(`Unresolved plain scalar ${JSON.stringify($)}`),$}},KI=[qI.map,BI.seq].concat(NI,VI);UI.schema=KI});var NX=F((fI)=>{var H9=D$("buffer"),BX=W0(),FI=B9(),OI={identify:($)=>$ instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve($,w){if(typeof H9.Buffer==="function")return H9.Buffer.from($,"base64");else if(typeof atob==="function"){let G=atob($.replace(/[\n\r]/g,"")),Z=new Uint8Array(G.length);for(let X=0;X<G.length;++X)Z[X]=G.charCodeAt(X);return Z}else return w("This environment does not support reading binary tags; either Buffer or atob is required"),$},stringify({comment:$,type:w,value:G},Z,X,Y){if(!G)return"";let J=G,W;if(typeof H9.Buffer==="function")W=J instanceof H9.Buffer?J.toString("base64"):H9.Buffer.from(J.buffer).toString("base64");else if(typeof btoa==="function"){let T="";for(let Q=0;Q<J.length;++Q)T+=String.fromCharCode(J[Q]);W=btoa(T)}else throw Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(w??(w=BX.Scalar.BLOCK_LITERAL),w!==BX.Scalar.QUOTE_DOUBLE){let T=Math.max(Z.options.lineWidth-Z.indent.length,Z.options.minContentWidth),Q=Math.ceil(W.length/T),z=Array(Q);for(let M=0,P=0;M<Q;++M,P+=T)z[M]=W.substr(P,T);W=z.join(w===BX.Scalar.BLOCK_LITERAL?`
86
+ `:" ")}return FI.stringifyString({comment:$,type:w,value:W},Z,X,Y)}};fI.binary=OI});var u5=F((RI)=>{var g5=r(),VX=J1(),DI=W0(),EI=Q1();function TP($,w){if(g5.isSeq($))for(let G=0;G<$.items.length;++G){let Z=$.items[G];if(g5.isPair(Z))continue;else if(g5.isMap(Z)){if(Z.items.length>1)w("Each pair must have its own sequence indicator");let X=Z.items[0]||new VX.Pair(new DI.Scalar(null));if(Z.commentBefore)X.key.commentBefore=X.key.commentBefore?`${Z.commentBefore}
87
+ ${X.key.commentBefore}`:Z.commentBefore;if(Z.comment){let Y=X.value??X.key;Y.comment=Y.comment?`${Z.comment}
88
+ ${Y.comment}`:Z.comment}Z=X}$.items[G]=g5.isPair(Z)?Z:new VX.Pair(Z)}else w("Expected a sequence for this tag");return $}function QP($,w,G){let{replacer:Z}=G,X=new EI.YAMLSeq($);X.tag="tag:yaml.org,2002:pairs";let Y=0;if(w&&Symbol.iterator in Object(w))for(let J of w){if(typeof Z==="function")J=Z.call(w,String(Y++),J);let W,T;if(Array.isArray(J))if(J.length===2)W=J[0],T=J[1];else throw TypeError(`Expected [key, value] tuple: ${J}`);else if(J&&J instanceof Object){let Q=Object.keys(J);if(Q.length===1)W=Q[0],T=J[W];else throw TypeError(`Expected tuple with one key, not ${Q.length} keys`)}else W=J;X.items.push(VX.createPair(W,T,G))}return X}var AI={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:TP,createNode:QP};RI.createPairs=QP;RI.pairs=AI;RI.resolvePairs=TP});var UX=F((kI)=>{var zP=r(),KX=Z1(),F9=T1(),CI=Q1(),MP=u5();class i1 extends CI.YAMLSeq{constructor(){super();this.add=F9.YAMLMap.prototype.add.bind(this),this.delete=F9.YAMLMap.prototype.delete.bind(this),this.get=F9.YAMLMap.prototype.get.bind(this),this.has=F9.YAMLMap.prototype.has.bind(this),this.set=F9.YAMLMap.prototype.set.bind(this),this.tag=i1.tag}toJSON($,w){if(!w)return super.toJSON($);let G=new Map;if(w?.onCreate)w.onCreate(G);for(let Z of this.items){let X,Y;if(zP.isPair(Z))X=KX.toJS(Z.key,"",w),Y=KX.toJS(Z.value,X,w);else X=KX.toJS(Z,"",w);if(G.has(X))throw Error("Ordered maps must not include duplicate keys");G.set(X,Y)}return G}static from($,w,G){let Z=MP.createPairs($,w,G),X=new this;return X.items=Z.items,X}}i1.tag="tag:yaml.org,2002:omap";var bI={collection:"seq",identify:($)=>$ instanceof Map,nodeClass:i1,default:!1,tag:"tag:yaml.org,2002:omap",resolve($,w){let G=MP.resolvePairs($,w),Z=[];for(let{key:X}of G.items)if(zP.isScalar(X))if(Z.includes(X.value))w(`Ordered maps must not include duplicate keys: ${X.value}`);else Z.push(X.value);return Object.assign(new i1,G)},createNode:($,w,G)=>i1.from($,w,G)};kI.YAMLOMap=i1;kI.omap=bI});var VP=F((xI)=>{var PP=W0();function qP({value:$,source:w},G){if(w&&($?BP:NP).test.test(w))return w;return $?G.options.trueStr:G.options.falseStr}var BP={identify:($)=>$===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new PP.Scalar(!0),stringify:qP},NP={identify:($)=>$===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new PP.Scalar(!1),stringify:qP};xI.falseTag=NP;xI.trueTag=BP});var KP=F((lI)=>{var hI=W0(),HX=cw(),vI={identify:($)=>typeof $==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:($)=>$.slice(-3).toLowerCase()==="nan"?NaN:$[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:HX.stringifyNumber},iI={identify:($)=>typeof $==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:($)=>parseFloat($.replace(/_/g,"")),stringify($){let w=Number($.value);return isFinite(w)?w.toExponential():HX.stringifyNumber($)}},mI={identify:($)=>typeof $==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve($){let w=new hI.Scalar(parseFloat($.replace(/_/g,""))),G=$.indexOf(".");if(G!==-1){let Z=$.substring(G+1).replace(/_/g,"");if(Z[Z.length-1]==="0")w.minFractionDigits=Z.length}return w},stringify:HX.stringifyNumber};lI.float=mI;lI.floatExp=iI;lI.floatNaN=vI});var HP=F((tI)=>{var UP=cw(),O9=($)=>typeof $==="bigint"||Number.isInteger($);function h5($,w,G,{intAsBigInt:Z}){let X=$[0];if(X==="-"||X==="+")w+=1;if($=$.substring(w).replace(/_/g,""),Z){switch(G){case 2:$=`0b${$}`;break;case 8:$=`0o${$}`;break;case 16:$=`0x${$}`;break}let J=BigInt($);return X==="-"?BigInt(-1)*J:J}let Y=parseInt($,G);return X==="-"?-1*Y:Y}function FX($,w,G){let{value:Z}=$;if(O9(Z)){let X=Z.toString(w);return Z<0?"-"+G+X.substr(1):G+X}return UP.stringifyNumber($)}var nI={identify:O9,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:($,w,G)=>h5($,2,2,G),stringify:($)=>FX($,2,"0b")},rI={identify:O9,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:($,w,G)=>h5($,1,8,G),stringify:($)=>FX($,8,"0")},sI={identify:O9,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:($,w,G)=>h5($,0,10,G),stringify:UP.stringifyNumber},aI={identify:O9,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:($,w,G)=>h5($,2,16,G),stringify:($)=>FX($,16,"0x")};tI.int=sI;tI.intBin=nI;tI.intHex=aI;tI.intOct=rI});var OX=F((Zj)=>{var m5=r(),v5=J1(),i5=T1();class m1 extends i5.YAMLMap{constructor($){super($);this.tag=m1.tag}add($){let w;if(m5.isPair($))w=$;else if($&&typeof $==="object"&&"key"in $&&"value"in $&&$.value===null)w=new v5.Pair($.key,null);else w=new v5.Pair($,null);if(!i5.findPair(this.items,w.key))this.items.push(w)}get($,w){let G=i5.findPair(this.items,$);return!w&&m5.isPair(G)?m5.isScalar(G.key)?G.key.value:G.key:G}set($,w){if(typeof w!=="boolean")throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof w}`);let G=i5.findPair(this.items,$);if(G&&!w)this.items.splice(this.items.indexOf(G),1);else if(!G&&w)this.items.push(new v5.Pair($))}toJSON($,w){return super.toJSON($,w,Set)}toString($,w,G){if(!$)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},$,{allNullValues:!0}),w,G);else throw Error("Set items must all have null values")}static from($,w,G){let{replacer:Z}=G,X=new this($);if(w&&Symbol.iterator in Object(w))for(let Y of w){if(typeof Z==="function")Y=Z.call(w,Y,Y);X.items.push(v5.createPair(Y,null,G))}return X}}m1.tag="tag:yaml.org,2002:set";var Gj={collection:"map",identify:($)=>$ instanceof Set,nodeClass:m1,default:!1,tag:"tag:yaml.org,2002:set",createNode:($,w,G)=>m1.from($,w,G),resolve($,w){if(m5.isMap($))if($.hasAllNullValues(!0))return Object.assign(new m1,$);else w("Set items must all have null values");else w("Expected a mapping for this tag");return $}};Zj.YAMLSet=m1;Zj.set=Gj});var LX=F((Qj)=>{var Jj=cw();function fX($,w){let G=$[0],Z=G==="-"||G==="+"?$.substring(1):$,X=(J)=>w?BigInt(J):Number(J),Y=Z.replace(/_/g,"").split(":").reduce((J,W)=>J*X(60)+X(W),X(0));return G==="-"?X(-1)*Y:Y}function FP($){let{value:w}=$,G=(J)=>J;if(typeof w==="bigint")G=(J)=>BigInt(J);else if(isNaN(w)||!isFinite(w))return Jj.stringifyNumber($);let Z="";if(w<0)Z="-",w*=G(-1);let X=G(60),Y=[w%X];if(w<60)Y.unshift(0);else if(w=(w-Y[0])/X,Y.unshift(w%X),w>=60)w=(w-Y[0])/X,Y.unshift(w);return Z+Y.map((J)=>String(J).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Wj={identify:($)=>typeof $==="bigint"||Number.isInteger($),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:($,w,{intAsBigInt:G})=>fX($,G),stringify:FP},Tj={identify:($)=>typeof $==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:($)=>fX($,!1),stringify:FP},OP={identify:($)=>$ instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve($){let w=$.match(OP.test);if(!w)throw Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,G,Z,X,Y,J,W]=w.map(Number),T=w[7]?Number((w[7]+"00").substr(1,3)):0,Q=Date.UTC(G,Z-1,X,Y||0,J||0,W||0,T),z=w[8];if(z&&z!=="Z"){let M=fX(z,!1);if(Math.abs(M)<30)M*=60;Q-=60000*M}return new Date(Q)},stringify:({value:$})=>$?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Qj.floatTime=Tj;Qj.intTime=Wj;Qj.timestamp=OP});var LP=F((Lj)=>{var qj=lw(),Bj=y5(),Nj=dw(),Vj=U9(),Kj=NX(),fP=VP(),DX=KP(),l5=HP(),Uj=A5(),Hj=UX(),Fj=u5(),Oj=OX(),EX=LX(),fj=[qj.map,Nj.seq,Vj.string,Bj.nullTag,fP.trueTag,fP.falseTag,l5.intBin,l5.intOct,l5.int,l5.intHex,DX.floatNaN,DX.floatExp,DX.float,Kj.binary,Uj.merge,Hj.omap,Fj.pairs,Oj.set,EX.intTime,EX.floatTime,EX.timestamp];Lj.schema=fj});var kP=F((bj)=>{var RP=lw(),Ej=y5(),SP=dw(),Aj=U9(),Rj=WX(),AX=QX(),RX=MX(),Sj=YP(),Ij=WP(),IP=NX(),f9=A5(),jP=UX(),CP=u5(),DP=LP(),bP=OX(),d5=LX(),EP=new Map([["core",Sj.schema],["failsafe",[RP.map,SP.seq,Aj.string]],["json",Ij.schema],["yaml11",DP.schema],["yaml-1.1",DP.schema]]),AP={binary:IP.binary,bool:Rj.boolTag,float:AX.float,floatExp:AX.floatExp,floatNaN:AX.floatNaN,floatTime:d5.floatTime,int:RX.int,intHex:RX.intHex,intOct:RX.intOct,intTime:d5.intTime,map:RP.map,merge:f9.merge,null:Ej.nullTag,omap:jP.omap,pairs:CP.pairs,seq:SP.seq,set:bP.set,timestamp:d5.timestamp},jj={"tag:yaml.org,2002:binary":IP.binary,"tag:yaml.org,2002:merge":f9.merge,"tag:yaml.org,2002:omap":jP.omap,"tag:yaml.org,2002:pairs":CP.pairs,"tag:yaml.org,2002:set":bP.set,"tag:yaml.org,2002:timestamp":d5.timestamp};function Cj($,w,G){let Z=EP.get(w);if(Z&&!$)return G&&!Z.includes(f9.merge)?Z.concat(f9.merge):Z.slice();let X=Z;if(!X)if(Array.isArray($))X=[];else{let Y=Array.from(EP.keys()).filter((J)=>J!=="yaml11").map((J)=>JSON.stringify(J)).join(", ");throw Error(`Unknown schema "${w}"; use one of ${Y} or define customTags array`)}if(Array.isArray($))for(let Y of $)X=X.concat(Y);else if(typeof $==="function")X=$(X.slice());if(G)X=X.concat(f9.merge);return X.reduce((Y,J)=>{let W=typeof J==="string"?AP[J]:J;if(!W){let T=JSON.stringify(J),Q=Object.keys(AP).map((z)=>JSON.stringify(z)).join(", ");throw Error(`Unknown custom tag ${T}; use one of ${Q}`)}if(!Y.includes(W))Y.push(W);return Y},[])}bj.coreKnownTags=jj;bj.getTags=Cj});var jX=F((hj)=>{var SX=r(),_j=lw(),xj=dw(),gj=U9(),c5=kP(),uj=($,w)=>$.key<w.key?-1:$.key>w.key?1:0;class IX{constructor({compat:$,customTags:w,merge:G,resolveKnownTags:Z,schema:X,sortMapEntries:Y,toStringDefaults:J}){this.compat=Array.isArray($)?c5.getTags($,"compat"):$?c5.getTags(null,$):null,this.name=typeof X==="string"&&X||"core",this.knownTags=Z?c5.coreKnownTags:{},this.tags=c5.getTags(w,this.name,G),this.toStringOptions=J??null,Object.defineProperty(this,SX.MAP,{value:_j.map}),Object.defineProperty(this,SX.SCALAR,{value:gj.string}),Object.defineProperty(this,SX.SEQ,{value:xj.seq}),this.sortMapEntries=typeof Y==="function"?Y:Y===!0?uj:null}clone(){let $=Object.create(IX.prototype,Object.getOwnPropertyDescriptors(this));return $.tags=this.tags.slice(),$}}hj.Schema=IX});var yP=F((lj)=>{var ij=r(),CX=N9(),L9=P9();function mj($,w){let G=[],Z=w.directives===!0;if(w.directives!==!1&&$.directives){let T=$.directives.toString($);if(T)G.push(T),Z=!0;else if($.directives.docStart)Z=!0}if(Z)G.push("---");let X=CX.createStringifyContext($,w),{commentString:Y}=X.options;if($.commentBefore){if(G.length!==1)G.unshift("");let T=Y($.commentBefore);G.unshift(L9.indentComment(T,""))}let J=!1,W=null;if($.contents){if(ij.isNode($.contents)){if($.contents.spaceBefore&&Z)G.push("");if($.contents.commentBefore){let z=Y($.contents.commentBefore);G.push(L9.indentComment(z,""))}X.forceBlockIndent=!!$.comment,W=$.contents.comment}let T=W?void 0:()=>J=!0,Q=CX.stringify($.contents,X,()=>W=null,T);if(W)Q+=L9.lineComment(Q,"",Y(W));if((Q[0]==="|"||Q[0]===">")&&G[G.length-1]==="---")G[G.length-1]=`--- ${Q}`;else G.push(Q)}else G.push(CX.stringify($.contents,X));if($.directives?.docEnd)if($.comment){let T=Y($.comment);if(T.includes(`
89
+ `))G.push("..."),G.push(L9.indentComment(T,""));else G.push(`... ${T}`)}else G.push("...");else{let T=$.comment;if(T&&J)T=T.replace(/^\n+/,"");if(T){if((!J||W)&&G[G.length-1]!=="")G.push("");G.push(L9.indentComment(Y(T),""))}}return G.join(`
90
+ `)+`
91
+ `}lj.stringifyDocument=mj});var D9=F((oj)=>{var cj=z9(),pw=H5(),a0=r(),pj=J1(),nj=Z1(),rj=jX(),sj=yP(),bX=V5(),aj=tZ(),tj=M9(),kX=aZ();class yX{constructor($,w,G){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,a0.NODE_TYPE,{value:a0.DOC});let Z=null;if(typeof w==="function"||Array.isArray(w))Z=w;else if(G===void 0&&w)G=w,w=void 0;let X=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},G);this.options=X;let{version:Y}=X;if(G?._directives){if(this.directives=G._directives.atDocument(),this.directives.yaml.explicit)Y=this.directives.yaml.version}else this.directives=new kX.Directives({version:Y});this.setSchema(Y,G),this.contents=$===void 0?null:this.createNode($,Z,G)}clone(){let $=Object.create(yX.prototype,{[a0.NODE_TYPE]:{value:a0.DOC}});if($.commentBefore=this.commentBefore,$.comment=this.comment,$.errors=this.errors.slice(),$.warnings=this.warnings.slice(),$.options=Object.assign({},this.options),this.directives)$.directives=this.directives.clone();if($.schema=this.schema.clone(),$.contents=a0.isNode(this.contents)?this.contents.clone($.schema):this.contents,this.range)$.range=this.range.slice();return $}add($){if(nw(this.contents))this.contents.add($)}addIn($,w){if(nw(this.contents))this.contents.addIn($,w)}createAlias($,w){if(!$.anchor){let G=bX.anchorNames(this);$.anchor=!w||G.has(w)?bX.findNewAnchor(w||"a",G):w}return new cj.Alias($.anchor)}createNode($,w,G){let Z=void 0;if(typeof w==="function")$=w.call({"":$},"",$),Z=w;else if(Array.isArray(w)){let B=(K)=>typeof K==="number"||K instanceof String||K instanceof Number,V=w.filter(B).map(String);if(V.length>0)w=w.concat(V);Z=w}else if(G===void 0&&w)G=w,w=void 0;let{aliasDuplicateObjects:X,anchorPrefix:Y,flow:J,keepUndefined:W,onTagObj:T,tag:Q}=G??{},{onAnchor:z,setAnchors:M,sourceObjects:P}=bX.createNodeAnchors(this,Y||"a"),q={aliasDuplicateObjects:X??!0,keepUndefined:W??!1,onAnchor:z,onTagObj:T,replacer:Z,schema:this.schema,sourceObjects:P},N=tj.createNode($,Q,q);if(J&&a0.isCollection(N))N.flow=!0;return M(),N}createPair($,w,G={}){let Z=this.createNode($,null,G),X=this.createNode(w,null,G);return new pj.Pair(Z,X)}delete($){return nw(this.contents)?this.contents.delete($):!1}deleteIn($){if(pw.isEmptyPath($)){if(this.contents==null)return!1;return this.contents=null,!0}return nw(this.contents)?this.contents.deleteIn($):!1}get($,w){return a0.isCollection(this.contents)?this.contents.get($,w):void 0}getIn($,w){if(pw.isEmptyPath($))return!w&&a0.isScalar(this.contents)?this.contents.value:this.contents;return a0.isCollection(this.contents)?this.contents.getIn($,w):void 0}has($){return a0.isCollection(this.contents)?this.contents.has($):!1}hasIn($){if(pw.isEmptyPath($))return this.contents!==void 0;return a0.isCollection(this.contents)?this.contents.hasIn($):!1}set($,w){if(this.contents==null)this.contents=pw.collectionFromPath(this.schema,[$],w);else if(nw(this.contents))this.contents.set($,w)}setIn($,w){if(pw.isEmptyPath($))this.contents=w;else if(this.contents==null)this.contents=pw.collectionFromPath(this.schema,Array.from($),w);else if(nw(this.contents))this.contents.setIn($,w)}setSchema($,w={}){if(typeof $==="number")$=String($);let G;switch($){case"1.1":if(this.directives)this.directives.yaml.version="1.1";else this.directives=new kX.Directives({version:"1.1"});G={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":if(this.directives)this.directives.yaml.version=$;else this.directives=new kX.Directives({version:$});G={resolveKnownTags:!0,schema:"core"};break;case null:if(this.directives)delete this.directives;G=null;break;default:{let Z=JSON.stringify($);throw Error(`Expected '1.1', '1.2' or null as first argument, but found: ${Z}`)}}if(w.schema instanceof Object)this.schema=w.schema;else if(G)this.schema=new rj.Schema(Object.assign(G,w));else throw Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:$,jsonArg:w,mapAsMap:G,maxAliasCount:Z,onAnchor:X,reviver:Y}={}){let J={anchors:new Map,doc:this,keep:!$,mapAsMap:G===!0,mapKeyWarned:!1,maxAliasCount:typeof Z==="number"?Z:100},W=nj.toJS(this.contents,w??"",J);if(typeof X==="function")for(let{count:T,res:Q}of J.anchors.values())X(Q,T);return typeof Y==="function"?aj.applyReviver(Y,{"":W},"",W):W}toJSON($,w){return this.toJS({json:!0,jsonArg:$,mapAsMap:!1,onAnchor:w})}toString($={}){if(this.errors.length>0)throw Error("Document with errors cannot be stringified");if("indent"in $&&(!Number.isInteger($.indent)||Number($.indent)<=0)){let w=JSON.stringify($.indent);throw Error(`"indent" option must be a positive integer, not ${w}`)}return sj.stringifyDocument(this,$)}}function nw($){if(a0.isCollection($))return!0;throw Error("Expected a YAML collection as document contents")}oj.Document=yX});var E9=F((wC)=>{class p5 extends Error{constructor($,w,G,Z){super();this.name=$,this.code=G,this.message=Z,this.pos=w}}class _P extends p5{constructor($,w,G){super("YAMLParseError",$,w,G)}}class xP extends p5{constructor($,w,G){super("YAMLWarning",$,w,G)}}var $C=($,w)=>(G)=>{if(G.pos[0]===-1)return;G.linePos=G.pos.map((W)=>w.linePos(W));let{line:Z,col:X}=G.linePos[0];G.message+=` at line ${Z}, column ${X}`;let Y=X-1,J=$.substring(w.lineStarts[Z-1],w.lineStarts[Z]).replace(/[\n\r]+$/,"");if(Y>=60&&J.length>80){let W=Math.min(Y-39,J.length-79);J="…"+J.substring(W),Y-=W-1}if(J.length>80)J=J.substring(0,79)+"…";if(Z>1&&/^ *$/.test(J.substring(0,Y))){let W=$.substring(w.lineStarts[Z-2],w.lineStarts[Z-1]);if(W.length>80)W=W.substring(0,79)+`…
92
+ `;J=W+J}if(/[^ ]/.test(J)){let W=1,T=G.linePos[1];if(T?.line===Z&&T.col>X)W=Math.max(1,Math.min(T.col-X,80-Y));let Q=" ".repeat(Y)+"^".repeat(W);G.message+=`:
93
+
94
+ ${J}
95
+ ${Q}
96
+ `}};wC.YAMLError=p5;wC.YAMLParseError=_P;wC.YAMLWarning=xP;wC.prettifyError=$C});var A9=F((WC)=>{function JC($,{flow:w,indicator:G,next:Z,offset:X,onError:Y,parentIndent:J,startOnNewline:W}){let T=!1,Q=W,z=W,M="",P="",q=!1,N=!1,B=null,V=null,K=null,U=null,O=null,D=null,f=null;for(let S of $){if(N){if(S.type!=="space"&&S.type!=="newline"&&S.type!=="comma")Y(S.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space");N=!1}if(B){if(Q&&S.type!=="comment"&&S.type!=="newline")Y(B,"TAB_AS_INDENT","Tabs are not allowed as indentation");B=null}switch(S.type){case"space":if(!w&&(G!=="doc-start"||Z?.type!=="flow-collection")&&S.source.includes("\t"))B=S;z=!0;break;case"comment":{if(!z)Y(S,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let h=S.source.substring(1)||" ";if(!M)M=h;else M+=P+h;P="",Q=!1;break}case"newline":if(Q){if(M)M+=S.source;else if(!D||G!=="seq-item-ind")T=!0}else P+=S.source;if(Q=!0,q=!0,V||K)U=S;z=!0;break;case"anchor":if(V)Y(S,"MULTIPLE_ANCHORS","A node can have at most one anchor");if(S.source.endsWith(":"))Y(S.offset+S.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0);V=S,f??(f=S.offset),Q=!1,z=!1,N=!0;break;case"tag":{if(K)Y(S,"MULTIPLE_TAGS","A node can have at most one tag");K=S,f??(f=S.offset),Q=!1,z=!1,N=!0;break}case G:if(V||K)Y(S,"BAD_PROP_ORDER",`Anchors and tags must be after the ${S.source} indicator`);if(D)Y(S,"UNEXPECTED_TOKEN",`Unexpected ${S.source} in ${w??"collection"}`);D=S,Q=G==="seq-item-ind"||G==="explicit-key-ind",z=!1;break;case"comma":if(w){if(O)Y(S,"UNEXPECTED_TOKEN",`Unexpected , in ${w}`);O=S,Q=!1,z=!1;break}default:Y(S,"UNEXPECTED_TOKEN",`Unexpected ${S.type} token`),Q=!1,z=!1}}let L=$[$.length-1],C=L?L.offset+L.source.length:X;if(N&&Z&&Z.type!=="space"&&Z.type!=="newline"&&Z.type!=="comma"&&(Z.type!=="scalar"||Z.source!==""))Y(Z.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space");if(B&&(Q&&B.indent<=J||Z?.type==="block-map"||Z?.type==="block-seq"))Y(B,"TAB_AS_INDENT","Tabs are not allowed as indentation");return{comma:O,found:D,spaceBefore:T,comment:M,hasNewline:q,anchor:V,tag:K,newlineAfterProp:U,end:C,start:f??C}}WC.resolveProps=JC});var n5=F((QC)=>{function _X($){if(!$)return null;switch($.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if($.source.includes(`
97
+ `))return!0;if($.end){for(let w of $.end)if(w.type==="newline")return!0}return!1;case"flow-collection":for(let w of $.items){for(let G of w.start)if(G.type==="newline")return!0;if(w.sep){for(let G of w.sep)if(G.type==="newline")return!0}if(_X(w.key)||_X(w.value))return!0}return!1;default:return!0}}QC.containsNewline=_X});var xX=F((qC)=>{var MC=n5();function PC($,w,G){if(w?.type==="flow-collection"){let Z=w.end[0];if(Z.indent===$&&(Z.source==="]"||Z.source==="}")&&MC.containsNewline(w))G(Z,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}qC.flowIndentCheck=PC});var gX=F((VC)=>{var gP=r();function NC($,w,G){let{uniqueKeys:Z}=$.options;if(Z===!1)return!1;let X=typeof Z==="function"?Z:(Y,J)=>Y===J||gP.isScalar(Y)&&gP.isScalar(J)&&Y.value===J.value;return w.some((Y)=>X(Y.key,G))}VC.mapIncludes=NC});var mP=F((fC)=>{var uP=J1(),UC=T1(),hP=A9(),HC=n5(),vP=xX(),FC=gX(),iP="All mapping items must start at the same column";function OC({composeNode:$,composeEmptyNode:w},G,Z,X,Y){let W=new(Y?.nodeClass??UC.YAMLMap)(G.schema);if(G.atRoot)G.atRoot=!1;let T=Z.offset,Q=null;for(let z of Z.items){let{start:M,key:P,sep:q,value:N}=z,B=hP.resolveProps(M,{indicator:"explicit-key-ind",next:P??q?.[0],offset:T,onError:X,parentIndent:Z.indent,startOnNewline:!0}),V=!B.found;if(V){if(P){if(P.type==="block-seq")X(T,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key");else if("indent"in P&&P.indent!==Z.indent)X(T,"BAD_INDENT",iP)}if(!B.anchor&&!B.tag&&!q){if(Q=B.end,B.comment)if(W.comment)W.comment+=`
98
+ `+B.comment;else W.comment=B.comment;continue}if(B.newlineAfterProp||HC.containsNewline(P))X(P??M[M.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else if(B.found?.indent!==Z.indent)X(T,"BAD_INDENT",iP);G.atKey=!0;let K=B.end,U=P?$(G,P,B,X):w(G,K,M,null,B,X);if(G.schema.compat)vP.flowIndentCheck(Z.indent,P,X);if(G.atKey=!1,FC.mapIncludes(G,W.items,U))X(K,"DUPLICATE_KEY","Map keys must be unique");let O=hP.resolveProps(q??[],{indicator:"map-value-ind",next:N,offset:U.range[2],onError:X,parentIndent:Z.indent,startOnNewline:!P||P.type==="block-scalar"});if(T=O.end,O.found){if(V){if(N?.type==="block-map"&&!O.hasNewline)X(T,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings");if(G.options.strict&&B.start<O.found.offset-1024)X(U.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key")}let D=N?$(G,N,O,X):w(G,T,q,null,O,X);if(G.schema.compat)vP.flowIndentCheck(Z.indent,N,X);T=D.range[2];let f=new uP.Pair(U,D);if(G.options.keepSourceTokens)f.srcToken=z;W.items.push(f)}else{if(V)X(U.range,"MISSING_CHAR","Implicit map keys need to be followed by map values");if(O.comment)if(U.comment)U.comment+=`
99
+ `+O.comment;else U.comment=O.comment;let D=new uP.Pair(U);if(G.options.keepSourceTokens)D.srcToken=z;W.items.push(D)}}if(Q&&Q<T)X(Q,"IMPOSSIBLE","Map comment with trailing content");return W.range=[Z.offset,T,Q??T],W}fC.resolveBlockMap=OC});var lP=F((SC)=>{var DC=Q1(),EC=A9(),AC=xX();function RC({composeNode:$,composeEmptyNode:w},G,Z,X,Y){let W=new(Y?.nodeClass??DC.YAMLSeq)(G.schema);if(G.atRoot)G.atRoot=!1;if(G.atKey)G.atKey=!1;let T=Z.offset,Q=null;for(let{start:z,value:M}of Z.items){let P=EC.resolveProps(z,{indicator:"seq-item-ind",next:M,offset:T,onError:X,parentIndent:Z.indent,startOnNewline:!0});if(!P.found)if(P.anchor||P.tag||M)if(M?.type==="block-seq")X(P.end,"BAD_INDENT","All sequence items must start at the same column");else X(T,"MISSING_CHAR","Sequence item without - indicator");else{if(Q=P.end,P.comment)W.comment=P.comment;continue}let q=M?$(G,M,P,X):w(G,P.end,z,null,P,X);if(G.schema.compat)AC.flowIndentCheck(Z.indent,M,X);T=q.range[2],W.items.push(q)}return W.range=[Z.offset,T,Q??T],W}SC.resolveBlockSeq=RC});var rw=F((CC)=>{function jC($,w,G,Z){let X="";if($){let Y=!1,J="";for(let W of $){let{source:T,type:Q}=W;switch(Q){case"space":Y=!0;break;case"comment":{if(G&&!Y)Z(W,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let z=T.substring(1)||" ";if(!X)X=z;else X+=J+z;J="";break}case"newline":if(X)J+=T;Y=!0;break;default:Z(W,"UNEXPECTED_TOKEN",`Unexpected ${Q} at node end`)}w+=T.length}}return{comment:X,offset:w}}CC.resolveEnd=jC});var pP=F((vC)=>{var kC=r(),yC=J1(),dP=T1(),_C=Q1(),xC=rw(),cP=A9(),gC=n5(),uC=gX(),uX="Block collections are not allowed within flow collections",hX=($)=>$&&($.type==="block-map"||$.type==="block-seq");function hC({composeNode:$,composeEmptyNode:w},G,Z,X,Y){let J=Z.start.source==="{",W=J?"flow map":"flow sequence",Q=new(Y?.nodeClass??(J?dP.YAMLMap:_C.YAMLSeq))(G.schema);Q.flow=!0;let z=G.atRoot;if(z)G.atRoot=!1;if(G.atKey)G.atKey=!1;let M=Z.offset+Z.start.source.length;for(let V=0;V<Z.items.length;++V){let K=Z.items[V],{start:U,key:O,sep:D,value:f}=K,L=cP.resolveProps(U,{flow:W,indicator:"explicit-key-ind",next:O??D?.[0],offset:M,onError:X,parentIndent:Z.indent,startOnNewline:!1});if(!L.found){if(!L.anchor&&!L.tag&&!D&&!f){if(V===0&&L.comma)X(L.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${W}`);else if(V<Z.items.length-1)X(L.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${W}`);if(L.comment)if(Q.comment)Q.comment+=`
100
+ `+L.comment;else Q.comment=L.comment;M=L.end;continue}if(!J&&G.options.strict&&gC.containsNewline(O))X(O,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(V===0){if(L.comma)X(L.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${W}`)}else{if(!L.comma)X(L.start,"MISSING_CHAR",`Missing , between ${W} items`);if(L.comment){let C="";$:for(let S of U)switch(S.type){case"comma":case"space":break;case"comment":C=S.source.substring(1);break $;default:break $}if(C){let S=Q.items[Q.items.length-1];if(kC.isPair(S))S=S.value??S.key;if(S.comment)S.comment+=`
101
+ `+C;else S.comment=C;L.comment=L.comment.substring(C.length+1)}}}if(!J&&!D&&!L.found){let C=f?$(G,f,L,X):w(G,L.end,D,null,L,X);if(Q.items.push(C),M=C.range[2],hX(f))X(C.range,"BLOCK_IN_FLOW",uX)}else{G.atKey=!0;let C=L.end,S=O?$(G,O,L,X):w(G,C,U,null,L,X);if(hX(O))X(S.range,"BLOCK_IN_FLOW",uX);G.atKey=!1;let h=cP.resolveProps(D??[],{flow:W,indicator:"map-value-ind",next:f,offset:S.range[2],onError:X,parentIndent:Z.indent,startOnNewline:!1});if(h.found){if(!J&&!L.found&&G.options.strict){if(D)for(let e of D){if(e===h.found)break;if(e.type==="newline"){X(e,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}if(L.start<h.found.offset-1024)X(h.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else if(f)if("source"in f&&f.source?.[0]===":")X(f,"MISSING_CHAR",`Missing space after : in ${W}`);else X(h.start,"MISSING_CHAR",`Missing , or : between ${W} items`);let g=f?$(G,f,h,X):h.found?w(G,h.end,D,null,h,X):null;if(g){if(hX(f))X(g.range,"BLOCK_IN_FLOW",uX)}else if(h.comment)if(S.comment)S.comment+=`
102
+ `+h.comment;else S.comment=h.comment;let G0=new yC.Pair(S,g);if(G.options.keepSourceTokens)G0.srcToken=K;if(J){let e=Q;if(uC.mapIncludes(G,e.items,S))X(C,"DUPLICATE_KEY","Map keys must be unique");e.items.push(G0)}else{let e=new dP.YAMLMap(G.schema);e.flow=!0,e.items.push(G0);let c0=(g??S).range;e.range=[S.range[0],c0[1],c0[2]],Q.items.push(e)}M=g?g.range[2]:h.end}}let P=J?"}":"]",[q,...N]=Z.end,B=M;if(q?.source===P)B=q.offset+q.source.length;else{let V=W[0].toUpperCase()+W.substring(1),K=z?`${V} must end with a ${P}`:`${V} in block collection must be sufficiently indented and end with a ${P}`;if(X(M,z?"MISSING_CHAR":"BAD_INDENT",K),q&&q.source.length!==1)N.unshift(q)}if(N.length>0){let V=xC.resolveEnd(N,B,G.options.strict,X);if(V.comment)if(Q.comment)Q.comment+=`
103
+ `+V.comment;else Q.comment=V.comment;Q.range=[Z.offset,B,V.offset]}else Q.range=[Z.offset,B,B];return Q}vC.resolveFlowCollection=hC});var nP=F((aC)=>{var mC=r(),lC=W0(),dC=T1(),cC=Q1(),pC=mP(),nC=lP(),rC=pP();function vX($,w,G,Z,X,Y){let J=G.type==="block-map"?pC.resolveBlockMap($,w,G,Z,Y):G.type==="block-seq"?nC.resolveBlockSeq($,w,G,Z,Y):rC.resolveFlowCollection($,w,G,Z,Y),W=J.constructor;if(X==="!"||X===W.tagName)return J.tag=W.tagName,J;if(X)J.tag=X;return J}function sC($,w,G,Z,X){let Y=Z.tag,J=!Y?null:w.directives.tagName(Y.source,(P)=>X(Y,"TAG_RESOLVE_FAILED",P));if(G.type==="block-seq"){let{anchor:P,newlineAfterProp:q}=Z,N=P&&Y?P.offset>Y.offset?P:Y:P??Y;if(N&&(!q||q.offset<N.offset))X(N,"MISSING_CHAR","Missing newline after block sequence props")}let W=G.type==="block-map"?"map":G.type==="block-seq"?"seq":G.start.source==="{"?"map":"seq";if(!Y||!J||J==="!"||J===dC.YAMLMap.tagName&&W==="map"||J===cC.YAMLSeq.tagName&&W==="seq")return vX($,w,G,X,J);let T=w.schema.tags.find((P)=>P.tag===J&&P.collection===W);if(!T){let P=w.schema.knownTags[J];if(P?.collection===W)w.schema.tags.push(Object.assign({},P,{default:!1})),T=P;else{if(P)X(Y,"BAD_COLLECTION_TYPE",`${P.tag} used for ${W} collection, but expects ${P.collection??"scalar"}`,!0);else X(Y,"TAG_RESOLVE_FAILED",`Unresolved tag: ${J}`,!0);return vX($,w,G,X,J)}}let Q=vX($,w,G,X,J,T),z=T.resolve?.(Q,(P)=>X(Y,"TAG_RESOLVE_FAILED",P),w.options)??Q,M=mC.isNode(z)?z:new lC.Scalar(z);if(M.range=Q.range,M.tag=J,T?.format)M.format=T.format;return M}aC.composeCollection=sC});var mX=F((wb)=>{var iX=W0();function oC($,w,G){let Z=w.offset,X=eC(w,$.options.strict,G);if(!X)return{value:"",type:null,comment:"",range:[Z,Z,Z]};let Y=X.mode===">"?iX.Scalar.BLOCK_FOLDED:iX.Scalar.BLOCK_LITERAL,J=w.source?$b(w.source):[],W=J.length;for(let B=J.length-1;B>=0;--B){let V=J[B][1];if(V===""||V==="\r")W=B;else break}if(W===0){let B=X.chomp==="+"&&J.length>0?`
104
+ `.repeat(Math.max(1,J.length-1)):"",V=Z+X.length;if(w.source)V+=w.source.length;return{value:B,type:Y,comment:X.comment,range:[Z,V,V]}}let T=w.indent+X.indent,Q=w.offset+X.length,z=0;for(let B=0;B<W;++B){let[V,K]=J[B];if(K===""||K==="\r"){if(X.indent===0&&V.length>T)T=V.length}else{if(V.length<T)G(Q+V.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator");if(X.indent===0)T=V.length;if(z=B,T===0&&!$.atRoot)G(Q,"BAD_INDENT","Block scalar values in collections must be indented");break}Q+=V.length+K.length+1}for(let B=J.length-1;B>=W;--B)if(J[B][0].length>T)W=B+1;let M="",P="",q=!1;for(let B=0;B<z;++B)M+=J[B][0].slice(T)+`
105
+ `;for(let B=z;B<W;++B){let[V,K]=J[B];Q+=V.length+K.length+1;let U=K[K.length-1]==="\r";if(U)K=K.slice(0,-1);if(K&&V.length<T){let D=`Block scalar lines must not be less indented than their ${X.indent?"explicit indentation indicator":"first line"}`;G(Q-K.length-(U?2:1),"BAD_INDENT",D),V=""}if(Y===iX.Scalar.BLOCK_LITERAL)M+=P+V.slice(T)+K,P=`
106
+ `;else if(V.length>T||K[0]==="\t"){if(P===" ")P=`
107
+ `;else if(!q&&P===`
108
+ `)P=`
109
+
110
+ `;M+=P+V.slice(T)+K,P=`
111
+ `,q=!0}else if(K==="")if(P===`
112
+ `)M+=`
113
+ `;else P=`
114
+ `;else M+=P+K,P=" ",q=!1}switch(X.chomp){case"-":break;case"+":for(let B=W;B<J.length;++B)M+=`
115
+ `+J[B][0].slice(T);if(M[M.length-1]!==`
116
+ `)M+=`
117
+ `;break;default:M+=`
118
+ `}let N=Z+X.length+w.source.length;return{value:M,type:Y,comment:X.comment,range:[Z,N,N]}}function eC({offset:$,props:w},G,Z){if(w[0].type!=="block-scalar-header")return Z(w[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:X}=w[0],Y=X[0],J=0,W="",T=-1;for(let P=1;P<X.length;++P){let q=X[P];if(!W&&(q==="-"||q==="+"))W=q;else{let N=Number(q);if(!J&&N)J=N;else if(T===-1)T=$+P}}if(T!==-1)Z(T,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${X}`);let Q=!1,z="",M=X.length;for(let P=1;P<w.length;++P){let q=w[P];switch(q.type){case"space":Q=!0;case"newline":M+=q.source.length;break;case"comment":if(G&&!Q)Z(q,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");M+=q.source.length,z=q.source.substring(1);break;case"error":Z(q,"UNEXPECTED_TOKEN",q.message),M+=q.source.length;break;default:{let N=`Unexpected token in block scalar header: ${q.type}`;Z(q,"UNEXPECTED_TOKEN",N);let B=q.source;if(B&&typeof B==="string")M+=B.length}}}return{mode:Y,indent:J,chomp:W,comment:z,length:M}}function $b($){let w=$.split(/\n( *)/),G=w[0],Z=G.match(/^( *)/),Y=[Z?.[1]?[Z[1],G.slice(Z[1].length)]:["",G]];for(let J=1;J<w.length;J+=2)Y.push([w[J],w[J+1]]);return Y}wb.resolveBlockScalar=oC});var dX=F((Mb)=>{var lX=W0(),Zb=rw();function Xb($,w,G){let{offset:Z,type:X,source:Y,end:J}=$,W,T,Q=(P,q,N)=>G(Z+P,q,N);switch(X){case"scalar":W=lX.Scalar.PLAIN,T=Yb(Y,Q);break;case"single-quoted-scalar":W=lX.Scalar.QUOTE_SINGLE,T=Jb(Y,Q);break;case"double-quoted-scalar":W=lX.Scalar.QUOTE_DOUBLE,T=Wb(Y,Q);break;default:return G($,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${X}`),{value:"",type:null,comment:"",range:[Z,Z+Y.length,Z+Y.length]}}let z=Z+Y.length,M=Zb.resolveEnd(J,z,w,G);return{value:T,type:W,comment:M.comment,range:[Z,z,M.offset]}}function Yb($,w){let G="";switch($[0]){case"\t":G="a tab character";break;case",":G="flow indicator character ,";break;case"%":G="directive indicator character %";break;case"|":case">":{G=`block scalar indicator ${$[0]}`;break}case"@":case"`":{G=`reserved character ${$[0]}`;break}}if(G)w(0,"BAD_SCALAR_START",`Plain value cannot start with ${G}`);return rP($)}function Jb($,w){if($[$.length-1]!=="'"||$.length===1)w($.length,"MISSING_CHAR","Missing closing 'quote");return rP($.slice(1,-1)).replace(/''/g,"'")}function rP($){let w,G;try{w=new RegExp(`(.*?)(?<![ ])[ ]*\r?
119
+ `,"sy"),G=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
120
+ `,"sy")}catch{w=/(.*?)[ \t]*\r?\n/sy,G=/[ \t]*(.*?)[ \t]*\r?\n/sy}let Z=w.exec($);if(!Z)return $;let X=Z[1],Y=" ",J=w.lastIndex;G.lastIndex=J;while(Z=G.exec($)){if(Z[1]==="")if(Y===`
121
+ `)X+=Y;else Y=`
122
+ `;else X+=Y+Z[1],Y=" ";J=G.lastIndex}let W=/[ \t]*(.*)/sy;return W.lastIndex=J,Z=W.exec($),X+Y+(Z?.[1]??"")}function Wb($,w){let G="";for(let Z=1;Z<$.length-1;++Z){let X=$[Z];if(X==="\r"&&$[Z+1]===`
123
+ `)continue;if(X===`
124
+ `){let{fold:Y,offset:J}=Tb($,Z);G+=Y,Z=J}else if(X==="\\"){let Y=$[++Z],J=Qb[Y];if(J)G+=J;else if(Y===`
125
+ `){Y=$[Z+1];while(Y===" "||Y==="\t")Y=$[++Z+1]}else if(Y==="\r"&&$[Z+1]===`
126
+ `){Y=$[++Z+1];while(Y===" "||Y==="\t")Y=$[++Z+1]}else if(Y==="x"||Y==="u"||Y==="U"){let W=Y==="x"?2:Y==="u"?4:8;G+=zb($,Z+1,W,w),Z+=W}else{let W=$.substr(Z-1,2);w(Z-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${W}`),G+=W}}else if(X===" "||X==="\t"){let Y=Z,J=$[Z+1];while(J===" "||J==="\t")J=$[++Z+1];if(J!==`
127
+ `&&!(J==="\r"&&$[Z+2]===`
128
+ `))G+=Z>Y?$.slice(Y,Z+1):X}else G+=X}if($[$.length-1]!=='"'||$.length===1)w($.length,"MISSING_CHAR",'Missing closing "quote');return G}function Tb($,w){let G="",Z=$[w+1];while(Z===" "||Z==="\t"||Z===`
129
+ `||Z==="\r"){if(Z==="\r"&&$[w+2]!==`
130
+ `)break;if(Z===`
131
+ `)G+=`
132
+ `;w+=1,Z=$[w+1]}if(!G)G=" ";return{fold:G,offset:w}}var Qb={"0":"\x00",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
133
+ `,r:"\r",t:"\t",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\","\t":"\t"};function zb($,w,G,Z){let X=$.substr(w,G),J=X.length===G&&/^[0-9a-fA-F]+$/.test(X)?parseInt(X,16):NaN;try{return String.fromCodePoint(J)}catch{let W=$.substr(w-2,G+2);return Z(w-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${W}`),W}}Mb.resolveFlowScalar=Xb});var aP=F((Ub)=>{var l1=r(),sP=W0(),qb=mX(),Bb=dX();function Nb($,w,G,Z){let{value:X,type:Y,comment:J,range:W}=w.type==="block-scalar"?qb.resolveBlockScalar($,w,Z):Bb.resolveFlowScalar(w,$.options.strict,Z),T=G?$.directives.tagName(G.source,(M)=>Z(G,"TAG_RESOLVE_FAILED",M)):null,Q;if($.options.stringKeys&&$.atKey)Q=$.schema[l1.SCALAR];else if(T)Q=Vb($.schema,X,T,G,Z);else if(w.type==="scalar")Q=Kb($,X,w,Z);else Q=$.schema[l1.SCALAR];let z;try{let M=Q.resolve(X,(P)=>Z(G??w,"TAG_RESOLVE_FAILED",P),$.options);z=l1.isScalar(M)?M:new sP.Scalar(M)}catch(M){let P=M instanceof Error?M.message:String(M);Z(G??w,"TAG_RESOLVE_FAILED",P),z=new sP.Scalar(X)}if(z.range=W,z.source=X,Y)z.type=Y;if(T)z.tag=T;if(Q.format)z.format=Q.format;if(J)z.comment=J;return z}function Vb($,w,G,Z,X){if(G==="!")return $[l1.SCALAR];let Y=[];for(let W of $.tags)if(!W.collection&&W.tag===G)if(W.default&&W.test)Y.push(W);else return W;for(let W of Y)if(W.test?.test(w))return W;let J=$.knownTags[G];if(J&&!J.collection)return $.tags.push(Object.assign({},J,{default:!1,test:void 0})),J;return X(Z,"TAG_RESOLVE_FAILED",`Unresolved tag: ${G}`,G!=="tag:yaml.org,2002:str"),$[l1.SCALAR]}function Kb({atKey:$,directives:w,schema:G},Z,X,Y){let J=G.tags.find((W)=>(W.default===!0||$&&W.default==="key")&&W.test?.test(Z))||G[l1.SCALAR];if(G.compat){let W=G.compat.find((T)=>T.default&&T.test?.test(Z))??G[l1.SCALAR];if(J.tag!==W.tag){let T=w.tagString(J.tag),Q=w.tagString(W.tag),z=`Value may be parsed as either ${T} or ${Q}`;Y(X,"TAG_RESOLVE_FAILED",z,!0)}}return J}Ub.composeScalar=Nb});var tP=F((Ob)=>{function Fb($,w,G){if(w){G??(G=w.length);for(let Z=G-1;Z>=0;--Z){let X=w[Z];switch(X.type){case"space":case"comment":case"newline":$-=X.source.length;continue}X=w[++Z];while(X?.type==="space")$+=X.source.length,X=w[++Z];break}}return $}Ob.emptyScalarPosition=Fb});var $q=F((jb)=>{var Lb=z9(),Db=r(),Eb=nP(),oP=aP(),Ab=rw(),Rb=tP(),Sb={composeNode:eP,composeEmptyNode:cX};function eP($,w,G,Z){let X=$.atKey,{spaceBefore:Y,comment:J,anchor:W,tag:T}=G,Q,z=!0;switch(w.type){case"alias":if(Q=Ib($,w,Z),W||T)Z(w,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":if(Q=oP.composeScalar($,w,T,Z),W)Q.anchor=W.source.substring(1);break;case"block-map":case"block-seq":case"flow-collection":try{if(Q=Eb.composeCollection(Sb,$,w,G,Z),W)Q.anchor=W.source.substring(1)}catch(M){let P=M instanceof Error?M.message:String(M);Z(w,"RESOURCE_EXHAUSTION",P)}break;default:{let M=w.type==="error"?w.message:`Unsupported token (type: ${w.type})`;Z(w,"UNEXPECTED_TOKEN",M),z=!1}}if(Q??(Q=cX($,w.offset,void 0,null,G,Z)),W&&Q.anchor==="")Z(W,"BAD_ALIAS","Anchor cannot be an empty string");if(X&&$.options.stringKeys&&(!Db.isScalar(Q)||typeof Q.value!=="string"||Q.tag&&Q.tag!=="tag:yaml.org,2002:str"))Z(T??w,"NON_STRING_KEY","With stringKeys, all keys must be strings");if(Y)Q.spaceBefore=!0;if(J)if(w.type==="scalar"&&w.source==="")Q.comment=J;else Q.commentBefore=J;if($.options.keepSourceTokens&&z)Q.srcToken=w;return Q}function cX($,w,G,Z,{spaceBefore:X,comment:Y,anchor:J,tag:W,end:T},Q){let z={type:"scalar",offset:Rb.emptyScalarPosition(w,G,Z),indent:-1,source:""},M=oP.composeScalar($,z,W,Q);if(J){if(M.anchor=J.source.substring(1),M.anchor==="")Q(J,"BAD_ALIAS","Anchor cannot be an empty string")}if(X)M.spaceBefore=!0;if(Y)M.comment=Y,M.range[2]=T;return M}function Ib({options:$},{offset:w,source:G,end:Z},X){let Y=new Lb.Alias(G.substring(1));if(Y.source==="")X(w,"BAD_ALIAS","Alias cannot be an empty string");if(Y.source.endsWith(":"))X(w+G.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let J=w+G.length,W=Ab.resolveEnd(Z,J,$.strict,X);if(Y.range=[w,J,W.offset],W.comment)Y.comment=W.comment;return Y}jb.composeEmptyNode=cX;jb.composeNode=eP});var Gq=F((gb)=>{var kb=D9(),wq=$q(),yb=rw(),_b=A9();function xb($,w,{offset:G,start:Z,value:X,end:Y},J){let W=Object.assign({_directives:w},$),T=new kb.Document(void 0,W),Q={atKey:!1,atRoot:!0,directives:T.directives,options:T.options,schema:T.schema},z=_b.resolveProps(Z,{indicator:"doc-start",next:X??Y?.[0],offset:G,onError:J,parentIndent:0,startOnNewline:!0});if(z.found){if(T.directives.docStart=!0,X&&(X.type==="block-map"||X.type==="block-seq")&&!z.hasNewline)J(z.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")}T.contents=X?wq.composeNode(Q,X,z,J):wq.composeEmptyNode(Q,z.end,Z,null,z,J);let M=T.contents.range[2],P=yb.resolveEnd(Y,M,!1,J);if(P.comment)T.comment=P.comment;return T.range=[G,M,P.offset],T}gb.composeDoc=xb});var pX=F((db)=>{var hb=D$("process"),vb=aZ(),ib=D9(),R9=E9(),Zq=r(),mb=Gq(),lb=rw();function S9($){if(typeof $==="number")return[$,$+1];if(Array.isArray($))return $.length===2?$:[$[0],$[1]];let{offset:w,source:G}=$;return[w,w+(typeof G==="string"?G.length:1)]}function Xq($){let w="",G=!1,Z=!1;for(let X=0;X<$.length;++X){let Y=$[X];switch(Y[0]){case"#":w+=(w===""?"":Z?`
134
+
135
+ `:`
136
+ `)+(Y.substring(1)||" "),G=!0,Z=!1;break;case"%":if($[X+1]?.[0]!=="#")X+=1;G=!1;break;default:if(!G)Z=!0;G=!1}}return{comment:w,afterEmptyLine:Z}}class Yq{constructor($={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(w,G,Z,X)=>{let Y=S9(w);if(X)this.warnings.push(new R9.YAMLWarning(Y,G,Z));else this.errors.push(new R9.YAMLParseError(Y,G,Z))},this.directives=new vb.Directives({version:$.version||"1.2"}),this.options=$}decorate($,w){let{comment:G,afterEmptyLine:Z}=Xq(this.prelude);if(G){let X=$.contents;if(w)$.comment=$.comment?`${$.comment}
137
+ ${G}`:G;else if(Z||$.directives.docStart||!X)$.commentBefore=G;else if(Zq.isCollection(X)&&!X.flow&&X.items.length>0){let Y=X.items[0];if(Zq.isPair(Y))Y=Y.key;let J=Y.commentBefore;Y.commentBefore=J?`${G}
138
+ ${J}`:G}else{let Y=X.commentBefore;X.commentBefore=Y?`${G}
139
+ ${Y}`:G}}if(w){for(let X=0;X<this.errors.length;++X)$.errors.push(this.errors[X]);for(let X=0;X<this.warnings.length;++X)$.warnings.push(this.warnings[X])}else $.errors=this.errors,$.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Xq(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose($,w=!1,G=-1){for(let Z of $)yield*this.next(Z);yield*this.end(w,G)}*next($){if(hb.env.LOG_STREAM)console.dir($,{depth:null});switch($.type){case"directive":this.directives.add($.source,(w,G,Z)=>{let X=S9($);X[0]+=w,this.onError(X,"BAD_DIRECTIVE",G,Z)}),this.prelude.push($.source),this.atDirectives=!0;break;case"document":{let w=mb.composeDoc(this.options,this.directives,$,this.onError);if(this.atDirectives&&!w.directives.docStart)this.onError($,"MISSING_CHAR","Missing directives-end/doc-start indicator line");if(this.decorate(w,!1),this.doc)yield this.doc;this.doc=w,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push($.source);break;case"error":{let w=$.source?`${$.message}: ${JSON.stringify($.source)}`:$.message,G=new R9.YAMLParseError(S9($),"UNEXPECTED_TOKEN",w);if(this.atDirectives||!this.doc)this.errors.push(G);else this.doc.errors.push(G);break}case"doc-end":{if(!this.doc){this.errors.push(new R9.YAMLParseError(S9($),"UNEXPECTED_TOKEN","Unexpected doc-end without preceding document"));break}this.doc.directives.docEnd=!0;let w=lb.resolveEnd($.end,$.offset+$.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),w.comment){let G=this.doc.comment;this.doc.comment=G?`${G}
140
+ ${w.comment}`:w.comment}this.doc.range[2]=w.offset;break}default:this.errors.push(new R9.YAMLParseError(S9($),"UNEXPECTED_TOKEN",`Unsupported token ${$.type}`))}}*end($=!1,w=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if($){let G=Object.assign({_directives:this.directives},this.options),Z=new ib.Document(void 0,G);if(this.atDirectives)this.onError(w,"MISSING_CHAR","Missing directives-end indicator line");Z.range=[0,w,w],this.decorate(Z,!1),yield Z}}}db.Composer=Yq});var Tq=F((eb)=>{var pb=mX(),nb=dX(),rb=E9(),Jq=B9();function sb($,w=!0,G){if($){let Z=(X,Y,J)=>{let W=typeof X==="number"?X:Array.isArray(X)?X[0]:X.offset;if(G)G(W,Y,J);else throw new rb.YAMLParseError([W,W+1],Y,J)};switch($.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return nb.resolveFlowScalar($,w,Z);case"block-scalar":return pb.resolveBlockScalar({options:{strict:w}},$,Z)}}return null}function ab($,w){let{implicitKey:G=!1,indent:Z,inFlow:X=!1,offset:Y=-1,type:J="PLAIN"}=w,W=Jq.stringifyString({type:J,value:$},{implicitKey:G,indent:Z>0?" ".repeat(Z):"",inFlow:X,options:{blockQuote:!0,lineWidth:-1}}),T=w.end??[{type:"newline",offset:-1,indent:Z,source:`
141
+ `}];switch(W[0]){case"|":case">":{let Q=W.indexOf(`
142
+ `),z=W.substring(0,Q),M=W.substring(Q+1)+`
143
+ `,P=[{type:"block-scalar-header",offset:Y,indent:Z,source:z}];if(!Wq(P,T))P.push({type:"newline",offset:-1,indent:Z,source:`
144
+ `});return{type:"block-scalar",offset:Y,indent:Z,props:P,source:M}}case'"':return{type:"double-quoted-scalar",offset:Y,indent:Z,source:W,end:T};case"'":return{type:"single-quoted-scalar",offset:Y,indent:Z,source:W,end:T};default:return{type:"scalar",offset:Y,indent:Z,source:W,end:T}}}function tb($,w,G={}){let{afterKey:Z=!1,implicitKey:X=!1,inFlow:Y=!1,type:J}=G,W="indent"in $?$.indent:null;if(Z&&typeof W==="number")W+=2;if(!J)switch($.type){case"single-quoted-scalar":J="QUOTE_SINGLE";break;case"double-quoted-scalar":J="QUOTE_DOUBLE";break;case"block-scalar":{let Q=$.props[0];if(Q.type!=="block-scalar-header")throw Error("Invalid block scalar header");J=Q.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:J="PLAIN"}let T=Jq.stringifyString({type:J,value:w},{implicitKey:X||W===null,indent:W!==null&&W>0?" ".repeat(W):"",inFlow:Y,options:{blockQuote:!0,lineWidth:-1}});switch(T[0]){case"|":case">":ob($,T);break;case'"':nX($,T,"double-quoted-scalar");break;case"'":nX($,T,"single-quoted-scalar");break;default:nX($,T,"scalar")}}function ob($,w){let G=w.indexOf(`
145
+ `),Z=w.substring(0,G),X=w.substring(G+1)+`
146
+ `;if($.type==="block-scalar"){let Y=$.props[0];if(Y.type!=="block-scalar-header")throw Error("Invalid block scalar header");Y.source=Z,$.source=X}else{let{offset:Y}=$,J="indent"in $?$.indent:-1,W=[{type:"block-scalar-header",offset:Y,indent:J,source:Z}];if(!Wq(W,"end"in $?$.end:void 0))W.push({type:"newline",offset:-1,indent:J,source:`
147
+ `});for(let T of Object.keys($))if(T!=="type"&&T!=="offset")delete $[T];Object.assign($,{type:"block-scalar",indent:J,props:W,source:X})}}function Wq($,w){if(w)for(let G of w)switch(G.type){case"space":case"comment":$.push(G);break;case"newline":return $.push(G),!0}return!1}function nX($,w,G){switch($.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":$.type=G,$.source=w;break;case"block-scalar":{let Z=$.props.slice(1),X=w.length;if($.props[0].type==="block-scalar-header")X-=$.props[0].source.length;for(let Y of Z)Y.offset+=X;delete $.props,Object.assign($,{type:G,source:w,end:Z});break}case"block-map":case"block-seq":{let X={type:"newline",offset:$.offset+w.length,indent:$.indent,source:`
148
+ `};delete $.items,Object.assign($,{type:G,source:w,end:[X]});break}default:{let Z="indent"in $?$.indent:-1,X="end"in $&&Array.isArray($.end)?$.end.filter((Y)=>Y.type==="space"||Y.type==="comment"||Y.type==="newline"):[];for(let Y of Object.keys($))if(Y!=="type"&&Y!=="offset")delete $[Y];Object.assign($,{type:G,indent:Z,source:w,end:X})}}}eb.createScalarToken=ab;eb.resolveAsScalar=sb;eb.setScalarValue=tb});var Qq=F((Xk)=>{var Zk=($)=>("type"in $)?s5($):r5($);function s5($){switch($.type){case"block-scalar":{let w="";for(let G of $.props)w+=s5(G);return w+$.source}case"block-map":case"block-seq":{let w="";for(let G of $.items)w+=r5(G);return w}case"flow-collection":{let w=$.start.source;for(let G of $.items)w+=r5(G);for(let G of $.end)w+=G.source;return w}case"document":{let w=r5($);if($.end)for(let G of $.end)w+=G.source;return w}default:{let w=$.source;if("end"in $&&$.end)for(let G of $.end)w+=G.source;return w}}}function r5({start:$,key:w,sep:G,value:Z}){let X="";for(let Y of $)X+=Y.source;if(w)X+=s5(w);if(G)for(let Y of G)X+=Y.source;if(Z)X+=s5(Z);return X}Xk.stringify=Zk});var Pq=F((Wk)=>{var rX=Symbol("break visit"),Jk=Symbol("skip children"),zq=Symbol("remove item");function d1($,w){if("type"in $&&$.type==="document")$={start:$.start,value:$.value};Mq(Object.freeze([]),$,w)}d1.BREAK=rX;d1.SKIP=Jk;d1.REMOVE=zq;d1.itemAtPath=($,w)=>{let G=$;for(let[Z,X]of w){let Y=G?.[Z];if(Y&&"items"in Y)G=Y.items[X];else return}return G};d1.parentCollection=($,w)=>{let G=d1.itemAtPath($,w.slice(0,-1)),Z=w[w.length-1][0],X=G?.[Z];if(X&&"items"in X)return X;throw Error("Parent collection not found")};function Mq($,w,G){let Z=G(w,$);if(typeof Z==="symbol")return Z;for(let X of["key","value"]){let Y=w[X];if(Y&&"items"in Y){for(let J=0;J<Y.items.length;++J){let W=Mq(Object.freeze($.concat([[X,J]])),Y.items[J],G);if(typeof W==="number")J=W-1;else if(W===rX)return rX;else if(W===zq)Y.items.splice(J,1),J-=1}if(typeof Z==="function"&&X==="key")Z=Z(w,$)}}return typeof Z==="function"?Z(w,$):Z}Wk.visit=d1});var a5=F((Nk)=>{var sX=Tq(),Qk=Qq(),zk=Pq(),aX="\uFEFF",tX="\x02",oX="\x18",eX="\x1F",Mk=($)=>!!$&&("items"in $),Pk=($)=>!!$&&($.type==="scalar"||$.type==="single-quoted-scalar"||$.type==="double-quoted-scalar"||$.type==="block-scalar");function qk($){switch($){case aX:return"<BOM>";case tX:return"<DOC>";case oX:return"<FLOW_END>";case eX:return"<SCALAR>";default:return JSON.stringify($)}}function Bk($){switch($){case aX:return"byte-order-mark";case tX:return"doc-mode";case oX:return"flow-error-end";case eX:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
149
+ `:case`\r
150
+ `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch($[0]){case" ":case"\t":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}Nk.createScalarToken=sX.createScalarToken;Nk.resolveAsScalar=sX.resolveAsScalar;Nk.setScalarValue=sX.setScalarValue;Nk.stringify=Qk.stringify;Nk.visit=zk.visit;Nk.BOM=aX;Nk.DOCUMENT=tX;Nk.FLOW_END=oX;Nk.SCALAR=eX;Nk.isCollection=Mk;Nk.isScalar=Pk;Nk.prettyToken=qk;Nk.tokenType=Bk});var w7=F((Ck)=>{var I9=a5();function Y$($){switch($){case void 0:case" ":case`
151
+ `:case"\r":case"\t":return!0;default:return!1}}var qq=new Set("0123456789ABCDEFabcdef"),Ik=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),t5=new Set(",[]{}"),jk=new Set(` ,[]{}
152
+ \r `),$7=($)=>!$||jk.has($);class Bq{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex($,w=!1){if($){if(typeof $!=="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+$:$,this.lineEndPos=null}this.atEnd=!w;let G=this.next??"stream";while(G&&(w||this.hasChars(1)))G=yield*this.parseNext(G)}atLineEnd(){let $=this.pos,w=this.buffer[$];while(w===" "||w==="\t")w=this.buffer[++$];if(!w||w==="#"||w===`
153
+ `)return!0;if(w==="\r")return this.buffer[$+1]===`
154
+ `;return!1}charAt($){return this.buffer[this.pos+$]}continueScalar($){let w=this.buffer[$];if(this.indentNext>0){let G=0;while(w===" ")w=this.buffer[++G+$];if(w==="\r"){let Z=this.buffer[G+$+1];if(Z===`
155
+ `||!Z&&!this.atEnd)return $+G+1}return w===`
156
+ `||G>=this.indentNext||!w&&!this.atEnd?$+G:-1}if(w==="-"||w==="."){let G=this.buffer.substr($,3);if((G==="---"||G==="...")&&Y$(this.buffer[$+3]))return-1}return $}getLine(){let $=this.lineEndPos;if(typeof $!=="number"||$!==-1&&$<this.pos)$=this.buffer.indexOf(`
157
+ `,this.pos),this.lineEndPos=$;if($===-1)return this.atEnd?this.buffer.substring(this.pos):null;if(this.buffer[$-1]==="\r")$-=1;return this.buffer.substring(this.pos,$)}hasChars($){return this.pos+$<=this.buffer.length}setNext($){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=$,null}peek($){return this.buffer.substr(this.pos,$)}*parseNext($){switch($){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let $=this.getLine();if($===null)return this.setNext("stream");if($[0]===I9.BOM)yield*this.pushCount(1),$=$.substring(1);if($[0]==="%"){let w=$.length,G=$.indexOf("#");while(G!==-1){let X=$[G-1];if(X===" "||X==="\t"){w=G-1;break}else G=$.indexOf("#",G+1)}while(!0){let X=$[w-1];if(X===" "||X==="\t")w-=1;else break}let Z=(yield*this.pushCount(w))+(yield*this.pushSpaces(!0));return yield*this.pushCount($.length-Z),this.pushNewline(),"stream"}if(this.atLineEnd()){let w=yield*this.pushSpaces(!0);return yield*this.pushCount($.length-w),yield*this.pushNewline(),"stream"}return yield I9.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let $=this.charAt(0);if(!$&&!this.atEnd)return this.setNext("line-start");if($==="-"||$==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let w=this.peek(3);if((w==="---"||w==="...")&&Y$(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,w==="---"?"doc":"stream"}if(this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Y$(this.charAt(1)))this.indentNext=this.indentValue;return yield*this.parseBlockStart()}*parseBlockStart(){let[$,w]=this.peek(2);if(!w&&!this.atEnd)return this.setNext("block-start");if(($==="-"||$==="?"||$===":")&&Y$(w)){let G=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=G,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let $=this.getLine();if($===null)return this.setNext("doc");let w=yield*this.pushIndicators();switch($[w]){case"#":yield*this.pushCount($.length-w);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil($7),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return w+=yield*this.parseBlockScalarHeader(),w+=yield*this.pushSpaces(!0),yield*this.pushCount($.length-w),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let $,w,G=-1;do{if($=yield*this.pushNewline(),$>0)w=yield*this.pushSpaces(!1),this.indentValue=G=w;else w=0;w+=yield*this.pushSpaces(!0)}while($+w>0);let Z=this.getLine();if(Z===null)return this.setNext("flow");if(G!==-1&&G<this.indentNext&&Z[0]!=="#"||G===0&&(Z.startsWith("---")||Z.startsWith("..."))&&Y$(Z[3])){if(!(G===this.indentNext-1&&this.flowLevel===1&&(Z[0]==="]"||Z[0]==="}")))return this.flowLevel=0,yield I9.FLOW_END,yield*this.parseLineStart()}let X=0;while(Z[X]===",")X+=yield*this.pushCount(1),X+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(X+=yield*this.pushIndicators(),Z[X]){case void 0:return"flow";case"#":return yield*this.pushCount(Z.length-X),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil($7),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let Y=this.charAt(1);if(this.flowKey||Y$(Y)||Y===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let $=this.charAt(0),w=this.buffer.indexOf($,this.pos+1);if($==="'")while(w!==-1&&this.buffer[w+1]==="'")w=this.buffer.indexOf("'",w+2);else while(w!==-1){let X=0;while(this.buffer[w-1-X]==="\\")X+=1;if(X%2===0)break;w=this.buffer.indexOf('"',w+1)}let G=this.buffer.substring(0,w),Z=G.indexOf(`
158
+ `,this.pos);if(Z!==-1){while(Z!==-1){let X=this.continueScalar(Z+1);if(X===-1)break;Z=G.indexOf(`
159
+ `,X)}if(Z!==-1)w=Z-(G[Z-1]==="\r"?2:1)}if(w===-1){if(!this.atEnd)return this.setNext("quoted-scalar");w=this.buffer.length}return yield*this.pushToIndex(w+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let $=this.pos;while(!0){let w=this.buffer[++$];if(w==="+")this.blockScalarKeep=!0;else if(w>"0"&&w<="9")this.blockScalarIndent=Number(w)-1;else if(w!=="-")break}return yield*this.pushUntil((w)=>Y$(w)||w==="#")}*parseBlockScalar(){let $=this.pos-1,w=0,G;$:for(let X=this.pos;G=this.buffer[X];++X)switch(G){case" ":w+=1;break;case`
160
+ `:$=X,w=0;break;case"\r":{let Y=this.buffer[X+1];if(!Y&&!this.atEnd)return this.setNext("block-scalar");if(Y===`
161
+ `)break}default:break $}if(!G&&!this.atEnd)return this.setNext("block-scalar");if(w>=this.indentNext){if(this.blockScalarIndent===-1)this.indentNext=w;else this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let X=this.continueScalar($+1);if(X===-1)break;$=this.buffer.indexOf(`
162
+ `,X)}while($!==-1);if($===-1){if(!this.atEnd)return this.setNext("block-scalar");$=this.buffer.length}}let Z=$+1;G=this.buffer[Z];while(G===" ")G=this.buffer[++Z];if(G==="\t"){while(G==="\t"||G===" "||G==="\r"||G===`
163
+ `)G=this.buffer[++Z];$=Z-1}else if(!this.blockScalarKeep)do{let X=$-1,Y=this.buffer[X];if(Y==="\r")Y=this.buffer[--X];let J=X;while(Y===" ")Y=this.buffer[--X];if(Y===`
164
+ `&&X>=this.pos&&X+1+w>J)$=X;else break}while(!0);return yield I9.SCALAR,yield*this.pushToIndex($+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let $=this.flowLevel>0,w=this.pos-1,G=this.pos-1,Z;while(Z=this.buffer[++G])if(Z===":"){let X=this.buffer[G+1];if(Y$(X)||$&&t5.has(X))break;w=G}else if(Y$(Z)){let X=this.buffer[G+1];if(Z==="\r")if(X===`
165
+ `)G+=1,Z=`
166
+ `,X=this.buffer[G+1];else w=G;if(X==="#"||$&&t5.has(X))break;if(Z===`
167
+ `){let Y=this.continueScalar(G+1);if(Y===-1)break;G=Math.max(G,Y-2)}}else{if($&&t5.has(Z))break;w=G}if(!Z&&!this.atEnd)return this.setNext("plain-scalar");return yield I9.SCALAR,yield*this.pushToIndex(w+1,!0),$?"flow":"doc"}*pushCount($){if($>0)return yield this.buffer.substr(this.pos,$),this.pos+=$,$;return 0}*pushToIndex($,w){let G=this.buffer.slice(this.pos,$);if(G)return yield G,this.pos+=G.length,G.length;else if(w)yield"";return 0}*pushIndicators(){let $=0;$:while(!0){switch(this.charAt(0)){case"!":$+=yield*this.pushTag(),$+=yield*this.pushSpaces(!0);continue $;case"&":$+=yield*this.pushUntil($7),$+=yield*this.pushSpaces(!0);continue $;case"-":case"?":case":":{let w=this.flowLevel>0,G=this.charAt(1);if(Y$(G)||w&&t5.has(G)){if(!w)this.indentNext=this.indentValue+1;else if(this.flowKey)this.flowKey=!1;$+=yield*this.pushCount(1),$+=yield*this.pushSpaces(!0);continue $}}}break $}return $}*pushTag(){if(this.charAt(1)==="<"){let $=this.pos+2,w=this.buffer[$];while(!Y$(w)&&w!==">")w=this.buffer[++$];return yield*this.pushToIndex(w===">"?$+1:$,!1)}else{let $=this.pos+1,w=this.buffer[$];while(w)if(Ik.has(w))w=this.buffer[++$];else if(w==="%"&&qq.has(this.buffer[$+1])&&qq.has(this.buffer[$+2]))w=this.buffer[$+=3];else break;return yield*this.pushToIndex($,!1)}}*pushNewline(){let $=this.buffer[this.pos];if($===`
168
+ `)return yield*this.pushCount(1);else if($==="\r"&&this.charAt(1)===`
169
+ `)return yield*this.pushCount(2);else return 0}*pushSpaces($){let w=this.pos-1,G;do G=this.buffer[++w];while(G===" "||$&&G==="\t");let Z=w-this.pos;if(Z>0)yield this.buffer.substr(this.pos,Z),this.pos=w;return Z}*pushUntil($){let w=this.pos,G=this.buffer[w];while(!$(G))G=this.buffer[++w];return yield*this.pushToIndex(w,!1)}}Ck.Lexer=Bq});var G7=F((kk)=>{class Nq{constructor(){this.lineStarts=[],this.addNewLine=($)=>this.lineStarts.push($),this.linePos=($)=>{let w=0,G=this.lineStarts.length;while(w<G){let X=w+G>>1;if(this.lineStarts[X]<$)w=X+1;else G=X}if(this.lineStarts[w]===$)return{line:w+1,col:1};if(w===0)return{line:0,col:$};let Z=this.lineStarts[w-1];return{line:w,col:$-Z+1}}}}kk.LineCounter=Nq});var Z7=F((gk)=>{var _k=D$("process"),Vq=a5(),xk=w7();function z1($,w){for(let G=0;G<$.length;++G)if($[G].type===w)return!0;return!1}function Kq($){for(let w=0;w<$.length;++w)switch($[w].type){case"space":case"comment":case"newline":break;default:return w}return-1}function Hq($){switch($?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function o5($){switch($.type){case"document":return $.start;case"block-map":{let w=$.items[$.items.length-1];return w.sep??w.start}case"block-seq":return $.items[$.items.length-1].start;default:return[]}}function sw($){if($.length===0)return[];let w=$.length;$:while(--w>=0)switch($[w].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break $}while($[++w]?.type==="space");return $.splice(w,$.length)}function e5($,w){if(w.length<1e5)Array.prototype.push.apply($,w);else for(let G=0;G<w.length;++G)$.push(w[G])}function Uq($){if($.start.type==="flow-seq-start"){for(let w of $.items)if(w.sep&&!w.value&&!z1(w.start,"explicit-key-ind")&&!z1(w.sep,"map-value-ind")){if(w.key)w.value=w.key;if(delete w.key,Hq(w.value))if(w.value.end)e5(w.value.end,w.sep);else w.value.end=w.sep;else e5(w.start,w.sep);delete w.sep}}}class Fq{constructor($){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new xk.Lexer,this.onNewLine=$}*parse($,w=!1){if(this.onNewLine&&this.offset===0)this.onNewLine(0);for(let G of this.lexer.lex($,w))yield*this.next(G);if(!w)yield*this.end()}*next($){if(this.source=$,_k.env.LOG_TOKENS)console.log("|",Vq.prettyToken($));if(this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=$.length;return}let w=Vq.tokenType($);if(!w){let G=`Not a YAML token: ${$}`;yield*this.pop({type:"error",offset:this.offset,message:G,source:$}),this.offset+=$.length}else if(w==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=w,yield*this.step(),w){case"newline":if(this.atNewLine=!0,this.indent=0,this.onNewLine)this.onNewLine(this.offset+$.length);break;case"space":if(this.atNewLine&&$[0]===" ")this.indent+=$.length;break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":if(this.atNewLine)this.indent+=$.length;break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=$.length}}*end(){while(this.stack.length>0)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let $=this.peek(1);if(this.type==="doc-end"&&$?.type!=="doc-end"){while(this.stack.length>0)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!$)return yield*this.stream();switch($.type){case"document":return yield*this.document($);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar($);case"block-scalar":return yield*this.blockScalar($);case"block-map":return yield*this.blockMap($);case"block-seq":return yield*this.blockSequence($);case"flow-collection":return yield*this.flowCollection($);case"doc-end":return yield*this.documentEnd($)}yield*this.pop()}peek($){return this.stack[this.stack.length-$]}*pop($){let w=$??this.stack.pop();if(!w)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield w;else{let G=this.peek(1);if(w.type==="block-scalar")w.indent="indent"in G?G.indent:0;else if(w.type==="flow-collection"&&G.type==="document")w.indent=0;if(w.type==="flow-collection")Uq(w);switch(G.type){case"document":G.value=w;break;case"block-scalar":G.props.push(w);break;case"block-map":{let Z=G.items[G.items.length-1];if(Z.value){G.items.push({start:[],key:w,sep:[]}),this.onKeyLine=!0;return}else if(Z.sep)Z.value=w;else{Object.assign(Z,{key:w,sep:[]}),this.onKeyLine=!Z.explicitKey;return}break}case"block-seq":{let Z=G.items[G.items.length-1];if(Z.value)G.items.push({start:[],value:w});else Z.value=w;break}case"flow-collection":{let Z=G.items[G.items.length-1];if(!Z||Z.value)G.items.push({start:[],key:w,sep:[]});else if(Z.sep)Z.value=w;else Object.assign(Z,{key:w,sep:[]});return}default:yield*this.pop(),yield*this.pop(w)}if((G.type==="document"||G.type==="block-map"||G.type==="block-seq")&&(w.type==="block-map"||w.type==="block-seq")){let Z=w.items[w.items.length-1];if(Z&&!Z.sep&&!Z.value&&Z.start.length>0&&Kq(Z.start)===-1&&(w.indent===0||Z.start.every((X)=>X.type!=="comment"||X.indent<w.indent))){if(G.type==="document")G.end=Z.start;else G.items.push({start:Z.start});w.items.splice(-1,1)}}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let $={type:"document",offset:this.offset,start:[]};if(this.type==="doc-start")$.start.push(this.sourceToken);this.stack.push($);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document($){if($.value)return yield*this.lineEnd($);switch(this.type){case"doc-start":{if(Kq($.start)!==-1)yield*this.pop(),yield*this.step();else $.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":$.start.push(this.sourceToken);return}let w=this.startBlockValue($);if(w)this.stack.push(w);else yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar($){if(this.type==="map-value-ind"){let w=o5(this.peek(2)),G=sw(w),Z;if($.end)Z=$.end,Z.push(this.sourceToken),delete $.end;else Z=[this.sourceToken];let X={type:"block-map",offset:$.offset,indent:$.indent,items:[{start:G,key:$,sep:Z}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=X}else yield*this.lineEnd($)}*blockScalar($){switch(this.type){case"space":case"comment":case"newline":$.props.push(this.sourceToken);return;case"scalar":if($.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let w=this.source.indexOf(`
170
+ `)+1;while(w!==0)this.onNewLine(this.offset+w),w=this.source.indexOf(`
171
+ `,w)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap($){let w=$.items[$.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,w.value){let G="end"in w.value?w.value.end:void 0;if((Array.isArray(G)?G[G.length-1]:void 0)?.type==="comment")G?.push(this.sourceToken);else $.items.push({start:[this.sourceToken]})}else if(w.sep)w.sep.push(this.sourceToken);else w.start.push(this.sourceToken);return;case"space":case"comment":if(w.value)$.items.push({start:[this.sourceToken]});else if(w.sep)w.sep.push(this.sourceToken);else{if(this.atIndentedComment(w.start,$.indent)){let Z=$.items[$.items.length-2]?.value?.end;if(Array.isArray(Z)){e5(Z,w.start),Z.push(this.sourceToken),$.items.pop();return}}w.start.push(this.sourceToken)}return}if(this.indent>=$.indent){let G=!this.onKeyLine&&this.indent===$.indent,Z=G&&(w.sep||w.explicitKey)&&this.type!=="seq-item-ind",X=[];if(Z&&w.sep&&!w.value){let Y=[];for(let J=0;J<w.sep.length;++J){let W=w.sep[J];switch(W.type){case"newline":Y.push(J);break;case"space":break;case"comment":if(W.indent>$.indent)Y.length=0;break;default:Y.length=0}}if(Y.length>=2)X=w.sep.splice(Y[1])}switch(this.type){case"anchor":case"tag":if(Z||w.value)X.push(this.sourceToken),$.items.push({start:X}),this.onKeyLine=!0;else if(w.sep)w.sep.push(this.sourceToken);else w.start.push(this.sourceToken);return;case"explicit-key-ind":if(!w.sep&&!w.explicitKey)w.start.push(this.sourceToken),w.explicitKey=!0;else if(Z||w.value)X.push(this.sourceToken),$.items.push({start:X,explicitKey:!0});else this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]});this.onKeyLine=!0;return;case"map-value-ind":if(w.explicitKey)if(!w.sep)if(z1(w.start,"newline"))Object.assign(w,{key:null,sep:[this.sourceToken]});else{let Y=sw(w.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:Y,key:null,sep:[this.sourceToken]}]})}else if(w.value)$.items.push({start:[],key:null,sep:[this.sourceToken]});else if(z1(w.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:X,key:null,sep:[this.sourceToken]}]});else if(Hq(w.key)&&!z1(w.sep,"newline")){let Y=sw(w.start),J=w.key,W=w.sep;W.push(this.sourceToken),delete w.key,delete w.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:Y,key:J,sep:W}]})}else if(X.length>0)w.sep=w.sep.concat(X,this.sourceToken);else w.sep.push(this.sourceToken);else if(!w.sep)Object.assign(w,{key:null,sep:[this.sourceToken]});else if(w.value||Z)$.items.push({start:X,key:null,sep:[this.sourceToken]});else if(z1(w.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]});else w.sep.push(this.sourceToken);this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let Y=this.flowScalar(this.type);if(Z||w.value)$.items.push({start:X,key:Y,sep:[]}),this.onKeyLine=!0;else if(w.sep)this.stack.push(Y);else Object.assign(w,{key:Y,sep:[]}),this.onKeyLine=!0;return}default:{let Y=this.startBlockValue($);if(Y){if(Y.type==="block-seq"){if(!w.explicitKey&&w.sep&&!z1(w.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else if(G)$.items.push({start:X});this.stack.push(Y);return}}}}yield*this.pop(),yield*this.step()}*blockSequence($){let w=$.items[$.items.length-1];switch(this.type){case"newline":if(w.value){let G="end"in w.value?w.value.end:void 0;if((Array.isArray(G)?G[G.length-1]:void 0)?.type==="comment")G?.push(this.sourceToken);else $.items.push({start:[this.sourceToken]})}else w.start.push(this.sourceToken);return;case"space":case"comment":if(w.value)$.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(w.start,$.indent)){let Z=$.items[$.items.length-2]?.value?.end;if(Array.isArray(Z)){e5(Z,w.start),Z.push(this.sourceToken),$.items.pop();return}}w.start.push(this.sourceToken)}return;case"anchor":case"tag":if(w.value||this.indent<=$.indent)break;w.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==$.indent)break;if(w.value||z1(w.start,"seq-item-ind"))$.items.push({start:[this.sourceToken]});else w.start.push(this.sourceToken);return}if(this.indent>$.indent){let G=this.startBlockValue($);if(G){this.stack.push(G);return}}yield*this.pop(),yield*this.step()}*flowCollection($){let w=$.items[$.items.length-1];if(this.type==="flow-error-end"){let G;do yield*this.pop(),G=this.peek(1);while(G?.type==="flow-collection")}else if($.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":if(!w||w.sep)$.items.push({start:[this.sourceToken]});else w.start.push(this.sourceToken);return;case"map-value-ind":if(!w||w.value)$.items.push({start:[],key:null,sep:[this.sourceToken]});else if(w.sep)w.sep.push(this.sourceToken);else Object.assign(w,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":if(!w||w.value)$.items.push({start:[this.sourceToken]});else if(w.sep)w.sep.push(this.sourceToken);else w.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let Z=this.flowScalar(this.type);if(!w||w.value)$.items.push({start:[],key:Z,sep:[]});else if(w.sep)this.stack.push(Z);else Object.assign(w,{key:Z,sep:[]});return}case"flow-map-end":case"flow-seq-end":$.end.push(this.sourceToken);return}let G=this.startBlockValue($);if(G)this.stack.push(G);else yield*this.pop(),yield*this.step()}else{let G=this.peek(2);if(G.type==="block-map"&&(this.type==="map-value-ind"&&G.indent===$.indent||this.type==="newline"&&!G.items[G.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&G.type!=="flow-collection"){let Z=o5(G),X=sw(Z);Uq($);let Y=$.end.splice(1,$.end.length);Y.push(this.sourceToken);let J={type:"block-map",offset:$.offset,indent:$.indent,items:[{start:X,key:$,sep:Y}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=J}else yield*this.lineEnd($)}}flowScalar($){if(this.onNewLine){let w=this.source.indexOf(`
172
+ `)+1;while(w!==0)this.onNewLine(this.offset+w),w=this.source.indexOf(`
173
+ `,w)+1}return{type:$,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue($){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let w=o5($),G=sw(w);return G.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:G,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let w=o5($),G=sw(w);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:G,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment($,w){if(this.type!=="comment")return!1;if(this.indent<=w)return!1;return $.every((G)=>G.type==="newline"||G.type==="space")}*documentEnd($){if(this.type!=="doc-mode"){if($.end)$.end.push(this.sourceToken);else $.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd($){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:if($.end)$.end.push(this.sourceToken);else $.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}gk.Parser=Fq});var Eq=F((pk)=>{var Oq=pX(),hk=D9(),j9=E9(),vk=GX(),ik=r(),mk=G7(),fq=Z7();function Lq($){let w=$.prettyErrors!==!1;return{lineCounter:$.lineCounter||w&&new mk.LineCounter||null,prettyErrors:w}}function lk($,w={}){let{lineCounter:G,prettyErrors:Z}=Lq(w),X=new fq.Parser(G?.addNewLine),Y=new Oq.Composer(w),J=Array.from(Y.compose(X.parse($)));if(Z&&G)for(let W of J)W.errors.forEach(j9.prettifyError($,G)),W.warnings.forEach(j9.prettifyError($,G));if(J.length>0)return J;return Object.assign([],{empty:!0},Y.streamInfo())}function Dq($,w={}){let{lineCounter:G,prettyErrors:Z}=Lq(w),X=new fq.Parser(G?.addNewLine),Y=new Oq.Composer(w),J=null;for(let W of Y.compose(X.parse($),!0,$.length))if(!J)J=W;else if(J.options.logLevel!=="silent"){J.errors.push(new j9.YAMLParseError(W.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(Z&&G)J.errors.forEach(j9.prettifyError($,G)),J.warnings.forEach(j9.prettifyError($,G));return J}function dk($,w,G){let Z=void 0;if(typeof w==="function")Z=w;else if(G===void 0&&w&&typeof w==="object")G=w;let X=Dq($,G);if(!X)return null;if(X.warnings.forEach((Y)=>vk.warn(X.options.logLevel,Y)),X.errors.length>0)if(X.options.logLevel!=="silent")throw X.errors[0];else X.errors=[];return X.toJS(Object.assign({reviver:Z},G))}function ck($,w,G){let Z=null;if(typeof w==="function"||Array.isArray(w))Z=w;else if(G===void 0&&w)G=w;if(typeof G==="string")G=G.length;if(typeof G==="number"){let X=Math.round(G);G=X<1?void 0:X>8?{indent:8}:{indent:X}}if($===void 0){let{keepUndefined:X}=G??w??{};if(!X)return}if(ik.isDocument($)&&!Z)return $.toString(G);return new hk.Document($,Z,G).toString(G)}pk.parse=dk;pk.parseAllDocuments=lk;pk.parseDocument=Dq;pk.stringify=ck});var y9=F((Rc,q7)=>{var QG=process||{},nq=QG.argv||[],TG=QG.env||{},Y_=!(!!TG.NO_COLOR||nq.includes("--no-color"))&&(!!TG.FORCE_COLOR||nq.includes("--color")||QG.platform==="win32"||(QG.stdout||{}).isTTY&&TG.TERM!=="dumb"||!!TG.CI),J_=($,w,G=$)=>(Z)=>{let X=""+Z,Y=X.indexOf(w,$.length);return~Y?$+W_(X,w,G,Y)+w:$+X+w},W_=($,w,G,Z)=>{let X="",Y=0;do X+=$.substring(Y,Z)+G,Y=Z+w.length,Z=$.indexOf(w,Y);while(~Z);return X+$.substring(Y)},rq=($=Y_)=>{let w=$?J_:()=>String;return{isColorSupported:$,reset:w("\x1B[0m","\x1B[0m"),bold:w("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:w("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:w("\x1B[3m","\x1B[23m"),underline:w("\x1B[4m","\x1B[24m"),inverse:w("\x1B[7m","\x1B[27m"),hidden:w("\x1B[8m","\x1B[28m"),strikethrough:w("\x1B[9m","\x1B[29m"),black:w("\x1B[30m","\x1B[39m"),red:w("\x1B[31m","\x1B[39m"),green:w("\x1B[32m","\x1B[39m"),yellow:w("\x1B[33m","\x1B[39m"),blue:w("\x1B[34m","\x1B[39m"),magenta:w("\x1B[35m","\x1B[39m"),cyan:w("\x1B[36m","\x1B[39m"),white:w("\x1B[37m","\x1B[39m"),gray:w("\x1B[90m","\x1B[39m"),bgBlack:w("\x1B[40m","\x1B[49m"),bgRed:w("\x1B[41m","\x1B[49m"),bgGreen:w("\x1B[42m","\x1B[49m"),bgYellow:w("\x1B[43m","\x1B[49m"),bgBlue:w("\x1B[44m","\x1B[49m"),bgMagenta:w("\x1B[45m","\x1B[49m"),bgCyan:w("\x1B[46m","\x1B[49m"),bgWhite:w("\x1B[47m","\x1B[49m"),blackBright:w("\x1B[90m","\x1B[39m"),redBright:w("\x1B[91m","\x1B[39m"),greenBright:w("\x1B[92m","\x1B[39m"),yellowBright:w("\x1B[93m","\x1B[39m"),blueBright:w("\x1B[94m","\x1B[39m"),magentaBright:w("\x1B[95m","\x1B[39m"),cyanBright:w("\x1B[96m","\x1B[39m"),whiteBright:w("\x1B[97m","\x1B[39m"),bgBlackBright:w("\x1B[100m","\x1B[49m"),bgRedBright:w("\x1B[101m","\x1B[49m"),bgGreenBright:w("\x1B[102m","\x1B[49m"),bgYellowBright:w("\x1B[103m","\x1B[49m"),bgBlueBright:w("\x1B[104m","\x1B[49m"),bgMagentaBright:w("\x1B[105m","\x1B[49m"),bgCyanBright:w("\x1B[106m","\x1B[49m"),bgWhiteBright:w("\x1B[107m","\x1B[49m")}};q7.exports=rq();q7.exports.createColors=rq});import{realpathSync as mV}from"fs";import{realpath as Dh}from"fs/promises";import Eh from"path";import{createInterface as Ah}from"readline/promises";import{fileURLToPath as Rh}from"url";var OJ=A1(b3(),1),{program:ih,createCommand:mh,createArgument:lh,createOption:dh,CommanderError:ch,InvalidArgumentError:ph,InvalidOptionArgumentError:nh,Command:fJ,Argument:rh,Option:sh,Help:ah}=OJ.default;import LJ from"node:os";import f6 from"node:path";function DJ(){return process.env.XDG_CONFIG_HOME?f6.join(process.env.XDG_CONFIG_HOME,"coden"):f6.join(LJ.homedir(),".config","coden")}function EJ(){return process.env.XDG_DATA_HOME?f6.join(process.env.XDG_DATA_HOME,"coden"):f6.join(LJ.homedir(),".local","share","coden")}import{mkdir as pK,readFile as nK,realpath as AJ,writeFile as rK}from"node:fs/promises";import sK from"node:path";class k3{file;constructor($){this.file=$}async isTrusted($){return(await this.read()).includes($)}async isWorkspaceTrusted($){return this.isTrusted(await AJ($))}async trustWorkspace($){return this.trust(await AJ($))}async trust($){let w=await this.read();if(!w.includes($))w.push($);await pK(sK.dirname(this.file),{recursive:!0}),await rK(this.file,`${JSON.stringify(w,null,2)}
174
+ `,{encoding:"utf8",mode:384})}async read(){try{let $=JSON.parse(await nK(this.file,"utf8"));return Array.isArray($)?$.filter((w)=>typeof w==="string"):[]}catch($){if($.code==="ENOENT")return[];throw $}}}function Ew($,w){if($.length<=w)return $;let Z=Math.max(0,w-80),X=Math.ceil(Z/2),Y=Math.floor(Z/2),J=$.length-X-Y;return`${$.slice(0,X)}
175
+ ... [${J} characters omitted] ...
176
+ ${$.slice($.length-Y)}`}class y extends Error{category;code;retryable;details;constructor($,w,G,Z=!1,X,Y){super(G,Y);this.category=$;this.code=w;this.retryable=Z;this.details=X;this.name="CodeNError"}}import{spawn as aK}from"node:child_process";class y3{headLimit;tailLimit;head="";tail="";total=0;constructor($){this.headLimit=Math.ceil($*0.6),this.tailLimit=Math.floor($*0.4)}add($){this.total+=$.length;let w=Math.max(0,this.headLimit-this.head.length);this.head+=$.slice(0,w);let G=$.slice(w);if(G)this.tail=`${this.tail}${G}`.slice(-this.tailLimit)}value(){let $=this.total-this.head.length-this.tail.length;return $>0?`${this.head}
39
177
  ... [${$} characters omitted while capturing] ...
40
- ${this.tail}`:`${this.head}${this.tail}`}}var T8=($,w,G)=>new Promise((W)=>{let Y=process.platform!=="win32",Z=NN($,w,{cwd:G.cwd,env:G.env,stdio:["ignore","pipe","pipe"],detached:Y}),X=new j5(G.maxOutputChars),J=new j5(G.maxOutputChars),T=!1,M=!1,f=!1,Q,N,z=(V)=>{if(Y&&Z.pid)try{process.kill(-Z.pid,V);return}catch{}Z.kill(V)},K=(V,E)=>{if(f)return;if((T||M)&&Y&&Z.pid)try{process.kill(-Z.pid,"SIGKILL")}catch{}if(f=!0,clearTimeout(N),Q)clearTimeout(Q);G.signal?.removeEventListener("abort",q),W({ok:!T&&!M&&V===0,stdout:X.value(),stderr:J.value(),exitCode:V,signal:E,timedOut:T,cancelled:M})},P=()=>{if(Q)return;Q=setTimeout(()=>z("SIGKILL"),500),Q.unref()},q=()=>{if(M)return;M=!0,z("SIGTERM"),P()};if(Z.stdout.setEncoding("utf8"),Z.stderr.setEncoding("utf8"),Z.stdout.on("data",(V)=>X.add(V)),Z.stderr.on("data",(V)=>J.add(V)),Z.once("error",(V)=>{J.add(V.message),K(null,null)}),Z.once("close",K),G.signal?.aborted)q();else G.signal?.addEventListener("abort",q,{once:!0});N=setTimeout(()=>{T=!0,z("SIGTERM"),P()},G.timeoutMs)});function zN($){let w=$.timedOut?"bun install timed out":$.cancelled?"bun install cancelled":`bun install exited with code ${$.exitCode??"null"}${$.signal?` (signal ${$.signal})`:""}`;return d$([w,$.stderr?`stderr:
178
+ ${this.tail}`:`${this.head}${this.tail}`}}var L6=($,w,G)=>new Promise((Z)=>{let X=process.platform!=="win32",Y=aK($,w,{cwd:G.cwd,env:G.env,stdio:["ignore","pipe","pipe"],detached:X}),J=new y3(G.maxOutputChars),W=new y3(G.maxOutputChars),T=!1,Q=!1,z=!1,M,P,q=(K)=>{if(X&&Y.pid)try{process.kill(-Y.pid,K);return}catch{}Y.kill(K)},N=(K,U)=>{if(z)return;if((T||Q)&&X&&Y.pid)try{process.kill(-Y.pid,"SIGKILL")}catch{}if(z=!0,clearTimeout(P),M)clearTimeout(M);G.signal?.removeEventListener("abort",V),Z({ok:!T&&!Q&&K===0,stdout:J.value(),stderr:W.value(),exitCode:K,signal:U,timedOut:T,cancelled:Q})},B=()=>{if(M)return;M=setTimeout(()=>q("SIGKILL"),500),M.unref()},V=()=>{if(Q)return;Q=!0,q("SIGTERM"),B()};if(Y.stdout.setEncoding("utf8"),Y.stderr.setEncoding("utf8"),Y.stdout.on("data",(K)=>J.add(K)),Y.stderr.on("data",(K)=>W.add(K)),Y.once("error",(K)=>{W.add(K.message),N(null,null)}),Y.once("close",N),G.signal?.aborted)V();else G.signal?.addEventListener("abort",V,{once:!0});P=setTimeout(()=>{T=!0,q("SIGTERM"),B()},G.timeoutMs)});function tK($){let w=$.timedOut?"bun install timed out":$.cancelled?"bun install cancelled":`bun install exited with code ${$.exitCode??"null"}${$.signal?` (signal ${$.signal})`:""}`;return Ew([w,$.stderr?`stderr:
41
179
  ${$.stderr}`:`stderr:
42
180
  <empty>`].join(`
43
- `),4000)}class C5{runner;constructor($=T8){this.runner=$}async install($){let w=["install","--registry","https://registry.npmjs.org"];if($.frozenLockfile)w.push("--frozen-lockfile");if(!$.allowScripts)w.push("--ignore-scripts");let G=await this.runner("bun",w,{cwd:$.cwd,env:process.env,...$.signal?{signal:$.signal}:{},timeoutMs:120000,maxOutputChars:30000});if(!G.ok)throw new y("plugin","plugin.install_failed",zN(G))}}import IU from"node:path";import{pathToFileURL as bU}from"node:url";var _J=c$(bJ(),1);var jG=new _J.default({allErrors:!0,strict:!1,useDefaults:!0});class Z1{#$=new Map;constructor($=[]){for(let w of $)this.register(w,{kind:"builtin"})}register($,w={kind:"local"}){if(!/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/.test($.name))throw new y("plugin","tool.invalid_name",`Invalid tool name: ${$.name}`);let G=this.#$.get($.name);if(G)throw new y("plugin","tool.duplicate",`Duplicate tool: ${$.name} from ${xJ(G.source)} and ${xJ(w)}`);try{jG.compile($.inputSchema)}catch(W){throw new y("plugin","tool.invalid_schema",`Invalid schema for ${$.name}`,!1,void 0,{cause:W})}this.#$.set($.name,{definition:$,source:w})}get($){return this.#$.get($)?.definition}list(){return[...this.#$.values()].map(($)=>$.definition)}source($){return this.#$.get($)?.source}entries(){return[...this.#$.values()].map(($)=>({definition:$.definition,source:$.source}))}clone(){let $=new Z1;return $.#$=new Map(this.#$),$}replaceWith($){this.#$=new Map($.#$)}validate($,w){let G=this.get($);if(!G)return{valid:!1,errors:`Unknown tool: ${$}`};let W=jG.compile(G.inputSchema);return W(w)?{valid:!0}:{valid:!1,errors:jG.errorsText(W.errors)}}}function xJ($){switch($.kind){case"builtin":return"builtin";case"local":return $.path?`local:${$.path}`:"local";case"npm":return $.path?`${$.pluginName}@${$.pluginVersion}:${$.path}`:`${$.pluginName}@${$.pluginVersion}`}}var CG=1;function n8($,w){if(gJ($))return[$];if(!$||typeof $!=="object")throw new y("plugin","plugin.export_invalid","plugin.export_invalid: default export must be a tool or CodeNPlugin");let G=$;if(G.apiVersion!==CG)throw new y("plugin","plugin.api_unsupported",`plugin.api_unsupported: ${String(G.apiVersion)}`);if(G.name!==w)throw new y("plugin","plugin.name_mismatch",`plugin.name_mismatch: expected ${w}, received ${String(G.name)}`);if(!Array.isArray(G.tools)||G.tools.length===0)throw new y("plugin","plugin.export_invalid","plugin.export_invalid: tools must be a non-empty array");if(!G.tools.every(gJ))throw new y("plugin","plugin.export_invalid","plugin.export_invalid: every tool must match ToolDefinition");return G.tools}function gJ($){if(!$||typeof $!=="object")return!1;let w=$;return typeof w.name==="string"&&typeof w.description==="string"&&(w.risk==="read"||w.risk==="modify"||w.risk==="dangerous")&&!!w.inputSchema&&typeof w.execute==="function"}import{readFile as LU}from"node:fs/promises";var FU=/^(?:@[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*|[a-z0-9][a-z0-9._-]*)$/;function N$($){return FU.test($)&&!$.includes("..")&&!$.includes("\\")}function vJ($){if(typeof $!=="string"||!$.startsWith("npm:"))throw V4($);let w=$.slice(4);if(!w||/\s/.test(w)||w.includes("\\")||w.includes("://"))throw V4($);let{packageName:G,requested:W}=OU(w);if(!N$(G))throw V4($);if(!W||/\s/.test(W)||W.includes("\\")||W.includes("/")||W.includes(":")||W.includes(".."))throw V4($);return{source:"npm",packageName:G,requested:W,raw:$}}function OU($){if($.startsWith("@")){let G=$.indexOf("/");if(G<2)throw V4($);let W=$.lastIndexOf("@");if(W<=G)return{packageName:$,requested:"latest"};return{packageName:$.slice(0,W),requested:$.slice(W+1)}}let w=$.lastIndexOf("@");if(w===-1)return{packageName:$,requested:"latest"};return{packageName:$.slice(0,w),requested:$.slice(w+1)}}function V4($){return new y("plugin","plugin.specifier_invalid",`plugin.specifier_invalid: ${String($)}`)}var DU=()=>({schemaVersion:1,plugins:{}});async function E1($){try{let w=JSON.parse(await LU($,"utf8"));return IG(w)}catch(w){if(kU(w))return DU();if(w instanceof y)throw w;throw z$(w,$)}}function yG($){return`${JSON.stringify(IG($),null,2)}
44
- `}function uJ($){let w=IG($),G={};for(let[W,Y]of Object.entries(w.plugins))G[W]=Y.requested;return{private:!0,dependencies:G}}function IG($){if(!$||typeof $!=="object")throw z$();let w=$;if(w.schemaVersion!==1)throw z$();if(!w.plugins||typeof w.plugins!=="object"||Array.isArray(w.plugins))throw z$();let G={};for(let W of Object.keys(w.plugins).sort()){if(!N$(W))throw z$();let Y=w.plugins[W];if(!Y||typeof Y!=="object"||Array.isArray(Y))throw z$();let Z=Y;if(Z.source!=="npm"||typeof Z.requested!=="string"||!Z.requested)throw z$();G[W]={source:"npm",requested:Z.requested}}return{schemaVersion:1,plugins:G}}function kU($){return typeof $==="object"&&$!==null&&"code"in $&&$.code==="ENOENT"}function z$($,w){return new y("plugin","plugin.manifest_invalid",w?`plugin.manifest_invalid: ${w}`:"plugin.manifest_invalid",!1,void 0,$ instanceof Error?{cause:$}:void 0)}import{readFile as AU,realpath as SU}from"node:fs/promises";import p8 from"node:path";async function Ww($,w){if(!N$(w))throw K$();let G=p8.join($,"node_modules",...w.split("/")),W=p8.join(G,"package.json"),Y;try{Y=JSON.parse(await AU(W,"utf8"))}catch{throw K$()}let Z=RU(Y,w),X=await hJ(G),J=p8.resolve(G,Z.entry),T=await hJ(J,!0);if(!jU(X,T))throw bG();return{packageName:w,version:Z.version,packageDirectory:X,entryPath:T,apiVersion:1}}function RU($,w){if(!$||typeof $!=="object")throw K$();let G=$;if(G.name!==w||typeof G.version!=="string"||!G.version)throw K$();if(G.type!=="module")throw K$();if(!G.coden||typeof G.coden!=="object"||Array.isArray(G.coden))throw K$();let W=G.coden;if(W.apiVersion!==1)throw yU(W.apiVersion);if(typeof W.plugin!=="string"||!CU(W.plugin))throw bG();return{version:G.version,entry:W.plugin}}async function hJ($,w=!1){try{return await SU($)}catch{if(w)throw bG();throw K$()}}function jU($,w){return w===$||w.startsWith(`${$}${p8.sep}`)}function CU($){if(!$.startsWith("./"))return!1;if($.includes("\\")||$.includes("://")||/\s/.test($))return!1;if(!($.endsWith(".js")||$.endsWith(".mjs")))return!1;if($.split("/").includes(".."))return!1;return!0}function K$(){return new y("plugin","plugin.metadata_missing","plugin.metadata_missing")}function yU($){return new y("plugin","plugin.api_unsupported",`plugin.api_unsupported: ${String($)}`)}function bG(){return new y("plugin","plugin.entry_invalid","plugin.entry_invalid")}class xG{importer;constructor($=(w)=>import(w)){this.importer=$}async loadScope($){let w=await E1($.manifestPath),G=[],W=[];for(let Y of Object.keys(w.plugins).sort()){let Z=xU($.runtimeDir,Y);try{let X=await Ww($.runtimeDir,Y);try{let J=await this.importer(bU(X.entryPath).href),T=n8(J.default,Y);G.push({packageName:Y,version:X.version,entryPath:X.entryPath,tools:T})}catch(J){W.push({packageName:Y,path:X.entryPath,message:iJ(J)})}}catch(X){W.push({packageName:Y,path:Z,message:iJ(X)})}}return{loaded:G,failed:W}}}function xU($,w){return IU.join($,"node_modules",...w.split("/"))}function iJ($){return $ instanceof Error?$.message:String($)}import{constants as nU}from"node:fs";import{access as pU,copyFile as tU,mkdir as rU,writeFile as s8}from"node:fs/promises";import c1 from"node:path";import _U from"node:path";import{pathToFileURL as gU}from"node:url";class _G{importer;constructor($=(w)=>import(w)){this.importer=$}async loadScope($){let w=await E1($.manifestPath),G=[],W=[];for(let Y of Object.keys(w.plugins).sort()){let Z=uU($.runtimeDir,Y);try{let X=await Ww($.runtimeDir,Y);try{let J=await this.importer(gU(X.entryPath).href),T=n8(J.default,Y);G.push({packageName:Y,version:X.version,entryPath:X.entryPath,tools:T})}catch(J){W.push({packageName:Y,path:X.entryPath,message:lJ(J)})}}catch(X){W.push({packageName:Y,path:Z,message:lJ(X)})}}return{loaded:G,failed:W}}}function gG($,w,G){let W=new Z1($),Y=new Map(G.map((T)=>[T.packageName,T])),Z=[],X=[];for(let T of w){let M=Y.get(T.packageName);if(M){Z.push({packageName:T.packageName,globalVersion:T.version,projectVersion:M.version});continue}X.push(T)}let J=[...X,...G];for(let T of J)vU(W,T);return{registry:W,effective:J,shadowed:Z}}function vU($,w){let G={kind:"npm",pluginName:w.packageName,pluginVersion:w.version,path:w.entryPath};for(let W of w.tools){let Y=$.source(W.name);if(Y)throw new y("plugin","plugin.tool_conflict",`plugin.tool_conflict: ${W.name} from ${mJ(Y)} conflicts with ${mJ(G)}`);$.register(W,G)}}function uU($,w){return _U.join($,"node_modules",...w.split("/"))}function mJ($){switch($.kind){case"builtin":return"builtin";case"local":return $.path?`local:${$.path}`:"local";case"npm":return $.path?`${$.pluginName}@${$.pluginVersion}:${$.path}`:`${$.pluginName}@${$.pluginVersion}`}}function lJ($){return $ instanceof Error?$.message:String($)}import X1 from"node:path";import{readFile as hU}from"node:fs/promises";import nJ from"node:os";import Yw from"node:path";function t8(){return process.env.XDG_CONFIG_HOME?Yw.join(process.env.XDG_CONFIG_HOME,"coden"):Yw.join(nJ.homedir(),".config","coden")}function vG(){return process.env.XDG_DATA_HOME?Yw.join(process.env.XDG_DATA_HOME,"coden"):Yw.join(nJ.homedir(),".local","share","coden")}async function cJ($){try{let w=JSON.parse(await hU($,"utf8"));return iU(w)}catch(w){if(w.code==="ENOENT")return{};throw Error(`Cannot read config ${$}: ${w instanceof Error?w.message:String(w)}`)}}function iU($){let w={};if($.provider==="openai"||$.provider==="anthropic")w.provider=$.provider;if(typeof $.model==="string")w.model=$.model;if(typeof $.maxSteps==="number")w.maxSteps=$.maxSteps;if(typeof $.contextWindow==="number")w.contextWindow=$.contextWindow;if(typeof $.reservedOutputTokens==="number")w.reservedOutputTokens=$.reservedOutputTokens;if(typeof $.safetyMargin==="number")w.safetyMargin=$.safetyMargin;if(Array.isArray($.plugins))w.plugins=$.plugins.filter((G)=>typeof G==="string");if($.env!==void 0){if(typeof $.env!=="object"||$.env===null||Array.isArray($.env))throw Error("env must be an object");let G={};for(let[W,Y]of Object.entries($.env)){if(typeof Y!=="string")throw Error(`env "${W}" must be a string`);G[W]=Y}w.env=G}return w}function dJ($){let{env:w,...G}=$;return G}async function pJ($,w={}){let G={provider:"openai",model:"gpt-5-mini",maxSteps:20,contextWindow:128000,reservedOutputTokens:8192,safetyMargin:4096,plugins:[],dataDir:vG(),env:{}},W=await cJ(Yw.join(t8(),"config.json")),Y=await cJ(Yw.join($,".coden","config.json")),Z={};if(process.env.CODEN_PROVIDER==="openai"||process.env.CODEN_PROVIDER==="anthropic")Z.provider=process.env.CODEN_PROVIDER;if(process.env.CODEN_MODEL)Z.model=process.env.CODEN_MODEL;if(process.env.CODEN_MAX_STEPS)Z.maxSteps=Number(process.env.CODEN_MAX_STEPS);let X={...W.env??{},...Y.env??{}};for(let[T,M]of Object.entries(X))if(process.env[T]===void 0)process.env[T]=M;let J={...G,...dJ(W),...dJ(Y),...Z,...w,env:X};if(J.plugins=[...W.plugins??[],...Y.plugins??[],...w.plugins??[]],J.provider!=="openai"&&J.provider!=="anthropic")throw Error("provider must be openai or anthropic");if(typeof J.model!=="string"||!J.model.trim())throw Error("model must be a non-empty string");if(!Number.isInteger(J.maxSteps)||J.maxSteps<1)throw Error("maxSteps must be a positive integer");for(let T of["contextWindow","reservedOutputTokens","safetyMargin"])if(!Number.isInteger(J[T])||J[T]<0)throw Error(`${T} must be a non-negative integer`);if(J.contextWindow===0||J.reservedOutputTokens===0)throw Error("contextWindow and reservedOutputTokens must be positive");if(J.contextWindow<=J.reservedOutputTokens+J.safetyMargin)throw Error("contextWindow must exceed reservedOutputTokens plus safetyMargin");if(!Array.isArray(J.plugins)||J.plugins.some((T)=>typeof T!=="string"))throw Error("plugins must be an array of paths");return J}function q4($,w,G=vG()){if(w==="project"){let Z=X1.join($,".coden"),X=X1.join(Z,"plugin-runtime");return{scope:w,root:Z,manifestPath:X1.join(Z,"plugins.json"),runtimeDir:X,lockPath:X1.join(Z,"plugin-lock"),transactionPath:X1.join(Z,"plugin-transaction.json")}}let W=X1.join(G,"plugins"),Y=X1.join(W,"runtime");return{scope:w,root:W,manifestPath:X1.join(W,"plugins.json"),runtimeDir:Y,lockPath:X1.join(W,"plugin-lock"),transactionPath:X1.join(W,"plugin-transaction.json")}}import{randomUUID as mU}from"node:crypto";import{constants as lU}from"node:fs";import{access as cU,mkdir as r8,readFile as tJ,rename as m1,rm as G0,writeFile as rJ}from"node:fs/promises";import l1 from"node:path";class hG extends Error{constructor($){super($ instanceof Error?$.message:String($),$ instanceof Error?{cause:$}:void 0);this.name="FaultInterruption"}}class C0{paths;options;constructor($,w={}){this.paths=$;this.options=w}async run($){let w=!1,G;try{await this.acquireLock(),w=!0,await this.recoverLocked();let W=mU(),Y=l1.join(this.paths.root,`.transaction-${W}-stage`);G={version:1,id:W,phase:"prepared",stageDirectory:Y,backupManifestPath:l1.join(this.paths.root,`.transaction-${W}-plugins.json.bak`),backupRuntimeDir:l1.join(this.paths.root,`.transaction-${W}-runtime.bak`),hadManifest:await E4(this.paths.manifestPath),hadRuntime:await E4(this.paths.runtimeDir)},await r8(Y,{recursive:!0});let Z={manifestPath:l1.join(Y,"plugins.json"),runtimeDir:l1.join(Y,"runtime")},X=await $(Z);await this.verifyCandidate(Z),await this.writeMarker(G),await this.backupCurrent(G);let J={...G,phase:"backed-up"};await this.writeMarker(J),G=J,this.fault("after-backup"),await m1(Z.runtimeDir,this.paths.runtimeDir);let T={...G,phase:"runtime-committed"};await this.writeMarker(T),G=T,this.fault("after-runtime-commit"),await m1(Z.manifestPath,this.paths.manifestPath);let M={...G,phase:"manifest-committed"};return await this.writeMarker(M),G=M,this.fault("after-manifest-commit"),await this.cleanupCommitted(G),X}catch(W){if(W instanceof hG)throw W.cause??W;throw await this.rollbackAfterError(G),W}finally{if(w)await this.releaseLock()}}async recover(){let $=!1;try{await this.acquireLock(),$=!0,await this.recoverLocked()}finally{if($)await this.releaseLock()}}async acquireLock(){await r8(this.paths.root,{recursive:!0});for(let $=0;$<2;$++){try{await r8(this.paths.lockPath)}catch(w){if(!uG(w,"EEXIST"))throw w;let G=await this.readLockOwner();if(!G||this.isProcessAlive(G.pid))throw new y("plugin","plugin.install_busy",`plugin.install_busy: ${this.paths.scope} plugin installation is already running`,!0,{scope:this.paths.scope});if($===1)throw new y("plugin","plugin.install_busy",`plugin.install_busy: could not acquire ${this.paths.scope} plugin lock`,!0,{scope:this.paths.scope});await G0(this.paths.lockPath,{recursive:!0,force:!0});continue}try{await rJ(l1.join(this.paths.lockPath,"owner.json"),`${JSON.stringify({pid:process.pid,createdAt:this.now()})}
45
- `,{mode:384});return}catch(w){throw await G0(this.paths.lockPath,{recursive:!0,force:!0}),w}}}async readLockOwner(){try{let $=JSON.parse(await tJ(l1.join(this.paths.lockPath,"owner.json"),"utf8"));if(typeof $.pid==="number"&&Number.isInteger($.pid)&&$.pid>0)return{pid:$.pid,createdAt:typeof $.createdAt==="number"?$.createdAt:0};return}catch{return}}async releaseLock(){await G0(this.paths.lockPath,{recursive:!0,force:!0})}async verifyCandidate($){if(!await E4($.manifestPath)||!await E4($.runtimeDir))throw new y("plugin","plugin.transaction_recovery_failed","plugin.transaction_recovery_failed: candidate manifest and runtime are required",!1,{scope:this.paths.scope})}async backupCurrent($){if(await G0($.backupManifestPath,{force:!0}),await G0($.backupRuntimeDir,{recursive:!0,force:!0}),$.hadManifest)await m1(this.paths.manifestPath,$.backupManifestPath);if($.hadRuntime)await m1(this.paths.runtimeDir,$.backupRuntimeDir)}async rollbackAfterError($){if(!$)return;try{if($.phase==="manifest-committed"){await this.cleanupCommitted($);return}await this.restoreBackupPairBestEffort($),await this.cleanupRecoveryArtifacts($)}catch(w){throw new y("plugin","plugin.transaction_recovery_failed",`plugin.transaction_recovery_failed: could not roll back ${this.paths.scope} plugin transaction`,!1,{scope:this.paths.scope},w instanceof Error?{cause:w}:void 0)}}async recoverLocked(){let $=await this.readMarker();if(!$)return;try{if($.phase==="prepared"){await G0($.stageDirectory,{recursive:!0,force:!0}),await G0(this.paths.transactionPath,{force:!0});return}if($.phase==="backed-up"||$.phase==="runtime-committed"){await this.removeCurrentTargets(),await this.restoreBackups($),await this.cleanupRecoveryArtifacts($);return}await G0($.backupManifestPath,{force:!0}),await G0($.backupRuntimeDir,{recursive:!0,force:!0}),await this.cleanupRecoveryArtifacts($)}catch(w){throw new y("plugin","plugin.transaction_recovery_failed",`plugin.transaction_recovery_failed: could not recover ${this.paths.scope} plugin transaction`,!1,{scope:this.paths.scope},w instanceof Error?{cause:w}:void 0)}}async readMarker(){try{let $=JSON.parse(await tJ(this.paths.transactionPath,"utf8"));if(!dU($))throw Error("invalid transaction marker");return $}catch($){if(uG($,"ENOENT"))return;throw new y("plugin","plugin.transaction_recovery_failed",`plugin.transaction_recovery_failed: invalid ${this.paths.scope} plugin transaction marker`,!1,{scope:this.paths.scope},$ instanceof Error?{cause:$}:void 0)}}async writeMarker($){await r8(l1.dirname(this.paths.transactionPath),{recursive:!0});let w=`${this.paths.transactionPath}.tmp`;await rJ(w,`${JSON.stringify($,null,2)}
46
- `,{mode:384}),await m1(w,this.paths.transactionPath)}async cleanupCommitted($){await G0($.backupManifestPath,{force:!0}),await G0($.backupRuntimeDir,{recursive:!0,force:!0}),await G0($.stageDirectory,{recursive:!0,force:!0}),await G0(this.paths.transactionPath,{force:!0}),await G0(`${this.paths.transactionPath}.tmp`,{recursive:!0,force:!0})}async cleanupRecoveryArtifacts($){await G0($.stageDirectory,{recursive:!0,force:!0}),await G0(this.paths.transactionPath,{force:!0}),await G0(`${this.paths.transactionPath}.tmp`,{recursive:!0,force:!0})}async removeCurrentTargets(){await G0(this.paths.manifestPath,{force:!0}),await G0(this.paths.runtimeDir,{recursive:!0,force:!0})}async restoreBackups($){if($.hadManifest)await m1($.backupManifestPath,this.paths.manifestPath);if($.hadRuntime)await m1($.backupRuntimeDir,this.paths.runtimeDir)}async restoreBackupPairBestEffort($){await this.restoreSingleBackup({hadTarget:$.hadManifest,backupPath:$.backupManifestPath,targetPath:this.paths.manifestPath,directory:!1}),await this.restoreSingleBackup({hadTarget:$.hadRuntime,backupPath:$.backupRuntimeDir,targetPath:this.paths.runtimeDir,directory:!0})}async restoreSingleBackup($){if(await E4($.backupPath)){await G0($.targetPath,{recursive:$.directory,force:!0}),await m1($.backupPath,$.targetPath);return}if(!$.hadTarget)await G0($.targetPath,{recursive:$.directory,force:!0})}fault($){try{this.options.fault?.($)}catch(w){throw new hG(w)}}now(){return this.options.now?.()??Date.now()}isProcessAlive($){if(this.options.isProcessAlive)return this.options.isProcessAlive($);try{return process.kill($,0),!0}catch(w){return!uG(w,"ESRCH")}}}function dU($){return $.version===1&&typeof $.id==="string"&&["prepared","backed-up","runtime-committed","manifest-committed"].includes(String($.phase))&&typeof $.stageDirectory==="string"&&typeof $.backupManifestPath==="string"&&typeof $.backupRuntimeDir==="string"&&typeof $.hadManifest==="boolean"&&typeof $.hadRuntime==="boolean"}async function E4($){try{return await cU($,lU.F_OK),!0}catch{return!1}}function uG($,w){return typeof $==="object"&&$!==null&&"code"in $&&$.code===w}class lG{workspace;dataDir;packageManager;loader;builtins;constructor($,w,G,W,Y){this.workspace=$;this.dataDir=w;this.packageManager=G;this.loader=W;this.builtins=Y}async install($,w){let G=vJ($),W=this.paths(w.scope);await new C0(W).recover();let Y=await E1(W.manifestPath);if(Y.plugins[G.packageName]?.requested===G.requested){let T=await this.loader.loadScope(W),M=T.loaded.find((f)=>f.packageName===G.packageName);if(T.failed.length===0&&M)return iG(M,G.requested,w.scope)}let Z=sJ(Y);Z.plugins[G.packageName]={source:"npm",requested:G.requested};let X=[];await new C0(W).run(async(T)=>{X=await this.buildCandidate(T,Z,W,w,!1),await this.validateCandidate(W.scope,X)});let J=X.find((T)=>T.packageName===G.packageName);if(!J)throw mG([{packageName:G.packageName,path:W.runtimeDir,message:"plugin did not load"}]);return iG(J,G.requested,w.scope)}async remove($,w){if(!N$($))throw oU($);let G=this.paths(w.scope);await new C0(G).recover();let W=await E1(G.manifestPath);if(!W.plugins[$])throw new y("plugin","plugin.install_failed",`plugin.install_failed: ${$} is not installed in ${w.scope} scope`);let Y=sJ(W);delete Y.plugins[$],await new C0(G).run(async(Z)=>{let X=await this.buildCandidate(Z,Y,G,w,!1);await this.validateCandidate(G.scope,X)})}async sync($){let w=this.paths($.scope);await new C0(w).recover();let G=await E1(w.manifestPath);if($.scope==="project"&&Object.keys(G.plugins).length>0&&!await aJ(c1.join(w.runtimeDir,"bun.lock")))throw new y("plugin","plugin.lock_missing",`plugin.lock_missing: ${$.scope} plugin sync requires ${c1.join(w.runtimeDir,"bun.lock")}`);let W=[];return await new C0(w).run(async(Y)=>{W=await this.buildCandidate(Y,G,w,$,!0),await this.validateCandidate(w.scope,W)}),W.map((Y)=>iG(Y,G.plugins[Y.packageName]?.requested??"latest",$.scope))}async list(){let[$,w]=await Promise.all([this.listScope(this.paths("project")),this.listScope(this.paths("global"))]),G=new Set($.map((W)=>W.packageName));return{project:$,global:w.map((W)=>({...W,shadowedByProject:G.has(W.packageName)}))}}paths($){return q4(this.workspace,$,this.dataDir)}async buildCandidate($,w,G,W,Y){if(await rU($.runtimeDir,{recursive:!0}),await s8($.manifestPath,yG(w),"utf8"),await s8(c1.join($.runtimeDir,"package.json"),`${JSON.stringify(uJ(w),null,2)}
47
- `,"utf8"),await aJ(c1.join(G.runtimeDir,"bun.lock")))await tU(c1.join(G.runtimeDir,"bun.lock"),c1.join($.runtimeDir,"bun.lock"));try{await this.packageManager.install({cwd:$.runtimeDir,frozenLockfile:Y,allowScripts:W.allowScripts,...W.signal?{signal:W.signal}:{}})}catch(X){throw eU(X,Y)}await sU($.runtimeDir,w),await aU($.runtimeDir,G.scope);let Z=await this.loader.loadScope({...G,manifestPath:$.manifestPath,runtimeDir:$.runtimeDir});if(Z.failed.length>0)throw mG(Z.failed);return Z.loaded}async validateCandidate($,w){if($==="global"){gG(this.builtins,w,[]);return}let G=this.paths("global");await new C0(G).recover();let W=await this.loadScopeOrThrow(G);gG(this.builtins,W,w)}async loadScopeOrThrow($){let w=await this.loader.loadScope($);if(w.failed.length>0)throw mG(w.failed);return w.loaded}async listScope($){await new C0($).recover();let w=await E1($.manifestPath),G=[];for(let W of Object.keys(w.plugins).sort()){let Y=await Ww($.runtimeDir,W);G.push({packageName:W,requested:w.plugins[W]?.requested??"latest",version:Y.version,tools:[],scope:$.scope,shadowedByProject:!1})}return G}}async function sU($,w){if(Object.keys(w.plugins).length>0)return;await s8(c1.join($,"bun.lock"),"","utf8")}async function aU($,w){if(w!=="project")return;await s8(c1.join($,".gitignore"),`*
181
+ `),4000)}class _3{runner;constructor($=L6){this.runner=$}async install($){let w=["install","--registry","https://registry.npmjs.org"];if($.frozenLockfile)w.push("--frozen-lockfile");if(!$.allowScripts)w.push("--ignore-scripts");let G=await this.runner("bun",w,{cwd:$.cwd,env:process.env,...$.signal?{signal:$.signal}:{},timeoutMs:120000,maxOutputChars:30000});if(!G.ok)throw new y("plugin","plugin.install_failed",tK(G))}}import UA from"node:path";import{pathToFileURL as HA}from"node:url";var GM=A1($M(),1);var yZ=new GM.default({allErrors:!0,strict:!1,useDefaults:!0});class q${#$=new Map;constructor($=[]){for(let w of $)this.register(w,{kind:"builtin"})}register($,w={kind:"local"}){if(!/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/.test($.name))throw new y("plugin","tool.invalid_name",`Invalid tool name: ${$.name}`);let G=this.#$.get($.name);if(G)throw new y("plugin","tool.duplicate",`Duplicate tool: ${$.name} from ${wM(G.source)} and ${wM(w)}`);try{yZ.compile($.inputSchema)}catch(Z){throw new y("plugin","tool.invalid_schema",`Invalid schema for ${$.name}`,!1,void 0,{cause:Z})}this.#$.set($.name,{definition:$,source:w})}get($){return this.#$.get($)?.definition}list(){return[...this.#$.values()].map(($)=>$.definition)}source($){return this.#$.get($)?.source}entries(){return[...this.#$.values()].map(($)=>({definition:$.definition,source:$.source}))}clone(){let $=new q$;return $.#$=new Map(this.#$),$}replaceWith($){this.#$=new Map($.#$)}validate($,w){let G=this.get($);if(!G)return{valid:!1,errors:`Unknown tool: ${$}`};let Z=yZ.compile(G.inputSchema);return Z(w)?{valid:!0}:{valid:!1,errors:yZ.errorsText(Z.errors)}}}function wM($){switch($.kind){case"builtin":return"builtin";case"local":return $.path?`local:${$.path}`:"local";case"npm":return $.path?`${$.pluginName}@${$.pluginVersion}:${$.path}`:`${$.pluginName}@${$.pluginVersion}`}}var _Z=1;function W5($,w){if(ZM($))return[$];if(!$||typeof $!=="object")throw new y("plugin","plugin.export_invalid","plugin.export_invalid: default export must be a tool or CodeNPlugin");let G=$;if(G.apiVersion!==_Z)throw new y("plugin","plugin.api_unsupported",`plugin.api_unsupported: ${String(G.apiVersion)}`);if(G.name!==w)throw new y("plugin","plugin.name_mismatch",`plugin.name_mismatch: expected ${w}, received ${String(G.name)}`);if(!Array.isArray(G.tools)||G.tools.length===0)throw new y("plugin","plugin.export_invalid","plugin.export_invalid: tools must be a non-empty array");if(!G.tools.every(ZM))throw new y("plugin","plugin.export_invalid","plugin.export_invalid: every tool must match ToolDefinition");return G.tools}function ZM($){if(!$||typeof $!=="object")return!1;let w=$;return typeof w.name==="string"&&typeof w.description==="string"&&(w.risk==="read"||w.risk==="modify"||w.risk==="dangerous")&&!!w.inputSchema&&typeof w.execute==="function"}import{readFile as QA}from"node:fs/promises";var WA=/^(?:@[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*|[a-z0-9][a-z0-9._-]*)$/;function _1($){return WA.test($)&&!$.includes("..")&&!$.includes("\\")}function XM($){if(typeof $!=="string"||!$.startsWith("npm:"))throw Y9($);let w=$.slice(4);if(!w||/\s/.test(w)||w.includes("\\")||w.includes("://"))throw Y9($);let{packageName:G,requested:Z}=TA(w);if(!_1(G))throw Y9($);if(!Z||/\s/.test(Z)||Z.includes("\\")||Z.includes("/")||Z.includes(":")||Z.includes(".."))throw Y9($);return{source:"npm",packageName:G,requested:Z,raw:$}}function TA($){if($.startsWith("@")){let G=$.indexOf("/");if(G<2)throw Y9($);let Z=$.lastIndexOf("@");if(Z<=G)return{packageName:$,requested:"latest"};return{packageName:$.slice(0,Z),requested:$.slice(Z+1)}}let w=$.lastIndexOf("@");if(w===-1)return{packageName:$,requested:"latest"};return{packageName:$.slice(0,w),requested:$.slice(w+1)}}function Y9($){return new y("plugin","plugin.specifier_invalid",`plugin.specifier_invalid: ${String($)}`)}var zA=()=>({schemaVersion:1,plugins:{}});async function j$($){try{let w=JSON.parse(await QA($,"utf8"));return gZ(w)}catch(w){if(MA(w))return zA();if(w instanceof y)throw w;throw x1(w,$)}}function xZ($){return`${JSON.stringify(gZ($),null,2)}
182
+ `}function YM($){let w=gZ($),G={};for(let[Z,X]of Object.entries(w.plugins))G[Z]=X.requested;return{private:!0,dependencies:G}}function gZ($){if(!$||typeof $!=="object")throw x1();let w=$;if(w.schemaVersion!==1)throw x1();if(!w.plugins||typeof w.plugins!=="object"||Array.isArray(w.plugins))throw x1();let G={};for(let Z of Object.keys(w.plugins).sort()){if(!_1(Z))throw x1();let X=w.plugins[Z];if(!X||typeof X!=="object"||Array.isArray(X))throw x1();let Y=X;if(Y.source!=="npm"||typeof Y.requested!=="string"||!Y.requested)throw x1();G[Z]={source:"npm",requested:Y.requested}}return{schemaVersion:1,plugins:G}}function MA($){return typeof $==="object"&&$!==null&&"code"in $&&$.code==="ENOENT"}function x1($,w){return new y("plugin","plugin.manifest_invalid",w?`plugin.manifest_invalid: ${w}`:"plugin.manifest_invalid",!1,void 0,$ instanceof Error?{cause:$}:void 0)}import{readFile as PA,realpath as qA}from"node:fs/promises";import T5 from"node:path";async function gw($,w){if(!_1(w))throw g1();let G=T5.join($,"node_modules",...w.split("/")),Z=T5.join(G,"package.json"),X;try{X=JSON.parse(await PA(Z,"utf8"))}catch{throw g1()}let Y=BA(X,w),J=await JM(G),W=T5.resolve(G,Y.entry),T=await JM(W,!0);if(!NA(J,T))throw uZ();return{packageName:w,version:Y.version,packageDirectory:J,entryPath:T,apiVersion:1}}function BA($,w){if(!$||typeof $!=="object")throw g1();let G=$;if(G.name!==w||typeof G.version!=="string"||!G.version)throw g1();if(G.type!=="module")throw g1();if(!G.coden||typeof G.coden!=="object"||Array.isArray(G.coden))throw g1();let Z=G.coden;if(Z.apiVersion!==1)throw KA(Z.apiVersion);if(typeof Z.plugin!=="string"||!VA(Z.plugin))throw uZ();return{version:G.version,entry:Z.plugin}}async function JM($,w=!1){try{return await qA($)}catch{if(w)throw uZ();throw g1()}}function NA($,w){return w===$||w.startsWith(`${$}${T5.sep}`)}function VA($){if(!$.startsWith("./"))return!1;if($.includes("\\")||$.includes("://")||/\s/.test($))return!1;if(!($.endsWith(".js")||$.endsWith(".mjs")))return!1;if($.split("/").includes(".."))return!1;return!0}function g1(){return new y("plugin","plugin.metadata_missing","plugin.metadata_missing")}function KA($){return new y("plugin","plugin.api_unsupported",`plugin.api_unsupported: ${String($)}`)}function uZ(){return new y("plugin","plugin.entry_invalid","plugin.entry_invalid")}class hZ{importer;constructor($=(w)=>import(w)){this.importer=$}async loadScope($){let w=await j$($.manifestPath),G=[],Z=[];for(let X of Object.keys(w.plugins).sort()){let Y=FA($.runtimeDir,X);try{let J=await gw($.runtimeDir,X);try{let W=await this.importer(HA(J.entryPath).href),T=W5(W.default,X);G.push({packageName:X,version:J.version,entryPath:J.entryPath,tools:T})}catch(W){Z.push({packageName:X,path:J.entryPath,message:WM(W)})}}catch(J){Z.push({packageName:X,path:Y,message:WM(J)})}}return{loaded:G,failed:Z}}}function FA($,w){return UA.join($,"node_modules",...w.split("/"))}function WM($){return $ instanceof Error?$.message:String($)}import{constants as CA}from"node:fs";import{access as bA,copyFile as kA,mkdir as yA,writeFile as M5}from"node:fs/promises";import G1 from"node:path";import OA from"node:path";import{pathToFileURL as fA}from"node:url";class vZ{importer;constructor($=(w)=>import(w)){this.importer=$}async loadScope($){let w=await j$($.manifestPath),G=[],Z=[];for(let X of Object.keys(w.plugins).sort()){let Y=DA($.runtimeDir,X);try{let J=await gw($.runtimeDir,X);try{let W=await this.importer(fA(J.entryPath).href),T=W5(W.default,X);G.push({packageName:X,version:J.version,entryPath:J.entryPath,tools:T})}catch(W){Z.push({packageName:X,path:J.entryPath,message:QM(W)})}}catch(J){Z.push({packageName:X,path:Y,message:QM(J)})}}return{loaded:G,failed:Z}}}function iZ($,w,G){let Z=new q$($),X=new Map(G.map((T)=>[T.packageName,T])),Y=[],J=[];for(let T of w){let Q=X.get(T.packageName);if(Q){Y.push({packageName:T.packageName,globalVersion:T.version,projectVersion:Q.version});continue}J.push(T)}let W=[...J,...G];for(let T of W)LA(Z,T);return{registry:Z,effective:W,shadowed:Y}}function LA($,w){let G={kind:"npm",pluginName:w.packageName,pluginVersion:w.version,path:w.entryPath};for(let Z of w.tools){let X=$.source(Z.name);if(X)throw new y("plugin","plugin.tool_conflict",`plugin.tool_conflict: ${Z.name} from ${TM(X)} conflicts with ${TM(G)}`);$.register(Z,G)}}function DA($,w){return OA.join($,"node_modules",...w.split("/"))}function TM($){switch($.kind){case"builtin":return"builtin";case"local":return $.path?`local:${$.path}`:"local";case"npm":return $.path?`${$.pluginName}@${$.pluginVersion}:${$.path}`:`${$.pluginName}@${$.pluginVersion}`}}function QM($){return $ instanceof Error?$.message:String($)}import B$ from"node:path";import{readFile as EA}from"node:fs/promises";import PM from"node:os";import uw from"node:path";function Q5(){return process.env.XDG_CONFIG_HOME?uw.join(process.env.XDG_CONFIG_HOME,"coden"):uw.join(PM.homedir(),".config","coden")}function mZ(){return process.env.XDG_DATA_HOME?uw.join(process.env.XDG_DATA_HOME,"coden"):uw.join(PM.homedir(),".local","share","coden")}async function zM($){try{let w=JSON.parse(await EA($,"utf8"));return AA(w)}catch(w){if(w.code==="ENOENT")return{};throw Error(`Cannot read config ${$}: ${w instanceof Error?w.message:String(w)}`)}}function AA($){let w={};if($.provider==="openai"||$.provider==="anthropic")w.provider=$.provider;if(typeof $.model==="string")w.model=$.model;if(typeof $.maxSteps==="number")w.maxSteps=$.maxSteps;if(typeof $.contextWindow==="number")w.contextWindow=$.contextWindow;if(typeof $.reservedOutputTokens==="number")w.reservedOutputTokens=$.reservedOutputTokens;if(typeof $.safetyMargin==="number")w.safetyMargin=$.safetyMargin;if(Array.isArray($.plugins))w.plugins=$.plugins.filter((G)=>typeof G==="string");if($.env!==void 0){if(typeof $.env!=="object"||$.env===null||Array.isArray($.env))throw Error("env must be an object");let G={};for(let[Z,X]of Object.entries($.env)){if(typeof X!=="string")throw Error(`env "${Z}" must be a string`);G[Z]=X}w.env=G}return w}function MM($){let{env:w,...G}=$;return G}async function qM($,w={}){let G={provider:"openai",model:"gpt-5-mini",maxSteps:20,contextWindow:128000,reservedOutputTokens:8192,safetyMargin:4096,plugins:[],dataDir:mZ(),env:{}},Z=await zM(uw.join(Q5(),"config.json")),X=await zM(uw.join($,".coden","config.json")),Y={};if(process.env.CODEN_PROVIDER==="openai"||process.env.CODEN_PROVIDER==="anthropic")Y.provider=process.env.CODEN_PROVIDER;if(process.env.CODEN_MODEL)Y.model=process.env.CODEN_MODEL;if(process.env.CODEN_MAX_STEPS)Y.maxSteps=Number(process.env.CODEN_MAX_STEPS);let J={...Z.env??{},...X.env??{}};for(let[T,Q]of Object.entries(J))if(process.env[T]===void 0)process.env[T]=Q;let W={...G,...MM(Z),...MM(X),...Y,...w,env:J};if(W.plugins=[...Z.plugins??[],...X.plugins??[],...w.plugins??[]],W.provider!=="openai"&&W.provider!=="anthropic")throw Error("provider must be openai or anthropic");if(typeof W.model!=="string"||!W.model.trim())throw Error("model must be a non-empty string");if(!Number.isInteger(W.maxSteps)||W.maxSteps<1)throw Error("maxSteps must be a positive integer");for(let T of["contextWindow","reservedOutputTokens","safetyMargin"])if(!Number.isInteger(W[T])||W[T]<0)throw Error(`${T} must be a non-negative integer`);if(W.contextWindow===0||W.reservedOutputTokens===0)throw Error("contextWindow and reservedOutputTokens must be positive");if(W.contextWindow<=W.reservedOutputTokens+W.safetyMargin)throw Error("contextWindow must exceed reservedOutputTokens plus safetyMargin");if(!Array.isArray(W.plugins)||W.plugins.some((T)=>typeof T!=="string"))throw Error("plugins must be an array of paths");return W}function J9($,w,G=mZ()){if(w==="project"){let Y=B$.join($,".coden"),J=B$.join(Y,"plugin-runtime");return{scope:w,root:Y,manifestPath:B$.join(Y,"plugins.json"),runtimeDir:J,lockPath:B$.join(Y,"plugin-lock"),transactionPath:B$.join(Y,"plugin-transaction.json")}}let Z=B$.join(G,"plugins"),X=B$.join(Z,"runtime");return{scope:w,root:Z,manifestPath:B$.join(Z,"plugins.json"),runtimeDir:X,lockPath:B$.join(Z,"plugin-lock"),transactionPath:B$.join(Z,"plugin-transaction.json")}}import{randomUUID as RA}from"node:crypto";import{constants as SA}from"node:fs";import{access as IA,mkdir as z5,readFile as BM,rename as $1,rm as Y0,writeFile as NM}from"node:fs/promises";import w1 from"node:path";class dZ extends Error{constructor($){super($ instanceof Error?$.message:String($),$ instanceof Error?{cause:$}:void 0);this.name="FaultInterruption"}}class _0{paths;options;constructor($,w={}){this.paths=$;this.options=w}async run($){let w=!1,G;try{await this.acquireLock(),w=!0,await this.recoverLocked();let Z=RA(),X=w1.join(this.paths.root,`.transaction-${Z}-stage`);G={version:1,id:Z,phase:"prepared",stageDirectory:X,backupManifestPath:w1.join(this.paths.root,`.transaction-${Z}-plugins.json.bak`),backupRuntimeDir:w1.join(this.paths.root,`.transaction-${Z}-runtime.bak`),hadManifest:await W9(this.paths.manifestPath),hadRuntime:await W9(this.paths.runtimeDir)},await z5(X,{recursive:!0});let Y={manifestPath:w1.join(X,"plugins.json"),runtimeDir:w1.join(X,"runtime")},J=await $(Y);await this.verifyCandidate(Y),await this.writeMarker(G),await this.backupCurrent(G);let W={...G,phase:"backed-up"};await this.writeMarker(W),G=W,this.fault("after-backup"),await $1(Y.runtimeDir,this.paths.runtimeDir);let T={...G,phase:"runtime-committed"};await this.writeMarker(T),G=T,this.fault("after-runtime-commit"),await $1(Y.manifestPath,this.paths.manifestPath);let Q={...G,phase:"manifest-committed"};return await this.writeMarker(Q),G=Q,this.fault("after-manifest-commit"),await this.cleanupCommitted(G),J}catch(Z){if(Z instanceof dZ)throw Z.cause??Z;throw await this.rollbackAfterError(G),Z}finally{if(w)await this.releaseLock()}}async recover(){let $=!1;try{await this.acquireLock(),$=!0,await this.recoverLocked()}finally{if($)await this.releaseLock()}}async acquireLock(){await z5(this.paths.root,{recursive:!0});for(let $=0;$<2;$++){try{await z5(this.paths.lockPath)}catch(w){if(!lZ(w,"EEXIST"))throw w;let G=await this.readLockOwner();if(!G||this.isProcessAlive(G.pid))throw new y("plugin","plugin.install_busy",`plugin.install_busy: ${this.paths.scope} plugin installation is already running`,!0,{scope:this.paths.scope});if($===1)throw new y("plugin","plugin.install_busy",`plugin.install_busy: could not acquire ${this.paths.scope} plugin lock`,!0,{scope:this.paths.scope});await Y0(this.paths.lockPath,{recursive:!0,force:!0});continue}try{await NM(w1.join(this.paths.lockPath,"owner.json"),`${JSON.stringify({pid:process.pid,createdAt:this.now()})}
183
+ `,{mode:384});return}catch(w){throw await Y0(this.paths.lockPath,{recursive:!0,force:!0}),w}}}async readLockOwner(){try{let $=JSON.parse(await BM(w1.join(this.paths.lockPath,"owner.json"),"utf8"));if(typeof $.pid==="number"&&Number.isInteger($.pid)&&$.pid>0)return{pid:$.pid,createdAt:typeof $.createdAt==="number"?$.createdAt:0};return}catch{return}}async releaseLock(){await Y0(this.paths.lockPath,{recursive:!0,force:!0})}async verifyCandidate($){if(!await W9($.manifestPath)||!await W9($.runtimeDir))throw new y("plugin","plugin.transaction_recovery_failed","plugin.transaction_recovery_failed: candidate manifest and runtime are required",!1,{scope:this.paths.scope})}async backupCurrent($){if(await Y0($.backupManifestPath,{force:!0}),await Y0($.backupRuntimeDir,{recursive:!0,force:!0}),$.hadManifest)await $1(this.paths.manifestPath,$.backupManifestPath);if($.hadRuntime)await $1(this.paths.runtimeDir,$.backupRuntimeDir)}async rollbackAfterError($){if(!$)return;try{if($.phase==="manifest-committed"){await this.cleanupCommitted($);return}await this.restoreBackupPairBestEffort($),await this.cleanupRecoveryArtifacts($)}catch(w){throw new y("plugin","plugin.transaction_recovery_failed",`plugin.transaction_recovery_failed: could not roll back ${this.paths.scope} plugin transaction`,!1,{scope:this.paths.scope},w instanceof Error?{cause:w}:void 0)}}async recoverLocked(){let $=await this.readMarker();if(!$)return;try{if($.phase==="prepared"){await Y0($.stageDirectory,{recursive:!0,force:!0}),await Y0(this.paths.transactionPath,{force:!0});return}if($.phase==="backed-up"||$.phase==="runtime-committed"){await this.removeCurrentTargets(),await this.restoreBackups($),await this.cleanupRecoveryArtifacts($);return}await Y0($.backupManifestPath,{force:!0}),await Y0($.backupRuntimeDir,{recursive:!0,force:!0}),await this.cleanupRecoveryArtifacts($)}catch(w){throw new y("plugin","plugin.transaction_recovery_failed",`plugin.transaction_recovery_failed: could not recover ${this.paths.scope} plugin transaction`,!1,{scope:this.paths.scope},w instanceof Error?{cause:w}:void 0)}}async readMarker(){try{let $=JSON.parse(await BM(this.paths.transactionPath,"utf8"));if(!jA($))throw Error("invalid transaction marker");return $}catch($){if(lZ($,"ENOENT"))return;throw new y("plugin","plugin.transaction_recovery_failed",`plugin.transaction_recovery_failed: invalid ${this.paths.scope} plugin transaction marker`,!1,{scope:this.paths.scope},$ instanceof Error?{cause:$}:void 0)}}async writeMarker($){await z5(w1.dirname(this.paths.transactionPath),{recursive:!0});let w=`${this.paths.transactionPath}.tmp`;await NM(w,`${JSON.stringify($,null,2)}
184
+ `,{mode:384}),await $1(w,this.paths.transactionPath)}async cleanupCommitted($){await Y0($.backupManifestPath,{force:!0}),await Y0($.backupRuntimeDir,{recursive:!0,force:!0}),await Y0($.stageDirectory,{recursive:!0,force:!0}),await Y0(this.paths.transactionPath,{force:!0}),await Y0(`${this.paths.transactionPath}.tmp`,{recursive:!0,force:!0})}async cleanupRecoveryArtifacts($){await Y0($.stageDirectory,{recursive:!0,force:!0}),await Y0(this.paths.transactionPath,{force:!0}),await Y0(`${this.paths.transactionPath}.tmp`,{recursive:!0,force:!0})}async removeCurrentTargets(){await Y0(this.paths.manifestPath,{force:!0}),await Y0(this.paths.runtimeDir,{recursive:!0,force:!0})}async restoreBackups($){if($.hadManifest)await $1($.backupManifestPath,this.paths.manifestPath);if($.hadRuntime)await $1($.backupRuntimeDir,this.paths.runtimeDir)}async restoreBackupPairBestEffort($){await this.restoreSingleBackup({hadTarget:$.hadManifest,backupPath:$.backupManifestPath,targetPath:this.paths.manifestPath,directory:!1}),await this.restoreSingleBackup({hadTarget:$.hadRuntime,backupPath:$.backupRuntimeDir,targetPath:this.paths.runtimeDir,directory:!0})}async restoreSingleBackup($){if(await W9($.backupPath)){await Y0($.targetPath,{recursive:$.directory,force:!0}),await $1($.backupPath,$.targetPath);return}if(!$.hadTarget)await Y0($.targetPath,{recursive:$.directory,force:!0})}fault($){try{this.options.fault?.($)}catch(w){throw new dZ(w)}}now(){return this.options.now?.()??Date.now()}isProcessAlive($){if(this.options.isProcessAlive)return this.options.isProcessAlive($);try{return process.kill($,0),!0}catch(w){return!lZ(w,"ESRCH")}}}function jA($){return $.version===1&&typeof $.id==="string"&&["prepared","backed-up","runtime-committed","manifest-committed"].includes(String($.phase))&&typeof $.stageDirectory==="string"&&typeof $.backupManifestPath==="string"&&typeof $.backupRuntimeDir==="string"&&typeof $.hadManifest==="boolean"&&typeof $.hadRuntime==="boolean"}async function W9($){try{return await IA($,SA.F_OK),!0}catch{return!1}}function lZ($,w){return typeof $==="object"&&$!==null&&"code"in $&&$.code===w}class nZ{workspace;dataDir;packageManager;loader;builtins;constructor($,w,G,Z,X){this.workspace=$;this.dataDir=w;this.packageManager=G;this.loader=Z;this.builtins=X}async install($,w){let G=XM($),Z=this.paths(w.scope);await new _0(Z).recover();let X=await j$(Z.manifestPath);if(X.plugins[G.packageName]?.requested===G.requested){let T=await this.loader.loadScope(Z),Q=T.loaded.find((z)=>z.packageName===G.packageName);if(T.failed.length===0&&Q)return cZ(Q,G.requested,w.scope)}let Y=VM(X);Y.plugins[G.packageName]={source:"npm",requested:G.requested};let J=[];await new _0(Z).run(async(T)=>{J=await this.buildCandidate(T,Y,Z,w,!1),await this.validateCandidate(Z.scope,J)});let W=J.find((T)=>T.packageName===G.packageName);if(!W)throw pZ([{packageName:G.packageName,path:Z.runtimeDir,message:"plugin did not load"}]);return cZ(W,G.requested,w.scope)}async remove($,w){if(!_1($))throw gA($);let G=this.paths(w.scope);await new _0(G).recover();let Z=await j$(G.manifestPath);if(!Z.plugins[$])throw new y("plugin","plugin.install_failed",`plugin.install_failed: ${$} is not installed in ${w.scope} scope`);let X=VM(Z);delete X.plugins[$],await new _0(G).run(async(Y)=>{let J=await this.buildCandidate(Y,X,G,w,!1);await this.validateCandidate(G.scope,J)})}async sync($){let w=this.paths($.scope);await new _0(w).recover();let G=await j$(w.manifestPath);if($.scope==="project"&&Object.keys(G.plugins).length>0&&!await KM(G1.join(w.runtimeDir,"bun.lock")))throw new y("plugin","plugin.lock_missing",`plugin.lock_missing: ${$.scope} plugin sync requires ${G1.join(w.runtimeDir,"bun.lock")}`);let Z=[];return await new _0(w).run(async(X)=>{Z=await this.buildCandidate(X,G,w,$,!0),await this.validateCandidate(w.scope,Z)}),Z.map((X)=>cZ(X,G.plugins[X.packageName]?.requested??"latest",$.scope))}async list(){let[$,w]=await Promise.all([this.listScope(this.paths("project")),this.listScope(this.paths("global"))]),G=new Set($.map((Z)=>Z.packageName));return{project:$,global:w.map((Z)=>({...Z,shadowedByProject:G.has(Z.packageName)}))}}paths($){return J9(this.workspace,$,this.dataDir)}async buildCandidate($,w,G,Z,X){if(await yA($.runtimeDir,{recursive:!0}),await M5($.manifestPath,xZ(w),"utf8"),await M5(G1.join($.runtimeDir,"package.json"),`${JSON.stringify(YM(w),null,2)}
185
+ `,"utf8"),await KM(G1.join(G.runtimeDir,"bun.lock")))await kA(G1.join(G.runtimeDir,"bun.lock"),G1.join($.runtimeDir,"bun.lock"));try{await this.packageManager.install({cwd:$.runtimeDir,frozenLockfile:X,allowScripts:Z.allowScripts,...Z.signal?{signal:Z.signal}:{}})}catch(J){throw uA(J,X)}await _A($.runtimeDir,w),await xA($.runtimeDir,G.scope);let Y=await this.loader.loadScope({...G,manifestPath:$.manifestPath,runtimeDir:$.runtimeDir});if(Y.failed.length>0)throw pZ(Y.failed);return Y.loaded}async validateCandidate($,w){if($==="global"){iZ(this.builtins,w,[]);return}let G=this.paths("global");await new _0(G).recover();let Z=await this.loadScopeOrThrow(G);iZ(this.builtins,Z,w)}async loadScopeOrThrow($){let w=await this.loader.loadScope($);if(w.failed.length>0)throw pZ(w.failed);return w.loaded}async listScope($){await new _0($).recover();let w=await j$($.manifestPath),G=[];for(let Z of Object.keys(w.plugins).sort()){let X=await gw($.runtimeDir,Z);G.push({packageName:Z,requested:w.plugins[Z]?.requested??"latest",version:X.version,tools:[],scope:$.scope,shadowedByProject:!1})}return G}}async function _A($,w){if(Object.keys(w.plugins).length>0)return;await M5(G1.join($,"bun.lock"),"","utf8")}async function xA($,w){if(w!=="project")return;await M5(G1.join($,".gitignore"),`*
48
186
  !.gitignore
49
187
  !bun.lock
50
- `,"utf8")}function iG($,w,G){return{packageName:$.packageName,requested:w,version:$.version,tools:$.tools.map((W)=>W.name).sort(),scope:G}}function sJ($){return JSON.parse(yG($))}function mG($){let w=$.map((G)=>`${G.packageName}: ${G.message} (${G.path})`).join("; ");return new y("plugin","plugin.sync_failed",`plugin.sync_failed: ${w}`)}function oU($){return new y("plugin","plugin.specifier_invalid",`plugin.specifier_invalid: ${$}`)}function eU($,w){if(w&&$H($))return new y("plugin","plugin.lock_outdated","plugin.lock_outdated: committed plugin lockfile is out of date",!1,void 0,$ instanceof Error?{cause:$}:void 0);return $}function $H($){if(!($ instanceof Error))return!1;let w=`${$.message}
51
- ${$ instanceof y?$.code:""}`;return/frozen-lockfile|lockfile.*out.?of.?date|lockfile.*would.*change|lockfile had changes/i.test(w)}async function aJ($){try{return await pU($,nU.F_OK),!0}catch{return!1}}var a8={name:"bash",description:"Run a bash command in the workspace with timeout and bounded output.",risk:"modify",inputSchema:{type:"object",additionalProperties:!1,required:["command"],properties:{command:{type:"string",minLength:1},timeout:{type:"integer",minimum:100,maximum:60000,default:30000},maxOutput:{type:"integer",minimum:1000,maximum:1e5,default:30000}}},async execute($,w){let{command:G,timeout:W=30000,maxOutput:Y=30000}=$,Z=await T8("bash",["-lc",G],{cwd:w.workspace,env:process.env,signal:w.signal,timeoutMs:W,maxOutputChars:Y}),X=[Z.stdout&&`stdout:
52
- ${Z.stdout}`,Z.stderr&&`stderr:
53
- ${Z.stderr}`].filter(Boolean).join(`
54
- `);if(Z.exitCode===null&&!Z.timedOut&&!Z.cancelled&&Z.signal===null)return{content:`bash.spawn_error: ${Z.stderr||"unknown error"}`,isError:!0};let J=Z.timedOut?`Timed out after ${W}ms`:Z.cancelled?"Cancelled":`Exit code: ${Z.exitCode??"null"}${Z.signal?` (signal ${Z.signal})`:""}`;return{content:d$(`${J}
55
- ${X}`.trimEnd(),Y),isError:Z.timedOut||Z.cancelled||Z.exitCode!==0,metadata:{exitCode:Z.exitCode,signal:Z.signal,timedOut:Z.timedOut,cancelled:Z.cancelled}}}};import{constants as WT}from"node:fs";import{open as YH}from"node:fs/promises";import{constants as oJ}from"node:fs";import{lstat as eJ,open as wH,readlink as $T,realpath as o8}from"node:fs/promises";import j0 from"node:path";function e8($,w){let G=j0.relative(w,$);return G===""||!G.startsWith("..")&&!j0.isAbsolute(G)}async function wT($,w,G=1e6){let W=await J1($,w),Y=await wH(W,oJ.O_RDONLY|oJ.O_NOFOLLOW);try{if((await Y.stat()).size>G)throw new y("context","workspace.instructions_too_large",`${w} exceeds the ${G}-byte instruction limit`);return await Y.readFile("utf8")}finally{await Y.close()}}async function J1($,w){let G=await o8($),W=j0.resolve(G,w);if(!e8(W,G))throw new y("permission","workspace.outside",`Path is outside workspace: ${w}`);try{let Y=await o8(W);if(!e8(Y,G))throw new y("permission","workspace.symlink_escape",`Path escapes workspace through a symlink: ${w}`);return Y}catch(Y){if(Y instanceof y)throw Y;try{if((await eJ(W)).isSymbolicLink()){let X=j0.resolve(j0.dirname(W),await $T(W));await GT(X,G,w,"dangling symlink")}}catch(Z){if(Z instanceof y)throw Z}return await GH(W,G,w),W}}async function GT($,w,G,W){let Y=await WH($);if(!Y||!e8(Y,w))throw new y("permission","workspace.symlink_escape",`Path escapes workspace through a ${W}: ${G}`)}async function GH($,w,G){let W=j0.dirname($);while(W!==j0.dirname(W)){let Y;try{Y=await eJ(W)}catch{W=j0.dirname(W);continue}if(!Y){W=j0.dirname(W);continue}if(Y.isSymbolicLink()){let Z=j0.resolve(j0.dirname(W),await $T(W));await GT(Z,w,G,"symlink")}else{let Z;try{Z=await o8(W)}catch{W=j0.dirname(W);continue}if(!Z)continue;if(e8(Z,w))return;throw new y("permission","workspace.symlink_escape",`Parent escapes workspace: ${G}`)}W=j0.dirname(W)}}async function WH($){let w=$;while(!0)try{return await o8(w)}catch{let G=j0.dirname(w);if(G===w)return;w=G}}var $6={name:"edit",description:"Replace one uniquely matching exact text block in a UTF-8 file.",risk:"modify",inputSchema:{type:"object",additionalProperties:!1,required:["path","oldText","newText"],properties:{path:{type:"string"},oldText:{type:"string",minLength:1},newText:{type:"string"}}},async execute($,w){let{path:G,oldText:W,newText:Y}=$,Z=await J1(w.workspace,G),X=await YH(Z,WT.O_RDWR|WT.O_NOFOLLOW);try{let J=await X.readFile("utf8"),T=J.indexOf(W);if(T<0)return{content:"edit.no_match: oldText was not found",isError:!0};if(J.indexOf(W,T+1)>=0)return{content:"edit.multiple_matches: oldText is not unique",isError:!0};let M=`${J.slice(0,T)}${Y}${J.slice(T+W.length)}`;await X.truncate(0),await X.write(M,0,"utf8")}finally{await X.close()}return{content:`Edited ${G}`}}};import{constants as YT}from"node:fs";import{open as ZH}from"node:fs/promises";class ZT{limit;text="";omitted=0;constructor($){this.limit=$}add($){let w=Math.max(0,this.limit-this.text.length);this.text+=$.slice(0,w),this.omitted+=Math.max(0,$.length-w)}value(){return this.omitted>0?`${this.text}
56
- ... [${this.omitted} selected characters omitted]`:this.text}}var w6={name:"read",description:"Read a UTF-8 text file by 1-based line offset and limit.",risk:"read",inputSchema:{type:"object",additionalProperties:!1,required:["path"],properties:{path:{type:"string"},offset:{type:"integer",minimum:1,default:1},limit:{type:"integer",minimum:1,maximum:2000,default:500}}},async execute($,w){let{path:G,offset:W=1,limit:Y=500}=$,Z=await J1(w.workspace,G),X=new ZT(50000),J=1,T=0,M=!1,f=()=>J>=W&&J<W+Y,Q=(P)=>{if(!f())return;if(!M){if(T>0)X.add(`
57
- `);T++,M=!0}X.add(P)},N=await ZH(Z,YT.O_RDONLY|YT.O_NOFOLLOW);try{let P=N.createReadStream({encoding:"utf8",autoClose:!1,highWaterMark:65536,signal:w.signal});for await(let q of P){let V=String(q),E=0;for(let O=V.indexOf(`
58
- `,E);O>=0;O=V.indexOf(`
59
- `,E))Q(V.slice(E,O)),J++,M=!1,E=O+1;Q(V.slice(E))}}finally{await N.close()}Q("");let z=J,K=Math.max(0,z-(W-1+T));return{content:X.value()+(K>0?`
60
- ... [${K} lines omitted]`:""),metadata:{totalLines:z,offset:W,limit:Y}}}};import{constants as G6}from"node:fs";import{mkdir as XH,open as JH}from"node:fs/promises";import TH from"node:path";var W6={name:"write",description:"Create or overwrite a UTF-8 file inside the workspace.",risk:"modify",inputSchema:{type:"object",additionalProperties:!1,required:["path","content"],properties:{path:{type:"string"},content:{type:"string"}}},async execute($,w){let{path:G,content:W}=$,Y=await J1(w.workspace,G);await XH(TH.dirname(Y),{recursive:!0}),Y=await J1(w.workspace,G);let Z=await JH(Y,G6.O_WRONLY|G6.O_CREAT|G6.O_TRUNC|G6.O_NOFOLLOW,384);try{await Z.writeFile(W,"utf8")}finally{await Z.close()}return{content:`Wrote ${Buffer.byteLength(W)} bytes to ${G}`}}};function XT(){return[w6,W6,$6,a8]}var JT="0.1.5";import V5 from"node:path";import{stdin as j3,stdout as d0}from"node:process";import{createInterface as sf}from"node:readline/promises";var TT=c$(S5(),1),{program:_R,createCommand:gR,createArgument:vR,createOption:uR,CommanderError:hR,InvalidArgumentError:cG,InvalidOptionArgumentError:iR,Command:mR,Argument:lR,Option:cR,Help:dR}=TT.default;import{mkdir as MH,readFile as fH,realpath as MT,writeFile as QH}from"node:fs/promises";import NH from"node:path";class dG{file;constructor($){this.file=$}async isTrusted($){return(await this.read()).includes($)}async isWorkspaceTrusted($){return this.isTrusted(await MT($))}async trustWorkspace($){return this.trust(await MT($))}async trust($){let w=await this.read();if(!w.includes($))w.push($);await MH(NH.dirname(this.file),{recursive:!0}),await QH(this.file,`${JSON.stringify(w,null,2)}
61
- `,{encoding:"utf8",mode:384})}async read(){try{let $=JSON.parse(await fH(this.file,"utf8"));return Array.isArray($)?$.filter((w)=>typeof w==="string"):[]}catch($){if($.code==="ENOENT")return[];throw $}}}class NT{estimateText($){return Math.ceil($.length/3.5)}estimateMessages($){return $.reduce((w,G)=>w+6+this.estimateText(JSON.stringify(G)),0)}estimateTools($){return this.estimateText(JSON.stringify($.map(({execute:w,...G})=>G)))}}class nG{budget;threshold;estimator=new NT;summary;compactionRange;compactedThrough=0;constructor($,w=0.8){this.budget=$;this.threshold=w}inputBudget(){return this.budget.contextWindow-this.budget.reservedOutputTokens-this.budget.safetyMargin}prepare($,w){let G=$[0]??{role:"system",content:"You are CodeN."},W=fT($.slice(1)),Y=this.estimator.estimateTools(w),Z=this.inputBudget(),X=this.summary?W.filter((Q)=>Q.end>this.compactedThrough):[...W],J=Math.min(3,X.length),T=this.project(G,X),M=this.estimator.estimateMessages(T)+Y,f=!1;if(M>Z*this.threshold&&X.length>J){let Q=X.slice(0,-J);X=X.slice(-J);let N=[...this.summary?[this.summary]:[],...Q.flatMap((z)=>z.messages)];this.compactionRange={start:Q[0]?.start??1,end:Q.at(-1)?.end??1},this.compactedThrough=this.compactionRange.end,this.summary={role:"system",content:`Compacted conversation summary:
62
- ${QT(N)}`},T=this.project(G,X),M=this.estimator.estimateMessages(T)+Y,f=!0}while(M>Z&&X.length>1)X=X.slice(1),T=this.project(G,X),M=this.estimator.estimateMessages(T)+Y,f=!0;return{messages:T,estimatedTokens:M,compacted:f}}forceCompact($,w){let G=$[0]??{role:"system",content:"You are CodeN."},W=fT($.slice(1)),Y=this.summary?W.filter((f)=>f.end>this.compactedThrough):W,Z=Y.slice(-1),X=Y.slice(0,-1),J=[...this.summary?[this.summary]:[],...X.flatMap((f)=>f.messages)];if(X.length)this.compactionRange={start:X[0]?.start??1,end:X.at(-1)?.end??1},this.compactedThrough=this.compactionRange.end;this.summary={role:"system",content:`Emergency compacted summary:
63
- ${QT(J)}`};let T=this.project(G,Z),M=this.estimator.estimateMessages(T)+this.estimator.estimateTools(w);return{messages:T,estimatedTokens:M,compacted:!0}}setSummary($,w=0){this.summary={role:"system",content:$},this.compactedThrough=w}getSummary(){return this.summary?.content}getCompactionRange(){return this.compactionRange}clearSummary(){this.summary=void 0,this.compactionRange=void 0,this.compactedThrough=0}project($,w){return[$,...this.summary?[this.summary]:[],...w.flatMap((G)=>G.messages)]}}function fT($){let w=[],G;for(let W=0;W<$.length;W++){let Y=$[W];if(!Y)continue;let Z=W+1;if(Y.role==="user"||!G){if(G)w.push(G);G={messages:[Y],start:Z,end:Z}}else G.messages.push(Y),G.end=Z}if(G)w.push(G);return w}function QT($){return $.map((G)=>{if(G.role==="tool")return`Tool ${G.name} (${G.isError?"error":"ok"}): ${G.content.slice(0,300)}`;return`${G.role}: ${G.content.slice(0,500)}`}).join(`
64
- `).slice(0,6000)}function pG($,w,G,W,Y){let Z={model:$,messages:w.messages,tools:G,maxOutputTokens:W.reservedOutputTokens};if(Y)Z.signal=Y;return Z}class tG{#$=new Set;on($){return this.#$.add($),()=>this.#$.delete($)}async emit($,w,G){let W={type:$,timestamp:new Date().toISOString()};if(G!==void 0)W.turnId=G;if(w!==void 0)W.data=w;return await Promise.all([...this.#$].map((Y)=>Y(W))),W}}import{randomUUID as zH}from"node:crypto";class rG{provider;registry;executor;context;sessions;events;options;messages;maxSteps;retries;retryBaseMs;systemPersisted;constructor($,w,G,W,Y,Z,X,J){this.provider=$;this.registry=w;this.executor=G;this.context=W;this.sessions=Y;this.events=Z;this.options=X;this.maxSteps=X.maxSteps??20,this.retries=X.retries??3,this.retryBaseMs=X.retryBaseMs??250,this.systemPersisted=Boolean(J?.length),this.messages=J?.length?[...J]:[{role:"system",content:X.systemPrompt??"You are CodeN, a concise coding agent. Inspect before editing, use tools carefully, and verify changes."}]}async reset(){let $=this.messages.find((w)=>w.role==="system")??{role:"system",content:"You are CodeN."};if(this.sessions.isCreated)await this.sessions.append("session.reset",{});this.messages.splice(0,this.messages.length,$),this.context.clearSummary(),this.systemPersisted=!1}async compact(){let $=this.context.forceCompact(this.messages,this.registry.list()),w=this.context.getSummary();if(w)await this.sessions.appendCompaction(w,this.context.getCompactionRange());await this.events.emit("context.compacted",{manual:!0,estimatedTokens:$.estimatedTokens})}async run($,w=new AbortController().signal){let G=zH(),W=Date.now(),Y=0,Z={inputTokens:0,outputTokens:0};await this.sessions.create(),await this.events.emit("turn.started",{input:$},G);try{if(!this.systemPersisted){let T=this.messages[0];if(T?.role==="system")await this.sessions.appendMessage(T);this.systemPersisted=!0}let X=this.messages.some((T)=>T.role==="user"),J={role:"user",content:$};if(this.messages.push(J),await this.sessions.appendMessage(J),!X)await this.sessions.setTitle($);for(let T=0;T<this.maxSteps;T++){let M=this.context.prepare(this.messages,this.registry.list());if(M.compacted){let N=this.context.getSummary();if(N){let z=await this.refineSummary(N,w,G);if(z){let K=N;N=z,this.context.setSummary(z,this.context.getCompactionRange()?.end??0),M.messages=M.messages.map((P)=>P.role==="system"&&P.content===K?{role:"system",content:z}:P)}await this.sessions.appendCompaction(N,this.context.getCompactionRange())}await this.events.emit("context.compacted",{estimatedTokens:M.estimatedTokens},G)}await this.events.emit("context.prepared",{estimatedTokens:M.estimatedTokens,budget:this.context.inputBudget()},G);let f=await this.requestWithRetry(pG(this.options.model,M,this.registry.list(),this.context.budget,w),G,async()=>{M=this.context.forceCompact(this.messages,this.registry.list());let N=this.context.getSummary();if(N)await this.sessions.appendCompaction(N,this.context.getCompactionRange());return pG(this.options.model,M,this.registry.list(),this.context.budget,w)});Z.inputTokens+=f.usage.inputTokens,Z.outputTokens+=f.usage.outputTokens;let Q={role:"assistant",content:f.text,toolCalls:f.toolCalls,model:this.options.model,usage:f.usage};if(this.messages.push(Q),await this.sessions.appendMessage(Q),Q.toolCalls.length===0)return await this.events.emit("turn.completed",{tools:Y,durationMs:Date.now()-W,inputTokens:Z.inputTokens,outputTokens:Z.outputTokens,contextTokens:M.estimatedTokens},G),{answer:Q.content,messages:this.messages,toolsExecuted:Y,usage:Z};for(let N of Q.toolCalls){let z=await this.executor.execute(N,w,G);Y++;let K={role:"tool",callId:N.callId,name:N.name,content:z.content,isError:z.isError??!1};this.messages.push(K),await this.sessions.appendMessage(K)}}throw new y("runtime","runtime.step_limit",`Maximum model steps (${this.maxSteps}) reached`)}catch(X){throw await this.events.emit("turn.failed",{code:X instanceof y?X.code:"runtime.unknown",message:X instanceof Error?X.message:String(X)},G),X}}async refineSummary($,w,G){try{await this.events.emit("context.compaction_started",{model:this.options.model},G);let W=await zT(this.provider.stream({model:this.options.model,messages:[{role:"system",content:"Rewrite the supplied coding-session summary concisely. Preserve goals, constraints, decisions, changed files, tool/test results, unresolved errors, and next steps. Return only the summary."},{role:"user",content:$}],tools:[],maxOutputTokens:Math.min(2048,this.context.budget.reservedOutputTokens),signal:w}));if(W.toolCalls.length>0||!W.text.trim())return;return`Compacted conversation summary:
65
- ${W.text.trim()}`}catch(W){await this.events.emit("context.compaction_failed",{message:W instanceof Error?W.message:String(W),fallback:"deterministic"},G);return}}async requestWithRetry($,w,G){let W=$,Y=!1;for(let Z=0;;Z++)try{await this.events.emit("provider.started",{attempt:Z},w);let X=await zT(this.provider.stream(W),async(J)=>{await this.events.emit("provider.delta",{text:J},w)},async(J)=>{await this.events.emit("provider.reasoning_delta",{text:J},w)},async(J)=>{if(J.type==="tool_call_start")await this.events.emit("provider.tool_call_start",{index:J.index,callId:J.callId,name:J.name},w);else if(J.type==="tool_call_delta")await this.events.emit("provider.tool_call_delta",{index:J.index,argumentsDelta:J.argumentsDelta},w);else await this.events.emit("provider.tool_call_end",{index:J.index},w)});return await this.events.emit("provider.completed",{usage:X.usage},w),X}catch(X){if(W.signal?.aborted)throw X;if(BH(X)){if(!Y){Y=!0,W=await G(),await this.events.emit("context.compacted",{emergency:!0},w);continue}throw new y("context","context.exhausted","Context is still over the provider limit after emergency compaction",!1,void 0,{cause:X})}if(Z>=this.retries||!KH(X))throw X;await this.events.emit("provider.retry",{attempt:Z+1,message:X instanceof Error?X.message:String(X)},w);let J=PH(X),T=this.retryBaseMs*2**Z*(0.8+Math.random()*0.4);await VH(J??Math.min(30000,T),W.signal)}}}async function zT($,w,G,W){let Y="",Z={inputTokens:0,outputTokens:0},X=new Map;for await(let T of $)if(T.type==="reasoning_delta")await G?.(T.text);else if(T.type==="text_delta")Y+=T.text,await w?.(T.text);else if(T.type==="tool_call_start")X.set(T.index,{callId:T.callId,name:T.name,json:"",ended:!1}),await W?.(T);else if(T.type==="tool_call_delta"){let M=X.get(T.index);if(!M)throw new y("provider","provider.invalid_stream","Tool arguments arrived before tool start");M.json+=T.argumentsDelta,await W?.(T)}else if(T.type==="tool_call_end"){let M=X.get(T.index);if(M)M.ended=!0,await W?.(T)}else if(T.type==="usage")Z={inputTokens:Math.max(Z.inputTokens,T.usage.inputTokens),outputTokens:Math.max(Z.outputTokens,T.usage.outputTokens)};let J=[...X.entries()].sort(([T],[M])=>T-M).map(([,T])=>{if(!T.ended)throw new y("provider","provider.incomplete_tool_call",`Incomplete tool call: ${T.name}`);try{return{callId:T.callId,name:T.name,input:JSON.parse(T.json||"{}")}}catch(M){throw new y("provider","provider.invalid_tool_json",`Invalid JSON for tool ${T.name}`,!1,void 0,{cause:M})}});return{text:Y,toolCalls:J,usage:Z}}function KH($){if($ instanceof y)return $.retryable;let w=$?.status;return typeof w!=="number"||w===429||w>=500}function PH($){let G=$?.headers?.get?.("retry-after");if(!G)return;let W=Number(G);if(Number.isFinite(W))return Math.max(0,W*1000);let Y=Date.parse(G);return Number.isNaN(Y)?void 0:Math.max(0,Y-Date.now())}function BH($){let w=$?.status,G=$ instanceof Error?$.message:String($);return w===413||/context.{0,20}(?:length|window|limit|too long)/i.test(G)}function VH($,w){return new Promise((G,W)=>{if(w?.aborted){W(w.reason);return}let Y=setTimeout(G,$);w?.addEventListener("abort",()=>{clearTimeout(Y),W(w.reason)},{once:!0})})}var M1=c$(X6(),1);import*as Mw from"node:readline";function oG(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var V$=oG();function OT($){V$=$}var P$={exec:()=>null};function Zw($){let w=[];return(G)=>{let W=Math.max(0,Math.min(3,G-1)),Y=w[W];return Y||(Y=$(W),w[W]=Y),Y}}function m($,w=""){let G=typeof $=="string"?$:$.source,W={replace:(Y,Z)=>{let X=typeof Z=="string"?Z:Z.source;return X=X.replace(V0.caret,"$1"),G=G.replace(Y,X),W},getRegex:()=>new RegExp(G,w)};return W}var HH=(($="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+$)}catch{return!1}})(),V0={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:($)=>new RegExp(`^( {0,3}${$})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:Zw(($)=>new RegExp(`^ {0,${$}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:Zw(($)=>new RegExp(`^ {0,${$}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:Zw(($)=>new RegExp(`^ {0,${$}}(?:\`\`\`|~~~)`)),headingBeginRegex:Zw(($)=>new RegExp(`^ {0,${$}}#`)),htmlBeginRegex:Zw(($)=>new RegExp(`^ {0,${$}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:Zw(($)=>new RegExp(`^ {0,${$}}>`))},FH=/^(?:[ \t]*(?:\n|$))+/,OH=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,LH=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,F4=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,DH=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,eG=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,LT=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,DT=m(LT).replace(/bull/g,eG).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),kH=m(LT).replace(/bull/g,eG).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),$W=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,AH=/^[^\n]+/,wW=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,SH=m(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",wW).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),RH=m(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,eG).getRegex(),Q6="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",GW=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,jH=m("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$))","i").replace("comment",GW).replace("tag",Q6).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),kT=($)=>m($W).replace("hr",F4).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",$).replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Q6).getRegex(),CH=kT(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),yH=kT(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),IH=m(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",yH).getRegex(),WW={blockquote:IH,code:OH,def:SH,fences:LH,heading:DH,hr:F4,html:jH,lheading:DT,list:RH,newline:FH,paragraph:CH,table:P$,text:AH},BT=m("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",F4).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3}\t)[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Q6).getRegex(),bH={...WW,lheading:kH,table:BT,paragraph:m($W).replace("hr",F4).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",BT).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Q6).getRegex()},xH={...WW,html:m(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",GW).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:P$,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:m($W).replace("hr",F4).replace("heading",` *#{1,6} *[^
66
- ]`).replace("lheading",DT).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},_H=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,gH=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,AT=/^( {2,}|\\)\n(?!\s*$)/,vH=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,U1=/[\p{P}\p{S}]/u,Xw=/[\s\p{P}\p{S}]/u,O4=/[^\s\p{P}\p{S}]/u,uH=m(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Xw).getRegex(),hH=/[\p{Pi}\p{Ps}"']/u,ST=/(?!~)[\p{P}\p{S}]/u,iH=/(?!~)[\s\p{P}\p{S}]/u,mH=/(?:[^\s\p{P}\p{S}]|~)/u,lH=m(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",HH?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),RT=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,cH=m(RT,"u").replace(/punct/g,U1).getRegex(),dH=m(RT,"u").replace(/punct/g,ST).getRegex(),nH=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,pH=m(nH,"u").replace(/openQuote/g,hH).replace(/punct/g,U1).getRegex(),jT="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",tH=m(jT,"gu").replace(/notPunctSpace/g,O4).replace(/punctSpace/g,Xw).replace(/punct/g,U1).getRegex(),rH=m(jT,"gu").replace(/notPunctSpace/g,mH).replace(/punctSpace/g,iH).replace(/punct/g,ST).getRegex(),sH="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",aH=m(sH,"gu").replace(/notPunctSpace/g,O4).replace(/punctSpace/g,Xw).replace(/punct/g,U1).getRegex(),oH=m("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,O4).replace(/punctSpace/g,Xw).replace(/punct/g,U1).getRegex(),eH="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",$F=m(eH,"gu").replace(/notPunctSpace/g,O4).replace(/punctSpace/g,Xw).replace(/punct/g,U1).getRegex(),wF=m(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,U1).getRegex(),GF="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",WF=m(GF,"gu").replace(/notPunctSpace/g,O4).replace(/punctSpace/g,Xw).replace(/punct/g,U1).getRegex(),YF=m(/\\(punct)/,"gu").replace(/punct/g,U1).getRegex(),ZF=m(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),XF=m(GW).replace("(?:-->|$)","-->").getRegex(),JF=m("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",XF).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),T6=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,TF=m(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",T6).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),CT=m(/^!?\[(label)\]\[(ref)\]/).replace("label",T6).replace("ref",wW).getRegex(),yT=m(/^!?\[(ref)\](?:\[\])?/).replace("ref",wW).getRegex(),MF=m("reflink|nolink(?!\\()","g").replace("reflink",CT).replace("nolink",yT).getRegex(),VT=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,YW={_backpedal:P$,anyPunctuation:YF,autolink:ZF,blockSkip:lH,br:AT,code:gH,del:P$,delLDelim:P$,delRDelim:P$,emStrongLDelim:cH,emStrongRDelimAst:tH,emStrongRDelimUnd:oH,escape:_H,link:TF,nolink:yT,punctuation:uH,reflink:CT,reflinkSearch:MF,tag:JF,text:vH,url:P$},fF={...YW,emStrongLDelim:pH,emStrongRDelimAst:aH,emStrongRDelimUnd:$F,link:m(/^!?\[(label)\]\((.*?)\)/).replace("label",T6).getRegex(),reflink:m(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",T6).getRegex()},aG={...YW,emStrongRDelimAst:rH,emStrongLDelim:dH,delLDelim:wF,delRDelim:WF,url:m(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",VT).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:m(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",VT).getRegex()},QF={...aG,br:m(AT).replace("{2,}","*").getRegex(),text:m(aG.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},J6={normal:WW,gfm:bH,pedantic:xH},U4={normal:YW,gfm:aG,breaks:QF,pedantic:fF},NF={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},qT=($)=>NF[$];function T1($,w){if(w){if(V0.escapeTest.test($))return $.replace(V0.escapeReplace,qT)}else if(V0.escapeTestNoEncode.test($))return $.replace(V0.escapeReplaceNoEncode,qT);return $}function ET($){try{$=encodeURI($).replace(V0.percentDecode,"%")}catch{return null}return $}function UT($,w){let G=$.replace(V0.findPipe,(Z,X,J)=>{let T=!1,M=X;for(;--M>=0&&J[M]==="\\";)T=!T;return T?"|":" |"}),W=G.split(V0.splitPipe),Y=0;if(W[0].trim()||W.shift(),W.length>0&&!W.at(-1)?.trim()&&W.pop(),w)if(W.length>w)W.splice(w);else for(;W.length<w;)W.push("");for(;Y<W.length;Y++)W[Y]=W[Y].trim().replace(V0.slashPipe,"|");return W}function d1($,w,G){let W=$.length;if(W===0)return"";let Y=0;for(;Y<W;){let Z=$.charAt(W-Y-1);if(Z===w&&!G)Y++;else if(Z!==w&&G)Y++;else break}return $.slice(0,W-Y)}function HT($){let w=$.split(`
67
- `),G=w.length-1;for(;G>=0&&V0.blankLine.test(w[G]);)G--;return w.length-G<=2?$:w.slice(0,G+1).join(`
68
- `)}function zF($,w){if($.indexOf(w[1])===-1)return-1;let G=0;for(let W=0;W<$.length;W++)if($[W]==="\\")W++;else if($[W]===w[0])G++;else if($[W]===w[1]&&(G--,G<0))return W;return G>0?-2:-1}function KF($,w=0){let G=w,W="";for(let Y of $)if(Y==="\t"){let Z=4-G%4;W+=" ".repeat(Z),G+=Z}else W+=Y,G++;return W}function FT($,w,G,W,Y){let Z=w.href,X=w.title||null,J=$[1].replace(Y.other.outputLinkReplace,"$1"),T=$[0].charAt(0)==="!";W.state.inLink=!0;let M=W.state.linkEmitted,f=W.state.inRawBlock;W.state.linkEmitted=!1;let Q=W.inlineTokens(J),N=W.state.linkEmitted;if(W.state.linkEmitted=M,W.state.inLink=!1,!T){if(N){W.state.inRawBlock=f;return}W.state.linkEmitted=!0}return{type:T?"image":"link",raw:G,href:Z,title:X,text:J,tokens:Q}}function PF($,w,G){let W=$.match(G.other.indentCodeCompensation);if(W===null)return w;let Y=W[1];return w.split(`
69
- `).map((Z)=>{let X=Z.match(G.other.beginningSpace);if(X===null)return Z;let[J]=X;return J.length>=Y.length?Z.slice(Y.length):Z}).join(`
70
- `)}var M6=class{options;rules;lexer;constructor($){this.options=$||V$}space($){let w=this.rules.block.newline.exec($);if(w&&w[0].length>0)return{type:"space",raw:w[0]}}code($){let w=this.rules.block.code.exec($);if(w){let G=this.options.pedantic?w[0]:HT(w[0]),W=G.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:G,codeBlockStyle:"indented",text:W}}}fences($){let w=this.rules.block.fences.exec($);if(w){let G=w[0],W=PF(G,w[3]||"",this.rules);return{type:"code",raw:G,lang:w[2]?w[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):w[2],text:W}}}heading($){let w=this.rules.block.heading.exec($);if(w){let G=w[2].trim();if(this.rules.other.endingHash.test(G)){let W=d1(G,"#");(this.options.pedantic||!W||this.rules.other.endingSpaceChar.test(W))&&(G=W.trim())}return{type:"heading",raw:d1(w[0],`
71
- `),depth:w[1].length,text:G,tokens:this.lexer.inline(G)}}}hr($){let w=this.rules.block.hr.exec($);if(w)return{type:"hr",raw:d1(w[0],`
72
- `)}}blockquote($){let w=this.rules.block.blockquote.exec($);if(w){let G=d1(w[0],`
188
+ `,"utf8")}function cZ($,w,G){return{packageName:$.packageName,requested:w,version:$.version,tools:$.tools.map((Z)=>Z.name).sort(),scope:G}}function VM($){return JSON.parse(xZ($))}function pZ($){let w=$.map((G)=>`${G.packageName}: ${G.message} (${G.path})`).join("; ");return new y("plugin","plugin.sync_failed",`plugin.sync_failed: ${w}`)}function gA($){return new y("plugin","plugin.specifier_invalid",`plugin.specifier_invalid: ${$}`)}function uA($,w){if(w&&hA($))return new y("plugin","plugin.lock_outdated","plugin.lock_outdated: committed plugin lockfile is out of date",!1,void 0,$ instanceof Error?{cause:$}:void 0);return $}function hA($){if(!($ instanceof Error))return!1;let w=`${$.message}
189
+ ${$ instanceof y?$.code:""}`;return/frozen-lockfile|lockfile.*out.?of.?date|lockfile.*would.*change|lockfile had changes/i.test(w)}async function KM($){try{return await bA($,CA.F_OK),!0}catch{return!1}}import{constants as Iq}from"node:fs";import{open as hy,realpath as jq,stat as vy}from"node:fs/promises";import Cq from"node:path";import{constants as Rq}from"node:fs";import{open as _y}from"node:fs/promises";import xy from"node:path";var tk=pX(),ok=D9(),ek=jX(),X7=E9(),$y=z9(),M1=r(),wy=J1(),Gy=W0(),Zy=T1(),Xy=Q1(),Ud=a5(),Yy=w7(),Jy=G7(),Wy=Z7(),$G=Eq(),Aq=T9();var Ty=tk.Composer,Qy=ok.Document,zy=ek.Schema,My=X7.YAMLError,Py=X7.YAMLParseError,qy=X7.YAMLWarning,By=$y.Alias,Ny=M1.isAlias,Vy=M1.isCollection,Ky=M1.isDocument,Uy=M1.isMap,Hy=M1.isNode,Fy=M1.isPair,Oy=M1.isScalar,fy=M1.isSeq,Ly=wy.Pair,Dy=Gy.Scalar,Ey=Zy.YAMLMap,Ay=Xy.YAMLSeq;var Ry=Yy.Lexer,Sy=Jy.LineCounter,Iy=Wy.Parser,jy=$G.parse,Cy=$G.parseAllDocuments,Y7=$G.parseDocument,by=$G.stringify,ky=Aq.visit,yy=Aq.visitAsync;var C9=1048576,gy=/^[a-z0-9][a-z0-9-]{0,63}$/;class J7{async parse($){let w=await _y($.entryRealPath,Rq.O_RDONLY|Rq.O_NOFOLLOW),G,Z,X;try{let Q=await w.stat();if(!Q.isFile())throw Error("SKILL.md must be a regular file");if(Q.size>C9)throw Error(`SKILL.md exceeds ${C9} bytes`);Z=Q.dev,X=Q.ino,G=await w.readFile("utf8")}finally{await w.close()}let Y=uy(G),J=Y.name,W=Y.description;if(typeof J!=="string"||!gy.test(J))throw Error("frontmatter name must be 1-64 lowercase letters, digits, or hyphens");if(J!==xy.basename($.rootPath))throw Error("frontmatter name must match the skill directory name");if(typeof W!=="string"||!W.trim()||W.length>1024)throw Error("frontmatter description must be a non-empty string of at most 1024 characters");let T={name:J,description:W,scope:$.scope,rootPath:$.rootPath,entryPath:$.entryPath,rootRealPath:$.rootRealPath,entryRealPath:$.entryRealPath,rootDevice:$.rootDevice,rootInode:$.rootInode,entryDevice:Z,entryInode:X};if(typeof Y.license==="string")T.license=Y.license;if(typeof Y.compatibility==="string")T.compatibility=Y.compatibility;if(Sq(Y.metadata))T.metadata=Y.metadata;if(Y["allowed-tools"]!==void 0)T.allowedTools=Y["allowed-tools"];return T}}function uy($){let w=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec($);if(!w?.[1])throw Error("SKILL.md must start with YAML frontmatter");let G=Y7(w[1]);if(G.errors.length)throw Error(`invalid YAML frontmatter: ${G.errors[0]?.message}`);let Z=G.toJSON();if(!Sq(Z))throw Error("frontmatter must be a YAML mapping");return Z}function Sq($){return!!$&&typeof $==="object"&&!Array.isArray($)}class c1{#$=new Map;constructor($=[]){for(let w of $)if(!this.#$.get(w.name)||w.scope==="project")this.#$.set(w.name,w)}get($){return this.#$.get($)}list(){return[...this.#$.values()].sort(($,w)=>$.name<w.name?-1:$.name>w.name?1:0)}async activate($){let w=this.get($);if(!w)throw new b9("skill.not_found",`No active skill named ${$}`);try{let G=await jq(w.rootPath),Z=await jq(w.entryPath),X=await vy(G);if(G!==w.rootRealPath||Z!==w.entryRealPath||!iy(Z,G)||X.dev!==w.rootDevice||X.ino!==w.rootInode)throw Error("skill entry was replaced or escapes its registered root");let Y=await hy(Z,Iq.O_RDONLY|Iq.O_NOFOLLOW);try{let J=await Y.stat();if(!J.isFile()||J.dev!==w.entryDevice||J.ino!==w.entryInode)throw Error("skill entry was replaced after discovery");if(J.size>C9)throw Error(`SKILL.md exceeds ${C9} bytes`);return{skill:w,content:await Y.readFile("utf8")}}finally{await Y.close()}}catch(G){throw new b9("skill.activation_failed",`Could not activate ${$}: ${G instanceof Error?G.message:String(G)}`)}}}function iy($,w){let G=Cq.relative(w,$);return G===""||!G.startsWith("..")&&!Cq.isAbsolute(G)}class b9 extends Error{code;constructor($,w){super(w);this.code=$}}function wG($){return{name:"activate_skill",description:"Load full instructions for one available Agent Skill by name.",risk:"read",inputSchema:{type:"object",additionalProperties:!1,required:["name"],properties:{name:{type:"string",minLength:1,maxLength:64}}},async execute(w){let{name:G}=w;try{let Z=await $.activate(G);return{content:`Skill root: ${Z.skill.rootRealPath}
190
+
191
+ ${Z.content}`}}catch(Z){if(Z instanceof b9)return{content:`${Z.code}: ${Z.message}`,isError:!0};return{content:`skill.activation_failed: ${Z instanceof Error?Z.message:String(Z)}`,isError:!0}}}}}var GG={name:"bash",description:"Run a bash command in the workspace with timeout and bounded output.",risk:"modify",inputSchema:{type:"object",additionalProperties:!1,required:["command"],properties:{command:{type:"string",minLength:1},timeout:{type:"integer",minimum:100,maximum:60000,default:30000},maxOutput:{type:"integer",minimum:1000,maximum:1e5,default:30000}}},async execute($,w){let{command:G,timeout:Z=30000,maxOutput:X=30000}=$,Y=await L6("bash",["-lc",G],{cwd:w.workspace,env:process.env,signal:w.signal,timeoutMs:Z,maxOutputChars:X}),J=[Y.stdout&&`stdout:
192
+ ${Y.stdout}`,Y.stderr&&`stderr:
193
+ ${Y.stderr}`].filter(Boolean).join(`
194
+ `);if(Y.exitCode===null&&!Y.timedOut&&!Y.cancelled&&Y.signal===null)return{content:`bash.spawn_error: ${Y.stderr||"unknown error"}`,isError:!0};let W=Y.timedOut?`Timed out after ${Z}ms`:Y.cancelled?"Cancelled":`Exit code: ${Y.exitCode??"null"}${Y.signal?` (signal ${Y.signal})`:""}`;return{content:Ew(`${W}
195
+ ${J}`.trimEnd(),X),isError:Y.timedOut||Y.cancelled||Y.exitCode!==0,metadata:{exitCode:Y.exitCode,signal:Y.signal,timedOut:Y.timedOut,cancelled:Y.cancelled}}}};import{constants as xq}from"node:fs";import{open as cy}from"node:fs/promises";import{constants as bq}from"node:fs";import{lstat as my,open as ly,readlink as dy,realpath as k9}from"node:fs/promises";import K$ from"node:path";function kq($,w){let G=K$.relative(w,$);return G===""||!G.startsWith("..")&&!K$.isAbsolute(G)}async function ZG($,w){let G=await k9($),Z=K$.resolve(G,w),X=await _q(Z);return{requested:w,path:X,scope:kq(X,G)?"inside":"outside"}}async function p1($,w,G){let Z=await ZG($,G);if(w&&(Z.scope!==w.scope||Z.path!==w.path))throw new y("permission","workspace.path_changed",`Path changed before execution: ${G}`);return Z.path}async function yq($,w,G=1e6){let Z=await P1($,w),X=await ly(Z,bq.O_RDONLY|bq.O_NOFOLLOW);try{if((await X.stat()).size>G)throw new y("context","workspace.instructions_too_large",`${w} exceeds the ${G}-byte instruction limit`);return await X.readFile("utf8")}finally{await X.close()}}async function P1($,w){let G=await k9($),Z=K$.resolve(G,w);if((await ZG($,w)).scope==="inside")try{return await k9(Z)}catch{return Z}let Y=kq(Z,G)?"workspace.symlink_escape":"workspace.outside";throw new y("permission",Y,`Path is outside workspace: ${w}`)}async function _q($,w=0){if(w>32)throw Error(`Too many symbolic links while resolving ${$}`);let G=K$.parse($),Z=$.slice(G.root.length).split(K$.sep).filter(Boolean),X=G.root,Y=await k9(G.root);for(let J=0;J<Z.length;J++){let W=Z[J];if(!W)continue;X=K$.join(X,W);try{if((await my(X)).isSymbolicLink()){let Q=await dy(X);return _q(K$.resolve(K$.dirname(X),Q,...Z.slice(J+1)),w+1)}Y=await k9(X)}catch(T){if(T.code!=="ENOENT")throw T;return K$.resolve(Y,...Z.slice(J))}}return Y}var XG={name:"edit",description:"Replace one uniquely matching exact text block in a UTF-8 file.",risk:"modify",inputSchema:{type:"object",additionalProperties:!1,required:["path","oldText","newText"],properties:{path:{type:"string"},oldText:{type:"string",minLength:1},newText:{type:"string"}}},async execute($,w){let{path:G,oldText:Z,newText:X}=$,Y=w.structuredFilePath?await p1(w.workspace,w.structuredFilePath,G):await P1(w.workspace,G),J=await cy(Y,xq.O_RDWR|xq.O_NOFOLLOW);try{let W=await J.readFile("utf8"),T=W.indexOf(Z);if(T<0)return{content:"edit.no_match: oldText was not found",isError:!0};if(W.indexOf(Z,T+1)>=0)return{content:"edit.multiple_matches: oldText is not unique",isError:!0};let Q=`${W.slice(0,T)}${X}${W.slice(T+Z.length)}`;await J.truncate(0),await J.write(Q,0,"utf8")}finally{await J.close()}return{content:`Edited ${G}`}}};import{constants as gq}from"node:fs";import{open as py}from"node:fs/promises";class uq{limit;text="";omitted=0;constructor($){this.limit=$}add($){let w=Math.max(0,this.limit-this.text.length);this.text+=$.slice(0,w),this.omitted+=Math.max(0,$.length-w)}value(){return this.omitted>0?`${this.text}
196
+ ... [${this.omitted} selected characters omitted]`:this.text}}var YG={name:"read",description:"Read a UTF-8 text file by 1-based line offset and limit.",risk:"read",inputSchema:{type:"object",additionalProperties:!1,required:["path"],properties:{path:{type:"string"},offset:{type:"integer",minimum:1,default:1},limit:{type:"integer",minimum:1,maximum:2000,default:500}}},async execute($,w){let{path:G,offset:Z=1,limit:X=500}=$,Y=w.structuredFilePath?await p1(w.workspace,w.structuredFilePath,G):await P1(w.workspace,G),J=new uq(50000),W=1,T=0,Q=!1,z=()=>W>=Z&&W<Z+X,M=(B)=>{if(!z())return;if(!Q){if(T>0)J.add(`
197
+ `);T++,Q=!0}J.add(B)},P=await py(Y,gq.O_RDONLY|gq.O_NOFOLLOW);try{let B=P.createReadStream({encoding:"utf8",autoClose:!1,highWaterMark:65536,signal:w.signal});for await(let V of B){let K=String(V),U=0;for(let O=K.indexOf(`
198
+ `,U);O>=0;O=K.indexOf(`
199
+ `,U))M(K.slice(U,O)),W++,Q=!1,U=O+1;M(K.slice(U))}}finally{await P.close()}M("");let q=W,N=Math.max(0,q-(Z-1+T));return{content:J.value()+(N>0?`
200
+ ... [${N} lines omitted]`:""),metadata:{totalLines:q,offset:Z,limit:X}}}};import{constants as JG}from"node:fs";import{mkdir as ny,open as ry}from"node:fs/promises";import sy from"node:path";var WG={name:"write",description:"Create or overwrite a UTF-8 file.",risk:"modify",inputSchema:{type:"object",additionalProperties:!1,required:["path","content"],properties:{path:{type:"string"},content:{type:"string"}}},async execute($,w){let{path:G,content:Z}=$,X=w.structuredFilePath?await p1(w.workspace,w.structuredFilePath,G):await P1(w.workspace,G);await ny(sy.dirname(X),{recursive:!0}),X=w.structuredFilePath?await p1(w.workspace,w.structuredFilePath,G):await P1(w.workspace,G);let Y=await ry(X,JG.O_WRONLY|JG.O_CREAT|JG.O_TRUNC|JG.O_NOFOLLOW,384);try{await Y.writeFile(Z,"utf8")}finally{await Y.close()}return{content:`Wrote ${Buffer.byteLength(Z)} bytes to ${G}`}}};function hq($=new c1){return[YG,WG,XG,GG,wG($)]}var vq="0.1.6";import F3 from"node:path";import{stdin as aY,stdout as d0}from"node:process";import{createInterface as bV}from"node:readline/promises";var iq=A1(b3(),1),{program:Wc,createCommand:Tc,createArgument:Qc,createOption:zc,CommanderError:Mc,InvalidArgumentError:W7,InvalidOptionArgumentError:Pc,Command:qc,Argument:Bc,Option:Nc,Help:Vc}=iq.default;import{mkdir as ay,readFile as ty,realpath as mq,writeFile as oy}from"node:fs/promises";import ey from"node:path";class T7{file;constructor($){this.file=$}async isTrusted($){return(await this.read()).includes($)}async isWorkspaceTrusted($){return this.isTrusted(await mq($))}async trustWorkspace($){return this.trust(await mq($))}async trust($){let w=await this.read();if(!w.includes($))w.push($);await ay(ey.dirname(this.file),{recursive:!0}),await oy(this.file,`${JSON.stringify(w,null,2)}
201
+ `,{encoding:"utf8",mode:384})}async read(){try{let $=JSON.parse(await ty(this.file,"utf8"));return Array.isArray($)?$.filter((w)=>typeof w==="string"):[]}catch($){if($.code==="ENOENT")return[];throw $}}}class cq{estimateText($){return Math.ceil($.length/3.5)}estimateMessages($){return $.reduce((w,G)=>w+6+this.estimateText(JSON.stringify(G)),0)}estimateTools($){return this.estimateText(JSON.stringify($.map(({execute:w,...G})=>G)))}}class Q7{budget;threshold;estimator=new cq;summary;compactionRange;compactedThrough=0;constructor($,w=0.8){this.budget=$;this.threshold=w}inputBudget(){return this.budget.contextWindow-this.budget.reservedOutputTokens-this.budget.safetyMargin}prepare($,w){let G=$[0]??{role:"system",content:"You are CodeN."},Z=lq($.slice(1)),X=this.estimator.estimateTools(w),Y=this.inputBudget(),J=this.summary?Z.filter((M)=>M.end>this.compactedThrough):[...Z],W=Math.min(3,J.length),T=this.project(G,J),Q=this.estimator.estimateMessages(T)+X,z=!1;if(Q>Y*this.threshold&&J.length>W){let M=J.slice(0,-W);J=J.slice(-W);let P=[...this.summary?[this.summary]:[],...M.flatMap((q)=>q.messages)];this.compactionRange={start:M[0]?.start??1,end:M.at(-1)?.end??1},this.compactedThrough=this.compactionRange.end,this.summary={role:"system",content:`Compacted conversation summary:
202
+ ${dq(P)}`},T=this.project(G,J),Q=this.estimator.estimateMessages(T)+X,z=!0}while(Q>Y&&J.length>1)J=J.slice(1),T=this.project(G,J),Q=this.estimator.estimateMessages(T)+X,z=!0;return{messages:T,estimatedTokens:Q,compacted:z}}forceCompact($,w){let G=$[0]??{role:"system",content:"You are CodeN."},Z=lq($.slice(1)),X=this.summary?Z.filter((z)=>z.end>this.compactedThrough):Z,Y=X.slice(-1),J=X.slice(0,-1),W=[...this.summary?[this.summary]:[],...J.flatMap((z)=>z.messages)];if(J.length)this.compactionRange={start:J[0]?.start??1,end:J.at(-1)?.end??1},this.compactedThrough=this.compactionRange.end;this.summary={role:"system",content:`Emergency compacted summary:
203
+ ${dq(W)}`};let T=this.project(G,Y),Q=this.estimator.estimateMessages(T)+this.estimator.estimateTools(w);return{messages:T,estimatedTokens:Q,compacted:!0}}setSummary($,w=0){this.summary={role:"system",content:$},this.compactedThrough=w}getSummary(){return this.summary?.content}getCompactionRange(){return this.compactionRange}clearSummary(){this.summary=void 0,this.compactionRange=void 0,this.compactedThrough=0}project($,w){return[$,...this.summary?[this.summary]:[],...w.flatMap((G)=>G.messages)]}}function lq($){let w=[],G;for(let Z=0;Z<$.length;Z++){let X=$[Z];if(!X)continue;let Y=Z+1;if(X.role==="user"||!G){if(G)w.push(G);G={messages:[X],start:Y,end:Y}}else G.messages.push(X),G.end=Y}if(G)w.push(G);return w}function dq($){return $.map((G)=>{if(G.role==="tool")return`Tool ${G.name} (${G.isError?"error":"ok"}): ${G.content.slice(0,300)}`;return`${G.role}: ${G.content.slice(0,500)}`}).join(`
204
+ `).slice(0,6000)}function z7($,w,G,Z,X){let Y={model:$,messages:w.messages,tools:G,maxOutputTokens:Z.reservedOutputTokens};if(X)Y.signal=X;return Y}class M7{#$=new Set;on($){return this.#$.add($),()=>this.#$.delete($)}async emit($,w,G){let Z={type:$,timestamp:new Date().toISOString()};if(G!==void 0)Z.turnId=G;if(w!==void 0)Z.data=w;return await Promise.all([...this.#$].map((X)=>X(Z))),Z}}import{randomUUID as $_}from"node:crypto";class P7{provider;registry;executor;context;sessions;events;options;messages;maxSteps;retries;retryBaseMs;systemPersisted;constructor($,w,G,Z,X,Y,J,W){this.provider=$;this.registry=w;this.executor=G;this.context=Z;this.sessions=X;this.events=Y;this.options=J;this.maxSteps=J.maxSteps??20,this.retries=J.retries??3,this.retryBaseMs=J.retryBaseMs??250,this.systemPersisted=Boolean(W?.length),this.messages=W?.length?[...W]:[{role:"system",content:J.systemPrompt??"You are CodeN, a concise coding agent. Inspect before editing, use tools carefully, and verify changes."}]}async reset(){let $=this.messages.find((w)=>w.role==="system")??{role:"system",content:"You are CodeN."};if(this.sessions.isCreated)await this.sessions.append("session.reset",{});this.messages.splice(0,this.messages.length,$),this.context.clearSummary(),this.systemPersisted=!1}async compact(){let $=this.context.forceCompact(this.messages,this.registry.list()),w=this.context.getSummary();if(w)await this.sessions.appendCompaction(w,this.context.getCompactionRange());await this.events.emit("context.compacted",{manual:!0,estimatedTokens:$.estimatedTokens})}async run($,w=new AbortController().signal){let G=$_(),Z=Date.now(),X=0,Y={inputTokens:0,outputTokens:0};await this.sessions.create(),await this.events.emit("turn.started",{input:$},G);try{if(!this.systemPersisted){let T=this.messages[0];if(T?.role==="system")await this.sessions.appendMessage(T);this.systemPersisted=!0}let J=this.messages.some((T)=>T.role==="user"),W={role:"user",content:$};if(this.messages.push(W),await this.sessions.appendMessage(W),!J)await this.sessions.setTitle($);for(let T=0;T<this.maxSteps;T++){let Q=this.context.prepare(this.messages,this.registry.list());if(Q.compacted){let P=this.context.getSummary();if(P){let q=await this.refineSummary(P,w,G);if(q){let N=P;P=q,this.context.setSummary(q,this.context.getCompactionRange()?.end??0),Q.messages=Q.messages.map((B)=>B.role==="system"&&B.content===N?{role:"system",content:q}:B)}await this.sessions.appendCompaction(P,this.context.getCompactionRange())}await this.events.emit("context.compacted",{estimatedTokens:Q.estimatedTokens},G)}await this.events.emit("context.prepared",{estimatedTokens:Q.estimatedTokens,budget:this.context.inputBudget()},G);let z=await this.requestWithRetry(z7(this.options.model,Q,this.registry.list(),this.context.budget,w),G,async()=>{Q=this.context.forceCompact(this.messages,this.registry.list());let P=this.context.getSummary();if(P)await this.sessions.appendCompaction(P,this.context.getCompactionRange());return z7(this.options.model,Q,this.registry.list(),this.context.budget,w)});Y.inputTokens+=z.usage.inputTokens,Y.outputTokens+=z.usage.outputTokens;let M={role:"assistant",content:z.text,toolCalls:z.toolCalls,model:this.options.model,usage:z.usage};if(this.messages.push(M),await this.sessions.appendMessage(M),M.toolCalls.length===0)return await this.events.emit("turn.completed",{tools:X,durationMs:Date.now()-Z,inputTokens:Y.inputTokens,outputTokens:Y.outputTokens,contextTokens:Q.estimatedTokens},G),{answer:M.content,messages:this.messages,toolsExecuted:X,usage:Y};for(let P of M.toolCalls){let q=await this.executor.execute(P,w,G);X++;let N={role:"tool",callId:P.callId,name:P.name,content:q.content,isError:q.isError??!1};this.messages.push(N),await this.sessions.appendMessage(N)}}throw new y("runtime","runtime.step_limit",`Maximum model steps (${this.maxSteps}) reached`)}catch(J){throw await this.events.emit("turn.failed",{code:J instanceof y?J.code:"runtime.unknown",message:J instanceof Error?J.message:String(J)},G),J}}async refineSummary($,w,G){try{await this.events.emit("context.compaction_started",{model:this.options.model},G);let Z=await pq(this.provider.stream({model:this.options.model,messages:[{role:"system",content:"Rewrite the supplied coding-session summary concisely. Preserve goals, constraints, decisions, changed files, tool/test results, unresolved errors, and next steps. Return only the summary."},{role:"user",content:$}],tools:[],maxOutputTokens:Math.min(2048,this.context.budget.reservedOutputTokens),signal:w}));if(Z.toolCalls.length>0||!Z.text.trim())return;return`Compacted conversation summary:
205
+ ${Z.text.trim()}`}catch(Z){await this.events.emit("context.compaction_failed",{message:Z instanceof Error?Z.message:String(Z),fallback:"deterministic"},G);return}}async requestWithRetry($,w,G){let Z=$,X=!1;for(let Y=0;;Y++)try{await this.events.emit("provider.started",{attempt:Y},w);let J=await pq(this.provider.stream(Z),async(W)=>{await this.events.emit("provider.delta",{text:W},w)},async(W)=>{await this.events.emit("provider.reasoning_delta",{text:W},w)},async(W)=>{if(W.type==="tool_call_start")await this.events.emit("provider.tool_call_start",{index:W.index,callId:W.callId,name:W.name},w);else if(W.type==="tool_call_delta")await this.events.emit("provider.tool_call_delta",{index:W.index,argumentsDelta:W.argumentsDelta},w);else await this.events.emit("provider.tool_call_end",{index:W.index},w)});return await this.events.emit("provider.completed",{usage:J.usage},w),J}catch(J){if(Z.signal?.aborted)throw J;if(Z_(J)){if(!X){X=!0,Z=await G(),await this.events.emit("context.compacted",{emergency:!0},w);continue}throw new y("context","context.exhausted","Context is still over the provider limit after emergency compaction",!1,void 0,{cause:J})}if(Y>=this.retries||!w_(J))throw J;await this.events.emit("provider.retry",{attempt:Y+1,message:J instanceof Error?J.message:String(J)},w);let W=G_(J),T=this.retryBaseMs*2**Y*(0.8+Math.random()*0.4);await X_(W??Math.min(30000,T),Z.signal)}}}async function pq($,w,G,Z){let X="",Y={inputTokens:0,outputTokens:0},J=new Map;for await(let T of $)if(T.type==="reasoning_delta")await G?.(T.text);else if(T.type==="text_delta")X+=T.text,await w?.(T.text);else if(T.type==="tool_call_start")J.set(T.index,{callId:T.callId,name:T.name,json:"",ended:!1}),await Z?.(T);else if(T.type==="tool_call_delta"){let Q=J.get(T.index);if(!Q)throw new y("provider","provider.invalid_stream","Tool arguments arrived before tool start");Q.json+=T.argumentsDelta,await Z?.(T)}else if(T.type==="tool_call_end"){let Q=J.get(T.index);if(Q)Q.ended=!0,await Z?.(T)}else if(T.type==="usage")Y={inputTokens:Math.max(Y.inputTokens,T.usage.inputTokens),outputTokens:Math.max(Y.outputTokens,T.usage.outputTokens)};let W=[...J.entries()].sort(([T],[Q])=>T-Q).map(([,T])=>{if(!T.ended)throw new y("provider","provider.incomplete_tool_call",`Incomplete tool call: ${T.name}`);try{return{callId:T.callId,name:T.name,input:JSON.parse(T.json||"{}")}}catch(Q){throw new y("provider","provider.invalid_tool_json",`Invalid JSON for tool ${T.name}`,!1,void 0,{cause:Q})}});return{text:X,toolCalls:W,usage:Y}}function w_($){if($ instanceof y)return $.retryable;let w=$?.status;return typeof w!=="number"||w===429||w>=500}function G_($){let G=$?.headers?.get?.("retry-after");if(!G)return;let Z=Number(G);if(Number.isFinite(Z))return Math.max(0,Z*1000);let X=Date.parse(G);return Number.isNaN(X)?void 0:Math.max(0,X-Date.now())}function Z_($){let w=$?.status,G=$ instanceof Error?$.message:String($);return w===413||/context.{0,20}(?:length|window|limit|too long)/i.test(G)}function X_($,w){return new Promise((G,Z)=>{if(w?.aborted){Z(w.reason);return}let X=setTimeout(G,$);w?.addEventListener("abort",()=>{clearTimeout(X),Z(w.reason)},{once:!0})})}var H$=A1(y9(),1);import*as $4 from"node:readline";function N7(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var s1=N7();function GB($){s1=$}var n1={exec:()=>null};function aw($){let w=[];return(G)=>{let Z=Math.max(0,Math.min(3,G-1)),X=w[Z];return X||(X=$(Z),w[Z]=X),X}}function d($,w=""){let G=typeof $=="string"?$:$.source,Z={replace:(X,Y)=>{let J=typeof Y=="string"?Y:Y.source;return J=J.replace(f0.caret,"$1"),G=G.replace(X,J),Z},getRegex:()=>new RegExp(G,w)};return Z}var T_=(($="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+$)}catch{return!1}})(),f0={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:($)=>new RegExp(`^( {0,3}${$})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:aw(($)=>new RegExp(`^ {0,${$}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:aw(($)=>new RegExp(`^ {0,${$}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:aw(($)=>new RegExp(`^ {0,${$}}(?:\`\`\`|~~~)`)),headingBeginRegex:aw(($)=>new RegExp(`^ {0,${$}}#`)),htmlBeginRegex:aw(($)=>new RegExp(`^ {0,${$}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:aw(($)=>new RegExp(`^ {0,${$}}>`))},Q_=/^(?:[ \t]*(?:\n|$))+/,z_=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,M_=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,g9=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,P_=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,V7=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,ZB=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,XB=d(ZB).replace(/bull/g,V7).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),q_=d(ZB).replace(/bull/g,V7).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),K7=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,B_=/^[^\n]+/,U7=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,N_=d(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",U7).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),V_=d(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,V7).getRegex(),BG="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",H7=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,K_=d("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$))","i").replace("comment",H7).replace("tag",BG).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),YB=($)=>d(K7).replace("hr",g9).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",$).replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",BG).getRegex(),U_=YB(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),H_=YB(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),F_=d(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",H_).getRegex(),F7={blockquote:F_,code:z_,def:N_,fences:M_,heading:P_,hr:g9,html:K_,lheading:XB,list:V_,newline:Q_,paragraph:U_,table:n1,text:B_},sq=d("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",g9).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3}\t)[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",BG).getRegex(),O_={...F7,lheading:q_,table:sq,paragraph:d(K7).replace("hr",g9).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",sq).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",BG).getRegex()},f_={...F7,html:d(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",H7).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:n1,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:d(K7).replace("hr",g9).replace("heading",` *#{1,6} *[^
206
+ ]`).replace("lheading",XB).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},L_=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,D_=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,JB=/^( {2,}|\\)\n(?!\s*$)/,E_=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,k$=/[\p{P}\p{S}]/u,tw=/[\s\p{P}\p{S}]/u,u9=/[^\s\p{P}\p{S}]/u,A_=d(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,tw).getRegex(),R_=/[\p{Pi}\p{Ps}"']/u,WB=/(?!~)[\p{P}\p{S}]/u,S_=/(?!~)[\s\p{P}\p{S}]/u,I_=/(?:[^\s\p{P}\p{S}]|~)/u,j_=d(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",T_?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),TB=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,C_=d(TB,"u").replace(/punct/g,k$).getRegex(),b_=d(TB,"u").replace(/punct/g,WB).getRegex(),k_=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,y_=d(k_,"u").replace(/openQuote/g,R_).replace(/punct/g,k$).getRegex(),QB="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",__=d(QB,"gu").replace(/notPunctSpace/g,u9).replace(/punctSpace/g,tw).replace(/punct/g,k$).getRegex(),x_=d(QB,"gu").replace(/notPunctSpace/g,I_).replace(/punctSpace/g,S_).replace(/punct/g,WB).getRegex(),g_="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",u_=d(g_,"gu").replace(/notPunctSpace/g,u9).replace(/punctSpace/g,tw).replace(/punct/g,k$).getRegex(),h_=d("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,u9).replace(/punctSpace/g,tw).replace(/punct/g,k$).getRegex(),v_="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",i_=d(v_,"gu").replace(/notPunctSpace/g,u9).replace(/punctSpace/g,tw).replace(/punct/g,k$).getRegex(),m_=d(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,k$).getRegex(),l_="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",d_=d(l_,"gu").replace(/notPunctSpace/g,u9).replace(/punctSpace/g,tw).replace(/punct/g,k$).getRegex(),c_=d(/\\(punct)/,"gu").replace(/punct/g,k$).getRegex(),p_=d(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),n_=d(H7).replace("(?:-->|$)","-->").getRegex(),r_=d("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",n_).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),MG=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,s_=d(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",MG).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),zB=d(/^!?\[(label)\]\[(ref)\]/).replace("label",MG).replace("ref",U7).getRegex(),MB=d(/^!?\[(ref)\](?:\[\])?/).replace("ref",U7).getRegex(),a_=d("reflink|nolink(?!\\()","g").replace("reflink",zB).replace("nolink",MB).getRegex(),aq=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,O7={_backpedal:n1,anyPunctuation:c_,autolink:p_,blockSkip:j_,br:JB,code:D_,del:n1,delLDelim:n1,delRDelim:n1,emStrongLDelim:C_,emStrongRDelimAst:__,emStrongRDelimUnd:h_,escape:L_,link:s_,nolink:MB,punctuation:A_,reflink:zB,reflinkSearch:a_,tag:r_,text:E_,url:n1},t_={...O7,emStrongLDelim:y_,emStrongRDelimAst:u_,emStrongRDelimUnd:i_,link:d(/^!?\[(label)\]\((.*?)\)/).replace("label",MG).getRegex(),reflink:d(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",MG).getRegex()},B7={...O7,emStrongRDelimAst:x_,emStrongLDelim:b_,delLDelim:m_,delRDelim:d_,url:d(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",aq).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:d(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",aq).getRegex()},o_={...B7,br:d(JB).replace("{2,}","*").getRegex(),text:d(B7.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},zG={normal:F7,gfm:O_,pedantic:f_},_9={normal:O7,gfm:B7,breaks:o_,pedantic:t_},e_={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},tq=($)=>e_[$];function U$($,w){if(w){if(f0.escapeTest.test($))return $.replace(f0.escapeReplace,tq)}else if(f0.escapeTestNoEncode.test($))return $.replace(f0.escapeReplaceNoEncode,tq);return $}function oq($){try{$=encodeURI($).replace(f0.percentDecode,"%")}catch{return null}return $}function eq($,w){let G=$.replace(f0.findPipe,(Y,J,W)=>{let T=!1,Q=J;for(;--Q>=0&&W[Q]==="\\";)T=!T;return T?"|":" |"}),Z=G.split(f0.splitPipe),X=0;if(Z[0].trim()||Z.shift(),Z.length>0&&!Z.at(-1)?.trim()&&Z.pop(),w)if(Z.length>w)Z.splice(w);else for(;Z.length<w;)Z.push("");for(;X<Z.length;X++)Z[X]=Z[X].trim().replace(f0.slashPipe,"|");return Z}function q1($,w,G){let Z=$.length;if(Z===0)return"";let X=0;for(;X<Z;){let Y=$.charAt(Z-X-1);if(Y===w&&!G)X++;else if(Y!==w&&G)X++;else break}return $.slice(0,Z-X)}function $B($){let w=$.split(`
207
+ `),G=w.length-1;for(;G>=0&&f0.blankLine.test(w[G]);)G--;return w.length-G<=2?$:w.slice(0,G+1).join(`
208
+ `)}function $x($,w){if($.indexOf(w[1])===-1)return-1;let G=0;for(let Z=0;Z<$.length;Z++)if($[Z]==="\\")Z++;else if($[Z]===w[0])G++;else if($[Z]===w[1]&&(G--,G<0))return Z;return G>0?-2:-1}function wx($,w=0){let G=w,Z="";for(let X of $)if(X==="\t"){let Y=4-G%4;Z+=" ".repeat(Y),G+=Y}else Z+=X,G++;return Z}function wB($,w,G,Z,X){let Y=w.href,J=w.title||null,W=$[1].replace(X.other.outputLinkReplace,"$1"),T=$[0].charAt(0)==="!";Z.state.inLink=!0;let Q=Z.state.linkEmitted,z=Z.state.inRawBlock;Z.state.linkEmitted=!1;let M=Z.inlineTokens(W),P=Z.state.linkEmitted;if(Z.state.linkEmitted=Q,Z.state.inLink=!1,!T){if(P){Z.state.inRawBlock=z;return}Z.state.linkEmitted=!0}return{type:T?"image":"link",raw:G,href:Y,title:J,text:W,tokens:M}}function Gx($,w,G){let Z=$.match(G.other.indentCodeCompensation);if(Z===null)return w;let X=Z[1];return w.split(`
209
+ `).map((Y)=>{let J=Y.match(G.other.beginningSpace);if(J===null)return Y;let[W]=J;return W.length>=X.length?Y.slice(X.length):Y}).join(`
210
+ `)}var PG=class{options;rules;lexer;constructor($){this.options=$||s1}space($){let w=this.rules.block.newline.exec($);if(w&&w[0].length>0)return{type:"space",raw:w[0]}}code($){let w=this.rules.block.code.exec($);if(w){let G=this.options.pedantic?w[0]:$B(w[0]),Z=G.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:G,codeBlockStyle:"indented",text:Z}}}fences($){let w=this.rules.block.fences.exec($);if(w){let G=w[0],Z=Gx(G,w[3]||"",this.rules);return{type:"code",raw:G,lang:w[2]?w[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):w[2],text:Z}}}heading($){let w=this.rules.block.heading.exec($);if(w){let G=w[2].trim();if(this.rules.other.endingHash.test(G)){let Z=q1(G,"#");(this.options.pedantic||!Z||this.rules.other.endingSpaceChar.test(Z))&&(G=Z.trim())}return{type:"heading",raw:q1(w[0],`
211
+ `),depth:w[1].length,text:G,tokens:this.lexer.inline(G)}}}hr($){let w=this.rules.block.hr.exec($);if(w)return{type:"hr",raw:q1(w[0],`
212
+ `)}}blockquote($){let w=this.rules.block.blockquote.exec($);if(w){let G=q1(w[0],`
73
213
  `).split(`
74
- `),W="",Y="",Z=[];for(;G.length>0;){let X=!1,J=[],T;for(T=0;T<G.length;T++)if(this.rules.other.blockquoteStart.test(G[T]))J.push(G[T]),X=!0;else if(!X)J.push(G[T]);else break;G=G.slice(T);let M=J.join(`
75
- `),f=M.replace(this.rules.other.blockquoteSetextReplace,`
76
- $1`).replace(this.rules.other.blockquoteSetextReplace2,"");W=W?`${W}
77
- ${M}`:M,Y=Y?`${Y}
78
- ${f}`:f;let Q=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(f,Z,!0),this.lexer.state.top=Q,G.length===0)break;let N=Z.at(-1);if(N?.type==="code")break;if(N?.type==="blockquote"){let z=N,K=G.join(`
79
- `),P=z.raw+`
80
- `+K.replace(this.rules.other.blockquoteSetextReplace2,""),q=this.blockquote(P);Z[Z.length-1]=q,W=`${W}
81
- ${K}`,Y=Y.substring(0,Y.length-z.text.length)+q.text;break}else if(N?.type==="list"){let z=N,K=z.raw+`
214
+ `),Z="",X="",Y=[];for(;G.length>0;){let J=!1,W=[],T;for(T=0;T<G.length;T++)if(this.rules.other.blockquoteStart.test(G[T]))W.push(G[T]),J=!0;else if(!J)W.push(G[T]);else break;G=G.slice(T);let Q=W.join(`
215
+ `),z=Q.replace(this.rules.other.blockquoteSetextReplace,`
216
+ $1`).replace(this.rules.other.blockquoteSetextReplace2,"");Z=Z?`${Z}
217
+ ${Q}`:Q,X=X?`${X}
218
+ ${z}`:z;let M=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(z,Y,!0),this.lexer.state.top=M,G.length===0)break;let P=Y.at(-1);if(P?.type==="code")break;if(P?.type==="blockquote"){let q=P,N=G.join(`
219
+ `),B=q.raw+`
220
+ `+N.replace(this.rules.other.blockquoteSetextReplace2,""),V=this.blockquote(B);Y[Y.length-1]=V,Z=`${Z}
221
+ ${N}`,X=X.substring(0,X.length-q.text.length)+V.text;break}else if(P?.type==="list"){let q=P,N=q.raw+`
82
222
  `+G.join(`
83
- `),P=this.list(K);Z[Z.length-1]=P,W=W.substring(0,W.length-N.raw.length)+P.raw,Y=Y.substring(0,Y.length-z.raw.length)+P.raw,G=K.substring(Z.at(-1).raw.length).split(`
84
- `);continue}}return{type:"blockquote",raw:W,tokens:Z,text:Y}}}list($){let w=this.rules.block.list.exec($);if(w){let G=w[1].trim(),W=G.length>1,Y={type:"list",raw:"",ordered:W,start:W?+G.slice(0,-1):"",loose:!1,items:[]};G=W?`\\d{1,9}\\${G.slice(-1)}`:`\\${G}`,this.options.pedantic&&(G=W?G:"[*+-]");let Z=this.rules.other.listItemRegex(G),X=!1;for(;$;){let T=!1,M="",f="";if(!(w=Z.exec($))||this.rules.block.hr.test($))break;M=w[0],$=$.substring(M.length);let Q=KF(w[2].split(`
85
- `,1)[0],w[1].length),N=$.split(`
86
- `,1)[0],z=!Q.trim(),K=0;if(this.options.pedantic?(K=2,f=Q.trimStart()):z?K=w[1].length+1:(K=Q.search(this.rules.other.nonSpaceChar),K=K>4?1:K,f=Q.slice(K),K+=w[1].length),z&&this.rules.other.blankLine.test(N)&&(M+=N+`
87
- `,$=$.substring(N.length+1),T=!0),!T){let P=this.rules.other.nextBulletRegex(K),q=this.rules.other.hrRegex(K),V=this.rules.other.fencesBeginRegex(K),E=this.rules.other.headingBeginRegex(K),O=this.rules.other.htmlBeginRegex(K),A=this.rules.other.blockquoteBeginRegex(K);for(;$;){let R=$.split(`
88
- `,1)[0],S;if(N=R,this.options.pedantic?(N=N.replace(this.rules.other.listReplaceNesting," "),S=N):S=N.replace(this.rules.other.tabCharGlobal," "),V.test(N)||E.test(N)||O.test(N)||A.test(N)||P.test(N)||q.test(N))break;if(S.search(this.rules.other.nonSpaceChar)>=K||!N.trim())f+=`
89
- `+S.slice(K);else{if(z||Q.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||V.test(Q)||E.test(Q)||q.test(Q))break;f+=`
90
- `+N}z=!N.trim(),M+=R+`
91
- `,$=$.substring(R.length+1),Q=S.slice(K)}}Y.loose||(X?Y.loose=!0:this.rules.other.doubleBlankLine.test(M)&&(X=!0)),Y.items.push({type:"list_item",raw:M,task:!!this.options.gfm&&this.rules.other.listIsTask.test(f),loose:!1,text:f,tokens:[]}),Y.raw+=M}let J=Y.items.at(-1);if(J)J.raw=J.raw.trimEnd(),J.text=J.text.trimEnd();else return;Y.raw=Y.raw.trimEnd();for(let T of Y.items)if(this.lexer.state.top=!1,T.tokens=this.lexer.blockTokens(T.text,[]),!Y.loose){let M=T.tokens.filter((Q)=>Q.type==="space"),f=M.length>0&&M.some((Q)=>this.rules.other.anyLine.test(Q.raw));Y.loose=f}for(let T of Y.items){let M=T.tokens[0];if(T.task&&(M?.type==="text"||M?.type==="paragraph")){T.text=T.text.replace(this.rules.other.listReplaceTask,""),M.raw=M.raw.replace(this.rules.other.listReplaceTask,""),M.text=M.text.replace(this.rules.other.listReplaceTask,"");for(let Q=this.lexer.inlineQueue.length-1;Q>=0;Q--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[Q].src)){this.lexer.inlineQueue[Q].src=this.lexer.inlineQueue[Q].src.replace(this.rules.other.listReplaceTask,"");break}let f=this.rules.other.listTaskCheckbox.exec(T.raw);if(f){let Q={type:"checkbox",raw:f[0]+" ",checked:f[0]!=="[ ]"};T.checked=Q.checked,Y.loose?T.tokens[0]&&["paragraph","text"].includes(T.tokens[0].type)&&"tokens"in T.tokens[0]&&T.tokens[0].tokens?(T.tokens[0].raw=Q.raw+T.tokens[0].raw,T.tokens[0].text=Q.raw+T.tokens[0].text,T.tokens[0].tokens.unshift(Q)):T.tokens.unshift({type:"paragraph",raw:Q.raw,text:Q.raw,tokens:[Q]}):T.tokens.unshift(Q)}}else T.task&&(T.task=!1)}if(Y.loose)for(let T of Y.items){T.loose=!0;for(let M of T.tokens)M.type==="text"&&(M.type="paragraph")}return Y}}html($){let w=this.rules.block.html.exec($);if(w){let G=HT(w[0]);return{type:"html",block:!0,raw:G,pre:w[1]==="pre"||w[1]==="script"||w[1]==="style",text:G}}}def($){let w=this.rules.block.def.exec($);if(w){let G=w[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),W=w[2]?w[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",Y=w[3]?w[3].substring(1,w[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):w[3];return{type:"def",tag:G,raw:d1(w[0],`
92
- `),href:W,title:Y}}}table($){let w=this.rules.block.table.exec($);if(!w||!this.rules.other.tableDelimiter.test(w[2]))return;let G=UT(w[1]),W=w[2].replace(this.rules.other.tableAlignChars,"").split("|"),Y=w[3]?.trim()?w[3].replace(this.rules.other.tableRowBlankLine,"").split(`
93
- `):[],Z={type:"table",raw:d1(w[0],`
94
- `),header:[],align:[],rows:[]};if(G.length===W.length){for(let X of W)this.rules.other.tableAlignRight.test(X)?Z.align.push("right"):this.rules.other.tableAlignCenter.test(X)?Z.align.push("center"):this.rules.other.tableAlignLeft.test(X)?Z.align.push("left"):Z.align.push(null);for(let X=0;X<G.length;X++)Z.header.push({text:G[X],tokens:this.lexer.inline(G[X]),header:!0,align:Z.align[X]});for(let X of Y)Z.rows.push(UT(X,Z.header.length).map((J,T)=>({text:J,tokens:this.lexer.inline(J),header:!1,align:Z.align[T]})));return Z}}lheading($){let w=this.rules.block.lheading.exec($);if(w){let G=w[1].trim();return{type:"heading",raw:d1(w[0],`
223
+ `),B=this.list(N);Y[Y.length-1]=B,Z=Z.substring(0,Z.length-P.raw.length)+B.raw,X=X.substring(0,X.length-q.raw.length)+B.raw,G=N.substring(Y.at(-1).raw.length).split(`
224
+ `);continue}}return{type:"blockquote",raw:Z,tokens:Y,text:X}}}list($){let w=this.rules.block.list.exec($);if(w){let G=w[1].trim(),Z=G.length>1,X={type:"list",raw:"",ordered:Z,start:Z?+G.slice(0,-1):"",loose:!1,items:[]};G=Z?`\\d{1,9}\\${G.slice(-1)}`:`\\${G}`,this.options.pedantic&&(G=Z?G:"[*+-]");let Y=this.rules.other.listItemRegex(G),J=!1;for(;$;){let T=!1,Q="",z="";if(!(w=Y.exec($))||this.rules.block.hr.test($))break;Q=w[0],$=$.substring(Q.length);let M=wx(w[2].split(`
225
+ `,1)[0],w[1].length),P=$.split(`
226
+ `,1)[0],q=!M.trim(),N=0;if(this.options.pedantic?(N=2,z=M.trimStart()):q?N=w[1].length+1:(N=M.search(this.rules.other.nonSpaceChar),N=N>4?1:N,z=M.slice(N),N+=w[1].length),q&&this.rules.other.blankLine.test(P)&&(Q+=P+`
227
+ `,$=$.substring(P.length+1),T=!0),!T){let B=this.rules.other.nextBulletRegex(N),V=this.rules.other.hrRegex(N),K=this.rules.other.fencesBeginRegex(N),U=this.rules.other.headingBeginRegex(N),O=this.rules.other.htmlBeginRegex(N),D=this.rules.other.blockquoteBeginRegex(N);for(;$;){let f=$.split(`
228
+ `,1)[0],L;if(P=f,this.options.pedantic?(P=P.replace(this.rules.other.listReplaceNesting," "),L=P):L=P.replace(this.rules.other.tabCharGlobal," "),K.test(P)||U.test(P)||O.test(P)||D.test(P)||B.test(P)||V.test(P))break;if(L.search(this.rules.other.nonSpaceChar)>=N||!P.trim())z+=`
229
+ `+L.slice(N);else{if(q||M.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||K.test(M)||U.test(M)||V.test(M))break;z+=`
230
+ `+P}q=!P.trim(),Q+=f+`
231
+ `,$=$.substring(f.length+1),M=L.slice(N)}}X.loose||(J?X.loose=!0:this.rules.other.doubleBlankLine.test(Q)&&(J=!0)),X.items.push({type:"list_item",raw:Q,task:!!this.options.gfm&&this.rules.other.listIsTask.test(z),loose:!1,text:z,tokens:[]}),X.raw+=Q}let W=X.items.at(-1);if(W)W.raw=W.raw.trimEnd(),W.text=W.text.trimEnd();else return;X.raw=X.raw.trimEnd();for(let T of X.items)if(this.lexer.state.top=!1,T.tokens=this.lexer.blockTokens(T.text,[]),!X.loose){let Q=T.tokens.filter((M)=>M.type==="space"),z=Q.length>0&&Q.some((M)=>this.rules.other.anyLine.test(M.raw));X.loose=z}for(let T of X.items){let Q=T.tokens[0];if(T.task&&(Q?.type==="text"||Q?.type==="paragraph")){T.text=T.text.replace(this.rules.other.listReplaceTask,""),Q.raw=Q.raw.replace(this.rules.other.listReplaceTask,""),Q.text=Q.text.replace(this.rules.other.listReplaceTask,"");for(let M=this.lexer.inlineQueue.length-1;M>=0;M--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[M].src)){this.lexer.inlineQueue[M].src=this.lexer.inlineQueue[M].src.replace(this.rules.other.listReplaceTask,"");break}let z=this.rules.other.listTaskCheckbox.exec(T.raw);if(z){let M={type:"checkbox",raw:z[0]+" ",checked:z[0]!=="[ ]"};T.checked=M.checked,X.loose?T.tokens[0]&&["paragraph","text"].includes(T.tokens[0].type)&&"tokens"in T.tokens[0]&&T.tokens[0].tokens?(T.tokens[0].raw=M.raw+T.tokens[0].raw,T.tokens[0].text=M.raw+T.tokens[0].text,T.tokens[0].tokens.unshift(M)):T.tokens.unshift({type:"paragraph",raw:M.raw,text:M.raw,tokens:[M]}):T.tokens.unshift(M)}}else T.task&&(T.task=!1)}if(X.loose)for(let T of X.items){T.loose=!0;for(let Q of T.tokens)Q.type==="text"&&(Q.type="paragraph")}return X}}html($){let w=this.rules.block.html.exec($);if(w){let G=$B(w[0]);return{type:"html",block:!0,raw:G,pre:w[1]==="pre"||w[1]==="script"||w[1]==="style",text:G}}}def($){let w=this.rules.block.def.exec($);if(w){let G=w[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),Z=w[2]?w[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",X=w[3]?w[3].substring(1,w[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):w[3];return{type:"def",tag:G,raw:q1(w[0],`
232
+ `),href:Z,title:X}}}table($){let w=this.rules.block.table.exec($);if(!w||!this.rules.other.tableDelimiter.test(w[2]))return;let G=eq(w[1]),Z=w[2].replace(this.rules.other.tableAlignChars,"").split("|"),X=w[3]?.trim()?w[3].replace(this.rules.other.tableRowBlankLine,"").split(`
233
+ `):[],Y={type:"table",raw:q1(w[0],`
234
+ `),header:[],align:[],rows:[]};if(G.length===Z.length){for(let J of Z)this.rules.other.tableAlignRight.test(J)?Y.align.push("right"):this.rules.other.tableAlignCenter.test(J)?Y.align.push("center"):this.rules.other.tableAlignLeft.test(J)?Y.align.push("left"):Y.align.push(null);for(let J=0;J<G.length;J++)Y.header.push({text:G[J],tokens:this.lexer.inline(G[J]),header:!0,align:Y.align[J]});for(let J of X)Y.rows.push(eq(J,Y.header.length).map((W,T)=>({text:W,tokens:this.lexer.inline(W),header:!1,align:Y.align[T]})));return Y}}lheading($){let w=this.rules.block.lheading.exec($);if(w){let G=w[1].trim();return{type:"heading",raw:q1(w[0],`
95
235
  `),depth:w[2].charAt(0)==="="?1:2,text:G,tokens:this.lexer.inline(G)}}}paragraph($){let w=this.rules.block.paragraph.exec($);if(w){let G=w[1].charAt(w[1].length-1)===`
96
- `?w[1].slice(0,-1):w[1];return{type:"paragraph",raw:w[0],text:G,tokens:this.lexer.inline(G)}}}text($){let w=this.rules.block.text.exec($);if(w)return{type:"text",raw:w[0],text:w[0],tokens:this.lexer.inline(w[0])}}escape($){let w=this.rules.inline.escape.exec($);if(w)return{type:"escape",raw:w[0],text:w[1]}}tag($){let w=this.rules.inline.tag.exec($);if(w)return!this.lexer.state.inLink&&this.rules.other.startATag.test(w[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(w[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(w[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(w[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:w[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:w[0]}}link($){let w=this.rules.inline.link.exec($);if(w){let G=w[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(G)){if(!this.rules.other.endAngleBracket.test(G))return;let Z=d1(G.slice(0,-1),"\\");if((G.length-Z.length)%2===0)return}else{let Z=zF(w[2],"()");if(Z===-2)return;if(Z>-1){let X=(w[0].indexOf("!")===0?5:4)+w[1].length+Z;w[2]=w[2].substring(0,Z),w[0]=w[0].substring(0,X).trim(),w[3]=""}}let W=w[2],Y="";if(this.options.pedantic){let Z=this.rules.other.pedanticHrefTitle.exec(W);Z&&(W=Z[1],Y=Z[3])}else Y=w[3]?w[3].slice(1,-1):"";return W=W.trim(),this.rules.other.startAngleBracket.test(W)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(G)?W=W.slice(1):W=W.slice(1,-1)),FT(w,{href:W&&W.replace(this.rules.inline.anyPunctuation,"$1"),title:Y&&Y.replace(this.rules.inline.anyPunctuation,"$1")},w[0],this.lexer,this.rules)}}reflink($,w){let G;if((G=this.rules.inline.reflink.exec($))||(G=this.rules.inline.nolink.exec($))){let W=(G[2]||G[1]).replace(this.rules.other.multipleSpaceGlobal," "),Y=w[W.toLowerCase()];if(!Y){let Z=G[0].charAt(0);return{type:"text",raw:Z,text:Z}}return FT(G,Y,G[0],this.lexer,this.rules)}}emStrong($,w,G=""){let W=this.rules.inline.emStrongLDelim.exec($);if(!W||!W[1]&&!W[2]&&!W[3]&&!W[4]||W[4]&&G.match(this.rules.other.unicodeAlphaNumeric))return;if(!(W[1]||W[3])||!G||this.rules.inline.punctuation.exec(G)){let Y=[...W[0]].length-1,Z,X,J=Y,T=0,M=W[0][0],f=G===M,Q=M==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(Q.lastIndex=0,w=w.slice(-1*$.length+Y);(W=Q.exec(w))!==null;){if(Z=W[1]||W[2]||W[3]||W[4]||W[5]||W[6],!Z)continue;if(X=[...Z].length,W[3]||W[4]){J+=X;continue}else if(W[5]||W[6]){if(Y%3&&!((Y+X)%3)){T+=X;continue}if(f)break}if(J-=X,J>0)continue;X=Math.min(X,X+J+T);let N=[...W[0]][0].length,z=$.slice(0,Y+W.index+N+X);if(Math.min(Y,X)%2){let P=z.slice(1,-1);return{type:"em",raw:z,text:P,tokens:this.lexer.inlineTokens(P)}}let K=z.slice(2,-2);return{type:"strong",raw:z,text:K,tokens:this.lexer.inlineTokens(K)}}}}codespan($){let w=this.rules.inline.code.exec($);if(w){let G=w[2].replace(this.rules.other.newLineCharGlobal," "),W=this.rules.other.nonSpaceChar.test(G),Y=this.rules.other.startingSpaceChar.test(G)&&this.rules.other.endingSpaceChar.test(G);return W&&Y&&(G=G.substring(1,G.length-1)),{type:"codespan",raw:w[0],text:G}}}br($){let w=this.rules.inline.br.exec($);if(w)return{type:"br",raw:w[0]}}del($,w,G=""){let W=this.rules.inline.delLDelim.exec($);if(!W)return;if(!W[1]||!G||this.rules.inline.punctuation.exec(G)){let Y=[...W[0]].length-1,Z,X,J=Y,T=this.rules.inline.delRDelim;for(T.lastIndex=0,w=w.slice(-1*$.length+Y);(W=T.exec(w))!==null;){if(Z=W[1]||W[2]||W[3]||W[4]||W[5]||W[6],!Z||(X=[...Z].length,X!==Y))continue;if(W[3]||W[4]){J+=X;continue}if(J-=X,J>0)continue;X=Math.min(X,X+J);let M=[...W[0]][0].length,f=$.slice(0,Y+W.index+M+X),Q=f.slice(Y,-Y);return{type:"del",raw:f,text:Q,tokens:this.lexer.inlineTokens(Q)}}}}autolink($){let w=this.rules.inline.autolink.exec($);if(w){let G,W;return w[2]==="@"?(G=w[1],W="mailto:"+G):(G=w[1],W=G),{type:"link",raw:w[0],text:G,href:W,tokens:[{type:"text",raw:G,text:G}]}}}url($){let w;if(w=this.rules.inline.url.exec($)){let G,W;if(w[2]==="@")G=w[0],W="mailto:"+G;else{let Y;do Y=w[0],w[0]=this.rules.inline._backpedal.exec(w[0])?.[0]??"";while(Y!==w[0]);G=w[0],w[1]==="www."?W="http://"+w[0]:W=w[0]}return{type:"link",raw:w[0],text:G,href:W,tokens:[{type:"text",raw:G,text:G}]}}}inlineText($){let w=this.rules.inline.text.exec($);if(w){let G=this.lexer.state.inRawBlock;return{type:"text",raw:w[0],text:w[0],escaped:G}}}},a0=class ${tokens;options;state;inlineQueue;tokenizer;constructor(w){this.tokens=[],this.tokens.links=Object.create(null),this.options=w||V$,this.options.tokenizer=this.options.tokenizer||new M6,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,linkEmitted:!1,top:!0};let G={other:V0,block:J6.normal,inline:U4.normal};this.options.pedantic?(G.block=J6.pedantic,G.inline=U4.pedantic):this.options.gfm&&(G.block=J6.gfm,this.options.breaks?G.inline=U4.breaks:G.inline=U4.gfm),this.tokenizer.rules=G}static get rules(){return{block:J6,inline:U4}}static lex(w,G){return new $(G).lex(w)}static lexInline(w,G){return new $(G).inlineTokens(w)}lex(w){w=w.replace(V0.carriageReturn,`
97
- `),this.blockTokens(w,this.tokens);for(let G=0;G<this.inlineQueue.length;G++){let W=this.inlineQueue[G];this.inlineTokens(W.src,W.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(w,G=[],W=!1){this.tokenizer.lexer=this,this.options.pedantic&&(w=w.replace(V0.tabCharGlobal," ").replace(V0.spaceLine,""));let Y=1/0;for(;w;){if(w.length<Y)Y=w.length;else{this.infiniteLoopError(w.charCodeAt(0));break}let Z;if(this.options.extensions?.block?.some((J)=>(Z=J.call({lexer:this},w,G))?(w=w.substring(Z.raw.length),G.push(Z),!0):!1))continue;if(Z=this.tokenizer.space(w)){w=w.substring(Z.raw.length);let J=G.at(-1);Z.raw.length===1&&J!==void 0?J.raw+=`
98
- `:G.push(Z);continue}if(Z=this.tokenizer.code(w)){w=w.substring(Z.raw.length);let J=G.at(-1);J?.type==="paragraph"||J?.type==="text"?(J.raw+=(J.raw.endsWith(`
236
+ `?w[1].slice(0,-1):w[1];return{type:"paragraph",raw:w[0],text:G,tokens:this.lexer.inline(G)}}}text($){let w=this.rules.block.text.exec($);if(w)return{type:"text",raw:w[0],text:w[0],tokens:this.lexer.inline(w[0])}}escape($){let w=this.rules.inline.escape.exec($);if(w)return{type:"escape",raw:w[0],text:w[1]}}tag($){let w=this.rules.inline.tag.exec($);if(w)return!this.lexer.state.inLink&&this.rules.other.startATag.test(w[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(w[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(w[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(w[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:w[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:w[0]}}link($){let w=this.rules.inline.link.exec($);if(w){let G=w[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(G)){if(!this.rules.other.endAngleBracket.test(G))return;let Y=q1(G.slice(0,-1),"\\");if((G.length-Y.length)%2===0)return}else{let Y=$x(w[2],"()");if(Y===-2)return;if(Y>-1){let J=(w[0].indexOf("!")===0?5:4)+w[1].length+Y;w[2]=w[2].substring(0,Y),w[0]=w[0].substring(0,J).trim(),w[3]=""}}let Z=w[2],X="";if(this.options.pedantic){let Y=this.rules.other.pedanticHrefTitle.exec(Z);Y&&(Z=Y[1],X=Y[3])}else X=w[3]?w[3].slice(1,-1):"";return Z=Z.trim(),this.rules.other.startAngleBracket.test(Z)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(G)?Z=Z.slice(1):Z=Z.slice(1,-1)),wB(w,{href:Z&&Z.replace(this.rules.inline.anyPunctuation,"$1"),title:X&&X.replace(this.rules.inline.anyPunctuation,"$1")},w[0],this.lexer,this.rules)}}reflink($,w){let G;if((G=this.rules.inline.reflink.exec($))||(G=this.rules.inline.nolink.exec($))){let Z=(G[2]||G[1]).replace(this.rules.other.multipleSpaceGlobal," "),X=w[Z.toLowerCase()];if(!X){let Y=G[0].charAt(0);return{type:"text",raw:Y,text:Y}}return wB(G,X,G[0],this.lexer,this.rules)}}emStrong($,w,G=""){let Z=this.rules.inline.emStrongLDelim.exec($);if(!Z||!Z[1]&&!Z[2]&&!Z[3]&&!Z[4]||Z[4]&&G.match(this.rules.other.unicodeAlphaNumeric))return;if(!(Z[1]||Z[3])||!G||this.rules.inline.punctuation.exec(G)){let X=[...Z[0]].length-1,Y,J,W=X,T=0,Q=Z[0][0],z=G===Q,M=Q==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(M.lastIndex=0,w=w.slice(-1*$.length+X);(Z=M.exec(w))!==null;){if(Y=Z[1]||Z[2]||Z[3]||Z[4]||Z[5]||Z[6],!Y)continue;if(J=[...Y].length,Z[3]||Z[4]){W+=J;continue}else if(Z[5]||Z[6]){if(X%3&&!((X+J)%3)){T+=J;continue}if(z)break}if(W-=J,W>0)continue;J=Math.min(J,J+W+T);let P=[...Z[0]][0].length,q=$.slice(0,X+Z.index+P+J);if(Math.min(X,J)%2){let B=q.slice(1,-1);return{type:"em",raw:q,text:B,tokens:this.lexer.inlineTokens(B)}}let N=q.slice(2,-2);return{type:"strong",raw:q,text:N,tokens:this.lexer.inlineTokens(N)}}}}codespan($){let w=this.rules.inline.code.exec($);if(w){let G=w[2].replace(this.rules.other.newLineCharGlobal," "),Z=this.rules.other.nonSpaceChar.test(G),X=this.rules.other.startingSpaceChar.test(G)&&this.rules.other.endingSpaceChar.test(G);return Z&&X&&(G=G.substring(1,G.length-1)),{type:"codespan",raw:w[0],text:G}}}br($){let w=this.rules.inline.br.exec($);if(w)return{type:"br",raw:w[0]}}del($,w,G=""){let Z=this.rules.inline.delLDelim.exec($);if(!Z)return;if(!Z[1]||!G||this.rules.inline.punctuation.exec(G)){let X=[...Z[0]].length-1,Y,J,W=X,T=this.rules.inline.delRDelim;for(T.lastIndex=0,w=w.slice(-1*$.length+X);(Z=T.exec(w))!==null;){if(Y=Z[1]||Z[2]||Z[3]||Z[4]||Z[5]||Z[6],!Y||(J=[...Y].length,J!==X))continue;if(Z[3]||Z[4]){W+=J;continue}if(W-=J,W>0)continue;J=Math.min(J,J+W);let Q=[...Z[0]][0].length,z=$.slice(0,X+Z.index+Q+J),M=z.slice(X,-X);return{type:"del",raw:z,text:M,tokens:this.lexer.inlineTokens(M)}}}}autolink($){let w=this.rules.inline.autolink.exec($);if(w){let G,Z;return w[2]==="@"?(G=w[1],Z="mailto:"+G):(G=w[1],Z=G),{type:"link",raw:w[0],text:G,href:Z,tokens:[{type:"text",raw:G,text:G}]}}}url($){let w;if(w=this.rules.inline.url.exec($)){let G,Z;if(w[2]==="@")G=w[0],Z="mailto:"+G;else{let X;do X=w[0],w[0]=this.rules.inline._backpedal.exec(w[0])?.[0]??"";while(X!==w[0]);G=w[0],w[1]==="www."?Z="http://"+w[0]:Z=w[0]}return{type:"link",raw:w[0],text:G,href:Z,tokens:[{type:"text",raw:G,text:G}]}}}inlineText($){let w=this.rules.inline.text.exec($);if(w){let G=this.lexer.state.inRawBlock;return{type:"text",raw:w[0],text:w[0],escaped:G}}}},J$=class ${tokens;options;state;inlineQueue;tokenizer;constructor(w){this.tokens=[],this.tokens.links=Object.create(null),this.options=w||s1,this.options.tokenizer=this.options.tokenizer||new PG,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,linkEmitted:!1,top:!0};let G={other:f0,block:zG.normal,inline:_9.normal};this.options.pedantic?(G.block=zG.pedantic,G.inline=_9.pedantic):this.options.gfm&&(G.block=zG.gfm,this.options.breaks?G.inline=_9.breaks:G.inline=_9.gfm),this.tokenizer.rules=G}static get rules(){return{block:zG,inline:_9}}static lex(w,G){return new $(G).lex(w)}static lexInline(w,G){return new $(G).inlineTokens(w)}lex(w){w=w.replace(f0.carriageReturn,`
237
+ `),this.blockTokens(w,this.tokens);for(let G=0;G<this.inlineQueue.length;G++){let Z=this.inlineQueue[G];this.inlineTokens(Z.src,Z.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(w,G=[],Z=!1){this.tokenizer.lexer=this,this.options.pedantic&&(w=w.replace(f0.tabCharGlobal," ").replace(f0.spaceLine,""));let X=1/0;for(;w;){if(w.length<X)X=w.length;else{this.infiniteLoopError(w.charCodeAt(0));break}let Y;if(this.options.extensions?.block?.some((W)=>(Y=W.call({lexer:this},w,G))?(w=w.substring(Y.raw.length),G.push(Y),!0):!1))continue;if(Y=this.tokenizer.space(w)){w=w.substring(Y.raw.length);let W=G.at(-1);Y.raw.length===1&&W!==void 0?W.raw+=`
238
+ `:G.push(Y);continue}if(Y=this.tokenizer.code(w)){w=w.substring(Y.raw.length);let W=G.at(-1);W?.type==="paragraph"||W?.type==="text"?(W.raw+=(W.raw.endsWith(`
99
239
  `)?"":`
100
- `)+Z.raw,J.text+=`
101
- `+Z.text,this.inlineQueue.at(-1).src=J.text):G.push(Z);continue}if(Z=this.tokenizer.fences(w)){w=w.substring(Z.raw.length),G.push(Z);continue}if(Z=this.tokenizer.heading(w)){w=w.substring(Z.raw.length),G.push(Z);continue}if(Z=this.tokenizer.hr(w)){w=w.substring(Z.raw.length),G.push(Z);continue}if(Z=this.tokenizer.blockquote(w)){w=w.substring(Z.raw.length),G.push(Z);continue}if(Z=this.tokenizer.list(w)){w=w.substring(Z.raw.length),G.push(Z);continue}if(Z=this.tokenizer.html(w)){w=w.substring(Z.raw.length),G.push(Z);continue}if(Z=this.tokenizer.def(w)){w=w.substring(Z.raw.length);let J=G.at(-1);J?.type==="paragraph"||J?.type==="text"?(J.raw+=(J.raw.endsWith(`
240
+ `)+Y.raw,W.text+=`
241
+ `+Y.text,this.inlineQueue.at(-1).src=W.text):G.push(Y);continue}if(Y=this.tokenizer.fences(w)){w=w.substring(Y.raw.length),G.push(Y);continue}if(Y=this.tokenizer.heading(w)){w=w.substring(Y.raw.length),G.push(Y);continue}if(Y=this.tokenizer.hr(w)){w=w.substring(Y.raw.length),G.push(Y);continue}if(Y=this.tokenizer.blockquote(w)){w=w.substring(Y.raw.length),G.push(Y);continue}if(Y=this.tokenizer.list(w)){w=w.substring(Y.raw.length),G.push(Y);continue}if(Y=this.tokenizer.html(w)){w=w.substring(Y.raw.length),G.push(Y);continue}if(Y=this.tokenizer.def(w)){w=w.substring(Y.raw.length);let W=G.at(-1);W?.type==="paragraph"||W?.type==="text"?(W.raw+=(W.raw.endsWith(`
102
242
  `)?"":`
103
- `)+Z.raw,J.text+=`
104
- `+Z.raw,this.inlineQueue.at(-1).src=J.text):this.tokens.links[Z.tag]||(this.tokens.links[Z.tag]={href:Z.href,title:Z.title},G.push(Z));continue}if(Z=this.tokenizer.table(w)){w=w.substring(Z.raw.length),G.push(Z);continue}if(Z=this.tokenizer.lheading(w)){w=w.substring(Z.raw.length),G.push(Z);continue}let X=w;if(this.options.extensions?.startBlock){let J=1/0,T=w.slice(1),M;this.options.extensions.startBlock.forEach((f)=>{M=f.call({lexer:this},T),typeof M=="number"&&M>=0&&(J=Math.min(J,M))}),J<1/0&&J>=0&&(X=w.substring(0,J+1))}if(this.state.top&&(Z=this.tokenizer.paragraph(X))){let J=G.at(-1);W&&J?.type==="paragraph"?(J.raw+=(J.raw.endsWith(`
243
+ `)+Y.raw,W.text+=`
244
+ `+Y.raw,this.inlineQueue.at(-1).src=W.text):this.tokens.links[Y.tag]||(this.tokens.links[Y.tag]={href:Y.href,title:Y.title},G.push(Y));continue}if(Y=this.tokenizer.table(w)){w=w.substring(Y.raw.length),G.push(Y);continue}if(Y=this.tokenizer.lheading(w)){w=w.substring(Y.raw.length),G.push(Y);continue}let J=w;if(this.options.extensions?.startBlock){let W=1/0,T=w.slice(1),Q;this.options.extensions.startBlock.forEach((z)=>{Q=z.call({lexer:this},T),typeof Q=="number"&&Q>=0&&(W=Math.min(W,Q))}),W<1/0&&W>=0&&(J=w.substring(0,W+1))}if(this.state.top&&(Y=this.tokenizer.paragraph(J))){let W=G.at(-1);Z&&W?.type==="paragraph"?(W.raw+=(W.raw.endsWith(`
105
245
  `)?"":`
106
- `)+Z.raw,J.text+=`
107
- `+Z.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=J.text):G.push(Z),W=X.length!==w.length,w=w.substring(Z.raw.length);continue}if(Z=this.tokenizer.text(w)){w=w.substring(Z.raw.length);let J=G.at(-1);J?.type==="text"?(J.raw+=(J.raw.endsWith(`
246
+ `)+Y.raw,W.text+=`
247
+ `+Y.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=W.text):G.push(Y),Z=J.length!==w.length,w=w.substring(Y.raw.length);continue}if(Y=this.tokenizer.text(w)){w=w.substring(Y.raw.length);let W=G.at(-1);W?.type==="text"?(W.raw+=(W.raw.endsWith(`
108
248
  `)?"":`
109
- `)+Z.raw,J.text+=`
110
- `+Z.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=J.text):G.push(Z);continue}if(w){this.infiniteLoopError(w.charCodeAt(0));break}}return this.state.top=!0,G}inline(w,G=[]){return this.inlineQueue.push({src:w,tokens:G}),G}linkInText(w){if(!w.includes("["))return!1;let G=this.tokenizer.rules.inline.link;for(let W of w.matchAll(this.tokenizer.rules.inline.blockSkip))if(G.test(W[0])&&w.charAt(W.index-1)!=="!")return!0;for(let W of w.matchAll(this.tokenizer.rules.inline.reflinkSearch)){let Y=W[0],Z=Y.lastIndexOf("[");if(!(Y.charAt(0)==="!"||!Object.hasOwn(this.tokens.links,Y.slice(Z+1,-1)))&&!(Z>1&&this.linkInText(Y.slice(1,Z-1))))return!0}return!1}inlineTokens(w,G=[]){this.tokenizer.lexer=this;let W=w;if(this.tokens.links&&w.includes("[")){let J=this.tokenizer.rules.inline.reflinkSearch,T=(M)=>{let f=M.lastIndexOf("[");if(!Object.hasOwn(this.tokens.links,M.slice(f+1,-1)))return M;if(f>1&&M.charAt(0)!=="!"){let Q=M.slice(1,f-1);if(this.linkInText(Q))return"["+Q.replace(J,T)+"]["+"a".repeat(M.length-f-2)+"]"}return"["+"a".repeat(M.length-2)+"]"};W=W.replace(J,T)}W=W.replace(this.tokenizer.rules.inline.anyPunctuation,(J)=>"+".repeat(J.length)),W=W.replace(this.tokenizer.rules.inline.blockSkip,(J,T,M)=>{let f=M?M.length:0;return J.slice(0,f)+"["+"a".repeat(J.length-f-2)+"]"}),W=this.options.hooks?.emStrongMask?.call({lexer:this},W)??W;let Y=!1,Z="",X=1/0;for(;w;){if(w.length<X)X=w.length;else{this.infiniteLoopError(w.charCodeAt(0));break}Y||(Z=""),Y=!1;let J;if(this.options.extensions?.inline?.some((M)=>(J=M.call({lexer:this},w,G))?(w=w.substring(J.raw.length),G.push(J),!0):!1))continue;if(J=this.tokenizer.escape(w)){w=w.substring(J.raw.length),G.push(J);continue}if(J=this.tokenizer.tag(w)){w=w.substring(J.raw.length),G.push(J);continue}if(J=this.tokenizer.link(w)){w=w.substring(J.raw.length),G.push(J);continue}if(J=this.tokenizer.reflink(w,this.tokens.links)){w=w.substring(J.raw.length);let M=G.at(-1);J.type==="text"&&M?.type==="text"?(M.raw+=J.raw,M.text+=J.text):G.push(J);continue}if(J=this.tokenizer.emStrong(w,W,Z)){w=w.substring(J.raw.length),G.push(J);continue}if(J=this.tokenizer.codespan(w)){w=w.substring(J.raw.length),G.push(J);continue}if(J=this.tokenizer.br(w)){w=w.substring(J.raw.length),G.push(J);continue}if(J=this.tokenizer.del(w,W,Z)){w=w.substring(J.raw.length),G.push(J);continue}if(J=this.tokenizer.autolink(w)){w=w.substring(J.raw.length),G.push(J);continue}if(!this.state.inLink&&(J=this.tokenizer.url(w))){w=w.substring(J.raw.length),G.push(J);continue}let T=w;if(this.options.extensions?.startInline){let M=1/0,f=w.slice(1),Q;this.options.extensions.startInline.forEach((N)=>{Q=N.call({lexer:this},f),typeof Q=="number"&&Q>=0&&(M=Math.min(M,Q))}),M<1/0&&M>=0&&(T=w.substring(0,M+1))}if(J=this.tokenizer.inlineText(T)){w=w.substring(J.raw.length),J.raw.slice(-1)!=="_"&&(Z=J.raw.slice(-1)),Y=!0;let M=G.at(-1);M?.type==="text"?(M.raw+=J.raw,M.text+=J.text):G.push(J);continue}if(w){this.infiniteLoopError(w.charCodeAt(0));break}}return G}infiniteLoopError(w){let G="Infinite loop on byte: "+w;if(this.options.silent)console.error(G);else throw Error(G)}},f6=class{options;parser;constructor($){this.options=$||V$}space($){return""}code({text:$,lang:w,escaped:G}){let W=(w||"").match(V0.notSpaceStart)?.[0],Y=$.replace(V0.endingNewline,"")+`
111
- `;return W?'<pre><code class="language-'+T1(W)+'">'+(G?Y:T1(Y,!0))+`</code></pre>
112
- `:"<pre><code>"+(G?Y:T1(Y,!0))+`</code></pre>
249
+ `)+Y.raw,W.text+=`
250
+ `+Y.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=W.text):G.push(Y);continue}if(w){this.infiniteLoopError(w.charCodeAt(0));break}}return this.state.top=!0,G}inline(w,G=[]){return this.inlineQueue.push({src:w,tokens:G}),G}linkInText(w){if(!w.includes("["))return!1;let G=this.tokenizer.rules.inline.link;for(let Z of w.matchAll(this.tokenizer.rules.inline.blockSkip))if(G.test(Z[0])&&w.charAt(Z.index-1)!=="!")return!0;for(let Z of w.matchAll(this.tokenizer.rules.inline.reflinkSearch)){let X=Z[0],Y=X.lastIndexOf("[");if(!(X.charAt(0)==="!"||!Object.hasOwn(this.tokens.links,X.slice(Y+1,-1)))&&!(Y>1&&this.linkInText(X.slice(1,Y-1))))return!0}return!1}inlineTokens(w,G=[]){this.tokenizer.lexer=this;let Z=w;if(this.tokens.links&&w.includes("[")){let W=this.tokenizer.rules.inline.reflinkSearch,T=(Q)=>{let z=Q.lastIndexOf("[");if(!Object.hasOwn(this.tokens.links,Q.slice(z+1,-1)))return Q;if(z>1&&Q.charAt(0)!=="!"){let M=Q.slice(1,z-1);if(this.linkInText(M))return"["+M.replace(W,T)+"]["+"a".repeat(Q.length-z-2)+"]"}return"["+"a".repeat(Q.length-2)+"]"};Z=Z.replace(W,T)}Z=Z.replace(this.tokenizer.rules.inline.anyPunctuation,(W)=>"+".repeat(W.length)),Z=Z.replace(this.tokenizer.rules.inline.blockSkip,(W,T,Q)=>{let z=Q?Q.length:0;return W.slice(0,z)+"["+"a".repeat(W.length-z-2)+"]"}),Z=this.options.hooks?.emStrongMask?.call({lexer:this},Z)??Z;let X=!1,Y="",J=1/0;for(;w;){if(w.length<J)J=w.length;else{this.infiniteLoopError(w.charCodeAt(0));break}X||(Y=""),X=!1;let W;if(this.options.extensions?.inline?.some((Q)=>(W=Q.call({lexer:this},w,G))?(w=w.substring(W.raw.length),G.push(W),!0):!1))continue;if(W=this.tokenizer.escape(w)){w=w.substring(W.raw.length),G.push(W);continue}if(W=this.tokenizer.tag(w)){w=w.substring(W.raw.length),G.push(W);continue}if(W=this.tokenizer.link(w)){w=w.substring(W.raw.length),G.push(W);continue}if(W=this.tokenizer.reflink(w,this.tokens.links)){w=w.substring(W.raw.length);let Q=G.at(-1);W.type==="text"&&Q?.type==="text"?(Q.raw+=W.raw,Q.text+=W.text):G.push(W);continue}if(W=this.tokenizer.emStrong(w,Z,Y)){w=w.substring(W.raw.length),G.push(W);continue}if(W=this.tokenizer.codespan(w)){w=w.substring(W.raw.length),G.push(W);continue}if(W=this.tokenizer.br(w)){w=w.substring(W.raw.length),G.push(W);continue}if(W=this.tokenizer.del(w,Z,Y)){w=w.substring(W.raw.length),G.push(W);continue}if(W=this.tokenizer.autolink(w)){w=w.substring(W.raw.length),G.push(W);continue}if(!this.state.inLink&&(W=this.tokenizer.url(w))){w=w.substring(W.raw.length),G.push(W);continue}let T=w;if(this.options.extensions?.startInline){let Q=1/0,z=w.slice(1),M;this.options.extensions.startInline.forEach((P)=>{M=P.call({lexer:this},z),typeof M=="number"&&M>=0&&(Q=Math.min(Q,M))}),Q<1/0&&Q>=0&&(T=w.substring(0,Q+1))}if(W=this.tokenizer.inlineText(T)){w=w.substring(W.raw.length),W.raw.slice(-1)!=="_"&&(Y=W.raw.slice(-1)),X=!0;let Q=G.at(-1);Q?.type==="text"?(Q.raw+=W.raw,Q.text+=W.text):G.push(W);continue}if(w){this.infiniteLoopError(w.charCodeAt(0));break}}return G}infiniteLoopError(w){let G="Infinite loop on byte: "+w;if(this.options.silent)console.error(G);else throw Error(G)}},qG=class{options;parser;constructor($){this.options=$||s1}space($){return""}code({text:$,lang:w,escaped:G}){let Z=(w||"").match(f0.notSpaceStart)?.[0],X=$.replace(f0.endingNewline,"")+`
251
+ `;return Z?'<pre><code class="language-'+U$(Z)+'">'+(G?X:U$(X,!0))+`</code></pre>
252
+ `:"<pre><code>"+(G?X:U$(X,!0))+`</code></pre>
113
253
  `}blockquote({tokens:$}){return`<blockquote>
114
254
  ${this.parser.parse($)}</blockquote>
115
255
  `}html({text:$}){return $}def($){return""}heading({tokens:$,depth:w}){return`<h${w}>${this.parser.parseInline($)}</h${w}>
116
256
  `}hr($){return`<hr>
117
- `}list($){let{ordered:w,start:G}=$,W="";for(let X=0;X<$.items.length;X++){let J=$.items[X];W+=this.listitem(J)}let Y=w?"ol":"ul",Z=w&&G!==1?' start="'+G+'"':"";return"<"+Y+Z+`>
118
- `+W+"</"+Y+`>
257
+ `}list($){let{ordered:w,start:G}=$,Z="";for(let J=0;J<$.items.length;J++){let W=$.items[J];Z+=this.listitem(W)}let X=w?"ol":"ul",Y=w&&G!==1?' start="'+G+'"':"";return"<"+X+Y+`>
258
+ `+Z+"</"+X+`>
119
259
  `}listitem($){return`<li>${this.parser.parse($.tokens)}</li>
120
260
  `}checkbox({checked:$}){return"<input "+($?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:$}){return`<p>${this.parser.parseInline($)}</p>
121
- `}table($){let w="",G="";for(let Y=0;Y<$.header.length;Y++)G+=this.tablecell($.header[Y]);w+=this.tablerow({text:G});let W="";for(let Y=0;Y<$.rows.length;Y++){let Z=$.rows[Y];G="";for(let X=0;X<Z.length;X++)G+=this.tablecell(Z[X]);W+=this.tablerow({text:G})}return W&&(W=`<tbody>${W}</tbody>`),`<table>
261
+ `}table($){let w="",G="";for(let X=0;X<$.header.length;X++)G+=this.tablecell($.header[X]);w+=this.tablerow({text:G});let Z="";for(let X=0;X<$.rows.length;X++){let Y=$.rows[X];G="";for(let J=0;J<Y.length;J++)G+=this.tablecell(Y[J]);Z+=this.tablerow({text:G})}return Z&&(Z=`<tbody>${Z}</tbody>`),`<table>
122
262
  <thead>
123
263
  `+w+`</thead>
124
- `+W+`</table>
264
+ `+Z+`</table>
125
265
  `}tablerow({text:$}){return`<tr>
126
266
  ${$}</tr>
127
267
  `}tablecell($){let w=this.parser.parseInline($.tokens),G=$.header?"th":"td";return($.align?`<${G} align="${$.align}">`:`<${G}>`)+w+`</${G}>
128
- `}strong({tokens:$}){return`<strong>${this.parser.parseInline($)}</strong>`}em({tokens:$}){return`<em>${this.parser.parseInline($)}</em>`}codespan({text:$}){return`<code>${T1($,!0)}</code>`}br($){return"<br>"}del({tokens:$}){return`<del>${this.parser.parseInline($)}</del>`}link({href:$,title:w,tokens:G}){let W=this.parser.parseInline(G),Y=ET($);if(Y===null)return W;$=Y;let Z='<a href="'+$+'"';return w&&(Z+=' title="'+T1(w)+'"'),Z+=">"+W+"</a>",Z}image({href:$,title:w,text:G,tokens:W}){W&&(G=this.parser.parseInline(W,this.parser.textRenderer));let Y=ET($);if(Y===null)return T1(G);$=Y;let Z=`<img src="${$}" alt="${T1(G)}"`;return w&&(Z+=` title="${T1(w)}"`),Z+=">",Z}text($){return"tokens"in $&&$.tokens?this.parser.parseInline($.tokens):("escaped"in $)&&$.escaped?$.text:T1($.text)}},ZW=class{strong({text:$}){return $}em({text:$}){return $}codespan({text:$}){return $}del({text:$}){return $}html({text:$}){return $}text({text:$}){return $}link({text:$}){return""+$}image({text:$}){return""+$}br(){return""}checkbox({raw:$}){return $}},o0=class ${options;renderer;textRenderer;constructor(w){this.options=w||V$,this.options.renderer=this.options.renderer||new f6,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new ZW}static parse(w,G){return new $(G).parse(w)}static parseInline(w,G){return new $(G).parseInline(w)}parse(w){this.renderer.parser=this;let G="";for(let W=0;W<w.length;W++){let Y=w[W];if(this.options.extensions?.renderers?.[Y.type]){let X=Y,J=this.options.extensions.renderers[X.type].call({parser:this},X);if(J!==!1||!["space","hr","heading","code","table","blockquote","list","checkbox","html","def","paragraph","text"].includes(X.type)){G+=J||"";continue}}let Z=Y;switch(Z.type){case"space":{G+=this.renderer.space(Z);break}case"hr":{G+=this.renderer.hr(Z);break}case"heading":{G+=this.renderer.heading(Z);break}case"code":{G+=this.renderer.code(Z);break}case"table":{G+=this.renderer.table(Z);break}case"blockquote":{G+=this.renderer.blockquote(Z);break}case"list":{G+=this.renderer.list(Z);break}case"checkbox":{G+=this.renderer.checkbox(Z);break}case"html":{G+=this.renderer.html(Z);break}case"def":{G+=this.renderer.def(Z);break}case"paragraph":{G+=this.renderer.paragraph(Z);break}case"text":{G+=this.renderer.text(Z);break}default:{let X='Token with "'+Z.type+'" type was not found.';if(this.options.silent)return console.error(X),"";throw Error(X)}}}return G}parseInline(w,G=this.renderer){this.renderer.parser=this;let W="";for(let Y=0;Y<w.length;Y++){let Z=w[Y];if(this.options.extensions?.renderers?.[Z.type]){let J=this.options.extensions.renderers[Z.type].call({parser:this},Z);if(J!==!1||!["escape","html","link","image","checkbox","strong","em","codespan","br","del","text"].includes(Z.type)){W+=J||"";continue}}let X=Z;switch(X.type){case"escape":{W+=G.text(X);break}case"html":{W+=G.html(X);break}case"link":{W+=G.link(X);break}case"image":{W+=G.image(X);break}case"checkbox":{W+=G.checkbox(X);break}case"strong":{W+=G.strong(X);break}case"em":{W+=G.em(X);break}case"codespan":{W+=G.codespan(X);break}case"br":{W+=G.br(X);break}case"del":{W+=G.del(X);break}case"text":{W+=G.text(X);break}default:{let J='Token with "'+X.type+'" type was not found.';if(this.options.silent)return console.error(J),"";throw Error(J)}}}return W}},H4=class{options;block;constructor($){this.options=$||V$}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess($){return $}postprocess($){return $}processAllTokens($){return $}emStrongMask($){return $}provideLexer($=this.block){return $?a0.lex:a0.lexInline}provideParser($=this.block){return $?o0.parse:o0.parseInline}},BF=class{defaults=oG();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=o0;Renderer=f6;TextRenderer=ZW;Lexer=a0;Tokenizer=M6;Hooks=H4;constructor(...$){this.use(...$)}walkTokens($,w){let G=[];for(let W of $)switch(G=G.concat(w.call(this,W)),W.type){case"table":{let Y=W;for(let Z of Y.header)G=G.concat(this.walkTokens(Z.tokens,w));for(let Z of Y.rows)for(let X of Z)G=G.concat(this.walkTokens(X.tokens,w));break}case"list":{let Y=W;G=G.concat(this.walkTokens(Y.items,w));break}default:{let Y=W;this.defaults.extensions?.childTokens?.[Y.type]?this.defaults.extensions.childTokens[Y.type].forEach((Z)=>{let X=Y[Z].flat(1/0);G=G.concat(this.walkTokens(X,w))}):Y.tokens&&(G=G.concat(this.walkTokens(Y.tokens,w)))}}return G}use(...$){let w=this.defaults.extensions||{renderers:{},childTokens:{}};return $.forEach((G)=>{let W={...G};if(W.async=this.defaults.async||W.async||!1,G.extensions&&(G.extensions.forEach((Y)=>{if(!Y.name)throw Error("extension name required");if("renderer"in Y){let Z=w.renderers[Y.name];Z?w.renderers[Y.name]=function(...X){let J=Y.renderer.apply(this,X);return J===!1&&(J=Z.apply(this,X)),J}:w.renderers[Y.name]=Y.renderer}if("tokenizer"in Y){if(!Y.level||Y.level!=="block"&&Y.level!=="inline")throw Error("extension level must be 'block' or 'inline'");let Z=w[Y.level];Z?Z.unshift(Y.tokenizer):w[Y.level]=[Y.tokenizer],Y.start&&(Y.level==="block"?w.startBlock?w.startBlock.push(Y.start):w.startBlock=[Y.start]:Y.level==="inline"&&(w.startInline?w.startInline.push(Y.start):w.startInline=[Y.start]))}"childTokens"in Y&&Y.childTokens&&(w.childTokens[Y.name]=Y.childTokens)}),W.extensions=w),G.renderer){let Y=this.defaults.renderer||new f6(this.defaults);for(let Z in G.renderer){if(!(Z in Y))throw Error(`renderer '${Z}' does not exist`);if(["options","parser"].includes(Z))continue;let X=Z,J=G.renderer[X],T=Y[X];Y[X]=(...M)=>{let f=J.apply(Y,M);return f===!1&&(f=T.apply(Y,M)),f||""}}W.renderer=Y}if(G.tokenizer){let Y=this.defaults.tokenizer||new M6(this.defaults);for(let Z in G.tokenizer){if(!(Z in Y))throw Error(`tokenizer '${Z}' does not exist`);if(["options","rules","lexer"].includes(Z))continue;let X=Z,J=G.tokenizer[X],T=Y[X];Y[X]=(...M)=>{let f=J.apply(Y,M);return f===!1&&(f=T.apply(Y,M)),f}}W.tokenizer=Y}if(G.hooks){let Y=this.defaults.hooks||new H4;for(let Z in G.hooks){if(!(Z in Y))throw Error(`hook '${Z}' does not exist`);if(["options","block"].includes(Z))continue;let X=Z,J=G.hooks[X],T=Y[X];H4.passThroughHooks.has(Z)?Y[X]=(M)=>{if(this.defaults.async&&H4.passThroughHooksRespectAsync.has(Z))return(async()=>{let Q=await J.call(Y,M);return T.call(Y,Q)})();let f=J.call(Y,M);return T.call(Y,f)}:Y[X]=(...M)=>{if(this.defaults.async)return(async()=>{let Q=await J.apply(Y,M);return Q===!1&&(Q=await T.apply(Y,M)),Q})();let f=J.apply(Y,M);return f===!1&&(f=T.apply(Y,M)),f}}W.hooks=Y}if(G.walkTokens){let Y=this.defaults.walkTokens,Z=G.walkTokens;W.walkTokens=function(X){let J=[];return J.push(Z.call(this,X)),Y&&(J=J.concat(Y.call(this,X))),J}}this.defaults={...this.defaults,...W}}),this}setOptions($){return this.defaults={...this.defaults,...$},this}lexer($,w){return a0.lex($,w??this.defaults)}parser($,w){return o0.parse($,w??this.defaults)}parseMarkdown($){return(w,G)=>{let W={...G},Y={...this.defaults,...W},Z=this.onError(!!Y.silent,!!Y.async);if(this.defaults.async===!0&&W.async===!1)return Z(Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof w>"u"||w===null)return Z(Error("marked(): input parameter is undefined or null"));if(typeof w!="string")return Z(Error("marked(): input parameter is of type "+Object.prototype.toString.call(w)+", string expected"));if(Y.hooks&&(Y.hooks.options=Y,Y.hooks.block=$),Y.async)return(async()=>{let X=Y.hooks?await Y.hooks.preprocess(w):w,J=await(Y.hooks?await Y.hooks.provideLexer($):$?a0.lex:a0.lexInline)(X,Y),T=Y.hooks?await Y.hooks.processAllTokens(J):J;Y.walkTokens&&await Promise.all(this.walkTokens(T,Y.walkTokens));let M=await(Y.hooks?await Y.hooks.provideParser($):$?o0.parse:o0.parseInline)(T,Y);return Y.hooks?await Y.hooks.postprocess(M):M})().catch(Z);try{Y.hooks&&(w=Y.hooks.preprocess(w));let X=(Y.hooks?Y.hooks.provideLexer($):$?a0.lex:a0.lexInline)(w,Y);Y.hooks&&(X=Y.hooks.processAllTokens(X)),Y.walkTokens&&this.walkTokens(X,Y.walkTokens);let J=(Y.hooks?Y.hooks.provideParser($):$?o0.parse:o0.parseInline)(X,Y);return Y.hooks&&(J=Y.hooks.postprocess(J)),J}catch(X){return Z(X)}}}onError($,w){return(G)=>{if(G.message+=`
129
- Please report this to https://github.com/markedjs/marked.`,$){let W="<p>An error occurred:</p><pre>"+T1(G.message+"",!0)+"</pre>";return w?Promise.resolve(W):W}if(w)return Promise.reject(G);throw G}}},B$=new BF;function t($,w){return B$.parse($,w)}t.options=t.setOptions=function($){return B$.setOptions($),t.defaults=B$.defaults,OT(t.defaults),t};t.getDefaults=oG;t.defaults=V$;function VF(...$){return B$.use(...$),t.defaults=B$.defaults,OT(t.defaults),t}t.use=VF;t.walkTokens=function($,w){return B$.walkTokens($,w)};t.parseInline=B$.parseInline;t.Parser=o0;t.parser=o0.parse;t.Renderer=f6;t.TextRenderer=ZW;t.Lexer=a0;t.lexer=a0.lex;t.Tokenizer=M6;t.Hooks=H4;t.parse=t;var{options:Wj,setOptions:Yj,walkTokens:Zj,parseInline:Xj}=t;var Jj=o0.parse,Tj=a0.lex;var e0=c$(X6(),1);var D4=c$(X6(),1);import{stripVTControlCharacters as FF}from"node:util";import{stripVTControlCharacters as qF}from"node:util";var EF=new Intl.Segmenter(void 0,{granularity:"grapheme"}),UF=/\p{Mark}/u,HF=/\p{Extended_Pictographic}|\p{Regional_Indicator}|\u20e3/u;function Y0($){return Array.from(qF($)).filter((w)=>{let G=w.codePointAt(0)??0;return G===9||G===10||G>159||G>31&&G<127}).join("")}function XW($){let w=$.codePointAt(0)??0;if(w>=9472&&w<=9599)return 1;return w<=255?1:2}function H1($){return Array.from(EF.segment($),({segment:w})=>w)}function Jw($){if(!$)return 0;if(HF.test($)||$.includes("️"))return 2;return Array.from($).filter((G)=>!UF.test(G)&&G!=="‍"&&G!=="︎").reduce((G,W)=>Math.max(G,XW(W)),0)}function L4($){return H1($).reduce((w,G)=>w+Jw(G),0)}function Tw($,w,G="head"){if(w<=0)return"";if(L4($)<=w)return $;if(w===1)return"…";let W=H1($),Y=[],Z=1,X=G==="head"?W.map((J,T)=>T):W.map((J,T)=>W.length-T-1);for(let J of X){let T=W[J];if(T===void 0||Z+Jw(T)>w)break;if(G==="head")Y.push(T);else Y.unshift(T);Z+=Jw(T)}return G==="head"?`${Y.join("")}…`:`…${Y.join("")}`}var MW="\x1B",bT=`${MW}[0m`,OF=new RegExp(`^${MW}\\[[0-?]*[ -/]*[@-~]`);function xT($){return L4(FF($))}function _T($){let w=[],G=0,W="";while(G<$.length){let Y=$.slice(G).match(OF)?.[0];if(Y){if(Y.endsWith("m"))W=Y===`${MW}[m`||Y===bT?"":`${W}${Y}`;G+=Y.length;continue}let Z=$.codePointAt(G);if(Z===void 0)break;let X=String.fromCodePoint(Z);w.push({value:X,width:XW(X),state:W}),G+=X.length}return w}function JW($){return $.map((w)=>w.state?`${w.state}${w.value}${bT}`:w.value).join("")}function LF($,w){if($.length===0)return[""];let G=[],W=$;while(W.length>0){if(G.length>0){while(W[0]&&/\s/u.test(W[0].value))W=W.slice(1);if(W.length===0)break}let Y=0,Z=0,X=-1;while(Z<W.length){let J=W[Z];if(!J||Z>0&&Y+J.width>w)break;if(Y+=J.width,/\s/u.test(J.value))X=Z;if(Z+=1,Y>=w)break}if(Z>=W.length){G.push(JW(W));break}if(X>=0){G.push(JW(W.slice(0,X))),W=W.slice(X+1);while(W[0]&&/\s/u.test(W[0].value))W=W.slice(1);continue}G.push(JW(W.slice(0,Math.max(1,Z)))),W=W.slice(Math.max(1,Z))}return G.length>0?G:[""]}function DF($,w){let G=Math.max(1,w);return $.split(`
130
- `).flatMap((W)=>LF(_T(W),G))}function kF($){return $.some((w)=>_T(w).some((G)=>G.width>1))?2:1}function AF($){return Math.max(1,...$.flatMap((w)=>w.split(`
131
- `).map(xT)))}function SF($,w){let G=$.header.length,W=$.header.map((J,T)=>[J,...$.rows.map((M)=>M[T]??"")]),Y=W.map(kF),Z=W.map(AF),X=Math.max(Y.reduce((J,T)=>J+T,0),w-(3*G+1));while(Z.reduce((J,T)=>J+T,0)>X){let J=-1;for(let T=0;T<Z.length;T+=1){let M=Z[T]??0,f=Y[T]??1;if(M>f&&(J<0||M>(Z[J]??0)))J=T}if(J<0)break;Z[J]=(Z[J]??1)-1}return Z}function RF($,w,G){let W=Math.max(0,w-xT($)),Y=G==="right"?W:G==="center"?Math.floor(W/2):0;return`${" ".repeat(Y)}${$}${" ".repeat(W-Y)}`}function TW($,w,G,W){return D4.default.dim(`${$}${W.map((Y)=>"─".repeat(Y+2)).join(w)}${G}`)}function IT($,w,G){let W=G.map((Z,X)=>DF($[X]??"",Z)),Y=Math.max(1,...W.map((Z)=>Z.length));return Array.from({length:Y},(Z,X)=>{let J=G.map((T,M)=>RF(W[M]?.[X]??"",T,w[M]??"left"));return`${D4.default.dim("│")} ${J.join(` ${D4.default.dim("│")} `)} ${D4.default.dim("│")}`})}function gT($,w){if($.header.length===0)return"";let G=SF($,Math.max(1,w)),W=G.map((Z,X)=>$.align[X]??"left");return[TW("┌","┬","┐",G),...IT($.header,W,G),TW("├","┼","┤",G),...$.rows.flatMap((Z)=>IT(Z,W,G)),TW("└","┴","┘",G)].join(`
132
- `)}class k4{write;columns;pending="";fence;table;constructor($,w=()=>80){this.write=$;this.columns=w}push($){this.pending+=Y0($);let w=this.pending.indexOf(`
268
+ `}strong({tokens:$}){return`<strong>${this.parser.parseInline($)}</strong>`}em({tokens:$}){return`<em>${this.parser.parseInline($)}</em>`}codespan({text:$}){return`<code>${U$($,!0)}</code>`}br($){return"<br>"}del({tokens:$}){return`<del>${this.parser.parseInline($)}</del>`}link({href:$,title:w,tokens:G}){let Z=this.parser.parseInline(G),X=oq($);if(X===null)return Z;$=X;let Y='<a href="'+$+'"';return w&&(Y+=' title="'+U$(w)+'"'),Y+=">"+Z+"</a>",Y}image({href:$,title:w,text:G,tokens:Z}){Z&&(G=this.parser.parseInline(Z,this.parser.textRenderer));let X=oq($);if(X===null)return U$(G);$=X;let Y=`<img src="${$}" alt="${U$(G)}"`;return w&&(Y+=` title="${U$(w)}"`),Y+=">",Y}text($){return"tokens"in $&&$.tokens?this.parser.parseInline($.tokens):("escaped"in $)&&$.escaped?$.text:U$($.text)}},f7=class{strong({text:$}){return $}em({text:$}){return $}codespan({text:$}){return $}del({text:$}){return $}html({text:$}){return $}text({text:$}){return $}link({text:$}){return""+$}image({text:$}){return""+$}br(){return""}checkbox({raw:$}){return $}},W$=class ${options;renderer;textRenderer;constructor(w){this.options=w||s1,this.options.renderer=this.options.renderer||new qG,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new f7}static parse(w,G){return new $(G).parse(w)}static parseInline(w,G){return new $(G).parseInline(w)}parse(w){this.renderer.parser=this;let G="";for(let Z=0;Z<w.length;Z++){let X=w[Z];if(this.options.extensions?.renderers?.[X.type]){let J=X,W=this.options.extensions.renderers[J.type].call({parser:this},J);if(W!==!1||!["space","hr","heading","code","table","blockquote","list","checkbox","html","def","paragraph","text"].includes(J.type)){G+=W||"";continue}}let Y=X;switch(Y.type){case"space":{G+=this.renderer.space(Y);break}case"hr":{G+=this.renderer.hr(Y);break}case"heading":{G+=this.renderer.heading(Y);break}case"code":{G+=this.renderer.code(Y);break}case"table":{G+=this.renderer.table(Y);break}case"blockquote":{G+=this.renderer.blockquote(Y);break}case"list":{G+=this.renderer.list(Y);break}case"checkbox":{G+=this.renderer.checkbox(Y);break}case"html":{G+=this.renderer.html(Y);break}case"def":{G+=this.renderer.def(Y);break}case"paragraph":{G+=this.renderer.paragraph(Y);break}case"text":{G+=this.renderer.text(Y);break}default:{let J='Token with "'+Y.type+'" type was not found.';if(this.options.silent)return console.error(J),"";throw Error(J)}}}return G}parseInline(w,G=this.renderer){this.renderer.parser=this;let Z="";for(let X=0;X<w.length;X++){let Y=w[X];if(this.options.extensions?.renderers?.[Y.type]){let W=this.options.extensions.renderers[Y.type].call({parser:this},Y);if(W!==!1||!["escape","html","link","image","checkbox","strong","em","codespan","br","del","text"].includes(Y.type)){Z+=W||"";continue}}let J=Y;switch(J.type){case"escape":{Z+=G.text(J);break}case"html":{Z+=G.html(J);break}case"link":{Z+=G.link(J);break}case"image":{Z+=G.image(J);break}case"checkbox":{Z+=G.checkbox(J);break}case"strong":{Z+=G.strong(J);break}case"em":{Z+=G.em(J);break}case"codespan":{Z+=G.codespan(J);break}case"br":{Z+=G.br(J);break}case"del":{Z+=G.del(J);break}case"text":{Z+=G.text(J);break}default:{let W='Token with "'+J.type+'" type was not found.';if(this.options.silent)return console.error(W),"";throw Error(W)}}}return Z}},x9=class{options;block;constructor($){this.options=$||s1}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess($){return $}postprocess($){return $}processAllTokens($){return $}emStrongMask($){return $}provideLexer($=this.block){return $?J$.lex:J$.lexInline}provideParser($=this.block){return $?W$.parse:W$.parseInline}},Zx=class{defaults=N7();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=W$;Renderer=qG;TextRenderer=f7;Lexer=J$;Tokenizer=PG;Hooks=x9;constructor(...$){this.use(...$)}walkTokens($,w){let G=[];for(let Z of $)switch(G=G.concat(w.call(this,Z)),Z.type){case"table":{let X=Z;for(let Y of X.header)G=G.concat(this.walkTokens(Y.tokens,w));for(let Y of X.rows)for(let J of Y)G=G.concat(this.walkTokens(J.tokens,w));break}case"list":{let X=Z;G=G.concat(this.walkTokens(X.items,w));break}default:{let X=Z;this.defaults.extensions?.childTokens?.[X.type]?this.defaults.extensions.childTokens[X.type].forEach((Y)=>{let J=X[Y].flat(1/0);G=G.concat(this.walkTokens(J,w))}):X.tokens&&(G=G.concat(this.walkTokens(X.tokens,w)))}}return G}use(...$){let w=this.defaults.extensions||{renderers:{},childTokens:{}};return $.forEach((G)=>{let Z={...G};if(Z.async=this.defaults.async||Z.async||!1,G.extensions&&(G.extensions.forEach((X)=>{if(!X.name)throw Error("extension name required");if("renderer"in X){let Y=w.renderers[X.name];Y?w.renderers[X.name]=function(...J){let W=X.renderer.apply(this,J);return W===!1&&(W=Y.apply(this,J)),W}:w.renderers[X.name]=X.renderer}if("tokenizer"in X){if(!X.level||X.level!=="block"&&X.level!=="inline")throw Error("extension level must be 'block' or 'inline'");let Y=w[X.level];Y?Y.unshift(X.tokenizer):w[X.level]=[X.tokenizer],X.start&&(X.level==="block"?w.startBlock?w.startBlock.push(X.start):w.startBlock=[X.start]:X.level==="inline"&&(w.startInline?w.startInline.push(X.start):w.startInline=[X.start]))}"childTokens"in X&&X.childTokens&&(w.childTokens[X.name]=X.childTokens)}),Z.extensions=w),G.renderer){let X=this.defaults.renderer||new qG(this.defaults);for(let Y in G.renderer){if(!(Y in X))throw Error(`renderer '${Y}' does not exist`);if(["options","parser"].includes(Y))continue;let J=Y,W=G.renderer[J],T=X[J];X[J]=(...Q)=>{let z=W.apply(X,Q);return z===!1&&(z=T.apply(X,Q)),z||""}}Z.renderer=X}if(G.tokenizer){let X=this.defaults.tokenizer||new PG(this.defaults);for(let Y in G.tokenizer){if(!(Y in X))throw Error(`tokenizer '${Y}' does not exist`);if(["options","rules","lexer"].includes(Y))continue;let J=Y,W=G.tokenizer[J],T=X[J];X[J]=(...Q)=>{let z=W.apply(X,Q);return z===!1&&(z=T.apply(X,Q)),z}}Z.tokenizer=X}if(G.hooks){let X=this.defaults.hooks||new x9;for(let Y in G.hooks){if(!(Y in X))throw Error(`hook '${Y}' does not exist`);if(["options","block"].includes(Y))continue;let J=Y,W=G.hooks[J],T=X[J];x9.passThroughHooks.has(Y)?X[J]=(Q)=>{if(this.defaults.async&&x9.passThroughHooksRespectAsync.has(Y))return(async()=>{let M=await W.call(X,Q);return T.call(X,M)})();let z=W.call(X,Q);return T.call(X,z)}:X[J]=(...Q)=>{if(this.defaults.async)return(async()=>{let M=await W.apply(X,Q);return M===!1&&(M=await T.apply(X,Q)),M})();let z=W.apply(X,Q);return z===!1&&(z=T.apply(X,Q)),z}}Z.hooks=X}if(G.walkTokens){let X=this.defaults.walkTokens,Y=G.walkTokens;Z.walkTokens=function(J){let W=[];return W.push(Y.call(this,J)),X&&(W=W.concat(X.call(this,J))),W}}this.defaults={...this.defaults,...Z}}),this}setOptions($){return this.defaults={...this.defaults,...$},this}lexer($,w){return J$.lex($,w??this.defaults)}parser($,w){return W$.parse($,w??this.defaults)}parseMarkdown($){return(w,G)=>{let Z={...G},X={...this.defaults,...Z},Y=this.onError(!!X.silent,!!X.async);if(this.defaults.async===!0&&Z.async===!1)return Y(Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof w>"u"||w===null)return Y(Error("marked(): input parameter is undefined or null"));if(typeof w!="string")return Y(Error("marked(): input parameter is of type "+Object.prototype.toString.call(w)+", string expected"));if(X.hooks&&(X.hooks.options=X,X.hooks.block=$),X.async)return(async()=>{let J=X.hooks?await X.hooks.preprocess(w):w,W=await(X.hooks?await X.hooks.provideLexer($):$?J$.lex:J$.lexInline)(J,X),T=X.hooks?await X.hooks.processAllTokens(W):W;X.walkTokens&&await Promise.all(this.walkTokens(T,X.walkTokens));let Q=await(X.hooks?await X.hooks.provideParser($):$?W$.parse:W$.parseInline)(T,X);return X.hooks?await X.hooks.postprocess(Q):Q})().catch(Y);try{X.hooks&&(w=X.hooks.preprocess(w));let J=(X.hooks?X.hooks.provideLexer($):$?J$.lex:J$.lexInline)(w,X);X.hooks&&(J=X.hooks.processAllTokens(J)),X.walkTokens&&this.walkTokens(J,X.walkTokens);let W=(X.hooks?X.hooks.provideParser($):$?W$.parse:W$.parseInline)(J,X);return X.hooks&&(W=X.hooks.postprocess(W)),W}catch(J){return Y(J)}}}onError($,w){return(G)=>{if(G.message+=`
269
+ Please report this to https://github.com/markedjs/marked.`,$){let Z="<p>An error occurred:</p><pre>"+U$(G.message+"",!0)+"</pre>";return w?Promise.resolve(Z):Z}if(w)return Promise.reject(G);throw G}}},r1=new Zx;function t($,w){return r1.parse($,w)}t.options=t.setOptions=function($){return r1.setOptions($),t.defaults=r1.defaults,GB(t.defaults),t};t.getDefaults=N7;t.defaults=s1;function Xx(...$){return r1.use(...$),t.defaults=r1.defaults,GB(t.defaults),t}t.use=Xx;t.walkTokens=function($,w){return r1.walkTokens($,w)};t.parseInline=r1.parseInline;t.Parser=W$;t.parser=W$.parse;t.Renderer=qG;t.TextRenderer=f7;t.Lexer=J$;t.lexer=J$.lex;t.Tokenizer=PG;t.Hooks=x9;t.parse=t;var{options:Sc,setOptions:Ic,walkTokens:jc,parseInline:Cc}=t;var bc=W$.parse,kc=J$.lex;var T$=A1(y9(),1);var v9=A1(y9(),1);import{stripVTControlCharacters as Qx}from"node:util";import{stripVTControlCharacters as Yx}from"node:util";var Jx=new Intl.Segmenter(void 0,{granularity:"grapheme"}),Wx=/\p{Mark}/u,Tx=/\p{Extended_Pictographic}|\p{Regional_Indicator}|\u20e3/u;function T0($){return Array.from(Yx($)).filter((w)=>{let G=w.codePointAt(0)??0;return G===9||G===10||G>159||G>31&&G<127}).join("")}function L7($){let w=$.codePointAt(0)??0;if(w>=9472&&w<=9599)return 1;return w<=255?1:2}function y$($){return Array.from(Jx.segment($),({segment:w})=>w)}function ow($){if(!$)return 0;if(Tx.test($)||$.includes("️"))return 2;return Array.from($).filter((G)=>!Wx.test(G)&&G!=="‍"&&G!=="︎").reduce((G,Z)=>Math.max(G,L7(Z)),0)}function h9($){return y$($).reduce((w,G)=>w+ow(G),0)}function ew($,w,G="head"){if(w<=0)return"";if(h9($)<=w)return $;if(w===1)return"…";let Z=y$($),X=[],Y=1,J=G==="head"?Z.map((W,T)=>T):Z.map((W,T)=>Z.length-T-1);for(let W of J){let T=Z[W];if(T===void 0||Y+ow(T)>w)break;if(G==="head")X.push(T);else X.unshift(T);Y+=ow(T)}return G==="head"?`${X.join("")}…`:`…${X.join("")}`}var A7="\x1B",qB=`${A7}[0m`,zx=new RegExp(`^${A7}\\[[0-?]*[ -/]*[@-~]`);function BB($){return h9(Qx($))}function NB($){let w=[],G=0,Z="";while(G<$.length){let X=$.slice(G).match(zx)?.[0];if(X){if(X.endsWith("m"))Z=X===`${A7}[m`||X===qB?"":`${Z}${X}`;G+=X.length;continue}let Y=$.codePointAt(G);if(Y===void 0)break;let J=String.fromCodePoint(Y);w.push({value:J,width:L7(J),state:Z}),G+=J.length}return w}function D7($){return $.map((w)=>w.state?`${w.state}${w.value}${qB}`:w.value).join("")}function Mx($,w){if($.length===0)return[""];let G=[],Z=$;while(Z.length>0){if(G.length>0){while(Z[0]&&/\s/u.test(Z[0].value))Z=Z.slice(1);if(Z.length===0)break}let X=0,Y=0,J=-1;while(Y<Z.length){let W=Z[Y];if(!W||Y>0&&X+W.width>w)break;if(X+=W.width,/\s/u.test(W.value))J=Y;if(Y+=1,X>=w)break}if(Y>=Z.length){G.push(D7(Z));break}if(J>=0){G.push(D7(Z.slice(0,J))),Z=Z.slice(J+1);while(Z[0]&&/\s/u.test(Z[0].value))Z=Z.slice(1);continue}G.push(D7(Z.slice(0,Math.max(1,Y)))),Z=Z.slice(Math.max(1,Y))}return G.length>0?G:[""]}function Px($,w){let G=Math.max(1,w);return $.split(`
270
+ `).flatMap((Z)=>Mx(NB(Z),G))}function qx($){return $.some((w)=>NB(w).some((G)=>G.width>1))?2:1}function Bx($){return Math.max(1,...$.flatMap((w)=>w.split(`
271
+ `).map(BB)))}function Nx($,w){let G=$.header.length,Z=$.header.map((W,T)=>[W,...$.rows.map((Q)=>Q[T]??"")]),X=Z.map(qx),Y=Z.map(Bx),J=Math.max(X.reduce((W,T)=>W+T,0),w-(3*G+1));while(Y.reduce((W,T)=>W+T,0)>J){let W=-1;for(let T=0;T<Y.length;T+=1){let Q=Y[T]??0,z=X[T]??1;if(Q>z&&(W<0||Q>(Y[W]??0)))W=T}if(W<0)break;Y[W]=(Y[W]??1)-1}return Y}function Vx($,w,G){let Z=Math.max(0,w-BB($)),X=G==="right"?Z:G==="center"?Math.floor(Z/2):0;return`${" ".repeat(X)}${$}${" ".repeat(Z-X)}`}function E7($,w,G,Z){return v9.default.dim(`${$}${Z.map((X)=>"─".repeat(X+2)).join(w)}${G}`)}function PB($,w,G){let Z=G.map((Y,J)=>Px($[J]??"",Y)),X=Math.max(1,...Z.map((Y)=>Y.length));return Array.from({length:X},(Y,J)=>{let W=G.map((T,Q)=>Vx(Z[Q]?.[J]??"",T,w[Q]??"left"));return`${v9.default.dim("│")} ${W.join(` ${v9.default.dim("│")} `)} ${v9.default.dim("│")}`})}function VB($,w){if($.header.length===0)return"";let G=Nx($,Math.max(1,w)),Z=G.map((Y,J)=>$.align[J]??"left");return[E7("┌","┬","┐",G),...PB($.header,Z,G),E7("├","┼","┤",G),...$.rows.flatMap((Y)=>PB(Y,Z,G)),E7("└","┴","┘",G)].join(`
272
+ `)}class i9{write;columns;pending="";fence;table;constructor($,w=()=>80){this.write=$;this.columns=w}push($){this.pending+=T0($);let w=this.pending.indexOf(`
133
273
  `);while(w>=0){let G=this.pending.slice(0,w+1);this.pending=this.pending.slice(w+1),this.consumeLine(G),w=this.pending.indexOf(`
134
274
  `)}}preview(){if(this.pending)return this.pending;let $=this.table?.lines.at(-1);if($!==void 0)return $.endsWith(`
135
275
  `)?$.slice(0,-1):$;let w=this.fence?.lines.at(-1);if(w===void 0)return;return w.endsWith(`
136
- `)?w.slice(0,-1):w}complete(){if(this.pending){let $=this.pending;this.pending="",this.consumeLine($)}if(this.flushTable(),this.fence)this.renderUnit(this.fence.lines.join("")),this.fence=void 0}reset(){this.pending="",this.fence=void 0,this.table=void 0}tableToken($){let w=t.lexer($)[0];return w?.type==="table"&&w.raw===$?w:void 0}flushTable(){let $=this.table;if(this.table=void 0,!$)return;this.renderUnit($.lines.join(""))}consumeLine($){if(this.fence){this.fence.lines.push($);let Z=($.endsWith(`
137
- `)?$.slice(0,-1):$).match(/^ {0,3}(`{3,}|~{3,})[ \t]*$/);if(Z?.[1]?.[0]===this.fence.marker&&Z[1].length>=this.fence.length){let X=this.fence.lines.join("");this.fence=void 0,this.renderUnit(X)}return}if(this.table){let Y=`${this.table.lines.join("")}${$}`,Z=this.tableToken(Y);if(this.table.confirmed){if(Z){this.table.lines.push($);return}this.flushTable(),this.consumeLine($);return}if(Z){this.table.lines.push($),this.table.confirmed=!0;return}this.flushTable(),this.consumeLine($);return}let w=$.endsWith(`
138
- `)?$.slice(0,-1):$,W=w.match(/^ {0,3}(`{3,}|~{3,})(.*)$/)?.[1];if(W){this.fence={marker:W[0],length:W.length,lines:[$]};return}if(w.includes("|")){this.table={lines:[$],confirmed:!1};return}this.renderUnit($)}renderUnit($){try{let w=this.renderTokens(t.lexer($));if($.endsWith(`
276
+ `)?w.slice(0,-1):w}complete(){if(this.pending){let $=this.pending;this.pending="",this.consumeLine($)}if(this.flushTable(),this.fence)this.renderUnit(this.fence.lines.join("")),this.fence=void 0}reset(){this.pending="",this.fence=void 0,this.table=void 0}tableToken($){let w=t.lexer($)[0];return w?.type==="table"&&w.raw===$?w:void 0}flushTable(){let $=this.table;if(this.table=void 0,!$)return;this.renderUnit($.lines.join(""))}consumeLine($){if(this.fence){this.fence.lines.push($);let Y=($.endsWith(`
277
+ `)?$.slice(0,-1):$).match(/^ {0,3}(`{3,}|~{3,})[ \t]*$/);if(Y?.[1]?.[0]===this.fence.marker&&Y[1].length>=this.fence.length){let J=this.fence.lines.join("");this.fence=void 0,this.renderUnit(J)}return}if(this.table){let X=`${this.table.lines.join("")}${$}`,Y=this.tableToken(X);if(this.table.confirmed){if(Y){this.table.lines.push($);return}this.flushTable(),this.consumeLine($);return}if(Y){this.table.lines.push($),this.table.confirmed=!0;return}this.flushTable(),this.consumeLine($);return}let w=$.endsWith(`
278
+ `)?$.slice(0,-1):$,Z=w.match(/^ {0,3}(`{3,}|~{3,})(.*)$/)?.[1];if(Z){this.fence={marker:Z[0],length:Z.length,lines:[$]};return}if(w.includes("|")){this.table={lines:[$],confirmed:!1};return}this.renderUnit($)}renderUnit($){try{let w=this.renderTokens(t.lexer($));if($.endsWith(`
139
279
  `)&&!w.endsWith(`
140
280
  `))w+=`
141
- `;this.write(w)}catch{this.write(Y0($))}}renderTokens($){return($??[]).map((w)=>this.renderToken(w)).join("")}renderToken($){let w=()=>this.renderTokens("tokens"in $?$.tokens:void 0),G=()=>Y0("text"in $?$.text:"");switch($.type){case"heading":return e0.default.bold(w()||G());case"strong":return e0.default.bold(w()||G());case"em":return e0.default.italic(w()||G());case"codespan":return e0.default.cyan(G());case"link":{let W=w()||G(),Y=Y0($.href??"");return`${e0.default.underline(W)}${Y?e0.default.dim(` (${Y})`):""}`}case"list":{let W=$,Y=typeof W.start==="number"?W.start:1;return W.items.map((Z,X)=>{let J=this.renderTokens(Z.tokens)||Y0(Z.text??""),T=W.ordered?`${Y+X}. `:"• ";return J.trimEnd().split(`
142
- `).map((f,Q)=>`${Q===0?T:" "}${f}`).join(`
281
+ `;this.write(w)}catch{this.write(T0($))}}renderTokens($){return($??[]).map((w)=>this.renderToken(w)).join("")}renderToken($){let w=()=>this.renderTokens("tokens"in $?$.tokens:void 0),G=()=>T0("text"in $?$.text:"");switch($.type){case"heading":return T$.default.bold(w()||G());case"strong":return T$.default.bold(w()||G());case"em":return T$.default.italic(w()||G());case"codespan":return T$.default.cyan(G());case"link":{let Z=w()||G(),X=T0($.href??"");return`${T$.default.underline(Z)}${X?T$.default.dim(` (${X})`):""}`}case"list":{let Z=$,X=typeof Z.start==="number"?Z.start:1;return Z.items.map((Y,J)=>{let W=this.renderTokens(Y.tokens)||T0(Y.text??""),T=Z.ordered?`${X+J}. `:"• ";return W.trimEnd().split(`
282
+ `).map((z,M)=>`${M===0?T:" "}${z}`).join(`
143
283
  `)}).join(`
144
284
  `)}case"list_item":return w()||G();case"blockquote":return(w()||G()).trimEnd().split(`
145
- `).map((Y)=>`${e0.default.dim("│ ")}${Y}`).join(`
146
- `);case"code":{let W=Y0(($.lang??"").trim()),Y=e0.default.cyan(G());return W?`${e0.default.dim(W)}
147
- ${Y}`:Y}case"table":{let W=$;return gT({header:W.header.map((Y)=>e0.default.bold(this.renderTokens(Y.tokens))),align:W.align.map((Y)=>Y??"left"),rows:W.rows.map((Y)=>Y.map((Z)=>this.renderTokens(Z.tokens)))},Math.max(1,this.columns()))}case"paragraph":case"text":case"escape":return w()||G();case"space":case"br":return`
148
- `;default:{let W=w();if(W)return W;let Y=G();if(Y)return Y;return Y0($.raw??"")}}}}var vT=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];class QW{options;stdout;stderr;tty;markdown;spinner;frame=0;providerStartedAt;reasoningText="";toolCallPreviews=new Map;activeToolCallIndex;contentStarted=!1;pendingText="";constructor($,w={}){this.options=w;this.stdout=w.stdout??process.stdout,this.stderr=w.stderr??process.stderr,this.tty=!w.printMode&&(w.tty??Boolean(process.stderr.isTTY&&!process.env.NO_COLOR&&!process.env.CI)),this.markdown=new k4((G)=>this.stdout.write(G),()=>{let G=this.stdout.columns,W=this.stderr.columns;return G??W??80}),$.on((G)=>this.render(G))}render($){if($.type==="provider.started")this.startProviderAttempt();if($.type==="provider.reasoning_delta"){let w=String($.data?.text??"");if(this.tty&&this.providerStartedAt!==void 0&&!this.contentStarted&&w)this.reasoningText+=w,this.renderActivityLine()}if($.type==="provider.tool_call_start"&&this.tty){let w=Number($.data?.index),G=String($.data?.name??"tool");if(Number.isInteger(w))this.startToolCallPreview(w,G)}if($.type==="provider.tool_call_delta"&&this.tty){let w=Number($.data?.index),G=String($.data?.argumentsDelta??"");if(Number.isInteger(w)&&G)this.appendToolCallPreview(w,G)}if($.type==="provider.tool_call_end"&&this.tty){let w=Number($.data?.index);if(Number.isInteger(w))this.endToolCallPreview(w)}if($.type==="provider.delta"){let w=String($.data?.text??"");if(w&&!this.contentStarted)this.finishThinking();if(this.tty){if(this.clearActivityLine(),this.markdown.push(w),w)this.startSpinner(),this.renderActivityLine()}else this.pendingText+=w}if($.type==="provider.completed"){if(this.tty)this.stopSpinner(),this.markdown.complete();if(!this.tty&&this.pendingText)this.stdout.write(this.pendingText),this.pendingText="";this.endProviderAttempt()}if($.type==="provider.retry"||$.type==="turn.failed")this.endProviderAttempt(),this.pendingText="";if($.type==="tool.started"){this.endProviderAttempt();let w=Y0(String($.data?.name??"tool"));if(this.tty){let G=Y0(String($.data?.summary??""));this.toolStatus(`◇ ${w}${G?` ${G}`:""}`)}else this.status(`tool ${w} started`)}if($.type==="tool.completed"){let w=Y0(String($.data?.name??"tool")),G=String($.data?.durationMs??"?");if(this.tty){let W=Boolean($.data?.isError);this.toolStatus(`${W?"✗":"✓"} ${w} ${G}ms`,W)}else this.status(`tool ${w} ${$.data?.isError?"failed":"completed"} (${G}ms)`)}if($.type==="provider.retry"&&this.options.verbose)this.status(`provider retry ${String($.data?.attempt)}`);if($.type==="turn.completed")this.endProviderAttempt(),this.stdout.write(`
149
- `),this.status(`done: ${String($.data?.tools)} tools, ${String($.data?.durationMs)}ms, ${String($.data?.inputTokens)}/${String($.data?.outputTokens)} tokens`);if($.type==="turn.failed")this.status(M1.default.red(`failed: ${String($.data?.message)}`));if($.type==="plugin.loaded"&&this.options.verbose)this.status(`plugin loaded: ${N6($)}`);if($.type==="plugin.failed")this.status(M1.default.red(`plugin failed: ${N6($)}${fW($)}`));if($.type==="plugin.unavailable")this.status(M1.default.yellow(`plugin unavailable: ${N6($)}${fW($)}`));if($.type==="plugin.restart_required")this.status(M1.default.yellow(`plugin restart required: ${N6($)}${fW($)}`))}status($){this.stderr.write(this.tty?`${M1.default.dim($)}
285
+ `).map((X)=>`${T$.default.dim("│ ")}${X}`).join(`
286
+ `);case"code":{let Z=T0(($.lang??"").trim()),X=T$.default.cyan(G());return Z?`${T$.default.dim(Z)}
287
+ ${X}`:X}case"table":{let Z=$;return VB({header:Z.header.map((X)=>T$.default.bold(this.renderTokens(X.tokens))),align:Z.align.map((X)=>X??"left"),rows:Z.rows.map((X)=>X.map((Y)=>this.renderTokens(Y.tokens)))},Math.max(1,this.columns()))}case"paragraph":case"text":case"escape":return w()||G();case"space":case"br":return`
288
+ `;default:{let Z=w();if(Z)return Z;let X=G();if(X)return X;return T0($.raw??"")}}}}var KB=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];class S7{options;stdout;stderr;tty;markdown;spinner;frame=0;providerStartedAt;reasoningText="";toolCallPreviews=new Map;activeToolCallIndex;contentStarted=!1;pendingText="";constructor($,w={}){this.options=w;this.stdout=w.stdout??process.stdout,this.stderr=w.stderr??process.stderr,this.tty=!w.printMode&&(w.tty??Boolean(process.stderr.isTTY&&!process.env.NO_COLOR&&!process.env.CI)),this.markdown=new i9((G)=>this.stdout.write(G),()=>{let G=this.stdout.columns,Z=this.stderr.columns;return G??Z??80}),$.on((G)=>this.render(G))}render($){if($.type==="provider.started")this.startProviderAttempt();if($.type==="provider.reasoning_delta"){let w=String($.data?.text??"");if(this.tty&&this.providerStartedAt!==void 0&&!this.contentStarted&&w)this.reasoningText+=w,this.renderActivityLine()}if($.type==="provider.tool_call_start"&&this.tty){let w=Number($.data?.index),G=String($.data?.name??"tool");if(Number.isInteger(w))this.startToolCallPreview(w,G)}if($.type==="provider.tool_call_delta"&&this.tty){let w=Number($.data?.index),G=String($.data?.argumentsDelta??"");if(Number.isInteger(w)&&G)this.appendToolCallPreview(w,G)}if($.type==="provider.tool_call_end"&&this.tty){let w=Number($.data?.index);if(Number.isInteger(w))this.endToolCallPreview(w)}if($.type==="provider.delta"){let w=String($.data?.text??"");if(w&&!this.contentStarted)this.finishThinking();if(this.tty){if(this.clearActivityLine(),this.markdown.push(w),w)this.startSpinner(),this.renderActivityLine()}else this.pendingText+=w}if($.type==="provider.completed"){if(this.tty)this.stopSpinner(),this.markdown.complete();if(!this.tty&&this.pendingText)this.stdout.write(this.pendingText),this.pendingText="";this.endProviderAttempt()}if($.type==="provider.retry"||$.type==="turn.failed")this.endProviderAttempt(),this.pendingText="";if($.type==="tool.started"){this.endProviderAttempt();let w=T0(String($.data?.name??"tool"));if(this.tty){let G=T0(String($.data?.summary??""));this.toolStatus(`◇ ${w}${G?` ${G}`:""}`)}else this.status(`tool ${w} started`)}if($.type==="tool.completed"){let w=T0(String($.data?.name??"tool")),G=String($.data?.durationMs??"?");if(this.tty){let Z=Boolean($.data?.isError);this.toolStatus(`${Z?"✗":"✓"} ${w} ${G}ms`,Z)}else this.status(`tool ${w} ${$.data?.isError?"failed":"completed"} (${G}ms)`)}if($.type==="provider.retry"&&this.options.verbose)this.status(`provider retry ${String($.data?.attempt)}`);if($.type==="turn.completed")this.endProviderAttempt(),this.stdout.write(`
289
+ `),this.status(`done: ${String($.data?.tools)} tools, ${String($.data?.durationMs)}ms, ${String($.data?.inputTokens)}/${String($.data?.outputTokens)} tokens`);if($.type==="turn.failed")this.status(H$.default.red(`failed: ${String($.data?.message)}`));if($.type==="plugin.loaded"&&this.options.verbose)this.status(`plugin loaded: ${NG($)}`);if($.type==="plugin.failed")this.status(H$.default.red(`plugin failed: ${NG($)}${R7($)}`));if($.type==="plugin.unavailable")this.status(H$.default.yellow(`plugin unavailable: ${NG($)}${R7($)}`));if($.type==="plugin.restart_required")this.status(H$.default.yellow(`plugin restart required: ${NG($)}${R7($)}`))}status($){this.stderr.write(this.tty?`${H$.default.dim($)}
150
290
  `:`[coden] ${$}
151
- `)}toolStatus($,w=!1){let G=this.stderr.columns??80,W=Tw(Y0($),G);this.stderr.write(`${w?M1.default.red(W):M1.default.dim(W)}
152
- `)}startProviderAttempt(){this.endProviderAttempt(),this.providerStartedAt=Date.now(),this.startSpinner(),this.renderActivityLine()}endProviderAttempt(){this.stopSpinner(),this.clearToolCallPreviews(),this.markdown.reset(),this.providerStartedAt=void 0,this.reasoningText="",this.contentStarted=!1}finishThinking(){let $=this.providerStartedAt,w=Boolean(this.normalizedReasoning());if(this.clearToolCallPreviews(),this.stopSpinner(),this.contentStarted=!0,this.tty&&$!==void 0&&w){let G=((Date.now()-$)/1000).toFixed(1);this.stderr.write(`${M1.default.dim(`thought for ${G}s`)}
153
- `)}}normalizedReasoning(){return this.reasoningText.replace(/\s+/g," ").trim()}startToolCallPreview($,w){this.toolCallPreviews.set($,{name:w,argumentsText:""}),this.activeToolCallIndex=$,this.startSpinner(),this.renderActivityLine()}appendToolCallPreview($,w){let G=this.toolCallPreviews.get($);if(!G)return;G.argumentsText+=w,this.activeToolCallIndex=$,this.renderActivityLine()}endToolCallPreview($){if(!this.toolCallPreviews.delete($))return;if(this.activeToolCallIndex===$)this.activeToolCallIndex=[...this.toolCallPreviews.keys()].at(-1);if(this.activeToolCallIndex===void 0&&this.contentStarted){this.stopSpinner();return}this.renderActivityLine()}clearToolCallPreviews(){this.toolCallPreviews.clear(),this.activeToolCallIndex=void 0}renderActivityLine(){if(!this.tty||this.providerStartedAt===void 0)return;let $=this.stderr.columns??80,w=Math.max(0,$-2),G=vT[this.frame++%vT.length]??"",W=this.currentActivityText(w);Mw.clearLine(this.stderr,0),Mw.cursorTo(this.stderr,0),this.stderr.write(M1.default.dim(`${G} ${W}`))}currentActivityText($){let w=this.activeToolCallIndex===void 0?void 0:this.toolCallPreviews.get(this.activeToolCallIndex);if(w){let W=`preparing ${w.name}…`,Y=w.argumentsText.replace(/\s+/g," ").trim();if(!Y)return this.truncateTail(W,$);let Z=Math.max(0,$-L4(W)-1);if(Z===0)return this.truncateTail(W,$);return`${W} ${this.truncateTail(Y,Z)}`}if(this.contentStarted){let W=this.markdown.preview();return W===void 0?"rendering…":this.truncateTail(W,$)}let G=this.normalizedReasoning();return G?this.truncateTail(G,$):"thinking"}truncateTail($,w){return Tw($,w,"tail")}startSpinner(){if(!this.tty||this.spinner){if(!this.tty&&this.options.verbose)this.status("requesting model");return}this.spinner=setInterval(()=>{this.renderActivityLine()},80)}clearActivityLine(){if(!this.tty)return;Mw.clearLine(this.stderr,0),Mw.cursorTo(this.stderr,0)}stopSpinner(){if(!this.spinner)return;clearInterval(this.spinner),this.spinner=void 0,this.clearActivityLine()}dispose(){this.endProviderAttempt()}}function N6($){let w=$.data??{},G=q$(w.scope),W=q$(w.packageName),Y=q$(w.version??w.diskVersion),Z=q$(w.name),X=q$(w.path),J=q$(w.source);if(W)return`${G?`${G} `:""}${W}${Y?`@${Y}`:""}`;if(Z)return Z;if(X)return`${G?`${G} `:""}${X}`;if(J)return J;return"plugin"}function fW($){let w=q$($.data?.message??$.data?.reason);return w?` — ${w}`:""}function q$($){return typeof $==="string"&&$.length>0?$:void 0}import{appendFile as jF,chmod as uT,mkdir as CF}from"node:fs/promises";import yF from"node:path";class NW{file;shouldPersist;#$=Promise.resolve();#w=[];constructor($,w,G=()=>!0){this.file=$;this.shouldPersist=G;w.on((W)=>this.write(W))}write($){if(!this.shouldPersist())return this.#w.push($),Promise.resolve();let w=[...this.#w.splice(0),$],G=this.#$.then(async()=>{let W=yF.dirname(this.file);await CF(W,{recursive:!0,mode:448}),await uT(W,448),await jF(this.file,`${w.map((Y)=>JSON.stringify(Y)).join(`
291
+ `)}toolStatus($,w=!1){let G=this.stderr.columns??80,Z=ew(T0($),G);this.stderr.write(`${w?H$.default.red(Z):H$.default.dim(Z)}
292
+ `)}startProviderAttempt(){this.endProviderAttempt(),this.providerStartedAt=Date.now(),this.startSpinner(),this.renderActivityLine()}endProviderAttempt(){this.stopSpinner(),this.clearToolCallPreviews(),this.markdown.reset(),this.providerStartedAt=void 0,this.reasoningText="",this.contentStarted=!1}finishThinking(){let $=this.providerStartedAt,w=Boolean(this.normalizedReasoning());if(this.clearToolCallPreviews(),this.stopSpinner(),this.contentStarted=!0,this.tty&&$!==void 0&&w){let G=((Date.now()-$)/1000).toFixed(1);this.stderr.write(`${H$.default.dim(`thought for ${G}s`)}
293
+ `)}}normalizedReasoning(){return this.reasoningText.replace(/\s+/g," ").trim()}startToolCallPreview($,w){this.toolCallPreviews.set($,{name:w,argumentsText:""}),this.activeToolCallIndex=$,this.startSpinner(),this.renderActivityLine()}appendToolCallPreview($,w){let G=this.toolCallPreviews.get($);if(!G)return;G.argumentsText+=w,this.activeToolCallIndex=$,this.renderActivityLine()}endToolCallPreview($){if(!this.toolCallPreviews.delete($))return;if(this.activeToolCallIndex===$)this.activeToolCallIndex=[...this.toolCallPreviews.keys()].at(-1);if(this.activeToolCallIndex===void 0&&this.contentStarted){this.stopSpinner();return}this.renderActivityLine()}clearToolCallPreviews(){this.toolCallPreviews.clear(),this.activeToolCallIndex=void 0}renderActivityLine(){if(!this.tty||this.providerStartedAt===void 0)return;let $=this.stderr.columns??80,w=Math.max(0,$-2),G=KB[this.frame++%KB.length]??"",Z=this.currentActivityText(w);$4.clearLine(this.stderr,0),$4.cursorTo(this.stderr,0),this.stderr.write(H$.default.dim(`${G} ${Z}`))}currentActivityText($){let w=this.activeToolCallIndex===void 0?void 0:this.toolCallPreviews.get(this.activeToolCallIndex);if(w){let Z=`preparing ${w.name}…`,X=w.argumentsText.replace(/\s+/g," ").trim();if(!X)return this.truncateTail(Z,$);let Y=Math.max(0,$-h9(Z)-1);if(Y===0)return this.truncateTail(Z,$);return`${Z} ${this.truncateTail(X,Y)}`}if(this.contentStarted){let Z=this.markdown.preview();return Z===void 0?"rendering…":this.truncateTail(Z,$)}let G=this.normalizedReasoning();return G?this.truncateTail(G,$):"thinking"}truncateTail($,w){return ew($,w,"tail")}startSpinner(){if(!this.tty||this.spinner){if(!this.tty&&this.options.verbose)this.status("requesting model");return}this.spinner=setInterval(()=>{this.renderActivityLine()},80)}clearActivityLine(){if(!this.tty)return;$4.clearLine(this.stderr,0),$4.cursorTo(this.stderr,0)}stopSpinner(){if(!this.spinner)return;clearInterval(this.spinner),this.spinner=void 0,this.clearActivityLine()}dispose(){this.endProviderAttempt()}}function NG($){let w=$.data??{},G=a1(w.scope),Z=a1(w.packageName),X=a1(w.version??w.diskVersion),Y=a1(w.name),J=a1(w.path),W=a1(w.source);if(Z)return`${G?`${G} `:""}${Z}${X?`@${X}`:""}`;if(Y)return Y;if(J)return`${G?`${G} `:""}${J}`;if(W)return W;return"plugin"}function R7($){let w=a1($.data?.message??$.data?.reason);return w?` — ${w}`:""}function a1($){return typeof $==="string"&&$.length>0?$:void 0}import{appendFile as Kx,chmod as UB,mkdir as Ux}from"node:fs/promises";import Hx from"node:path";class I7{file;shouldPersist;#$=Promise.resolve();#w=[];constructor($,w,G=()=>!0){this.file=$;this.shouldPersist=G;w.on((Z)=>this.write(Z))}write($){if(!this.shouldPersist())return this.#w.push($),Promise.resolve();let w=[...this.#w.splice(0),$],G=this.#$.then(async()=>{let Z=Hx.dirname(this.file);await Ux(Z,{recursive:!0,mode:448}),await UB(Z,448),await Kx(this.file,`${w.map((X)=>JSON.stringify(X)).join(`
154
294
  `)}
155
- `,{encoding:"utf8",mode:384}),await uT(this.file,384)});return this.#$=G.catch(()=>{}),G}async flush(){await this.#$}}var IF=[/\brm\s+(?:-[^\s]*r[^\s]*\s+|--recursive\b)/i,/\bsudo\b/i,/\bgit\b[^;&|\n]*\breset\s+--hard\b/i,/\bgit\b[^;&|\n]*\bclean\s+(?:-[^\s]*f[^\s]*|--force)\b/i,/\bgit\b[^;&|\n]*\bpush\b[^;&|\n]*(?:--force(?:-with-lease)?|-f)\b/i,/\bgit\b[^;&|\n]*\bcheckout\s+--\s/i,/\bgit\b[^;&|\n]*\brestore\b/i,/\b(?:mkfs|fdisk|dd)\b/i,/\b(?:killall|pkill)\b/i,/(?:curl|wget)[^|;&]*(?:\||&&)\s*(?:sh|bash)\b/i,/(?:^|\s)(?:\/etc|\/usr|\/bin|\/sbin)\//];function bF($){return IF.some((w)=>w.test($))?"dangerous":"modify"}class zW{auto;prompt;#$=new Set;constructor($,w){this.auto=$;this.prompt=w}async authorize($,w,G){let W=$.risk;if($.name==="bash"&&typeof w.input?.command==="string"){if(bF(w.input.command)==="dangerous")W="dangerous"}if(this.auto||W==="read"||W==="modify"&&this.#$.has($.name))return{allowed:!0,risk:W};if(!this.prompt)return{allowed:!1,risk:W};let Y=await this.prompt($,w,W,G);if(Y==="allow_session"&&W!=="dangerous")this.#$.add($.name);return{allowed:Y!=="deny",risk:W}}}function I($,w,G,W,Y){if(W==="m")throw TypeError("Private method is not writable");if(W==="a"&&!Y)throw TypeError("Private accessor was defined without a setter");if(typeof w==="function"?$!==w||!Y:!w.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return W==="a"?Y.call($,G):Y?Y.value=G:w.set($,G),G}function H($,w,G,W){if(G==="a"&&!W)throw TypeError("Private accessor was defined without a getter");if(typeof w==="function"?$!==w||!W:!w.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return G==="m"?W:G==="a"?W.call($):W?W.value:w.get($)}var KW=function(){let{crypto:$}=globalThis;if($?.randomUUID)return KW=$.randomUUID.bind($),$.randomUUID();let w=new Uint8Array(1),G=$?()=>$.getRandomValues(w)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(W)=>(+W^G()&15>>+W/4).toString(16))};function F1($){return typeof $==="object"&&$!==null&&(("name"in $)&&$.name==="AbortError"||("message"in $)&&String($.message).includes("FetchRequestCanceledException"))}var A4=($)=>{if($ instanceof Error)return $;if(typeof $==="object"&&$!==null){try{if(Object.prototype.toString.call($)==="[object Error]"){let w=Error($.message,$.cause?{cause:$.cause}:{});if($.stack)w.stack=$.stack;if($.cause&&!w.cause)w.cause=$.cause;if($.name)w.name=$.name;return w}}catch{}try{return Error(JSON.stringify($))}catch{}}return Error($)};class b extends Error{}class X0 extends b{constructor($,w,G,W){super(`${X0.makeMessage($,w,G)}`);this.status=$,this.headers=W,this.requestID=W?.get("request-id"),this.error=w}static makeMessage($,w,G){let W=w?.message?typeof w.message==="string"?w.message:JSON.stringify(w.message):w?JSON.stringify(w):G;if($&&W)return`${$} ${W}`;if($)return`${$} status code (no body)`;if(W)return W;return"(no status code or body)"}static generate($,w,G,W){if(!$||!W)return new E$({message:G,cause:A4(w)});let Y=w;if($===400)return new R4($,Y,G,W);if($===401)return new j4($,Y,G,W);if($===403)return new C4($,Y,G,W);if($===404)return new y4($,Y,G,W);if($===409)return new I4($,Y,G,W);if($===422)return new b4($,Y,G,W);if($===429)return new x4($,Y,G,W);if($>=500)return new _4($,Y,G,W);return new X0($,Y,G,W)}}class q0 extends X0{constructor({message:$}={}){super(void 0,void 0,$||"Request was aborted.",void 0)}}class E$ extends X0{constructor({message:$,cause:w}){super(void 0,void 0,$||"Connection error.",void 0);if(w)this.cause=w}}class S4 extends E${constructor({message:$}={}){super({message:$??"Request timed out."})}}class R4 extends X0{}class j4 extends X0{}class C4 extends X0{}class y4 extends X0{}class I4 extends X0{}class b4 extends X0{}class x4 extends X0{}class _4 extends X0{}var _F=/^[a-z][a-z0-9+.-]*:/i,hT=($)=>{return _F.test($)},PW=($)=>(PW=Array.isArray,PW($)),BW=PW;function VW($){if(typeof $!=="object")return{};return $??{}}function iT($){if(!$)return!0;for(let w in $)return!1;return!0}function mT($,w){return Object.prototype.hasOwnProperty.call($,w)}var lT=($,w)=>{if(typeof w!=="number"||!Number.isInteger(w))throw new b(`${$} must be an integer`);if(w<0)throw new b(`${$} must be a positive integer`);return w};var z6=($)=>{try{return JSON.parse($)}catch(w){return}};var cT=($)=>new Promise((w)=>setTimeout(w,$));var n1="0.61.0";var tT=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"};function gF(){if(typeof Deno<"u"&&Deno.build!=null)return"deno";if(typeof EdgeRuntime<"u")return"edge";if(Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]")return"node";return"unknown"}var vF=()=>{let $=gF();if($==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":n1,"X-Stainless-OS":nT(Deno.build.os),"X-Stainless-Arch":dT(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version==="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":n1,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if($==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":n1,"X-Stainless-OS":nT(globalThis.process.platform??"unknown"),"X-Stainless-Arch":dT(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let w=uF();if(w)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":n1,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${w.browser}`,"X-Stainless-Runtime-Version":w.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":n1,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function uF(){if(typeof navigator>"u"||!navigator)return null;let $=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:w,pattern:G}of $){let W=G.exec(navigator.userAgent);if(W){let Y=W[1]||0,Z=W[2]||0,X=W[3]||0;return{browser:w,version:`${Y}.${Z}.${X}`}}}return null}var dT=($)=>{if($==="x32")return"x32";if($==="x86_64"||$==="x64")return"x64";if($==="arm")return"arm";if($==="aarch64"||$==="arm64")return"arm64";if($)return`other:${$}`;return"unknown"},nT=($)=>{if($=$.toLowerCase(),$.includes("ios"))return"iOS";if($==="android")return"Android";if($==="darwin")return"MacOS";if($==="win32")return"Windows";if($==="freebsd")return"FreeBSD";if($==="openbsd")return"OpenBSD";if($==="linux")return"Linux";if($)return`Other:${$}`;return"Unknown"},pT,rT=()=>{return pT??(pT=vF())};function sT(){if(typeof fetch<"u")return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function qW(...$){let w=globalThis.ReadableStream;if(typeof w>"u")throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new w(...$)}function K6($){let w=Symbol.asyncIterator in $?$[Symbol.asyncIterator]():$[Symbol.iterator]();return qW({start(){},async pull(G){let{done:W,value:Y}=await w.next();if(W)G.close();else G.enqueue(Y)},async cancel(){await w.return?.()}})}function g4($){if($[Symbol.asyncIterator])return $;let w=$.getReader();return{async next(){try{let G=await w.read();if(G?.done)w.releaseLock();return G}catch(G){throw w.releaseLock(),G}},async return(){let G=w.cancel();return w.releaseLock(),await G,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function aT($){if($===null||typeof $!=="object")return;if($[Symbol.asyncIterator]){await $[Symbol.asyncIterator]().return?.();return}let w=$.getReader(),G=w.cancel();w.releaseLock(),await G}var oT=({headers:$,body:w})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(w)}};function wM($){let w=0;for(let Y of $)w+=Y.length;let G=new Uint8Array(w),W=0;for(let Y of $)G.set(Y,W),W+=Y.length;return G}var eT;function v4($){let w;return(eT??(w=new globalThis.TextEncoder,eT=w.encode.bind(w)))($)}var $M;function EW($){let w;return($M??(w=new globalThis.TextDecoder,$M=w.decode.bind(w)))($)}var y0,I0;class p1{constructor(){y0.set(this,void 0),I0.set(this,void 0),I(this,y0,new Uint8Array,"f"),I(this,I0,null,"f")}decode($){if($==null)return[];let w=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?v4($):$;I(this,y0,wM([H(this,y0,"f"),w]),"f");let G=[],W;while((W=mF(H(this,y0,"f"),H(this,I0,"f")))!=null){if(W.carriage&&H(this,I0,"f")==null){I(this,I0,W.index,"f");continue}if(H(this,I0,"f")!=null&&(W.index!==H(this,I0,"f")+1||W.carriage)){G.push(EW(H(this,y0,"f").subarray(0,H(this,I0,"f")-1))),I(this,y0,H(this,y0,"f").subarray(H(this,I0,"f")),"f"),I(this,I0,null,"f");continue}let Y=H(this,I0,"f")!==null?W.preceding-1:W.preceding,Z=EW(H(this,y0,"f").subarray(0,Y));G.push(Z),I(this,y0,H(this,y0,"f").subarray(W.index),"f"),I(this,I0,null,"f")}return G}flush(){if(!H(this,y0,"f").length)return[];return this.decode(`
156
- `)}}y0=new WeakMap,I0=new WeakMap;p1.NEWLINE_CHARS=new Set([`
157
- `,"\r"]);p1.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function mF($,w){for(let Y=w??0;Y<$.length;Y++){if($[Y]===10)return{preceding:Y,index:Y+1,carriage:!1};if($[Y]===13)return{preceding:Y,index:Y+1,carriage:!0}}return null}function GM($){for(let W=0;W<$.length-1;W++){if($[W]===10&&$[W+1]===10)return W+2;if($[W]===13&&$[W+1]===13)return W+2;if($[W]===13&&$[W+1]===10&&W+3<$.length&&$[W+2]===13&&$[W+3]===10)return W+4}return-1}var B6={off:0,error:200,warn:300,info:400,debug:500},UW=($,w,G)=>{if(!$)return;if(mT(B6,$))return $;Q0(G).warn(`${w} was set to ${JSON.stringify($)}, expected one of ${JSON.stringify(Object.keys(B6))}`);return};function u4(){}function P6($,w,G){if(!w||B6[$]>B6[G])return u4;else return w[$].bind(w)}var lF={error:u4,warn:u4,info:u4,debug:u4},WM=new WeakMap;function Q0($){let w=$.logger,G=$.logLevel??"off";if(!w)return lF;let W=WM.get(w);if(W&&W[0]===G)return W[1];let Y={error:P6("error",w,G),warn:P6("warn",w,G),info:P6("info",w,G),debug:P6("debug",w,G)};return WM.set(w,[G,Y]),Y}var O1=($)=>{if($.options)$.options={...$.options},delete $.options.headers;if($.headers)$.headers=Object.fromEntries(($.headers instanceof Headers?[...$.headers]:Object.entries($.headers)).map(([w,G])=>[w,w.toLowerCase()==="x-api-key"||w.toLowerCase()==="authorization"||w.toLowerCase()==="cookie"||w.toLowerCase()==="set-cookie"?"***":G]));if("retryOfRequestLogID"in $){if($.retryOfRequestLogID)$.retryOf=$.retryOfRequestLogID;delete $.retryOfRequestLogID}return $};var h4;class b0{constructor($,w,G){this.iterator=$,h4.set(this,void 0),this.controller=w,I(this,h4,G,"f")}static fromSSEResponse($,w,G){let W=!1,Y=G?Q0(G):console;async function*Z(){if(W)throw new b("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");W=!0;let X=!1;try{for await(let J of cF($,w)){if(J.event==="completion")try{yield JSON.parse(J.data)}catch(T){throw Y.error("Could not parse message into JSON:",J.data),Y.error("From chunk:",J.raw),T}if(J.event==="message_start"||J.event==="message_delta"||J.event==="message_stop"||J.event==="content_block_start"||J.event==="content_block_delta"||J.event==="content_block_stop")try{yield JSON.parse(J.data)}catch(T){throw Y.error("Could not parse message into JSON:",J.data),Y.error("From chunk:",J.raw),T}if(J.event==="ping")continue;if(J.event==="error")throw new X0(void 0,z6(J.data)??J.data,void 0,$.headers)}X=!0}catch(J){if(F1(J))return;throw J}finally{if(!X)w.abort()}}return new b0(Z,w,G)}static fromReadableStream($,w,G){let W=!1;async function*Y(){let X=new p1,J=g4($);for await(let T of J)for(let M of X.decode(T))yield M;for(let T of X.flush())yield T}async function*Z(){if(W)throw new b("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");W=!0;let X=!1;try{for await(let J of Y()){if(X)continue;if(J)yield JSON.parse(J)}X=!0}catch(J){if(F1(J))return;throw J}finally{if(!X)w.abort()}}return new b0(Z,w,G)}[(h4=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let $=[],w=[],G=this.iterator(),W=(Y)=>{return{next:()=>{if(Y.length===0){let Z=G.next();$.push(Z),w.push(Z)}return Y.shift()}}};return[new b0(()=>W($),this.controller,H(this,h4,"f")),new b0(()=>W(w),this.controller,H(this,h4,"f"))]}toReadableStream(){let $=this,w;return qW({async start(){w=$[Symbol.asyncIterator]()},async pull(G){try{let{value:W,done:Y}=await w.next();if(Y)return G.close();let Z=v4(JSON.stringify(W)+`
158
- `);G.enqueue(Z)}catch(W){G.error(W)}},async cancel(){await w.return?.()}})}}async function*cF($,w){if(!$.body){if(w.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new b("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new b("Attempted to iterate over a response with no body")}let G=new YM,W=new p1,Y=g4($.body);for await(let Z of dF(Y))for(let X of W.decode(Z)){let J=G.decode(X);if(J)yield J}for(let Z of W.flush()){let X=G.decode(Z);if(X)yield X}}async function*dF($){let w=new Uint8Array;for await(let G of $){if(G==null)continue;let W=G instanceof ArrayBuffer?new Uint8Array(G):typeof G==="string"?v4(G):G,Y=new Uint8Array(w.length+W.length);Y.set(w),Y.set(W,w.length),w=Y;let Z;while((Z=GM(w))!==-1)yield w.slice(0,Z),w=w.slice(Z)}if(w.length>0)yield w}class YM{constructor(){this.event=null,this.data=[],this.chunks=[]}decode($){if($.endsWith("\r"))$=$.substring(0,$.length-1);if(!$){if(!this.event&&!this.data.length)return null;let Y={event:this.event,data:this.data.join(`
159
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],Y}if(this.chunks.push($),$.startsWith(":"))return null;let[w,G,W]=nF($,":");if(W.startsWith(" "))W=W.substring(1);if(w==="event")this.event=W;else if(w==="data")this.data.push(W);return null}}function nF($,w){let G=$.indexOf(w);if(G!==-1)return[$.substring(0,G),w,$.substring(G+w.length)];return[$,"",""]}async function V6($,w){let{response:G,requestLogID:W,retryOfRequestLogID:Y,startTime:Z}=w,X=await(async()=>{if(w.options.stream){if(Q0($).debug("response",G.status,G.url,G.headers,G.body),w.options.__streamClass)return w.options.__streamClass.fromSSEResponse(G,w.controller);return b0.fromSSEResponse(G,w.controller)}if(G.status===204)return null;if(w.options.__binaryResponse)return G;let T=G.headers.get("content-type")?.split(";")[0]?.trim();if(T?.includes("application/json")||T?.endsWith("+json")){let Q=await G.json();return HW(Q,G)}return await G.text()})();return Q0($).debug(`[${W}] response parsed`,O1({retryOfRequestLogID:Y,url:G.url,status:G.status,body:X,durationMs:Date.now()-Z})),X}function HW($,w){if(!$||typeof $!=="object"||Array.isArray($))return $;return Object.defineProperty($,"_request_id",{value:w.headers.get("request-id"),enumerable:!1})}var i4;class U$ extends Promise{constructor($,w,G=V6){super((W)=>{W(null)});this.responsePromise=w,this.parseResponse=G,i4.set(this,void 0),I(this,i4,$,"f")}_thenUnwrap($){return new U$(H(this,i4,"f"),this.responsePromise,async(w,G)=>HW($(await this.parseResponse(w,G),G),G.response))}asResponse(){return this.responsePromise.then(($)=>$.response)}async withResponse(){let[$,w]=await Promise.all([this.parse(),this.asResponse()]);return{data:$,response:w,request_id:w.headers.get("request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then(($)=>this.parseResponse(H(this,i4,"f"),$));return this.parsedPromise}then($,w){return this.parse().then($,w)}catch($){return this.parse().catch($)}finally($){return this.parse().finally($)}}i4=new WeakMap;var q6;class ZM{constructor($,w,G,W){q6.set(this,void 0),I(this,q6,$,"f"),this.options=W,this.response=w,this.body=G}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageRequestOptions()!=null}async getNextPage(){let $=this.nextPageRequestOptions();if(!$)throw new b("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await H(this,q6,"f").requestAPIList(this.constructor,$)}async*iterPages(){let $=this;yield $;while($.hasNextPage())$=await $.getNextPage(),yield $}async*[(q6=new WeakMap,Symbol.asyncIterator)](){for await(let $ of this.iterPages())for(let w of $.getPaginatedItems())yield w}}class E6 extends U${constructor($,w,G){super($,w,async(W,Y)=>new G(W,Y.response,await V6(W,Y),Y.options))}async*[Symbol.asyncIterator](){let $=await this;for await(let w of $)yield w}}class $1 extends ZM{constructor($,w,G,W){super($,w,G,W);this.data=G.data||[],this.has_more=G.has_more||!1,this.first_id=G.first_id||null,this.last_id=G.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){let w=this.first_id;if(!w)return null;return{...this.options,query:{...VW(this.options.query),before_id:w}}}let $=this.last_id;if(!$)return null;return{...this.options,query:{...VW(this.options.query),after_id:$}}}}var OW=()=>{if(typeof File>"u"){let{process:$}=globalThis,w=typeof $?.versions?.node==="string"&&parseInt($.versions.node.split("."))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(w?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function H$($,w,G){return OW(),new File($,w??"unknown_file",G)}function m4($){return(typeof $==="object"&&$!==null&&(("name"in $)&&$.name&&String($.name)||("url"in $)&&$.url&&String($.url)||("filename"in $)&&$.filename&&String($.filename)||("path"in $)&&$.path&&String($.path))||"").split(/[\\/]/).pop()||void 0}var LW=($)=>$!=null&&typeof $==="object"&&typeof $[Symbol.asyncIterator]==="function";var JM=async($,w)=>{return{...$,body:await rF($.body,w)}},XM=new WeakMap;function tF($){let w=typeof $==="function"?$:$.fetch,G=XM.get(w);if(G)return G;let W=(async()=>{try{let Y="Response"in w?w.Response:(await w("data:,")).constructor,Z=new FormData;if(Z.toString()===await new Y(Z).text())return!1;return!0}catch{return!0}})();return XM.set(w,W),W}var rF=async($,w)=>{if(!await tF(w))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let G=new FormData;return await Promise.all(Object.entries($||{}).map(([W,Y])=>FW(G,W,Y))),G},sF=($)=>$ instanceof Blob&&("name"in $);var FW=async($,w,G)=>{if(G===void 0)return;if(G==null)throw TypeError(`Received null for "${w}"; to pass null in FormData, you must use the string 'null'`);if(typeof G==="string"||typeof G==="number"||typeof G==="boolean")$.append(w,String(G));else if(G instanceof Response){let W={},Y=G.headers.get("Content-Type");if(Y)W={type:Y};$.append(w,H$([await G.blob()],m4(G),W))}else if(LW(G))$.append(w,H$([await new Response(K6(G)).blob()],m4(G)));else if(sF(G))$.append(w,H$([G],m4(G),{type:G.type}));else if(Array.isArray(G))await Promise.all(G.map((W)=>FW($,w+"[]",W)));else if(typeof G==="object")await Promise.all(Object.entries(G).map(([W,Y])=>FW($,`${w}[${W}]`,Y)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${G} instead`)};var TM=($)=>$!=null&&typeof $==="object"&&typeof $.size==="number"&&typeof $.type==="string"&&typeof $.text==="function"&&typeof $.slice==="function"&&typeof $.arrayBuffer==="function",aF=($)=>$!=null&&typeof $==="object"&&typeof $.name==="string"&&typeof $.lastModified==="number"&&TM($),oF=($)=>$!=null&&typeof $==="object"&&typeof $.url==="string"&&typeof $.blob==="function";async function U6($,w,G){if(OW(),$=await $,w||(w=m4($)),aF($)){if($ instanceof File&&w==null&&G==null)return $;return H$([await $.arrayBuffer()],w??$.name,{type:$.type,lastModified:$.lastModified,...G})}if(oF($)){let Y=await $.blob();return w||(w=new URL($.url).pathname.split(/[\\/]/).pop()),H$(await DW(Y),w,G)}let W=await DW($);if(!G?.type){let Y=W.find((Z)=>typeof Z==="object"&&("type"in Z)&&Z.type);if(typeof Y==="string")G={...G,type:Y}}return H$(W,w,G)}async function DW($){let w=[];if(typeof $==="string"||ArrayBuffer.isView($)||$ instanceof ArrayBuffer)w.push($);else if(TM($))w.push($ instanceof Blob?$:await $.arrayBuffer());else if(LW($))for await(let G of $)w.push(...await DW(G));else{let G=$?.constructor?.name;throw Error(`Unexpected data type: ${typeof $}${G?`; constructor: ${G}`:""}${eF($)}`)}return w}function eF($){if(typeof $!=="object"||$===null)return"";return`; props: [${Object.getOwnPropertyNames($).map((G)=>`"${G}"`).join(", ")}]`}class J0{constructor($){this._client=$}}var MM=Symbol.for("brand.privateNullableHeaders");function*wO($){if(!$)return;if(MM in $){let{values:W,nulls:Y}=$;yield*W.entries();for(let Z of Y)yield[Z,null];return}let w=!1,G;if($ instanceof Headers)G=$.entries();else if(BW($))G=$;else w=!0,G=Object.entries($??{});for(let W of G){let Y=W[0];if(typeof Y!=="string")throw TypeError("expected header name to be a string");let Z=BW(W[1])?W[1]:[W[1]],X=!1;for(let J of Z){if(J===void 0)continue;if(w&&!X)X=!0,yield[Y,null];yield[Y,J]}}}var n=($)=>{let w=new Headers,G=new Set;for(let W of $){let Y=new Set;for(let[Z,X]of wO(W)){let J=Z.toLowerCase();if(!Y.has(J))w.delete(Z),Y.add(J);if(X===null)w.delete(Z),G.add(J);else w.append(Z,X),G.delete(J)}}return{[MM]:!0,values:w,nulls:G}};function QM($){return $.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var fM=Object.freeze(Object.create(null)),GO=($=QM)=>function(G,...W){if(G.length===1)return G[0];let Y=!1,Z=[],X=G.reduce((f,Q,N)=>{if(/[?#]/.test(Q))Y=!0;let z=W[N],K=(Y?encodeURIComponent:$)(""+z);if(N!==W.length&&(z==null||typeof z==="object"&&z.toString===Object.getPrototypeOf(Object.getPrototypeOf(z.hasOwnProperty??fM)??fM)?.toString))K=z+"",Z.push({start:f.length+Q.length,length:K.length,error:`Value of type ${Object.prototype.toString.call(z).slice(8,-1)} is not a valid path parameter`});return f+Q+(N===W.length?"":K)},""),J=X.split(/[?#]/,1)[0],T=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,M;while((M=T.exec(J))!==null)Z.push({start:M.index,length:M[0].length,error:`Value "${M[0]}" can't be safely passed as a path parameter`});if(Z.sort((f,Q)=>f.start-Q.start),Z.length>0){let f=0,Q=Z.reduce((N,z)=>{let K=" ".repeat(z.start-f),P="^".repeat(z.length);return f=z.start+z.length,N+K+P},"");throw new b(`Path parameters result in path with invalid segments:
160
- ${Z.map((N)=>N.error).join(`
295
+ `,{encoding:"utf8",mode:384}),await UB(this.file,384)});return this.#$=G.catch(()=>{}),G}async flush(){await this.#$}}var Fx=[/\brm\s+(?:-[^\s]*r[^\s]*\s+|--recursive\b)/i,/\bsudo\b/i,/\bgit\b[^;&|\n]*\breset\s+--hard\b/i,/\bgit\b[^;&|\n]*\bclean\s+(?:-[^\s]*f[^\s]*|--force)\b/i,/\bgit\b[^;&|\n]*\bpush\b[^;&|\n]*(?:--force(?:-with-lease)?|-f)\b/i,/\bgit\b[^;&|\n]*\bcheckout\s+--\s/i,/\bgit\b[^;&|\n]*\brestore\b/i,/\b(?:mkfs|fdisk|dd)\b/i,/\b(?:killall|pkill)\b/i,/(?:curl|wget)[^|;&]*(?:\||&&)\s*(?:sh|bash)\b/i,/(?:^|\s)(?:\/etc|\/usr|\/bin|\/sbin)\//];function Ox($){return Fx.some((w)=>w.test($))?"dangerous":"modify"}class j7{auto;prompt;#$=new Set;constructor($,w){this.auto=$;this.prompt=w}get isAuto(){return this.auto}async authorize($,w,G,Z){let X=Z??$.risk;if($.name==="bash"&&typeof w.input?.command==="string"){if(Ox(w.input.command)==="dangerous")X="dangerous"}if(this.auto||X==="read"||X==="modify"&&this.#$.has($.name))return{allowed:!0,risk:X};if(!this.prompt)return{allowed:!1,risk:X};let Y=await this.prompt($,w,X,G);if(Y==="allow_session"&&X!=="dangerous")this.#$.add($.name);return{allowed:Y!=="deny",risk:X}}}function _($,w,G,Z,X){if(Z==="m")throw TypeError("Private method is not writable");if(Z==="a"&&!X)throw TypeError("Private accessor was defined without a setter");if(typeof w==="function"?$!==w||!X:!w.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return Z==="a"?X.call($,G):X?X.value=G:w.set($,G),G}function A($,w,G,Z){if(G==="a"&&!Z)throw TypeError("Private accessor was defined without a getter");if(typeof w==="function"?$!==w||!Z:!w.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return G==="m"?Z:G==="a"?Z.call($):Z?Z.value:w.get($)}var C7=function(){let{crypto:$}=globalThis;if($?.randomUUID)return C7=$.randomUUID.bind($),$.randomUUID();let w=new Uint8Array(1),G=$?()=>$.getRandomValues(w)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(Z)=>(+Z^G()&15>>+Z/4).toString(16))};function _$($){return typeof $==="object"&&$!==null&&(("name"in $)&&$.name==="AbortError"||("message"in $)&&String($.message).includes("FetchRequestCanceledException"))}var m9=($)=>{if($ instanceof Error)return $;if(typeof $==="object"&&$!==null){try{if(Object.prototype.toString.call($)==="[object Error]"){let w=Error($.message,$.cause?{cause:$.cause}:{});if($.stack)w.stack=$.stack;if($.cause&&!w.cause)w.cause=$.cause;if($.name)w.name=$.name;return w}}catch{}try{return Error(JSON.stringify($))}catch{}}return Error($)};class x extends Error{}class M0 extends x{constructor($,w,G,Z){super(`${M0.makeMessage($,w,G)}`);this.status=$,this.headers=Z,this.requestID=Z?.get("request-id"),this.error=w}static makeMessage($,w,G){let Z=w?.message?typeof w.message==="string"?w.message:JSON.stringify(w.message):w?JSON.stringify(w):G;if($&&Z)return`${$} ${Z}`;if($)return`${$} status code (no body)`;if(Z)return Z;return"(no status code or body)"}static generate($,w,G,Z){if(!$||!Z)return new t1({message:G,cause:m9(w)});let X=w;if($===400)return new d9($,X,G,Z);if($===401)return new c9($,X,G,Z);if($===403)return new p9($,X,G,Z);if($===404)return new n9($,X,G,Z);if($===409)return new r9($,X,G,Z);if($===422)return new s9($,X,G,Z);if($===429)return new a9($,X,G,Z);if($>=500)return new t9($,X,G,Z);return new M0($,X,G,Z)}}class L0 extends M0{constructor({message:$}={}){super(void 0,void 0,$||"Request was aborted.",void 0)}}class t1 extends M0{constructor({message:$,cause:w}){super(void 0,void 0,$||"Connection error.",void 0);if(w)this.cause=w}}class l9 extends t1{constructor({message:$}={}){super({message:$??"Request timed out."})}}class d9 extends M0{}class c9 extends M0{}class p9 extends M0{}class n9 extends M0{}class r9 extends M0{}class s9 extends M0{}class a9 extends M0{}class t9 extends M0{}var Lx=/^[a-z][a-z0-9+.-]*:/i,HB=($)=>{return Lx.test($)},b7=($)=>(b7=Array.isArray,b7($)),k7=b7;function y7($){if(typeof $!=="object")return{};return $??{}}function FB($){if(!$)return!0;for(let w in $)return!1;return!0}function OB($,w){return Object.prototype.hasOwnProperty.call($,w)}var fB=($,w)=>{if(typeof w!=="number"||!Number.isInteger(w))throw new x(`${$} must be an integer`);if(w<0)throw new x(`${$} must be a positive integer`);return w};var VG=($)=>{try{return JSON.parse($)}catch(w){return}};var LB=($)=>new Promise((w)=>setTimeout(w,$));var B1="0.61.0";var RB=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"};function Dx(){if(typeof Deno<"u"&&Deno.build!=null)return"deno";if(typeof EdgeRuntime<"u")return"edge";if(Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]")return"node";return"unknown"}var Ex=()=>{let $=Dx();if($==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":B1,"X-Stainless-OS":EB(Deno.build.os),"X-Stainless-Arch":DB(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version==="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":B1,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if($==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":B1,"X-Stainless-OS":EB(globalThis.process.platform??"unknown"),"X-Stainless-Arch":DB(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let w=Ax();if(w)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":B1,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${w.browser}`,"X-Stainless-Runtime-Version":w.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":B1,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Ax(){if(typeof navigator>"u"||!navigator)return null;let $=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:w,pattern:G}of $){let Z=G.exec(navigator.userAgent);if(Z){let X=Z[1]||0,Y=Z[2]||0,J=Z[3]||0;return{browser:w,version:`${X}.${Y}.${J}`}}}return null}var DB=($)=>{if($==="x32")return"x32";if($==="x86_64"||$==="x64")return"x64";if($==="arm")return"arm";if($==="aarch64"||$==="arm64")return"arm64";if($)return`other:${$}`;return"unknown"},EB=($)=>{if($=$.toLowerCase(),$.includes("ios"))return"iOS";if($==="android")return"Android";if($==="darwin")return"MacOS";if($==="win32")return"Windows";if($==="freebsd")return"FreeBSD";if($==="openbsd")return"OpenBSD";if($==="linux")return"Linux";if($)return`Other:${$}`;return"Unknown"},AB,SB=()=>{return AB??(AB=Ex())};function IB(){if(typeof fetch<"u")return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function _7(...$){let w=globalThis.ReadableStream;if(typeof w>"u")throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new w(...$)}function KG($){let w=Symbol.asyncIterator in $?$[Symbol.asyncIterator]():$[Symbol.iterator]();return _7({start(){},async pull(G){let{done:Z,value:X}=await w.next();if(Z)G.close();else G.enqueue(X)},async cancel(){await w.return?.()}})}function o9($){if($[Symbol.asyncIterator])return $;let w=$.getReader();return{async next(){try{let G=await w.read();if(G?.done)w.releaseLock();return G}catch(G){throw w.releaseLock(),G}},async return(){let G=w.cancel();return w.releaseLock(),await G,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function jB($){if($===null||typeof $!=="object")return;if($[Symbol.asyncIterator]){await $[Symbol.asyncIterator]().return?.();return}let w=$.getReader(),G=w.cancel();w.releaseLock(),await G}var CB=({headers:$,body:w})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(w)}};function yB($){let w=0;for(let X of $)w+=X.length;let G=new Uint8Array(w),Z=0;for(let X of $)G.set(X,Z),Z+=X.length;return G}var bB;function e9($){let w;return(bB??(w=new globalThis.TextEncoder,bB=w.encode.bind(w)))($)}var kB;function x7($){let w;return(kB??(w=new globalThis.TextDecoder,kB=w.decode.bind(w)))($)}var x0,g0;class N1{constructor(){x0.set(this,void 0),g0.set(this,void 0),_(this,x0,new Uint8Array,"f"),_(this,g0,null,"f")}decode($){if($==null)return[];let w=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?e9($):$;_(this,x0,yB([A(this,x0,"f"),w]),"f");let G=[],Z;while((Z=Ix(A(this,x0,"f"),A(this,g0,"f")))!=null){if(Z.carriage&&A(this,g0,"f")==null){_(this,g0,Z.index,"f");continue}if(A(this,g0,"f")!=null&&(Z.index!==A(this,g0,"f")+1||Z.carriage)){G.push(x7(A(this,x0,"f").subarray(0,A(this,g0,"f")-1))),_(this,x0,A(this,x0,"f").subarray(A(this,g0,"f")),"f"),_(this,g0,null,"f");continue}let X=A(this,g0,"f")!==null?Z.preceding-1:Z.preceding,Y=x7(A(this,x0,"f").subarray(0,X));G.push(Y),_(this,x0,A(this,x0,"f").subarray(Z.index),"f"),_(this,g0,null,"f")}return G}flush(){if(!A(this,x0,"f").length)return[];return this.decode(`
296
+ `)}}x0=new WeakMap,g0=new WeakMap;N1.NEWLINE_CHARS=new Set([`
297
+ `,"\r"]);N1.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Ix($,w){for(let X=w??0;X<$.length;X++){if($[X]===10)return{preceding:X,index:X+1,carriage:!1};if($[X]===13)return{preceding:X,index:X+1,carriage:!0}}return null}function _B($){for(let Z=0;Z<$.length-1;Z++){if($[Z]===10&&$[Z+1]===10)return Z+2;if($[Z]===13&&$[Z+1]===13)return Z+2;if($[Z]===13&&$[Z+1]===10&&Z+3<$.length&&$[Z+2]===13&&$[Z+3]===10)return Z+4}return-1}var HG={off:0,error:200,warn:300,info:400,debug:500},g7=($,w,G)=>{if(!$)return;if(OB(HG,$))return $;V0(G).warn(`${w} was set to ${JSON.stringify($)}, expected one of ${JSON.stringify(Object.keys(HG))}`);return};function $8(){}function UG($,w,G){if(!w||HG[$]>HG[G])return $8;else return w[$].bind(w)}var jx={error:$8,warn:$8,info:$8,debug:$8},xB=new WeakMap;function V0($){let w=$.logger,G=$.logLevel??"off";if(!w)return jx;let Z=xB.get(w);if(Z&&Z[0]===G)return Z[1];let X={error:UG("error",w,G),warn:UG("warn",w,G),info:UG("info",w,G),debug:UG("debug",w,G)};return xB.set(w,[G,X]),X}var x$=($)=>{if($.options)$.options={...$.options},delete $.options.headers;if($.headers)$.headers=Object.fromEntries(($.headers instanceof Headers?[...$.headers]:Object.entries($.headers)).map(([w,G])=>[w,w.toLowerCase()==="x-api-key"||w.toLowerCase()==="authorization"||w.toLowerCase()==="cookie"||w.toLowerCase()==="set-cookie"?"***":G]));if("retryOfRequestLogID"in $){if($.retryOfRequestLogID)$.retryOf=$.retryOfRequestLogID;delete $.retryOfRequestLogID}return $};var w8;class u0{constructor($,w,G){this.iterator=$,w8.set(this,void 0),this.controller=w,_(this,w8,G,"f")}static fromSSEResponse($,w,G){let Z=!1,X=G?V0(G):console;async function*Y(){if(Z)throw new x("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");Z=!0;let J=!1;try{for await(let W of Cx($,w)){if(W.event==="completion")try{yield JSON.parse(W.data)}catch(T){throw X.error("Could not parse message into JSON:",W.data),X.error("From chunk:",W.raw),T}if(W.event==="message_start"||W.event==="message_delta"||W.event==="message_stop"||W.event==="content_block_start"||W.event==="content_block_delta"||W.event==="content_block_stop")try{yield JSON.parse(W.data)}catch(T){throw X.error("Could not parse message into JSON:",W.data),X.error("From chunk:",W.raw),T}if(W.event==="ping")continue;if(W.event==="error")throw new M0(void 0,VG(W.data)??W.data,void 0,$.headers)}J=!0}catch(W){if(_$(W))return;throw W}finally{if(!J)w.abort()}}return new u0(Y,w,G)}static fromReadableStream($,w,G){let Z=!1;async function*X(){let J=new N1,W=o9($);for await(let T of W)for(let Q of J.decode(T))yield Q;for(let T of J.flush())yield T}async function*Y(){if(Z)throw new x("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");Z=!0;let J=!1;try{for await(let W of X()){if(J)continue;if(W)yield JSON.parse(W)}J=!0}catch(W){if(_$(W))return;throw W}finally{if(!J)w.abort()}}return new u0(Y,w,G)}[(w8=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let $=[],w=[],G=this.iterator(),Z=(X)=>{return{next:()=>{if(X.length===0){let Y=G.next();$.push(Y),w.push(Y)}return X.shift()}}};return[new u0(()=>Z($),this.controller,A(this,w8,"f")),new u0(()=>Z(w),this.controller,A(this,w8,"f"))]}toReadableStream(){let $=this,w;return _7({async start(){w=$[Symbol.asyncIterator]()},async pull(G){try{let{value:Z,done:X}=await w.next();if(X)return G.close();let Y=e9(JSON.stringify(Z)+`
298
+ `);G.enqueue(Y)}catch(Z){G.error(Z)}},async cancel(){await w.return?.()}})}}async function*Cx($,w){if(!$.body){if(w.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new x("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new x("Attempted to iterate over a response with no body")}let G=new gB,Z=new N1,X=o9($.body);for await(let Y of bx(X))for(let J of Z.decode(Y)){let W=G.decode(J);if(W)yield W}for(let Y of Z.flush()){let J=G.decode(Y);if(J)yield J}}async function*bx($){let w=new Uint8Array;for await(let G of $){if(G==null)continue;let Z=G instanceof ArrayBuffer?new Uint8Array(G):typeof G==="string"?e9(G):G,X=new Uint8Array(w.length+Z.length);X.set(w),X.set(Z,w.length),w=X;let Y;while((Y=_B(w))!==-1)yield w.slice(0,Y),w=w.slice(Y)}if(w.length>0)yield w}class gB{constructor(){this.event=null,this.data=[],this.chunks=[]}decode($){if($.endsWith("\r"))$=$.substring(0,$.length-1);if(!$){if(!this.event&&!this.data.length)return null;let X={event:this.event,data:this.data.join(`
299
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],X}if(this.chunks.push($),$.startsWith(":"))return null;let[w,G,Z]=kx($,":");if(Z.startsWith(" "))Z=Z.substring(1);if(w==="event")this.event=Z;else if(w==="data")this.data.push(Z);return null}}function kx($,w){let G=$.indexOf(w);if(G!==-1)return[$.substring(0,G),w,$.substring(G+w.length)];return[$,"",""]}async function FG($,w){let{response:G,requestLogID:Z,retryOfRequestLogID:X,startTime:Y}=w,J=await(async()=>{if(w.options.stream){if(V0($).debug("response",G.status,G.url,G.headers,G.body),w.options.__streamClass)return w.options.__streamClass.fromSSEResponse(G,w.controller);return u0.fromSSEResponse(G,w.controller)}if(G.status===204)return null;if(w.options.__binaryResponse)return G;let T=G.headers.get("content-type")?.split(";")[0]?.trim();if(T?.includes("application/json")||T?.endsWith("+json")){let M=await G.json();return u7(M,G)}return await G.text()})();return V0($).debug(`[${Z}] response parsed`,x$({retryOfRequestLogID:X,url:G.url,status:G.status,body:J,durationMs:Date.now()-Y})),J}function u7($,w){if(!$||typeof $!=="object"||Array.isArray($))return $;return Object.defineProperty($,"_request_id",{value:w.headers.get("request-id"),enumerable:!1})}var G8;class o1 extends Promise{constructor($,w,G=FG){super((Z)=>{Z(null)});this.responsePromise=w,this.parseResponse=G,G8.set(this,void 0),_(this,G8,$,"f")}_thenUnwrap($){return new o1(A(this,G8,"f"),this.responsePromise,async(w,G)=>u7($(await this.parseResponse(w,G),G),G.response))}asResponse(){return this.responsePromise.then(($)=>$.response)}async withResponse(){let[$,w]=await Promise.all([this.parse(),this.asResponse()]);return{data:$,response:w,request_id:w.headers.get("request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then(($)=>this.parseResponse(A(this,G8,"f"),$));return this.parsedPromise}then($,w){return this.parse().then($,w)}catch($){return this.parse().catch($)}finally($){return this.parse().finally($)}}G8=new WeakMap;var OG;class uB{constructor($,w,G,Z){OG.set(this,void 0),_(this,OG,$,"f"),this.options=Z,this.response=w,this.body=G}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageRequestOptions()!=null}async getNextPage(){let $=this.nextPageRequestOptions();if(!$)throw new x("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await A(this,OG,"f").requestAPIList(this.constructor,$)}async*iterPages(){let $=this;yield $;while($.hasNextPage())$=await $.getNextPage(),yield $}async*[(OG=new WeakMap,Symbol.asyncIterator)](){for await(let $ of this.iterPages())for(let w of $.getPaginatedItems())yield w}}class fG extends o1{constructor($,w,G){super($,w,async(Z,X)=>new G(Z,X.response,await FG(Z,X),X.options))}async*[Symbol.asyncIterator](){let $=await this;for await(let w of $)yield w}}class Q$ extends uB{constructor($,w,G,Z){super($,w,G,Z);this.data=G.data||[],this.has_more=G.has_more||!1,this.first_id=G.first_id||null,this.last_id=G.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){let w=this.first_id;if(!w)return null;return{...this.options,query:{...y7(this.options.query),before_id:w}}}let $=this.last_id;if(!$)return null;return{...this.options,query:{...y7(this.options.query),after_id:$}}}}var v7=()=>{if(typeof File>"u"){let{process:$}=globalThis,w=typeof $?.versions?.node==="string"&&parseInt($.versions.node.split("."))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(w?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function e1($,w,G){return v7(),new File($,w??"unknown_file",G)}function Z8($){return(typeof $==="object"&&$!==null&&(("name"in $)&&$.name&&String($.name)||("url"in $)&&$.url&&String($.url)||("filename"in $)&&$.filename&&String($.filename)||("path"in $)&&$.path&&String($.path))||"").split(/[\\/]/).pop()||void 0}var i7=($)=>$!=null&&typeof $==="object"&&typeof $[Symbol.asyncIterator]==="function";var vB=async($,w)=>{return{...$,body:await xx($.body,w)}},hB=new WeakMap;function _x($){let w=typeof $==="function"?$:$.fetch,G=hB.get(w);if(G)return G;let Z=(async()=>{try{let X="Response"in w?w.Response:(await w("data:,")).constructor,Y=new FormData;if(Y.toString()===await new X(Y).text())return!1;return!0}catch{return!0}})();return hB.set(w,Z),Z}var xx=async($,w)=>{if(!await _x(w))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let G=new FormData;return await Promise.all(Object.entries($||{}).map(([Z,X])=>h7(G,Z,X))),G},gx=($)=>$ instanceof Blob&&("name"in $);var h7=async($,w,G)=>{if(G===void 0)return;if(G==null)throw TypeError(`Received null for "${w}"; to pass null in FormData, you must use the string 'null'`);if(typeof G==="string"||typeof G==="number"||typeof G==="boolean")$.append(w,String(G));else if(G instanceof Response){let Z={},X=G.headers.get("Content-Type");if(X)Z={type:X};$.append(w,e1([await G.blob()],Z8(G),Z))}else if(i7(G))$.append(w,e1([await new Response(KG(G)).blob()],Z8(G)));else if(gx(G))$.append(w,e1([G],Z8(G),{type:G.type}));else if(Array.isArray(G))await Promise.all(G.map((Z)=>h7($,w+"[]",Z)));else if(typeof G==="object")await Promise.all(Object.entries(G).map(([Z,X])=>h7($,`${w}[${Z}]`,X)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${G} instead`)};var iB=($)=>$!=null&&typeof $==="object"&&typeof $.size==="number"&&typeof $.type==="string"&&typeof $.text==="function"&&typeof $.slice==="function"&&typeof $.arrayBuffer==="function",ux=($)=>$!=null&&typeof $==="object"&&typeof $.name==="string"&&typeof $.lastModified==="number"&&iB($),hx=($)=>$!=null&&typeof $==="object"&&typeof $.url==="string"&&typeof $.blob==="function";async function LG($,w,G){if(v7(),$=await $,w||(w=Z8($)),ux($)){if($ instanceof File&&w==null&&G==null)return $;return e1([await $.arrayBuffer()],w??$.name,{type:$.type,lastModified:$.lastModified,...G})}if(hx($)){let X=await $.blob();return w||(w=new URL($.url).pathname.split(/[\\/]/).pop()),e1(await m7(X),w,G)}let Z=await m7($);if(!G?.type){let X=Z.find((Y)=>typeof Y==="object"&&("type"in Y)&&Y.type);if(typeof X==="string")G={...G,type:X}}return e1(Z,w,G)}async function m7($){let w=[];if(typeof $==="string"||ArrayBuffer.isView($)||$ instanceof ArrayBuffer)w.push($);else if(iB($))w.push($ instanceof Blob?$:await $.arrayBuffer());else if(i7($))for await(let G of $)w.push(...await m7(G));else{let G=$?.constructor?.name;throw Error(`Unexpected data type: ${typeof $}${G?`; constructor: ${G}`:""}${vx($)}`)}return w}function vx($){if(typeof $!=="object"||$===null)return"";return`; props: [${Object.getOwnPropertyNames($).map((G)=>`"${G}"`).join(", ")}]`}class P0{constructor($){this._client=$}}var mB=Symbol.for("brand.privateNullableHeaders");function*mx($){if(!$)return;if(mB in $){let{values:Z,nulls:X}=$;yield*Z.entries();for(let Y of X)yield[Y,null];return}let w=!1,G;if($ instanceof Headers)G=$.entries();else if(k7($))G=$;else w=!0,G=Object.entries($??{});for(let Z of G){let X=Z[0];if(typeof X!=="string")throw TypeError("expected header name to be a string");let Y=k7(Z[1])?Z[1]:[Z[1]],J=!1;for(let W of Y){if(W===void 0)continue;if(w&&!J)J=!0,yield[X,null];yield[X,W]}}}var s=($)=>{let w=new Headers,G=new Set;for(let Z of $){let X=new Set;for(let[Y,J]of mx(Z)){let W=Y.toLowerCase();if(!X.has(W))w.delete(Y),X.add(W);if(J===null)w.delete(Y),G.add(W);else w.append(Y,J),G.delete(W)}}return{[mB]:!0,values:w,nulls:G}};function dB($){return $.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var lB=Object.freeze(Object.create(null)),lx=($=dB)=>function(G,...Z){if(G.length===1)return G[0];let X=!1,Y=[],J=G.reduce((z,M,P)=>{if(/[?#]/.test(M))X=!0;let q=Z[P],N=(X?encodeURIComponent:$)(""+q);if(P!==Z.length&&(q==null||typeof q==="object"&&q.toString===Object.getPrototypeOf(Object.getPrototypeOf(q.hasOwnProperty??lB)??lB)?.toString))N=q+"",Y.push({start:z.length+M.length,length:N.length,error:`Value of type ${Object.prototype.toString.call(q).slice(8,-1)} is not a valid path parameter`});return z+M+(P===Z.length?"":N)},""),W=J.split(/[?#]/,1)[0],T=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,Q;while((Q=T.exec(W))!==null)Y.push({start:Q.index,length:Q[0].length,error:`Value "${Q[0]}" can't be safely passed as a path parameter`});if(Y.sort((z,M)=>z.start-M.start),Y.length>0){let z=0,M=Y.reduce((P,q)=>{let N=" ".repeat(q.start-z),B="^".repeat(q.length);return z=q.start+q.length,P+N+B},"");throw new x(`Path parameters result in path with invalid segments:
300
+ ${Y.map((P)=>P.error).join(`
161
301
  `)}
162
- ${X}
163
- ${Q}`)}return X},E0=GO(QM);class l4 extends J0{list($={},w){let{betas:G,...W}=$??{};return this._client.getAPIList("/v1/files",$1,{query:W,...w,headers:n([{"anthropic-beta":[...G??[],"files-api-2025-04-14"].toString()},w?.headers])})}delete($,w={},G){let{betas:W}=w??{};return this._client.delete(E0`/v1/files/${$}`,{...G,headers:n([{"anthropic-beta":[...W??[],"files-api-2025-04-14"].toString()},G?.headers])})}download($,w={},G){let{betas:W}=w??{};return this._client.get(E0`/v1/files/${$}/content`,{...G,headers:n([{"anthropic-beta":[...W??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},G?.headers]),__binaryResponse:!0})}retrieveMetadata($,w={},G){let{betas:W}=w??{};return this._client.get(E0`/v1/files/${$}`,{...G,headers:n([{"anthropic-beta":[...W??[],"files-api-2025-04-14"].toString()},G?.headers])})}upload($,w){let{betas:G,...W}=$;return this._client.post("/v1/files",JM({body:W,...w,headers:n([{"anthropic-beta":[...G??[],"files-api-2025-04-14"].toString()},w?.headers])},this._client))}}class c4 extends J0{retrieve($,w={},G){let{betas:W}=w??{};return this._client.get(E0`/v1/models/${$}?beta=true`,{...G,headers:n([{...W?.toString()!=null?{"anthropic-beta":W?.toString()}:void 0},G?.headers])})}list($={},w){let{betas:G,...W}=$??{};return this._client.getAPIList("/v1/models?beta=true",$1,{query:W,...w,headers:n([{...G?.toString()!=null?{"anthropic-beta":G?.toString()}:void 0},w?.headers])})}}class fw{constructor($,w){this.iterator=$,this.controller=w}async*decoder(){let $=new p1;for await(let w of this.iterator)for(let G of $.decode(w))yield JSON.parse(G);for(let w of $.flush())yield JSON.parse(w)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse($,w){if(!$.body){if(w.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new b("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new b("Attempted to iterate over a response with no body")}return new fw(g4($.body),w)}}class d4 extends J0{create($,w){let{betas:G,...W}=$;return this._client.post("/v1/messages/batches?beta=true",{body:W,...w,headers:n([{"anthropic-beta":[...G??[],"message-batches-2024-09-24"].toString()},w?.headers])})}retrieve($,w={},G){let{betas:W}=w??{};return this._client.get(E0`/v1/messages/batches/${$}?beta=true`,{...G,headers:n([{"anthropic-beta":[...W??[],"message-batches-2024-09-24"].toString()},G?.headers])})}list($={},w){let{betas:G,...W}=$??{};return this._client.getAPIList("/v1/messages/batches?beta=true",$1,{query:W,...w,headers:n([{"anthropic-beta":[...G??[],"message-batches-2024-09-24"].toString()},w?.headers])})}delete($,w={},G){let{betas:W}=w??{};return this._client.delete(E0`/v1/messages/batches/${$}?beta=true`,{...G,headers:n([{"anthropic-beta":[...W??[],"message-batches-2024-09-24"].toString()},G?.headers])})}cancel($,w={},G){let{betas:W}=w??{};return this._client.post(E0`/v1/messages/batches/${$}/cancel?beta=true`,{...G,headers:n([{"anthropic-beta":[...W??[],"message-batches-2024-09-24"].toString()},G?.headers])})}async results($,w={},G){let W=await this.retrieve($);if(!W.results_url)throw new b(`No batch \`results_url\`; Has it finished processing? ${W.processing_status} - ${W.id}`);let{betas:Y}=w??{};return this._client.get(W.results_url,{...G,headers:n([{"anthropic-beta":[...Y??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},G?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((Z,X)=>fw.fromResponse(X.response,X.controller))}}var XO=($)=>{let w=0,G=[];while(w<$.length){let W=$[w];if(W==="\\"){w++;continue}if(W==="{"){G.push({type:"brace",value:"{"}),w++;continue}if(W==="}"){G.push({type:"brace",value:"}"}),w++;continue}if(W==="["){G.push({type:"paren",value:"["}),w++;continue}if(W==="]"){G.push({type:"paren",value:"]"}),w++;continue}if(W===":"){G.push({type:"separator",value:":"}),w++;continue}if(W===","){G.push({type:"delimiter",value:","}),w++;continue}if(W==='"'){let J="",T=!1;W=$[++w];while(W!=='"'){if(w===$.length){T=!0;break}if(W==="\\"){if(w++,w===$.length){T=!0;break}J+=W+$[w],W=$[++w]}else J+=W,W=$[++w]}if(W=$[++w],!T)G.push({type:"string",value:J});continue}if(W&&/\s/.test(W)){w++;continue}let Z=/[0-9]/;if(W&&Z.test(W)||W==="-"||W==="."){let J="";if(W==="-")J+=W,W=$[++w];while(W&&Z.test(W)||W===".")J+=W,W=$[++w];G.push({type:"number",value:J});continue}let X=/[a-z]/i;if(W&&X.test(W)){let J="";while(W&&X.test(W)){if(w===$.length)break;J+=W,W=$[++w]}if(J=="true"||J=="false"||J==="null")G.push({type:"name",value:J});else{w++;continue}continue}w++}return G},Qw=($)=>{if($.length===0)return $;let w=$[$.length-1];switch(w.type){case"separator":return $=$.slice(0,$.length-1),Qw($);break;case"number":let G=w.value[w.value.length-1];if(G==="."||G==="-")return $=$.slice(0,$.length-1),Qw($);case"string":let W=$[$.length-2];if(W?.type==="delimiter")return $=$.slice(0,$.length-1),Qw($);else if(W?.type==="brace"&&W.value==="{")return $=$.slice(0,$.length-1),Qw($);break;case"delimiter":return $=$.slice(0,$.length-1),Qw($);break}return $},JO=($)=>{let w=[];if($.map((G)=>{if(G.type==="brace")if(G.value==="{")w.push("}");else w.splice(w.lastIndexOf("}"),1);if(G.type==="paren")if(G.value==="[")w.push("]");else w.splice(w.lastIndexOf("]"),1)}),w.length>0)w.reverse().map((G)=>{if(G==="}")$.push({type:"brace",value:"}"});else if(G==="]")$.push({type:"paren",value:"]"})});return $},TO=($)=>{let w="";return $.map((G)=>{switch(G.type){case"string":w+='"'+G.value+'"';break;default:w+=G.value;break}}),w},H6=($)=>JSON.parse(TO(JO(Qw(XO($)))));var l0,t1,n4,F6,p4,t4,O6,r4,L1,s4,L6,D6,Nw,k6,A6,kW,NM,S6,AW,SW,RW,zM,KM="__json_buf";function PM($){return $.type==="tool_use"||$.type==="server_tool_use"||$.type==="mcp_tool_use"}class a4{constructor(){l0.add(this),this.messages=[],this.receivedMessages=[],t1.set(this,void 0),this.controller=new AbortController,n4.set(this,void 0),F6.set(this,()=>{}),p4.set(this,()=>{}),t4.set(this,void 0),O6.set(this,()=>{}),r4.set(this,()=>{}),L1.set(this,{}),s4.set(this,!1),L6.set(this,!1),D6.set(this,!1),Nw.set(this,!1),k6.set(this,void 0),A6.set(this,void 0),S6.set(this,($)=>{if(I(this,L6,!0,"f"),F1($))$=new q0;if($ instanceof q0)return I(this,D6,!0,"f"),this._emit("abort",$);if($ instanceof b)return this._emit("error",$);if($ instanceof Error){let w=new b($.message);return w.cause=$,this._emit("error",w)}return this._emit("error",new b(String($)))}),I(this,n4,new Promise(($,w)=>{I(this,F6,$,"f"),I(this,p4,w,"f")}),"f"),I(this,t4,new Promise(($,w)=>{I(this,O6,$,"f"),I(this,r4,w,"f")}),"f"),H(this,n4,"f").catch(()=>{}),H(this,t4,"f").catch(()=>{})}get response(){return H(this,k6,"f")}get request_id(){return H(this,A6,"f")}async withResponse(){let $=await H(this,n4,"f");if(!$)throw Error("Could not resolve a `Response` object");return{data:this,response:$,request_id:$.headers.get("request-id")}}static fromReadableStream($){let w=new a4;return w._run(()=>w._fromReadableStream($)),w}static createMessage($,w,G){let W=new a4;for(let Y of w.messages)W._addMessageParam(Y);return W._run(()=>W._createMessage($,{...w,stream:!0},{...G,headers:{...G?.headers,"X-Stainless-Helper-Method":"stream"}})),W}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},H(this,S6,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,w=!0){if(this.receivedMessages.push($),w)this._emit("message",$)}async _createMessage($,w,G){let W=G?.signal,Y;if(W){if(W.aborted)this.controller.abort();Y=this.controller.abort.bind(this.controller),W.addEventListener("abort",Y)}try{H(this,l0,"m",AW).call(this);let{response:Z,data:X}=await $.create({...w,stream:!0},{...G,signal:this.controller.signal}).withResponse();this._connected(Z);for await(let J of X)H(this,l0,"m",SW).call(this,J);if(X.controller.signal?.aborted)throw new q0;H(this,l0,"m",RW).call(this)}finally{if(W&&Y)W.removeEventListener("abort",Y)}}_connected($){if(this.ended)return;I(this,k6,$,"f"),I(this,A6,$?.headers.get("request-id"),"f"),H(this,F6,"f").call(this,$),this._emit("connect")}get ended(){return H(this,s4,"f")}get errored(){return H(this,L6,"f")}get aborted(){return H(this,D6,"f")}abort(){this.controller.abort()}on($,w){return(H(this,L1,"f")[$]||(H(this,L1,"f")[$]=[])).push({listener:w}),this}off($,w){let G=H(this,L1,"f")[$];if(!G)return this;let W=G.findIndex((Y)=>Y.listener===w);if(W>=0)G.splice(W,1);return this}once($,w){return(H(this,L1,"f")[$]||(H(this,L1,"f")[$]=[])).push({listener:w,once:!0}),this}emitted($){return new Promise((w,G)=>{if(I(this,Nw,!0,"f"),$!=="error")this.once("error",G);this.once($,w)})}async done(){I(this,Nw,!0,"f"),await H(this,t4,"f")}get currentMessage(){return H(this,t1,"f")}async finalMessage(){return await this.done(),H(this,l0,"m",kW).call(this)}async finalText(){return await this.done(),H(this,l0,"m",NM).call(this)}_emit($,...w){if(H(this,s4,"f"))return;if($==="end")I(this,s4,!0,"f"),H(this,O6,"f").call(this);let G=H(this,L1,"f")[$];if(G)H(this,L1,"f")[$]=G.filter((W)=>!W.once),G.forEach(({listener:W})=>W(...w));if($==="abort"){let W=w[0];if(!H(this,Nw,"f")&&!G?.length)Promise.reject(W);H(this,p4,"f").call(this,W),H(this,r4,"f").call(this,W),this._emit("end");return}if($==="error"){let W=w[0];if(!H(this,Nw,"f")&&!G?.length)Promise.reject(W);H(this,p4,"f").call(this,W),H(this,r4,"f").call(this,W),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",H(this,l0,"m",kW).call(this))}async _fromReadableStream($,w){let G=w?.signal,W;if(G){if(G.aborted)this.controller.abort();W=this.controller.abort.bind(this.controller),G.addEventListener("abort",W)}try{H(this,l0,"m",AW).call(this),this._connected(null);let Y=b0.fromReadableStream($,this.controller);for await(let Z of Y)H(this,l0,"m",SW).call(this,Z);if(Y.controller.signal?.aborted)throw new q0;H(this,l0,"m",RW).call(this)}finally{if(G&&W)G.removeEventListener("abort",W)}}[(t1=new WeakMap,n4=new WeakMap,F6=new WeakMap,p4=new WeakMap,t4=new WeakMap,O6=new WeakMap,r4=new WeakMap,L1=new WeakMap,s4=new WeakMap,L6=new WeakMap,D6=new WeakMap,Nw=new WeakMap,k6=new WeakMap,A6=new WeakMap,S6=new WeakMap,l0=new WeakSet,kW=function(){if(this.receivedMessages.length===0)throw new b("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},NM=function(){if(this.receivedMessages.length===0)throw new b("stream ended without producing a Message with role=assistant");let w=this.receivedMessages.at(-1).content.filter((G)=>G.type==="text").map((G)=>G.text);if(w.length===0)throw new b("stream ended without producing a content block with type=text");return w.join(" ")},AW=function(){if(this.ended)return;I(this,t1,void 0,"f")},SW=function(w){if(this.ended)return;let G=H(this,l0,"m",zM).call(this,w);switch(this._emit("streamEvent",w,G),w.type){case"content_block_delta":{let W=G.content.at(-1);switch(w.delta.type){case"text_delta":{if(W.type==="text")this._emit("text",w.delta.text,W.text||"");break}case"citations_delta":{if(W.type==="text")this._emit("citation",w.delta.citation,W.citations??[]);break}case"input_json_delta":{if(PM(W)&&W.input)this._emit("inputJson",w.delta.partial_json,W.input);break}case"thinking_delta":{if(W.type==="thinking")this._emit("thinking",w.delta.thinking,W.thinking);break}case"signature_delta":{if(W.type==="thinking")this._emit("signature",W.signature);break}default:BM(w.delta)}break}case"message_stop":{this._addMessageParam(G),this._addMessage(G,!0);break}case"content_block_stop":{this._emit("contentBlock",G.content.at(-1));break}case"message_start":{I(this,t1,G,"f");break}case"content_block_start":case"message_delta":break}},RW=function(){if(this.ended)throw new b("stream has ended, this shouldn't happen");let w=H(this,t1,"f");if(!w)throw new b("request ended without sending any chunks");return I(this,t1,void 0,"f"),w},zM=function(w){let G=H(this,t1,"f");if(w.type==="message_start"){if(G)throw new b(`Unexpected event order, got ${w.type} before receiving "message_stop"`);return w.message}if(!G)throw new b(`Unexpected event order, got ${w.type} before "message_start"`);switch(w.type){case"message_stop":return G;case"message_delta":if(G.container=w.delta.container,G.stop_reason=w.delta.stop_reason,G.stop_sequence=w.delta.stop_sequence,G.usage.output_tokens=w.usage.output_tokens,w.usage.input_tokens!=null)G.usage.input_tokens=w.usage.input_tokens;if(w.usage.cache_creation_input_tokens!=null)G.usage.cache_creation_input_tokens=w.usage.cache_creation_input_tokens;if(w.usage.cache_read_input_tokens!=null)G.usage.cache_read_input_tokens=w.usage.cache_read_input_tokens;if(w.usage.server_tool_use!=null)G.usage.server_tool_use=w.usage.server_tool_use;return G;case"content_block_start":return G.content.push(w.content_block),G;case"content_block_delta":{let W=G.content.at(w.index);switch(w.delta.type){case"text_delta":{if(W?.type==="text")G.content[w.index]={...W,text:(W.text||"")+w.delta.text};break}case"citations_delta":{if(W?.type==="text")G.content[w.index]={...W,citations:[...W.citations??[],w.delta.citation]};break}case"input_json_delta":{if(W&&PM(W)){let Y=W[KM]||"";Y+=w.delta.partial_json;let Z={...W};if(Object.defineProperty(Z,KM,{value:Y,enumerable:!1,writable:!0}),Y)try{Z.input=H6(Y)}catch(X){let J=new b(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${X}. JSON: ${Y}`);H(this,S6,"f").call(this,J)}G.content[w.index]=Z}break}case"thinking_delta":{if(W?.type==="thinking")G.content[w.index]={...W,thinking:W.thinking+w.delta.thinking};break}case"signature_delta":{if(W?.type==="thinking")G.content[w.index]={...W,signature:w.delta.signature};break}default:BM(w.delta)}return G}case"content_block_stop":return G}},Symbol.asyncIterator)](){let $=[],w=[],G=!1;return this.on("streamEvent",(W)=>{let Y=w.shift();if(Y)Y.resolve(W);else $.push(W)}),this.on("end",()=>{G=!0;for(let W of w)W.resolve(void 0);w.length=0}),this.on("abort",(W)=>{G=!0;for(let Y of w)Y.reject(W);w.length=0}),this.on("error",(W)=>{G=!0;for(let Y of w)Y.reject(W);w.length=0}),{next:async()=>{if(!$.length){if(G)return{value:void 0,done:!0};return new Promise((Y,Z)=>w.push({resolve:Y,reject:Z})).then((Y)=>Y?{value:Y,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new b0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function BM($){}var R6={"claude-opus-4-20250514":8192,"claude-opus-4-0":8192,"claude-4-opus-20250514":8192,"anthropic.claude-opus-4-20250514-v1:0":8192,"claude-opus-4@20250514":8192,"claude-opus-4-1-20250805":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192};var VM={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-5-sonnet-20241022":"October 22, 2025","claude-3-5-sonnet-20240620":"October 22, 2025"};class zw extends J0{constructor(){super(...arguments);this.batches=new d4(this._client)}create($,w){let{betas:G,...W}=$;if(W.model in VM)console.warn(`The model '${W.model}' is deprecated and will reach end-of-life on ${VM[W.model]}
164
- Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let Y=this._client._options.timeout;if(!W.stream&&Y==null){let Z=R6[W.model]??void 0;Y=this._client.calculateNonstreamingTimeout(W.max_tokens,Z)}return this._client.post("/v1/messages?beta=true",{body:W,timeout:Y??600000,...w,headers:n([{...G?.toString()!=null?{"anthropic-beta":G?.toString()}:void 0},w?.headers]),stream:$.stream??!1})}stream($,w){return a4.createMessage(this,$,w)}countTokens($,w){let{betas:G,...W}=$;return this._client.post("/v1/messages/count_tokens?beta=true",{body:W,...w,headers:n([{"anthropic-beta":[...G??[],"token-counting-2024-11-01"].toString()},w?.headers])})}}zw.Batches=d4;class D1 extends J0{constructor(){super(...arguments);this.models=new c4(this._client),this.messages=new zw(this._client),this.files=new l4(this._client)}}D1.Models=c4;D1.Messages=zw;D1.Files=l4;class Kw extends J0{create($,w){let{betas:G,...W}=$;return this._client.post("/v1/complete",{body:W,timeout:this._client._options.timeout??600000,...w,headers:n([{...G?.toString()!=null?{"anthropic-beta":G?.toString()}:void 0},w?.headers]),stream:$.stream??!1})}}var c0,r1,o4,j6,e4,$9,C6,w9,k1,G9,y6,I6,Pw,b6,x6,jW,qM,CW,yW,IW,bW,EM,UM="__json_buf";function HM($){return $.type==="tool_use"||$.type==="server_tool_use"}class W9{constructor(){c0.add(this),this.messages=[],this.receivedMessages=[],r1.set(this,void 0),this.controller=new AbortController,o4.set(this,void 0),j6.set(this,()=>{}),e4.set(this,()=>{}),$9.set(this,void 0),C6.set(this,()=>{}),w9.set(this,()=>{}),k1.set(this,{}),G9.set(this,!1),y6.set(this,!1),I6.set(this,!1),Pw.set(this,!1),b6.set(this,void 0),x6.set(this,void 0),CW.set(this,($)=>{if(I(this,y6,!0,"f"),F1($))$=new q0;if($ instanceof q0)return I(this,I6,!0,"f"),this._emit("abort",$);if($ instanceof b)return this._emit("error",$);if($ instanceof Error){let w=new b($.message);return w.cause=$,this._emit("error",w)}return this._emit("error",new b(String($)))}),I(this,o4,new Promise(($,w)=>{I(this,j6,$,"f"),I(this,e4,w,"f")}),"f"),I(this,$9,new Promise(($,w)=>{I(this,C6,$,"f"),I(this,w9,w,"f")}),"f"),H(this,o4,"f").catch(()=>{}),H(this,$9,"f").catch(()=>{})}get response(){return H(this,b6,"f")}get request_id(){return H(this,x6,"f")}async withResponse(){let $=await H(this,o4,"f");if(!$)throw Error("Could not resolve a `Response` object");return{data:this,response:$,request_id:$.headers.get("request-id")}}static fromReadableStream($){let w=new W9;return w._run(()=>w._fromReadableStream($)),w}static createMessage($,w,G){let W=new W9;for(let Y of w.messages)W._addMessageParam(Y);return W._run(()=>W._createMessage($,{...w,stream:!0},{...G,headers:{...G?.headers,"X-Stainless-Helper-Method":"stream"}})),W}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},H(this,CW,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,w=!0){if(this.receivedMessages.push($),w)this._emit("message",$)}async _createMessage($,w,G){let W=G?.signal,Y;if(W){if(W.aborted)this.controller.abort();Y=this.controller.abort.bind(this.controller),W.addEventListener("abort",Y)}try{H(this,c0,"m",yW).call(this);let{response:Z,data:X}=await $.create({...w,stream:!0},{...G,signal:this.controller.signal}).withResponse();this._connected(Z);for await(let J of X)H(this,c0,"m",IW).call(this,J);if(X.controller.signal?.aborted)throw new q0;H(this,c0,"m",bW).call(this)}finally{if(W&&Y)W.removeEventListener("abort",Y)}}_connected($){if(this.ended)return;I(this,b6,$,"f"),I(this,x6,$?.headers.get("request-id"),"f"),H(this,j6,"f").call(this,$),this._emit("connect")}get ended(){return H(this,G9,"f")}get errored(){return H(this,y6,"f")}get aborted(){return H(this,I6,"f")}abort(){this.controller.abort()}on($,w){return(H(this,k1,"f")[$]||(H(this,k1,"f")[$]=[])).push({listener:w}),this}off($,w){let G=H(this,k1,"f")[$];if(!G)return this;let W=G.findIndex((Y)=>Y.listener===w);if(W>=0)G.splice(W,1);return this}once($,w){return(H(this,k1,"f")[$]||(H(this,k1,"f")[$]=[])).push({listener:w,once:!0}),this}emitted($){return new Promise((w,G)=>{if(I(this,Pw,!0,"f"),$!=="error")this.once("error",G);this.once($,w)})}async done(){I(this,Pw,!0,"f"),await H(this,$9,"f")}get currentMessage(){return H(this,r1,"f")}async finalMessage(){return await this.done(),H(this,c0,"m",jW).call(this)}async finalText(){return await this.done(),H(this,c0,"m",qM).call(this)}_emit($,...w){if(H(this,G9,"f"))return;if($==="end")I(this,G9,!0,"f"),H(this,C6,"f").call(this);let G=H(this,k1,"f")[$];if(G)H(this,k1,"f")[$]=G.filter((W)=>!W.once),G.forEach(({listener:W})=>W(...w));if($==="abort"){let W=w[0];if(!H(this,Pw,"f")&&!G?.length)Promise.reject(W);H(this,e4,"f").call(this,W),H(this,w9,"f").call(this,W),this._emit("end");return}if($==="error"){let W=w[0];if(!H(this,Pw,"f")&&!G?.length)Promise.reject(W);H(this,e4,"f").call(this,W),H(this,w9,"f").call(this,W),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",H(this,c0,"m",jW).call(this))}async _fromReadableStream($,w){let G=w?.signal,W;if(G){if(G.aborted)this.controller.abort();W=this.controller.abort.bind(this.controller),G.addEventListener("abort",W)}try{H(this,c0,"m",yW).call(this),this._connected(null);let Y=b0.fromReadableStream($,this.controller);for await(let Z of Y)H(this,c0,"m",IW).call(this,Z);if(Y.controller.signal?.aborted)throw new q0;H(this,c0,"m",bW).call(this)}finally{if(G&&W)G.removeEventListener("abort",W)}}[(r1=new WeakMap,o4=new WeakMap,j6=new WeakMap,e4=new WeakMap,$9=new WeakMap,C6=new WeakMap,w9=new WeakMap,k1=new WeakMap,G9=new WeakMap,y6=new WeakMap,I6=new WeakMap,Pw=new WeakMap,b6=new WeakMap,x6=new WeakMap,CW=new WeakMap,c0=new WeakSet,jW=function(){if(this.receivedMessages.length===0)throw new b("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},qM=function(){if(this.receivedMessages.length===0)throw new b("stream ended without producing a Message with role=assistant");let w=this.receivedMessages.at(-1).content.filter((G)=>G.type==="text").map((G)=>G.text);if(w.length===0)throw new b("stream ended without producing a content block with type=text");return w.join(" ")},yW=function(){if(this.ended)return;I(this,r1,void 0,"f")},IW=function(w){if(this.ended)return;let G=H(this,c0,"m",EM).call(this,w);switch(this._emit("streamEvent",w,G),w.type){case"content_block_delta":{let W=G.content.at(-1);switch(w.delta.type){case"text_delta":{if(W.type==="text")this._emit("text",w.delta.text,W.text||"");break}case"citations_delta":{if(W.type==="text")this._emit("citation",w.delta.citation,W.citations??[]);break}case"input_json_delta":{if(HM(W)&&W.input)this._emit("inputJson",w.delta.partial_json,W.input);break}case"thinking_delta":{if(W.type==="thinking")this._emit("thinking",w.delta.thinking,W.thinking);break}case"signature_delta":{if(W.type==="thinking")this._emit("signature",W.signature);break}default:FM(w.delta)}break}case"message_stop":{this._addMessageParam(G),this._addMessage(G,!0);break}case"content_block_stop":{this._emit("contentBlock",G.content.at(-1));break}case"message_start":{I(this,r1,G,"f");break}case"content_block_start":case"message_delta":break}},bW=function(){if(this.ended)throw new b("stream has ended, this shouldn't happen");let w=H(this,r1,"f");if(!w)throw new b("request ended without sending any chunks");return I(this,r1,void 0,"f"),w},EM=function(w){let G=H(this,r1,"f");if(w.type==="message_start"){if(G)throw new b(`Unexpected event order, got ${w.type} before receiving "message_stop"`);return w.message}if(!G)throw new b(`Unexpected event order, got ${w.type} before "message_start"`);switch(w.type){case"message_stop":return G;case"message_delta":if(G.stop_reason=w.delta.stop_reason,G.stop_sequence=w.delta.stop_sequence,G.usage.output_tokens=w.usage.output_tokens,w.usage.input_tokens!=null)G.usage.input_tokens=w.usage.input_tokens;if(w.usage.cache_creation_input_tokens!=null)G.usage.cache_creation_input_tokens=w.usage.cache_creation_input_tokens;if(w.usage.cache_read_input_tokens!=null)G.usage.cache_read_input_tokens=w.usage.cache_read_input_tokens;if(w.usage.server_tool_use!=null)G.usage.server_tool_use=w.usage.server_tool_use;return G;case"content_block_start":return G.content.push({...w.content_block}),G;case"content_block_delta":{let W=G.content.at(w.index);switch(w.delta.type){case"text_delta":{if(W?.type==="text")G.content[w.index]={...W,text:(W.text||"")+w.delta.text};break}case"citations_delta":{if(W?.type==="text")G.content[w.index]={...W,citations:[...W.citations??[],w.delta.citation]};break}case"input_json_delta":{if(W&&HM(W)){let Y=W[UM]||"";Y+=w.delta.partial_json;let Z={...W};if(Object.defineProperty(Z,UM,{value:Y,enumerable:!1,writable:!0}),Y)Z.input=H6(Y);G.content[w.index]=Z}break}case"thinking_delta":{if(W?.type==="thinking")G.content[w.index]={...W,thinking:W.thinking+w.delta.thinking};break}case"signature_delta":{if(W?.type==="thinking")G.content[w.index]={...W,signature:w.delta.signature};break}default:FM(w.delta)}return G}case"content_block_stop":return G}},Symbol.asyncIterator)](){let $=[],w=[],G=!1;return this.on("streamEvent",(W)=>{let Y=w.shift();if(Y)Y.resolve(W);else $.push(W)}),this.on("end",()=>{G=!0;for(let W of w)W.resolve(void 0);w.length=0}),this.on("abort",(W)=>{G=!0;for(let Y of w)Y.reject(W);w.length=0}),this.on("error",(W)=>{G=!0;for(let Y of w)Y.reject(W);w.length=0}),{next:async()=>{if(!$.length){if(G)return{value:void 0,done:!0};return new Promise((Y,Z)=>w.push({resolve:Y,reject:Z})).then((Y)=>Y?{value:Y,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new b0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function FM($){}class Y9 extends J0{create($,w){return this._client.post("/v1/messages/batches",{body:$,...w})}retrieve($,w){return this._client.get(E0`/v1/messages/batches/${$}`,w)}list($={},w){return this._client.getAPIList("/v1/messages/batches",$1,{query:$,...w})}delete($,w){return this._client.delete(E0`/v1/messages/batches/${$}`,w)}cancel($,w){return this._client.post(E0`/v1/messages/batches/${$}/cancel`,w)}async results($,w){let G=await this.retrieve($);if(!G.results_url)throw new b(`No batch \`results_url\`; Has it finished processing? ${G.processing_status} - ${G.id}`);return this._client.get(G.results_url,{...w,headers:n([{Accept:"application/binary"},w?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((W,Y)=>fw.fromResponse(Y.response,Y.controller))}}class F$ extends J0{constructor(){super(...arguments);this.batches=new Y9(this._client)}create($,w){if($.model in OM)console.warn(`The model '${$.model}' is deprecated and will reach end-of-life on ${OM[$.model]}
165
- Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let G=this._client._options.timeout;if(!$.stream&&G==null){let W=R6[$.model]??void 0;G=this._client.calculateNonstreamingTimeout($.max_tokens,W)}return this._client.post("/v1/messages",{body:$,timeout:G??600000,...w,stream:$.stream??!1})}stream($,w){return W9.createMessage(this,$,w)}countTokens($,w){return this._client.post("/v1/messages/count_tokens",{body:$,...w})}}var OM={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-5-sonnet-20241022":"October 22, 2025","claude-3-5-sonnet-20240620":"October 22, 2025"};F$.Batches=Y9;class Bw extends J0{retrieve($,w={},G){let{betas:W}=w??{};return this._client.get(E0`/v1/models/${$}`,{...G,headers:n([{...W?.toString()!=null?{"anthropic-beta":W?.toString()}:void 0},G?.headers])})}list($={},w){let{betas:G,...W}=$??{};return this._client.getAPIList("/v1/models",$1,{query:W,...w,headers:n([{...G?.toString()!=null?{"anthropic-beta":G?.toString()}:void 0},w?.headers])})}}var Z9=($)=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[$]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.($)?.trim();return};var xW,_W,_6,LM,DM="\\n\\nHuman:",kM="\\n\\nAssistant:";class $0{constructor({baseURL:$=Z9("ANTHROPIC_BASE_URL"),apiKey:w=Z9("ANTHROPIC_API_KEY")??null,authToken:G=Z9("ANTHROPIC_AUTH_TOKEN")??null,...W}={}){xW.add(this),_6.set(this,void 0);let Y={apiKey:w,authToken:G,...W,baseURL:$||"https://api.anthropic.com"};if(!Y.dangerouslyAllowBrowser&&tT())throw new b(`It looks like you're running in a browser-like environment.
302
+ ${J}
303
+ ${M}`)}return J},D0=lx(dB);class X8 extends P0{list($={},w){let{betas:G,...Z}=$??{};return this._client.getAPIList("/v1/files",Q$,{query:Z,...w,headers:s([{"anthropic-beta":[...G??[],"files-api-2025-04-14"].toString()},w?.headers])})}delete($,w={},G){let{betas:Z}=w??{};return this._client.delete(D0`/v1/files/${$}`,{...G,headers:s([{"anthropic-beta":[...Z??[],"files-api-2025-04-14"].toString()},G?.headers])})}download($,w={},G){let{betas:Z}=w??{};return this._client.get(D0`/v1/files/${$}/content`,{...G,headers:s([{"anthropic-beta":[...Z??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},G?.headers]),__binaryResponse:!0})}retrieveMetadata($,w={},G){let{betas:Z}=w??{};return this._client.get(D0`/v1/files/${$}`,{...G,headers:s([{"anthropic-beta":[...Z??[],"files-api-2025-04-14"].toString()},G?.headers])})}upload($,w){let{betas:G,...Z}=$;return this._client.post("/v1/files",vB({body:Z,...w,headers:s([{"anthropic-beta":[...G??[],"files-api-2025-04-14"].toString()},w?.headers])},this._client))}}class Y8 extends P0{retrieve($,w={},G){let{betas:Z}=w??{};return this._client.get(D0`/v1/models/${$}?beta=true`,{...G,headers:s([{...Z?.toString()!=null?{"anthropic-beta":Z?.toString()}:void 0},G?.headers])})}list($={},w){let{betas:G,...Z}=$??{};return this._client.getAPIList("/v1/models?beta=true",Q$,{query:Z,...w,headers:s([{...G?.toString()!=null?{"anthropic-beta":G?.toString()}:void 0},w?.headers])})}}class w4{constructor($,w){this.iterator=$,this.controller=w}async*decoder(){let $=new N1;for await(let w of this.iterator)for(let G of $.decode(w))yield JSON.parse(G);for(let w of $.flush())yield JSON.parse(w)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse($,w){if(!$.body){if(w.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new x("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new x("Attempted to iterate over a response with no body")}return new w4(o9($.body),w)}}class J8 extends P0{create($,w){let{betas:G,...Z}=$;return this._client.post("/v1/messages/batches?beta=true",{body:Z,...w,headers:s([{"anthropic-beta":[...G??[],"message-batches-2024-09-24"].toString()},w?.headers])})}retrieve($,w={},G){let{betas:Z}=w??{};return this._client.get(D0`/v1/messages/batches/${$}?beta=true`,{...G,headers:s([{"anthropic-beta":[...Z??[],"message-batches-2024-09-24"].toString()},G?.headers])})}list($={},w){let{betas:G,...Z}=$??{};return this._client.getAPIList("/v1/messages/batches?beta=true",Q$,{query:Z,...w,headers:s([{"anthropic-beta":[...G??[],"message-batches-2024-09-24"].toString()},w?.headers])})}delete($,w={},G){let{betas:Z}=w??{};return this._client.delete(D0`/v1/messages/batches/${$}?beta=true`,{...G,headers:s([{"anthropic-beta":[...Z??[],"message-batches-2024-09-24"].toString()},G?.headers])})}cancel($,w={},G){let{betas:Z}=w??{};return this._client.post(D0`/v1/messages/batches/${$}/cancel?beta=true`,{...G,headers:s([{"anthropic-beta":[...Z??[],"message-batches-2024-09-24"].toString()},G?.headers])})}async results($,w={},G){let Z=await this.retrieve($);if(!Z.results_url)throw new x(`No batch \`results_url\`; Has it finished processing? ${Z.processing_status} - ${Z.id}`);let{betas:X}=w??{};return this._client.get(Z.results_url,{...G,headers:s([{"anthropic-beta":[...X??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},G?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((Y,J)=>w4.fromResponse(J.response,J.controller))}}var nx=($)=>{let w=0,G=[];while(w<$.length){let Z=$[w];if(Z==="\\"){w++;continue}if(Z==="{"){G.push({type:"brace",value:"{"}),w++;continue}if(Z==="}"){G.push({type:"brace",value:"}"}),w++;continue}if(Z==="["){G.push({type:"paren",value:"["}),w++;continue}if(Z==="]"){G.push({type:"paren",value:"]"}),w++;continue}if(Z===":"){G.push({type:"separator",value:":"}),w++;continue}if(Z===","){G.push({type:"delimiter",value:","}),w++;continue}if(Z==='"'){let W="",T=!1;Z=$[++w];while(Z!=='"'){if(w===$.length){T=!0;break}if(Z==="\\"){if(w++,w===$.length){T=!0;break}W+=Z+$[w],Z=$[++w]}else W+=Z,Z=$[++w]}if(Z=$[++w],!T)G.push({type:"string",value:W});continue}if(Z&&/\s/.test(Z)){w++;continue}let Y=/[0-9]/;if(Z&&Y.test(Z)||Z==="-"||Z==="."){let W="";if(Z==="-")W+=Z,Z=$[++w];while(Z&&Y.test(Z)||Z===".")W+=Z,Z=$[++w];G.push({type:"number",value:W});continue}let J=/[a-z]/i;if(Z&&J.test(Z)){let W="";while(Z&&J.test(Z)){if(w===$.length)break;W+=Z,Z=$[++w]}if(W=="true"||W=="false"||W==="null")G.push({type:"name",value:W});else{w++;continue}continue}w++}return G},G4=($)=>{if($.length===0)return $;let w=$[$.length-1];switch(w.type){case"separator":return $=$.slice(0,$.length-1),G4($);break;case"number":let G=w.value[w.value.length-1];if(G==="."||G==="-")return $=$.slice(0,$.length-1),G4($);case"string":let Z=$[$.length-2];if(Z?.type==="delimiter")return $=$.slice(0,$.length-1),G4($);else if(Z?.type==="brace"&&Z.value==="{")return $=$.slice(0,$.length-1),G4($);break;case"delimiter":return $=$.slice(0,$.length-1),G4($);break}return $},rx=($)=>{let w=[];if($.map((G)=>{if(G.type==="brace")if(G.value==="{")w.push("}");else w.splice(w.lastIndexOf("}"),1);if(G.type==="paren")if(G.value==="[")w.push("]");else w.splice(w.lastIndexOf("]"),1)}),w.length>0)w.reverse().map((G)=>{if(G==="}")$.push({type:"brace",value:"}"});else if(G==="]")$.push({type:"paren",value:"]"})});return $},sx=($)=>{let w="";return $.map((G)=>{switch(G.type){case"string":w+='"'+G.value+'"';break;default:w+=G.value;break}}),w},DG=($)=>JSON.parse(sx(rx(G4(nx($)))));var t0,V1,W8,EG,T8,Q8,AG,z8,g$,M8,RG,SG,Z4,IG,jG,l7,cB,CG,d7,c7,p7,pB,nB="__json_buf";function rB($){return $.type==="tool_use"||$.type==="server_tool_use"||$.type==="mcp_tool_use"}class P8{constructor(){t0.add(this),this.messages=[],this.receivedMessages=[],V1.set(this,void 0),this.controller=new AbortController,W8.set(this,void 0),EG.set(this,()=>{}),T8.set(this,()=>{}),Q8.set(this,void 0),AG.set(this,()=>{}),z8.set(this,()=>{}),g$.set(this,{}),M8.set(this,!1),RG.set(this,!1),SG.set(this,!1),Z4.set(this,!1),IG.set(this,void 0),jG.set(this,void 0),CG.set(this,($)=>{if(_(this,RG,!0,"f"),_$($))$=new L0;if($ instanceof L0)return _(this,SG,!0,"f"),this._emit("abort",$);if($ instanceof x)return this._emit("error",$);if($ instanceof Error){let w=new x($.message);return w.cause=$,this._emit("error",w)}return this._emit("error",new x(String($)))}),_(this,W8,new Promise(($,w)=>{_(this,EG,$,"f"),_(this,T8,w,"f")}),"f"),_(this,Q8,new Promise(($,w)=>{_(this,AG,$,"f"),_(this,z8,w,"f")}),"f"),A(this,W8,"f").catch(()=>{}),A(this,Q8,"f").catch(()=>{})}get response(){return A(this,IG,"f")}get request_id(){return A(this,jG,"f")}async withResponse(){let $=await A(this,W8,"f");if(!$)throw Error("Could not resolve a `Response` object");return{data:this,response:$,request_id:$.headers.get("request-id")}}static fromReadableStream($){let w=new P8;return w._run(()=>w._fromReadableStream($)),w}static createMessage($,w,G){let Z=new P8;for(let X of w.messages)Z._addMessageParam(X);return Z._run(()=>Z._createMessage($,{...w,stream:!0},{...G,headers:{...G?.headers,"X-Stainless-Helper-Method":"stream"}})),Z}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},A(this,CG,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,w=!0){if(this.receivedMessages.push($),w)this._emit("message",$)}async _createMessage($,w,G){let Z=G?.signal,X;if(Z){if(Z.aborted)this.controller.abort();X=this.controller.abort.bind(this.controller),Z.addEventListener("abort",X)}try{A(this,t0,"m",d7).call(this);let{response:Y,data:J}=await $.create({...w,stream:!0},{...G,signal:this.controller.signal}).withResponse();this._connected(Y);for await(let W of J)A(this,t0,"m",c7).call(this,W);if(J.controller.signal?.aborted)throw new L0;A(this,t0,"m",p7).call(this)}finally{if(Z&&X)Z.removeEventListener("abort",X)}}_connected($){if(this.ended)return;_(this,IG,$,"f"),_(this,jG,$?.headers.get("request-id"),"f"),A(this,EG,"f").call(this,$),this._emit("connect")}get ended(){return A(this,M8,"f")}get errored(){return A(this,RG,"f")}get aborted(){return A(this,SG,"f")}abort(){this.controller.abort()}on($,w){return(A(this,g$,"f")[$]||(A(this,g$,"f")[$]=[])).push({listener:w}),this}off($,w){let G=A(this,g$,"f")[$];if(!G)return this;let Z=G.findIndex((X)=>X.listener===w);if(Z>=0)G.splice(Z,1);return this}once($,w){return(A(this,g$,"f")[$]||(A(this,g$,"f")[$]=[])).push({listener:w,once:!0}),this}emitted($){return new Promise((w,G)=>{if(_(this,Z4,!0,"f"),$!=="error")this.once("error",G);this.once($,w)})}async done(){_(this,Z4,!0,"f"),await A(this,Q8,"f")}get currentMessage(){return A(this,V1,"f")}async finalMessage(){return await this.done(),A(this,t0,"m",l7).call(this)}async finalText(){return await this.done(),A(this,t0,"m",cB).call(this)}_emit($,...w){if(A(this,M8,"f"))return;if($==="end")_(this,M8,!0,"f"),A(this,AG,"f").call(this);let G=A(this,g$,"f")[$];if(G)A(this,g$,"f")[$]=G.filter((Z)=>!Z.once),G.forEach(({listener:Z})=>Z(...w));if($==="abort"){let Z=w[0];if(!A(this,Z4,"f")&&!G?.length)Promise.reject(Z);A(this,T8,"f").call(this,Z),A(this,z8,"f").call(this,Z),this._emit("end");return}if($==="error"){let Z=w[0];if(!A(this,Z4,"f")&&!G?.length)Promise.reject(Z);A(this,T8,"f").call(this,Z),A(this,z8,"f").call(this,Z),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",A(this,t0,"m",l7).call(this))}async _fromReadableStream($,w){let G=w?.signal,Z;if(G){if(G.aborted)this.controller.abort();Z=this.controller.abort.bind(this.controller),G.addEventListener("abort",Z)}try{A(this,t0,"m",d7).call(this),this._connected(null);let X=u0.fromReadableStream($,this.controller);for await(let Y of X)A(this,t0,"m",c7).call(this,Y);if(X.controller.signal?.aborted)throw new L0;A(this,t0,"m",p7).call(this)}finally{if(G&&Z)G.removeEventListener("abort",Z)}}[(V1=new WeakMap,W8=new WeakMap,EG=new WeakMap,T8=new WeakMap,Q8=new WeakMap,AG=new WeakMap,z8=new WeakMap,g$=new WeakMap,M8=new WeakMap,RG=new WeakMap,SG=new WeakMap,Z4=new WeakMap,IG=new WeakMap,jG=new WeakMap,CG=new WeakMap,t0=new WeakSet,l7=function(){if(this.receivedMessages.length===0)throw new x("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},cB=function(){if(this.receivedMessages.length===0)throw new x("stream ended without producing a Message with role=assistant");let w=this.receivedMessages.at(-1).content.filter((G)=>G.type==="text").map((G)=>G.text);if(w.length===0)throw new x("stream ended without producing a content block with type=text");return w.join(" ")},d7=function(){if(this.ended)return;_(this,V1,void 0,"f")},c7=function(w){if(this.ended)return;let G=A(this,t0,"m",pB).call(this,w);switch(this._emit("streamEvent",w,G),w.type){case"content_block_delta":{let Z=G.content.at(-1);switch(w.delta.type){case"text_delta":{if(Z.type==="text")this._emit("text",w.delta.text,Z.text||"");break}case"citations_delta":{if(Z.type==="text")this._emit("citation",w.delta.citation,Z.citations??[]);break}case"input_json_delta":{if(rB(Z)&&Z.input)this._emit("inputJson",w.delta.partial_json,Z.input);break}case"thinking_delta":{if(Z.type==="thinking")this._emit("thinking",w.delta.thinking,Z.thinking);break}case"signature_delta":{if(Z.type==="thinking")this._emit("signature",Z.signature);break}default:sB(w.delta)}break}case"message_stop":{this._addMessageParam(G),this._addMessage(G,!0);break}case"content_block_stop":{this._emit("contentBlock",G.content.at(-1));break}case"message_start":{_(this,V1,G,"f");break}case"content_block_start":case"message_delta":break}},p7=function(){if(this.ended)throw new x("stream has ended, this shouldn't happen");let w=A(this,V1,"f");if(!w)throw new x("request ended without sending any chunks");return _(this,V1,void 0,"f"),w},pB=function(w){let G=A(this,V1,"f");if(w.type==="message_start"){if(G)throw new x(`Unexpected event order, got ${w.type} before receiving "message_stop"`);return w.message}if(!G)throw new x(`Unexpected event order, got ${w.type} before "message_start"`);switch(w.type){case"message_stop":return G;case"message_delta":if(G.container=w.delta.container,G.stop_reason=w.delta.stop_reason,G.stop_sequence=w.delta.stop_sequence,G.usage.output_tokens=w.usage.output_tokens,w.usage.input_tokens!=null)G.usage.input_tokens=w.usage.input_tokens;if(w.usage.cache_creation_input_tokens!=null)G.usage.cache_creation_input_tokens=w.usage.cache_creation_input_tokens;if(w.usage.cache_read_input_tokens!=null)G.usage.cache_read_input_tokens=w.usage.cache_read_input_tokens;if(w.usage.server_tool_use!=null)G.usage.server_tool_use=w.usage.server_tool_use;return G;case"content_block_start":return G.content.push(w.content_block),G;case"content_block_delta":{let Z=G.content.at(w.index);switch(w.delta.type){case"text_delta":{if(Z?.type==="text")G.content[w.index]={...Z,text:(Z.text||"")+w.delta.text};break}case"citations_delta":{if(Z?.type==="text")G.content[w.index]={...Z,citations:[...Z.citations??[],w.delta.citation]};break}case"input_json_delta":{if(Z&&rB(Z)){let X=Z[nB]||"";X+=w.delta.partial_json;let Y={...Z};if(Object.defineProperty(Y,nB,{value:X,enumerable:!1,writable:!0}),X)try{Y.input=DG(X)}catch(J){let W=new x(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${J}. JSON: ${X}`);A(this,CG,"f").call(this,W)}G.content[w.index]=Y}break}case"thinking_delta":{if(Z?.type==="thinking")G.content[w.index]={...Z,thinking:Z.thinking+w.delta.thinking};break}case"signature_delta":{if(Z?.type==="thinking")G.content[w.index]={...Z,signature:w.delta.signature};break}default:sB(w.delta)}return G}case"content_block_stop":return G}},Symbol.asyncIterator)](){let $=[],w=[],G=!1;return this.on("streamEvent",(Z)=>{let X=w.shift();if(X)X.resolve(Z);else $.push(Z)}),this.on("end",()=>{G=!0;for(let Z of w)Z.resolve(void 0);w.length=0}),this.on("abort",(Z)=>{G=!0;for(let X of w)X.reject(Z);w.length=0}),this.on("error",(Z)=>{G=!0;for(let X of w)X.reject(Z);w.length=0}),{next:async()=>{if(!$.length){if(G)return{value:void 0,done:!0};return new Promise((X,Y)=>w.push({resolve:X,reject:Y})).then((X)=>X?{value:X,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new u0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function sB($){}var bG={"claude-opus-4-20250514":8192,"claude-opus-4-0":8192,"claude-4-opus-20250514":8192,"anthropic.claude-opus-4-20250514-v1:0":8192,"claude-opus-4@20250514":8192,"claude-opus-4-1-20250805":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192};var aB={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-5-sonnet-20241022":"October 22, 2025","claude-3-5-sonnet-20240620":"October 22, 2025"};class X4 extends P0{constructor(){super(...arguments);this.batches=new J8(this._client)}create($,w){let{betas:G,...Z}=$;if(Z.model in aB)console.warn(`The model '${Z.model}' is deprecated and will reach end-of-life on ${aB[Z.model]}
304
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let X=this._client._options.timeout;if(!Z.stream&&X==null){let Y=bG[Z.model]??void 0;X=this._client.calculateNonstreamingTimeout(Z.max_tokens,Y)}return this._client.post("/v1/messages?beta=true",{body:Z,timeout:X??600000,...w,headers:s([{...G?.toString()!=null?{"anthropic-beta":G?.toString()}:void 0},w?.headers]),stream:$.stream??!1})}stream($,w){return P8.createMessage(this,$,w)}countTokens($,w){let{betas:G,...Z}=$;return this._client.post("/v1/messages/count_tokens?beta=true",{body:Z,...w,headers:s([{"anthropic-beta":[...G??[],"token-counting-2024-11-01"].toString()},w?.headers])})}}X4.Batches=J8;class u$ extends P0{constructor(){super(...arguments);this.models=new Y8(this._client),this.messages=new X4(this._client),this.files=new X8(this._client)}}u$.Models=Y8;u$.Messages=X4;u$.Files=X8;class Y4 extends P0{create($,w){let{betas:G,...Z}=$;return this._client.post("/v1/complete",{body:Z,timeout:this._client._options.timeout??600000,...w,headers:s([{...G?.toString()!=null?{"anthropic-beta":G?.toString()}:void 0},w?.headers]),stream:$.stream??!1})}}var o0,K1,q8,kG,B8,N8,yG,V8,h$,K8,_G,xG,J4,gG,uG,n7,tB,r7,s7,a7,t7,oB,eB="__json_buf";function $N($){return $.type==="tool_use"||$.type==="server_tool_use"}class U8{constructor(){o0.add(this),this.messages=[],this.receivedMessages=[],K1.set(this,void 0),this.controller=new AbortController,q8.set(this,void 0),kG.set(this,()=>{}),B8.set(this,()=>{}),N8.set(this,void 0),yG.set(this,()=>{}),V8.set(this,()=>{}),h$.set(this,{}),K8.set(this,!1),_G.set(this,!1),xG.set(this,!1),J4.set(this,!1),gG.set(this,void 0),uG.set(this,void 0),r7.set(this,($)=>{if(_(this,_G,!0,"f"),_$($))$=new L0;if($ instanceof L0)return _(this,xG,!0,"f"),this._emit("abort",$);if($ instanceof x)return this._emit("error",$);if($ instanceof Error){let w=new x($.message);return w.cause=$,this._emit("error",w)}return this._emit("error",new x(String($)))}),_(this,q8,new Promise(($,w)=>{_(this,kG,$,"f"),_(this,B8,w,"f")}),"f"),_(this,N8,new Promise(($,w)=>{_(this,yG,$,"f"),_(this,V8,w,"f")}),"f"),A(this,q8,"f").catch(()=>{}),A(this,N8,"f").catch(()=>{})}get response(){return A(this,gG,"f")}get request_id(){return A(this,uG,"f")}async withResponse(){let $=await A(this,q8,"f");if(!$)throw Error("Could not resolve a `Response` object");return{data:this,response:$,request_id:$.headers.get("request-id")}}static fromReadableStream($){let w=new U8;return w._run(()=>w._fromReadableStream($)),w}static createMessage($,w,G){let Z=new U8;for(let X of w.messages)Z._addMessageParam(X);return Z._run(()=>Z._createMessage($,{...w,stream:!0},{...G,headers:{...G?.headers,"X-Stainless-Helper-Method":"stream"}})),Z}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},A(this,r7,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,w=!0){if(this.receivedMessages.push($),w)this._emit("message",$)}async _createMessage($,w,G){let Z=G?.signal,X;if(Z){if(Z.aborted)this.controller.abort();X=this.controller.abort.bind(this.controller),Z.addEventListener("abort",X)}try{A(this,o0,"m",s7).call(this);let{response:Y,data:J}=await $.create({...w,stream:!0},{...G,signal:this.controller.signal}).withResponse();this._connected(Y);for await(let W of J)A(this,o0,"m",a7).call(this,W);if(J.controller.signal?.aborted)throw new L0;A(this,o0,"m",t7).call(this)}finally{if(Z&&X)Z.removeEventListener("abort",X)}}_connected($){if(this.ended)return;_(this,gG,$,"f"),_(this,uG,$?.headers.get("request-id"),"f"),A(this,kG,"f").call(this,$),this._emit("connect")}get ended(){return A(this,K8,"f")}get errored(){return A(this,_G,"f")}get aborted(){return A(this,xG,"f")}abort(){this.controller.abort()}on($,w){return(A(this,h$,"f")[$]||(A(this,h$,"f")[$]=[])).push({listener:w}),this}off($,w){let G=A(this,h$,"f")[$];if(!G)return this;let Z=G.findIndex((X)=>X.listener===w);if(Z>=0)G.splice(Z,1);return this}once($,w){return(A(this,h$,"f")[$]||(A(this,h$,"f")[$]=[])).push({listener:w,once:!0}),this}emitted($){return new Promise((w,G)=>{if(_(this,J4,!0,"f"),$!=="error")this.once("error",G);this.once($,w)})}async done(){_(this,J4,!0,"f"),await A(this,N8,"f")}get currentMessage(){return A(this,K1,"f")}async finalMessage(){return await this.done(),A(this,o0,"m",n7).call(this)}async finalText(){return await this.done(),A(this,o0,"m",tB).call(this)}_emit($,...w){if(A(this,K8,"f"))return;if($==="end")_(this,K8,!0,"f"),A(this,yG,"f").call(this);let G=A(this,h$,"f")[$];if(G)A(this,h$,"f")[$]=G.filter((Z)=>!Z.once),G.forEach(({listener:Z})=>Z(...w));if($==="abort"){let Z=w[0];if(!A(this,J4,"f")&&!G?.length)Promise.reject(Z);A(this,B8,"f").call(this,Z),A(this,V8,"f").call(this,Z),this._emit("end");return}if($==="error"){let Z=w[0];if(!A(this,J4,"f")&&!G?.length)Promise.reject(Z);A(this,B8,"f").call(this,Z),A(this,V8,"f").call(this,Z),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",A(this,o0,"m",n7).call(this))}async _fromReadableStream($,w){let G=w?.signal,Z;if(G){if(G.aborted)this.controller.abort();Z=this.controller.abort.bind(this.controller),G.addEventListener("abort",Z)}try{A(this,o0,"m",s7).call(this),this._connected(null);let X=u0.fromReadableStream($,this.controller);for await(let Y of X)A(this,o0,"m",a7).call(this,Y);if(X.controller.signal?.aborted)throw new L0;A(this,o0,"m",t7).call(this)}finally{if(G&&Z)G.removeEventListener("abort",Z)}}[(K1=new WeakMap,q8=new WeakMap,kG=new WeakMap,B8=new WeakMap,N8=new WeakMap,yG=new WeakMap,V8=new WeakMap,h$=new WeakMap,K8=new WeakMap,_G=new WeakMap,xG=new WeakMap,J4=new WeakMap,gG=new WeakMap,uG=new WeakMap,r7=new WeakMap,o0=new WeakSet,n7=function(){if(this.receivedMessages.length===0)throw new x("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},tB=function(){if(this.receivedMessages.length===0)throw new x("stream ended without producing a Message with role=assistant");let w=this.receivedMessages.at(-1).content.filter((G)=>G.type==="text").map((G)=>G.text);if(w.length===0)throw new x("stream ended without producing a content block with type=text");return w.join(" ")},s7=function(){if(this.ended)return;_(this,K1,void 0,"f")},a7=function(w){if(this.ended)return;let G=A(this,o0,"m",oB).call(this,w);switch(this._emit("streamEvent",w,G),w.type){case"content_block_delta":{let Z=G.content.at(-1);switch(w.delta.type){case"text_delta":{if(Z.type==="text")this._emit("text",w.delta.text,Z.text||"");break}case"citations_delta":{if(Z.type==="text")this._emit("citation",w.delta.citation,Z.citations??[]);break}case"input_json_delta":{if($N(Z)&&Z.input)this._emit("inputJson",w.delta.partial_json,Z.input);break}case"thinking_delta":{if(Z.type==="thinking")this._emit("thinking",w.delta.thinking,Z.thinking);break}case"signature_delta":{if(Z.type==="thinking")this._emit("signature",Z.signature);break}default:wN(w.delta)}break}case"message_stop":{this._addMessageParam(G),this._addMessage(G,!0);break}case"content_block_stop":{this._emit("contentBlock",G.content.at(-1));break}case"message_start":{_(this,K1,G,"f");break}case"content_block_start":case"message_delta":break}},t7=function(){if(this.ended)throw new x("stream has ended, this shouldn't happen");let w=A(this,K1,"f");if(!w)throw new x("request ended without sending any chunks");return _(this,K1,void 0,"f"),w},oB=function(w){let G=A(this,K1,"f");if(w.type==="message_start"){if(G)throw new x(`Unexpected event order, got ${w.type} before receiving "message_stop"`);return w.message}if(!G)throw new x(`Unexpected event order, got ${w.type} before "message_start"`);switch(w.type){case"message_stop":return G;case"message_delta":if(G.stop_reason=w.delta.stop_reason,G.stop_sequence=w.delta.stop_sequence,G.usage.output_tokens=w.usage.output_tokens,w.usage.input_tokens!=null)G.usage.input_tokens=w.usage.input_tokens;if(w.usage.cache_creation_input_tokens!=null)G.usage.cache_creation_input_tokens=w.usage.cache_creation_input_tokens;if(w.usage.cache_read_input_tokens!=null)G.usage.cache_read_input_tokens=w.usage.cache_read_input_tokens;if(w.usage.server_tool_use!=null)G.usage.server_tool_use=w.usage.server_tool_use;return G;case"content_block_start":return G.content.push({...w.content_block}),G;case"content_block_delta":{let Z=G.content.at(w.index);switch(w.delta.type){case"text_delta":{if(Z?.type==="text")G.content[w.index]={...Z,text:(Z.text||"")+w.delta.text};break}case"citations_delta":{if(Z?.type==="text")G.content[w.index]={...Z,citations:[...Z.citations??[],w.delta.citation]};break}case"input_json_delta":{if(Z&&$N(Z)){let X=Z[eB]||"";X+=w.delta.partial_json;let Y={...Z};if(Object.defineProperty(Y,eB,{value:X,enumerable:!1,writable:!0}),X)Y.input=DG(X);G.content[w.index]=Y}break}case"thinking_delta":{if(Z?.type==="thinking")G.content[w.index]={...Z,thinking:Z.thinking+w.delta.thinking};break}case"signature_delta":{if(Z?.type==="thinking")G.content[w.index]={...Z,signature:w.delta.signature};break}default:wN(w.delta)}return G}case"content_block_stop":return G}},Symbol.asyncIterator)](){let $=[],w=[],G=!1;return this.on("streamEvent",(Z)=>{let X=w.shift();if(X)X.resolve(Z);else $.push(Z)}),this.on("end",()=>{G=!0;for(let Z of w)Z.resolve(void 0);w.length=0}),this.on("abort",(Z)=>{G=!0;for(let X of w)X.reject(Z);w.length=0}),this.on("error",(Z)=>{G=!0;for(let X of w)X.reject(Z);w.length=0}),{next:async()=>{if(!$.length){if(G)return{value:void 0,done:!0};return new Promise((X,Y)=>w.push({resolve:X,reject:Y})).then((X)=>X?{value:X,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new u0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function wN($){}class H8 extends P0{create($,w){return this._client.post("/v1/messages/batches",{body:$,...w})}retrieve($,w){return this._client.get(D0`/v1/messages/batches/${$}`,w)}list($={},w){return this._client.getAPIList("/v1/messages/batches",Q$,{query:$,...w})}delete($,w){return this._client.delete(D0`/v1/messages/batches/${$}`,w)}cancel($,w){return this._client.post(D0`/v1/messages/batches/${$}/cancel`,w)}async results($,w){let G=await this.retrieve($);if(!G.results_url)throw new x(`No batch \`results_url\`; Has it finished processing? ${G.processing_status} - ${G.id}`);return this._client.get(G.results_url,{...w,headers:s([{Accept:"application/binary"},w?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((Z,X)=>w4.fromResponse(X.response,X.controller))}}class $w extends P0{constructor(){super(...arguments);this.batches=new H8(this._client)}create($,w){if($.model in GN)console.warn(`The model '${$.model}' is deprecated and will reach end-of-life on ${GN[$.model]}
305
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let G=this._client._options.timeout;if(!$.stream&&G==null){let Z=bG[$.model]??void 0;G=this._client.calculateNonstreamingTimeout($.max_tokens,Z)}return this._client.post("/v1/messages",{body:$,timeout:G??600000,...w,stream:$.stream??!1})}stream($,w){return U8.createMessage(this,$,w)}countTokens($,w){return this._client.post("/v1/messages/count_tokens",{body:$,...w})}}var GN={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-5-sonnet-20241022":"October 22, 2025","claude-3-5-sonnet-20240620":"October 22, 2025"};$w.Batches=H8;class W4 extends P0{retrieve($,w={},G){let{betas:Z}=w??{};return this._client.get(D0`/v1/models/${$}`,{...G,headers:s([{...Z?.toString()!=null?{"anthropic-beta":Z?.toString()}:void 0},G?.headers])})}list($={},w){let{betas:G,...Z}=$??{};return this._client.getAPIList("/v1/models",Q$,{query:Z,...w,headers:s([{...G?.toString()!=null?{"anthropic-beta":G?.toString()}:void 0},w?.headers])})}}var F8=($)=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[$]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.($)?.trim();return};var o7,e7,hG,ZN,XN="\\n\\nHuman:",YN="\\n\\nAssistant:";class Z0{constructor({baseURL:$=F8("ANTHROPIC_BASE_URL"),apiKey:w=F8("ANTHROPIC_API_KEY")??null,authToken:G=F8("ANTHROPIC_AUTH_TOKEN")??null,...Z}={}){o7.add(this),hG.set(this,void 0);let X={apiKey:w,authToken:G,...Z,baseURL:$||"https://api.anthropic.com"};if(!X.dangerouslyAllowBrowser&&RB())throw new x(`It looks like you're running in a browser-like environment.
166
306
 
167
307
  This is disabled by default, as it risks exposing your secret API credentials to attackers.
168
308
  If you understand the risks and have appropriate mitigations in place,
169
309
  you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
170
310
 
171
311
  new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
172
- `);this.baseURL=Y.baseURL,this.timeout=Y.timeout??_W.DEFAULT_TIMEOUT,this.logger=Y.logger??console;let Z="warn";this.logLevel=Z,this.logLevel=UW(Y.logLevel,"ClientOptions.logLevel",this)??UW(Z9("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??Z,this.fetchOptions=Y.fetchOptions,this.maxRetries=Y.maxRetries??2,this.fetch=Y.fetch??sT(),I(this,_6,oT,"f"),this._options=Y,this.apiKey=w,this.authToken=G}withOptions($){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...$})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:$,nulls:w}){if(this.apiKey&&$.get("x-api-key"))return;if(w.has("x-api-key"))return;if(this.authToken&&$.get("authorization"))return;if(w.has("authorization"))return;throw Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders($){return n([await this.apiKeyAuth($),await this.bearerAuth($)])}async apiKeyAuth($){if(this.apiKey==null)return;return n([{"X-Api-Key":this.apiKey}])}async bearerAuth($){if(this.authToken==null)return;return n([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery($){return Object.entries($).filter(([w,G])=>typeof G<"u").map(([w,G])=>{if(typeof G==="string"||typeof G==="number"||typeof G==="boolean")return`${encodeURIComponent(w)}=${encodeURIComponent(G)}`;if(G===null)return`${encodeURIComponent(w)}=`;throw new b(`Cannot stringify type ${typeof G}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${n1}`}defaultIdempotencyKey(){return`stainless-node-retry-${KW()}`}makeStatusError($,w,G,W){return X0.generate($,w,G,W)}buildURL($,w,G){let W=!H(this,xW,"m",LM).call(this)&&G||this.baseURL,Y=hT($)?new URL($):new URL(W+(W.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),Z=this.defaultQuery();if(!iT(Z))w={...Z,...w};if(typeof w==="object"&&w&&!Array.isArray(w))Y.search=this.stringifyQuery(w);return Y.toString()}_calculateNonstreamingTimeout($){if(3600*$/128000>600)throw new b("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600000}async prepareOptions($){}async prepareRequest($,{url:w,options:G}){}get($,w){return this.methodRequest("get",$,w)}post($,w){return this.methodRequest("post",$,w)}patch($,w){return this.methodRequest("patch",$,w)}put($,w){return this.methodRequest("put",$,w)}delete($,w){return this.methodRequest("delete",$,w)}methodRequest($,w,G){return this.request(Promise.resolve(G).then((W)=>{return{method:$,path:w,...W}}))}request($,w=null){return new U$(this,this.makeRequest($,w,void 0))}async makeRequest($,w,G){let W=await $,Y=W.maxRetries??this.maxRetries;if(w==null)w=Y;await this.prepareOptions(W);let{req:Z,url:X,timeout:J}=await this.buildRequest(W,{retryCount:Y-w});await this.prepareRequest(Z,{url:X,options:W});let T="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),M=G===void 0?"":`, retryOf: ${G}`,f=Date.now();if(Q0(this).debug(`[${T}] sending request`,O1({retryOfRequestLogID:G,method:W.method,url:X,options:W,headers:Z.headers})),W.signal?.aborted)throw new q0;let Q=new AbortController,N=await this.fetchWithTimeout(X,Z,J,Q).catch(A4),z=Date.now();if(N instanceof globalThis.Error){let q=`retrying, ${w} attempts remaining`;if(W.signal?.aborted)throw new q0;let V=F1(N)||/timed? ?out/i.test(String(N)+("cause"in N?String(N.cause):""));if(w)return Q0(this).info(`[${T}] connection ${V?"timed out":"failed"} - ${q}`),Q0(this).debug(`[${T}] connection ${V?"timed out":"failed"} (${q})`,O1({retryOfRequestLogID:G,url:X,durationMs:z-f,message:N.message})),this.retryRequest(W,w,G??T);if(Q0(this).info(`[${T}] connection ${V?"timed out":"failed"} - error; no more retries left`),Q0(this).debug(`[${T}] connection ${V?"timed out":"failed"} (error; no more retries left)`,O1({retryOfRequestLogID:G,url:X,durationMs:z-f,message:N.message})),V)throw new S4;throw new E$({cause:N})}let K=[...N.headers.entries()].filter(([q])=>q==="request-id").map(([q,V])=>", "+q+": "+JSON.stringify(V)).join(""),P=`[${T}${M}${K}] ${Z.method} ${X} ${N.ok?"succeeded":"failed"} with status ${N.status} in ${z-f}ms`;if(!N.ok){let q=await this.shouldRetry(N);if(w&&q){let S=`retrying, ${w} attempts remaining`;return await aT(N.body),Q0(this).info(`${P} - ${S}`),Q0(this).debug(`[${T}] response error (${S})`,O1({retryOfRequestLogID:G,url:N.url,status:N.status,headers:N.headers,durationMs:z-f})),this.retryRequest(W,w,G??T,N.headers)}let V=q?"error; no more retries left":"error; not retryable";Q0(this).info(`${P} - ${V}`);let E=await N.text().catch((S)=>A4(S).message),O=z6(E),A=O?void 0:E;throw Q0(this).debug(`[${T}] response error (${V})`,O1({retryOfRequestLogID:G,url:N.url,status:N.status,headers:N.headers,message:A,durationMs:Date.now()-f})),this.makeStatusError(N.status,O,A,N.headers)}return Q0(this).info(P),Q0(this).debug(`[${T}] response start`,O1({retryOfRequestLogID:G,url:N.url,status:N.status,headers:N.headers,durationMs:z-f})),{response:N,options:W,controller:Q,requestLogID:T,retryOfRequestLogID:G,startTime:f}}getAPIList($,w,G){return this.requestAPIList(w,{method:"get",path:$,...G})}requestAPIList($,w){let G=this.makeRequest(w,null,void 0);return new E6(this,G,$)}async fetchWithTimeout($,w,G,W){let{signal:Y,method:Z,...X}=w||{};if(Y)Y.addEventListener("abort",()=>W.abort());let J=setTimeout(()=>W.abort(),G),T=globalThis.ReadableStream&&X.body instanceof globalThis.ReadableStream||typeof X.body==="object"&&X.body!==null&&Symbol.asyncIterator in X.body,M={signal:W.signal,...T?{duplex:"half"}:{},method:"GET",...X};if(Z)M.method=Z.toUpperCase();try{return await this.fetch.call(void 0,$,M)}finally{clearTimeout(J)}}async shouldRetry($){let w=$.headers.get("x-should-retry");if(w==="true")return!0;if(w==="false")return!1;if($.status===408)return!0;if($.status===409)return!0;if($.status===429)return!0;if($.status>=500)return!0;return!1}async retryRequest($,w,G,W){let Y,Z=W?.get("retry-after-ms");if(Z){let J=parseFloat(Z);if(!Number.isNaN(J))Y=J}let X=W?.get("retry-after");if(X&&!Y){let J=parseFloat(X);if(!Number.isNaN(J))Y=J*1000;else Y=Date.parse(X)-Date.now()}if(!(Y&&0<=Y&&Y<60000)){let J=$.maxRetries??this.maxRetries;Y=this.calculateDefaultRetryTimeoutMillis(w,J)}return await cT(Y),this.makeRequest($,w-1,G)}calculateDefaultRetryTimeoutMillis($,w){let Y=w-$,Z=Math.min(0.5*Math.pow(2,Y),8),X=1-Math.random()*0.25;return Z*X*1000}calculateNonstreamingTimeout($,w){if(3600000*$/128000>600000||w!=null&&$>w)throw new b("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 600000}async buildRequest($,{retryCount:w=0}={}){let G={...$},{method:W,path:Y,query:Z,defaultBaseURL:X}=G,J=this.buildURL(Y,Z,X);if("timeout"in G)lT("timeout",G.timeout);G.timeout=G.timeout??this.timeout;let{bodyHeaders:T,body:M}=this.buildBody({options:G}),f=await this.buildHeaders({options:$,method:W,bodyHeaders:T,retryCount:w});return{req:{method:W,headers:f,...G.signal&&{signal:G.signal},...globalThis.ReadableStream&&M instanceof globalThis.ReadableStream&&{duplex:"half"},...M&&{body:M},...this.fetchOptions??{},...G.fetchOptions??{}},url:J,timeout:G.timeout}}async buildHeaders({options:$,method:w,bodyHeaders:G,retryCount:W}){let Y={};if(this.idempotencyHeader&&w!=="get"){if(!$.idempotencyKey)$.idempotencyKey=this.defaultIdempotencyKey();Y[this.idempotencyHeader]=$.idempotencyKey}let Z=n([Y,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(W),...$.timeout?{"X-Stainless-Timeout":String(Math.trunc($.timeout/1000))}:{},...rT(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders($),this._options.defaultHeaders,G,$.headers]);return this.validateHeaders(Z),Z.values}buildBody({options:{body:$,headers:w}}){if(!$)return{bodyHeaders:void 0,body:void 0};let G=n([w]);if(ArrayBuffer.isView($)||$ instanceof ArrayBuffer||$ instanceof DataView||typeof $==="string"&&G.values.has("content-type")||globalThis.Blob&&$ instanceof globalThis.Blob||$ instanceof FormData||$ instanceof URLSearchParams||globalThis.ReadableStream&&$ instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:$};else if(typeof $==="object"&&((Symbol.asyncIterator in $)||(Symbol.iterator in $)&&("next"in $)&&typeof $.next==="function"))return{bodyHeaders:void 0,body:K6($)};else return H(this,_6,"f").call(this,{body:$,headers:G})}}_W=$0,_6=new WeakMap,xW=new WeakSet,LM=function(){return this.baseURL!=="https://api.anthropic.com"};$0.Anthropic=_W;$0.HUMAN_PROMPT=DM;$0.AI_PROMPT=kM;$0.DEFAULT_TIMEOUT=600000;$0.AnthropicError=b;$0.APIError=X0;$0.APIConnectionError=E$;$0.APIConnectionTimeoutError=S4;$0.APIUserAbortError=q0;$0.NotFoundError=y4;$0.ConflictError=I4;$0.RateLimitError=x4;$0.BadRequestError=R4;$0.AuthenticationError=j4;$0.InternalServerError=_4;$0.PermissionDeniedError=C4;$0.UnprocessableEntityError=b4;$0.toFile=U6;class A1 extends $0{constructor(){super(...arguments);this.completions=new Kw(this),this.messages=new F$(this),this.models=new Bw(this),this.beta=new D1(this)}}A1.Completions=Kw;A1.Messages=F$;A1.Models=Bw;A1.Beta=D1;class gW{client;constructor($){this.client=new A1({...$,maxRetries:0})}async*stream($){let{system:w,messages:G}=NO($.messages),W=this.client.messages.stream({model:$.model,system:w,messages:G,max_tokens:$.maxOutputTokens,...$.tools.length?{tools:$.tools.map((Z)=>({name:Z.name,description:Z.description,input_schema:Z.inputSchema}))}:{}},$.signal?{signal:$.signal}:void 0),Y=new Map;for await(let Z of W)if(Z.type==="content_block_start"&&Z.content_block.type==="tool_use")Y.set(Z.index,""),yield{type:"tool_call_start",index:Z.index,callId:Z.content_block.id,name:Z.content_block.name};else if(Z.type==="content_block_delta"&&Z.delta.type==="text_delta")yield{type:"text_delta",text:Z.delta.text};else if(Z.type==="content_block_delta"&&Z.delta.type==="input_json_delta")Y.set(Z.index,(Y.get(Z.index)??"")+Z.delta.partial_json),yield{type:"tool_call_delta",index:Z.index,argumentsDelta:Z.delta.partial_json};else if(Z.type==="content_block_stop"&&Y.has(Z.index))yield{type:"tool_call_end",index:Z.index};else if(Z.type==="message_start")yield{type:"usage",usage:{inputTokens:Z.message.usage.input_tokens,outputTokens:Z.message.usage.output_tokens}};else if(Z.type==="message_delta")yield{type:"usage",usage:{inputTokens:0,outputTokens:Z.usage.output_tokens}};yield{type:"done"}}}function NO($){let w=$.filter((W)=>W.role==="system").map((W)=>W.content).join(`
312
+ `);this.baseURL=X.baseURL,this.timeout=X.timeout??e7.DEFAULT_TIMEOUT,this.logger=X.logger??console;let Y="warn";this.logLevel=Y,this.logLevel=g7(X.logLevel,"ClientOptions.logLevel",this)??g7(F8("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??Y,this.fetchOptions=X.fetchOptions,this.maxRetries=X.maxRetries??2,this.fetch=X.fetch??IB(),_(this,hG,CB,"f"),this._options=X,this.apiKey=w,this.authToken=G}withOptions($){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...$})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:$,nulls:w}){if(this.apiKey&&$.get("x-api-key"))return;if(w.has("x-api-key"))return;if(this.authToken&&$.get("authorization"))return;if(w.has("authorization"))return;throw Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders($){return s([await this.apiKeyAuth($),await this.bearerAuth($)])}async apiKeyAuth($){if(this.apiKey==null)return;return s([{"X-Api-Key":this.apiKey}])}async bearerAuth($){if(this.authToken==null)return;return s([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery($){return Object.entries($).filter(([w,G])=>typeof G<"u").map(([w,G])=>{if(typeof G==="string"||typeof G==="number"||typeof G==="boolean")return`${encodeURIComponent(w)}=${encodeURIComponent(G)}`;if(G===null)return`${encodeURIComponent(w)}=`;throw new x(`Cannot stringify type ${typeof G}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${B1}`}defaultIdempotencyKey(){return`stainless-node-retry-${C7()}`}makeStatusError($,w,G,Z){return M0.generate($,w,G,Z)}buildURL($,w,G){let Z=!A(this,o7,"m",ZN).call(this)&&G||this.baseURL,X=HB($)?new URL($):new URL(Z+(Z.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),Y=this.defaultQuery();if(!FB(Y))w={...Y,...w};if(typeof w==="object"&&w&&!Array.isArray(w))X.search=this.stringifyQuery(w);return X.toString()}_calculateNonstreamingTimeout($){if(3600*$/128000>600)throw new x("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600000}async prepareOptions($){}async prepareRequest($,{url:w,options:G}){}get($,w){return this.methodRequest("get",$,w)}post($,w){return this.methodRequest("post",$,w)}patch($,w){return this.methodRequest("patch",$,w)}put($,w){return this.methodRequest("put",$,w)}delete($,w){return this.methodRequest("delete",$,w)}methodRequest($,w,G){return this.request(Promise.resolve(G).then((Z)=>{return{method:$,path:w,...Z}}))}request($,w=null){return new o1(this,this.makeRequest($,w,void 0))}async makeRequest($,w,G){let Z=await $,X=Z.maxRetries??this.maxRetries;if(w==null)w=X;await this.prepareOptions(Z);let{req:Y,url:J,timeout:W}=await this.buildRequest(Z,{retryCount:X-w});await this.prepareRequest(Y,{url:J,options:Z});let T="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),Q=G===void 0?"":`, retryOf: ${G}`,z=Date.now();if(V0(this).debug(`[${T}] sending request`,x$({retryOfRequestLogID:G,method:Z.method,url:J,options:Z,headers:Y.headers})),Z.signal?.aborted)throw new L0;let M=new AbortController,P=await this.fetchWithTimeout(J,Y,W,M).catch(m9),q=Date.now();if(P instanceof globalThis.Error){let V=`retrying, ${w} attempts remaining`;if(Z.signal?.aborted)throw new L0;let K=_$(P)||/timed? ?out/i.test(String(P)+("cause"in P?String(P.cause):""));if(w)return V0(this).info(`[${T}] connection ${K?"timed out":"failed"} - ${V}`),V0(this).debug(`[${T}] connection ${K?"timed out":"failed"} (${V})`,x$({retryOfRequestLogID:G,url:J,durationMs:q-z,message:P.message})),this.retryRequest(Z,w,G??T);if(V0(this).info(`[${T}] connection ${K?"timed out":"failed"} - error; no more retries left`),V0(this).debug(`[${T}] connection ${K?"timed out":"failed"} (error; no more retries left)`,x$({retryOfRequestLogID:G,url:J,durationMs:q-z,message:P.message})),K)throw new l9;throw new t1({cause:P})}let N=[...P.headers.entries()].filter(([V])=>V==="request-id").map(([V,K])=>", "+V+": "+JSON.stringify(K)).join(""),B=`[${T}${Q}${N}] ${Y.method} ${J} ${P.ok?"succeeded":"failed"} with status ${P.status} in ${q-z}ms`;if(!P.ok){let V=await this.shouldRetry(P);if(w&&V){let L=`retrying, ${w} attempts remaining`;return await jB(P.body),V0(this).info(`${B} - ${L}`),V0(this).debug(`[${T}] response error (${L})`,x$({retryOfRequestLogID:G,url:P.url,status:P.status,headers:P.headers,durationMs:q-z})),this.retryRequest(Z,w,G??T,P.headers)}let K=V?"error; no more retries left":"error; not retryable";V0(this).info(`${B} - ${K}`);let U=await P.text().catch((L)=>m9(L).message),O=VG(U),D=O?void 0:U;throw V0(this).debug(`[${T}] response error (${K})`,x$({retryOfRequestLogID:G,url:P.url,status:P.status,headers:P.headers,message:D,durationMs:Date.now()-z})),this.makeStatusError(P.status,O,D,P.headers)}return V0(this).info(B),V0(this).debug(`[${T}] response start`,x$({retryOfRequestLogID:G,url:P.url,status:P.status,headers:P.headers,durationMs:q-z})),{response:P,options:Z,controller:M,requestLogID:T,retryOfRequestLogID:G,startTime:z}}getAPIList($,w,G){return this.requestAPIList(w,{method:"get",path:$,...G})}requestAPIList($,w){let G=this.makeRequest(w,null,void 0);return new fG(this,G,$)}async fetchWithTimeout($,w,G,Z){let{signal:X,method:Y,...J}=w||{};if(X)X.addEventListener("abort",()=>Z.abort());let W=setTimeout(()=>Z.abort(),G),T=globalThis.ReadableStream&&J.body instanceof globalThis.ReadableStream||typeof J.body==="object"&&J.body!==null&&Symbol.asyncIterator in J.body,Q={signal:Z.signal,...T?{duplex:"half"}:{},method:"GET",...J};if(Y)Q.method=Y.toUpperCase();try{return await this.fetch.call(void 0,$,Q)}finally{clearTimeout(W)}}async shouldRetry($){let w=$.headers.get("x-should-retry");if(w==="true")return!0;if(w==="false")return!1;if($.status===408)return!0;if($.status===409)return!0;if($.status===429)return!0;if($.status>=500)return!0;return!1}async retryRequest($,w,G,Z){let X,Y=Z?.get("retry-after-ms");if(Y){let W=parseFloat(Y);if(!Number.isNaN(W))X=W}let J=Z?.get("retry-after");if(J&&!X){let W=parseFloat(J);if(!Number.isNaN(W))X=W*1000;else X=Date.parse(J)-Date.now()}if(!(X&&0<=X&&X<60000)){let W=$.maxRetries??this.maxRetries;X=this.calculateDefaultRetryTimeoutMillis(w,W)}return await LB(X),this.makeRequest($,w-1,G)}calculateDefaultRetryTimeoutMillis($,w){let X=w-$,Y=Math.min(0.5*Math.pow(2,X),8),J=1-Math.random()*0.25;return Y*J*1000}calculateNonstreamingTimeout($,w){if(3600000*$/128000>600000||w!=null&&$>w)throw new x("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 600000}async buildRequest($,{retryCount:w=0}={}){let G={...$},{method:Z,path:X,query:Y,defaultBaseURL:J}=G,W=this.buildURL(X,Y,J);if("timeout"in G)fB("timeout",G.timeout);G.timeout=G.timeout??this.timeout;let{bodyHeaders:T,body:Q}=this.buildBody({options:G}),z=await this.buildHeaders({options:$,method:Z,bodyHeaders:T,retryCount:w});return{req:{method:Z,headers:z,...G.signal&&{signal:G.signal},...globalThis.ReadableStream&&Q instanceof globalThis.ReadableStream&&{duplex:"half"},...Q&&{body:Q},...this.fetchOptions??{},...G.fetchOptions??{}},url:W,timeout:G.timeout}}async buildHeaders({options:$,method:w,bodyHeaders:G,retryCount:Z}){let X={};if(this.idempotencyHeader&&w!=="get"){if(!$.idempotencyKey)$.idempotencyKey=this.defaultIdempotencyKey();X[this.idempotencyHeader]=$.idempotencyKey}let Y=s([X,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(Z),...$.timeout?{"X-Stainless-Timeout":String(Math.trunc($.timeout/1000))}:{},...SB(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders($),this._options.defaultHeaders,G,$.headers]);return this.validateHeaders(Y),Y.values}buildBody({options:{body:$,headers:w}}){if(!$)return{bodyHeaders:void 0,body:void 0};let G=s([w]);if(ArrayBuffer.isView($)||$ instanceof ArrayBuffer||$ instanceof DataView||typeof $==="string"&&G.values.has("content-type")||globalThis.Blob&&$ instanceof globalThis.Blob||$ instanceof FormData||$ instanceof URLSearchParams||globalThis.ReadableStream&&$ instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:$};else if(typeof $==="object"&&((Symbol.asyncIterator in $)||(Symbol.iterator in $)&&("next"in $)&&typeof $.next==="function"))return{bodyHeaders:void 0,body:KG($)};else return A(this,hG,"f").call(this,{body:$,headers:G})}}e7=Z0,hG=new WeakMap,o7=new WeakSet,ZN=function(){return this.baseURL!=="https://api.anthropic.com"};Z0.Anthropic=e7;Z0.HUMAN_PROMPT=XN;Z0.AI_PROMPT=YN;Z0.DEFAULT_TIMEOUT=600000;Z0.AnthropicError=x;Z0.APIError=M0;Z0.APIConnectionError=t1;Z0.APIConnectionTimeoutError=l9;Z0.APIUserAbortError=L0;Z0.NotFoundError=n9;Z0.ConflictError=r9;Z0.RateLimitError=a9;Z0.BadRequestError=d9;Z0.AuthenticationError=c9;Z0.InternalServerError=t9;Z0.PermissionDeniedError=p9;Z0.UnprocessableEntityError=s9;Z0.toFile=LG;class v$ extends Z0{constructor(){super(...arguments);this.completions=new Y4(this),this.messages=new $w(this),this.models=new W4(this),this.beta=new u$(this)}}v$.Completions=Y4;v$.Messages=$w;v$.Models=W4;v$.Beta=u$;class $Y{client;constructor($){this.client=new v$({...$,maxRetries:0})}async*stream($){let{system:w,messages:G}=ex($.messages),Z=this.client.messages.stream({model:$.model,system:w,messages:G,max_tokens:$.maxOutputTokens,...$.tools.length?{tools:$.tools.map((Y)=>({name:Y.name,description:Y.description,input_schema:Y.inputSchema}))}:{}},$.signal?{signal:$.signal}:void 0),X=new Map;for await(let Y of Z)if(Y.type==="content_block_start"&&Y.content_block.type==="tool_use")X.set(Y.index,""),yield{type:"tool_call_start",index:Y.index,callId:Y.content_block.id,name:Y.content_block.name};else if(Y.type==="content_block_delta"&&Y.delta.type==="text_delta")yield{type:"text_delta",text:Y.delta.text};else if(Y.type==="content_block_delta"&&Y.delta.type==="input_json_delta")X.set(Y.index,(X.get(Y.index)??"")+Y.delta.partial_json),yield{type:"tool_call_delta",index:Y.index,argumentsDelta:Y.delta.partial_json};else if(Y.type==="content_block_stop"&&X.has(Y.index))yield{type:"tool_call_end",index:Y.index};else if(Y.type==="message_start")yield{type:"usage",usage:{inputTokens:Y.message.usage.input_tokens,outputTokens:Y.message.usage.output_tokens}};else if(Y.type==="message_delta")yield{type:"usage",usage:{inputTokens:0,outputTokens:Y.usage.output_tokens}};yield{type:"done"}}}function ex($){let w=$.filter((Z)=>Z.role==="system").map((Z)=>Z.content).join(`
173
313
 
174
- `),G=[];for(let W of $){if(W.role==="system")continue;if(W.role==="user")G.push({role:"user",content:W.content});else if(W.role==="assistant")G.push({role:"assistant",content:[...W.content?[{type:"text",text:W.content}]:[],...W.toolCalls.map((Y)=>({type:"tool_use",id:Y.callId,name:Y.name,input:Y.input}))]});else{let Y={type:"tool_result",tool_use_id:W.callId,content:W.content,is_error:W.isError},Z=G.at(-1);if(Z?.role==="user"&&Array.isArray(Z.content))Z.content=[...Z.content,Y];else G.push({role:"user",content:[Y]})}}return{system:w,messages:G}}function C($,w,G,W,Y){if(W==="m")throw TypeError("Private method is not writable");if(W==="a"&&!Y)throw TypeError("Private accessor was defined without a setter");if(typeof w==="function"?$!==w||!Y:!w.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return W==="a"?Y.call($,G):Y?Y.value=G:w.set($,G),G}function B($,w,G,W){if(G==="a"&&!W)throw TypeError("Private accessor was defined without a getter");if(typeof w==="function"?$!==w||!W:!w.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return G==="m"?W:G==="a"?W.call($):W?W.value:w.get($)}var vW=function(){let{crypto:$}=globalThis;if($?.randomUUID)return vW=$.randomUUID.bind($),$.randomUUID();let w=new Uint8Array(1),G=$?()=>$.getRandomValues(w)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(W)=>(+W^G()&15>>+W/4).toString(16))};function X9($){return typeof $==="object"&&$!==null&&(("name"in $)&&$.name==="AbortError"||("message"in $)&&String($.message).includes("FetchRequestCanceledException"))}var J9=($)=>{if($ instanceof Error)return $;if(typeof $==="object"&&$!==null){try{if(Object.prototype.toString.call($)==="[object Error]"){let w=Error($.message,$.cause?{cause:$.cause}:{});if($.stack)w.stack=$.stack;if($.cause&&!w.cause)w.cause=$.cause;if($.name)w.name=$.name;return w}}catch{}try{return Error(JSON.stringify($))}catch{}}return Error($)};class k extends Error{}class Z0 extends k{constructor($,w,G,W){super(`${Z0.makeMessage($,w,G)}`);this.status=$,this.headers=W,this.requestID=W?.get("x-request-id"),this.error=w;let Y=w;this.code=Y?.code,this.param=Y?.param,this.type=Y?.type}static makeMessage($,w,G){let W=w?.message?typeof w.message==="string"?w.message:JSON.stringify(w.message):w?JSON.stringify(w):G;if($&&W)return`${$} ${W}`;if($)return`${$} status code (no body)`;if(W)return W;return"(no status code or body)"}static generate($,w,G,W){if(!$||!W)return new O$({message:G,cause:J9(w)});let Y=w?.error;if($===400)return new T9($,Y,G,W);if($===401)return new M9($,Y,G,W);if($===403)return new f9($,Y,G,W);if($===404)return new Q9($,Y,G,W);if($===409)return new N9($,Y,G,W);if($===422)return new z9($,Y,G,W);if($===429)return new K9($,Y,G,W);if($>=500)return new P9($,Y,G,W);return new Z0($,Y,G,W)}}class T0 extends Z0{constructor({message:$}={}){super(void 0,void 0,$||"Request was aborted.",void 0)}}class O$ extends Z0{constructor({message:$,cause:w}){super(void 0,void 0,$||"Connection error.",void 0);if(w)this.cause=w}}class L$ extends O${constructor({message:$}={}){super({message:$??"Request timed out."})}}class T9 extends Z0{}class M9 extends Z0{}class f9 extends Z0{}class Q9 extends Z0{}class N9 extends Z0{}class z9 extends Z0{}class K9 extends Z0{}class P9 extends Z0{}class B9 extends k{constructor(){super("Could not parse response content as the length limit was reached")}}class V9 extends k{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class S1 extends Error{constructor($){super($)}}var KO=/^[a-z][a-z0-9+.-]*:/i,AM=($)=>{return KO.test($)},U0=($)=>(U0=Array.isArray,U0($)),uW=U0;function hW($){if(typeof $!=="object")return{};return $??{}}function SM($){if(!$)return!0;for(let w in $)return!1;return!0}function RM($,w){return Object.prototype.hasOwnProperty.call($,w)}function q9($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var jM=($,w)=>{if(typeof w!=="number"||!Number.isInteger(w))throw new k(`${$} must be an integer`);if(w<0)throw new k(`${$} must be a positive integer`);return w};var CM=($)=>{try{return JSON.parse($)}catch(w){return}};var f1=($)=>new Promise((w)=>setTimeout(w,$));var s1="5.23.2";var xM=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"};function PO(){if(typeof Deno<"u"&&Deno.build!=null)return"deno";if(typeof EdgeRuntime<"u")return"edge";if(Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]")return"node";return"unknown"}var BO=()=>{let $=PO();if($==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":s1,"X-Stainless-OS":IM(Deno.build.os),"X-Stainless-Arch":yM(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version==="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":s1,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if($==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":s1,"X-Stainless-OS":IM(globalThis.process.platform??"unknown"),"X-Stainless-Arch":yM(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let w=VO();if(w)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":s1,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${w.browser}`,"X-Stainless-Runtime-Version":w.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":s1,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function VO(){if(typeof navigator>"u"||!navigator)return null;let $=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:w,pattern:G}of $){let W=G.exec(navigator.userAgent);if(W){let Y=W[1]||0,Z=W[2]||0,X=W[3]||0;return{browser:w,version:`${Y}.${Z}.${X}`}}}return null}var yM=($)=>{if($==="x32")return"x32";if($==="x86_64"||$==="x64")return"x64";if($==="arm")return"arm";if($==="aarch64"||$==="arm64")return"arm64";if($)return`other:${$}`;return"unknown"},IM=($)=>{if($=$.toLowerCase(),$.includes("ios"))return"iOS";if($==="android")return"Android";if($==="darwin")return"MacOS";if($==="win32")return"Windows";if($==="freebsd")return"FreeBSD";if($==="openbsd")return"OpenBSD";if($==="linux")return"Linux";if($)return`Other:${$}`;return"Unknown"},bM,_M=()=>{return bM??(bM=BO())};function gM(){if(typeof fetch<"u")return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function iW(...$){let w=globalThis.ReadableStream;if(typeof w>"u")throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new w(...$)}function g6($){let w=Symbol.asyncIterator in $?$[Symbol.asyncIterator]():$[Symbol.iterator]();return iW({start(){},async pull(G){let{done:W,value:Y}=await w.next();if(W)G.close();else G.enqueue(Y)},async cancel(){await w.return?.()}})}function mW($){if($[Symbol.asyncIterator])return $;let w=$.getReader();return{async next(){try{let G=await w.read();if(G?.done)w.releaseLock();return G}catch(G){throw w.releaseLock(),G}},async return(){let G=w.cancel();return w.releaseLock(),await G,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function vM($){if($===null||typeof $!=="object")return;if($[Symbol.asyncIterator]){await $[Symbol.asyncIterator]().return?.();return}let w=$.getReader(),G=w.cancel();w.releaseLock(),await G}var uM=({headers:$,body:w})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(w)}};var v6="RFC3986",lW=($)=>String($),u6={RFC1738:($)=>String($).replace(/%20/g,"+"),RFC3986:lW},cW="RFC1738";var h6=($,w)=>(h6=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),h6($,w)),Q1=(()=>{let $=[];for(let w=0;w<256;++w)$.push("%"+((w<16?"0":"")+w.toString(16)).toUpperCase());return $})();var dW=1024,hM=($,w,G,W,Y)=>{if($.length===0)return $;let Z=$;if(typeof $==="symbol")Z=Symbol.prototype.toString.call($);else if(typeof $!=="string")Z=String($);if(G==="iso-8859-1")return escape(Z).replace(/%u[0-9a-f]{4}/gi,function(J){return"%26%23"+parseInt(J.slice(2),16)+"%3B"});let X="";for(let J=0;J<Z.length;J+=dW){let T=Z.length>=dW?Z.slice(J,J+dW):Z,M=[];for(let f=0;f<T.length;++f){let Q=T.charCodeAt(f);if(Q===45||Q===46||Q===95||Q===126||Q>=48&&Q<=57||Q>=65&&Q<=90||Q>=97&&Q<=122||Y===cW&&(Q===40||Q===41)){M[M.length]=T.charAt(f);continue}if(Q<128){M[M.length]=Q1[Q];continue}if(Q<2048){M[M.length]=Q1[192|Q>>6]+Q1[128|Q&63];continue}if(Q<55296||Q>=57344){M[M.length]=Q1[224|Q>>12]+Q1[128|Q>>6&63]+Q1[128|Q&63];continue}f+=1,Q=65536+((Q&1023)<<10|T.charCodeAt(f)&1023),M[M.length]=Q1[240|Q>>18]+Q1[128|Q>>12&63]+Q1[128|Q>>6&63]+Q1[128|Q&63]}X+=M.join("")}return X};function iM($){if(!$||typeof $!=="object")return!1;return!!($.constructor&&$.constructor.isBuffer&&$.constructor.isBuffer($))}function nW($,w){if(U0($)){let G=[];for(let W=0;W<$.length;W+=1)G.push(w($[W]));return G}return w($)}var lM={brackets($){return String($)+"[]"},comma:"comma",indices($,w){return String($)+"["+w+"]"},repeat($){return String($)}},cM=function($,w){Array.prototype.push.apply($,U0(w)?w:[w])},mM,M0={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:hM,encodeValuesOnly:!1,format:v6,formatter:lW,indices:!1,serializeDate($){return(mM??(mM=Function.prototype.call.bind(Date.prototype.toISOString)))($)},skipNulls:!1,strictNullHandling:!1};function UO($){return typeof $==="string"||typeof $==="number"||typeof $==="boolean"||typeof $==="symbol"||typeof $==="bigint"}var pW={};function dM($,w,G,W,Y,Z,X,J,T,M,f,Q,N,z,K,P,q,V){let E=$,O=V,A=0,R=!1;while((O=O.get(pW))!==void 0&&!R){let v=O.get($);if(A+=1,typeof v<"u")if(v===A)throw RangeError("Cyclic object value");else R=!0;if(typeof O.get(pW)>"u")A=0}if(typeof M==="function")E=M(w,E);else if(E instanceof Date)E=N?.(E);else if(G==="comma"&&U0(E))E=nW(E,function(v){if(v instanceof Date)return N?.(v);return v});if(E===null){if(Z)return T&&!P?T(w,M0.encoder,q,"key",z):w;E=""}if(UO(E)||iM(E)){if(T){let v=P?w:T(w,M0.encoder,q,"key",z);return[K?.(v)+"="+K?.(T(E,M0.encoder,q,"value",z))]}return[K?.(w)+"="+K?.(String(E))]}let S=[];if(typeof E>"u")return S;let _;if(G==="comma"&&U0(E)){if(P&&T)E=nW(E,T);_=[{value:E.length>0?E.join(",")||null:void 0}]}else if(U0(M))_=M;else{let v=Object.keys(E);_=f?v.sort(f):v}let s=J?String(w).replace(/\./g,"%2E"):String(w),e=W&&U0(E)&&E.length===1?s+"[]":s;if(Y&&U0(E)&&E.length===0)return e+"[]";for(let v=0;v<_.length;++v){let H0=_[v],x1=typeof H0==="object"&&typeof H0.value<"u"?H0.value:E[H0];if(X&&x1===null)continue;let W1=Q&&J?H0.replace(/\./g,"%2E"):H0,lw=U0(E)?typeof G==="function"?G(e,W1):e:e+(Q?"."+W1:"["+W1+"]");V.set($,A);let cw=new WeakMap;cw.set(pW,V),cM(S,dM(x1,lw,G,W,Y,Z,X,J,G==="comma"&&P&&U0(E)?null:T,M,f,Q,N,z,K,P,q,cw))}return S}function HO($=M0){if(typeof $.allowEmptyArrays<"u"&&typeof $.allowEmptyArrays!=="boolean")throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof $.encodeDotInKeys<"u"&&typeof $.encodeDotInKeys!=="boolean")throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if($.encoder!==null&&typeof $.encoder<"u"&&typeof $.encoder!=="function")throw TypeError("Encoder has to be a function.");let w=$.charset||M0.charset;if(typeof $.charset<"u"&&$.charset!=="utf-8"&&$.charset!=="iso-8859-1")throw TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let G=v6;if(typeof $.format<"u"){if(!h6(u6,$.format))throw TypeError("Unknown format option provided.");G=$.format}let W=u6[G],Y=M0.filter;if(typeof $.filter==="function"||U0($.filter))Y=$.filter;let Z;if($.arrayFormat&&$.arrayFormat in lM)Z=$.arrayFormat;else if("indices"in $)Z=$.indices?"indices":"repeat";else Z=M0.arrayFormat;if("commaRoundTrip"in $&&typeof $.commaRoundTrip!=="boolean")throw TypeError("`commaRoundTrip` must be a boolean, or absent");let X=typeof $.allowDots>"u"?!!$.encodeDotInKeys===!0?!0:M0.allowDots:!!$.allowDots;return{addQueryPrefix:typeof $.addQueryPrefix==="boolean"?$.addQueryPrefix:M0.addQueryPrefix,allowDots:X,allowEmptyArrays:typeof $.allowEmptyArrays==="boolean"?!!$.allowEmptyArrays:M0.allowEmptyArrays,arrayFormat:Z,charset:w,charsetSentinel:typeof $.charsetSentinel==="boolean"?$.charsetSentinel:M0.charsetSentinel,commaRoundTrip:!!$.commaRoundTrip,delimiter:typeof $.delimiter>"u"?M0.delimiter:$.delimiter,encode:typeof $.encode==="boolean"?$.encode:M0.encode,encodeDotInKeys:typeof $.encodeDotInKeys==="boolean"?$.encodeDotInKeys:M0.encodeDotInKeys,encoder:typeof $.encoder==="function"?$.encoder:M0.encoder,encodeValuesOnly:typeof $.encodeValuesOnly==="boolean"?$.encodeValuesOnly:M0.encodeValuesOnly,filter:Y,format:G,formatter:W,serializeDate:typeof $.serializeDate==="function"?$.serializeDate:M0.serializeDate,skipNulls:typeof $.skipNulls==="boolean"?$.skipNulls:M0.skipNulls,sort:typeof $.sort==="function"?$.sort:null,strictNullHandling:typeof $.strictNullHandling==="boolean"?$.strictNullHandling:M0.strictNullHandling}}function tW($,w={}){let G=$,W=HO(w),Y,Z;if(typeof W.filter==="function")Z=W.filter,G=Z("",G);else if(U0(W.filter))Z=W.filter,Y=Z;let X=[];if(typeof G!=="object"||G===null)return"";let J=lM[W.arrayFormat],T=J==="comma"&&W.commaRoundTrip;if(!Y)Y=Object.keys(G);if(W.sort)Y.sort(W.sort);let M=new WeakMap;for(let N=0;N<Y.length;++N){let z=Y[N];if(W.skipNulls&&G[z]===null)continue;cM(X,dM(G[z],z,J,T,W.allowEmptyArrays,W.strictNullHandling,W.skipNulls,W.encodeDotInKeys,W.encode?W.encoder:null,W.filter,W.sort,W.allowDots,W.serializeDate,W.format,W.formatter,W.encodeValuesOnly,W.charset,M))}let f=X.join(W.delimiter),Q=W.addQueryPrefix===!0?"?":"";if(W.charsetSentinel)if(W.charset==="iso-8859-1")Q+="utf8=%26%2310003%3B&";else Q+="utf8=%E2%9C%93&";return f.length>0?Q+f:""}function tM($){let w=0;for(let Y of $)w+=Y.length;let G=new Uint8Array(w),W=0;for(let Y of $)G.set(Y,W),W+=Y.length;return G}var nM;function Vw($){let w;return(nM??(w=new globalThis.TextEncoder,nM=w.encode.bind(w)))($)}var pM;function rW($){let w;return(pM??(w=new globalThis.TextDecoder,pM=w.decode.bind(w)))($)}var x0,_0;class qw{constructor(){x0.set(this,void 0),_0.set(this,void 0),C(this,x0,new Uint8Array,"f"),C(this,_0,null,"f")}decode($){if($==null)return[];let w=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?Vw($):$;C(this,x0,tM([B(this,x0,"f"),w]),"f");let G=[],W;while((W=OO(B(this,x0,"f"),B(this,_0,"f")))!=null){if(W.carriage&&B(this,_0,"f")==null){C(this,_0,W.index,"f");continue}if(B(this,_0,"f")!=null&&(W.index!==B(this,_0,"f")+1||W.carriage)){G.push(rW(B(this,x0,"f").subarray(0,B(this,_0,"f")-1))),C(this,x0,B(this,x0,"f").subarray(B(this,_0,"f")),"f"),C(this,_0,null,"f");continue}let Y=B(this,_0,"f")!==null?W.preceding-1:W.preceding,Z=rW(B(this,x0,"f").subarray(0,Y));G.push(Z),C(this,x0,B(this,x0,"f").subarray(W.index),"f"),C(this,_0,null,"f")}return G}flush(){if(!B(this,x0,"f").length)return[];return this.decode(`
175
- `)}}x0=new WeakMap,_0=new WeakMap;qw.NEWLINE_CHARS=new Set([`
176
- `,"\r"]);qw.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function OO($,w){for(let Y=w??0;Y<$.length;Y++){if($[Y]===10)return{preceding:Y,index:Y+1,carriage:!1};if($[Y]===13)return{preceding:Y,index:Y+1,carriage:!0}}return null}function rM($){for(let W=0;W<$.length-1;W++){if($[W]===10&&$[W+1]===10)return W+2;if($[W]===13&&$[W+1]===13)return W+2;if($[W]===13&&$[W+1]===10&&W+3<$.length&&$[W+2]===13&&$[W+3]===10)return W+4}return-1}var m6={off:0,error:200,warn:300,info:400,debug:500},sW=($,w,G)=>{if(!$)return;if(RM(m6,$))return $;W0(G).warn(`${w} was set to ${JSON.stringify($)}, expected one of ${JSON.stringify(Object.keys(m6))}`);return};function E9(){}function i6($,w,G){if(!w||m6[$]>m6[G])return E9;else return w[$].bind(w)}var LO={error:E9,warn:E9,info:E9,debug:E9},sM=new WeakMap;function W0($){let w=$.logger,G=$.logLevel??"off";if(!w)return LO;let W=sM.get(w);if(W&&W[0]===G)return W[1];let Y={error:i6("error",w,G),warn:i6("warn",w,G),info:i6("info",w,G),debug:i6("debug",w,G)};return sM.set(w,[G,Y]),Y}var R1=($)=>{if($.options)$.options={...$.options},delete $.options.headers;if($.headers)$.headers=Object.fromEntries(($.headers instanceof Headers?[...$.headers]:Object.entries($.headers)).map(([w,G])=>[w,w.toLowerCase()==="authorization"||w.toLowerCase()==="cookie"||w.toLowerCase()==="set-cookie"?"***":G]));if("retryOfRequestLogID"in $){if($.retryOfRequestLogID)$.retryOf=$.retryOfRequestLogID;delete $.retryOfRequestLogID}return $};var U9;class g0{constructor($,w,G){this.iterator=$,U9.set(this,void 0),this.controller=w,C(this,U9,G,"f")}static fromSSEResponse($,w,G){let W=!1,Y=G?W0(G):console;async function*Z(){if(W)throw new k("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");W=!0;let X=!1;try{for await(let J of DO($,w)){if(X)continue;if(J.data.startsWith("[DONE]")){X=!0;continue}if(J.event===null||!J.event.startsWith("thread.")){let T;try{T=JSON.parse(J.data)}catch(M){throw Y.error("Could not parse message into JSON:",J.data),Y.error("From chunk:",J.raw),M}if(T&&T.error)throw new Z0(void 0,T.error,void 0,$.headers);yield T}else{let T;try{T=JSON.parse(J.data)}catch(M){throw console.error("Could not parse message into JSON:",J.data),console.error("From chunk:",J.raw),M}if(J.event=="error")throw new Z0(void 0,T.error,T.message,void 0);yield{event:J.event,data:T}}}X=!0}catch(J){if(X9(J))return;throw J}finally{if(!X)w.abort()}}return new g0(Z,w,G)}static fromReadableStream($,w,G){let W=!1;async function*Y(){let X=new qw,J=mW($);for await(let T of J)for(let M of X.decode(T))yield M;for(let T of X.flush())yield T}async function*Z(){if(W)throw new k("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");W=!0;let X=!1;try{for await(let J of Y()){if(X)continue;if(J)yield JSON.parse(J)}X=!0}catch(J){if(X9(J))return;throw J}finally{if(!X)w.abort()}}return new g0(Z,w,G)}[(U9=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let $=[],w=[],G=this.iterator(),W=(Y)=>{return{next:()=>{if(Y.length===0){let Z=G.next();$.push(Z),w.push(Z)}return Y.shift()}}};return[new g0(()=>W($),this.controller,B(this,U9,"f")),new g0(()=>W(w),this.controller,B(this,U9,"f"))]}toReadableStream(){let $=this,w;return iW({async start(){w=$[Symbol.asyncIterator]()},async pull(G){try{let{value:W,done:Y}=await w.next();if(Y)return G.close();let Z=Vw(JSON.stringify(W)+`
177
- `);G.enqueue(Z)}catch(W){G.error(W)}},async cancel(){await w.return?.()}})}}async function*DO($,w){if(!$.body){if(w.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new k("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new k("Attempted to iterate over a response with no body")}let G=new aM,W=new qw,Y=mW($.body);for await(let Z of kO(Y))for(let X of W.decode(Z)){let J=G.decode(X);if(J)yield J}for(let Z of W.flush()){let X=G.decode(Z);if(X)yield X}}async function*kO($){let w=new Uint8Array;for await(let G of $){if(G==null)continue;let W=G instanceof ArrayBuffer?new Uint8Array(G):typeof G==="string"?Vw(G):G,Y=new Uint8Array(w.length+W.length);Y.set(w),Y.set(W,w.length),w=Y;let Z;while((Z=rM(w))!==-1)yield w.slice(0,Z),w=w.slice(Z)}if(w.length>0)yield w}class aM{constructor(){this.event=null,this.data=[],this.chunks=[]}decode($){if($.endsWith("\r"))$=$.substring(0,$.length-1);if(!$){if(!this.event&&!this.data.length)return null;let Y={event:this.event,data:this.data.join(`
178
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],Y}if(this.chunks.push($),$.startsWith(":"))return null;let[w,G,W]=AO($,":");if(W.startsWith(" "))W=W.substring(1);if(w==="event")this.event=W;else if(w==="data")this.data.push(W);return null}}function AO($,w){let G=$.indexOf(w);if(G!==-1)return[$.substring(0,G),w,$.substring(G+w.length)];return[$,"",""]}async function l6($,w){let{response:G,requestLogID:W,retryOfRequestLogID:Y,startTime:Z}=w,X=await(async()=>{if(w.options.stream){if(W0($).debug("response",G.status,G.url,G.headers,G.body),w.options.__streamClass)return w.options.__streamClass.fromSSEResponse(G,w.controller,$);return g0.fromSSEResponse(G,w.controller,$)}if(G.status===204)return null;if(w.options.__binaryResponse)return G;let T=G.headers.get("content-type")?.split(";")[0]?.trim();if(T?.includes("application/json")||T?.endsWith("+json")){let Q=await G.json();return aW(Q,G)}return await G.text()})();return W0($).debug(`[${W}] response parsed`,R1({retryOfRequestLogID:Y,url:G.url,status:G.status,body:X,durationMs:Date.now()-Z})),X}function aW($,w){if(!$||typeof $!=="object"||Array.isArray($))return $;return Object.defineProperty($,"_request_id",{value:w.headers.get("x-request-id"),enumerable:!1})}var H9;class D$ extends Promise{constructor($,w,G=l6){super((W)=>{W(null)});this.responsePromise=w,this.parseResponse=G,H9.set(this,void 0),C(this,H9,$,"f")}_thenUnwrap($){return new D$(B(this,H9,"f"),this.responsePromise,async(w,G)=>aW($(await this.parseResponse(w,G),G),G.response))}asResponse(){return this.responsePromise.then(($)=>$.response)}async withResponse(){let[$,w]=await Promise.all([this.parse(),this.asResponse()]);return{data:$,response:w,request_id:w.headers.get("x-request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then(($)=>this.parseResponse(B(this,H9,"f"),$));return this.parsedPromise}then($,w){return this.parse().then($,w)}catch($){return this.parse().catch($)}finally($){return this.parse().finally($)}}H9=new WeakMap;var c6;class d6{constructor($,w,G,W){c6.set(this,void 0),C(this,c6,$,"f"),this.options=W,this.response=w,this.body=G}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageRequestOptions()!=null}async getNextPage(){let $=this.nextPageRequestOptions();if(!$)throw new k("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await B(this,c6,"f").requestAPIList(this.constructor,$)}async*iterPages(){let $=this;yield $;while($.hasNextPage())$=await $.getNextPage(),yield $}async*[(c6=new WeakMap,Symbol.asyncIterator)](){for await(let $ of this.iterPages())for(let w of $.getPaginatedItems())yield w}}class n6 extends D${constructor($,w,G){super($,w,async(W,Y)=>new G(W,Y.response,await l6(W,Y),Y.options))}async*[Symbol.asyncIterator](){let $=await this;for await(let w of $)yield w}}class j1 extends d6{constructor($,w,G,W){super($,w,G,W);this.data=G.data||[],this.object=G.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class h extends d6{constructor($,w,G,W){super($,w,G,W);this.data=G.data||[],this.has_more=G.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let $=this.getPaginatedItems(),w=$[$.length-1]?.id;if(!w)return null;return{...this.options,query:{...hW(this.options.query),after:w}}}}class oW extends d6{constructor($,w,G,W){super($,w,G,W);this.data=G.data||[],this.has_more=G.has_more||!1,this.last_id=G.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let $=this.last_id;if(!$)return null;return{...this.options,query:{...hW(this.options.query),after:$}}}}var $3=()=>{if(typeof File>"u"){let{process:$}=globalThis,w=typeof $?.versions?.node==="string"&&parseInt($.versions.node.split("."))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(w?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Ew($,w,G){return $3(),new File($,w??"unknown_file",G)}function F9($){return(typeof $==="object"&&$!==null&&(("name"in $)&&$.name&&String($.name)||("url"in $)&&$.url&&String($.url)||("filename"in $)&&$.filename&&String($.filename)||("path"in $)&&$.path&&String($.path))||"").split(/[\\/]/).pop()||void 0}var w3=($)=>$!=null&&typeof $==="object"&&typeof $[Symbol.asyncIterator]==="function";var v0=async($,w)=>{return{...$,body:await jO($.body,w)}},oM=new WeakMap;function RO($){let w=typeof $==="function"?$:$.fetch,G=oM.get(w);if(G)return G;let W=(async()=>{try{let Y="Response"in w?w.Response:(await w("data:,")).constructor,Z=new FormData;if(Z.toString()===await new Y(Z).text())return!1;return!0}catch{return!0}})();return oM.set(w,W),W}var jO=async($,w)=>{if(!await RO(w))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let G=new FormData;return await Promise.all(Object.entries($||{}).map(([W,Y])=>eW(G,W,Y))),G},CO=($)=>$ instanceof Blob&&("name"in $);var eW=async($,w,G)=>{if(G===void 0)return;if(G==null)throw TypeError(`Received null for "${w}"; to pass null in FormData, you must use the string 'null'`);if(typeof G==="string"||typeof G==="number"||typeof G==="boolean")$.append(w,String(G));else if(G instanceof Response)$.append(w,Ew([await G.blob()],F9(G)));else if(w3(G))$.append(w,Ew([await new Response(g6(G)).blob()],F9(G)));else if(CO(G))$.append(w,G,F9(G));else if(Array.isArray(G))await Promise.all(G.map((W)=>eW($,w+"[]",W)));else if(typeof G==="object")await Promise.all(Object.entries(G).map(([W,Y])=>eW($,`${w}[${W}]`,Y)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${G} instead`)};var eM=($)=>$!=null&&typeof $==="object"&&typeof $.size==="number"&&typeof $.type==="string"&&typeof $.text==="function"&&typeof $.slice==="function"&&typeof $.arrayBuffer==="function",yO=($)=>$!=null&&typeof $==="object"&&typeof $.name==="string"&&typeof $.lastModified==="number"&&eM($),IO=($)=>$!=null&&typeof $==="object"&&typeof $.url==="string"&&typeof $.blob==="function";async function p6($,w,G){if($3(),$=await $,yO($)){if($ instanceof File)return $;return Ew([await $.arrayBuffer()],$.name)}if(IO($)){let Y=await $.blob();return w||(w=new URL($.url).pathname.split(/[\\/]/).pop()),Ew(await G3(Y),w,G)}let W=await G3($);if(w||(w=F9($)),!G?.type){let Y=W.find((Z)=>typeof Z==="object"&&("type"in Z)&&Z.type);if(typeof Y==="string")G={...G,type:Y}}return Ew(W,w,G)}async function G3($){let w=[];if(typeof $==="string"||ArrayBuffer.isView($)||$ instanceof ArrayBuffer)w.push($);else if(eM($))w.push($ instanceof Blob?$:await $.arrayBuffer());else if(w3($))for await(let G of $)w.push(...await G3(G));else{let G=$?.constructor?.name;throw Error(`Unexpected data type: ${typeof $}${G?`; constructor: ${G}`:""}${bO($)}`)}return w}function bO($){if(typeof $!=="object"||$===null)return"";return`; props: [${Object.getOwnPropertyNames($).map((G)=>`"${G}"`).join(", ")}]`}class F{constructor($){this._client=$}}function wf($){return $.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var $f=Object.freeze(Object.create(null)),_O=($=wf)=>function(G,...W){if(G.length===1)return G[0];let Y=!1,Z=[],X=G.reduce((f,Q,N)=>{if(/[?#]/.test(Q))Y=!0;let z=W[N],K=(Y?encodeURIComponent:$)(""+z);if(N!==W.length&&(z==null||typeof z==="object"&&z.toString===Object.getPrototypeOf(Object.getPrototypeOf(z.hasOwnProperty??$f)??$f)?.toString))K=z+"",Z.push({start:f.length+Q.length,length:K.length,error:`Value of type ${Object.prototype.toString.call(z).slice(8,-1)} is not a valid path parameter`});return f+Q+(N===W.length?"":K)},""),J=X.split(/[?#]/,1)[0],T=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,M;while((M=T.exec(J))!==null)Z.push({start:M.index,length:M[0].length,error:`Value "${M[0]}" can't be safely passed as a path parameter`});if(Z.sort((f,Q)=>f.start-Q.start),Z.length>0){let f=0,Q=Z.reduce((N,z)=>{let K=" ".repeat(z.start-f),P="^".repeat(z.length);return f=z.start+z.length,N+K+P},"");throw new k(`Path parameters result in path with invalid segments:
179
- ${Z.map((N)=>N.error).join(`
314
+ `),G=[];for(let Z of $){if(Z.role==="system")continue;if(Z.role==="user")G.push({role:"user",content:Z.content});else if(Z.role==="assistant")G.push({role:"assistant",content:[...Z.content?[{type:"text",text:Z.content}]:[],...Z.toolCalls.map((X)=>({type:"tool_use",id:X.callId,name:X.name,input:X.input}))]});else{let X={type:"tool_result",tool_use_id:Z.callId,content:Z.content,is_error:Z.isError},Y=G.at(-1);if(Y?.role==="user"&&Array.isArray(Y.content))Y.content=[...Y.content,X];else G.push({role:"user",content:[X]})}}return{system:w,messages:G}}function k($,w,G,Z,X){if(Z==="m")throw TypeError("Private method is not writable");if(Z==="a"&&!X)throw TypeError("Private accessor was defined without a setter");if(typeof w==="function"?$!==w||!X:!w.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return Z==="a"?X.call($,G):X?X.value=G:w.set($,G),G}function H($,w,G,Z){if(G==="a"&&!Z)throw TypeError("Private accessor was defined without a getter");if(typeof w==="function"?$!==w||!Z:!w.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return G==="m"?Z:G==="a"?Z.call($):Z?Z.value:w.get($)}var wY=function(){let{crypto:$}=globalThis;if($?.randomUUID)return wY=$.randomUUID.bind($),$.randomUUID();let w=new Uint8Array(1),G=$?()=>$.getRandomValues(w)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(Z)=>(+Z^G()&15>>+Z/4).toString(16))};function O8($){return typeof $==="object"&&$!==null&&(("name"in $)&&$.name==="AbortError"||("message"in $)&&String($.message).includes("FetchRequestCanceledException"))}var f8=($)=>{if($ instanceof Error)return $;if(typeof $==="object"&&$!==null){try{if(Object.prototype.toString.call($)==="[object Error]"){let w=Error($.message,$.cause?{cause:$.cause}:{});if($.stack)w.stack=$.stack;if($.cause&&!w.cause)w.cause=$.cause;if($.name)w.name=$.name;return w}}catch{}try{return Error(JSON.stringify($))}catch{}}return Error($)};class j extends Error{}class Q0 extends j{constructor($,w,G,Z){super(`${Q0.makeMessage($,w,G)}`);this.status=$,this.headers=Z,this.requestID=Z?.get("x-request-id"),this.error=w;let X=w;this.code=X?.code,this.param=X?.param,this.type=X?.type}static makeMessage($,w,G){let Z=w?.message?typeof w.message==="string"?w.message:JSON.stringify(w.message):w?JSON.stringify(w):G;if($&&Z)return`${$} ${Z}`;if($)return`${$} status code (no body)`;if(Z)return Z;return"(no status code or body)"}static generate($,w,G,Z){if(!$||!Z)return new ww({message:G,cause:f8(w)});let X=w?.error;if($===400)return new L8($,X,G,Z);if($===401)return new D8($,X,G,Z);if($===403)return new E8($,X,G,Z);if($===404)return new A8($,X,G,Z);if($===409)return new R8($,X,G,Z);if($===422)return new S8($,X,G,Z);if($===429)return new I8($,X,G,Z);if($>=500)return new j8($,X,G,Z);return new Q0($,X,G,Z)}}class q0 extends Q0{constructor({message:$}={}){super(void 0,void 0,$||"Request was aborted.",void 0)}}class ww extends Q0{constructor({message:$,cause:w}){super(void 0,void 0,$||"Connection error.",void 0);if(w)this.cause=w}}class Gw extends ww{constructor({message:$}={}){super({message:$??"Request timed out."})}}class L8 extends Q0{}class D8 extends Q0{}class E8 extends Q0{}class A8 extends Q0{}class R8 extends Q0{}class S8 extends Q0{}class I8 extends Q0{}class j8 extends Q0{}class C8 extends j{constructor(){super("Could not parse response content as the length limit was reached")}}class b8 extends j{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class i$ extends Error{constructor($){super($)}}var wg=/^[a-z][a-z0-9+.-]*:/i,JN=($)=>{return wg.test($)},E0=($)=>(E0=Array.isArray,E0($)),GY=E0;function ZY($){if(typeof $!=="object")return{};return $??{}}function WN($){if(!$)return!0;for(let w in $)return!1;return!0}function TN($,w){return Object.prototype.hasOwnProperty.call($,w)}function k8($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var QN=($,w)=>{if(typeof w!=="number"||!Number.isInteger(w))throw new j(`${$} must be an integer`);if(w<0)throw new j(`${$} must be a positive integer`);return w};var zN=($)=>{try{return JSON.parse($)}catch(w){return}};var F$=($)=>new Promise((w)=>setTimeout(w,$));var U1="5.23.2";var BN=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"};function Gg(){if(typeof Deno<"u"&&Deno.build!=null)return"deno";if(typeof EdgeRuntime<"u")return"edge";if(Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]")return"node";return"unknown"}var Zg=()=>{let $=Gg();if($==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":U1,"X-Stainless-OS":PN(Deno.build.os),"X-Stainless-Arch":MN(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version==="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":U1,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if($==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":U1,"X-Stainless-OS":PN(globalThis.process.platform??"unknown"),"X-Stainless-Arch":MN(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let w=Xg();if(w)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":U1,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${w.browser}`,"X-Stainless-Runtime-Version":w.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":U1,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Xg(){if(typeof navigator>"u"||!navigator)return null;let $=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:w,pattern:G}of $){let Z=G.exec(navigator.userAgent);if(Z){let X=Z[1]||0,Y=Z[2]||0,J=Z[3]||0;return{browser:w,version:`${X}.${Y}.${J}`}}}return null}var MN=($)=>{if($==="x32")return"x32";if($==="x86_64"||$==="x64")return"x64";if($==="arm")return"arm";if($==="aarch64"||$==="arm64")return"arm64";if($)return`other:${$}`;return"unknown"},PN=($)=>{if($=$.toLowerCase(),$.includes("ios"))return"iOS";if($==="android")return"Android";if($==="darwin")return"MacOS";if($==="win32")return"Windows";if($==="freebsd")return"FreeBSD";if($==="openbsd")return"OpenBSD";if($==="linux")return"Linux";if($)return`Other:${$}`;return"Unknown"},qN,NN=()=>{return qN??(qN=Zg())};function VN(){if(typeof fetch<"u")return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function XY(...$){let w=globalThis.ReadableStream;if(typeof w>"u")throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new w(...$)}function vG($){let w=Symbol.asyncIterator in $?$[Symbol.asyncIterator]():$[Symbol.iterator]();return XY({start(){},async pull(G){let{done:Z,value:X}=await w.next();if(Z)G.close();else G.enqueue(X)},async cancel(){await w.return?.()}})}function YY($){if($[Symbol.asyncIterator])return $;let w=$.getReader();return{async next(){try{let G=await w.read();if(G?.done)w.releaseLock();return G}catch(G){throw w.releaseLock(),G}},async return(){let G=w.cancel();return w.releaseLock(),await G,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function KN($){if($===null||typeof $!=="object")return;if($[Symbol.asyncIterator]){await $[Symbol.asyncIterator]().return?.();return}let w=$.getReader(),G=w.cancel();w.releaseLock(),await G}var UN=({headers:$,body:w})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(w)}};var iG="RFC3986",JY=($)=>String($),mG={RFC1738:($)=>String($).replace(/%20/g,"+"),RFC3986:JY},WY="RFC1738";var lG=($,w)=>(lG=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),lG($,w)),O$=(()=>{let $=[];for(let w=0;w<256;++w)$.push("%"+((w<16?"0":"")+w.toString(16)).toUpperCase());return $})();var TY=1024,HN=($,w,G,Z,X)=>{if($.length===0)return $;let Y=$;if(typeof $==="symbol")Y=Symbol.prototype.toString.call($);else if(typeof $!=="string")Y=String($);if(G==="iso-8859-1")return escape(Y).replace(/%u[0-9a-f]{4}/gi,function(W){return"%26%23"+parseInt(W.slice(2),16)+"%3B"});let J="";for(let W=0;W<Y.length;W+=TY){let T=Y.length>=TY?Y.slice(W,W+TY):Y,Q=[];for(let z=0;z<T.length;++z){let M=T.charCodeAt(z);if(M===45||M===46||M===95||M===126||M>=48&&M<=57||M>=65&&M<=90||M>=97&&M<=122||X===WY&&(M===40||M===41)){Q[Q.length]=T.charAt(z);continue}if(M<128){Q[Q.length]=O$[M];continue}if(M<2048){Q[Q.length]=O$[192|M>>6]+O$[128|M&63];continue}if(M<55296||M>=57344){Q[Q.length]=O$[224|M>>12]+O$[128|M>>6&63]+O$[128|M&63];continue}z+=1,M=65536+((M&1023)<<10|T.charCodeAt(z)&1023),Q[Q.length]=O$[240|M>>18]+O$[128|M>>12&63]+O$[128|M>>6&63]+O$[128|M&63]}J+=Q.join("")}return J};function FN($){if(!$||typeof $!=="object")return!1;return!!($.constructor&&$.constructor.isBuffer&&$.constructor.isBuffer($))}function QY($,w){if(E0($)){let G=[];for(let Z=0;Z<$.length;Z+=1)G.push(w($[Z]));return G}return w($)}var fN={brackets($){return String($)+"[]"},comma:"comma",indices($,w){return String($)+"["+w+"]"},repeat($){return String($)}},LN=function($,w){Array.prototype.push.apply($,E0(w)?w:[w])},ON,B0={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:HN,encodeValuesOnly:!1,format:iG,formatter:JY,indices:!1,serializeDate($){return(ON??(ON=Function.prototype.call.bind(Date.prototype.toISOString)))($)},skipNulls:!1,strictNullHandling:!1};function Wg($){return typeof $==="string"||typeof $==="number"||typeof $==="boolean"||typeof $==="symbol"||typeof $==="bigint"}var zY={};function DN($,w,G,Z,X,Y,J,W,T,Q,z,M,P,q,N,B,V,K){let U=$,O=K,D=0,f=!1;while((O=O.get(zY))!==void 0&&!f){let g=O.get($);if(D+=1,typeof g<"u")if(g===D)throw RangeError("Cyclic object value");else f=!0;if(typeof O.get(zY)>"u")D=0}if(typeof Q==="function")U=Q(w,U);else if(U instanceof Date)U=P?.(U);else if(G==="comma"&&E0(U))U=QY(U,function(g){if(g instanceof Date)return P?.(g);return g});if(U===null){if(Y)return T&&!B?T(w,B0.encoder,V,"key",q):w;U=""}if(Wg(U)||FN(U)){if(T){let g=B?w:T(w,B0.encoder,V,"key",q);return[N?.(g)+"="+N?.(T(U,B0.encoder,V,"value",q))]}return[N?.(w)+"="+N?.(String(U))]}let L=[];if(typeof U>"u")return L;let C;if(G==="comma"&&E0(U)){if(B&&T)U=QY(U,T);C=[{value:U.length>0?U.join(",")||null:void 0}]}else if(E0(Q))C=Q;else{let g=Object.keys(U);C=z?g.sort(z):g}let S=W?String(w).replace(/\./g,"%2E"):String(w),h=Z&&E0(U)&&U.length===1?S+"[]":S;if(X&&E0(U)&&U.length===0)return h+"[]";for(let g=0;g<C.length;++g){let G0=C[g],e=typeof G0==="object"&&typeof G0.value<"u"?G0.value:U[G0];if(J&&e===null)continue;let c0=M&&W?G0.replace(/\./g,"%2E"):G0,fw=E0(U)?typeof G==="function"?G(h,c0):h:h+(M?"."+c0:"["+c0+"]");K.set($,D);let Lw=new WeakMap;Lw.set(zY,K),LN(L,DN(e,fw,G,Z,X,Y,J,W,G==="comma"&&B&&E0(U)?null:T,Q,z,M,P,q,N,B,V,Lw))}return L}function Tg($=B0){if(typeof $.allowEmptyArrays<"u"&&typeof $.allowEmptyArrays!=="boolean")throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof $.encodeDotInKeys<"u"&&typeof $.encodeDotInKeys!=="boolean")throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if($.encoder!==null&&typeof $.encoder<"u"&&typeof $.encoder!=="function")throw TypeError("Encoder has to be a function.");let w=$.charset||B0.charset;if(typeof $.charset<"u"&&$.charset!=="utf-8"&&$.charset!=="iso-8859-1")throw TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let G=iG;if(typeof $.format<"u"){if(!lG(mG,$.format))throw TypeError("Unknown format option provided.");G=$.format}let Z=mG[G],X=B0.filter;if(typeof $.filter==="function"||E0($.filter))X=$.filter;let Y;if($.arrayFormat&&$.arrayFormat in fN)Y=$.arrayFormat;else if("indices"in $)Y=$.indices?"indices":"repeat";else Y=B0.arrayFormat;if("commaRoundTrip"in $&&typeof $.commaRoundTrip!=="boolean")throw TypeError("`commaRoundTrip` must be a boolean, or absent");let J=typeof $.allowDots>"u"?!!$.encodeDotInKeys===!0?!0:B0.allowDots:!!$.allowDots;return{addQueryPrefix:typeof $.addQueryPrefix==="boolean"?$.addQueryPrefix:B0.addQueryPrefix,allowDots:J,allowEmptyArrays:typeof $.allowEmptyArrays==="boolean"?!!$.allowEmptyArrays:B0.allowEmptyArrays,arrayFormat:Y,charset:w,charsetSentinel:typeof $.charsetSentinel==="boolean"?$.charsetSentinel:B0.charsetSentinel,commaRoundTrip:!!$.commaRoundTrip,delimiter:typeof $.delimiter>"u"?B0.delimiter:$.delimiter,encode:typeof $.encode==="boolean"?$.encode:B0.encode,encodeDotInKeys:typeof $.encodeDotInKeys==="boolean"?$.encodeDotInKeys:B0.encodeDotInKeys,encoder:typeof $.encoder==="function"?$.encoder:B0.encoder,encodeValuesOnly:typeof $.encodeValuesOnly==="boolean"?$.encodeValuesOnly:B0.encodeValuesOnly,filter:X,format:G,formatter:Z,serializeDate:typeof $.serializeDate==="function"?$.serializeDate:B0.serializeDate,skipNulls:typeof $.skipNulls==="boolean"?$.skipNulls:B0.skipNulls,sort:typeof $.sort==="function"?$.sort:null,strictNullHandling:typeof $.strictNullHandling==="boolean"?$.strictNullHandling:B0.strictNullHandling}}function MY($,w={}){let G=$,Z=Tg(w),X,Y;if(typeof Z.filter==="function")Y=Z.filter,G=Y("",G);else if(E0(Z.filter))Y=Z.filter,X=Y;let J=[];if(typeof G!=="object"||G===null)return"";let W=fN[Z.arrayFormat],T=W==="comma"&&Z.commaRoundTrip;if(!X)X=Object.keys(G);if(Z.sort)X.sort(Z.sort);let Q=new WeakMap;for(let P=0;P<X.length;++P){let q=X[P];if(Z.skipNulls&&G[q]===null)continue;LN(J,DN(G[q],q,W,T,Z.allowEmptyArrays,Z.strictNullHandling,Z.skipNulls,Z.encodeDotInKeys,Z.encode?Z.encoder:null,Z.filter,Z.sort,Z.allowDots,Z.serializeDate,Z.format,Z.formatter,Z.encodeValuesOnly,Z.charset,Q))}let z=J.join(Z.delimiter),M=Z.addQueryPrefix===!0?"?":"";if(Z.charsetSentinel)if(Z.charset==="iso-8859-1")M+="utf8=%26%2310003%3B&";else M+="utf8=%E2%9C%93&";return z.length>0?M+z:""}function RN($){let w=0;for(let X of $)w+=X.length;let G=new Uint8Array(w),Z=0;for(let X of $)G.set(X,Z),Z+=X.length;return G}var EN;function T4($){let w;return(EN??(w=new globalThis.TextEncoder,EN=w.encode.bind(w)))($)}var AN;function PY($){let w;return(AN??(w=new globalThis.TextDecoder,AN=w.decode.bind(w)))($)}var h0,v0;class Q4{constructor(){h0.set(this,void 0),v0.set(this,void 0),k(this,h0,new Uint8Array,"f"),k(this,v0,null,"f")}decode($){if($==null)return[];let w=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?T4($):$;k(this,h0,RN([H(this,h0,"f"),w]),"f");let G=[],Z;while((Z=zg(H(this,h0,"f"),H(this,v0,"f")))!=null){if(Z.carriage&&H(this,v0,"f")==null){k(this,v0,Z.index,"f");continue}if(H(this,v0,"f")!=null&&(Z.index!==H(this,v0,"f")+1||Z.carriage)){G.push(PY(H(this,h0,"f").subarray(0,H(this,v0,"f")-1))),k(this,h0,H(this,h0,"f").subarray(H(this,v0,"f")),"f"),k(this,v0,null,"f");continue}let X=H(this,v0,"f")!==null?Z.preceding-1:Z.preceding,Y=PY(H(this,h0,"f").subarray(0,X));G.push(Y),k(this,h0,H(this,h0,"f").subarray(Z.index),"f"),k(this,v0,null,"f")}return G}flush(){if(!H(this,h0,"f").length)return[];return this.decode(`
315
+ `)}}h0=new WeakMap,v0=new WeakMap;Q4.NEWLINE_CHARS=new Set([`
316
+ `,"\r"]);Q4.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function zg($,w){for(let X=w??0;X<$.length;X++){if($[X]===10)return{preceding:X,index:X+1,carriage:!1};if($[X]===13)return{preceding:X,index:X+1,carriage:!0}}return null}function SN($){for(let Z=0;Z<$.length-1;Z++){if($[Z]===10&&$[Z+1]===10)return Z+2;if($[Z]===13&&$[Z+1]===13)return Z+2;if($[Z]===13&&$[Z+1]===10&&Z+3<$.length&&$[Z+2]===13&&$[Z+3]===10)return Z+4}return-1}var cG={off:0,error:200,warn:300,info:400,debug:500},qY=($,w,G)=>{if(!$)return;if(TN(cG,$))return $;J0(G).warn(`${w} was set to ${JSON.stringify($)}, expected one of ${JSON.stringify(Object.keys(cG))}`);return};function y8(){}function dG($,w,G){if(!w||cG[$]>cG[G])return y8;else return w[$].bind(w)}var Mg={error:y8,warn:y8,info:y8,debug:y8},IN=new WeakMap;function J0($){let w=$.logger,G=$.logLevel??"off";if(!w)return Mg;let Z=IN.get(w);if(Z&&Z[0]===G)return Z[1];let X={error:dG("error",w,G),warn:dG("warn",w,G),info:dG("info",w,G),debug:dG("debug",w,G)};return IN.set(w,[G,X]),X}var m$=($)=>{if($.options)$.options={...$.options},delete $.options.headers;if($.headers)$.headers=Object.fromEntries(($.headers instanceof Headers?[...$.headers]:Object.entries($.headers)).map(([w,G])=>[w,w.toLowerCase()==="authorization"||w.toLowerCase()==="cookie"||w.toLowerCase()==="set-cookie"?"***":G]));if("retryOfRequestLogID"in $){if($.retryOfRequestLogID)$.retryOf=$.retryOfRequestLogID;delete $.retryOfRequestLogID}return $};var _8;class i0{constructor($,w,G){this.iterator=$,_8.set(this,void 0),this.controller=w,k(this,_8,G,"f")}static fromSSEResponse($,w,G){let Z=!1,X=G?J0(G):console;async function*Y(){if(Z)throw new j("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");Z=!0;let J=!1;try{for await(let W of Pg($,w)){if(J)continue;if(W.data.startsWith("[DONE]")){J=!0;continue}if(W.event===null||!W.event.startsWith("thread.")){let T;try{T=JSON.parse(W.data)}catch(Q){throw X.error("Could not parse message into JSON:",W.data),X.error("From chunk:",W.raw),Q}if(T&&T.error)throw new Q0(void 0,T.error,void 0,$.headers);yield T}else{let T;try{T=JSON.parse(W.data)}catch(Q){throw console.error("Could not parse message into JSON:",W.data),console.error("From chunk:",W.raw),Q}if(W.event=="error")throw new Q0(void 0,T.error,T.message,void 0);yield{event:W.event,data:T}}}J=!0}catch(W){if(O8(W))return;throw W}finally{if(!J)w.abort()}}return new i0(Y,w,G)}static fromReadableStream($,w,G){let Z=!1;async function*X(){let J=new Q4,W=YY($);for await(let T of W)for(let Q of J.decode(T))yield Q;for(let T of J.flush())yield T}async function*Y(){if(Z)throw new j("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");Z=!0;let J=!1;try{for await(let W of X()){if(J)continue;if(W)yield JSON.parse(W)}J=!0}catch(W){if(O8(W))return;throw W}finally{if(!J)w.abort()}}return new i0(Y,w,G)}[(_8=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let $=[],w=[],G=this.iterator(),Z=(X)=>{return{next:()=>{if(X.length===0){let Y=G.next();$.push(Y),w.push(Y)}return X.shift()}}};return[new i0(()=>Z($),this.controller,H(this,_8,"f")),new i0(()=>Z(w),this.controller,H(this,_8,"f"))]}toReadableStream(){let $=this,w;return XY({async start(){w=$[Symbol.asyncIterator]()},async pull(G){try{let{value:Z,done:X}=await w.next();if(X)return G.close();let Y=T4(JSON.stringify(Z)+`
317
+ `);G.enqueue(Y)}catch(Z){G.error(Z)}},async cancel(){await w.return?.()}})}}async function*Pg($,w){if(!$.body){if(w.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new j("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new j("Attempted to iterate over a response with no body")}let G=new jN,Z=new Q4,X=YY($.body);for await(let Y of qg(X))for(let J of Z.decode(Y)){let W=G.decode(J);if(W)yield W}for(let Y of Z.flush()){let J=G.decode(Y);if(J)yield J}}async function*qg($){let w=new Uint8Array;for await(let G of $){if(G==null)continue;let Z=G instanceof ArrayBuffer?new Uint8Array(G):typeof G==="string"?T4(G):G,X=new Uint8Array(w.length+Z.length);X.set(w),X.set(Z,w.length),w=X;let Y;while((Y=SN(w))!==-1)yield w.slice(0,Y),w=w.slice(Y)}if(w.length>0)yield w}class jN{constructor(){this.event=null,this.data=[],this.chunks=[]}decode($){if($.endsWith("\r"))$=$.substring(0,$.length-1);if(!$){if(!this.event&&!this.data.length)return null;let X={event:this.event,data:this.data.join(`
318
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],X}if(this.chunks.push($),$.startsWith(":"))return null;let[w,G,Z]=Bg($,":");if(Z.startsWith(" "))Z=Z.substring(1);if(w==="event")this.event=Z;else if(w==="data")this.data.push(Z);return null}}function Bg($,w){let G=$.indexOf(w);if(G!==-1)return[$.substring(0,G),w,$.substring(G+w.length)];return[$,"",""]}async function pG($,w){let{response:G,requestLogID:Z,retryOfRequestLogID:X,startTime:Y}=w,J=await(async()=>{if(w.options.stream){if(J0($).debug("response",G.status,G.url,G.headers,G.body),w.options.__streamClass)return w.options.__streamClass.fromSSEResponse(G,w.controller,$);return i0.fromSSEResponse(G,w.controller,$)}if(G.status===204)return null;if(w.options.__binaryResponse)return G;let T=G.headers.get("content-type")?.split(";")[0]?.trim();if(T?.includes("application/json")||T?.endsWith("+json")){let M=await G.json();return BY(M,G)}return await G.text()})();return J0($).debug(`[${Z}] response parsed`,m$({retryOfRequestLogID:X,url:G.url,status:G.status,body:J,durationMs:Date.now()-Y})),J}function BY($,w){if(!$||typeof $!=="object"||Array.isArray($))return $;return Object.defineProperty($,"_request_id",{value:w.headers.get("x-request-id"),enumerable:!1})}var x8;class Zw extends Promise{constructor($,w,G=pG){super((Z)=>{Z(null)});this.responsePromise=w,this.parseResponse=G,x8.set(this,void 0),k(this,x8,$,"f")}_thenUnwrap($){return new Zw(H(this,x8,"f"),this.responsePromise,async(w,G)=>BY($(await this.parseResponse(w,G),G),G.response))}asResponse(){return this.responsePromise.then(($)=>$.response)}async withResponse(){let[$,w]=await Promise.all([this.parse(),this.asResponse()]);return{data:$,response:w,request_id:w.headers.get("x-request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then(($)=>this.parseResponse(H(this,x8,"f"),$));return this.parsedPromise}then($,w){return this.parse().then($,w)}catch($){return this.parse().catch($)}finally($){return this.parse().finally($)}}x8=new WeakMap;var nG;class rG{constructor($,w,G,Z){nG.set(this,void 0),k(this,nG,$,"f"),this.options=Z,this.response=w,this.body=G}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageRequestOptions()!=null}async getNextPage(){let $=this.nextPageRequestOptions();if(!$)throw new j("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await H(this,nG,"f").requestAPIList(this.constructor,$)}async*iterPages(){let $=this;yield $;while($.hasNextPage())$=await $.getNextPage(),yield $}async*[(nG=new WeakMap,Symbol.asyncIterator)](){for await(let $ of this.iterPages())for(let w of $.getPaginatedItems())yield w}}class sG extends Zw{constructor($,w,G){super($,w,async(Z,X)=>new G(Z,X.response,await pG(Z,X),X.options))}async*[Symbol.asyncIterator](){let $=await this;for await(let w of $)yield w}}class l$ extends rG{constructor($,w,G,Z){super($,w,G,Z);this.data=G.data||[],this.object=G.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class m extends rG{constructor($,w,G,Z){super($,w,G,Z);this.data=G.data||[],this.has_more=G.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let $=this.getPaginatedItems(),w=$[$.length-1]?.id;if(!w)return null;return{...this.options,query:{...ZY(this.options.query),after:w}}}}class NY extends rG{constructor($,w,G,Z){super($,w,G,Z);this.data=G.data||[],this.has_more=G.has_more||!1,this.last_id=G.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let $=this.last_id;if(!$)return null;return{...this.options,query:{...ZY(this.options.query),after:$}}}}var KY=()=>{if(typeof File>"u"){let{process:$}=globalThis,w=typeof $?.versions?.node==="string"&&parseInt($.versions.node.split("."))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(w?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function z4($,w,G){return KY(),new File($,w??"unknown_file",G)}function g8($){return(typeof $==="object"&&$!==null&&(("name"in $)&&$.name&&String($.name)||("url"in $)&&$.url&&String($.url)||("filename"in $)&&$.filename&&String($.filename)||("path"in $)&&$.path&&String($.path))||"").split(/[\\/]/).pop()||void 0}var UY=($)=>$!=null&&typeof $==="object"&&typeof $[Symbol.asyncIterator]==="function";var m0=async($,w)=>{return{...$,body:await Kg($.body,w)}},CN=new WeakMap;function Vg($){let w=typeof $==="function"?$:$.fetch,G=CN.get(w);if(G)return G;let Z=(async()=>{try{let X="Response"in w?w.Response:(await w("data:,")).constructor,Y=new FormData;if(Y.toString()===await new X(Y).text())return!1;return!0}catch{return!0}})();return CN.set(w,Z),Z}var Kg=async($,w)=>{if(!await Vg(w))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let G=new FormData;return await Promise.all(Object.entries($||{}).map(([Z,X])=>VY(G,Z,X))),G},Ug=($)=>$ instanceof Blob&&("name"in $);var VY=async($,w,G)=>{if(G===void 0)return;if(G==null)throw TypeError(`Received null for "${w}"; to pass null in FormData, you must use the string 'null'`);if(typeof G==="string"||typeof G==="number"||typeof G==="boolean")$.append(w,String(G));else if(G instanceof Response)$.append(w,z4([await G.blob()],g8(G)));else if(UY(G))$.append(w,z4([await new Response(vG(G)).blob()],g8(G)));else if(Ug(G))$.append(w,G,g8(G));else if(Array.isArray(G))await Promise.all(G.map((Z)=>VY($,w+"[]",Z)));else if(typeof G==="object")await Promise.all(Object.entries(G).map(([Z,X])=>VY($,`${w}[${Z}]`,X)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${G} instead`)};var bN=($)=>$!=null&&typeof $==="object"&&typeof $.size==="number"&&typeof $.type==="string"&&typeof $.text==="function"&&typeof $.slice==="function"&&typeof $.arrayBuffer==="function",Hg=($)=>$!=null&&typeof $==="object"&&typeof $.name==="string"&&typeof $.lastModified==="number"&&bN($),Fg=($)=>$!=null&&typeof $==="object"&&typeof $.url==="string"&&typeof $.blob==="function";async function aG($,w,G){if(KY(),$=await $,Hg($)){if($ instanceof File)return $;return z4([await $.arrayBuffer()],$.name)}if(Fg($)){let X=await $.blob();return w||(w=new URL($.url).pathname.split(/[\\/]/).pop()),z4(await HY(X),w,G)}let Z=await HY($);if(w||(w=g8($)),!G?.type){let X=Z.find((Y)=>typeof Y==="object"&&("type"in Y)&&Y.type);if(typeof X==="string")G={...G,type:X}}return z4(Z,w,G)}async function HY($){let w=[];if(typeof $==="string"||ArrayBuffer.isView($)||$ instanceof ArrayBuffer)w.push($);else if(bN($))w.push($ instanceof Blob?$:await $.arrayBuffer());else if(UY($))for await(let G of $)w.push(...await HY(G));else{let G=$?.constructor?.name;throw Error(`Unexpected data type: ${typeof $}${G?`; constructor: ${G}`:""}${Og($)}`)}return w}function Og($){if(typeof $!=="object"||$===null)return"";return`; props: [${Object.getOwnPropertyNames($).map((G)=>`"${G}"`).join(", ")}]`}class R{constructor($){this._client=$}}function yN($){return $.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var kN=Object.freeze(Object.create(null)),Lg=($=yN)=>function(G,...Z){if(G.length===1)return G[0];let X=!1,Y=[],J=G.reduce((z,M,P)=>{if(/[?#]/.test(M))X=!0;let q=Z[P],N=(X?encodeURIComponent:$)(""+q);if(P!==Z.length&&(q==null||typeof q==="object"&&q.toString===Object.getPrototypeOf(Object.getPrototypeOf(q.hasOwnProperty??kN)??kN)?.toString))N=q+"",Y.push({start:z.length+M.length,length:N.length,error:`Value of type ${Object.prototype.toString.call(q).slice(8,-1)} is not a valid path parameter`});return z+M+(P===Z.length?"":N)},""),W=J.split(/[?#]/,1)[0],T=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,Q;while((Q=T.exec(W))!==null)Y.push({start:Q.index,length:Q[0].length,error:`Value "${Q[0]}" can't be safely passed as a path parameter`});if(Y.sort((z,M)=>z.start-M.start),Y.length>0){let z=0,M=Y.reduce((P,q)=>{let N=" ".repeat(q.start-z),B="^".repeat(q.length);return z=q.start+q.length,P+N+B},"");throw new j(`Path parameters result in path with invalid segments:
319
+ ${Y.map((P)=>P.error).join(`
180
320
  `)}
181
- ${X}
182
- ${Q}`)}return X},U=_O(wf);class Uw extends F{list($,w={},G){return this._client.getAPIList(U`/chat/completions/${$}/messages`,h,{query:w,...G})}}function O9($){return $!==void 0&&"function"in $&&$.function!==void 0}function L9($){return $?.$brand==="auto-parseable-response-format"}function k$($){return $?.$brand==="auto-parseable-tool"}function Gf($,w){if(!w||!W3(w))return{...$,choices:$.choices.map((G)=>{return Yf(G.message.tool_calls),{...G,message:{...G.message,parsed:null,...G.message.tool_calls?{tool_calls:G.message.tool_calls}:void 0}}})};return D9($,w)}function D9($,w){let G=$.choices.map((W)=>{if(W.finish_reason==="length")throw new B9;if(W.finish_reason==="content_filter")throw new V9;return Yf(W.message.tool_calls),{...W,message:{...W.message,...W.message.tool_calls?{tool_calls:W.message.tool_calls?.map((Y)=>hO(w,Y))??void 0}:void 0,parsed:W.message.content&&!W.message.refusal?uO(w,W.message.content):null}}});return{...$,choices:G}}function uO($,w){if($.response_format?.type!=="json_schema")return null;if($.response_format?.type==="json_schema"){if("$parseRaw"in $.response_format)return $.response_format.$parseRaw(w);return JSON.parse(w)}return null}function hO($,w){let G=$.tools?.find((W)=>O9(W)&&W.function?.name===w.function.name);return{...w,function:{...w.function,parsed_arguments:k$(G)?G.$parseRaw(w.function.arguments):G?.function.strict?JSON.parse(w.function.arguments):null}}}function Wf($,w){if(!$||!("tools"in $)||!$.tools)return!1;let G=$.tools?.find((W)=>O9(W)&&W.function?.name===w.function.name);return O9(G)&&(k$(G)||G?.function.strict||!1)}function W3($){if(L9($.response_format))return!0;return $.tools?.some((w)=>k$(w)||w.type==="function"&&w.function.strict===!0)??!1}function Yf($){for(let w of $||[])if(w.type!=="function")throw new k(`Currently only \`function\` tool calls are supported; Received \`${w.type}\``)}function Zf($){for(let w of $??[]){if(w.type!=="function")throw new k(`Currently only \`function\` tool types support auto-parsing; Received \`${w.type}\``);if(w.function.strict!==!0)throw new k(`The \`${w.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var Hw=($)=>{return $?.role==="assistant"},Y3=($)=>{return $?.role==="tool"};var Z3,t6,r6,k9,A9,s6,S9,C1,R9,a6,o6,Fw,Xf;class A${constructor(){Z3.add(this),this.controller=new AbortController,t6.set(this,void 0),r6.set(this,()=>{}),k9.set(this,()=>{}),A9.set(this,void 0),s6.set(this,()=>{}),S9.set(this,()=>{}),C1.set(this,{}),R9.set(this,!1),a6.set(this,!1),o6.set(this,!1),Fw.set(this,!1),C(this,t6,new Promise(($,w)=>{C(this,r6,$,"f"),C(this,k9,w,"f")}),"f"),C(this,A9,new Promise(($,w)=>{C(this,s6,$,"f"),C(this,S9,w,"f")}),"f"),B(this,t6,"f").catch(()=>{}),B(this,A9,"f").catch(()=>{})}_run($){setTimeout(()=>{$().then(()=>{this._emitFinal(),this._emit("end")},B(this,Z3,"m",Xf).bind(this))},0)}_connected(){if(this.ended)return;B(this,r6,"f").call(this),this._emit("connect")}get ended(){return B(this,R9,"f")}get errored(){return B(this,a6,"f")}get aborted(){return B(this,o6,"f")}abort(){this.controller.abort()}on($,w){return(B(this,C1,"f")[$]||(B(this,C1,"f")[$]=[])).push({listener:w}),this}off($,w){let G=B(this,C1,"f")[$];if(!G)return this;let W=G.findIndex((Y)=>Y.listener===w);if(W>=0)G.splice(W,1);return this}once($,w){return(B(this,C1,"f")[$]||(B(this,C1,"f")[$]=[])).push({listener:w,once:!0}),this}emitted($){return new Promise((w,G)=>{if(C(this,Fw,!0,"f"),$!=="error")this.once("error",G);this.once($,w)})}async done(){C(this,Fw,!0,"f"),await B(this,A9,"f")}_emit($,...w){if(B(this,R9,"f"))return;if($==="end")C(this,R9,!0,"f"),B(this,s6,"f").call(this);let G=B(this,C1,"f")[$];if(G)B(this,C1,"f")[$]=G.filter((W)=>!W.once),G.forEach(({listener:W})=>W(...w));if($==="abort"){let W=w[0];if(!B(this,Fw,"f")&&!G?.length)Promise.reject(W);B(this,k9,"f").call(this,W),B(this,S9,"f").call(this,W),this._emit("end");return}if($==="error"){let W=w[0];if(!B(this,Fw,"f")&&!G?.length)Promise.reject(W);B(this,k9,"f").call(this,W),B(this,S9,"f").call(this,W),this._emit("end")}}_emitFinal(){}}t6=new WeakMap,r6=new WeakMap,k9=new WeakMap,A9=new WeakMap,s6=new WeakMap,S9=new WeakMap,C1=new WeakMap,R9=new WeakMap,a6=new WeakMap,o6=new WeakMap,Fw=new WeakMap,Z3=new WeakSet,Xf=function(w){if(C(this,a6,!0,"f"),w instanceof Error&&w.name==="AbortError")w=new T0;if(w instanceof T0)return C(this,o6,!0,"f"),this._emit("abort",w);if(w instanceof k)return this._emit("error",w);if(w instanceof Error){let G=new k(w.message);return G.cause=w,this._emit("error",G)}return this._emit("error",new k(String(w)))};function Jf($){return typeof $.parse==="function"}var L0,X3,e6,J3,T3,M3,Tf,Mf,iO=10;class j9 extends A${constructor(){super(...arguments);L0.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion($){this._chatCompletions.push($),this._emit("chatCompletion",$);let w=$.choices[0]?.message;if(w)this._addMessage(w);return $}_addMessage($,w=!0){if(!("content"in $))$.content=null;if(this.messages.push($),w){if(this._emit("message",$),Y3($)&&$.content)this._emit("functionToolCallResult",$.content);else if(Hw($)&&$.tool_calls){for(let G of $.tool_calls)if(G.type==="function")this._emit("functionToolCall",G.function)}}}async finalChatCompletion(){await this.done();let $=this._chatCompletions[this._chatCompletions.length-1];if(!$)throw new k("stream ended without producing a ChatCompletion");return $}async finalContent(){return await this.done(),B(this,L0,"m",X3).call(this)}async finalMessage(){return await this.done(),B(this,L0,"m",e6).call(this)}async finalFunctionToolCall(){return await this.done(),B(this,L0,"m",J3).call(this)}async finalFunctionToolCallResult(){return await this.done(),B(this,L0,"m",T3).call(this)}async totalUsage(){return await this.done(),B(this,L0,"m",M3).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let $=this._chatCompletions[this._chatCompletions.length-1];if($)this._emit("finalChatCompletion",$);let w=B(this,L0,"m",e6).call(this);if(w)this._emit("finalMessage",w);let G=B(this,L0,"m",X3).call(this);if(G)this._emit("finalContent",G);let W=B(this,L0,"m",J3).call(this);if(W)this._emit("finalFunctionToolCall",W);let Y=B(this,L0,"m",T3).call(this);if(Y!=null)this._emit("finalFunctionToolCallResult",Y);if(this._chatCompletions.some((Z)=>Z.usage))this._emit("totalUsage",B(this,L0,"m",M3).call(this))}async _createChatCompletion($,w,G){let W=G?.signal;if(W){if(W.aborted)this.controller.abort();W.addEventListener("abort",()=>this.controller.abort())}B(this,L0,"m",Tf).call(this,w);let Y=await $.chat.completions.create({...w,stream:!1},{...G,signal:this.controller.signal});return this._connected(),this._addChatCompletion(D9(Y,w))}async _runChatCompletion($,w,G){for(let W of w.messages)this._addMessage(W,!1);return await this._createChatCompletion($,w,G)}async _runTools($,w,G){let{tool_choice:Y="auto",stream:Z,...X}=w,J=typeof Y!=="string"&&Y.type==="function"&&Y?.function?.name,{maxChatCompletions:T=iO}=G||{},M=w.tools.map((N)=>{if(k$(N)){if(!N.$callback)throw new k("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:N.$callback,name:N.function.name,description:N.function.description||"",parameters:N.function.parameters,parse:N.$parseRaw,strict:!0}}}return N}),f={};for(let N of M)if(N.type==="function")f[N.function.name||N.function.function.name]=N.function;let Q="tools"in w?M.map((N)=>N.type==="function"?{type:"function",function:{name:N.function.name||N.function.function.name,parameters:N.function.parameters,description:N.function.description,strict:N.function.strict}}:N):void 0;for(let N of w.messages)this._addMessage(N,!1);for(let N=0;N<T;++N){let K=(await this._createChatCompletion($,{...X,tool_choice:Y,tools:Q,messages:[...this.messages]},G)).choices[0]?.message;if(!K)throw new k("missing message in ChatCompletion response");if(!K.tool_calls?.length)return;for(let P of K.tool_calls){if(P.type!=="function")continue;let q=P.id,{name:V,arguments:E}=P.function,O=f[V];if(!O){let _=`Invalid tool_call: ${JSON.stringify(V)}. Available options are: ${Object.keys(f).map((s)=>JSON.stringify(s)).join(", ")}. Please try again`;this._addMessage({role:"tool",tool_call_id:q,content:_});continue}else if(J&&J!==V){let _=`Invalid tool_call: ${JSON.stringify(V)}. ${JSON.stringify(J)} requested. Please try again`;this._addMessage({role:"tool",tool_call_id:q,content:_});continue}let A;try{A=Jf(O)?await O.parse(E):E}catch(_){let s=_ instanceof Error?_.message:String(_);this._addMessage({role:"tool",tool_call_id:q,content:s});continue}let R=await O.function(A,this),S=B(this,L0,"m",Mf).call(this,R);if(this._addMessage({role:"tool",tool_call_id:q,content:S}),J)return}}return}}L0=new WeakSet,X3=function(){return B(this,L0,"m",e6).call(this).content??null},e6=function(){let w=this.messages.length;while(w-- >0){let G=this.messages[w];if(Hw(G))return{...G,content:G.content??null,refusal:G.refusal??null}}throw new k("stream ended without producing a ChatCompletionMessage with role=assistant")},J3=function(){for(let w=this.messages.length-1;w>=0;w--){let G=this.messages[w];if(Hw(G)&&G?.tool_calls?.length)return G.tool_calls.filter((W)=>W.type==="function").at(-1)?.function}return},T3=function(){for(let w=this.messages.length-1;w>=0;w--){let G=this.messages[w];if(Y3(G)&&G.content!=null&&typeof G.content==="string"&&this.messages.some((W)=>W.role==="assistant"&&W.tool_calls?.some((Y)=>Y.type==="function"&&Y.id===G.tool_call_id)))return G.content}return},M3=function(){let w={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:G}of this._chatCompletions)if(G)w.completion_tokens+=G.completion_tokens,w.prompt_tokens+=G.prompt_tokens,w.total_tokens+=G.total_tokens;return w},Tf=function(w){if(w.n!=null&&w.n>1)throw new k("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Mf=function(w){return typeof w==="string"?w:w===void 0?"undefined":JSON.stringify(w)};class C9 extends j9{static runTools($,w,G){let W=new C9,Y={...G,headers:{...G?.headers,"X-Stainless-Helper-Method":"runTools"}};return W._run(()=>W._runTools($,w,Y)),W}_addMessage($,w=!0){if(super._addMessage($,w),Hw($)&&$.content)this._emit("content",$.content)}}var N0={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511};class ff extends Error{}class Qf extends Error{}function mO($,w=N0.ALL){if(typeof $!=="string")throw TypeError(`expecting str, got ${typeof $}`);if(!$.trim())throw Error(`${$} is empty`);return lO($.trim(),w)}var lO=($,w)=>{let G=$.length,W=0,Y=(N)=>{throw new ff(`${N} at position ${W}`)},Z=(N)=>{throw new Qf(`${N} at position ${W}`)},X=()=>{if(Q(),W>=G)Y("Unexpected end of input");if($[W]==='"')return J();if($[W]==="{")return T();if($[W]==="[")return M();if($.substring(W,W+4)==="null"||N0.NULL&w&&G-W<4&&"null".startsWith($.substring(W)))return W+=4,null;if($.substring(W,W+4)==="true"||N0.BOOL&w&&G-W<4&&"true".startsWith($.substring(W)))return W+=4,!0;if($.substring(W,W+5)==="false"||N0.BOOL&w&&G-W<5&&"false".startsWith($.substring(W)))return W+=5,!1;if($.substring(W,W+8)==="Infinity"||N0.INFINITY&w&&G-W<8&&"Infinity".startsWith($.substring(W)))return W+=8,1/0;if($.substring(W,W+9)==="-Infinity"||N0.MINUS_INFINITY&w&&1<G-W&&G-W<9&&"-Infinity".startsWith($.substring(W)))return W+=9,-1/0;if($.substring(W,W+3)==="NaN"||N0.NAN&w&&G-W<3&&"NaN".startsWith($.substring(W)))return W+=3,NaN;return f()},J=()=>{let N=W,z=!1;W++;while(W<G&&($[W]!=='"'||z&&$[W-1]==="\\"))z=$[W]==="\\"?!z:!1,W++;if($.charAt(W)=='"')try{return JSON.parse($.substring(N,++W-Number(z)))}catch(K){Z(String(K))}else if(N0.STR&w)try{return JSON.parse($.substring(N,W-Number(z))+'"')}catch(K){return JSON.parse($.substring(N,$.lastIndexOf("\\"))+'"')}Y("Unterminated string literal")},T=()=>{W++,Q();let N={};try{while($[W]!=="}"){if(Q(),W>=G&&N0.OBJ&w)return N;let z=J();Q(),W++;try{let K=X();Object.defineProperty(N,z,{value:K,writable:!0,enumerable:!0,configurable:!0})}catch(K){if(N0.OBJ&w)return N;else throw K}if(Q(),$[W]===",")W++}}catch(z){if(N0.OBJ&w)return N;else Y("Expected '}' at end of object")}return W++,N},M=()=>{W++;let N=[];try{while($[W]!=="]")if(N.push(X()),Q(),$[W]===",")W++}catch(z){if(N0.ARR&w)return N;Y("Expected ']' at end of array")}return W++,N},f=()=>{if(W===0){if($==="-"&&N0.NUM&w)Y("Not sure what '-' is");try{return JSON.parse($)}catch(z){if(N0.NUM&w)try{if($[$.length-1]===".")return JSON.parse($.substring(0,$.lastIndexOf(".")));return JSON.parse($.substring(0,$.lastIndexOf("e")))}catch(K){}Z(String(z))}}let N=W;if($[W]==="-")W++;while($[W]&&!",]}".includes($[W]))W++;if(W==G&&!(N0.NUM&w))Y("Unterminated number literal");try{return JSON.parse($.substring(N,W))}catch(z){if($.substring(N,W)==="-"&&N0.NUM&w)Y("Not sure what '-' is");try{return JSON.parse($.substring(N,$.lastIndexOf("e")))}catch(K){Z(String(K))}}},Q=()=>{while(W<G&&`
183
- \r `.includes($[W]))W++};return X()},f3=($)=>mO($,N0.ALL^N0.NUM);var f0,y1,Ow,a1,Q3,$5,N3,z3,K3,w5,P3,Nf;class o1 extends j9{constructor($){super();f0.add(this),y1.set(this,void 0),Ow.set(this,void 0),a1.set(this,void 0),C(this,y1,$,"f"),C(this,Ow,[],"f")}get currentChatCompletionSnapshot(){return B(this,a1,"f")}static fromReadableStream($){let w=new o1(null);return w._run(()=>w._fromReadableStream($)),w}static createChatCompletion($,w,G){let W=new o1(w);return W._run(()=>W._runChatCompletion($,{...w,stream:!0},{...G,headers:{...G?.headers,"X-Stainless-Helper-Method":"stream"}})),W}async _createChatCompletion($,w,G){super._createChatCompletion;let W=G?.signal;if(W){if(W.aborted)this.controller.abort();W.addEventListener("abort",()=>this.controller.abort())}B(this,f0,"m",Q3).call(this);let Y=await $.chat.completions.create({...w,stream:!0},{...G,signal:this.controller.signal});this._connected();for await(let Z of Y)B(this,f0,"m",N3).call(this,Z);if(Y.controller.signal?.aborted)throw new T0;return this._addChatCompletion(B(this,f0,"m",w5).call(this))}async _fromReadableStream($,w){let G=w?.signal;if(G){if(G.aborted)this.controller.abort();G.addEventListener("abort",()=>this.controller.abort())}B(this,f0,"m",Q3).call(this),this._connected();let W=g0.fromReadableStream($,this.controller),Y;for await(let Z of W){if(Y&&Y!==Z.id)this._addChatCompletion(B(this,f0,"m",w5).call(this));B(this,f0,"m",N3).call(this,Z),Y=Z.id}if(W.controller.signal?.aborted)throw new T0;return this._addChatCompletion(B(this,f0,"m",w5).call(this))}[(y1=new WeakMap,Ow=new WeakMap,a1=new WeakMap,f0=new WeakSet,Q3=function(){if(this.ended)return;C(this,a1,void 0,"f")},$5=function(w){let G=B(this,Ow,"f")[w.index];if(G)return G;return G={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},B(this,Ow,"f")[w.index]=G,G},N3=function(w){if(this.ended)return;let G=B(this,f0,"m",Nf).call(this,w);this._emit("chunk",w,G);for(let W of w.choices){let Y=G.choices[W.index];if(W.delta.content!=null&&Y.message?.role==="assistant"&&Y.message?.content)this._emit("content",W.delta.content,Y.message.content),this._emit("content.delta",{delta:W.delta.content,snapshot:Y.message.content,parsed:Y.message.parsed});if(W.delta.refusal!=null&&Y.message?.role==="assistant"&&Y.message?.refusal)this._emit("refusal.delta",{delta:W.delta.refusal,snapshot:Y.message.refusal});if(W.logprobs?.content!=null&&Y.message?.role==="assistant")this._emit("logprobs.content.delta",{content:W.logprobs?.content,snapshot:Y.logprobs?.content??[]});if(W.logprobs?.refusal!=null&&Y.message?.role==="assistant")this._emit("logprobs.refusal.delta",{refusal:W.logprobs?.refusal,snapshot:Y.logprobs?.refusal??[]});let Z=B(this,f0,"m",$5).call(this,Y);if(Y.finish_reason){if(B(this,f0,"m",K3).call(this,Y),Z.current_tool_call_index!=null)B(this,f0,"m",z3).call(this,Y,Z.current_tool_call_index)}for(let X of W.delta.tool_calls??[]){if(Z.current_tool_call_index!==X.index){if(B(this,f0,"m",K3).call(this,Y),Z.current_tool_call_index!=null)B(this,f0,"m",z3).call(this,Y,Z.current_tool_call_index)}Z.current_tool_call_index=X.index}for(let X of W.delta.tool_calls??[]){let J=Y.message.tool_calls?.[X.index];if(!J?.type)continue;if(J?.type==="function")this._emit("tool_calls.function.arguments.delta",{name:J.function?.name,index:X.index,arguments:J.function.arguments,parsed_arguments:J.function.parsed_arguments,arguments_delta:X.function?.arguments??""});else Kf(J?.type)}}},z3=function(w,G){if(B(this,f0,"m",$5).call(this,w).done_tool_calls.has(G))return;let Y=w.message.tool_calls?.[G];if(!Y)throw Error("no tool call snapshot");if(!Y.type)throw Error("tool call snapshot missing `type`");if(Y.type==="function"){let Z=B(this,y1,"f")?.tools?.find((X)=>O9(X)&&X.function.name===Y.function.name);this._emit("tool_calls.function.arguments.done",{name:Y.function.name,index:G,arguments:Y.function.arguments,parsed_arguments:k$(Z)?Z.$parseRaw(Y.function.arguments):Z?.function.strict?JSON.parse(Y.function.arguments):null})}else Kf(Y.type)},K3=function(w){let G=B(this,f0,"m",$5).call(this,w);if(w.message.content&&!G.content_done){G.content_done=!0;let W=B(this,f0,"m",P3).call(this);this._emit("content.done",{content:w.message.content,parsed:W?W.$parseRaw(w.message.content):null})}if(w.message.refusal&&!G.refusal_done)G.refusal_done=!0,this._emit("refusal.done",{refusal:w.message.refusal});if(w.logprobs?.content&&!G.logprobs_content_done)G.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:w.logprobs.content});if(w.logprobs?.refusal&&!G.logprobs_refusal_done)G.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:w.logprobs.refusal})},w5=function(){if(this.ended)throw new k("stream has ended, this shouldn't happen");let w=B(this,a1,"f");if(!w)throw new k("request ended without sending any chunks");return C(this,a1,void 0,"f"),C(this,Ow,[],"f"),cO(w,B(this,y1,"f"))},P3=function(){let w=B(this,y1,"f")?.response_format;if(L9(w))return w;return null},Nf=function(w){var G,W,Y,Z;let X=B(this,a1,"f"),{choices:J,...T}=w;if(!X)X=C(this,a1,{...T,choices:[]},"f");else Object.assign(X,T);for(let{delta:M,finish_reason:f,index:Q,logprobs:N=null,...z}of w.choices){let K=X.choices[Q];if(!K)K=X.choices[Q]={finish_reason:f,index:Q,message:{},logprobs:N,...z};if(N)if(!K.logprobs)K.logprobs=Object.assign({},N);else{let{content:R,refusal:S,..._}=N;if(zf(_),Object.assign(K.logprobs,_),R)(G=K.logprobs).content??(G.content=[]),K.logprobs.content.push(...R);if(S)(W=K.logprobs).refusal??(W.refusal=[]),K.logprobs.refusal.push(...S)}if(f){if(K.finish_reason=f,B(this,y1,"f")&&W3(B(this,y1,"f"))){if(f==="length")throw new B9;if(f==="content_filter")throw new V9}}if(Object.assign(K,z),!M)continue;let{content:P,refusal:q,function_call:V,role:E,tool_calls:O,...A}=M;if(zf(A),Object.assign(K.message,A),q)K.message.refusal=(K.message.refusal||"")+q;if(E)K.message.role=E;if(V)if(!K.message.function_call)K.message.function_call=V;else{if(V.name)K.message.function_call.name=V.name;if(V.arguments)(Y=K.message.function_call).arguments??(Y.arguments=""),K.message.function_call.arguments+=V.arguments}if(P){if(K.message.content=(K.message.content||"")+P,!K.message.refusal&&B(this,f0,"m",P3).call(this))K.message.parsed=f3(K.message.content)}if(O){if(!K.message.tool_calls)K.message.tool_calls=[];for(let{index:R,id:S,type:_,function:s,...e}of O){let v=(Z=K.message.tool_calls)[R]??(Z[R]={});if(Object.assign(v,e),S)v.id=S;if(_)v.type=_;if(s)v.function??(v.function={name:s.name??"",arguments:""});if(s?.name)v.function.name=s.name;if(s?.arguments){if(v.function.arguments+=s.arguments,Wf(B(this,y1,"f"),v))v.function.parsed_arguments=f3(v.function.arguments)}}}}return X},Symbol.asyncIterator)](){let $=[],w=[],G=!1;return this.on("chunk",(W)=>{let Y=w.shift();if(Y)Y.resolve(W);else $.push(W)}),this.on("end",()=>{G=!0;for(let W of w)W.resolve(void 0);w.length=0}),this.on("abort",(W)=>{G=!0;for(let Y of w)Y.reject(W);w.length=0}),this.on("error",(W)=>{G=!0;for(let Y of w)Y.reject(W);w.length=0}),{next:async()=>{if(!$.length){if(G)return{value:void 0,done:!0};return new Promise((Y,Z)=>w.push({resolve:Y,reject:Z})).then((Y)=>Y?{value:Y,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new g0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function cO($,w){let{id:G,choices:W,created:Y,model:Z,system_fingerprint:X,...J}=$,T={...J,id:G,choices:W.map(({message:M,finish_reason:f,index:Q,logprobs:N,...z})=>{if(!f)throw new k(`missing finish_reason for choice ${Q}`);let{content:K=null,function_call:P,tool_calls:q,...V}=M,E=M.role;if(!E)throw new k(`missing role for choice ${Q}`);if(P){let{arguments:O,name:A}=P;if(O==null)throw new k(`missing function_call.arguments for choice ${Q}`);if(!A)throw new k(`missing function_call.name for choice ${Q}`);return{...z,message:{content:K,function_call:{arguments:O,name:A},role:E,refusal:M.refusal??null},finish_reason:f,index:Q,logprobs:N}}if(q)return{...z,index:Q,finish_reason:f,logprobs:N,message:{...V,role:E,content:K,refusal:M.refusal??null,tool_calls:q.map((O,A)=>{let{function:R,type:S,id:_,...s}=O,{arguments:e,name:v,...H0}=R||{};if(_==null)throw new k(`missing choices[${Q}].tool_calls[${A}].id
184
- ${G5($)}`);if(S==null)throw new k(`missing choices[${Q}].tool_calls[${A}].type
185
- ${G5($)}`);if(v==null)throw new k(`missing choices[${Q}].tool_calls[${A}].function.name
186
- ${G5($)}`);if(e==null)throw new k(`missing choices[${Q}].tool_calls[${A}].function.arguments
187
- ${G5($)}`);return{...s,id:_,type:S,function:{...H0,name:v,arguments:e}}})}};return{...z,message:{...V,content:K,role:E,refusal:M.refusal??null},finish_reason:f,index:Q,logprobs:N}}),created:Y,model:Z,object:"chat.completion",...X?{system_fingerprint:X}:{}};return Gf(T,w)}function G5($){return JSON.stringify($)}function zf($){return}function Kf($){}class Lw extends o1{static fromReadableStream($){let w=new Lw(null);return w._run(()=>w._fromReadableStream($)),w}static runTools($,w,G){let W=new Lw(w),Y={...G,headers:{...G?.headers,"X-Stainless-Helper-Method":"runTools"}};return W._run(()=>W._runTools($,w,Y)),W}}class e1 extends F{constructor(){super(...arguments);this.messages=new Uw(this._client)}create($,w){return this._client.post("/chat/completions",{body:$,...w,stream:$.stream??!1})}retrieve($,w){return this._client.get(U`/chat/completions/${$}`,w)}update($,w,G){return this._client.post(U`/chat/completions/${$}`,{body:w,...G})}list($={},w){return this._client.getAPIList("/chat/completions",h,{query:$,...w})}delete($,w){return this._client.delete(U`/chat/completions/${$}`,w)}parse($,w){return Zf($.tools),this._client.chat.completions.create($,{...w,headers:{...w?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap((G)=>D9(G,$))}runTools($,w){if($.stream)return Lw.runTools(this._client,$,w);return C9.runTools(this._client,$,w)}stream($,w){return o1.createChatCompletion(this._client,$,w)}}e1.Messages=Uw;class S$ extends F{constructor(){super(...arguments);this.completions=new e1(this._client)}}S$.Completions=e1;var Pf=Symbol("brand.privateNullableHeaders");function*nO($){if(!$)return;if(Pf in $){let{values:W,nulls:Y}=$;yield*W.entries();for(let Z of Y)yield[Z,null];return}let w=!1,G;if($ instanceof Headers)G=$.entries();else if(uW($))G=$;else w=!0,G=Object.entries($??{});for(let W of G){let Y=W[0];if(typeof Y!=="string")throw TypeError("expected header name to be a string");let Z=uW(W[1])?W[1]:[W[1]],X=!1;for(let J of Z){if(J===void 0)continue;if(w&&!X)X=!0,yield[Y,null];yield[Y,J]}}}var D=($)=>{let w=new Headers,G=new Set;for(let W of $){let Y=new Set;for(let[Z,X]of nO(W)){let J=Z.toLowerCase();if(!Y.has(J))w.delete(Z),Y.add(J);if(X===null)w.delete(Z),G.add(J);else w.append(Z,X),G.delete(J)}}return{[Pf]:!0,values:w,nulls:G}};class y9 extends F{create($,w){return this._client.post("/audio/speech",{body:$,...w,headers:D([{Accept:"application/octet-stream"},w?.headers]),__binaryResponse:!0})}}class I9 extends F{create($,w){return this._client.post("/audio/transcriptions",v0({body:$,...w,stream:$.stream??!1,__metadata:{model:$.model}},this._client))}}class b9 extends F{create($,w){return this._client.post("/audio/translations",v0({body:$,...w,__metadata:{model:$.model}},this._client))}}class I1 extends F{constructor(){super(...arguments);this.transcriptions=new I9(this._client),this.translations=new b9(this._client),this.speech=new y9(this._client)}}I1.Transcriptions=I9;I1.Translations=b9;I1.Speech=y9;class Dw extends F{create($,w){return this._client.post("/batches",{body:$,...w})}retrieve($,w){return this._client.get(U`/batches/${$}`,w)}list($={},w){return this._client.getAPIList("/batches",h,{query:$,...w})}cancel($,w){return this._client.post(U`/batches/${$}/cancel`,w)}}class x9 extends F{create($,w){return this._client.post("/assistants",{body:$,...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}retrieve($,w){return this._client.get(U`/assistants/${$}`,{...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}update($,w,G){return this._client.post(U`/assistants/${$}`,{body:w,...G,headers:D([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}list($={},w){return this._client.getAPIList("/assistants",h,{query:$,...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}delete($,w){return this._client.delete(U`/assistants/${$}`,{...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}}class _9 extends F{create($,w){return this._client.post("/realtime/sessions",{body:$,...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}}class g9 extends F{create($,w){return this._client.post("/realtime/transcription_sessions",{body:$,...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}}class R$ extends F{constructor(){super(...arguments);this.sessions=new _9(this._client),this.transcriptionSessions=new g9(this._client)}}R$.Sessions=_9;R$.TranscriptionSessions=g9;class v9 extends F{create($,w,G){return this._client.post(U`/threads/${$}/messages`,{body:w,...G,headers:D([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}retrieve($,w,G){let{thread_id:W}=w;return this._client.get(U`/threads/${W}/messages/${$}`,{...G,headers:D([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}update($,w,G){let{thread_id:W,...Y}=w;return this._client.post(U`/threads/${W}/messages/${$}`,{body:Y,...G,headers:D([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}list($,w={},G){return this._client.getAPIList(U`/threads/${$}/messages`,h,{query:w,...G,headers:D([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}delete($,w,G){let{thread_id:W}=w;return this._client.delete(U`/threads/${W}/messages/${$}`,{...G,headers:D([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}}class u9 extends F{retrieve($,w,G){let{thread_id:W,run_id:Y,...Z}=w;return this._client.get(U`/threads/${W}/runs/${Y}/steps/${$}`,{query:Z,...G,headers:D([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}list($,w,G){let{thread_id:W,...Y}=w;return this._client.getAPIList(U`/threads/${W}/runs/${$}/steps`,h,{query:Y,...G,headers:D([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}}var Bf=($)=>{if(typeof Buffer<"u"){let w=Buffer.from($,"base64");return Array.from(new Float32Array(w.buffer,w.byteOffset,w.length/Float32Array.BYTES_PER_ELEMENT))}else{let w=atob($),G=w.length,W=new Uint8Array(G);for(let Y=0;Y<G;Y++)W[Y]=w.charCodeAt(Y);return Array.from(new Float32Array(W.buffer))}};var $$=($)=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[$]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.($)?.trim();return};var K0,C$,B3,N1,W5,w1,y$,kw,j$,X5,u0,Y5,Z5,m9,h9,i9,Vf,qf,Ef,Uf,Hf,Ff,Of;class w$ extends A${constructor(){super(...arguments);K0.add(this),B3.set(this,[]),N1.set(this,{}),W5.set(this,{}),w1.set(this,void 0),y$.set(this,void 0),kw.set(this,void 0),j$.set(this,void 0),X5.set(this,void 0),u0.set(this,void 0),Y5.set(this,void 0),Z5.set(this,void 0),m9.set(this,void 0)}[(B3=new WeakMap,N1=new WeakMap,W5=new WeakMap,w1=new WeakMap,y$=new WeakMap,kw=new WeakMap,j$=new WeakMap,X5=new WeakMap,u0=new WeakMap,Y5=new WeakMap,Z5=new WeakMap,m9=new WeakMap,K0=new WeakSet,Symbol.asyncIterator)](){let $=[],w=[],G=!1;return this.on("event",(W)=>{let Y=w.shift();if(Y)Y.resolve(W);else $.push(W)}),this.on("end",()=>{G=!0;for(let W of w)W.resolve(void 0);w.length=0}),this.on("abort",(W)=>{G=!0;for(let Y of w)Y.reject(W);w.length=0}),this.on("error",(W)=>{G=!0;for(let Y of w)Y.reject(W);w.length=0}),{next:async()=>{if(!$.length){if(G)return{value:void 0,done:!0};return new Promise((Y,Z)=>w.push({resolve:Y,reject:Z})).then((Y)=>Y?{value:Y,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}static fromReadableStream($){let w=new C$;return w._run(()=>w._fromReadableStream($)),w}async _fromReadableStream($,w){let G=w?.signal;if(G){if(G.aborted)this.controller.abort();G.addEventListener("abort",()=>this.controller.abort())}this._connected();let W=g0.fromReadableStream($,this.controller);for await(let Y of W)B(this,K0,"m",h9).call(this,Y);if(W.controller.signal?.aborted)throw new T0;return this._addRun(B(this,K0,"m",i9).call(this))}toReadableStream(){return new g0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream($,w,G,W){let Y=new C$;return Y._run(()=>Y._runToolAssistantStream($,w,G,{...W,headers:{...W?.headers,"X-Stainless-Helper-Method":"stream"}})),Y}async _createToolAssistantStream($,w,G,W){let Y=W?.signal;if(Y){if(Y.aborted)this.controller.abort();Y.addEventListener("abort",()=>this.controller.abort())}let Z={...G,stream:!0},X=await $.submitToolOutputs(w,Z,{...W,signal:this.controller.signal});this._connected();for await(let J of X)B(this,K0,"m",h9).call(this,J);if(X.controller.signal?.aborted)throw new T0;return this._addRun(B(this,K0,"m",i9).call(this))}static createThreadAssistantStream($,w,G){let W=new C$;return W._run(()=>W._threadAssistantStream($,w,{...G,headers:{...G?.headers,"X-Stainless-Helper-Method":"stream"}})),W}static createAssistantStream($,w,G,W){let Y=new C$;return Y._run(()=>Y._runAssistantStream($,w,G,{...W,headers:{...W?.headers,"X-Stainless-Helper-Method":"stream"}})),Y}currentEvent(){return B(this,Y5,"f")}currentRun(){return B(this,Z5,"f")}currentMessageSnapshot(){return B(this,w1,"f")}currentRunStepSnapshot(){return B(this,m9,"f")}async finalRunSteps(){return await this.done(),Object.values(B(this,N1,"f"))}async finalMessages(){return await this.done(),Object.values(B(this,W5,"f"))}async finalRun(){if(await this.done(),!B(this,y$,"f"))throw Error("Final run was not received.");return B(this,y$,"f")}async _createThreadAssistantStream($,w,G){let W=G?.signal;if(W){if(W.aborted)this.controller.abort();W.addEventListener("abort",()=>this.controller.abort())}let Y={...w,stream:!0},Z=await $.createAndRun(Y,{...G,signal:this.controller.signal});this._connected();for await(let X of Z)B(this,K0,"m",h9).call(this,X);if(Z.controller.signal?.aborted)throw new T0;return this._addRun(B(this,K0,"m",i9).call(this))}async _createAssistantStream($,w,G,W){let Y=W?.signal;if(Y){if(Y.aborted)this.controller.abort();Y.addEventListener("abort",()=>this.controller.abort())}let Z={...G,stream:!0},X=await $.create(w,Z,{...W,signal:this.controller.signal});this._connected();for await(let J of X)B(this,K0,"m",h9).call(this,J);if(X.controller.signal?.aborted)throw new T0;return this._addRun(B(this,K0,"m",i9).call(this))}static accumulateDelta($,w){for(let[G,W]of Object.entries(w)){if(!$.hasOwnProperty(G)){$[G]=W;continue}let Y=$[G];if(Y===null||Y===void 0){$[G]=W;continue}if(G==="index"||G==="type"){$[G]=W;continue}if(typeof Y==="string"&&typeof W==="string")Y+=W;else if(typeof Y==="number"&&typeof W==="number")Y+=W;else if(q9(Y)&&q9(W))Y=this.accumulateDelta(Y,W);else if(Array.isArray(Y)&&Array.isArray(W)){if(Y.every((Z)=>typeof Z==="string"||typeof Z==="number")){Y.push(...W);continue}for(let Z of W){if(!q9(Z))throw Error(`Expected array delta entry to be an object but got: ${Z}`);let X=Z.index;if(X==null)throw console.error(Z),Error("Expected array delta entry to have an `index` property");if(typeof X!=="number")throw Error(`Expected array delta entry \`index\` property to be a number but got ${X}`);let J=Y[X];if(J==null)Y.push(Z);else Y[X]=this.accumulateDelta(J,Z)}continue}else throw Error(`Unhandled record type: ${G}, deltaValue: ${W}, accValue: ${Y}`);$[G]=Y}return $}_addRun($){return $}async _threadAssistantStream($,w,G){return await this._createThreadAssistantStream(w,$,G)}async _runAssistantStream($,w,G,W){return await this._createAssistantStream(w,$,G,W)}async _runToolAssistantStream($,w,G,W){return await this._createToolAssistantStream(w,$,G,W)}}C$=w$,h9=function(w){if(this.ended)return;switch(C(this,Y5,w,"f"),B(this,K0,"m",Ef).call(this,w),w.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":B(this,K0,"m",Of).call(this,w);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":B(this,K0,"m",qf).call(this,w);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":B(this,K0,"m",Vf).call(this,w);break;case"error":throw Error("Encountered an error event in event processing - errors should be processed earlier");default:GL(w)}},i9=function(){if(this.ended)throw new k("stream has ended, this shouldn't happen");if(!B(this,y$,"f"))throw Error("Final run has not been received");return B(this,y$,"f")},Vf=function(w){let[G,W]=B(this,K0,"m",Hf).call(this,w,B(this,w1,"f"));C(this,w1,G,"f"),B(this,W5,"f")[G.id]=G;for(let Y of W){let Z=G.content[Y.index];if(Z?.type=="text")this._emit("textCreated",Z.text)}switch(w.event){case"thread.message.created":this._emit("messageCreated",w.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",w.data.delta,G),w.data.delta.content)for(let Y of w.data.delta.content){if(Y.type=="text"&&Y.text){let Z=Y.text,X=G.content[Y.index];if(X&&X.type=="text")this._emit("textDelta",Z,X.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(Y.index!=B(this,kw,"f")){if(B(this,j$,"f"))switch(B(this,j$,"f").type){case"text":this._emit("textDone",B(this,j$,"f").text,B(this,w1,"f"));break;case"image_file":this._emit("imageFileDone",B(this,j$,"f").image_file,B(this,w1,"f"));break}C(this,kw,Y.index,"f")}C(this,j$,G.content[Y.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(B(this,kw,"f")!==void 0){let Y=w.data.content[B(this,kw,"f")];if(Y)switch(Y.type){case"image_file":this._emit("imageFileDone",Y.image_file,B(this,w1,"f"));break;case"text":this._emit("textDone",Y.text,B(this,w1,"f"));break}}if(B(this,w1,"f"))this._emit("messageDone",w.data);C(this,w1,void 0,"f")}},qf=function(w){let G=B(this,K0,"m",Uf).call(this,w);switch(C(this,m9,G,"f"),w.event){case"thread.run.step.created":this._emit("runStepCreated",w.data);break;case"thread.run.step.delta":let W=w.data.delta;if(W.step_details&&W.step_details.type=="tool_calls"&&W.step_details.tool_calls&&G.step_details.type=="tool_calls")for(let Z of W.step_details.tool_calls)if(Z.index==B(this,X5,"f"))this._emit("toolCallDelta",Z,G.step_details.tool_calls[Z.index]);else{if(B(this,u0,"f"))this._emit("toolCallDone",B(this,u0,"f"));if(C(this,X5,Z.index,"f"),C(this,u0,G.step_details.tool_calls[Z.index],"f"),B(this,u0,"f"))this._emit("toolCallCreated",B(this,u0,"f"))}this._emit("runStepDelta",w.data.delta,G);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":if(C(this,m9,void 0,"f"),w.data.step_details.type=="tool_calls"){if(B(this,u0,"f"))this._emit("toolCallDone",B(this,u0,"f")),C(this,u0,void 0,"f")}this._emit("runStepDone",w.data,G);break;case"thread.run.step.in_progress":break}},Ef=function(w){B(this,B3,"f").push(w),this._emit("event",w)},Uf=function(w){switch(w.event){case"thread.run.step.created":return B(this,N1,"f")[w.data.id]=w.data,w.data;case"thread.run.step.delta":let G=B(this,N1,"f")[w.data.id];if(!G)throw Error("Received a RunStepDelta before creation of a snapshot");let W=w.data;if(W.delta){let Y=C$.accumulateDelta(G,W.delta);B(this,N1,"f")[w.data.id]=Y}return B(this,N1,"f")[w.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":B(this,N1,"f")[w.data.id]=w.data;break}if(B(this,N1,"f")[w.data.id])return B(this,N1,"f")[w.data.id];throw Error("No snapshot available")},Hf=function(w,G){let W=[];switch(w.event){case"thread.message.created":return[w.data,W];case"thread.message.delta":if(!G)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let Y=w.data;if(Y.delta.content)for(let Z of Y.delta.content)if(Z.index in G.content){let X=G.content[Z.index];G.content[Z.index]=B(this,K0,"m",Ff).call(this,Z,X)}else G.content[Z.index]=Z,W.push(Z);return[G,W];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(G)return[G,W];else throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Ff=function(w,G){return C$.accumulateDelta(G,w)},Of=function(w){switch(C(this,Z5,w.data,"f"),w.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":if(C(this,y$,w.data,"f"),B(this,u0,"f"))this._emit("toolCallDone",B(this,u0,"f")),C(this,u0,void 0,"f");break;case"thread.run.cancelling":break}};function GL($){}class Aw extends F{constructor(){super(...arguments);this.steps=new u9(this._client)}create($,w,G){let{include:W,...Y}=w;return this._client.post(U`/threads/${$}/runs`,{query:{include:W},body:Y,...G,headers:D([{"OpenAI-Beta":"assistants=v2"},G?.headers]),stream:w.stream??!1})}retrieve($,w,G){let{thread_id:W}=w;return this._client.get(U`/threads/${W}/runs/${$}`,{...G,headers:D([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}update($,w,G){let{thread_id:W,...Y}=w;return this._client.post(U`/threads/${W}/runs/${$}`,{body:Y,...G,headers:D([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}list($,w={},G){return this._client.getAPIList(U`/threads/${$}/runs`,h,{query:w,...G,headers:D([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}cancel($,w,G){let{thread_id:W}=w;return this._client.post(U`/threads/${W}/runs/${$}/cancel`,{...G,headers:D([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}async createAndPoll($,w,G){let W=await this.create($,w,G);return await this.poll(W.id,{thread_id:$},G)}createAndStream($,w,G){return w$.createAssistantStream($,this._client.beta.threads.runs,w,G)}async poll($,w,G){let W=D([G?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":G?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:Y,response:Z}=await this.retrieve($,w,{...G,headers:{...G?.headers,...W}}).withResponse();switch(Y.status){case"queued":case"in_progress":case"cancelling":let X=5000;if(G?.pollIntervalMs)X=G.pollIntervalMs;else{let J=Z.headers.get("openai-poll-after-ms");if(J){let T=parseInt(J);if(!isNaN(T))X=T}}await f1(X);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return Y}}}stream($,w,G){return w$.createAssistantStream($,this._client.beta.threads.runs,w,G)}submitToolOutputs($,w,G){let{thread_id:W,...Y}=w;return this._client.post(U`/threads/${W}/runs/${$}/submit_tool_outputs`,{body:Y,...G,headers:D([{"OpenAI-Beta":"assistants=v2"},G?.headers]),stream:w.stream??!1})}async submitToolOutputsAndPoll($,w,G){let W=await this.submitToolOutputs($,w,G);return await this.poll(W.id,w,G)}submitToolOutputsStream($,w,G){return w$.createToolAssistantStream($,this._client.beta.threads.runs,w,G)}}Aw.Steps=u9;class I$ extends F{constructor(){super(...arguments);this.runs=new Aw(this._client),this.messages=new v9(this._client)}create($={},w){return this._client.post("/threads",{body:$,...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}retrieve($,w){return this._client.get(U`/threads/${$}`,{...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}update($,w,G){return this._client.post(U`/threads/${$}`,{body:w,...G,headers:D([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}delete($,w){return this._client.delete(U`/threads/${$}`,{...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}createAndRun($,w){return this._client.post("/threads/runs",{body:$,...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers]),stream:$.stream??!1})}async createAndRunPoll($,w){let G=await this.createAndRun($,w);return await this.runs.poll(G.id,{thread_id:G.thread_id},w)}createAndRunStream($,w){return w$.createThreadAssistantStream($,this._client.beta.threads,w)}}I$.Runs=Aw;I$.Messages=v9;class b1 extends F{constructor(){super(...arguments);this.realtime=new R$(this._client),this.assistants=new x9(this._client),this.threads=new I$(this._client)}}b1.Realtime=R$;b1.Assistants=x9;b1.Threads=I$;class Sw extends F{create($,w){return this._client.post("/completions",{body:$,...w,stream:$.stream??!1})}}class l9 extends F{retrieve($,w,G){let{container_id:W}=w;return this._client.get(U`/containers/${W}/files/${$}/content`,{...G,headers:D([{Accept:"application/binary"},G?.headers]),__binaryResponse:!0})}}class Rw extends F{constructor(){super(...arguments);this.content=new l9(this._client)}create($,w,G){return this._client.post(U`/containers/${$}/files`,v0({body:w,...G},this._client))}retrieve($,w,G){let{container_id:W}=w;return this._client.get(U`/containers/${W}/files/${$}`,G)}list($,w={},G){return this._client.getAPIList(U`/containers/${$}/files`,h,{query:w,...G})}delete($,w,G){let{container_id:W}=w;return this._client.delete(U`/containers/${W}/files/${$}`,{...G,headers:D([{Accept:"*/*"},G?.headers])})}}Rw.Content=l9;class b$ extends F{constructor(){super(...arguments);this.files=new Rw(this._client)}create($,w){return this._client.post("/containers",{body:$,...w})}retrieve($,w){return this._client.get(U`/containers/${$}`,w)}list($={},w){return this._client.getAPIList("/containers",h,{query:$,...w})}delete($,w){return this._client.delete(U`/containers/${$}`,{...w,headers:D([{Accept:"*/*"},w?.headers])})}}b$.Files=Rw;class c9 extends F{create($,w,G){let{include:W,...Y}=w;return this._client.post(U`/conversations/${$}/items`,{query:{include:W},body:Y,...G})}retrieve($,w,G){let{conversation_id:W,...Y}=w;return this._client.get(U`/conversations/${W}/items/${$}`,{query:Y,...G})}list($,w={},G){return this._client.getAPIList(U`/conversations/${$}/items`,oW,{query:w,...G})}delete($,w,G){let{conversation_id:W}=w;return this._client.delete(U`/conversations/${W}/items/${$}`,G)}}class x$ extends F{constructor(){super(...arguments);this.items=new c9(this._client)}create($={},w){return this._client.post("/conversations",{body:$,...w})}retrieve($,w){return this._client.get(U`/conversations/${$}`,w)}update($,w,G){return this._client.post(U`/conversations/${$}`,{body:w,...G})}delete($,w){return this._client.delete(U`/conversations/${$}`,w)}}x$.Items=c9;class jw extends F{create($,w){let G=!!$.encoding_format,W=G?$.encoding_format:"base64";if(G)W0(this._client).debug("embeddings/user defined encoding_format:",$.encoding_format);let Y=this._client.post("/embeddings",{body:{...$,encoding_format:W},...w});if(G)return Y;return W0(this._client).debug("embeddings/decoding base64 embeddings from base64"),Y._thenUnwrap((Z)=>{if(Z&&Z.data)Z.data.forEach((X)=>{let J=X.embedding;X.embedding=Bf(J)});return Z})}}class d9 extends F{retrieve($,w,G){let{eval_id:W,run_id:Y}=w;return this._client.get(U`/evals/${W}/runs/${Y}/output_items/${$}`,G)}list($,w,G){let{eval_id:W,...Y}=w;return this._client.getAPIList(U`/evals/${W}/runs/${$}/output_items`,h,{query:Y,...G})}}class Cw extends F{constructor(){super(...arguments);this.outputItems=new d9(this._client)}create($,w,G){return this._client.post(U`/evals/${$}/runs`,{body:w,...G})}retrieve($,w,G){let{eval_id:W}=w;return this._client.get(U`/evals/${W}/runs/${$}`,G)}list($,w={},G){return this._client.getAPIList(U`/evals/${$}/runs`,h,{query:w,...G})}delete($,w,G){let{eval_id:W}=w;return this._client.delete(U`/evals/${W}/runs/${$}`,G)}cancel($,w,G){let{eval_id:W}=w;return this._client.post(U`/evals/${W}/runs/${$}`,G)}}Cw.OutputItems=d9;class _$ extends F{constructor(){super(...arguments);this.runs=new Cw(this._client)}create($,w){return this._client.post("/evals",{body:$,...w})}retrieve($,w){return this._client.get(U`/evals/${$}`,w)}update($,w,G){return this._client.post(U`/evals/${$}`,{body:w,...G})}list($={},w){return this._client.getAPIList("/evals",h,{query:$,...w})}delete($,w){return this._client.delete(U`/evals/${$}`,w)}}_$.Runs=Cw;class yw extends F{create($,w){return this._client.post("/files",v0({body:$,...w},this._client))}retrieve($,w){return this._client.get(U`/files/${$}`,w)}list($={},w){return this._client.getAPIList("/files",h,{query:$,...w})}delete($,w){return this._client.delete(U`/files/${$}`,w)}content($,w){return this._client.get(U`/files/${$}/content`,{...w,headers:D([{Accept:"application/binary"},w?.headers]),__binaryResponse:!0})}async waitForProcessing($,{pollInterval:w=5000,maxWait:G=1800000}={}){let W=new Set(["processed","error","deleted"]),Y=Date.now(),Z=await this.retrieve($);while(!Z.status||!W.has(Z.status))if(await f1(w),Z=await this.retrieve($),Date.now()-Y>G)throw new L$({message:`Giving up on waiting for file ${$} to finish processing after ${G} milliseconds.`});return Z}}class n9 extends F{}class p9 extends F{run($,w){return this._client.post("/fine_tuning/alpha/graders/run",{body:$,...w})}validate($,w){return this._client.post("/fine_tuning/alpha/graders/validate",{body:$,...w})}}class Iw extends F{constructor(){super(...arguments);this.graders=new p9(this._client)}}Iw.Graders=p9;class t9 extends F{create($,w,G){return this._client.getAPIList(U`/fine_tuning/checkpoints/${$}/permissions`,j1,{body:w,method:"post",...G})}retrieve($,w={},G){return this._client.get(U`/fine_tuning/checkpoints/${$}/permissions`,{query:w,...G})}delete($,w,G){let{fine_tuned_model_checkpoint:W}=w;return this._client.delete(U`/fine_tuning/checkpoints/${W}/permissions/${$}`,G)}}class bw extends F{constructor(){super(...arguments);this.permissions=new t9(this._client)}}bw.Permissions=t9;class r9 extends F{list($,w={},G){return this._client.getAPIList(U`/fine_tuning/jobs/${$}/checkpoints`,h,{query:w,...G})}}class xw extends F{constructor(){super(...arguments);this.checkpoints=new r9(this._client)}create($,w){return this._client.post("/fine_tuning/jobs",{body:$,...w})}retrieve($,w){return this._client.get(U`/fine_tuning/jobs/${$}`,w)}list($={},w){return this._client.getAPIList("/fine_tuning/jobs",h,{query:$,...w})}cancel($,w){return this._client.post(U`/fine_tuning/jobs/${$}/cancel`,w)}listEvents($,w={},G){return this._client.getAPIList(U`/fine_tuning/jobs/${$}/events`,h,{query:w,...G})}pause($,w){return this._client.post(U`/fine_tuning/jobs/${$}/pause`,w)}resume($,w){return this._client.post(U`/fine_tuning/jobs/${$}/resume`,w)}}xw.Checkpoints=r9;class z1 extends F{constructor(){super(...arguments);this.methods=new n9(this._client),this.jobs=new xw(this._client),this.checkpoints=new bw(this._client),this.alpha=new Iw(this._client)}}z1.Methods=n9;z1.Jobs=xw;z1.Checkpoints=bw;z1.Alpha=Iw;class s9 extends F{}class g$ extends F{constructor(){super(...arguments);this.graderModels=new s9(this._client)}}g$.GraderModels=s9;class _w extends F{createVariation($,w){return this._client.post("/images/variations",v0({body:$,...w},this._client))}edit($,w){return this._client.post("/images/edits",v0({body:$,...w,stream:$.stream??!1},this._client))}generate($,w){return this._client.post("/images/generations",{body:$,...w,stream:$.stream??!1})}}class gw extends F{retrieve($,w){return this._client.get(U`/models/${$}`,w)}list($){return this._client.getAPIList("/models",j1,$)}delete($,w){return this._client.delete(U`/models/${$}`,w)}}class vw extends F{create($,w){return this._client.post("/moderations",{body:$,...w})}}class a9 extends F{create($,w){return this._client.post("/realtime/client_secrets",{body:$,...w})}}class v$ extends F{constructor(){super(...arguments);this.clientSecrets=new a9(this._client)}}v$.ClientSecrets=a9;function Lf($,w){if(!w||!UL(w))return{...$,output_parsed:null,output:$.output.map((G)=>{if(G.type==="function_call")return{...G,parsed_arguments:null};if(G.type==="message")return{...G,content:G.content.map((W)=>({...W,parsed:null}))};else return G})};return V3($,w)}function V3($,w){let G=$.output.map((Y)=>{if(Y.type==="function_call")return{...Y,parsed_arguments:OL(w,Y)};if(Y.type==="message"){let Z=Y.content.map((X)=>{if(X.type==="output_text")return{...X,parsed:EL(w,X.text)};return X});return{...Y,content:Z}}return Y}),W=Object.assign({},$,{output:G});if(!Object.getOwnPropertyDescriptor($,"output_text"))J5(W);return Object.defineProperty(W,"output_parsed",{enumerable:!0,get(){for(let Y of W.output){if(Y.type!=="message")continue;for(let Z of Y.content)if(Z.type==="output_text"&&Z.parsed!==null)return Z.parsed}return null}}),W}function EL($,w){if($.text?.format?.type!=="json_schema")return null;if("$parseRaw"in $.text?.format)return($.text?.format).$parseRaw(w);return JSON.parse(w)}function UL($){if(L9($.text?.format))return!0;return!1}function HL($){return $?.$brand==="auto-parseable-tool"}function FL($,w){return $.find((G)=>G.type==="function"&&G.name===w)}function OL($,w){let G=FL($.tools??[],w.name);return{...w,...w,parsed_arguments:HL(G)?G.$parseRaw(w.arguments):G?.strict?JSON.parse(w.arguments):null}}function J5($){let w=[];for(let G of $.output){if(G.type!=="message")continue;for(let W of G.content)if(W.type==="output_text")w.push(W.text)}$.output_text=w.join("")}var uw,T5,G$,M5,Df,kf,Af,Sf;class f5 extends A${constructor($){super();uw.add(this),T5.set(this,void 0),G$.set(this,void 0),M5.set(this,void 0),C(this,T5,$,"f")}static createResponse($,w,G){let W=new f5(w);return W._run(()=>W._createOrRetrieveResponse($,w,{...G,headers:{...G?.headers,"X-Stainless-Helper-Method":"stream"}})),W}async _createOrRetrieveResponse($,w,G){let W=G?.signal;if(W){if(W.aborted)this.controller.abort();W.addEventListener("abort",()=>this.controller.abort())}B(this,uw,"m",Df).call(this);let Y,Z=null;if("response_id"in w)Y=await $.responses.retrieve(w.response_id,{stream:!0},{...G,signal:this.controller.signal,stream:!0}),Z=w.starting_after??null;else Y=await $.responses.create({...w,stream:!0},{...G,signal:this.controller.signal});this._connected();for await(let X of Y)B(this,uw,"m",kf).call(this,X,Z);if(Y.controller.signal?.aborted)throw new T0;return B(this,uw,"m",Af).call(this)}[(T5=new WeakMap,G$=new WeakMap,M5=new WeakMap,uw=new WeakSet,Df=function(){if(this.ended)return;C(this,G$,void 0,"f")},kf=function(w,G){if(this.ended)return;let W=(Z,X)=>{if(G==null||X.sequence_number>G)this._emit(Z,X)},Y=B(this,uw,"m",Sf).call(this,w);switch(W("event",w),w.type){case"response.output_text.delta":{let Z=Y.output[w.output_index];if(!Z)throw new k(`missing output at index ${w.output_index}`);if(Z.type==="message"){let X=Z.content[w.content_index];if(!X)throw new k(`missing content at index ${w.content_index}`);if(X.type!=="output_text")throw new k(`expected content to be 'output_text', got ${X.type}`);W("response.output_text.delta",{...w,snapshot:X.text})}break}case"response.function_call_arguments.delta":{let Z=Y.output[w.output_index];if(!Z)throw new k(`missing output at index ${w.output_index}`);if(Z.type==="function_call")W("response.function_call_arguments.delta",{...w,snapshot:Z.arguments});break}default:W(w.type,w);break}},Af=function(){if(this.ended)throw new k("stream has ended, this shouldn't happen");let w=B(this,G$,"f");if(!w)throw new k("request ended without sending any events");C(this,G$,void 0,"f");let G=LL(w,B(this,T5,"f"));return C(this,M5,G,"f"),G},Sf=function(w){let G=B(this,G$,"f");if(!G){if(w.type!=="response.created")throw new k(`When snapshot hasn't been set yet, expected 'response.created' event, got ${w.type}`);return G=C(this,G$,w.response,"f"),G}switch(w.type){case"response.output_item.added":{G.output.push(w.item);break}case"response.content_part.added":{let W=G.output[w.output_index];if(!W)throw new k(`missing output at index ${w.output_index}`);let Y=W.type,Z=w.part;if(Y==="message"&&Z.type!=="reasoning_text")W.content.push(Z);else if(Y==="reasoning"&&Z.type==="reasoning_text"){if(!W.content)W.content=[];W.content.push(Z)}break}case"response.output_text.delta":{let W=G.output[w.output_index];if(!W)throw new k(`missing output at index ${w.output_index}`);if(W.type==="message"){let Y=W.content[w.content_index];if(!Y)throw new k(`missing content at index ${w.content_index}`);if(Y.type!=="output_text")throw new k(`expected content to be 'output_text', got ${Y.type}`);Y.text+=w.delta}break}case"response.function_call_arguments.delta":{let W=G.output[w.output_index];if(!W)throw new k(`missing output at index ${w.output_index}`);if(W.type==="function_call")W.arguments+=w.delta;break}case"response.reasoning_text.delta":{let W=G.output[w.output_index];if(!W)throw new k(`missing output at index ${w.output_index}`);if(W.type==="reasoning"){let Y=W.content?.[w.content_index];if(!Y)throw new k(`missing content at index ${w.content_index}`);if(Y.type!=="reasoning_text")throw new k(`expected content to be 'reasoning_text', got ${Y.type}`);Y.text+=w.delta}break}case"response.completed":{C(this,G$,w.response,"f");break}}return G},Symbol.asyncIterator)](){let $=[],w=[],G=!1;return this.on("event",(W)=>{let Y=w.shift();if(Y)Y.resolve(W);else $.push(W)}),this.on("end",()=>{G=!0;for(let W of w)W.resolve(void 0);w.length=0}),this.on("abort",(W)=>{G=!0;for(let Y of w)Y.reject(W);w.length=0}),this.on("error",(W)=>{G=!0;for(let Y of w)Y.reject(W);w.length=0}),{next:async()=>{if(!$.length){if(G)return{value:void 0,done:!0};return new Promise((Y,Z)=>w.push({resolve:Y,reject:Z})).then((Y)=>Y?{value:Y,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}async finalResponse(){await this.done();let $=B(this,M5,"f");if(!$)throw new k("stream ended without producing a ChatCompletion");return $}}function LL($,w){return Lf($,w)}class o9 extends F{list($,w={},G){return this._client.getAPIList(U`/responses/${$}/input_items`,h,{query:w,...G})}}class u$ extends F{constructor(){super(...arguments);this.inputItems=new o9(this._client)}create($,w){return this._client.post("/responses",{body:$,...w,stream:$.stream??!1})._thenUnwrap((G)=>{if("object"in G&&G.object==="response")J5(G);return G})}retrieve($,w={},G){return this._client.get(U`/responses/${$}`,{query:w,...G,stream:w?.stream??!1})._thenUnwrap((W)=>{if("object"in W&&W.object==="response")J5(W);return W})}delete($,w){return this._client.delete(U`/responses/${$}`,{...w,headers:D([{Accept:"*/*"},w?.headers])})}parse($,w){return this._client.responses.create($,w)._thenUnwrap((G)=>V3(G,$))}stream($,w){return f5.createResponse(this._client,$,w)}cancel($,w){return this._client.post(U`/responses/${$}/cancel`,w)}}u$.InputItems=o9;class e9 extends F{create($,w,G){return this._client.post(U`/uploads/${$}/parts`,v0({body:w,...G},this._client))}}class h$ extends F{constructor(){super(...arguments);this.parts=new e9(this._client)}create($,w){return this._client.post("/uploads",{body:$,...w})}cancel($,w){return this._client.post(U`/uploads/${$}/cancel`,w)}complete($,w,G){return this._client.post(U`/uploads/${$}/complete`,{body:w,...G})}}h$.Parts=e9;var Rf=async($)=>{let w=await Promise.allSettled($),G=w.filter((Y)=>Y.status==="rejected");if(G.length){for(let Y of G)console.error(Y.reason);throw Error(`${G.length} promise(s) failed - see the above errors`)}let W=[];for(let Y of w)if(Y.status==="fulfilled")W.push(Y.value);return W};class $8 extends F{create($,w,G){return this._client.post(U`/vector_stores/${$}/file_batches`,{body:w,...G,headers:D([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}retrieve($,w,G){let{vector_store_id:W}=w;return this._client.get(U`/vector_stores/${W}/file_batches/${$}`,{...G,headers:D([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}cancel($,w,G){let{vector_store_id:W}=w;return this._client.post(U`/vector_stores/${W}/file_batches/${$}/cancel`,{...G,headers:D([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}async createAndPoll($,w,G){let W=await this.create($,w);return await this.poll($,W.id,G)}listFiles($,w,G){let{vector_store_id:W,...Y}=w;return this._client.getAPIList(U`/vector_stores/${W}/file_batches/${$}/files`,h,{query:Y,...G,headers:D([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}async poll($,w,G){let W=D([G?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":G?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:Y,response:Z}=await this.retrieve(w,{vector_store_id:$},{...G,headers:W}).withResponse();switch(Y.status){case"in_progress":let X=5000;if(G?.pollIntervalMs)X=G.pollIntervalMs;else{let J=Z.headers.get("openai-poll-after-ms");if(J){let T=parseInt(J);if(!isNaN(T))X=T}}await f1(X);break;case"failed":case"cancelled":case"completed":return Y}}}async uploadAndPoll($,{files:w,fileIds:G=[]},W){if(w==null||w.length==0)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let Y=W?.maxConcurrency??5,Z=Math.min(Y,w.length),X=this._client,J=w.values(),T=[...G];async function M(Q){for(let N of Q){let z=await X.files.create({file:N,purpose:"assistants"},W);T.push(z.id)}}let f=Array(Z).fill(J).map(M);return await Rf(f),await this.createAndPoll($,{file_ids:T})}}class w8 extends F{create($,w,G){return this._client.post(U`/vector_stores/${$}/files`,{body:w,...G,headers:D([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}retrieve($,w,G){let{vector_store_id:W}=w;return this._client.get(U`/vector_stores/${W}/files/${$}`,{...G,headers:D([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}update($,w,G){let{vector_store_id:W,...Y}=w;return this._client.post(U`/vector_stores/${W}/files/${$}`,{body:Y,...G,headers:D([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}list($,w={},G){return this._client.getAPIList(U`/vector_stores/${$}/files`,h,{query:w,...G,headers:D([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}delete($,w,G){let{vector_store_id:W}=w;return this._client.delete(U`/vector_stores/${W}/files/${$}`,{...G,headers:D([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}async createAndPoll($,w,G){let W=await this.create($,w,G);return await this.poll($,W.id,G)}async poll($,w,G){let W=D([G?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":G?.pollIntervalMs?.toString()??void 0}]);while(!0){let Y=await this.retrieve(w,{vector_store_id:$},{...G,headers:W}).withResponse(),Z=Y.data;switch(Z.status){case"in_progress":let X=5000;if(G?.pollIntervalMs)X=G.pollIntervalMs;else{let J=Y.response.headers.get("openai-poll-after-ms");if(J){let T=parseInt(J);if(!isNaN(T))X=T}}await f1(X);break;case"failed":case"completed":return Z}}}async upload($,w,G){let W=await this._client.files.create({file:w,purpose:"assistants"},G);return this.create($,{file_id:W.id},G)}async uploadAndPoll($,w,G){let W=await this.upload($,w,G);return await this.poll($,W.id,G)}content($,w,G){let{vector_store_id:W}=w;return this._client.getAPIList(U`/vector_stores/${W}/files/${$}/content`,j1,{...G,headers:D([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}}class W$ extends F{constructor(){super(...arguments);this.files=new w8(this._client),this.fileBatches=new $8(this._client)}create($,w){return this._client.post("/vector_stores",{body:$,...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}retrieve($,w){return this._client.get(U`/vector_stores/${$}`,{...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}update($,w,G){return this._client.post(U`/vector_stores/${$}`,{body:w,...G,headers:D([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}list($={},w){return this._client.getAPIList("/vector_stores",h,{query:$,...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}delete($,w){return this._client.delete(U`/vector_stores/${$}`,{...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}search($,w,G){return this._client.getAPIList(U`/vector_stores/${$}/search`,j1,{body:w,method:"post",...G,headers:D([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}}W$.Files=w8;W$.FileBatches=$8;var hw,jf,Q5;class iw extends F{constructor(){super(...arguments);hw.add(this)}async unwrap($,w,G=this._client.webhookSecret,W=300){return await this.verifySignature($,w,G,W),JSON.parse($)}async verifySignature($,w,G=this._client.webhookSecret,W=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!=="function"||typeof crypto.subtle.verify!=="function")throw Error("Webhook signature verification is only supported when the `crypto` global is defined");B(this,hw,"m",jf).call(this,G);let Y=D([w]).values,Z=B(this,hw,"m",Q5).call(this,Y,"webhook-signature"),X=B(this,hw,"m",Q5).call(this,Y,"webhook-timestamp"),J=B(this,hw,"m",Q5).call(this,Y,"webhook-id"),T=parseInt(X,10);if(isNaN(T))throw new S1("Invalid webhook timestamp format");let M=Math.floor(Date.now()/1000);if(M-T>W)throw new S1("Webhook timestamp is too old");if(T>M+W)throw new S1("Webhook timestamp is too new");let f=Z.split(" ").map((K)=>K.startsWith("v1,")?K.substring(3):K),Q=G.startsWith("whsec_")?Buffer.from(G.replace("whsec_",""),"base64"):Buffer.from(G,"utf-8"),N=J?`${J}.${X}.${$}`:`${X}.${$}`,z=await crypto.subtle.importKey("raw",Q,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let K of f)try{let P=Buffer.from(K,"base64");if(await crypto.subtle.verify("HMAC",z,P,new TextEncoder().encode(N)))return}catch{continue}throw new S1("The given webhook signature does not match the expected signature")}}hw=new WeakSet,jf=function(w){if(typeof w!=="string"||w.length===0)throw Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},Q5=function(w,G){if(!w)throw Error("Headers are required");let W=w.get(G);if(W===null||W===void 0)throw Error(`Missing required header: ${G}`);return W};var q3,E3,N5,Cf;class g{constructor({baseURL:$=$$("OPENAI_BASE_URL"),apiKey:w=$$("OPENAI_API_KEY"),organization:G=$$("OPENAI_ORG_ID")??null,project:W=$$("OPENAI_PROJECT_ID")??null,webhookSecret:Y=$$("OPENAI_WEBHOOK_SECRET")??null,...Z}={}){if(q3.add(this),N5.set(this,void 0),this.completions=new Sw(this),this.chat=new S$(this),this.embeddings=new jw(this),this.files=new yw(this),this.images=new _w(this),this.audio=new I1(this),this.moderations=new vw(this),this.models=new gw(this),this.fineTuning=new z1(this),this.graders=new g$(this),this.vectorStores=new W$(this),this.webhooks=new iw(this),this.beta=new b1(this),this.batches=new Dw(this),this.uploads=new h$(this),this.responses=new u$(this),this.realtime=new v$(this),this.conversations=new x$(this),this.evals=new _$(this),this.containers=new b$(this),w===void 0)throw new k("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");let X={apiKey:w,organization:G,project:W,webhookSecret:Y,...Z,baseURL:$||"https://api.openai.com/v1"};if(!X.dangerouslyAllowBrowser&&xM())throw new k(`It looks like you're running in a browser-like environment.
321
+ ${J}
322
+ ${M}`)}return J},E=Lg(yN);class M4 extends R{list($,w={},G){return this._client.getAPIList(E`/chat/completions/${$}/messages`,m,{query:w,...G})}}function u8($){return $!==void 0&&"function"in $&&$.function!==void 0}function h8($){return $?.$brand==="auto-parseable-response-format"}function Xw($){return $?.$brand==="auto-parseable-tool"}function _N($,w){if(!w||!FY(w))return{...$,choices:$.choices.map((G)=>{return gN(G.message.tool_calls),{...G,message:{...G.message,parsed:null,...G.message.tool_calls?{tool_calls:G.message.tool_calls}:void 0}}})};return v8($,w)}function v8($,w){let G=$.choices.map((Z)=>{if(Z.finish_reason==="length")throw new C8;if(Z.finish_reason==="content_filter")throw new b8;return gN(Z.message.tool_calls),{...Z,message:{...Z.message,...Z.message.tool_calls?{tool_calls:Z.message.tool_calls?.map((X)=>Rg(w,X))??void 0}:void 0,parsed:Z.message.content&&!Z.message.refusal?Ag(w,Z.message.content):null}}});return{...$,choices:G}}function Ag($,w){if($.response_format?.type!=="json_schema")return null;if($.response_format?.type==="json_schema"){if("$parseRaw"in $.response_format)return $.response_format.$parseRaw(w);return JSON.parse(w)}return null}function Rg($,w){let G=$.tools?.find((Z)=>u8(Z)&&Z.function?.name===w.function.name);return{...w,function:{...w.function,parsed_arguments:Xw(G)?G.$parseRaw(w.function.arguments):G?.function.strict?JSON.parse(w.function.arguments):null}}}function xN($,w){if(!$||!("tools"in $)||!$.tools)return!1;let G=$.tools?.find((Z)=>u8(Z)&&Z.function?.name===w.function.name);return u8(G)&&(Xw(G)||G?.function.strict||!1)}function FY($){if(h8($.response_format))return!0;return $.tools?.some((w)=>Xw(w)||w.type==="function"&&w.function.strict===!0)??!1}function gN($){for(let w of $||[])if(w.type!=="function")throw new j(`Currently only \`function\` tool calls are supported; Received \`${w.type}\``)}function uN($){for(let w of $??[]){if(w.type!=="function")throw new j(`Currently only \`function\` tool types support auto-parsing; Received \`${w.type}\``);if(w.function.strict!==!0)throw new j(`The \`${w.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var P4=($)=>{return $?.role==="assistant"},OY=($)=>{return $?.role==="tool"};var fY,tG,oG,i8,m8,eG,l8,d$,d8,$3,w3,q4,hN;class Yw{constructor(){fY.add(this),this.controller=new AbortController,tG.set(this,void 0),oG.set(this,()=>{}),i8.set(this,()=>{}),m8.set(this,void 0),eG.set(this,()=>{}),l8.set(this,()=>{}),d$.set(this,{}),d8.set(this,!1),$3.set(this,!1),w3.set(this,!1),q4.set(this,!1),k(this,tG,new Promise(($,w)=>{k(this,oG,$,"f"),k(this,i8,w,"f")}),"f"),k(this,m8,new Promise(($,w)=>{k(this,eG,$,"f"),k(this,l8,w,"f")}),"f"),H(this,tG,"f").catch(()=>{}),H(this,m8,"f").catch(()=>{})}_run($){setTimeout(()=>{$().then(()=>{this._emitFinal(),this._emit("end")},H(this,fY,"m",hN).bind(this))},0)}_connected(){if(this.ended)return;H(this,oG,"f").call(this),this._emit("connect")}get ended(){return H(this,d8,"f")}get errored(){return H(this,$3,"f")}get aborted(){return H(this,w3,"f")}abort(){this.controller.abort()}on($,w){return(H(this,d$,"f")[$]||(H(this,d$,"f")[$]=[])).push({listener:w}),this}off($,w){let G=H(this,d$,"f")[$];if(!G)return this;let Z=G.findIndex((X)=>X.listener===w);if(Z>=0)G.splice(Z,1);return this}once($,w){return(H(this,d$,"f")[$]||(H(this,d$,"f")[$]=[])).push({listener:w,once:!0}),this}emitted($){return new Promise((w,G)=>{if(k(this,q4,!0,"f"),$!=="error")this.once("error",G);this.once($,w)})}async done(){k(this,q4,!0,"f"),await H(this,m8,"f")}_emit($,...w){if(H(this,d8,"f"))return;if($==="end")k(this,d8,!0,"f"),H(this,eG,"f").call(this);let G=H(this,d$,"f")[$];if(G)H(this,d$,"f")[$]=G.filter((Z)=>!Z.once),G.forEach(({listener:Z})=>Z(...w));if($==="abort"){let Z=w[0];if(!H(this,q4,"f")&&!G?.length)Promise.reject(Z);H(this,i8,"f").call(this,Z),H(this,l8,"f").call(this,Z),this._emit("end");return}if($==="error"){let Z=w[0];if(!H(this,q4,"f")&&!G?.length)Promise.reject(Z);H(this,i8,"f").call(this,Z),H(this,l8,"f").call(this,Z),this._emit("end")}}_emitFinal(){}}tG=new WeakMap,oG=new WeakMap,i8=new WeakMap,m8=new WeakMap,eG=new WeakMap,l8=new WeakMap,d$=new WeakMap,d8=new WeakMap,$3=new WeakMap,w3=new WeakMap,q4=new WeakMap,fY=new WeakSet,hN=function(w){if(k(this,$3,!0,"f"),w instanceof Error&&w.name==="AbortError")w=new q0;if(w instanceof q0)return k(this,w3,!0,"f"),this._emit("abort",w);if(w instanceof j)return this._emit("error",w);if(w instanceof Error){let G=new j(w.message);return G.cause=w,this._emit("error",G)}return this._emit("error",new j(String(w)))};function vN($){return typeof $.parse==="function"}var S0,LY,G3,DY,EY,AY,iN,mN,Sg=10;class c8 extends Yw{constructor(){super(...arguments);S0.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion($){this._chatCompletions.push($),this._emit("chatCompletion",$);let w=$.choices[0]?.message;if(w)this._addMessage(w);return $}_addMessage($,w=!0){if(!("content"in $))$.content=null;if(this.messages.push($),w){if(this._emit("message",$),OY($)&&$.content)this._emit("functionToolCallResult",$.content);else if(P4($)&&$.tool_calls){for(let G of $.tool_calls)if(G.type==="function")this._emit("functionToolCall",G.function)}}}async finalChatCompletion(){await this.done();let $=this._chatCompletions[this._chatCompletions.length-1];if(!$)throw new j("stream ended without producing a ChatCompletion");return $}async finalContent(){return await this.done(),H(this,S0,"m",LY).call(this)}async finalMessage(){return await this.done(),H(this,S0,"m",G3).call(this)}async finalFunctionToolCall(){return await this.done(),H(this,S0,"m",DY).call(this)}async finalFunctionToolCallResult(){return await this.done(),H(this,S0,"m",EY).call(this)}async totalUsage(){return await this.done(),H(this,S0,"m",AY).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let $=this._chatCompletions[this._chatCompletions.length-1];if($)this._emit("finalChatCompletion",$);let w=H(this,S0,"m",G3).call(this);if(w)this._emit("finalMessage",w);let G=H(this,S0,"m",LY).call(this);if(G)this._emit("finalContent",G);let Z=H(this,S0,"m",DY).call(this);if(Z)this._emit("finalFunctionToolCall",Z);let X=H(this,S0,"m",EY).call(this);if(X!=null)this._emit("finalFunctionToolCallResult",X);if(this._chatCompletions.some((Y)=>Y.usage))this._emit("totalUsage",H(this,S0,"m",AY).call(this))}async _createChatCompletion($,w,G){let Z=G?.signal;if(Z){if(Z.aborted)this.controller.abort();Z.addEventListener("abort",()=>this.controller.abort())}H(this,S0,"m",iN).call(this,w);let X=await $.chat.completions.create({...w,stream:!1},{...G,signal:this.controller.signal});return this._connected(),this._addChatCompletion(v8(X,w))}async _runChatCompletion($,w,G){for(let Z of w.messages)this._addMessage(Z,!1);return await this._createChatCompletion($,w,G)}async _runTools($,w,G){let{tool_choice:X="auto",stream:Y,...J}=w,W=typeof X!=="string"&&X.type==="function"&&X?.function?.name,{maxChatCompletions:T=Sg}=G||{},Q=w.tools.map((P)=>{if(Xw(P)){if(!P.$callback)throw new j("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:P.$callback,name:P.function.name,description:P.function.description||"",parameters:P.function.parameters,parse:P.$parseRaw,strict:!0}}}return P}),z={};for(let P of Q)if(P.type==="function")z[P.function.name||P.function.function.name]=P.function;let M="tools"in w?Q.map((P)=>P.type==="function"?{type:"function",function:{name:P.function.name||P.function.function.name,parameters:P.function.parameters,description:P.function.description,strict:P.function.strict}}:P):void 0;for(let P of w.messages)this._addMessage(P,!1);for(let P=0;P<T;++P){let N=(await this._createChatCompletion($,{...J,tool_choice:X,tools:M,messages:[...this.messages]},G)).choices[0]?.message;if(!N)throw new j("missing message in ChatCompletion response");if(!N.tool_calls?.length)return;for(let B of N.tool_calls){if(B.type!=="function")continue;let V=B.id,{name:K,arguments:U}=B.function,O=z[K];if(!O){let C=`Invalid tool_call: ${JSON.stringify(K)}. Available options are: ${Object.keys(z).map((S)=>JSON.stringify(S)).join(", ")}. Please try again`;this._addMessage({role:"tool",tool_call_id:V,content:C});continue}else if(W&&W!==K){let C=`Invalid tool_call: ${JSON.stringify(K)}. ${JSON.stringify(W)} requested. Please try again`;this._addMessage({role:"tool",tool_call_id:V,content:C});continue}let D;try{D=vN(O)?await O.parse(U):U}catch(C){let S=C instanceof Error?C.message:String(C);this._addMessage({role:"tool",tool_call_id:V,content:S});continue}let f=await O.function(D,this),L=H(this,S0,"m",mN).call(this,f);if(this._addMessage({role:"tool",tool_call_id:V,content:L}),W)return}}return}}S0=new WeakSet,LY=function(){return H(this,S0,"m",G3).call(this).content??null},G3=function(){let w=this.messages.length;while(w-- >0){let G=this.messages[w];if(P4(G))return{...G,content:G.content??null,refusal:G.refusal??null}}throw new j("stream ended without producing a ChatCompletionMessage with role=assistant")},DY=function(){for(let w=this.messages.length-1;w>=0;w--){let G=this.messages[w];if(P4(G)&&G?.tool_calls?.length)return G.tool_calls.filter((Z)=>Z.type==="function").at(-1)?.function}return},EY=function(){for(let w=this.messages.length-1;w>=0;w--){let G=this.messages[w];if(OY(G)&&G.content!=null&&typeof G.content==="string"&&this.messages.some((Z)=>Z.role==="assistant"&&Z.tool_calls?.some((X)=>X.type==="function"&&X.id===G.tool_call_id)))return G.content}return},AY=function(){let w={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:G}of this._chatCompletions)if(G)w.completion_tokens+=G.completion_tokens,w.prompt_tokens+=G.prompt_tokens,w.total_tokens+=G.total_tokens;return w},iN=function(w){if(w.n!=null&&w.n>1)throw new j("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},mN=function(w){return typeof w==="string"?w:w===void 0?"undefined":JSON.stringify(w)};class p8 extends c8{static runTools($,w,G){let Z=new p8,X={...G,headers:{...G?.headers,"X-Stainless-Helper-Method":"runTools"}};return Z._run(()=>Z._runTools($,w,X)),Z}_addMessage($,w=!0){if(super._addMessage($,w),P4($)&&$.content)this._emit("content",$.content)}}var K0={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511};class lN extends Error{}class dN extends Error{}function Ig($,w=K0.ALL){if(typeof $!=="string")throw TypeError(`expecting str, got ${typeof $}`);if(!$.trim())throw Error(`${$} is empty`);return jg($.trim(),w)}var jg=($,w)=>{let G=$.length,Z=0,X=(P)=>{throw new lN(`${P} at position ${Z}`)},Y=(P)=>{throw new dN(`${P} at position ${Z}`)},J=()=>{if(M(),Z>=G)X("Unexpected end of input");if($[Z]==='"')return W();if($[Z]==="{")return T();if($[Z]==="[")return Q();if($.substring(Z,Z+4)==="null"||K0.NULL&w&&G-Z<4&&"null".startsWith($.substring(Z)))return Z+=4,null;if($.substring(Z,Z+4)==="true"||K0.BOOL&w&&G-Z<4&&"true".startsWith($.substring(Z)))return Z+=4,!0;if($.substring(Z,Z+5)==="false"||K0.BOOL&w&&G-Z<5&&"false".startsWith($.substring(Z)))return Z+=5,!1;if($.substring(Z,Z+8)==="Infinity"||K0.INFINITY&w&&G-Z<8&&"Infinity".startsWith($.substring(Z)))return Z+=8,1/0;if($.substring(Z,Z+9)==="-Infinity"||K0.MINUS_INFINITY&w&&1<G-Z&&G-Z<9&&"-Infinity".startsWith($.substring(Z)))return Z+=9,-1/0;if($.substring(Z,Z+3)==="NaN"||K0.NAN&w&&G-Z<3&&"NaN".startsWith($.substring(Z)))return Z+=3,NaN;return z()},W=()=>{let P=Z,q=!1;Z++;while(Z<G&&($[Z]!=='"'||q&&$[Z-1]==="\\"))q=$[Z]==="\\"?!q:!1,Z++;if($.charAt(Z)=='"')try{return JSON.parse($.substring(P,++Z-Number(q)))}catch(N){Y(String(N))}else if(K0.STR&w)try{return JSON.parse($.substring(P,Z-Number(q))+'"')}catch(N){return JSON.parse($.substring(P,$.lastIndexOf("\\"))+'"')}X("Unterminated string literal")},T=()=>{Z++,M();let P={};try{while($[Z]!=="}"){if(M(),Z>=G&&K0.OBJ&w)return P;let q=W();M(),Z++;try{let N=J();Object.defineProperty(P,q,{value:N,writable:!0,enumerable:!0,configurable:!0})}catch(N){if(K0.OBJ&w)return P;else throw N}if(M(),$[Z]===",")Z++}}catch(q){if(K0.OBJ&w)return P;else X("Expected '}' at end of object")}return Z++,P},Q=()=>{Z++;let P=[];try{while($[Z]!=="]")if(P.push(J()),M(),$[Z]===",")Z++}catch(q){if(K0.ARR&w)return P;X("Expected ']' at end of array")}return Z++,P},z=()=>{if(Z===0){if($==="-"&&K0.NUM&w)X("Not sure what '-' is");try{return JSON.parse($)}catch(q){if(K0.NUM&w)try{if($[$.length-1]===".")return JSON.parse($.substring(0,$.lastIndexOf(".")));return JSON.parse($.substring(0,$.lastIndexOf("e")))}catch(N){}Y(String(q))}}let P=Z;if($[Z]==="-")Z++;while($[Z]&&!",]}".includes($[Z]))Z++;if(Z==G&&!(K0.NUM&w))X("Unterminated number literal");try{return JSON.parse($.substring(P,Z))}catch(q){if($.substring(P,Z)==="-"&&K0.NUM&w)X("Not sure what '-' is");try{return JSON.parse($.substring(P,$.lastIndexOf("e")))}catch(N){Y(String(N))}}},M=()=>{while(Z<G&&`
323
+ \r `.includes($[Z]))Z++};return J()},RY=($)=>Ig($,K0.ALL^K0.NUM);var N0,c$,B4,H1,SY,Z3,IY,jY,CY,X3,bY,cN;class F1 extends c8{constructor($){super();N0.add(this),c$.set(this,void 0),B4.set(this,void 0),H1.set(this,void 0),k(this,c$,$,"f"),k(this,B4,[],"f")}get currentChatCompletionSnapshot(){return H(this,H1,"f")}static fromReadableStream($){let w=new F1(null);return w._run(()=>w._fromReadableStream($)),w}static createChatCompletion($,w,G){let Z=new F1(w);return Z._run(()=>Z._runChatCompletion($,{...w,stream:!0},{...G,headers:{...G?.headers,"X-Stainless-Helper-Method":"stream"}})),Z}async _createChatCompletion($,w,G){super._createChatCompletion;let Z=G?.signal;if(Z){if(Z.aborted)this.controller.abort();Z.addEventListener("abort",()=>this.controller.abort())}H(this,N0,"m",SY).call(this);let X=await $.chat.completions.create({...w,stream:!0},{...G,signal:this.controller.signal});this._connected();for await(let Y of X)H(this,N0,"m",IY).call(this,Y);if(X.controller.signal?.aborted)throw new q0;return this._addChatCompletion(H(this,N0,"m",X3).call(this))}async _fromReadableStream($,w){let G=w?.signal;if(G){if(G.aborted)this.controller.abort();G.addEventListener("abort",()=>this.controller.abort())}H(this,N0,"m",SY).call(this),this._connected();let Z=i0.fromReadableStream($,this.controller),X;for await(let Y of Z){if(X&&X!==Y.id)this._addChatCompletion(H(this,N0,"m",X3).call(this));H(this,N0,"m",IY).call(this,Y),X=Y.id}if(Z.controller.signal?.aborted)throw new q0;return this._addChatCompletion(H(this,N0,"m",X3).call(this))}[(c$=new WeakMap,B4=new WeakMap,H1=new WeakMap,N0=new WeakSet,SY=function(){if(this.ended)return;k(this,H1,void 0,"f")},Z3=function(w){let G=H(this,B4,"f")[w.index];if(G)return G;return G={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},H(this,B4,"f")[w.index]=G,G},IY=function(w){if(this.ended)return;let G=H(this,N0,"m",cN).call(this,w);this._emit("chunk",w,G);for(let Z of w.choices){let X=G.choices[Z.index];if(Z.delta.content!=null&&X.message?.role==="assistant"&&X.message?.content)this._emit("content",Z.delta.content,X.message.content),this._emit("content.delta",{delta:Z.delta.content,snapshot:X.message.content,parsed:X.message.parsed});if(Z.delta.refusal!=null&&X.message?.role==="assistant"&&X.message?.refusal)this._emit("refusal.delta",{delta:Z.delta.refusal,snapshot:X.message.refusal});if(Z.logprobs?.content!=null&&X.message?.role==="assistant")this._emit("logprobs.content.delta",{content:Z.logprobs?.content,snapshot:X.logprobs?.content??[]});if(Z.logprobs?.refusal!=null&&X.message?.role==="assistant")this._emit("logprobs.refusal.delta",{refusal:Z.logprobs?.refusal,snapshot:X.logprobs?.refusal??[]});let Y=H(this,N0,"m",Z3).call(this,X);if(X.finish_reason){if(H(this,N0,"m",CY).call(this,X),Y.current_tool_call_index!=null)H(this,N0,"m",jY).call(this,X,Y.current_tool_call_index)}for(let J of Z.delta.tool_calls??[]){if(Y.current_tool_call_index!==J.index){if(H(this,N0,"m",CY).call(this,X),Y.current_tool_call_index!=null)H(this,N0,"m",jY).call(this,X,Y.current_tool_call_index)}Y.current_tool_call_index=J.index}for(let J of Z.delta.tool_calls??[]){let W=X.message.tool_calls?.[J.index];if(!W?.type)continue;if(W?.type==="function")this._emit("tool_calls.function.arguments.delta",{name:W.function?.name,index:J.index,arguments:W.function.arguments,parsed_arguments:W.function.parsed_arguments,arguments_delta:J.function?.arguments??""});else nN(W?.type)}}},jY=function(w,G){if(H(this,N0,"m",Z3).call(this,w).done_tool_calls.has(G))return;let X=w.message.tool_calls?.[G];if(!X)throw Error("no tool call snapshot");if(!X.type)throw Error("tool call snapshot missing `type`");if(X.type==="function"){let Y=H(this,c$,"f")?.tools?.find((J)=>u8(J)&&J.function.name===X.function.name);this._emit("tool_calls.function.arguments.done",{name:X.function.name,index:G,arguments:X.function.arguments,parsed_arguments:Xw(Y)?Y.$parseRaw(X.function.arguments):Y?.function.strict?JSON.parse(X.function.arguments):null})}else nN(X.type)},CY=function(w){let G=H(this,N0,"m",Z3).call(this,w);if(w.message.content&&!G.content_done){G.content_done=!0;let Z=H(this,N0,"m",bY).call(this);this._emit("content.done",{content:w.message.content,parsed:Z?Z.$parseRaw(w.message.content):null})}if(w.message.refusal&&!G.refusal_done)G.refusal_done=!0,this._emit("refusal.done",{refusal:w.message.refusal});if(w.logprobs?.content&&!G.logprobs_content_done)G.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:w.logprobs.content});if(w.logprobs?.refusal&&!G.logprobs_refusal_done)G.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:w.logprobs.refusal})},X3=function(){if(this.ended)throw new j("stream has ended, this shouldn't happen");let w=H(this,H1,"f");if(!w)throw new j("request ended without sending any chunks");return k(this,H1,void 0,"f"),k(this,B4,[],"f"),Cg(w,H(this,c$,"f"))},bY=function(){let w=H(this,c$,"f")?.response_format;if(h8(w))return w;return null},cN=function(w){var G,Z,X,Y;let J=H(this,H1,"f"),{choices:W,...T}=w;if(!J)J=k(this,H1,{...T,choices:[]},"f");else Object.assign(J,T);for(let{delta:Q,finish_reason:z,index:M,logprobs:P=null,...q}of w.choices){let N=J.choices[M];if(!N)N=J.choices[M]={finish_reason:z,index:M,message:{},logprobs:P,...q};if(P)if(!N.logprobs)N.logprobs=Object.assign({},P);else{let{content:f,refusal:L,...C}=P;if(pN(C),Object.assign(N.logprobs,C),f)(G=N.logprobs).content??(G.content=[]),N.logprobs.content.push(...f);if(L)(Z=N.logprobs).refusal??(Z.refusal=[]),N.logprobs.refusal.push(...L)}if(z){if(N.finish_reason=z,H(this,c$,"f")&&FY(H(this,c$,"f"))){if(z==="length")throw new C8;if(z==="content_filter")throw new b8}}if(Object.assign(N,q),!Q)continue;let{content:B,refusal:V,function_call:K,role:U,tool_calls:O,...D}=Q;if(pN(D),Object.assign(N.message,D),V)N.message.refusal=(N.message.refusal||"")+V;if(U)N.message.role=U;if(K)if(!N.message.function_call)N.message.function_call=K;else{if(K.name)N.message.function_call.name=K.name;if(K.arguments)(X=N.message.function_call).arguments??(X.arguments=""),N.message.function_call.arguments+=K.arguments}if(B){if(N.message.content=(N.message.content||"")+B,!N.message.refusal&&H(this,N0,"m",bY).call(this))N.message.parsed=RY(N.message.content)}if(O){if(!N.message.tool_calls)N.message.tool_calls=[];for(let{index:f,id:L,type:C,function:S,...h}of O){let g=(Y=N.message.tool_calls)[f]??(Y[f]={});if(Object.assign(g,h),L)g.id=L;if(C)g.type=C;if(S)g.function??(g.function={name:S.name??"",arguments:""});if(S?.name)g.function.name=S.name;if(S?.arguments){if(g.function.arguments+=S.arguments,xN(H(this,c$,"f"),g))g.function.parsed_arguments=RY(g.function.arguments)}}}}return J},Symbol.asyncIterator)](){let $=[],w=[],G=!1;return this.on("chunk",(Z)=>{let X=w.shift();if(X)X.resolve(Z);else $.push(Z)}),this.on("end",()=>{G=!0;for(let Z of w)Z.resolve(void 0);w.length=0}),this.on("abort",(Z)=>{G=!0;for(let X of w)X.reject(Z);w.length=0}),this.on("error",(Z)=>{G=!0;for(let X of w)X.reject(Z);w.length=0}),{next:async()=>{if(!$.length){if(G)return{value:void 0,done:!0};return new Promise((X,Y)=>w.push({resolve:X,reject:Y})).then((X)=>X?{value:X,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new i0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function Cg($,w){let{id:G,choices:Z,created:X,model:Y,system_fingerprint:J,...W}=$,T={...W,id:G,choices:Z.map(({message:Q,finish_reason:z,index:M,logprobs:P,...q})=>{if(!z)throw new j(`missing finish_reason for choice ${M}`);let{content:N=null,function_call:B,tool_calls:V,...K}=Q,U=Q.role;if(!U)throw new j(`missing role for choice ${M}`);if(B){let{arguments:O,name:D}=B;if(O==null)throw new j(`missing function_call.arguments for choice ${M}`);if(!D)throw new j(`missing function_call.name for choice ${M}`);return{...q,message:{content:N,function_call:{arguments:O,name:D},role:U,refusal:Q.refusal??null},finish_reason:z,index:M,logprobs:P}}if(V)return{...q,index:M,finish_reason:z,logprobs:P,message:{...K,role:U,content:N,refusal:Q.refusal??null,tool_calls:V.map((O,D)=>{let{function:f,type:L,id:C,...S}=O,{arguments:h,name:g,...G0}=f||{};if(C==null)throw new j(`missing choices[${M}].tool_calls[${D}].id
324
+ ${Y3($)}`);if(L==null)throw new j(`missing choices[${M}].tool_calls[${D}].type
325
+ ${Y3($)}`);if(g==null)throw new j(`missing choices[${M}].tool_calls[${D}].function.name
326
+ ${Y3($)}`);if(h==null)throw new j(`missing choices[${M}].tool_calls[${D}].function.arguments
327
+ ${Y3($)}`);return{...S,id:C,type:L,function:{...G0,name:g,arguments:h}}})}};return{...q,message:{...K,content:N,role:U,refusal:Q.refusal??null},finish_reason:z,index:M,logprobs:P}}),created:X,model:Y,object:"chat.completion",...J?{system_fingerprint:J}:{}};return _N(T,w)}function Y3($){return JSON.stringify($)}function pN($){return}function nN($){}class N4 extends F1{static fromReadableStream($){let w=new N4(null);return w._run(()=>w._fromReadableStream($)),w}static runTools($,w,G){let Z=new N4(w),X={...G,headers:{...G?.headers,"X-Stainless-Helper-Method":"runTools"}};return Z._run(()=>Z._runTools($,w,X)),Z}}class O1 extends R{constructor(){super(...arguments);this.messages=new M4(this._client)}create($,w){return this._client.post("/chat/completions",{body:$,...w,stream:$.stream??!1})}retrieve($,w){return this._client.get(E`/chat/completions/${$}`,w)}update($,w,G){return this._client.post(E`/chat/completions/${$}`,{body:w,...G})}list($={},w){return this._client.getAPIList("/chat/completions",m,{query:$,...w})}delete($,w){return this._client.delete(E`/chat/completions/${$}`,w)}parse($,w){return uN($.tools),this._client.chat.completions.create($,{...w,headers:{...w?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap((G)=>v8(G,$))}runTools($,w){if($.stream)return N4.runTools(this._client,$,w);return p8.runTools(this._client,$,w)}stream($,w){return F1.createChatCompletion(this._client,$,w)}}O1.Messages=M4;class Jw extends R{constructor(){super(...arguments);this.completions=new O1(this._client)}}Jw.Completions=O1;var rN=Symbol("brand.privateNullableHeaders");function*kg($){if(!$)return;if(rN in $){let{values:Z,nulls:X}=$;yield*Z.entries();for(let Y of X)yield[Y,null];return}let w=!1,G;if($ instanceof Headers)G=$.entries();else if(GY($))G=$;else w=!0,G=Object.entries($??{});for(let Z of G){let X=Z[0];if(typeof X!=="string")throw TypeError("expected header name to be a string");let Y=GY(Z[1])?Z[1]:[Z[1]],J=!1;for(let W of Y){if(W===void 0)continue;if(w&&!J)J=!0,yield[X,null];yield[X,W]}}}var I=($)=>{let w=new Headers,G=new Set;for(let Z of $){let X=new Set;for(let[Y,J]of kg(Z)){let W=Y.toLowerCase();if(!X.has(W))w.delete(Y),X.add(W);if(J===null)w.delete(Y),G.add(W);else w.append(Y,J),G.delete(W)}}return{[rN]:!0,values:w,nulls:G}};class n8 extends R{create($,w){return this._client.post("/audio/speech",{body:$,...w,headers:I([{Accept:"application/octet-stream"},w?.headers]),__binaryResponse:!0})}}class r8 extends R{create($,w){return this._client.post("/audio/transcriptions",m0({body:$,...w,stream:$.stream??!1,__metadata:{model:$.model}},this._client))}}class s8 extends R{create($,w){return this._client.post("/audio/translations",m0({body:$,...w,__metadata:{model:$.model}},this._client))}}class p$ extends R{constructor(){super(...arguments);this.transcriptions=new r8(this._client),this.translations=new s8(this._client),this.speech=new n8(this._client)}}p$.Transcriptions=r8;p$.Translations=s8;p$.Speech=n8;class V4 extends R{create($,w){return this._client.post("/batches",{body:$,...w})}retrieve($,w){return this._client.get(E`/batches/${$}`,w)}list($={},w){return this._client.getAPIList("/batches",m,{query:$,...w})}cancel($,w){return this._client.post(E`/batches/${$}/cancel`,w)}}class a8 extends R{create($,w){return this._client.post("/assistants",{body:$,...w,headers:I([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}retrieve($,w){return this._client.get(E`/assistants/${$}`,{...w,headers:I([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}update($,w,G){return this._client.post(E`/assistants/${$}`,{body:w,...G,headers:I([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}list($={},w){return this._client.getAPIList("/assistants",m,{query:$,...w,headers:I([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}delete($,w){return this._client.delete(E`/assistants/${$}`,{...w,headers:I([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}}class t8 extends R{create($,w){return this._client.post("/realtime/sessions",{body:$,...w,headers:I([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}}class o8 extends R{create($,w){return this._client.post("/realtime/transcription_sessions",{body:$,...w,headers:I([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}}class Ww extends R{constructor(){super(...arguments);this.sessions=new t8(this._client),this.transcriptionSessions=new o8(this._client)}}Ww.Sessions=t8;Ww.TranscriptionSessions=o8;class e8 extends R{create($,w,G){return this._client.post(E`/threads/${$}/messages`,{body:w,...G,headers:I([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}retrieve($,w,G){let{thread_id:Z}=w;return this._client.get(E`/threads/${Z}/messages/${$}`,{...G,headers:I([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}update($,w,G){let{thread_id:Z,...X}=w;return this._client.post(E`/threads/${Z}/messages/${$}`,{body:X,...G,headers:I([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}list($,w={},G){return this._client.getAPIList(E`/threads/${$}/messages`,m,{query:w,...G,headers:I([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}delete($,w,G){let{thread_id:Z}=w;return this._client.delete(E`/threads/${Z}/messages/${$}`,{...G,headers:I([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}}class $6 extends R{retrieve($,w,G){let{thread_id:Z,run_id:X,...Y}=w;return this._client.get(E`/threads/${Z}/runs/${X}/steps/${$}`,{query:Y,...G,headers:I([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}list($,w,G){let{thread_id:Z,...X}=w;return this._client.getAPIList(E`/threads/${Z}/runs/${$}/steps`,m,{query:X,...G,headers:I([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}}var sN=($)=>{if(typeof Buffer<"u"){let w=Buffer.from($,"base64");return Array.from(new Float32Array(w.buffer,w.byteOffset,w.length/Float32Array.BYTES_PER_ELEMENT))}else{let w=atob($),G=w.length,Z=new Uint8Array(G);for(let X=0;X<G;X++)Z[X]=w.charCodeAt(X);return Array.from(new Float32Array(Z.buffer))}};var f1=($)=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[$]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.($)?.trim();return};var H0,Qw,kY,f$,J3,z$,zw,K4,Tw,Q3,l0,W3,T3,Z6,w6,G6,aN,tN,oN,eN,$V,wV,GV;class L1 extends Yw{constructor(){super(...arguments);H0.add(this),kY.set(this,[]),f$.set(this,{}),J3.set(this,{}),z$.set(this,void 0),zw.set(this,void 0),K4.set(this,void 0),Tw.set(this,void 0),Q3.set(this,void 0),l0.set(this,void 0),W3.set(this,void 0),T3.set(this,void 0),Z6.set(this,void 0)}[(kY=new WeakMap,f$=new WeakMap,J3=new WeakMap,z$=new WeakMap,zw=new WeakMap,K4=new WeakMap,Tw=new WeakMap,Q3=new WeakMap,l0=new WeakMap,W3=new WeakMap,T3=new WeakMap,Z6=new WeakMap,H0=new WeakSet,Symbol.asyncIterator)](){let $=[],w=[],G=!1;return this.on("event",(Z)=>{let X=w.shift();if(X)X.resolve(Z);else $.push(Z)}),this.on("end",()=>{G=!0;for(let Z of w)Z.resolve(void 0);w.length=0}),this.on("abort",(Z)=>{G=!0;for(let X of w)X.reject(Z);w.length=0}),this.on("error",(Z)=>{G=!0;for(let X of w)X.reject(Z);w.length=0}),{next:async()=>{if(!$.length){if(G)return{value:void 0,done:!0};return new Promise((X,Y)=>w.push({resolve:X,reject:Y})).then((X)=>X?{value:X,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}static fromReadableStream($){let w=new Qw;return w._run(()=>w._fromReadableStream($)),w}async _fromReadableStream($,w){let G=w?.signal;if(G){if(G.aborted)this.controller.abort();G.addEventListener("abort",()=>this.controller.abort())}this._connected();let Z=i0.fromReadableStream($,this.controller);for await(let X of Z)H(this,H0,"m",w6).call(this,X);if(Z.controller.signal?.aborted)throw new q0;return this._addRun(H(this,H0,"m",G6).call(this))}toReadableStream(){return new i0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream($,w,G,Z){let X=new Qw;return X._run(()=>X._runToolAssistantStream($,w,G,{...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"stream"}})),X}async _createToolAssistantStream($,w,G,Z){let X=Z?.signal;if(X){if(X.aborted)this.controller.abort();X.addEventListener("abort",()=>this.controller.abort())}let Y={...G,stream:!0},J=await $.submitToolOutputs(w,Y,{...Z,signal:this.controller.signal});this._connected();for await(let W of J)H(this,H0,"m",w6).call(this,W);if(J.controller.signal?.aborted)throw new q0;return this._addRun(H(this,H0,"m",G6).call(this))}static createThreadAssistantStream($,w,G){let Z=new Qw;return Z._run(()=>Z._threadAssistantStream($,w,{...G,headers:{...G?.headers,"X-Stainless-Helper-Method":"stream"}})),Z}static createAssistantStream($,w,G,Z){let X=new Qw;return X._run(()=>X._runAssistantStream($,w,G,{...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"stream"}})),X}currentEvent(){return H(this,W3,"f")}currentRun(){return H(this,T3,"f")}currentMessageSnapshot(){return H(this,z$,"f")}currentRunStepSnapshot(){return H(this,Z6,"f")}async finalRunSteps(){return await this.done(),Object.values(H(this,f$,"f"))}async finalMessages(){return await this.done(),Object.values(H(this,J3,"f"))}async finalRun(){if(await this.done(),!H(this,zw,"f"))throw Error("Final run was not received.");return H(this,zw,"f")}async _createThreadAssistantStream($,w,G){let Z=G?.signal;if(Z){if(Z.aborted)this.controller.abort();Z.addEventListener("abort",()=>this.controller.abort())}let X={...w,stream:!0},Y=await $.createAndRun(X,{...G,signal:this.controller.signal});this._connected();for await(let J of Y)H(this,H0,"m",w6).call(this,J);if(Y.controller.signal?.aborted)throw new q0;return this._addRun(H(this,H0,"m",G6).call(this))}async _createAssistantStream($,w,G,Z){let X=Z?.signal;if(X){if(X.aborted)this.controller.abort();X.addEventListener("abort",()=>this.controller.abort())}let Y={...G,stream:!0},J=await $.create(w,Y,{...Z,signal:this.controller.signal});this._connected();for await(let W of J)H(this,H0,"m",w6).call(this,W);if(J.controller.signal?.aborted)throw new q0;return this._addRun(H(this,H0,"m",G6).call(this))}static accumulateDelta($,w){for(let[G,Z]of Object.entries(w)){if(!$.hasOwnProperty(G)){$[G]=Z;continue}let X=$[G];if(X===null||X===void 0){$[G]=Z;continue}if(G==="index"||G==="type"){$[G]=Z;continue}if(typeof X==="string"&&typeof Z==="string")X+=Z;else if(typeof X==="number"&&typeof Z==="number")X+=Z;else if(k8(X)&&k8(Z))X=this.accumulateDelta(X,Z);else if(Array.isArray(X)&&Array.isArray(Z)){if(X.every((Y)=>typeof Y==="string"||typeof Y==="number")){X.push(...Z);continue}for(let Y of Z){if(!k8(Y))throw Error(`Expected array delta entry to be an object but got: ${Y}`);let J=Y.index;if(J==null)throw console.error(Y),Error("Expected array delta entry to have an `index` property");if(typeof J!=="number")throw Error(`Expected array delta entry \`index\` property to be a number but got ${J}`);let W=X[J];if(W==null)X.push(Y);else X[J]=this.accumulateDelta(W,Y)}continue}else throw Error(`Unhandled record type: ${G}, deltaValue: ${Z}, accValue: ${X}`);$[G]=X}return $}_addRun($){return $}async _threadAssistantStream($,w,G){return await this._createThreadAssistantStream(w,$,G)}async _runAssistantStream($,w,G,Z){return await this._createAssistantStream(w,$,G,Z)}async _runToolAssistantStream($,w,G,Z){return await this._createToolAssistantStream(w,$,G,Z)}}Qw=L1,w6=function(w){if(this.ended)return;switch(k(this,W3,w,"f"),H(this,H0,"m",oN).call(this,w),w.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":H(this,H0,"m",GV).call(this,w);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":H(this,H0,"m",tN).call(this,w);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":H(this,H0,"m",aN).call(this,w);break;case"error":throw Error("Encountered an error event in event processing - errors should be processed earlier");default:lg(w)}},G6=function(){if(this.ended)throw new j("stream has ended, this shouldn't happen");if(!H(this,zw,"f"))throw Error("Final run has not been received");return H(this,zw,"f")},aN=function(w){let[G,Z]=H(this,H0,"m",$V).call(this,w,H(this,z$,"f"));k(this,z$,G,"f"),H(this,J3,"f")[G.id]=G;for(let X of Z){let Y=G.content[X.index];if(Y?.type=="text")this._emit("textCreated",Y.text)}switch(w.event){case"thread.message.created":this._emit("messageCreated",w.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",w.data.delta,G),w.data.delta.content)for(let X of w.data.delta.content){if(X.type=="text"&&X.text){let Y=X.text,J=G.content[X.index];if(J&&J.type=="text")this._emit("textDelta",Y,J.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(X.index!=H(this,K4,"f")){if(H(this,Tw,"f"))switch(H(this,Tw,"f").type){case"text":this._emit("textDone",H(this,Tw,"f").text,H(this,z$,"f"));break;case"image_file":this._emit("imageFileDone",H(this,Tw,"f").image_file,H(this,z$,"f"));break}k(this,K4,X.index,"f")}k(this,Tw,G.content[X.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(H(this,K4,"f")!==void 0){let X=w.data.content[H(this,K4,"f")];if(X)switch(X.type){case"image_file":this._emit("imageFileDone",X.image_file,H(this,z$,"f"));break;case"text":this._emit("textDone",X.text,H(this,z$,"f"));break}}if(H(this,z$,"f"))this._emit("messageDone",w.data);k(this,z$,void 0,"f")}},tN=function(w){let G=H(this,H0,"m",eN).call(this,w);switch(k(this,Z6,G,"f"),w.event){case"thread.run.step.created":this._emit("runStepCreated",w.data);break;case"thread.run.step.delta":let Z=w.data.delta;if(Z.step_details&&Z.step_details.type=="tool_calls"&&Z.step_details.tool_calls&&G.step_details.type=="tool_calls")for(let Y of Z.step_details.tool_calls)if(Y.index==H(this,Q3,"f"))this._emit("toolCallDelta",Y,G.step_details.tool_calls[Y.index]);else{if(H(this,l0,"f"))this._emit("toolCallDone",H(this,l0,"f"));if(k(this,Q3,Y.index,"f"),k(this,l0,G.step_details.tool_calls[Y.index],"f"),H(this,l0,"f"))this._emit("toolCallCreated",H(this,l0,"f"))}this._emit("runStepDelta",w.data.delta,G);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":if(k(this,Z6,void 0,"f"),w.data.step_details.type=="tool_calls"){if(H(this,l0,"f"))this._emit("toolCallDone",H(this,l0,"f")),k(this,l0,void 0,"f")}this._emit("runStepDone",w.data,G);break;case"thread.run.step.in_progress":break}},oN=function(w){H(this,kY,"f").push(w),this._emit("event",w)},eN=function(w){switch(w.event){case"thread.run.step.created":return H(this,f$,"f")[w.data.id]=w.data,w.data;case"thread.run.step.delta":let G=H(this,f$,"f")[w.data.id];if(!G)throw Error("Received a RunStepDelta before creation of a snapshot");let Z=w.data;if(Z.delta){let X=Qw.accumulateDelta(G,Z.delta);H(this,f$,"f")[w.data.id]=X}return H(this,f$,"f")[w.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":H(this,f$,"f")[w.data.id]=w.data;break}if(H(this,f$,"f")[w.data.id])return H(this,f$,"f")[w.data.id];throw Error("No snapshot available")},$V=function(w,G){let Z=[];switch(w.event){case"thread.message.created":return[w.data,Z];case"thread.message.delta":if(!G)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let X=w.data;if(X.delta.content)for(let Y of X.delta.content)if(Y.index in G.content){let J=G.content[Y.index];G.content[Y.index]=H(this,H0,"m",wV).call(this,Y,J)}else G.content[Y.index]=Y,Z.push(Y);return[G,Z];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(G)return[G,Z];else throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},wV=function(w,G){return Qw.accumulateDelta(G,w)},GV=function(w){switch(k(this,T3,w.data,"f"),w.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":if(k(this,zw,w.data,"f"),H(this,l0,"f"))this._emit("toolCallDone",H(this,l0,"f")),k(this,l0,void 0,"f");break;case"thread.run.cancelling":break}};function lg($){}class U4 extends R{constructor(){super(...arguments);this.steps=new $6(this._client)}create($,w,G){let{include:Z,...X}=w;return this._client.post(E`/threads/${$}/runs`,{query:{include:Z},body:X,...G,headers:I([{"OpenAI-Beta":"assistants=v2"},G?.headers]),stream:w.stream??!1})}retrieve($,w,G){let{thread_id:Z}=w;return this._client.get(E`/threads/${Z}/runs/${$}`,{...G,headers:I([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}update($,w,G){let{thread_id:Z,...X}=w;return this._client.post(E`/threads/${Z}/runs/${$}`,{body:X,...G,headers:I([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}list($,w={},G){return this._client.getAPIList(E`/threads/${$}/runs`,m,{query:w,...G,headers:I([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}cancel($,w,G){let{thread_id:Z}=w;return this._client.post(E`/threads/${Z}/runs/${$}/cancel`,{...G,headers:I([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}async createAndPoll($,w,G){let Z=await this.create($,w,G);return await this.poll(Z.id,{thread_id:$},G)}createAndStream($,w,G){return L1.createAssistantStream($,this._client.beta.threads.runs,w,G)}async poll($,w,G){let Z=I([G?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":G?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:X,response:Y}=await this.retrieve($,w,{...G,headers:{...G?.headers,...Z}}).withResponse();switch(X.status){case"queued":case"in_progress":case"cancelling":let J=5000;if(G?.pollIntervalMs)J=G.pollIntervalMs;else{let W=Y.headers.get("openai-poll-after-ms");if(W){let T=parseInt(W);if(!isNaN(T))J=T}}await F$(J);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return X}}}stream($,w,G){return L1.createAssistantStream($,this._client.beta.threads.runs,w,G)}submitToolOutputs($,w,G){let{thread_id:Z,...X}=w;return this._client.post(E`/threads/${Z}/runs/${$}/submit_tool_outputs`,{body:X,...G,headers:I([{"OpenAI-Beta":"assistants=v2"},G?.headers]),stream:w.stream??!1})}async submitToolOutputsAndPoll($,w,G){let Z=await this.submitToolOutputs($,w,G);return await this.poll(Z.id,w,G)}submitToolOutputsStream($,w,G){return L1.createToolAssistantStream($,this._client.beta.threads.runs,w,G)}}U4.Steps=$6;class Mw extends R{constructor(){super(...arguments);this.runs=new U4(this._client),this.messages=new e8(this._client)}create($={},w){return this._client.post("/threads",{body:$,...w,headers:I([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}retrieve($,w){return this._client.get(E`/threads/${$}`,{...w,headers:I([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}update($,w,G){return this._client.post(E`/threads/${$}`,{body:w,...G,headers:I([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}delete($,w){return this._client.delete(E`/threads/${$}`,{...w,headers:I([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}createAndRun($,w){return this._client.post("/threads/runs",{body:$,...w,headers:I([{"OpenAI-Beta":"assistants=v2"},w?.headers]),stream:$.stream??!1})}async createAndRunPoll($,w){let G=await this.createAndRun($,w);return await this.runs.poll(G.id,{thread_id:G.thread_id},w)}createAndRunStream($,w){return L1.createThreadAssistantStream($,this._client.beta.threads,w)}}Mw.Runs=U4;Mw.Messages=e8;class n$ extends R{constructor(){super(...arguments);this.realtime=new Ww(this._client),this.assistants=new a8(this._client),this.threads=new Mw(this._client)}}n$.Realtime=Ww;n$.Assistants=a8;n$.Threads=Mw;class H4 extends R{create($,w){return this._client.post("/completions",{body:$,...w,stream:$.stream??!1})}}class X6 extends R{retrieve($,w,G){let{container_id:Z}=w;return this._client.get(E`/containers/${Z}/files/${$}/content`,{...G,headers:I([{Accept:"application/binary"},G?.headers]),__binaryResponse:!0})}}class F4 extends R{constructor(){super(...arguments);this.content=new X6(this._client)}create($,w,G){return this._client.post(E`/containers/${$}/files`,m0({body:w,...G},this._client))}retrieve($,w,G){let{container_id:Z}=w;return this._client.get(E`/containers/${Z}/files/${$}`,G)}list($,w={},G){return this._client.getAPIList(E`/containers/${$}/files`,m,{query:w,...G})}delete($,w,G){let{container_id:Z}=w;return this._client.delete(E`/containers/${Z}/files/${$}`,{...G,headers:I([{Accept:"*/*"},G?.headers])})}}F4.Content=X6;class Pw extends R{constructor(){super(...arguments);this.files=new F4(this._client)}create($,w){return this._client.post("/containers",{body:$,...w})}retrieve($,w){return this._client.get(E`/containers/${$}`,w)}list($={},w){return this._client.getAPIList("/containers",m,{query:$,...w})}delete($,w){return this._client.delete(E`/containers/${$}`,{...w,headers:I([{Accept:"*/*"},w?.headers])})}}Pw.Files=F4;class Y6 extends R{create($,w,G){let{include:Z,...X}=w;return this._client.post(E`/conversations/${$}/items`,{query:{include:Z},body:X,...G})}retrieve($,w,G){let{conversation_id:Z,...X}=w;return this._client.get(E`/conversations/${Z}/items/${$}`,{query:X,...G})}list($,w={},G){return this._client.getAPIList(E`/conversations/${$}/items`,NY,{query:w,...G})}delete($,w,G){let{conversation_id:Z}=w;return this._client.delete(E`/conversations/${Z}/items/${$}`,G)}}class qw extends R{constructor(){super(...arguments);this.items=new Y6(this._client)}create($={},w){return this._client.post("/conversations",{body:$,...w})}retrieve($,w){return this._client.get(E`/conversations/${$}`,w)}update($,w,G){return this._client.post(E`/conversations/${$}`,{body:w,...G})}delete($,w){return this._client.delete(E`/conversations/${$}`,w)}}qw.Items=Y6;class O4 extends R{create($,w){let G=!!$.encoding_format,Z=G?$.encoding_format:"base64";if(G)J0(this._client).debug("embeddings/user defined encoding_format:",$.encoding_format);let X=this._client.post("/embeddings",{body:{...$,encoding_format:Z},...w});if(G)return X;return J0(this._client).debug("embeddings/decoding base64 embeddings from base64"),X._thenUnwrap((Y)=>{if(Y&&Y.data)Y.data.forEach((J)=>{let W=J.embedding;J.embedding=sN(W)});return Y})}}class J6 extends R{retrieve($,w,G){let{eval_id:Z,run_id:X}=w;return this._client.get(E`/evals/${Z}/runs/${X}/output_items/${$}`,G)}list($,w,G){let{eval_id:Z,...X}=w;return this._client.getAPIList(E`/evals/${Z}/runs/${$}/output_items`,m,{query:X,...G})}}class f4 extends R{constructor(){super(...arguments);this.outputItems=new J6(this._client)}create($,w,G){return this._client.post(E`/evals/${$}/runs`,{body:w,...G})}retrieve($,w,G){let{eval_id:Z}=w;return this._client.get(E`/evals/${Z}/runs/${$}`,G)}list($,w={},G){return this._client.getAPIList(E`/evals/${$}/runs`,m,{query:w,...G})}delete($,w,G){let{eval_id:Z}=w;return this._client.delete(E`/evals/${Z}/runs/${$}`,G)}cancel($,w,G){let{eval_id:Z}=w;return this._client.post(E`/evals/${Z}/runs/${$}`,G)}}f4.OutputItems=J6;class Bw extends R{constructor(){super(...arguments);this.runs=new f4(this._client)}create($,w){return this._client.post("/evals",{body:$,...w})}retrieve($,w){return this._client.get(E`/evals/${$}`,w)}update($,w,G){return this._client.post(E`/evals/${$}`,{body:w,...G})}list($={},w){return this._client.getAPIList("/evals",m,{query:$,...w})}delete($,w){return this._client.delete(E`/evals/${$}`,w)}}Bw.Runs=f4;class L4 extends R{create($,w){return this._client.post("/files",m0({body:$,...w},this._client))}retrieve($,w){return this._client.get(E`/files/${$}`,w)}list($={},w){return this._client.getAPIList("/files",m,{query:$,...w})}delete($,w){return this._client.delete(E`/files/${$}`,w)}content($,w){return this._client.get(E`/files/${$}/content`,{...w,headers:I([{Accept:"application/binary"},w?.headers]),__binaryResponse:!0})}async waitForProcessing($,{pollInterval:w=5000,maxWait:G=1800000}={}){let Z=new Set(["processed","error","deleted"]),X=Date.now(),Y=await this.retrieve($);while(!Y.status||!Z.has(Y.status))if(await F$(w),Y=await this.retrieve($),Date.now()-X>G)throw new Gw({message:`Giving up on waiting for file ${$} to finish processing after ${G} milliseconds.`});return Y}}class W6 extends R{}class T6 extends R{run($,w){return this._client.post("/fine_tuning/alpha/graders/run",{body:$,...w})}validate($,w){return this._client.post("/fine_tuning/alpha/graders/validate",{body:$,...w})}}class D4 extends R{constructor(){super(...arguments);this.graders=new T6(this._client)}}D4.Graders=T6;class Q6 extends R{create($,w,G){return this._client.getAPIList(E`/fine_tuning/checkpoints/${$}/permissions`,l$,{body:w,method:"post",...G})}retrieve($,w={},G){return this._client.get(E`/fine_tuning/checkpoints/${$}/permissions`,{query:w,...G})}delete($,w,G){let{fine_tuned_model_checkpoint:Z}=w;return this._client.delete(E`/fine_tuning/checkpoints/${Z}/permissions/${$}`,G)}}class E4 extends R{constructor(){super(...arguments);this.permissions=new Q6(this._client)}}E4.Permissions=Q6;class z6 extends R{list($,w={},G){return this._client.getAPIList(E`/fine_tuning/jobs/${$}/checkpoints`,m,{query:w,...G})}}class A4 extends R{constructor(){super(...arguments);this.checkpoints=new z6(this._client)}create($,w){return this._client.post("/fine_tuning/jobs",{body:$,...w})}retrieve($,w){return this._client.get(E`/fine_tuning/jobs/${$}`,w)}list($={},w){return this._client.getAPIList("/fine_tuning/jobs",m,{query:$,...w})}cancel($,w){return this._client.post(E`/fine_tuning/jobs/${$}/cancel`,w)}listEvents($,w={},G){return this._client.getAPIList(E`/fine_tuning/jobs/${$}/events`,m,{query:w,...G})}pause($,w){return this._client.post(E`/fine_tuning/jobs/${$}/pause`,w)}resume($,w){return this._client.post(E`/fine_tuning/jobs/${$}/resume`,w)}}A4.Checkpoints=z6;class L$ extends R{constructor(){super(...arguments);this.methods=new W6(this._client),this.jobs=new A4(this._client),this.checkpoints=new E4(this._client),this.alpha=new D4(this._client)}}L$.Methods=W6;L$.Jobs=A4;L$.Checkpoints=E4;L$.Alpha=D4;class M6 extends R{}class Nw extends R{constructor(){super(...arguments);this.graderModels=new M6(this._client)}}Nw.GraderModels=M6;class R4 extends R{createVariation($,w){return this._client.post("/images/variations",m0({body:$,...w},this._client))}edit($,w){return this._client.post("/images/edits",m0({body:$,...w,stream:$.stream??!1},this._client))}generate($,w){return this._client.post("/images/generations",{body:$,...w,stream:$.stream??!1})}}class S4 extends R{retrieve($,w){return this._client.get(E`/models/${$}`,w)}list($){return this._client.getAPIList("/models",l$,$)}delete($,w){return this._client.delete(E`/models/${$}`,w)}}class I4 extends R{create($,w){return this._client.post("/moderations",{body:$,...w})}}class P6 extends R{create($,w){return this._client.post("/realtime/client_secrets",{body:$,...w})}}class Vw extends R{constructor(){super(...arguments);this.clientSecrets=new P6(this._client)}}Vw.ClientSecrets=P6;function ZV($,w){if(!w||!Wu(w))return{...$,output_parsed:null,output:$.output.map((G)=>{if(G.type==="function_call")return{...G,parsed_arguments:null};if(G.type==="message")return{...G,content:G.content.map((Z)=>({...Z,parsed:null}))};else return G})};return yY($,w)}function yY($,w){let G=$.output.map((X)=>{if(X.type==="function_call")return{...X,parsed_arguments:zu(w,X)};if(X.type==="message"){let Y=X.content.map((J)=>{if(J.type==="output_text")return{...J,parsed:Ju(w,J.text)};return J});return{...X,content:Y}}return X}),Z=Object.assign({},$,{output:G});if(!Object.getOwnPropertyDescriptor($,"output_text"))z3(Z);return Object.defineProperty(Z,"output_parsed",{enumerable:!0,get(){for(let X of Z.output){if(X.type!=="message")continue;for(let Y of X.content)if(Y.type==="output_text"&&Y.parsed!==null)return Y.parsed}return null}}),Z}function Ju($,w){if($.text?.format?.type!=="json_schema")return null;if("$parseRaw"in $.text?.format)return($.text?.format).$parseRaw(w);return JSON.parse(w)}function Wu($){if(h8($.text?.format))return!0;return!1}function Tu($){return $?.$brand==="auto-parseable-tool"}function Qu($,w){return $.find((G)=>G.type==="function"&&G.name===w)}function zu($,w){let G=Qu($.tools??[],w.name);return{...w,...w,parsed_arguments:Tu(G)?G.$parseRaw(w.arguments):G?.strict?JSON.parse(w.arguments):null}}function z3($){let w=[];for(let G of $.output){if(G.type!=="message")continue;for(let Z of G.content)if(Z.type==="output_text")w.push(Z.text)}$.output_text=w.join("")}var j4,M3,D1,P3,XV,YV,JV,WV;class q3 extends Yw{constructor($){super();j4.add(this),M3.set(this,void 0),D1.set(this,void 0),P3.set(this,void 0),k(this,M3,$,"f")}static createResponse($,w,G){let Z=new q3(w);return Z._run(()=>Z._createOrRetrieveResponse($,w,{...G,headers:{...G?.headers,"X-Stainless-Helper-Method":"stream"}})),Z}async _createOrRetrieveResponse($,w,G){let Z=G?.signal;if(Z){if(Z.aborted)this.controller.abort();Z.addEventListener("abort",()=>this.controller.abort())}H(this,j4,"m",XV).call(this);let X,Y=null;if("response_id"in w)X=await $.responses.retrieve(w.response_id,{stream:!0},{...G,signal:this.controller.signal,stream:!0}),Y=w.starting_after??null;else X=await $.responses.create({...w,stream:!0},{...G,signal:this.controller.signal});this._connected();for await(let J of X)H(this,j4,"m",YV).call(this,J,Y);if(X.controller.signal?.aborted)throw new q0;return H(this,j4,"m",JV).call(this)}[(M3=new WeakMap,D1=new WeakMap,P3=new WeakMap,j4=new WeakSet,XV=function(){if(this.ended)return;k(this,D1,void 0,"f")},YV=function(w,G){if(this.ended)return;let Z=(Y,J)=>{if(G==null||J.sequence_number>G)this._emit(Y,J)},X=H(this,j4,"m",WV).call(this,w);switch(Z("event",w),w.type){case"response.output_text.delta":{let Y=X.output[w.output_index];if(!Y)throw new j(`missing output at index ${w.output_index}`);if(Y.type==="message"){let J=Y.content[w.content_index];if(!J)throw new j(`missing content at index ${w.content_index}`);if(J.type!=="output_text")throw new j(`expected content to be 'output_text', got ${J.type}`);Z("response.output_text.delta",{...w,snapshot:J.text})}break}case"response.function_call_arguments.delta":{let Y=X.output[w.output_index];if(!Y)throw new j(`missing output at index ${w.output_index}`);if(Y.type==="function_call")Z("response.function_call_arguments.delta",{...w,snapshot:Y.arguments});break}default:Z(w.type,w);break}},JV=function(){if(this.ended)throw new j("stream has ended, this shouldn't happen");let w=H(this,D1,"f");if(!w)throw new j("request ended without sending any events");k(this,D1,void 0,"f");let G=Mu(w,H(this,M3,"f"));return k(this,P3,G,"f"),G},WV=function(w){let G=H(this,D1,"f");if(!G){if(w.type!=="response.created")throw new j(`When snapshot hasn't been set yet, expected 'response.created' event, got ${w.type}`);return G=k(this,D1,w.response,"f"),G}switch(w.type){case"response.output_item.added":{G.output.push(w.item);break}case"response.content_part.added":{let Z=G.output[w.output_index];if(!Z)throw new j(`missing output at index ${w.output_index}`);let X=Z.type,Y=w.part;if(X==="message"&&Y.type!=="reasoning_text")Z.content.push(Y);else if(X==="reasoning"&&Y.type==="reasoning_text"){if(!Z.content)Z.content=[];Z.content.push(Y)}break}case"response.output_text.delta":{let Z=G.output[w.output_index];if(!Z)throw new j(`missing output at index ${w.output_index}`);if(Z.type==="message"){let X=Z.content[w.content_index];if(!X)throw new j(`missing content at index ${w.content_index}`);if(X.type!=="output_text")throw new j(`expected content to be 'output_text', got ${X.type}`);X.text+=w.delta}break}case"response.function_call_arguments.delta":{let Z=G.output[w.output_index];if(!Z)throw new j(`missing output at index ${w.output_index}`);if(Z.type==="function_call")Z.arguments+=w.delta;break}case"response.reasoning_text.delta":{let Z=G.output[w.output_index];if(!Z)throw new j(`missing output at index ${w.output_index}`);if(Z.type==="reasoning"){let X=Z.content?.[w.content_index];if(!X)throw new j(`missing content at index ${w.content_index}`);if(X.type!=="reasoning_text")throw new j(`expected content to be 'reasoning_text', got ${X.type}`);X.text+=w.delta}break}case"response.completed":{k(this,D1,w.response,"f");break}}return G},Symbol.asyncIterator)](){let $=[],w=[],G=!1;return this.on("event",(Z)=>{let X=w.shift();if(X)X.resolve(Z);else $.push(Z)}),this.on("end",()=>{G=!0;for(let Z of w)Z.resolve(void 0);w.length=0}),this.on("abort",(Z)=>{G=!0;for(let X of w)X.reject(Z);w.length=0}),this.on("error",(Z)=>{G=!0;for(let X of w)X.reject(Z);w.length=0}),{next:async()=>{if(!$.length){if(G)return{value:void 0,done:!0};return new Promise((X,Y)=>w.push({resolve:X,reject:Y})).then((X)=>X?{value:X,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}async finalResponse(){await this.done();let $=H(this,P3,"f");if(!$)throw new j("stream ended without producing a ChatCompletion");return $}}function Mu($,w){return ZV($,w)}class q6 extends R{list($,w={},G){return this._client.getAPIList(E`/responses/${$}/input_items`,m,{query:w,...G})}}class Kw extends R{constructor(){super(...arguments);this.inputItems=new q6(this._client)}create($,w){return this._client.post("/responses",{body:$,...w,stream:$.stream??!1})._thenUnwrap((G)=>{if("object"in G&&G.object==="response")z3(G);return G})}retrieve($,w={},G){return this._client.get(E`/responses/${$}`,{query:w,...G,stream:w?.stream??!1})._thenUnwrap((Z)=>{if("object"in Z&&Z.object==="response")z3(Z);return Z})}delete($,w){return this._client.delete(E`/responses/${$}`,{...w,headers:I([{Accept:"*/*"},w?.headers])})}parse($,w){return this._client.responses.create($,w)._thenUnwrap((G)=>yY(G,$))}stream($,w){return q3.createResponse(this._client,$,w)}cancel($,w){return this._client.post(E`/responses/${$}/cancel`,w)}}Kw.InputItems=q6;class B6 extends R{create($,w,G){return this._client.post(E`/uploads/${$}/parts`,m0({body:w,...G},this._client))}}class Uw extends R{constructor(){super(...arguments);this.parts=new B6(this._client)}create($,w){return this._client.post("/uploads",{body:$,...w})}cancel($,w){return this._client.post(E`/uploads/${$}/cancel`,w)}complete($,w,G){return this._client.post(E`/uploads/${$}/complete`,{body:w,...G})}}Uw.Parts=B6;var TV=async($)=>{let w=await Promise.allSettled($),G=w.filter((X)=>X.status==="rejected");if(G.length){for(let X of G)console.error(X.reason);throw Error(`${G.length} promise(s) failed - see the above errors`)}let Z=[];for(let X of w)if(X.status==="fulfilled")Z.push(X.value);return Z};class N6 extends R{create($,w,G){return this._client.post(E`/vector_stores/${$}/file_batches`,{body:w,...G,headers:I([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}retrieve($,w,G){let{vector_store_id:Z}=w;return this._client.get(E`/vector_stores/${Z}/file_batches/${$}`,{...G,headers:I([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}cancel($,w,G){let{vector_store_id:Z}=w;return this._client.post(E`/vector_stores/${Z}/file_batches/${$}/cancel`,{...G,headers:I([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}async createAndPoll($,w,G){let Z=await this.create($,w);return await this.poll($,Z.id,G)}listFiles($,w,G){let{vector_store_id:Z,...X}=w;return this._client.getAPIList(E`/vector_stores/${Z}/file_batches/${$}/files`,m,{query:X,...G,headers:I([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}async poll($,w,G){let Z=I([G?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":G?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:X,response:Y}=await this.retrieve(w,{vector_store_id:$},{...G,headers:Z}).withResponse();switch(X.status){case"in_progress":let J=5000;if(G?.pollIntervalMs)J=G.pollIntervalMs;else{let W=Y.headers.get("openai-poll-after-ms");if(W){let T=parseInt(W);if(!isNaN(T))J=T}}await F$(J);break;case"failed":case"cancelled":case"completed":return X}}}async uploadAndPoll($,{files:w,fileIds:G=[]},Z){if(w==null||w.length==0)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let X=Z?.maxConcurrency??5,Y=Math.min(X,w.length),J=this._client,W=w.values(),T=[...G];async function Q(M){for(let P of M){let q=await J.files.create({file:P,purpose:"assistants"},Z);T.push(q.id)}}let z=Array(Y).fill(W).map(Q);return await TV(z),await this.createAndPoll($,{file_ids:T})}}class V6 extends R{create($,w,G){return this._client.post(E`/vector_stores/${$}/files`,{body:w,...G,headers:I([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}retrieve($,w,G){let{vector_store_id:Z}=w;return this._client.get(E`/vector_stores/${Z}/files/${$}`,{...G,headers:I([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}update($,w,G){let{vector_store_id:Z,...X}=w;return this._client.post(E`/vector_stores/${Z}/files/${$}`,{body:X,...G,headers:I([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}list($,w={},G){return this._client.getAPIList(E`/vector_stores/${$}/files`,m,{query:w,...G,headers:I([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}delete($,w,G){let{vector_store_id:Z}=w;return this._client.delete(E`/vector_stores/${Z}/files/${$}`,{...G,headers:I([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}async createAndPoll($,w,G){let Z=await this.create($,w,G);return await this.poll($,Z.id,G)}async poll($,w,G){let Z=I([G?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":G?.pollIntervalMs?.toString()??void 0}]);while(!0){let X=await this.retrieve(w,{vector_store_id:$},{...G,headers:Z}).withResponse(),Y=X.data;switch(Y.status){case"in_progress":let J=5000;if(G?.pollIntervalMs)J=G.pollIntervalMs;else{let W=X.response.headers.get("openai-poll-after-ms");if(W){let T=parseInt(W);if(!isNaN(T))J=T}}await F$(J);break;case"failed":case"completed":return Y}}}async upload($,w,G){let Z=await this._client.files.create({file:w,purpose:"assistants"},G);return this.create($,{file_id:Z.id},G)}async uploadAndPoll($,w,G){let Z=await this.upload($,w,G);return await this.poll($,Z.id,G)}content($,w,G){let{vector_store_id:Z}=w;return this._client.getAPIList(E`/vector_stores/${Z}/files/${$}/content`,l$,{...G,headers:I([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}}class E1 extends R{constructor(){super(...arguments);this.files=new V6(this._client),this.fileBatches=new N6(this._client)}create($,w){return this._client.post("/vector_stores",{body:$,...w,headers:I([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}retrieve($,w){return this._client.get(E`/vector_stores/${$}`,{...w,headers:I([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}update($,w,G){return this._client.post(E`/vector_stores/${$}`,{body:w,...G,headers:I([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}list($={},w){return this._client.getAPIList("/vector_stores",m,{query:$,...w,headers:I([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}delete($,w){return this._client.delete(E`/vector_stores/${$}`,{...w,headers:I([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}search($,w,G){return this._client.getAPIList(E`/vector_stores/${$}/search`,l$,{body:w,method:"post",...G,headers:I([{"OpenAI-Beta":"assistants=v2"},G?.headers])})}}E1.Files=V6;E1.FileBatches=N6;var C4,QV,B3;class b4 extends R{constructor(){super(...arguments);C4.add(this)}async unwrap($,w,G=this._client.webhookSecret,Z=300){return await this.verifySignature($,w,G,Z),JSON.parse($)}async verifySignature($,w,G=this._client.webhookSecret,Z=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!=="function"||typeof crypto.subtle.verify!=="function")throw Error("Webhook signature verification is only supported when the `crypto` global is defined");H(this,C4,"m",QV).call(this,G);let X=I([w]).values,Y=H(this,C4,"m",B3).call(this,X,"webhook-signature"),J=H(this,C4,"m",B3).call(this,X,"webhook-timestamp"),W=H(this,C4,"m",B3).call(this,X,"webhook-id"),T=parseInt(J,10);if(isNaN(T))throw new i$("Invalid webhook timestamp format");let Q=Math.floor(Date.now()/1000);if(Q-T>Z)throw new i$("Webhook timestamp is too old");if(T>Q+Z)throw new i$("Webhook timestamp is too new");let z=Y.split(" ").map((N)=>N.startsWith("v1,")?N.substring(3):N),M=G.startsWith("whsec_")?Buffer.from(G.replace("whsec_",""),"base64"):Buffer.from(G,"utf-8"),P=W?`${W}.${J}.${$}`:`${J}.${$}`,q=await crypto.subtle.importKey("raw",M,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let N of z)try{let B=Buffer.from(N,"base64");if(await crypto.subtle.verify("HMAC",q,B,new TextEncoder().encode(P)))return}catch{continue}throw new i$("The given webhook signature does not match the expected signature")}}C4=new WeakSet,QV=function(w){if(typeof w!=="string"||w.length===0)throw Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},B3=function(w,G){if(!w)throw Error("Headers are required");let Z=w.get(G);if(Z===null||Z===void 0)throw Error(`Missing required header: ${G}`);return Z};var _Y,xY,N3,zV;class v{constructor({baseURL:$=f1("OPENAI_BASE_URL"),apiKey:w=f1("OPENAI_API_KEY"),organization:G=f1("OPENAI_ORG_ID")??null,project:Z=f1("OPENAI_PROJECT_ID")??null,webhookSecret:X=f1("OPENAI_WEBHOOK_SECRET")??null,...Y}={}){if(_Y.add(this),N3.set(this,void 0),this.completions=new H4(this),this.chat=new Jw(this),this.embeddings=new O4(this),this.files=new L4(this),this.images=new R4(this),this.audio=new p$(this),this.moderations=new I4(this),this.models=new S4(this),this.fineTuning=new L$(this),this.graders=new Nw(this),this.vectorStores=new E1(this),this.webhooks=new b4(this),this.beta=new n$(this),this.batches=new V4(this),this.uploads=new Uw(this),this.responses=new Kw(this),this.realtime=new Vw(this),this.conversations=new qw(this),this.evals=new Bw(this),this.containers=new Pw(this),w===void 0)throw new j("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");let J={apiKey:w,organization:G,project:Z,webhookSecret:X,...Y,baseURL:$||"https://api.openai.com/v1"};if(!J.dangerouslyAllowBrowser&&BN())throw new j(`It looks like you're running in a browser-like environment.
188
328
 
189
329
  This is disabled by default, as it risks exposing your secret API credentials to attackers.
190
330
  If you understand the risks and have appropriate mitigations in place,
@@ -193,80 +333,90 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
193
333
  new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
194
334
 
195
335
  https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
196
- `);this.baseURL=X.baseURL,this.timeout=X.timeout??E3.DEFAULT_TIMEOUT,this.logger=X.logger??console;let J="warn";this.logLevel=J,this.logLevel=sW(X.logLevel,"ClientOptions.logLevel",this)??sW($$("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??J,this.fetchOptions=X.fetchOptions,this.maxRetries=X.maxRetries??2,this.fetch=X.fetch??gM(),C(this,N5,uM,"f"),this._options=X,this.apiKey=typeof w==="string"?w:"Missing Key",this.organization=G,this.project=W,this.webhookSecret=Y}withOptions($){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...$})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:$,nulls:w}){return}async authHeaders($){return D([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery($){return tW($,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${s1}`}defaultIdempotencyKey(){return`stainless-node-retry-${vW()}`}makeStatusError($,w,G,W){return Z0.generate($,w,G,W)}async _callApiKey(){let $=this._options.apiKey;if(typeof $!=="function")return!1;let w;try{w=await $()}catch(G){if(G instanceof k)throw G;throw new k(`Failed to get token from 'apiKey' function: ${G.message}`,{cause:G})}if(typeof w!=="string"||!w)throw new k(`Expected 'apiKey' function argument to return a string but it returned ${w}`);return this.apiKey=w,!0}buildURL($,w,G){let W=!B(this,q3,"m",Cf).call(this)&&G||this.baseURL,Y=AM($)?new URL($):new URL(W+(W.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),Z=this.defaultQuery();if(!SM(Z))w={...Z,...w};if(typeof w==="object"&&w&&!Array.isArray(w))Y.search=this.stringifyQuery(w);return Y.toString()}async prepareOptions($){await this._callApiKey()}async prepareRequest($,{url:w,options:G}){}get($,w){return this.methodRequest("get",$,w)}post($,w){return this.methodRequest("post",$,w)}patch($,w){return this.methodRequest("patch",$,w)}put($,w){return this.methodRequest("put",$,w)}delete($,w){return this.methodRequest("delete",$,w)}methodRequest($,w,G){return this.request(Promise.resolve(G).then((W)=>{return{method:$,path:w,...W}}))}request($,w=null){return new D$(this,this.makeRequest($,w,void 0))}async makeRequest($,w,G){let W=await $,Y=W.maxRetries??this.maxRetries;if(w==null)w=Y;await this.prepareOptions(W);let{req:Z,url:X,timeout:J}=await this.buildRequest(W,{retryCount:Y-w});await this.prepareRequest(Z,{url:X,options:W});let T="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),M=G===void 0?"":`, retryOf: ${G}`,f=Date.now();if(W0(this).debug(`[${T}] sending request`,R1({retryOfRequestLogID:G,method:W.method,url:X,options:W,headers:Z.headers})),W.signal?.aborted)throw new T0;let Q=new AbortController,N=await this.fetchWithTimeout(X,Z,J,Q).catch(J9),z=Date.now();if(N instanceof globalThis.Error){let q=`retrying, ${w} attempts remaining`;if(W.signal?.aborted)throw new T0;let V=X9(N)||/timed? ?out/i.test(String(N)+("cause"in N?String(N.cause):""));if(w)return W0(this).info(`[${T}] connection ${V?"timed out":"failed"} - ${q}`),W0(this).debug(`[${T}] connection ${V?"timed out":"failed"} (${q})`,R1({retryOfRequestLogID:G,url:X,durationMs:z-f,message:N.message})),this.retryRequest(W,w,G??T);if(W0(this).info(`[${T}] connection ${V?"timed out":"failed"} - error; no more retries left`),W0(this).debug(`[${T}] connection ${V?"timed out":"failed"} (error; no more retries left)`,R1({retryOfRequestLogID:G,url:X,durationMs:z-f,message:N.message})),V)throw new L$;throw new O$({cause:N})}let K=[...N.headers.entries()].filter(([q])=>q==="x-request-id").map(([q,V])=>", "+q+": "+JSON.stringify(V)).join(""),P=`[${T}${M}${K}] ${Z.method} ${X} ${N.ok?"succeeded":"failed"} with status ${N.status} in ${z-f}ms`;if(!N.ok){let q=await this.shouldRetry(N);if(w&&q){let S=`retrying, ${w} attempts remaining`;return await vM(N.body),W0(this).info(`${P} - ${S}`),W0(this).debug(`[${T}] response error (${S})`,R1({retryOfRequestLogID:G,url:N.url,status:N.status,headers:N.headers,durationMs:z-f})),this.retryRequest(W,w,G??T,N.headers)}let V=q?"error; no more retries left":"error; not retryable";W0(this).info(`${P} - ${V}`);let E=await N.text().catch((S)=>J9(S).message),O=CM(E),A=O?void 0:E;throw W0(this).debug(`[${T}] response error (${V})`,R1({retryOfRequestLogID:G,url:N.url,status:N.status,headers:N.headers,message:A,durationMs:Date.now()-f})),this.makeStatusError(N.status,O,A,N.headers)}return W0(this).info(P),W0(this).debug(`[${T}] response start`,R1({retryOfRequestLogID:G,url:N.url,status:N.status,headers:N.headers,durationMs:z-f})),{response:N,options:W,controller:Q,requestLogID:T,retryOfRequestLogID:G,startTime:f}}getAPIList($,w,G){return this.requestAPIList(w,{method:"get",path:$,...G})}requestAPIList($,w){let G=this.makeRequest(w,null,void 0);return new n6(this,G,$)}async fetchWithTimeout($,w,G,W){let{signal:Y,method:Z,...X}=w||{};if(Y)Y.addEventListener("abort",()=>W.abort());let J=setTimeout(()=>W.abort(),G),T=globalThis.ReadableStream&&X.body instanceof globalThis.ReadableStream||typeof X.body==="object"&&X.body!==null&&Symbol.asyncIterator in X.body,M={signal:W.signal,...T?{duplex:"half"}:{},method:"GET",...X};if(Z)M.method=Z.toUpperCase();try{return await this.fetch.call(void 0,$,M)}finally{clearTimeout(J)}}async shouldRetry($){let w=$.headers.get("x-should-retry");if(w==="true")return!0;if(w==="false")return!1;if($.status===408)return!0;if($.status===409)return!0;if($.status===429)return!0;if($.status>=500)return!0;return!1}async retryRequest($,w,G,W){let Y,Z=W?.get("retry-after-ms");if(Z){let J=parseFloat(Z);if(!Number.isNaN(J))Y=J}let X=W?.get("retry-after");if(X&&!Y){let J=parseFloat(X);if(!Number.isNaN(J))Y=J*1000;else Y=Date.parse(X)-Date.now()}if(!(Y&&0<=Y&&Y<60000)){let J=$.maxRetries??this.maxRetries;Y=this.calculateDefaultRetryTimeoutMillis(w,J)}return await f1(Y),this.makeRequest($,w-1,G)}calculateDefaultRetryTimeoutMillis($,w){let Y=w-$,Z=Math.min(0.5*Math.pow(2,Y),8),X=1-Math.random()*0.25;return Z*X*1000}async buildRequest($,{retryCount:w=0}={}){let G={...$},{method:W,path:Y,query:Z,defaultBaseURL:X}=G,J=this.buildURL(Y,Z,X);if("timeout"in G)jM("timeout",G.timeout);G.timeout=G.timeout??this.timeout;let{bodyHeaders:T,body:M}=this.buildBody({options:G}),f=await this.buildHeaders({options:$,method:W,bodyHeaders:T,retryCount:w});return{req:{method:W,headers:f,...G.signal&&{signal:G.signal},...globalThis.ReadableStream&&M instanceof globalThis.ReadableStream&&{duplex:"half"},...M&&{body:M},...this.fetchOptions??{},...G.fetchOptions??{}},url:J,timeout:G.timeout}}async buildHeaders({options:$,method:w,bodyHeaders:G,retryCount:W}){let Y={};if(this.idempotencyHeader&&w!=="get"){if(!$.idempotencyKey)$.idempotencyKey=this.defaultIdempotencyKey();Y[this.idempotencyHeader]=$.idempotencyKey}let Z=D([Y,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(W),...$.timeout?{"X-Stainless-Timeout":String(Math.trunc($.timeout/1000))}:{},..._M(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders($),this._options.defaultHeaders,G,$.headers]);return this.validateHeaders(Z),Z.values}buildBody({options:{body:$,headers:w}}){if(!$)return{bodyHeaders:void 0,body:void 0};let G=D([w]);if(ArrayBuffer.isView($)||$ instanceof ArrayBuffer||$ instanceof DataView||typeof $==="string"&&G.values.has("content-type")||globalThis.Blob&&$ instanceof globalThis.Blob||$ instanceof FormData||$ instanceof URLSearchParams||globalThis.ReadableStream&&$ instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:$};else if(typeof $==="object"&&((Symbol.asyncIterator in $)||(Symbol.iterator in $)&&("next"in $)&&typeof $.next==="function"))return{bodyHeaders:void 0,body:g6($)};else return B(this,N5,"f").call(this,{body:$,headers:G})}}E3=g,N5=new WeakMap,q3=new WeakSet,Cf=function(){return this.baseURL!=="https://api.openai.com/v1"};g.OpenAI=E3;g.DEFAULT_TIMEOUT=600000;g.OpenAIError=k;g.APIError=Z0;g.APIConnectionError=O$;g.APIConnectionTimeoutError=L$;g.APIUserAbortError=T0;g.NotFoundError=Q9;g.ConflictError=N9;g.RateLimitError=K9;g.BadRequestError=T9;g.AuthenticationError=M9;g.InternalServerError=P9;g.PermissionDeniedError=f9;g.UnprocessableEntityError=z9;g.InvalidWebhookSignatureError=S1;g.toFile=p6;g.Completions=Sw;g.Chat=S$;g.Embeddings=jw;g.Files=yw;g.Images=_w;g.Audio=I1;g.Moderations=vw;g.Models=gw;g.FineTuning=z1;g.Graders=g$;g.VectorStores=W$;g.Webhooks=iw;g.Beta=b1;g.Batches=Dw;g.Uploads=h$;g.Responses=u$;g.Realtime=v$;g.Conversations=x$;g.Evals=_$;g.Containers=b$;class U3{client;constructor($){this.client=new g({...$,maxRetries:0})}async*stream($){let w=await this.client.chat.completions.create({model:$.model,messages:jL($.messages),...$.tools.length?{tools:$.tools.map((W)=>({type:"function",function:{name:W.name,description:W.description,parameters:W.inputSchema}}))}:{},max_completion_tokens:$.maxOutputTokens,stream:!0,stream_options:{include_usage:!0}},$.signal?{signal:$.signal}:void 0),G=new Set;for await(let W of w){let Y=W.choices[0]?.delta,Z=Y?.reasoning_content;if(Z)yield{type:"reasoning_delta",text:Z};if(Y?.content)yield{type:"text_delta",text:Y.content};for(let X of Y?.tool_calls??[]){let J=X.index;if(!G.has(J))G.add(J),yield{type:"tool_call_start",index:J,callId:X.id??`call_${J}`,name:X.function?.name??""};if(X.function?.arguments)yield{type:"tool_call_delta",index:J,argumentsDelta:X.function.arguments}}if(W.usage)yield{type:"usage",usage:{inputTokens:W.usage.prompt_tokens,outputTokens:W.usage.completion_tokens}}}for(let W of G)yield{type:"tool_call_end",index:W};yield{type:"done"}}}function jL($){return $.map((w)=>{if(w.role==="system"||w.role==="user")return{role:w.role,content:w.content};if(w.role==="tool")return{role:"tool",tool_call_id:w.callId,content:w.content};let G={role:"assistant",content:w.content||null};if(w.toolCalls.length)G.tool_calls=w.toolCalls.map((W)=>({id:W.callId,type:"function",function:{name:W.name,arguments:JSON.stringify(W.input)}}));return G})}import{createHash as CL,randomUUID as yf}from"node:crypto";import{appendFile as yL,chmod as If,mkdir as IL,readdir as bL,readFile as bf}from"node:fs/promises";import i$ from"node:path";var xL=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;function xf($){return xL.test($)}function H3($){return CL("sha256").update(i$.resolve($)).digest("hex").slice(0,16)}class F3{workspace;sessionId;sessionPath;tracePath;#$=Promise.resolve();#w=!1;constructor($,w,G=yf()){this.workspace=w;this.sessionId=G;if(!xf(G))throw Error("Invalid session ID");let W=i$.join($,"sessions",H3(w));this.sessionPath=i$.join(W,`${G}.jsonl`),this.tracePath=i$.join(W,`${G}.trace.jsonl`)}get isCreated(){return this.#w}async create($=this.workspace){if(this.#w)return;await this.append("session.created",{workspace:$,sessionId:this.sessionId}),this.#w=!0}append($,w){let G={version:1,id:yf(),timestamp:new Date().toISOString(),type:$,data:w},W=this.#$.then(async()=>{let Y=i$.dirname(this.sessionPath);await IL(Y,{recursive:!0,mode:448}),await If(Y,448),await yL(this.sessionPath,`${JSON.stringify(G)}
197
- `,{encoding:"utf8",mode:384}),await If(this.sessionPath,384)});return this.#$=W.catch(()=>{}),W}appendMessage($){return this.append("message",$)}appendCompaction($,w){return this.append("context.compacted",w?{summary:$,sourceRange:w}:{summary:$})}setTitle($){return this.append("session.title",{title:$})}async list(){let $=i$.dirname(this.sessionPath),w;try{w=await bL($)}catch(W){if(W.code==="ENOENT")return[];throw W}let G=[];for(let W of w){if(!W.endsWith(".jsonl")||W.endsWith(".trace.jsonl"))continue;let Y=W.slice(0,-6);if(!xf(Y))continue;try{G.push(await this.#G(i$.join($,W),Y))}catch{}}return G.sort((W,Y)=>Y.lastActivity.localeCompare(W.lastActivity)),G}async#G($,w){let G=await bf($,"utf8"),W=0,Y,Z,X="";for(let M of G.split(`
198
- `)){if(!M)continue;let f;try{f=JSON.parse(M)}catch{continue}if(f.version!==1)continue;if(f.timestamp)X=f.timestamp;switch(f.type){case"session.reset":W=0,Z=void 0,Y=void 0;break;case"session.title":{let Q=f.data;if(typeof Q?.title==="string")Y=Q.title;break}case"message":if(W++,Z===void 0){let Q=f.data;if(Q?.role==="user"&&typeof Q.content==="string")Z=Q.content}break}}let J=Y??Z,T={id:w,messageCount:W,lastActivity:X};if(J!==void 0)T.title=J;return T}async recover(){let $=[],w=[],G,W,Y=await bf(this.sessionPath,"utf8");this.#w=!0;let Z=Y.split(`
199
- `),X=-1;for(let M=Z.length-1;M>=0;M--)if(Z[M]){X=M;break}for(let M=0;M<Z.length;M++){let f=Z[M];if(!f)continue;let Q;try{Q=JSON.parse(f)}catch(N){if(M===X){w.push("Ignored incomplete final JSONL record");break}throw _f(M,N)}try{if(Q.version!==1)throw Error("unsupported schema version");if(Q.type==="session.reset")$.length=0,G=void 0,W=void 0;if(Q.type==="message"){if(!_L(Q.data))throw Error("invalid message structure");$.push(Q.data)}if(Q.type==="context.compacted"){let N=Q.data;if(typeof N?.summary!=="string")throw Error("invalid compaction record");G=N.summary,W=typeof N.sourceRange?.start==="number"&&typeof N.sourceRange.end==="number"?{start:N.sourceRange.start,end:N.sourceRange.end}:void 0}}catch(N){throw _f(M,N)}}let J=gL($,w);for(let M of J)await this.appendMessage(M);let T={messages:$,warnings:w};if(G!==void 0)T.summary=G;if(W!==void 0)T.compactionRange=W;return T}}function _L($){if(!$||typeof $!=="object")return!1;let w=$;if((w.role==="system"||w.role==="user")&&typeof w.content==="string")return!0;if(w.role==="assistant"&&typeof w.content==="string")return Array.isArray(w.toolCalls)&&w.toolCalls.every((G)=>!!G&&typeof G==="object"&&typeof G.callId==="string"&&typeof G.name==="string"&&("input"in G));return w.role==="tool"&&typeof w.callId==="string"&&typeof w.name==="string"&&typeof w.content==="string"&&typeof w.isError==="boolean"}function _f($,w){return Error(`Invalid session record at line ${$+1}: ${w instanceof Error?w.message:String(w)}`)}function gL($,w){let G=new Map,W=new Set;for(let Z of $)if(Z.role==="assistant"){if(G.size>0)throw Error("Assistant message appeared before pending tool results");for(let X of Z.toolCalls){if(W.has(X.callId))throw Error(`Duplicate tool call ID: ${X.callId}`);W.add(X.callId),G.set(X.callId,X.name)}}else if(Z.role==="tool"){if(!G.delete(Z.callId))throw Error(`Orphan tool result: ${Z.callId}`)}else if(G.size>0)throw Error(`${Z.role} message appeared before pending tool results`);if(G.size===0)return[];let Y=[];for(let[Z,X]of G){let J={role:"tool",callId:Z,name:X,content:"runtime.interrupted: tool execution did not complete before the previous process exited",isError:!0};$.push(J),Y.push(J)}return w.push(`Recovered ${G.size} interrupted tool call(s)`),Y}function gf(){return[w6,W6,$6,a8]}var vL={maxLines:20,maxValueChars:2000,maxDepth:4,maxSummaryColumns:120};function m$($){return typeof $==="object"&&$!==null&&!Array.isArray($)?$:void 0}function vf($,w){let G=m$(w?.properties),W=G?Object.keys(G).filter((Y)=>(Y in $)):[];return[...W,...Object.keys($).filter((Y)=>!W.includes(Y))]}function uL($,w){return m$(m$($?.properties)?.[w])}function hL($,w){let G=Y0($),W=Array.from(G);if(W.length<=w)return G;let Y=W.length-w;return`${W.slice(0,w).join("")}[${Y} characters omitted]`}function z5($,w){if(typeof $==="string")return hL($,w.maxValueChars);if($===null)return"null";if(typeof $==="number"||typeof $==="boolean"||typeof $==="bigint")return String($);if($===void 0)return"undefined";return}function K5($,w={}){let G={...vL,...w},W=Y0($.name);try{let Y=[],Z=new WeakSet,X=Math.max(0,G.maxLines),J=(N)=>{if(Y.length<=X)Y.push(N)},T=(N,z,K,P,q)=>{if(Y.length>X)return;let V=q===void 0?void 0:Y0(q),E=z5(N,G);if(E!==void 0){let S=E.split(`
200
- `);if(V!==void 0&&S.length===1)J(`${P}${V}: ${E}`);else if(V!==void 0){J(`${P}${V}:`);for(let _ of S)J(`${P} ${_}`)}else for(let _ of S)J(`${P}${_}`);return}if(K>=G.maxDepth){J(`${P}${V===void 0?"":`${V}: `}[max depth]`);return}if(typeof N!=="object"||N===null){J(`${P}${V===void 0?"":`${V}: `}${Y0(String(N))}`);return}if(Z.has(N)){J(`${P}${V===void 0?"":`${V}: `}[circular]`);return}if(Z.add(N),Array.isArray(N)){if(N.length===0){J(`${P}${V===void 0?"":`${V}: `}[]`);return}if(V!==void 0)J(`${P}${V}:`);let S=V===void 0?P:`${P} `,_=m$(z?.items);for(let s of N){if(Y.length>X)break;let e=z5(s,G);if(e!==void 0&&!e.includes(`
201
- `))J(`${S}- ${e}`);else J(`${S}-`),T(s,_,K+1,`${S} `)}return}let O=N,A=vf(O,z);if(A.length===0){J(`${P}${V===void 0?"":`${V}: `}{}`);return}if(V!==void 0)J(`${P}${V}:`);let R=V===void 0?P:`${P} `;for(let S of A){if(Y.length>X)break;T(O[S],uL(z,S),K+1,R,S)}};T($.input,m$($.inputSchema),0,"");let M=Y;if(M.length>X)M=X===0?[]:[...M.slice(0,X-1),"... [1 or more lines omitted]"];let f=W,Q=m$($.input);if(Q)for(let N of vf(Q,m$($.inputSchema))){let z=z5(Q[N],G);if(z!==void 0){f=`${Y0(N)}: ${z.split(`
202
- `)[0]??""}`;break}}else{let N=z5($.input,G);if(N!==void 0)f=N.split(`
203
- `)[0]??W}return{lines:M,summary:Tw(Y0(f),G.maxSummaryColumns)}}catch{return{lines:["[unavailable]"],summary:Tw(W,G.maxSummaryColumns)}}}class O3{registry;permissions;events;workspace;timeoutMs;constructor($,w,G,W,Y=60000){this.registry=$;this.permissions=w;this.events=G;this.workspace=W;this.timeoutMs=Y}setRegistry($){this.registry=$}async execute($,w,G){await this.events.emit("tool.requested",{name:$.name,callId:$.callId},G);let W=this.registry.get($.name);if(!W)return{content:`tool.not_found: ${$.name}`,isError:!0};let Y=this.registry.validate($.name,$.input);if(!Y.valid)return{content:`tool.invalid_input: ${Y.errors}`,isError:!0};if(["read","write","edit"].includes($.name))try{await J1(this.workspace,$.input.path)}catch(N){return{content:`permission.workspace_denied: ${N instanceof Error?N.message:String(N)}`,isError:!0}}let Z=await this.permissions.authorize(W,$,w);if(await this.events.emit("permission.requested",{name:$.name,callId:$.callId,risk:Z.risk,allowed:Z.allowed},G),!Z.allowed)return{content:`permission.denied: ${$.name} was not authorized`,isError:!0};let X=K5({name:W.name,risk:Z.risk,inputSchema:W.inputSchema,input:$.input});await this.events.emit("tool.started",{name:$.name,callId:$.callId,summary:X.summary},G);let J=Date.now(),T,M=new AbortController,f=()=>M.abort(w.reason);if(w.aborted)f();else w.addEventListener("abort",f,{once:!0});let Q=setTimeout(()=>M.abort(Error(`Tool timed out after ${this.timeoutMs}ms`)),this.timeoutMs);try{let N=M.signal.aborted?Promise.reject(M.signal.reason):new Promise((z,K)=>{M.signal.addEventListener("abort",()=>K(M.signal.reason),{once:!0})});T=await Promise.race([W.execute($.input,{workspace:this.workspace,signal:M.signal}),N]),T={...T,content:d$(T.content,50000)}}catch(N){T={content:`${!w.aborted&&M.signal.aborted?"tool.timeout (abort requested; tools must cooperate)":"tool.internal_error"}: ${N instanceof Error?N.message:String(N)}`,isError:!0}}finally{clearTimeout(Q),w.removeEventListener("abort",f)}return await this.events.emit("tool.completed",{name:$.name,callId:$.callId,isError:T.isError??!1,durationMs:Date.now()-J},G),T}}import{createHash as iL,randomUUID as mL}from"node:crypto";import{readdir as lL,readFile as cL,realpath as dL,stat as uf}from"node:fs/promises";import hf from"node:path";import{pathToFileURL as L3}from"node:url";class G8{builtins;events;auto;trust;importer;static defaultImporter=($)=>import($);#$=new Map;constructor($,w,G,W,Y=G8.defaultImporter){this.builtins=$;this.events=w;this.auto=G;this.trust=W;this.importer=Y}async load($,w){let G=w?.clone()??new Z1(this.builtins),W=[],Y=[];for(let Z of $)try{let X=await dL(Z.path),J=await uf(X),T=J.isDirectory()?X:hf.dirname(X);if(Z.project&&!this.auto){if(!(this.trust?await this.trust(T):!1)){await this.events.emit("plugin.unavailable",{path:T,reason:"not trusted"});continue}}let M=J.isDirectory()?(await lL(X)).filter((f)=>f.endsWith(".ts")).sort().map((f)=>hf.join(X,f)):X.endsWith(".ts")?[X]:[];for(let f of M)try{let Q=await this.importPlugin(f);if(!nL(Q.default))throw Error("default export is not a ToolDefinition");G.register(Q.default,{kind:"local",path:f}),W.push(Q.default.name),await this.events.emit("plugin.loaded",{path:f,name:Q.default.name})}catch(Q){Y.push(f),await this.events.emit("plugin.failed",{path:f,message:Q instanceof Error?Q.message:String(Q)})}}catch(X){if(X.code!=="ENOENT")Y.push(Z.path),await this.events.emit("plugin.failed",{path:Z.path,message:X instanceof Error?X.message:String(X)})}return{registry:G,loaded:W,failed:Y}}async importPlugin($){if(this.importer!==G8.defaultImporter){let X=(await uf($)).mtimeMs;return this.importer(`${L3($).href}?mtime=${X}`)}let w=await cL($,"utf8"),G=iL("sha256").update(w).digest("hex"),W=this.#$.get($);if(W?.hash===G)return W.module;let Y=`// coden-source: ${L3($).href}
204
- // coden-load: ${mL()}
336
+ `);this.baseURL=J.baseURL,this.timeout=J.timeout??xY.DEFAULT_TIMEOUT,this.logger=J.logger??console;let W="warn";this.logLevel=W,this.logLevel=qY(J.logLevel,"ClientOptions.logLevel",this)??qY(f1("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??W,this.fetchOptions=J.fetchOptions,this.maxRetries=J.maxRetries??2,this.fetch=J.fetch??VN(),k(this,N3,UN,"f"),this._options=J,this.apiKey=typeof w==="string"?w:"Missing Key",this.organization=G,this.project=Z,this.webhookSecret=X}withOptions($){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...$})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:$,nulls:w}){return}async authHeaders($){return I([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery($){return MY($,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${U1}`}defaultIdempotencyKey(){return`stainless-node-retry-${wY()}`}makeStatusError($,w,G,Z){return Q0.generate($,w,G,Z)}async _callApiKey(){let $=this._options.apiKey;if(typeof $!=="function")return!1;let w;try{w=await $()}catch(G){if(G instanceof j)throw G;throw new j(`Failed to get token from 'apiKey' function: ${G.message}`,{cause:G})}if(typeof w!=="string"||!w)throw new j(`Expected 'apiKey' function argument to return a string but it returned ${w}`);return this.apiKey=w,!0}buildURL($,w,G){let Z=!H(this,_Y,"m",zV).call(this)&&G||this.baseURL,X=JN($)?new URL($):new URL(Z+(Z.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),Y=this.defaultQuery();if(!WN(Y))w={...Y,...w};if(typeof w==="object"&&w&&!Array.isArray(w))X.search=this.stringifyQuery(w);return X.toString()}async prepareOptions($){await this._callApiKey()}async prepareRequest($,{url:w,options:G}){}get($,w){return this.methodRequest("get",$,w)}post($,w){return this.methodRequest("post",$,w)}patch($,w){return this.methodRequest("patch",$,w)}put($,w){return this.methodRequest("put",$,w)}delete($,w){return this.methodRequest("delete",$,w)}methodRequest($,w,G){return this.request(Promise.resolve(G).then((Z)=>{return{method:$,path:w,...Z}}))}request($,w=null){return new Zw(this,this.makeRequest($,w,void 0))}async makeRequest($,w,G){let Z=await $,X=Z.maxRetries??this.maxRetries;if(w==null)w=X;await this.prepareOptions(Z);let{req:Y,url:J,timeout:W}=await this.buildRequest(Z,{retryCount:X-w});await this.prepareRequest(Y,{url:J,options:Z});let T="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),Q=G===void 0?"":`, retryOf: ${G}`,z=Date.now();if(J0(this).debug(`[${T}] sending request`,m$({retryOfRequestLogID:G,method:Z.method,url:J,options:Z,headers:Y.headers})),Z.signal?.aborted)throw new q0;let M=new AbortController,P=await this.fetchWithTimeout(J,Y,W,M).catch(f8),q=Date.now();if(P instanceof globalThis.Error){let V=`retrying, ${w} attempts remaining`;if(Z.signal?.aborted)throw new q0;let K=O8(P)||/timed? ?out/i.test(String(P)+("cause"in P?String(P.cause):""));if(w)return J0(this).info(`[${T}] connection ${K?"timed out":"failed"} - ${V}`),J0(this).debug(`[${T}] connection ${K?"timed out":"failed"} (${V})`,m$({retryOfRequestLogID:G,url:J,durationMs:q-z,message:P.message})),this.retryRequest(Z,w,G??T);if(J0(this).info(`[${T}] connection ${K?"timed out":"failed"} - error; no more retries left`),J0(this).debug(`[${T}] connection ${K?"timed out":"failed"} (error; no more retries left)`,m$({retryOfRequestLogID:G,url:J,durationMs:q-z,message:P.message})),K)throw new Gw;throw new ww({cause:P})}let N=[...P.headers.entries()].filter(([V])=>V==="x-request-id").map(([V,K])=>", "+V+": "+JSON.stringify(K)).join(""),B=`[${T}${Q}${N}] ${Y.method} ${J} ${P.ok?"succeeded":"failed"} with status ${P.status} in ${q-z}ms`;if(!P.ok){let V=await this.shouldRetry(P);if(w&&V){let L=`retrying, ${w} attempts remaining`;return await KN(P.body),J0(this).info(`${B} - ${L}`),J0(this).debug(`[${T}] response error (${L})`,m$({retryOfRequestLogID:G,url:P.url,status:P.status,headers:P.headers,durationMs:q-z})),this.retryRequest(Z,w,G??T,P.headers)}let K=V?"error; no more retries left":"error; not retryable";J0(this).info(`${B} - ${K}`);let U=await P.text().catch((L)=>f8(L).message),O=zN(U),D=O?void 0:U;throw J0(this).debug(`[${T}] response error (${K})`,m$({retryOfRequestLogID:G,url:P.url,status:P.status,headers:P.headers,message:D,durationMs:Date.now()-z})),this.makeStatusError(P.status,O,D,P.headers)}return J0(this).info(B),J0(this).debug(`[${T}] response start`,m$({retryOfRequestLogID:G,url:P.url,status:P.status,headers:P.headers,durationMs:q-z})),{response:P,options:Z,controller:M,requestLogID:T,retryOfRequestLogID:G,startTime:z}}getAPIList($,w,G){return this.requestAPIList(w,{method:"get",path:$,...G})}requestAPIList($,w){let G=this.makeRequest(w,null,void 0);return new sG(this,G,$)}async fetchWithTimeout($,w,G,Z){let{signal:X,method:Y,...J}=w||{};if(X)X.addEventListener("abort",()=>Z.abort());let W=setTimeout(()=>Z.abort(),G),T=globalThis.ReadableStream&&J.body instanceof globalThis.ReadableStream||typeof J.body==="object"&&J.body!==null&&Symbol.asyncIterator in J.body,Q={signal:Z.signal,...T?{duplex:"half"}:{},method:"GET",...J};if(Y)Q.method=Y.toUpperCase();try{return await this.fetch.call(void 0,$,Q)}finally{clearTimeout(W)}}async shouldRetry($){let w=$.headers.get("x-should-retry");if(w==="true")return!0;if(w==="false")return!1;if($.status===408)return!0;if($.status===409)return!0;if($.status===429)return!0;if($.status>=500)return!0;return!1}async retryRequest($,w,G,Z){let X,Y=Z?.get("retry-after-ms");if(Y){let W=parseFloat(Y);if(!Number.isNaN(W))X=W}let J=Z?.get("retry-after");if(J&&!X){let W=parseFloat(J);if(!Number.isNaN(W))X=W*1000;else X=Date.parse(J)-Date.now()}if(!(X&&0<=X&&X<60000)){let W=$.maxRetries??this.maxRetries;X=this.calculateDefaultRetryTimeoutMillis(w,W)}return await F$(X),this.makeRequest($,w-1,G)}calculateDefaultRetryTimeoutMillis($,w){let X=w-$,Y=Math.min(0.5*Math.pow(2,X),8),J=1-Math.random()*0.25;return Y*J*1000}async buildRequest($,{retryCount:w=0}={}){let G={...$},{method:Z,path:X,query:Y,defaultBaseURL:J}=G,W=this.buildURL(X,Y,J);if("timeout"in G)QN("timeout",G.timeout);G.timeout=G.timeout??this.timeout;let{bodyHeaders:T,body:Q}=this.buildBody({options:G}),z=await this.buildHeaders({options:$,method:Z,bodyHeaders:T,retryCount:w});return{req:{method:Z,headers:z,...G.signal&&{signal:G.signal},...globalThis.ReadableStream&&Q instanceof globalThis.ReadableStream&&{duplex:"half"},...Q&&{body:Q},...this.fetchOptions??{},...G.fetchOptions??{}},url:W,timeout:G.timeout}}async buildHeaders({options:$,method:w,bodyHeaders:G,retryCount:Z}){let X={};if(this.idempotencyHeader&&w!=="get"){if(!$.idempotencyKey)$.idempotencyKey=this.defaultIdempotencyKey();X[this.idempotencyHeader]=$.idempotencyKey}let Y=I([X,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(Z),...$.timeout?{"X-Stainless-Timeout":String(Math.trunc($.timeout/1000))}:{},...NN(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders($),this._options.defaultHeaders,G,$.headers]);return this.validateHeaders(Y),Y.values}buildBody({options:{body:$,headers:w}}){if(!$)return{bodyHeaders:void 0,body:void 0};let G=I([w]);if(ArrayBuffer.isView($)||$ instanceof ArrayBuffer||$ instanceof DataView||typeof $==="string"&&G.values.has("content-type")||globalThis.Blob&&$ instanceof globalThis.Blob||$ instanceof FormData||$ instanceof URLSearchParams||globalThis.ReadableStream&&$ instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:$};else if(typeof $==="object"&&((Symbol.asyncIterator in $)||(Symbol.iterator in $)&&("next"in $)&&typeof $.next==="function"))return{bodyHeaders:void 0,body:vG($)};else return H(this,N3,"f").call(this,{body:$,headers:G})}}xY=v,N3=new WeakMap,_Y=new WeakSet,zV=function(){return this.baseURL!=="https://api.openai.com/v1"};v.OpenAI=xY;v.DEFAULT_TIMEOUT=600000;v.OpenAIError=j;v.APIError=Q0;v.APIConnectionError=ww;v.APIConnectionTimeoutError=Gw;v.APIUserAbortError=q0;v.NotFoundError=A8;v.ConflictError=R8;v.RateLimitError=I8;v.BadRequestError=L8;v.AuthenticationError=D8;v.InternalServerError=j8;v.PermissionDeniedError=E8;v.UnprocessableEntityError=S8;v.InvalidWebhookSignatureError=i$;v.toFile=aG;v.Completions=H4;v.Chat=Jw;v.Embeddings=O4;v.Files=L4;v.Images=R4;v.Audio=p$;v.Moderations=I4;v.Models=S4;v.FineTuning=L$;v.Graders=Nw;v.VectorStores=E1;v.Webhooks=b4;v.Beta=n$;v.Batches=V4;v.Uploads=Uw;v.Responses=Kw;v.Realtime=Vw;v.Conversations=qw;v.Evals=Bw;v.Containers=Pw;class gY{client;constructor($){this.client=new v({...$,maxRetries:0})}async*stream($){let w=await this.client.chat.completions.create({model:$.model,messages:Ku($.messages),...$.tools.length?{tools:$.tools.map((Z)=>({type:"function",function:{name:Z.name,description:Z.description,parameters:Z.inputSchema}}))}:{},max_completion_tokens:$.maxOutputTokens,stream:!0,stream_options:{include_usage:!0}},$.signal?{signal:$.signal}:void 0),G=new Set;for await(let Z of w){let X=Z.choices[0]?.delta,Y=X?.reasoning_content;if(Y)yield{type:"reasoning_delta",text:Y};if(X?.content)yield{type:"text_delta",text:X.content};for(let J of X?.tool_calls??[]){let W=J.index;if(!G.has(W))G.add(W),yield{type:"tool_call_start",index:W,callId:J.id??`call_${W}`,name:J.function?.name??""};if(J.function?.arguments)yield{type:"tool_call_delta",index:W,argumentsDelta:J.function.arguments}}if(Z.usage)yield{type:"usage",usage:{inputTokens:Z.usage.prompt_tokens,outputTokens:Z.usage.completion_tokens}}}for(let Z of G)yield{type:"tool_call_end",index:Z};yield{type:"done"}}}function Ku($){return $.map((w)=>{if(w.role==="system"||w.role==="user")return{role:w.role,content:w.content};if(w.role==="tool")return{role:"tool",tool_call_id:w.callId,content:w.content};let G={role:"assistant",content:w.content||null};if(w.toolCalls.length)G.tool_calls=w.toolCalls.map((Z)=>({id:Z.callId,type:"function",function:{name:Z.name,arguments:JSON.stringify(Z.input)}}));return G})}import{createHash as Uu,randomUUID as MV}from"node:crypto";import{appendFile as Hu,chmod as PV,mkdir as Fu,readdir as Ou,readFile as qV}from"node:fs/promises";import Hw from"node:path";var fu=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;function BV($){return fu.test($)}function uY($){return Uu("sha256").update(Hw.resolve($)).digest("hex").slice(0,16)}class hY{workspace;sessionId;sessionPath;tracePath;#$=Promise.resolve();#w=!1;constructor($,w,G=MV()){this.workspace=w;this.sessionId=G;if(!BV(G))throw Error("Invalid session ID");let Z=Hw.join($,"sessions",uY(w));this.sessionPath=Hw.join(Z,`${G}.jsonl`),this.tracePath=Hw.join(Z,`${G}.trace.jsonl`)}get isCreated(){return this.#w}async create($=this.workspace){if(this.#w)return;await this.append("session.created",{workspace:$,sessionId:this.sessionId}),this.#w=!0}append($,w){let G={version:1,id:MV(),timestamp:new Date().toISOString(),type:$,data:w},Z=this.#$.then(async()=>{let X=Hw.dirname(this.sessionPath);await Fu(X,{recursive:!0,mode:448}),await PV(X,448),await Hu(this.sessionPath,`${JSON.stringify(G)}
337
+ `,{encoding:"utf8",mode:384}),await PV(this.sessionPath,384)});return this.#$=Z.catch(()=>{}),Z}appendMessage($){return this.append("message",$)}appendCompaction($,w){return this.append("context.compacted",w?{summary:$,sourceRange:w}:{summary:$})}setTitle($){return this.append("session.title",{title:$})}async list(){let $=Hw.dirname(this.sessionPath),w;try{w=await Ou($)}catch(Z){if(Z.code==="ENOENT")return[];throw Z}let G=[];for(let Z of w){if(!Z.endsWith(".jsonl")||Z.endsWith(".trace.jsonl"))continue;let X=Z.slice(0,-6);if(!BV(X))continue;try{G.push(await this.#G(Hw.join($,Z),X))}catch{}}return G.sort((Z,X)=>X.lastActivity.localeCompare(Z.lastActivity)),G}async#G($,w){let G=await qV($,"utf8"),Z=0,X,Y,J="";for(let Q of G.split(`
338
+ `)){if(!Q)continue;let z;try{z=JSON.parse(Q)}catch{continue}if(z.version!==1)continue;if(z.timestamp)J=z.timestamp;switch(z.type){case"session.reset":Z=0,Y=void 0,X=void 0;break;case"session.title":{let M=z.data;if(typeof M?.title==="string")X=M.title;break}case"message":if(Z++,Y===void 0){let M=z.data;if(M?.role==="user"&&typeof M.content==="string")Y=M.content}break}}let W=X??Y,T={id:w,messageCount:Z,lastActivity:J};if(W!==void 0)T.title=W;return T}async recover(){let $=[],w=[],G,Z,X=await qV(this.sessionPath,"utf8");this.#w=!0;let Y=X.split(`
339
+ `),J=-1;for(let Q=Y.length-1;Q>=0;Q--)if(Y[Q]){J=Q;break}for(let Q=0;Q<Y.length;Q++){let z=Y[Q];if(!z)continue;let M;try{M=JSON.parse(z)}catch(P){if(Q===J){w.push("Ignored incomplete final JSONL record");break}throw NV(Q,P)}try{if(M.version!==1)throw Error("unsupported schema version");if(M.type==="session.reset")$.length=0,G=void 0,Z=void 0;if(M.type==="message"){if(!Lu(M.data))throw Error("invalid message structure");$.push(M.data)}if(M.type==="context.compacted"){let P=M.data;if(typeof P?.summary!=="string")throw Error("invalid compaction record");G=P.summary,Z=typeof P.sourceRange?.start==="number"&&typeof P.sourceRange.end==="number"?{start:P.sourceRange.start,end:P.sourceRange.end}:void 0}}catch(P){throw NV(Q,P)}}let W=Du($,w);for(let Q of W)await this.appendMessage(Q);let T={messages:$,warnings:w};if(G!==void 0)T.summary=G;if(Z!==void 0)T.compactionRange=Z;return T}}function Lu($){if(!$||typeof $!=="object")return!1;let w=$;if((w.role==="system"||w.role==="user")&&typeof w.content==="string")return!0;if(w.role==="assistant"&&typeof w.content==="string")return Array.isArray(w.toolCalls)&&w.toolCalls.every((G)=>!!G&&typeof G==="object"&&typeof G.callId==="string"&&typeof G.name==="string"&&("input"in G));return w.role==="tool"&&typeof w.callId==="string"&&typeof w.name==="string"&&typeof w.content==="string"&&typeof w.isError==="boolean"}function NV($,w){return Error(`Invalid session record at line ${$+1}: ${w instanceof Error?w.message:String(w)}`)}function Du($,w){let G=new Map,Z=new Set;for(let Y of $)if(Y.role==="assistant"){if(G.size>0)throw Error("Assistant message appeared before pending tool results");for(let J of Y.toolCalls){if(Z.has(J.callId))throw Error(`Duplicate tool call ID: ${J.callId}`);Z.add(J.callId),G.set(J.callId,J.name)}}else if(Y.role==="tool"){if(!G.delete(Y.callId))throw Error(`Orphan tool result: ${Y.callId}`)}else if(G.size>0)throw Error(`${Y.role} message appeared before pending tool results`);if(G.size===0)return[];let X=[];for(let[Y,J]of G){let W={role:"tool",callId:Y,name:J,content:"runtime.interrupted: tool execution did not complete before the previous process exited",isError:!0};$.push(W),X.push(W)}return w.push(`Recovered ${G.size} interrupted tool call(s)`),X}import{readdir as Eu,realpath as vY,stat as Au}from"node:fs/promises";import Ru from"node:os";import k4 from"node:path";class mY{options;parser;constructor($){this.options=$;this.parser=$.parser??new J7}async discover(){let $=[],w=await this.scan("user",k4.join(this.options.home??Ru.homedir(),".agents","skills"),$),G=await this.scan("project",k4.join(this.options.workspace,".agents","skills"),$);return{registry:new c1([...w,...G]),failures:$}}async scan($,w,G){let Z;try{Z=await vY(w)}catch(J){if(J.code==="ENOENT")return[];return G.push({path:w,scope:$,reason:iY(J)}),[]}let X;try{X=await Eu(w,{withFileTypes:!0})}catch(J){return G.push({path:w,scope:$,reason:iY(J)}),[]}let Y=[];for(let J of X){if(!J.isDirectory()&&!J.isSymbolicLink())continue;let W=k4.join(w,J.name),T=k4.join(W,"SKILL.md");try{let Q=await vY(W),z=await vY(T);if(!VV(Q,Z)||!VV(z,Z))throw Error("skill path escapes its scan root through a symbolic link");let M=await Au(Q);if(!M.isDirectory())throw Error("skill root is not a directory");Y.push(await this.parser.parse({scope:$,rootPath:W,entryPath:T,rootRealPath:Q,entryRealPath:z,rootDevice:M.dev,rootInode:M.ino}))}catch(Q){G.push({path:W,scope:$,reason:iY(Q)})}}return Y}}function VV($,w){let G=k4.relative(w,$);return G===""||!G.startsWith("..")&&!k4.isAbsolute(G)}function iY($){return $ instanceof Error?$.message:String($)}var KV=A1(y9(),1);function UV($){let w=$.list();if(w.length===0)return"";return`Available skills:
340
+ ${w.map((G)=>`- ${G.name}: ${G.description}`).join(`
341
+ `)}
342
+
343
+ When a task matches a skill, call activate_skill before proceeding.`}function HV($,w=KV.default){let G=$.list();return G.length===0?`No active skills. Restart CodeN after adding standard .agents/skills entries.
344
+ `:`${G.map((Z)=>`${w.bold(Z.name)} (${Z.scope}): ${Z.description}`).join(`
345
+ `)}
346
+ `}function FV($=new c1){return[YG,WG,XG,GG,wG($)]}var Su={maxLines:20,maxValueChars:2000,maxDepth:4,maxSummaryColumns:120};function Fw($){return typeof $==="object"&&$!==null&&!Array.isArray($)?$:void 0}function OV($,w){let G=Fw(w?.properties),Z=G?Object.keys(G).filter((X)=>(X in $)):[];return[...Z,...Object.keys($).filter((X)=>!Z.includes(X))]}function Iu($,w){return Fw(Fw($?.properties)?.[w])}function ju($,w){let G=T0($),Z=Array.from(G);if(Z.length<=w)return G;let X=Z.length-w;return`${Z.slice(0,w).join("")}… [${X} characters omitted]`}function V3($,w){if(typeof $==="string")return ju($,w.maxValueChars);if($===null)return"null";if(typeof $==="number"||typeof $==="boolean"||typeof $==="bigint")return String($);if($===void 0)return"undefined";return}function K3($,w={}){let G={...Su,...w},Z=T0($.name);try{let X=[],Y=new WeakSet,J=Math.max(0,G.maxLines),W=(P)=>{if(X.length<=J)X.push(P)},T=(P,q,N,B,V)=>{if(X.length>J)return;let K=V===void 0?void 0:T0(V),U=V3(P,G);if(U!==void 0){let L=U.split(`
347
+ `);if(K!==void 0&&L.length===1)W(`${B}${K}: ${U}`);else if(K!==void 0){W(`${B}${K}:`);for(let C of L)W(`${B} ${C}`)}else for(let C of L)W(`${B}${C}`);return}if(N>=G.maxDepth){W(`${B}${K===void 0?"":`${K}: `}[max depth]`);return}if(typeof P!=="object"||P===null){W(`${B}${K===void 0?"":`${K}: `}${T0(String(P))}`);return}if(Y.has(P)){W(`${B}${K===void 0?"":`${K}: `}[circular]`);return}if(Y.add(P),Array.isArray(P)){if(P.length===0){W(`${B}${K===void 0?"":`${K}: `}[]`);return}if(K!==void 0)W(`${B}${K}:`);let L=K===void 0?B:`${B} `,C=Fw(q?.items);for(let S of P){if(X.length>J)break;let h=V3(S,G);if(h!==void 0&&!h.includes(`
348
+ `))W(`${L}- ${h}`);else W(`${L}-`),T(S,C,N+1,`${L} `)}return}let O=P,D=OV(O,q);if(D.length===0){W(`${B}${K===void 0?"":`${K}: `}{}`);return}if(K!==void 0)W(`${B}${K}:`);let f=K===void 0?B:`${B} `;for(let L of D){if(X.length>J)break;T(O[L],Iu(q,L),N+1,f,L)}};T($.input,Fw($.inputSchema),0,"");let Q=X;if(Q.length>J)Q=J===0?[]:[...Q.slice(0,J-1),"... [1 or more lines omitted]"];let z=Z,M=Fw($.input);if(M)for(let P of OV(M,Fw($.inputSchema))){let q=V3(M[P],G);if(q!==void 0){z=`${T0(P)}: ${q.split(`
349
+ `)[0]??""}`;break}}else{let P=V3($.input,G);if(P!==void 0)z=P.split(`
350
+ `)[0]??Z}return{lines:Q,summary:ew(T0(z),G.maxSummaryColumns)}}catch{return{lines:["[unavailable]"],summary:ew(Z,G.maxSummaryColumns)}}}var Cu=new Set(["read","write","edit"]);class lY{registry;permissions;events;workspace;timeoutMs;allowOutsideWorkspace;constructor($,w,G,Z,X=60000,Y=!1){this.registry=$;this.permissions=w;this.events=G;this.workspace=Z;this.timeoutMs=X;this.allowOutsideWorkspace=Y}setRegistry($){this.registry=$}async execute($,w,G){await this.events.emit("tool.requested",{name:$.name,callId:$.callId},G);let Z=this.registry.get($.name);if(!Z)return{content:`tool.not_found: ${$.name}`,isError:!0};let X=this.registry.validate($.name,$.input);if(!X.valid)return{content:`tool.invalid_input: ${X.errors}`,isError:!0};let Y;if(Cu.has($.name)){try{Y=await ZG(this.workspace,$.input.path)}catch(q){return{content:`permission.workspace_denied: ${q instanceof Error?q.message:String(q)}`,isError:!0}}if(Y.scope==="outside"&&!this.allowOutsideWorkspace&&this.permissions.isAuto)return await this.events.emit("permission.requested",{name:$.name,callId:$.callId,risk:"modify",allowed:!1},G),await this.events.emit("tool.completed",{name:$.name,callId:$.callId,isError:!0,durationMs:0},G),{content:"permission.outside_workspace_denied: rerun with --auto --allow-outside-workspace",isError:!0}}let J=await this.permissions.authorize(Z,$,w,Y?.scope==="outside"?"modify":void 0);if(await this.events.emit("permission.requested",{name:$.name,callId:$.callId,risk:J.risk,allowed:J.allowed},G),!J.allowed)return{content:`permission.denied: ${$.name} was not authorized`,isError:!0};let W=K3({name:Z.name,risk:J.risk,inputSchema:Z.inputSchema,input:$.input});await this.events.emit("tool.started",{name:$.name,callId:$.callId,summary:W.summary},G);let T=Date.now(),Q,z=new AbortController,M=()=>z.abort(w.reason);if(w.aborted)M();else w.addEventListener("abort",M,{once:!0});let P=setTimeout(()=>z.abort(Error(`Tool timed out after ${this.timeoutMs}ms`)),this.timeoutMs);try{let q=z.signal.aborted?Promise.reject(z.signal.reason):new Promise((N,B)=>{z.signal.addEventListener("abort",()=>B(z.signal.reason),{once:!0})});Q=await Promise.race([Z.execute($.input,{workspace:this.workspace,signal:z.signal,...Y?{structuredFilePath:Y}:{}}),q]),Q={...Q,content:Ew(Q.content,50000)}}catch(q){Q={content:`${!w.aborted&&z.signal.aborted?"tool.timeout (abort requested; tools must cooperate)":"tool.internal_error"}: ${q instanceof Error?q.message:String(q)}`,isError:!0}}finally{clearTimeout(P),w.removeEventListener("abort",M)}return await this.events.emit("tool.completed",{name:$.name,callId:$.callId,isError:Q.isError??!1,durationMs:Date.now()-T},G),Q}}import{createHash as bu,randomUUID as ku}from"node:crypto";import{readdir as yu,readFile as _u,realpath as xu,stat as fV}from"node:fs/promises";import LV from"node:path";import{pathToFileURL as dY}from"node:url";class K6{builtins;events;auto;trust;importer;static defaultImporter=($)=>import($);#$=new Map;constructor($,w,G,Z,X=K6.defaultImporter){this.builtins=$;this.events=w;this.auto=G;this.trust=Z;this.importer=X}async load($,w){let G=w?.clone()??new q$(this.builtins),Z=[],X=[];for(let Y of $)try{let J=await xu(Y.path),W=await fV(J),T=W.isDirectory()?J:LV.dirname(J);if(Y.project&&!this.auto){if(!(this.trust?await this.trust(T):!1)){await this.events.emit("plugin.unavailable",{path:T,reason:"not trusted"});continue}}let Q=W.isDirectory()?(await yu(J)).filter((z)=>z.endsWith(".ts")).sort().map((z)=>LV.join(J,z)):J.endsWith(".ts")?[J]:[];for(let z of Q)try{let M=await this.importPlugin(z);if(!gu(M.default))throw Error("default export is not a ToolDefinition");G.register(M.default,{kind:"local",path:z}),Z.push(M.default.name),await this.events.emit("plugin.loaded",{path:z,name:M.default.name})}catch(M){X.push(z),await this.events.emit("plugin.failed",{path:z,message:M instanceof Error?M.message:String(M)})}}catch(J){if(J.code!=="ENOENT")X.push(Y.path),await this.events.emit("plugin.failed",{path:Y.path,message:J instanceof Error?J.message:String(J)})}return{registry:G,loaded:Z,failed:X}}async importPlugin($){if(this.importer!==K6.defaultImporter){let J=(await fV($)).mtimeMs;return this.importer(`${dY($).href}?mtime=${J}`)}let w=await _u($,"utf8"),G=bu("sha256").update(w).digest("hex"),Z=this.#$.get($);if(Z?.hash===G)return Z.module;let X=`// coden-source: ${dY($).href}
351
+ // coden-load: ${ku()}
205
352
  ${w}
206
- //# sourceURL=${L3($).href}
207
- `,Z=await this.importer(`data:text/typescript;base64,${Buffer.from(Y).toString("base64")}`);return this.#$.set($,{hash:G,module:Z}),Z}}function nL($){if(!$||typeof $!=="object")return!1;let w=$;return typeof w.name==="string"&&typeof w.description==="string"&&(w.risk==="read"||w.risk==="modify"||w.risk==="dangerous")&&!!w.inputSchema&&typeof w.execute==="function"}var mf="0.1.5";function pL($,w){let G=Number.isFinite(w)?Math.max(0,Math.min($.length,Math.trunc(w))):0,W=0;for(let Y of H1($)){let Z=W+Y.length;if(G<Z)return W;W=Z}return W}function tL($){let w=[],G=0;while(G<=$.length){let W=$.indexOf(`
208
- `,G);if(W===-1){w.push({text:$.slice(G),start:G});break}if(w.push({text:$.slice(G,W),start:G}),G=W+1,G===$.length){w.push({text:"",start:G});break}}if(w.length===0)w.push({text:"",start:0});return w}function rL($,w){let G=[],W=w;for(let Y of H1($))G.push({text:Y,offset:W}),W+=Y.length;return G}function lf($,w,G,W,Y,Z){return{prefix:$,start:w,end:G,text:W,width:Y,positions:Z}}function W8($,w,G,W=4){let Y=pL($,w),Z=Number.isFinite(G)?Math.trunc(G):0,X=Math.max(1,Z-2),J=Number.isFinite(W)&&W>0?Math.trunc(W):4,T=[],M=0,f=0,Q=2,N=!1;for(let z of tL($)){let K=rL(z.text,z.start);if(K.length===0){let S=[{offset:z.start,column:0}];if(T.push(lf(M===0?"> ":" ",z.start,z.start,"",0,S)),!N&&Y===z.start)f=T.length-1,Q=2,N=!0;M+=1;continue}let P=K[0];if(!P)continue;let q=P.offset,V="",E=0,O=q,A=[{offset:q,column:0}],R=()=>{if(T.push(lf(M===0?"> ":" ",q,O,V,E,A)),!N&&Y===O)f=T.length-1,Q=2+E,N=!0;M+=1};for(let S of K){let _=S.text==="\t"?J-E%J:Jw(S.text);if(V.length>0&&E+_>X)R(),q=S.offset,V="",E=0,O=q,A=[{offset:q,column:0}];let e=S.text==="\t"?J-E%J:Jw(S.text);if(!N&&Y===S.offset&&A.length===1&&V.length===0)f=T.length,Q=2,N=!0;let v=A[A.length-1];if(!v||v.offset!==S.offset||v.column!==E)A.push({offset:S.offset,column:E});if(V+=S.text==="\t"?" ".repeat(e):S.text,E+=e,O=S.offset+S.text.length,A.push({offset:O,column:E}),!N&&Y===O)f=T.length,Q=2+E,N=!0}R()}if(!N){let z=T[T.length-1];f=z?T.length-1:0,Q=2+(z?z.positions[z.positions.length-1]?.column??0:0)}return{rows:T,cursor:{row:f,column:Q}}}function cf($,w){let G=$.positions[0]??{offset:$.start,column:0};for(let W of $.positions)if(Math.abs(W.column-w)<Math.abs(G.column-w))G=W;return G.offset}function G1($,w){let G=Number.isFinite(w)?Math.max(0,Math.min($.length,Math.trunc(w))):0,W=0;for(let Y of H1($)){let Z=W+Y.length;if(G<Z)return W;W=Z}return W}function df($){let w=[0],G=0;for(let W of H1($))G+=W.length,w.push(G);return w}function P5($){for(let w of $)if(!/\s/u.test(w))return!1;return $.length>0}function sL($){let w=0;for(let G=$.length-1;G>=0&&$[G]==="\\";G--)w++;return w}function D3($,w,G){let W=G1($,w);if(G)return{type:"continue",text:`${$.slice(0,W)}
209
- ${$.slice(W)}`,cursor:W+1};if(W<$.length)return{type:"submit",text:$};let Y=sL($);if(Y===0)return{type:"submit",text:$};let Z=$.slice(0,$.length-Y)+"\\".repeat(Math.floor(Y/2));if(Y%2===1)return{type:"continue",text:`${Z}
210
- `,cursor:Z.length+1};return{type:"submit",text:Z}}class k3{_text="";_cursor=0;preferredColumn;_entries;historyIndex=null;savedDraft=null;constructor($=[]){this._entries=[...$]}get text(){return this._text}get cursor(){return this._cursor}get entries(){return this._entries}setDraft($,w=$.length){this._text=$,this._cursor=G1($,w)}resetPreferredColumn(){this.preferredColumn=void 0}boundaries(){return df(this._text)}loadHistory($){let w=this._entries[$];if(w===void 0)return;this.historyIndex=$,this.setDraft(w,w.length),this.resetPreferredColumn()}insert($){if(!$)return;let w=G1(this._text,this._cursor);this._text=`${this._text.slice(0,w)}${$}${this._text.slice(w)}`,this._cursor=w+$.length,this.resetPreferredColumn()}backspace(){let $=this.boundaries(),w=G1(this._text,this._cursor),G=$.indexOf(w);if(G<=0)return;let W=$[G-1]??0;this._text=`${this._text.slice(0,W)}${this._text.slice(w)}`,this._cursor=G1(this._text,w),this.resetPreferredColumn()}deleteForward(){let $=this.boundaries(),w=G1(this._text,this._cursor),G=$.indexOf(w);if(G<0||G>=$.length-1)return;let W=$[G+1]??this._text.length;this._text=`${this._text.slice(0,w)}${this._text.slice(W)}`,this._cursor=w,this.resetPreferredColumn()}moveHorizontal($){let w=this.boundaries(),G=G1(this._text,this._cursor),W=w.indexOf(G);if(W<0)return;let Y=W+$;if(Y<0||Y>=w.length)return;this._cursor=w[Y]??G,this.resetPreferredColumn()}moveVertical($,w){let G=W8(this._text,this._cursor,w),W=Math.max(0,G.cursor.column-2);if(this.preferredColumn===void 0)this.preferredColumn=W;let Y=G.cursor.row+$;if(Y>=0&&Y<G.rows.length){let Z=G.rows[Y];if(Z)this._cursor=cf(Z,this.preferredColumn);return}if($<0)this.historyPrevious();else this.historyNext()}historyPrevious(){if(this._entries.length===0)return;if(this.historyIndex===null){this.savedDraft={text:this._text,cursor:this._cursor},this.loadHistory(this._entries.length-1);return}if(this.historyIndex>0)this.loadHistory(this.historyIndex-1)}historyNext(){if(this.historyIndex===null)return;if(this.historyIndex<this._entries.length-1){this.loadHistory(this.historyIndex+1);return}let $=this.savedDraft??{text:"",cursor:0};this.historyIndex=null,this.setDraft($.text,$.cursor),this.resetPreferredColumn()}moveLineBoundary($){let w=G1(this._text,this._cursor),G=$==="start"?this._text.lastIndexOf(`
211
- `,Math.max(0,w-1))+1:(()=>{let W=this._text.indexOf(`
212
- `,w);return W===-1?this._text.length:W})();if(G===w)return;this._cursor=G,this.resetPreferredColumn()}moveWord($){let w=H1(this._text),G=df(this._text),W=G.indexOf(G1(this._text,this._cursor));if(W<0)return;if($<0){while(W>0&&P5(w[W-1]??""))W--;while(W>0&&!P5(w[W-1]??""))W--}else{while(W<w.length&&!P5(w[W]??""))W++;while(W<w.length&&P5(w[W]??""))W++}let Y=G[W]??this._text.length;if(Y===this._cursor)return;this._cursor=Y,this.resetPreferredColumn()}deleteWordBackward(){let $=this._cursor;this.moveWord(-1);let w=this._cursor;if(w===$)return;this._text=`${this._text.slice(0,w)}${this._text.slice($)}`,this._cursor=w,this.resetPreferredColumn()}deleteToLineBoundary($){let w=G1(this._text,this._cursor),G=$==="start"?this._text.lastIndexOf(`
213
- `,Math.max(0,w-1))+1:(()=>{let W=this._text.indexOf(`
214
- `,w);return W===-1?this._text.length:W})();if(G===w)return;if($==="start")this._text=`${this._text.slice(0,G)}${this._text.slice(w)}`,this._cursor=G;else this._text=`${this._text.slice(0,w)}${this._text.slice(G)}`,this._cursor=w;this.resetPreferredColumn()}enter($){let w=D3(this._text,this._cursor,$);if(w.type==="continue")return this._text=w.text,this._cursor=G1(w.text,w.cursor),this.resetPreferredColumn(),{type:"continue"};return w}interrupt(){if(!this._text)return"eof";return this.reset(),"cleared"}endOfInput(){if(!this._text)return"eof";return this.deleteForward(),"deleted"}remember($){if(!$.trim())return;if(this._entries[this._entries.length-1]===$)return;this._entries.push($)}reset(){this._text="",this._cursor=0,this.preferredColumn=void 0,this.historyIndex=null,this.savedDraft=null}}var A3=2000;function aL($,w){let G=$.replace(/\s+/g," ").trim();return G.length<=w?G:`${G.slice(0,w-1)}…`}function oL($){let w=new Date($);if(Number.isNaN(w.getTime()))return $;let G=(W)=>String(W).padStart(2,"0");return`${w.getFullYear()}-${G(w.getMonth()+1)}-${G(w.getDate())} ${G(w.getHours())}:${G(w.getMinutes())}`}function S3($,w){if($.length===0)return`No sessions found.
215
- `;let G=$.map((Y)=>{let Z=Y.title?aL(Y.title,40):"(no title)",X=Y.messageCount===0?"new session":`${Y.messageCount} messages`,J=Y.id===w?" *":"";return`${Y.id}${J} ${Z} (${X}, ${oL(Y.lastActivity)})`}),W=w?`Current session: ${w}
353
+ //# sourceURL=${dY($).href}
354
+ `,Y=await this.importer(`data:text/typescript;base64,${Buffer.from(X).toString("base64")}`);return this.#$.set($,{hash:G,module:Y}),Y}}function gu($){if(!$||typeof $!=="object")return!1;let w=$;return typeof w.name==="string"&&typeof w.description==="string"&&(w.risk==="read"||w.risk==="modify"||w.risk==="dangerous")&&!!w.inputSchema&&typeof w.execute==="function"}var DV="0.1.6";function uu($,w){let G=Number.isFinite(w)?Math.max(0,Math.min($.length,Math.trunc(w))):0,Z=0;for(let X of y$($)){let Y=Z+X.length;if(G<Y)return Z;Z=Y}return Z}function hu($){let w=[],G=0;while(G<=$.length){let Z=$.indexOf(`
355
+ `,G);if(Z===-1){w.push({text:$.slice(G),start:G});break}if(w.push({text:$.slice(G,Z),start:G}),G=Z+1,G===$.length){w.push({text:"",start:G});break}}if(w.length===0)w.push({text:"",start:0});return w}function vu($,w){let G=[],Z=w;for(let X of y$($))G.push({text:X,offset:Z}),Z+=X.length;return G}function EV($,w,G,Z,X,Y){return{prefix:$,start:w,end:G,text:Z,width:X,positions:Y}}function U6($,w,G,Z=4){let X=uu($,w),Y=Number.isFinite(G)?Math.trunc(G):0,J=Math.max(1,Y-2),W=Number.isFinite(Z)&&Z>0?Math.trunc(Z):4,T=[],Q=0,z=0,M=2,P=!1;for(let q of hu($)){let N=vu(q.text,q.start);if(N.length===0){let L=[{offset:q.start,column:0}];if(T.push(EV(Q===0?"> ":" ",q.start,q.start,"",0,L)),!P&&X===q.start)z=T.length-1,M=2,P=!0;Q+=1;continue}let B=N[0];if(!B)continue;let V=B.offset,K="",U=0,O=V,D=[{offset:V,column:0}],f=()=>{if(T.push(EV(Q===0?"> ":" ",V,O,K,U,D)),!P&&X===O)z=T.length-1,M=2+U,P=!0;Q+=1};for(let L of N){let C=L.text==="\t"?W-U%W:ow(L.text);if(K.length>0&&U+C>J)f(),V=L.offset,K="",U=0,O=V,D=[{offset:V,column:0}];let h=L.text==="\t"?W-U%W:ow(L.text);if(!P&&X===L.offset&&D.length===1&&K.length===0)z=T.length,M=2,P=!0;let g=D[D.length-1];if(!g||g.offset!==L.offset||g.column!==U)D.push({offset:L.offset,column:U});if(K+=L.text==="\t"?" ".repeat(h):L.text,U+=h,O=L.offset+L.text.length,D.push({offset:O,column:U}),!P&&X===O)z=T.length,M=2+U,P=!0}f()}if(!P){let q=T[T.length-1];z=q?T.length-1:0,M=2+(q?q.positions[q.positions.length-1]?.column??0:0)}return{rows:T,cursor:{row:z,column:M}}}function AV($,w){let G=$.positions[0]??{offset:$.start,column:0};for(let Z of $.positions)if(Math.abs(Z.column-w)<Math.abs(G.column-w))G=Z;return G.offset}function M$($,w){let G=Number.isFinite(w)?Math.max(0,Math.min($.length,Math.trunc(w))):0,Z=0;for(let X of y$($)){let Y=Z+X.length;if(G<Y)return Z;Z=Y}return Z}function RV($){let w=[0],G=0;for(let Z of y$($))G+=Z.length,w.push(G);return w}function U3($){for(let w of $)if(!/\s/u.test(w))return!1;return $.length>0}function iu($){let w=0;for(let G=$.length-1;G>=0&&$[G]==="\\";G--)w++;return w}function cY($,w,G){let Z=M$($,w);if(G)return{type:"continue",text:`${$.slice(0,Z)}
356
+ ${$.slice(Z)}`,cursor:Z+1};if(Z<$.length)return{type:"submit",text:$};let X=iu($);if(X===0)return{type:"submit",text:$};let Y=$.slice(0,$.length-X)+"\\".repeat(Math.floor(X/2));if(X%2===1)return{type:"continue",text:`${Y}
357
+ `,cursor:Y.length+1};return{type:"submit",text:Y}}class pY{_text="";_cursor=0;preferredColumn;_entries;historyIndex=null;savedDraft=null;constructor($=[]){this._entries=[...$]}get text(){return this._text}get cursor(){return this._cursor}get entries(){return this._entries}setDraft($,w=$.length){this._text=$,this._cursor=M$($,w)}resetPreferredColumn(){this.preferredColumn=void 0}boundaries(){return RV(this._text)}loadHistory($){let w=this._entries[$];if(w===void 0)return;this.historyIndex=$,this.setDraft(w,w.length),this.resetPreferredColumn()}insert($){if(!$)return;let w=M$(this._text,this._cursor);this._text=`${this._text.slice(0,w)}${$}${this._text.slice(w)}`,this._cursor=w+$.length,this.resetPreferredColumn()}backspace(){let $=this.boundaries(),w=M$(this._text,this._cursor),G=$.indexOf(w);if(G<=0)return;let Z=$[G-1]??0;this._text=`${this._text.slice(0,Z)}${this._text.slice(w)}`,this._cursor=M$(this._text,w),this.resetPreferredColumn()}deleteForward(){let $=this.boundaries(),w=M$(this._text,this._cursor),G=$.indexOf(w);if(G<0||G>=$.length-1)return;let Z=$[G+1]??this._text.length;this._text=`${this._text.slice(0,w)}${this._text.slice(Z)}`,this._cursor=w,this.resetPreferredColumn()}moveHorizontal($){let w=this.boundaries(),G=M$(this._text,this._cursor),Z=w.indexOf(G);if(Z<0)return;let X=Z+$;if(X<0||X>=w.length)return;this._cursor=w[X]??G,this.resetPreferredColumn()}moveVertical($,w){let G=U6(this._text,this._cursor,w),Z=Math.max(0,G.cursor.column-2);if(this.preferredColumn===void 0)this.preferredColumn=Z;let X=G.cursor.row+$;if(X>=0&&X<G.rows.length){let Y=G.rows[X];if(Y)this._cursor=AV(Y,this.preferredColumn);return}if($<0)this.historyPrevious();else this.historyNext()}historyPrevious(){if(this._entries.length===0)return;if(this.historyIndex===null){this.savedDraft={text:this._text,cursor:this._cursor},this.loadHistory(this._entries.length-1);return}if(this.historyIndex>0)this.loadHistory(this.historyIndex-1)}historyNext(){if(this.historyIndex===null)return;if(this.historyIndex<this._entries.length-1){this.loadHistory(this.historyIndex+1);return}let $=this.savedDraft??{text:"",cursor:0};this.historyIndex=null,this.setDraft($.text,$.cursor),this.resetPreferredColumn()}moveLineBoundary($){let w=M$(this._text,this._cursor),G=$==="start"?this._text.lastIndexOf(`
358
+ `,Math.max(0,w-1))+1:(()=>{let Z=this._text.indexOf(`
359
+ `,w);return Z===-1?this._text.length:Z})();if(G===w)return;this._cursor=G,this.resetPreferredColumn()}moveWord($){let w=y$(this._text),G=RV(this._text),Z=G.indexOf(M$(this._text,this._cursor));if(Z<0)return;if($<0){while(Z>0&&U3(w[Z-1]??""))Z--;while(Z>0&&!U3(w[Z-1]??""))Z--}else{while(Z<w.length&&!U3(w[Z]??""))Z++;while(Z<w.length&&U3(w[Z]??""))Z++}let X=G[Z]??this._text.length;if(X===this._cursor)return;this._cursor=X,this.resetPreferredColumn()}deleteWordBackward(){let $=this._cursor;this.moveWord(-1);let w=this._cursor;if(w===$)return;this._text=`${this._text.slice(0,w)}${this._text.slice($)}`,this._cursor=w,this.resetPreferredColumn()}deleteToLineBoundary($){let w=M$(this._text,this._cursor),G=$==="start"?this._text.lastIndexOf(`
360
+ `,Math.max(0,w-1))+1:(()=>{let Z=this._text.indexOf(`
361
+ `,w);return Z===-1?this._text.length:Z})();if(G===w)return;if($==="start")this._text=`${this._text.slice(0,G)}${this._text.slice(w)}`,this._cursor=G;else this._text=`${this._text.slice(0,w)}${this._text.slice(G)}`,this._cursor=w;this.resetPreferredColumn()}enter($){let w=cY(this._text,this._cursor,$);if(w.type==="continue")return this._text=w.text,this._cursor=M$(w.text,w.cursor),this.resetPreferredColumn(),{type:"continue"};return w}interrupt(){if(!this._text)return"eof";return this.reset(),"cleared"}endOfInput(){if(!this._text)return"eof";return this.deleteForward(),"deleted"}remember($){if(!$.trim())return;if(this._entries[this._entries.length-1]===$)return;this._entries.push($)}reset(){this._text="",this._cursor=0,this.preferredColumn=void 0,this.historyIndex=null,this.savedDraft=null}}var nY=2000;function mu($,w){let G=$.replace(/\s+/g," ").trim();return G.length<=w?G:`${G.slice(0,w-1)}…`}function lu($){let w=new Date($);if(Number.isNaN(w.getTime()))return $;let G=(Z)=>String(Z).padStart(2,"0");return`${w.getFullYear()}-${G(w.getMonth()+1)}-${G(w.getDate())} ${G(w.getHours())}:${G(w.getMinutes())}`}function rY($,w){if($.length===0)return`No sessions found.
362
+ `;let G=$.map((X)=>{let Y=X.title?mu(X.title,40):"(no title)",J=X.messageCount===0?"new session":`${X.messageCount} messages`,W=X.id===w?" *":"";return`${X.id}${W} ${Y} (${J}, ${lu(X.lastActivity)})`}),Z=w?`Current session: ${w}
216
363
  `:"";return`${G.join(`
217
364
  `)}
218
- ${W}`}function nf($,w,G,W=80){let Y=K5({name:$.name,risk:G,inputSchema:$.inputSchema,input:w.input},{maxLines:1/0,maxValueChars:1/0,maxDepth:1/0}),Z=`${G.toUpperCase()} ${$.name}`,X=Y.lines.map((M)=>` ${M}`).join(`
219
- `),J=G==="dangerous"?"[y]es / [N]o":"[y]es / [s]ession / [N]o",T=eL(W);return`${T}
220
- ${Z}
365
+ ${Z}`}function SV($,w,G,Z=80){let X=K3({name:$.name,risk:G,inputSchema:$.inputSchema,input:w.input},{maxLines:1/0,maxValueChars:1/0,maxDepth:1/0}),Y=`${G.toUpperCase()} ${$.name}`,J=X.lines.map((Q)=>` ${Q}`).join(`
366
+ `),W=G==="dangerous"?"[y]es / [N]o":"[y]es / [s]ession / [N]o",T=du(Z);return`${T}
367
+ ${Y}
221
368
 
222
- ${X}
369
+ ${J}
223
370
  ${T}
224
- Allow? ${J}: `}function eL($){return"─".repeat(Math.max(1,$))}function pf($,w){let G=(Z)=>Z.role==="user"||Z.role==="assistant",W=[`Resumed session ${$} (${w.length} messages).`];for(let Z of w.filter(G))W.push(Z.role==="user"?$D(Z.content):wD(Z.content));let Y=WD(w);if(Y)W.push(Y);return W.join(`
371
+ Allow? ${W}: `}function du($){return"─".repeat(Math.max(1,$))}function IV($,w){let G=(Y)=>Y.role==="user"||Y.role==="assistant",Z=[`Resumed session ${$} (${w.length} messages).`];for(let Y of w.filter(G))Z.push(Y.role==="user"?cu(Y.content):pu(Y.content));let X=ru(w);if(X)Z.push(X);return Z.join(`
225
372
 
226
- `)}function $D($){return $.split(`
373
+ `)}function cu($){return $.split(`
227
374
  `).map((w,G)=>G===0?`> ${w}`:` ${w}`).join(`
228
- `)}function wD($){let{text:w,omitted:G}=GD($),W="",Y=new k4((X)=>{W+=X});if(Y.push(w),Y.complete(),!G)return W;return`${W.endsWith(`
229
- `)?W:`${W}
230
- `}…(已省略 ${G} 个字符)`}function GD($){let w=[...$];return w.length<=A3?{text:$,omitted:0}:{text:w.slice(0,A3).join(""),omitted:w.length-A3}}function WD($){let w=new Map;for(let X of $)if(X.role==="assistant")for(let J of X.toolCalls)w.set(J.name,(w.get(J.name)??0)+1);if(w.size===0)return;let G=[...w.values()].reduce((X,J)=>X+J,0),W=0;for(let X of $)if(X.role==="tool"&&X.isError)W++;let Y=[...w.entries()].sort((X,J)=>J[1]-X[1]||X[0].localeCompare(J[0])).map(([X,J])=>`${X} ×${J}`).join(", "),Z=`Tools: ${G} calls — ${Y}`;return W>0?`${Z}; ${W} failed`:Z}import{StringDecoder as YD}from"node:string_decoder";import{stripVTControlCharacters as ZD}from"node:util";var XD="\x1B",JD="\x1B[200~",tf="\x1B[201~",TD=new Set(["\x1B[13;2u","\x1B[27;2;13~","\x1B\r",`\x1B
231
- `]),MD=new Map([["\x1B[A","up"],["\x1B[B","down"],["\x1B[C","right"],["\x1B[D","left"],["\x1B[H","home"],["\x1B[F","end"],["\x1B[3~","delete"],["\x1B[1~","home"],["\x1B[4~","end"]]),fD=new Map([[1,"ctrl-a"],[3,"ctrl-c"],[4,"ctrl-d"],[5,"ctrl-e"],[9,"tab"],[10,"enter"],[11,"ctrl-k"],[13,"enter"],[14,"ctrl-n"],[16,"ctrl-p"],[21,"ctrl-u"],[23,"ctrl-w"],[127,"backspace"]]);function QD($){let w=$.codePointAt(0)??-1;return w>=0&&w<=8||w>=11&&w<=12||w>=14&&w<=31||w===127}function rf($){let w=$.replace(/\r\n?/g,`
232
- `),G=ZD(w);return Array.from(G).filter((W)=>!QD(W)).join("")}function ND($){let w=$.codePointAt(0)??0;return w>=64&&w<=126}function zD($){return fD.get($)}class R3{decoder=new YD("utf8");pending="";inPaste=!1;pasteBuffer="";push($){let w=typeof $==="string"?$:this.decoder.write($);if(this.inPaste){if(w)this.pasteBuffer+=w;return this.consumePasteBuffer()}if(w)this.pending+=w;return this.consumeNormalBuffer()}end(){let $=this.push(this.decoder.end());if(this.inPaste){let w=rf(this.pasteBuffer);if(this.pasteBuffer="",this.inPaste=!1,w)$.push({type:"paste",text:w})}return this.pending="",$}consumePasteBuffer(){let $=[];while(this.inPaste){let w=this.pasteBuffer.indexOf(tf);if(w===-1)return $;let G=this.pasteBuffer.slice(0,w),W=this.pasteBuffer.slice(w+tf.length);this.pasteBuffer="",this.inPaste=!1;let Y=rf(G);if(Y)$.push({type:"paste",text:Y});if(W)this.pending+=W;if(!this.pending)return $;return $.concat(this.consumeNormalBuffer())}return $}consumeNormalBuffer(){let $=this.pending,w=[],G=0,W=0,Y=(Z)=>{if(Z>W)w.push({type:"text",text:$.slice(W,Z)})};while(G<$.length){let Z=$.charAt(G);if(Z!==XD){let J=zD(Z.codePointAt(0)??0);if(J!==void 0){Y(G),w.push({type:"key",key:J}),G+=1,W=G;continue}G+=1;continue}Y(G);let X=this.consumeEscape($,G);if(X.kind==="incomplete")return this.pending=$.slice(G),w;if(G=X.nextIndex,W=G,X.kind==="paste-start")return this.pending="",this.inPaste=!0,this.pasteBuffer=$.slice(G),w.concat(this.consumePasteBuffer());if(X.kind==="key")w.push({type:"key",key:X.key})}return Y($.length),this.pending="",w}consumeEscape($,w){let G=$[w+1];if(G===void 0)return{kind:"incomplete"};if(G==="["){let W=w+2;while(W<$.length&&!ND($[W]??""))W+=1;if(W>=$.length)return{kind:"incomplete"};let Y=$.slice(w,W+1);if(Y===JD)return{kind:"paste-start",nextIndex:W+1};if(Y==="\x1B[13;2u"||Y==="\x1B[27;2;13~")return{kind:"key",key:"shift-enter",nextIndex:W+1};let Z=MD.get(Y);if(Z!==void 0)return{kind:"key",key:Z,nextIndex:W+1};return{kind:"ignore",nextIndex:W+1}}if(G==="b"||G==="B")return{kind:"key",key:"alt-b",nextIndex:w+2};if(G==="f"||G==="F")return{kind:"key",key:"alt-f",nextIndex:w+2};if(G==="\r"||G===`
233
- `){let W=$.slice(w,w+2);if(TD.has(W))return{kind:"key",key:"shift-enter",nextIndex:w+2};return{kind:"ignore",nextIndex:w+2}}return{kind:"ignore",nextIndex:w+2}}}var KD="\x1B[?2004h",PD="\x1B[?2004l";class B5{input;output;resizeEmitter;signalEmitter;terminate;term;state=new k3;active;disposed=!1;renderedRows=0;renderedCursorRow=0;constructor($={}){this.input=$.input??process.stdin,this.output=$.output??process.stderr,this.resizeEmitter=$.resizeEmitter??process,this.signalEmitter=$.signalEmitter??process,this.terminate=$.terminate??((w)=>process.kill(process.pid,w)),this.term=$.term}static supported($,w,G){let W=$,Y=w;return $.isTTY===!0&&Y.isTTY===!0&&typeof W.setRawMode==="function"&&(G??process.env.TERM)!=="dumb"}read(){if(this.disposed)return Promise.reject(Error("MultilineEditor is disposed"));if(this.active)return Promise.reject(Error("MultilineEditor read is already active"));return new Promise(($,w)=>{let G=new R3,W={decoder:G,resolve:$,reject:w,rawMode:this.input.isRaw,data:(Y)=>this.handleEvents(G.push(Y)),end:()=>{this.handleEvents(G.end()),this.finish({type:"eof"})},error:(Y)=>this.fail(Y),resize:()=>this.redraw(),sigint:()=>this.finish({type:"eof"}),sighup:()=>this.stopForSignal("SIGHUP"),sigterm:()=>this.stopForSignal("SIGTERM")};this.active=W,this.renderedRows=0,this.renderedCursorRow=0,this.state.reset();try{this.input.setRawMode(!0),this.input.resume(),this.output.write(KD),this.install(W),this.redraw()}catch(Y){this.fail(Y instanceof Error?Y:Error(String(Y)))}})}dispose(){this.disposed=!0,this.finish({type:"eof"})}install($){this.input.on("data",$.data),this.input.on("end",$.end),this.input.on("error",$.error),this.resizeEmitter.on("SIGWINCH",$.resize),this.signalEmitter.on("SIGINT",$.sigint),this.signalEmitter.on("SIGHUP",$.sighup),this.signalEmitter.on("SIGTERM",$.sigterm)}cleanup(){let $=this.active;if(!$)return;return this.active=void 0,this.input.removeListener("data",$.data),this.input.removeListener("end",$.end),this.input.removeListener("error",$.error),this.resizeEmitter.removeListener("SIGWINCH",$.resize),this.signalEmitter.removeListener("SIGINT",$.sigint),this.signalEmitter.removeListener("SIGHUP",$.sighup),this.signalEmitter.removeListener("SIGTERM",$.sigterm),this.output.write(PD),this.input.setRawMode($.rawMode??!1),this.input.pause(),this.renderedRows=0,this.renderedCursorRow=0,$}finish($){this.cleanup()?.resolve($)}fail($){this.cleanup()?.reject($)}stopForSignal($){this.finish({type:"eof"}),this.terminate($)}handleEvents($){if(!this.active)return;for(let w of $){if(!this.active)return;if(w.type==="text"||w.type==="paste")this.state.insert(w.text),this.redraw();else this.handleKey(w.key)}}handleKey($){if(!this.active)return;switch($){case"enter":case"shift-enter":{let w=this.state.enter($==="shift-enter");if(w.type==="submit"){this.state.remember(w.text),this.redraw(W8(w.text,w.text.length,this.columns())),this.output.write(`
234
- `),this.finish({type:"submit",text:w.text});return}break}case"left":this.state.moveHorizontal(-1);break;case"right":this.state.moveHorizontal(1);break;case"up":this.state.moveVertical(-1,this.columns());break;case"down":this.state.moveVertical(1,this.columns());break;case"home":case"ctrl-a":this.state.moveLineBoundary("start");break;case"end":case"ctrl-e":this.state.moveLineBoundary("end");break;case"backspace":this.state.backspace();break;case"delete":this.state.deleteForward();break;case"ctrl-d":if(this.state.endOfInput()==="eof"){this.finish({type:"eof"});return}break;case"ctrl-c":if(this.state.interrupt()==="eof"){this.finish({type:"eof"});return}break;case"ctrl-k":this.state.deleteToLineBoundary("end");break;case"ctrl-n":this.state.historyNext();break;case"ctrl-p":this.state.historyPrevious();break;case"ctrl-u":this.state.deleteToLineBoundary("start");break;case"ctrl-w":this.state.deleteWordBackward();break;case"alt-b":this.state.moveWord(-1);break;case"alt-f":this.state.moveWord(1);break;case"tab":this.state.insert("\t");break}this.redraw()}columns(){return this.output.columns??80}redraw($=W8(this.state.text,this.state.cursor,this.columns())){if(!this.active)return;if(this.renderedRows>0){if(this.output.write("\r"),this.renderedCursorRow>0)this.output.write(`\x1B[${this.renderedCursorRow}A`);this.output.write("\x1B[J")}for(let G=0;G<$.rows.length;G++){let W=$.rows[G];if(!W)continue;if(this.output.write(`${W.prefix}${W.text}`),G<$.rows.length-1)this.output.write(`
235
- `)}let w=$.rows.length-1-$.cursor.row;if(w>0)this.output.write(`\x1B[${w}A`);if(this.output.write("\r"),$.cursor.column>0)this.output.write(`\x1B[${$.cursor.column}C`);this.renderedRows=$.rows.length,this.renderedCursorRow=$.cursor.row}}class mw extends Error{}async function BD($,w){try{return await pJ($,w)}catch(G){throw new mw(`configuration: ${G instanceof Error?G.message:String(G)}`,{cause:G})}}async function of($,w){let G=process.cwd(),W=await BD(G,{...w.provider?{provider:w.provider}:{},...w.model?{model:w.model}:{},...w.maxSteps?{maxSteps:w.maxSteps}:{},plugins:w.plugin}),Y=new tG,Z=!$&&!w.print&&B5.supported(j3,process.stderr,process.env.TERM),J=(!w.auto||!$&&!w.print)&&!Z?sf({input:j3,output:process.stderr}):void 0,M=J?(a,h0)=>C3(J,a,h0):async(a,h0)=>{let l$=sf({input:j3,output:process.stderr});try{return await C3(l$,a,h0)}finally{l$.close()}},f=Z?new B5:void 0,Q=typeof w.resume==="string"?w.resume:void 0,N=new F3(W.dataDir,G,Q);if(w.resume===!0){J?.close(),d0.write(S3(await N.list()));return}let z,K,P=0,q;if(typeof w.resume==="string"){let a=await N.recover();z=a.messages,K=a.summary,P=a.compactionRange?.end??0;for(let h0 of a.warnings)process.stderr.write(`coden: ${h0}
236
- `);if(!w.print)q=pf(N.sessionId,a.messages)}let V=new NW(N.tracePath,Y,()=>N.isCreated),E=new QW(Y,{verbose:w.verbose,printMode:w.print}),O;try{O=ED(W.provider)}catch(a){throw new mw(`provider: ${a instanceof Error?a.message:String(a)}`,{cause:a})}let A=gf(),R=w.auto?void 0:HD(M),S=new zW(w.auto,R),_=new Z1(A),s=new O3(_,S,Y,G),e=new dG(V5.join(t8(),"trusted-workspaces.json")),v=new G8(A,Y,w.auto,async(a)=>{if(await e.isTrusted(a))return!0;let h0=await FD(M,`Project plugins at ${a} run with full process permissions. Trust? [y/N] `);if(h0)await e.trust(a);return h0}),H0=new _G,x1=q4(G,"global",W.dataDir),W1=q4(G,"project",W.dataDir),lw=[{path:V5.join(t8(),"plugins"),project:!1},{path:V5.join(G,".coden","plugins"),project:!0},...W.plugins.map((a)=>({path:V5.resolve(G,a),project:!0}))],cw=new Map,TQ=async()=>{await new C0(x1).recover(),await new C0(W1).recover();let a=await af(H0,x1,Y,"global"),l$=w.auto||await e.isWorkspaceTrusted(G)?await af(H0,W1,Y,"project"):{loaded:[],failed:[],unavailable:!0};if(l$.unavailable)await Y.emit("plugin.unavailable",{source:"npm",scope:"project",path:W1.root,reason:"workspace is not trusted; run coden plugin install or sync after trusting"});let v3=await VD(A,a.loaded,l$.loaded,Y);for(let{scope:MQ,plugin:dw}of v3.effective){let E5=`${MQ}:${dw.version}`,Y8=cw.get(dw.packageName);if(Y8&&Y8!==E5)await Y.emit("plugin.restart_required",{source:"npm",packageName:dw.packageName,loadedIdentity:Y8,diskIdentity:E5,loadedVersion:Y8.split(":").slice(1).join(":"),diskVersion:dw.version,reason:"npm plugin metadata changed; restart CodeN to load it"});cw.set(dw.packageName,E5)}return{composed:v3,global:a,project:l$}},b3=async()=>{let a=await TQ(),h0=await v.load(lw,a.composed.registry);return _.replaceWith(h0.registry),h0};await b3();let x3=await qD(G),_3=new nG({contextWindow:W.contextWindow,reservedOutputTokens:W.reservedOutputTokens,safetyMargin:W.safetyMargin});if(K)_3.setSummary(K,P);let g3=new rG(O,_,s,_3,N,Y,{model:W.model,maxSteps:W.maxSteps,systemPrompt:"You are CodeN, a concise coding agent. Inspect before editing, use tools carefully, and verify changes."+(x3?`
375
+ `)}function pu($){let{text:w,omitted:G}=nu($),Z="",X=new i9((J)=>{Z+=J});if(X.push(w),X.complete(),!G)return Z;return`${Z.endsWith(`
376
+ `)?Z:`${Z}
377
+ `}…(已省略 ${G} 个字符)`}function nu($){let w=[...$];return w.length<=nY?{text:$,omitted:0}:{text:w.slice(0,nY).join(""),omitted:w.length-nY}}function ru($){let w=new Map;for(let J of $)if(J.role==="assistant")for(let W of J.toolCalls)w.set(W.name,(w.get(W.name)??0)+1);if(w.size===0)return;let G=[...w.values()].reduce((J,W)=>J+W,0),Z=0;for(let J of $)if(J.role==="tool"&&J.isError)Z++;let X=[...w.entries()].sort((J,W)=>W[1]-J[1]||J[0].localeCompare(W[0])).map(([J,W])=>`${J} ×${W}`).join(", "),Y=`Tools: ${G} calls — ${X}`;return Z>0?`${Y}; ${Z} failed`:Y}import{StringDecoder as su}from"node:string_decoder";import{stripVTControlCharacters as au}from"node:util";var tu="\x1B",ou="\x1B[200~",jV="\x1B[201~",eu=new Set(["\x1B[13;2u","\x1B[27;2;13~","\x1B\r",`\x1B
378
+ `]),$h=new Map([["\x1B[A","up"],["\x1B[B","down"],["\x1B[C","right"],["\x1B[D","left"],["\x1B[H","home"],["\x1B[F","end"],["\x1B[3~","delete"],["\x1B[1~","home"],["\x1B[4~","end"]]),wh=new Map([[1,"ctrl-a"],[3,"ctrl-c"],[4,"ctrl-d"],[5,"ctrl-e"],[9,"tab"],[10,"enter"],[11,"ctrl-k"],[13,"enter"],[14,"ctrl-n"],[16,"ctrl-p"],[21,"ctrl-u"],[23,"ctrl-w"],[127,"backspace"]]);function Gh($){let w=$.codePointAt(0)??-1;return w>=0&&w<=8||w>=11&&w<=12||w>=14&&w<=31||w===127}function CV($){let w=$.replace(/\r\n?/g,`
379
+ `),G=au(w);return Array.from(G).filter((Z)=>!Gh(Z)).join("")}function Zh($){let w=$.codePointAt(0)??0;return w>=64&&w<=126}function Xh($){return wh.get($)}class sY{decoder=new su("utf8");pending="";inPaste=!1;pasteBuffer="";push($){let w=typeof $==="string"?$:this.decoder.write($);if(this.inPaste){if(w)this.pasteBuffer+=w;return this.consumePasteBuffer()}if(w)this.pending+=w;return this.consumeNormalBuffer()}end(){let $=this.push(this.decoder.end());if(this.inPaste){let w=CV(this.pasteBuffer);if(this.pasteBuffer="",this.inPaste=!1,w)$.push({type:"paste",text:w})}return this.pending="",$}consumePasteBuffer(){let $=[];while(this.inPaste){let w=this.pasteBuffer.indexOf(jV);if(w===-1)return $;let G=this.pasteBuffer.slice(0,w),Z=this.pasteBuffer.slice(w+jV.length);this.pasteBuffer="",this.inPaste=!1;let X=CV(G);if(X)$.push({type:"paste",text:X});if(Z)this.pending+=Z;if(!this.pending)return $;return $.concat(this.consumeNormalBuffer())}return $}consumeNormalBuffer(){let $=this.pending,w=[],G=0,Z=0,X=(Y)=>{if(Y>Z)w.push({type:"text",text:$.slice(Z,Y)})};while(G<$.length){let Y=$.charAt(G);if(Y!==tu){let W=Xh(Y.codePointAt(0)??0);if(W!==void 0){X(G),w.push({type:"key",key:W}),G+=1,Z=G;continue}G+=1;continue}X(G);let J=this.consumeEscape($,G);if(J.kind==="incomplete")return this.pending=$.slice(G),w;if(G=J.nextIndex,Z=G,J.kind==="paste-start")return this.pending="",this.inPaste=!0,this.pasteBuffer=$.slice(G),w.concat(this.consumePasteBuffer());if(J.kind==="key")w.push({type:"key",key:J.key})}return X($.length),this.pending="",w}consumeEscape($,w){let G=$[w+1];if(G===void 0)return{kind:"incomplete"};if(G==="["){let Z=w+2;while(Z<$.length&&!Zh($[Z]??""))Z+=1;if(Z>=$.length)return{kind:"incomplete"};let X=$.slice(w,Z+1);if(X===ou)return{kind:"paste-start",nextIndex:Z+1};if(X==="\x1B[13;2u"||X==="\x1B[27;2;13~")return{kind:"key",key:"shift-enter",nextIndex:Z+1};let Y=$h.get(X);if(Y!==void 0)return{kind:"key",key:Y,nextIndex:Z+1};return{kind:"ignore",nextIndex:Z+1}}if(G==="b"||G==="B")return{kind:"key",key:"alt-b",nextIndex:w+2};if(G==="f"||G==="F")return{kind:"key",key:"alt-f",nextIndex:w+2};if(G==="\r"||G===`
380
+ `){let Z=$.slice(w,w+2);if(eu.has(Z))return{kind:"key",key:"shift-enter",nextIndex:w+2};return{kind:"ignore",nextIndex:w+2}}return{kind:"ignore",nextIndex:w+2}}}var Yh="\x1B[?2004h",Jh="\x1B[?2004l";class H3{input;output;resizeEmitter;signalEmitter;terminate;term;state=new pY;active;disposed=!1;renderedRows=0;renderedCursorRow=0;constructor($={}){this.input=$.input??process.stdin,this.output=$.output??process.stderr,this.resizeEmitter=$.resizeEmitter??process,this.signalEmitter=$.signalEmitter??process,this.terminate=$.terminate??((w)=>process.kill(process.pid,w)),this.term=$.term}static supported($,w,G){let Z=$,X=w;return $.isTTY===!0&&X.isTTY===!0&&typeof Z.setRawMode==="function"&&(G??process.env.TERM)!=="dumb"}read(){if(this.disposed)return Promise.reject(Error("MultilineEditor is disposed"));if(this.active)return Promise.reject(Error("MultilineEditor read is already active"));return new Promise(($,w)=>{let G=new sY,Z={decoder:G,resolve:$,reject:w,rawMode:this.input.isRaw,data:(X)=>this.handleEvents(G.push(X)),end:()=>{this.handleEvents(G.end()),this.finish({type:"eof"})},error:(X)=>this.fail(X),resize:()=>this.redraw(),sigint:()=>this.finish({type:"eof"}),sighup:()=>this.stopForSignal("SIGHUP"),sigterm:()=>this.stopForSignal("SIGTERM")};this.active=Z,this.renderedRows=0,this.renderedCursorRow=0,this.state.reset();try{this.input.setRawMode(!0),this.input.resume(),this.output.write(Yh),this.install(Z),this.redraw()}catch(X){this.fail(X instanceof Error?X:Error(String(X)))}})}dispose(){this.disposed=!0,this.finish({type:"eof"})}install($){this.input.on("data",$.data),this.input.on("end",$.end),this.input.on("error",$.error),this.resizeEmitter.on("SIGWINCH",$.resize),this.signalEmitter.on("SIGINT",$.sigint),this.signalEmitter.on("SIGHUP",$.sighup),this.signalEmitter.on("SIGTERM",$.sigterm)}cleanup(){let $=this.active;if(!$)return;return this.active=void 0,this.input.removeListener("data",$.data),this.input.removeListener("end",$.end),this.input.removeListener("error",$.error),this.resizeEmitter.removeListener("SIGWINCH",$.resize),this.signalEmitter.removeListener("SIGINT",$.sigint),this.signalEmitter.removeListener("SIGHUP",$.sighup),this.signalEmitter.removeListener("SIGTERM",$.sigterm),this.output.write(Jh),this.input.setRawMode($.rawMode??!1),this.input.pause(),this.renderedRows=0,this.renderedCursorRow=0,$}finish($){this.cleanup()?.resolve($)}fail($){this.cleanup()?.reject($)}stopForSignal($){this.finish({type:"eof"}),this.terminate($)}handleEvents($){if(!this.active)return;for(let w of $){if(!this.active)return;if(w.type==="text"||w.type==="paste")this.state.insert(w.text),this.redraw();else this.handleKey(w.key)}}handleKey($){if(!this.active)return;switch($){case"enter":case"shift-enter":{let w=this.state.enter($==="shift-enter");if(w.type==="submit"){this.state.remember(w.text),this.redraw(U6(w.text,w.text.length,this.columns())),this.output.write(`
381
+ `),this.finish({type:"submit",text:w.text});return}break}case"left":this.state.moveHorizontal(-1);break;case"right":this.state.moveHorizontal(1);break;case"up":this.state.moveVertical(-1,this.columns());break;case"down":this.state.moveVertical(1,this.columns());break;case"home":case"ctrl-a":this.state.moveLineBoundary("start");break;case"end":case"ctrl-e":this.state.moveLineBoundary("end");break;case"backspace":this.state.backspace();break;case"delete":this.state.deleteForward();break;case"ctrl-d":if(this.state.endOfInput()==="eof"){this.finish({type:"eof"});return}break;case"ctrl-c":if(this.state.interrupt()==="eof"){this.finish({type:"eof"});return}break;case"ctrl-k":this.state.deleteToLineBoundary("end");break;case"ctrl-n":this.state.historyNext();break;case"ctrl-p":this.state.historyPrevious();break;case"ctrl-u":this.state.deleteToLineBoundary("start");break;case"ctrl-w":this.state.deleteWordBackward();break;case"alt-b":this.state.moveWord(-1);break;case"alt-f":this.state.moveWord(1);break;case"tab":this.state.insert("\t");break}this.redraw()}columns(){return this.output.columns??80}redraw($=U6(this.state.text,this.state.cursor,this.columns())){if(!this.active)return;if(this.renderedRows>0){if(this.output.write("\r"),this.renderedCursorRow>0)this.output.write(`\x1B[${this.renderedCursorRow}A`);this.output.write("\x1B[J")}for(let G=0;G<$.rows.length;G++){let Z=$.rows[G];if(!Z)continue;if(this.output.write(`${Z.prefix}${Z.text}`),G<$.rows.length-1)this.output.write(`
382
+ `)}let w=$.rows.length-1-$.cursor.row;if(w>0)this.output.write(`\x1B[${w}A`);if(this.output.write("\r"),$.cursor.column>0)this.output.write(`\x1B[${$.cursor.column}C`);this.renderedRows=$.rows.length,this.renderedCursorRow=$.cursor.row}}class Ow extends Error{}async function Wh($,w){try{return await qM($,w)}catch(G){throw new Ow(`configuration: ${G instanceof Error?G.message:String(G)}`,{cause:G})}}async function yV($,w){let G=process.cwd();if(w.allowOutsideWorkspace&&!w.auto)throw new Ow("--allow-outside-workspace requires --auto");let Z=await Wh(G,{...w.provider?{provider:w.provider}:{},...w.model?{model:w.model}:{},...w.maxSteps?{maxSteps:w.maxSteps}:{},plugins:w.plugin}),X=new M7,Y=!$&&!w.print&&H3.supported(aY,process.stderr,process.env.TERM),W=(!w.auto||!$&&!w.print)&&!Y?bV({input:aY,output:process.stderr}):void 0,Q=W?(o,p0)=>tY(W,o,p0):async(o,p0)=>{let Dw=bV({input:aY,output:process.stderr});try{return await tY(Dw,o,p0)}finally{Dw.close()}},z=Y?new H3:void 0,M=typeof w.resume==="string"?w.resume:void 0,P=new hY(Z.dataDir,G,M);if(w.resume===!0){W?.close(),d0.write(rY(await P.list()));return}let q,N,B=0,V;if(typeof w.resume==="string"){let o=await P.recover();q=o.messages,N=o.summary,B=o.compactionRange?.end??0;for(let p0 of o.warnings)process.stderr.write(`coden: ${p0}
383
+ `);if(!w.print)V=IV(P.sessionId,o.messages)}let K=new I7(P.tracePath,X,()=>P.isCreated),U=new S7(X,{verbose:w.verbose,printMode:w.print}),O;try{O=Mh(Z.provider)}catch(o){throw new Ow(`provider: ${o instanceof Error?o.message:String(o)}`,{cause:o})}let D=await new mY({workspace:G}).discover();if(w.verbose)for(let o of D.failures)process.stderr.write(`coden: ignored ${o.scope} skill ${o.path}: ${o.reason}
384
+ `);let f=D.registry,L=FV(f),C=w.auto?void 0:qh(Q),S=new j7(w.auto,C),h=new q$(L),g=new lY(h,S,X,G,60000,w.allowOutsideWorkspace),G0=new T7(F3.join(Q5(),"trusted-workspaces.json")),e=new K6(L,X,w.auto,async(o)=>{if(await G0.isTrusted(o))return!0;let p0=await Bh(Q,`Project plugins at ${o} run with full process permissions. Trust? [y/N] `);if(p0)await G0.trust(o);return p0}),c0=new vZ,fw=J9(G,"global",Z.dataDir),Lw=J9(G,"project",Z.dataDir),dV=[{path:F3.join(Q5(),"plugins"),project:!1},{path:F3.join(G,".coden","plugins"),project:!0},...Z.plugins.map((o)=>({path:F3.resolve(G,o),project:!0}))],$J=new Map,cV=async()=>{await new _0(fw).recover(),await new _0(Lw).recover();let o=await kV(c0,fw,X,"global"),Dw=w.auto||await G0.isWorkspaceTrusted(G)?await kV(c0,Lw,X,"project"):{loaded:[],failed:[],unavailable:!0};if(Dw.unavailable)await X.emit("plugin.unavailable",{source:"npm",scope:"project",path:Lw.root,reason:"workspace is not trusted; run coden plugin install or sync after trusting"});let XJ=await Th(L,o.loaded,Dw.loaded,X);for(let{scope:nV,plugin:y4}of XJ.effective){let L3=`${nV}:${y4.version}`,H6=$J.get(y4.packageName);if(H6&&H6!==L3)await X.emit("plugin.restart_required",{source:"npm",packageName:y4.packageName,loadedIdentity:H6,diskIdentity:L3,loadedVersion:H6.split(":").slice(1).join(":"),diskVersion:y4.version,reason:"npm plugin metadata changed; restart CodeN to load it"});$J.set(y4.packageName,L3)}return{composed:XJ,global:o,project:Dw}},wJ=async()=>{let o=await cV(),p0=await e.load(dV,o.composed.registry);return h.replaceWith(p0.registry),p0};await wJ();let pV=await Qh(G),f3=zh(pV,UV(f));if(q?.length)if(q[0]?.role==="system")q[0]={role:"system",content:f3};else q.unshift({role:"system",content:f3});let GJ=new Q7({contextWindow:Z.contextWindow,reservedOutputTokens:Z.reservedOutputTokens,safetyMargin:Z.safetyMargin});if(N)GJ.setSummary(N,B);let ZJ=new P7(O,h,g,GJ,P,X,{model:Z.model,maxSteps:Z.maxSteps,systemPrompt:f3},q);try{if($){await xV(ZJ,$,W);return}if(w.print)throw Error("print mode requires a prompt");await Ph(ZJ,P,wJ,h,f,W,z,uY(G),V)}finally{z?.dispose(),W?.close(),U.dispose(),await K.flush()}}async function Th($,w,G,Z){let X=new q$($),Y=new Set(G.map((T)=>T.packageName)),J=[...w.map((T)=>({scope:"global",plugin:T})),...G.map((T)=>({scope:"project",plugin:T}))],W=[];for(let T of J){if(T.scope==="global"&&Y.has(T.plugin.packageName))continue;let Q=X.clone(),z={kind:"npm",pluginName:T.plugin.packageName,pluginVersion:T.plugin.version,path:T.plugin.entryPath};try{for(let M of T.plugin.tools)Q.register(M,z);X.replaceWith(Q),W.push(T)}catch(M){await Z.emit("plugin.failed",{source:"npm",scope:T.scope,packageName:T.plugin.packageName,version:T.plugin.version,path:T.plugin.entryPath,message:`${M instanceof Error?M.message:String(M)}; package skipped to preserve earlier tools`})}}return{registry:X,effective:W}}async function kV($,w,G,Z){try{let X=await $.loadScope(w);for(let Y of X.loaded)await G.emit("plugin.loaded",{source:"npm",scope:Z,packageName:Y.packageName,version:Y.version,path:Y.entryPath,tools:Y.tools.map((J)=>J.name)});for(let Y of X.failed)await G.emit("plugin.failed",{source:"npm",scope:Z,packageName:Y.packageName,path:Y.path,message:`${Y.message}; run coden plugin sync to repair the runtime`});return X}catch(X){let Y=X instanceof Error?X.message:String(X);return await G.emit("plugin.failed",{source:"npm",scope:Z,path:w.runtimeDir,message:`${Y}; run coden plugin sync to repair the runtime`}),{loaded:[],failed:[],unavailable:!0}}}async function Qh($){try{return await yq($,"AGENTS.md")}catch(w){if(w.code==="ENOENT")return"";if(w.category==="permission")return process.stderr.write(`coden: ignoring AGENTS.md: ${w.message}
385
+ `),"";throw new Ow(`project instructions: ${w instanceof Error?w.message:String(w)}`,{cause:w})}}function zh($,w){return"You are CodeN, a concise coding agent. Inspect before editing, use tools carefully, and verify changes."+($?`
237
386
 
238
387
  Project instructions:
239
- ${x3}`:"")},z);try{if($){await $Q(g3,$,J);return}if(w.print)throw Error("print mode requires a prompt");await UD(g3,N,b3,_,J,f,H3(G),q)}finally{f?.dispose(),J?.close(),E.dispose(),await V.flush()}}async function VD($,w,G,W){let Y=new Z1($),Z=new Set(G.map((T)=>T.packageName)),X=[...w.map((T)=>({scope:"global",plugin:T})),...G.map((T)=>({scope:"project",plugin:T}))],J=[];for(let T of X){if(T.scope==="global"&&Z.has(T.plugin.packageName))continue;let M=Y.clone(),f={kind:"npm",pluginName:T.plugin.packageName,pluginVersion:T.plugin.version,path:T.plugin.entryPath};try{for(let Q of T.plugin.tools)M.register(Q,f);Y.replaceWith(M),J.push(T)}catch(Q){await W.emit("plugin.failed",{source:"npm",scope:T.scope,packageName:T.plugin.packageName,version:T.plugin.version,path:T.plugin.entryPath,message:`${Q instanceof Error?Q.message:String(Q)}; package skipped to preserve earlier tools`})}}return{registry:Y,effective:J}}async function af($,w,G,W){try{let Y=await $.loadScope(w);for(let Z of Y.loaded)await G.emit("plugin.loaded",{source:"npm",scope:W,packageName:Z.packageName,version:Z.version,path:Z.entryPath,tools:Z.tools.map((X)=>X.name)});for(let Z of Y.failed)await G.emit("plugin.failed",{source:"npm",scope:W,packageName:Z.packageName,path:Z.path,message:`${Z.message}; run coden plugin sync to repair the runtime`});return Y}catch(Y){let Z=Y instanceof Error?Y.message:String(Y);return await G.emit("plugin.failed",{source:"npm",scope:W,path:w.runtimeDir,message:`${Z}; run coden plugin sync to repair the runtime`}),{loaded:[],failed:[],unavailable:!0}}}async function qD($){try{return await wT($,"AGENTS.md")}catch(w){if(w.code==="ENOENT")return"";if(w.category==="permission")return process.stderr.write(`coden: ignoring AGENTS.md: ${w.message}
240
- `),"";throw new mw(`project instructions: ${w instanceof Error?w.message:String(w)}`,{cause:w})}}function ED($){if($==="anthropic"){let G=process.env.CODEN_ANTHROPIC_API_KEY;if(!G)throw Error("CODEN_ANTHROPIC_API_KEY is required");return new gW({apiKey:G})}let w=process.env.CODEN_OPENAI_API_KEY;if(!w)throw Error("CODEN_OPENAI_API_KEY is required");return new U3({apiKey:w,...process.env.CODEN_OPENAI_BASE_URL?{baseURL:process.env.CODEN_OPENAI_BASE_URL}:{}})}async function UD($,w,G,W,Y,Z,X,J){d0.write(AD),d0.write(`Version: ${mf}
241
- `),d0.write(`Workspace hash: ${X}
242
- `),d0.write(J?`${J}
388
+ ${$}`:"")+(w?`
389
+
390
+ ${w}`:"")}function Mh($){if($==="anthropic"){let G=process.env.CODEN_ANTHROPIC_API_KEY;if(!G)throw Error("CODEN_ANTHROPIC_API_KEY is required");return new $Y({apiKey:G})}let w=process.env.CODEN_OPENAI_API_KEY;if(!w)throw Error("CODEN_OPENAI_API_KEY is required");return new gY({apiKey:w,...process.env.CODEN_OPENAI_BASE_URL?{baseURL:process.env.CODEN_OPENAI_BASE_URL}:{}})}async function Ph($,w,G,Z,X,Y,J,W,T){d0.write(Hh),d0.write(`Version: ${DV}
391
+ `),d0.write(`Workspace hash: ${W}
392
+ `),d0.write(T?`${T}
243
393
 
244
394
  Type /help for commands.
245
395
  `:`CodeN session ${w.sessionId}. Type /help for commands.
246
- `);while(!0){let T=Z?await Z.read():await DD(async(f)=>{let Q=await C3(kD(Y),f);return Q===ef?void 0:Q});if(T.type==="eof")break;let M=LD(T.text);if(M.type==="empty")continue;if(M.type==="command"&&M.command==="/quit")break;if(M.type==="command"&&M.command==="/help"){d0.write(`/help /session /sessions /compact /reload /new /quit
247
- `);continue}if(M.type==="command"&&M.command==="/sessions"){d0.write(S3(await w.list(),w.sessionId));continue}if(M.type==="command"&&M.command==="/session"){d0.write(`${w.sessionId}
248
- `);continue}if(M.type==="command"&&M.command==="/compact"){await $.compact(),d0.write(`Context compacted.
249
- `);continue}if(M.type==="command"&&M.command==="/new"){await $.reset(),d0.write(`Started a new conversation in this session.
250
- `);continue}if(M.type==="command"&&M.command==="/reload"){let f=await G();d0.write(`Loaded: ${f.loaded.join(", ")||"none"}; failed: ${f.failed.length}; tools: ${W.list().map((Q)=>Q.name).join(", ")}
251
- `);continue}if(M.type==="message")await $Q($,M.text,Y)}}function HD($){return async(w,G,W,Y)=>{let Z=d0.columns??80,X=await $(nf(w,G,W,Z),Y);return X.toLowerCase()==="y"?"allow_once":X.toLowerCase()==="s"&&W!=="dangerous"?"allow_session":"deny"}}var ef="\x04";async function C3($,w,G){let W=G?void 0:new AbortController,Y=G??W?.signal,Z=()=>W?.abort(Error("Cancelled by user"));if(W)process.once("SIGINT",Z),$.once("SIGINT",Z);try{return Y?await $.question(w,{signal:Y}):await $.question(w)}catch(X){if(Y?.aborted)return"";if(X.code==="ERR_USE_AFTER_CLOSE"||/readline was closed/.test(X.message))return ef;throw X}finally{if(W)process.removeListener("SIGINT",Z),$.removeListener("SIGINT",Z)}}async function FD($,w){return/^y(?:es)?$/i.test(await $(w))}var OD=new Set(["/help","/session","/sessions","/compact","/reload","/new","/quit"]);function LD($){if(!$.trim())return{type:"empty"};let w=$.trim();if(!$.includes(`
252
- `)&&OD.has(w))return{type:"command",command:w};return{type:"message",text:$}}async function DD($){let w="",G=!0;while(!0){let W=await $(G?"> ":" ");if(W===void 0)return{type:"eof"};let Y=`${w}${W}`,Z=D3(Y,Y.length,!1);if(Z.type==="submit")return Z;w=Z.text,G=!1}}function kD($){if(!$)throw Error("Interactive input is unavailable");return $}async function $Q($,w,G){let W=new AbortController,Y=()=>W.abort(Error("Cancelled by user"));process.once("SIGINT",Y),G?.once("SIGINT",Y);try{await $.run(w,W.signal)}catch(Z){if(!W.signal.aborted)throw Z}finally{process.removeListener("SIGINT",Y),G?.removeListener("SIGINT",Y)}}function wQ($){if($!=="openai"&&$!=="anthropic")throw new cG("must be openai or anthropic");return $}function GQ($){let w=Number($);if(!Number.isInteger(w)||w<1)throw new cG("must be a positive integer");return w}function WQ($,w){return[...w,$]}var AD=`
396
+ `);while(!0){let Q=J?await J.read():await Kh(async(M)=>{let P=await tY(Uh(Y),M);return P===_V?void 0:P});if(Q.type==="eof")break;let z=Vh(Q.text);if(z.type==="empty")continue;if(z.type==="command"&&z.command==="/quit")break;if(z.type==="command"&&z.command==="/help"){d0.write(`/help /skills /session /sessions /compact /reload /new /quit
397
+ `);continue}if(z.type==="command"&&z.command==="/skills"){d0.write(HV(X));continue}if(z.type==="command"&&z.command==="/sessions"){d0.write(rY(await w.list(),w.sessionId));continue}if(z.type==="command"&&z.command==="/session"){d0.write(`${w.sessionId}
398
+ `);continue}if(z.type==="command"&&z.command==="/compact"){await $.compact(),d0.write(`Context compacted.
399
+ `);continue}if(z.type==="command"&&z.command==="/new"){await $.reset(),d0.write(`Started a new conversation in this session.
400
+ `);continue}if(z.type==="command"&&z.command==="/reload"){let M=await G();d0.write(`Loaded: ${M.loaded.join(", ")||"none"}; failed: ${M.failed.length}; tools: ${Z.list().map((P)=>P.name).join(", ")}
401
+ `);continue}if(z.type==="message")await xV($,z.text,Y)}}function qh($){return async(w,G,Z,X)=>{let Y=d0.columns??80,J=await $(SV(w,G,Z,Y),X);return J.toLowerCase()==="y"?"allow_once":J.toLowerCase()==="s"&&Z!=="dangerous"?"allow_session":"deny"}}var _V="\x04";async function tY($,w,G){let Z=G?void 0:new AbortController,X=G??Z?.signal,Y=()=>Z?.abort(Error("Cancelled by user"));if(Z)process.once("SIGINT",Y),$.once("SIGINT",Y);try{return X?await $.question(w,{signal:X}):await $.question(w)}catch(J){if(X?.aborted)return"";if(J.code==="ERR_USE_AFTER_CLOSE"||/readline was closed/.test(J.message))return _V;throw J}finally{if(Z)process.removeListener("SIGINT",Y),$.removeListener("SIGINT",Y)}}async function Bh($,w){return/^y(?:es)?$/i.test(await $(w))}var Nh=new Set(["/help","/skills","/session","/sessions","/compact","/reload","/new","/quit"]);function Vh($){if(!$.trim())return{type:"empty"};let w=$.trim();if(!$.includes(`
402
+ `)&&Nh.has(w))return{type:"command",command:w};return{type:"message",text:$}}async function Kh($){let w="",G=!0;while(!0){let Z=await $(G?"> ":" ");if(Z===void 0)return{type:"eof"};let X=`${w}${Z}`,Y=cY(X,X.length,!1);if(Y.type==="submit")return Y;w=Y.text,G=!1}}function Uh($){if(!$)throw Error("Interactive input is unavailable");return $}async function xV($,w,G){let Z=new AbortController,X=()=>Z.abort(Error("Cancelled by user"));process.once("SIGINT",X),G?.once("SIGINT",X);try{await $.run(w,Z.signal)}catch(Y){if(!Z.signal.aborted)throw Y}finally{process.removeListener("SIGINT",X),G?.removeListener("SIGINT",X)}}function gV($){if($!=="openai"&&$!=="anthropic")throw new W7("must be openai or anthropic");return $}function uV($){let w=Number($);if(!Number.isInteger(w)||w<1)throw new W7("must be a positive integer");return w}function hV($,w){return[...w,$]}var Hh=`
253
403
  ██████╗ ██████╗ ██████╗ ███████╗███╗ ██╗
254
404
  ██╔════╝██╔═══██╗██╔══██╗██╔════╝████╗ ██║
255
405
  ██║ ██║ ██║██║ ██║█████╗ ██╔██╗ ██║
256
406
  ██║ ██║ ██║██║ ██║██╔══╝ ██║╚██╗██║
257
407
  ╚██████╗╚██████╔╝██████╔╝███████╗██║ ╚████║
258
408
  ╚═════╝ ╚═════╝ ╚═════╝ ╚══════╝╚═╝ ╚═══╝
259
- `;function ZQ($,w){let G=$.command("plugin").description("manage installed npm plugins");G.command("install").argument("<specifier>","npm:<package> or npm:<package>@<version-or-tag>").option("--global","install in the user-global scope").option("--allow-scripts","allow npm lifecycle scripts with full user permissions during dependency install").option("--yes","skip confirmation prompts").action((W,Y)=>q5(w,async()=>{let Z=y3(Y);if(!await I3(w,"Install",W,Y))return;let X=await w.service.install(W,Z);w.stdout.write(SD(X,Z.allowScripts))})),G.command("remove").argument("<package>","installed npm package name").option("--global","remove from the user-global scope").option("--allow-scripts","allow npm lifecycle scripts with full user permissions while rebuilding dependencies").option("--yes","skip confirmation prompts").action((W,Y)=>q5(w,async()=>{let Z=y3(Y);if(!await I3(w,"Remove",W,Y))return;await w.service.remove(W,Z),w.stdout.write(`Removed ${W} from ${Z.scope} plugins.
409
+ `;function iV($,w){let G=$.command("plugin").description("manage installed npm plugins");G.command("install").argument("<specifier>","npm:<package> or npm:<package>@<version-or-tag>").option("--global","install in the user-global scope").option("--allow-scripts","allow npm lifecycle scripts with full user permissions during dependency install").option("--yes","skip confirmation prompts").action((Z,X)=>O3(w,async()=>{let Y=oY(X);if(!await eY(w,"Install",Z,X))return;let J=await w.service.install(Z,Y);w.stdout.write(Fh(J,Y.allowScripts))})),G.command("remove").argument("<package>","installed npm package name").option("--global","remove from the user-global scope").option("--allow-scripts","allow npm lifecycle scripts with full user permissions while rebuilding dependencies").option("--yes","skip confirmation prompts").action((Z,X)=>O3(w,async()=>{let Y=oY(X);if(!await eY(w,"Remove",Z,X))return;await w.service.remove(Z,Y),w.stdout.write(`Removed ${Z} from ${Y.scope} plugins.
260
410
  Restart CodeN to use npm plugin changes.
261
- `)})),G.command("list").option("--project","show only project plugins").option("--global","show only user-global plugins").action((W)=>q5(w,async()=>{if(W.project&&W.global)throw Error("plugin list accepts only one of --project or --global");let Y=await w.service.list();w.stdout.write(jD(Y,W))})),G.command("sync").option("--global","sync the user-global plugin runtime").option("--allow-scripts","allow npm lifecycle scripts with full user permissions during dependency install").option("--yes","skip confirmation prompts").action((W)=>q5(w,async()=>{let Y=y3(W);if(!await I3(w,"Sync",`${Y.scope} plugins`,W))return;let Z=await w.service.sync(Y);w.stdout.write(RD(Y.scope,Z,Y.allowScripts))}))}function y3($){return{scope:$.global?"global":"project",allowScripts:$.allowScripts===!0}}async function I3($,w,G,W){if(!W.yes){if(!await $.confirm(`${w} ${G}? npm plugins run with full process permissions; validation imports plugin top-level code with full permissions. Continue?`))return!1}if(W.allowScripts){if($.stderr.write(`Warning: --allow-scripts lets this package and transitive dependencies run lifecycle scripts with your user permissions.
262
- `),!W.yes){if(!await $.confirm("Allow npm lifecycle scripts to run with full user permissions?"))return!1}}return!0}async function q5($,w){try{await w()}catch(G){$.stderr.write(`coden: ${CD(G)}
263
- `),process.exitCode=2}}function SD($,w){return[`Installed ${$.packageName}@${$.version} (${$.scope})`,`Requested: ${$.requested}`,`Tools: ${$.tools.length>0?$.tools.slice().sort().join(", "):"none"}`,`Lifecycle scripts: ${w?"enabled":"disabled"}`,"Restart CodeN to use npm plugin changes.",""].join(`
264
- `)}function RD($,w,G){let W=w.slice().sort((Y,Z)=>Y.packageName.localeCompare(Z.packageName)).map((Y)=>`${Y.packageName}@${Y.version}`);return[`Synced ${$} plugins: ${W.join(", ")||"none"}`,`Lifecycle scripts: ${G?"enabled":"disabled"}`,"Restart CodeN to use npm plugin changes.",""].join(`
265
- `)}function jD($,w){let G=[];if(!w.global)G.push(YQ("Project plugins",$.project));if(!w.project)G.push(YQ("Global plugins",$.global));return`${G.join(`
411
+ `)})),G.command("list").option("--project","show only project plugins").option("--global","show only user-global plugins").action((Z)=>O3(w,async()=>{if(Z.project&&Z.global)throw Error("plugin list accepts only one of --project or --global");let X=await w.service.list();w.stdout.write(fh(X,Z))})),G.command("sync").option("--global","sync the user-global plugin runtime").option("--allow-scripts","allow npm lifecycle scripts with full user permissions during dependency install").option("--yes","skip confirmation prompts").action((Z)=>O3(w,async()=>{let X=oY(Z);if(!await eY(w,"Sync",`${X.scope} plugins`,Z))return;let Y=await w.service.sync(X);w.stdout.write(Oh(X.scope,Y,X.allowScripts))}))}function oY($){return{scope:$.global?"global":"project",allowScripts:$.allowScripts===!0}}async function eY($,w,G,Z){if(!Z.yes){if(!await $.confirm(`${w} ${G}? npm plugins run with full process permissions; validation imports plugin top-level code with full permissions. Continue?`))return!1}if(Z.allowScripts){if($.stderr.write(`Warning: --allow-scripts lets this package and transitive dependencies run lifecycle scripts with your user permissions.
412
+ `),!Z.yes){if(!await $.confirm("Allow npm lifecycle scripts to run with full user permissions?"))return!1}}return!0}async function O3($,w){try{await w()}catch(G){$.stderr.write(`coden: ${Lh(G)}
413
+ `),process.exitCode=2}}function Fh($,w){return[`Installed ${$.packageName}@${$.version} (${$.scope})`,`Requested: ${$.requested}`,`Tools: ${$.tools.length>0?$.tools.slice().sort().join(", "):"none"}`,`Lifecycle scripts: ${w?"enabled":"disabled"}`,"Restart CodeN to use npm plugin changes.",""].join(`
414
+ `)}function Oh($,w,G){let Z=w.slice().sort((X,Y)=>X.packageName.localeCompare(Y.packageName)).map((X)=>`${X.packageName}@${X.version}`);return[`Synced ${$} plugins: ${Z.join(", ")||"none"}`,`Lifecycle scripts: ${G?"enabled":"disabled"}`,"Restart CodeN to use npm plugin changes.",""].join(`
415
+ `)}function fh($,w){let G=[];if(!w.global)G.push(vV("Project plugins",$.project));if(!w.project)G.push(vV("Global plugins",$.global));return`${G.join(`
266
416
  `)}
267
- `}function YQ($,w){let G=w.slice().sort((Y,Z)=>Y.packageName.localeCompare(Z.packageName));if(G.length===0)return`${$}: none
268
- `;let W=G.map((Y)=>{let Z=Y.shadowedByProject?" (shadowed by project)":"";return` ${Y.packageName}@${Y.version} requested ${Y.requested}; ${Y.tools.length} tool(s)${Z}`});return`${$}:
269
- ${W.join(`
417
+ `}function vV($,w){let G=w.slice().sort((X,Y)=>X.packageName.localeCompare(Y.packageName));if(G.length===0)return`${$}: none
418
+ `;let Z=G.map((X)=>{let Y=X.shadowedByProject?" (shadowed by project)":"";return` ${X.packageName}@${X.version} requested ${X.requested}; ${X.tools.length} tool(s)${Y}`});return`${$}:
419
+ ${Z.join(`
270
420
  `)}
271
- `}function CD($){let w=$ instanceof Error?$.message:String($);for(let G of Object.values(process.env)){if(!G||G.length<8)continue;w=w.split(G).join("[redacted]")}return w}function _D($={}){let w=$.confirm??vD,G=$.pluginService??gD(w),W=new GY().name("coden").description("CodeN \u2014 a minimal coding agent").version(JT).argument("[prompt]","task to execute").option("-p, --print","non-interactive print mode",!1).option("--provider <provider>","openai or anthropic",wQ).option("--model <model-id>","model identifier").option("--resume [session-id]","resume a previous session, or list sessions when no id is given").option("--auto","skip permission and project-plugin confirmations",!1).option("--verbose","show detailed runtime status",!1).option("--max-steps <number>","maximum model steps",GQ).option("--plugin <path>","additional local TypeScript plugin or directory",WQ,[]).action((Y,Z)=>of(Y,Z));return ZQ(W,{service:G,confirm:w,stdout:process.stdout,stderr:process.stderr}),W}function gD($){let w=process.cwd(),G=new lG(w,ZY(),new C5,new xG,XT()),W=new R5(ID.join(YY(),"trusted-workspaces.json"));return new JQ(G,w,W,$)}class JQ{service;workspace;trustStore;confirm;constructor($,w,G,W){this.service=$;this.workspace=w;this.trustStore=G;this.confirm=W}async install($,w){if(w.scope==="project")await this.ensureProjectTrust();return this.service.install($,w)}async remove($,w){return this.service.remove($,w)}async sync($){if($.scope==="project")await this.ensureProjectTrust();return this.service.sync($)}async list(){return this.service.list()}async ensureProjectTrust(){let $=await yD(this.workspace);if(await this.trustStore.isWorkspaceTrusted($))return;if(!await this.confirm(`Project npm plugins in ${$} run in-process with full user permissions. Trust this workspace?`))throw Error("workspace is not trusted for project npm plugins");await this.trustStore.trustWorkspace($)}}async function vD($){let w=bD({input:process.stdin,output:process.stderr});try{let G=await w.question(`${$} [y/N] `);return/^y(?:es)?$/i.test(G)}finally{w.close()}}function uD(){let $=process.argv[1];if(!$)return!1;try{return XQ(xD(import.meta.url))===XQ($)}catch{return!1}}if(uD())_D().parseAsync().catch(($)=>{process.stderr.write(`coden: ${$ instanceof Error?$.message:String($)}
272
- `),process.exitCode=$ instanceof mw?2:1});export{_D as createCliProgram};
421
+ `}function Lh($){let w=$ instanceof Error?$.message:String($);for(let G of Object.values(process.env)){if(!G||G.length<8)continue;w=w.split(G).join("[redacted]")}return w}function Sh($={}){let w=$.confirm??jh,G=$.pluginService??Ih(w),Z=new fJ().name("coden").description("CodeN \u2014 a minimal coding agent").version(vq).argument("[prompt]","task to execute").option("-p, --print","non-interactive print mode",!1).option("--provider <provider>","openai or anthropic",gV).option("--model <model-id>","model identifier").option("--resume [session-id]","resume a previous session, or list sessions when no id is given").option("--auto","skip permission and project-plugin confirmations",!1).option("--allow-outside-workspace","with --auto, allow read/write/edit paths outside the workspace",!1).option("--verbose","show detailed runtime status",!1).option("--max-steps <number>","maximum model steps",uV).option("--plugin <path>","additional local TypeScript plugin or directory",hV,[]).action((X,Y)=>yV(X,Y));return iV(Z,{service:G,confirm:w,stdout:process.stdout,stderr:process.stderr}),Z}function Ih($){let w=process.cwd(),G=new nZ(w,EJ(),new _3,new hZ,hq()),Z=new k3(Eh.join(DJ(),"trusted-workspaces.json"));return new lV(G,w,Z,$)}class lV{service;workspace;trustStore;confirm;constructor($,w,G,Z){this.service=$;this.workspace=w;this.trustStore=G;this.confirm=Z}async install($,w){if(w.scope==="project")await this.ensureProjectTrust();return this.service.install($,w)}async remove($,w){return this.service.remove($,w)}async sync($){if($.scope==="project")await this.ensureProjectTrust();return this.service.sync($)}async list(){return this.service.list()}async ensureProjectTrust(){let $=await Dh(this.workspace);if(await this.trustStore.isWorkspaceTrusted($))return;if(!await this.confirm(`Project npm plugins in ${$} run in-process with full user permissions. Trust this workspace?`))throw Error("workspace is not trusted for project npm plugins");await this.trustStore.trustWorkspace($)}}async function jh($){let w=Ah({input:process.stdin,output:process.stderr});try{let G=await w.question(`${$} [y/N] `);return/^y(?:es)?$/i.test(G)}finally{w.close()}}function Ch(){let $=process.argv[1];if(!$)return!1;try{return mV(Rh(import.meta.url))===mV($)}catch{return!1}}if(Ch())Sh().parseAsync().catch(($)=>{process.stderr.write(`coden: ${$ instanceof Error?$.message:String($)}
422
+ `),process.exitCode=$ instanceof Ow?2:1});export{Sh as createCliProgram};