@twinklerg/coden 0.1.3 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +1 -1
  2. package/dist/index.js +113 -106
  3. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -1,73 +1,73 @@
1
1
  #!/usr/bin/env node
2
2
  // @bun
3
- import{createRequire as aM}from"node:module";var cM=Object.create;var{getPrototypeOf:dM,defineProperty:k3,getOwnPropertyNames:nM}=Object;var pM=Object.prototype.hasOwnProperty;function tM($){return this[$]}var rM,sM,m1=($,w,W)=>{var Z=$!=null&&typeof $==="object";if(Z){var X=w?rM??=new WeakMap:sM??=new WeakMap,Y=X.get($);if(Y)return Y}W=$!=null?cM(dM($)):{};let G=w||!$||!$.__esModule?k3(W,"default",{value:$,enumerable:!0}):W;for(let J of nM($))if(!pM.call(G,J))k3(G,J,{get:tM.bind($,J),enumerable:!0});if(Z)X.set($,G);return G};var L=($,w)=>()=>(w||$((w={exports:{}}).exports,w),w.exports);var mw=aM(import.meta.url);var lw=L((oM)=>{class BW extends Error{constructor($,w,W){super(W);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=w,this.exitCode=$,this.nestedError=void 0}}class A3 extends BW{constructor($){super(1,"commander.invalidArgument",$);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}oM.CommanderError=BW;oM.InvalidArgumentError=A3});var $8=L((Zz)=>{var{InvalidArgumentError:wz}=lw();class S3{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,W)=>{if(!this.argChoices.includes(w))throw new wz(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(w,W);return w},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function Wz($){let w=$.name()+($.variadic===!0?"...":"");return $.required?"<"+w+">":"["+w+"]"}Zz.Argument=S3;Zz.humanReadableArgName=Wz});var PW=L((Jz)=>{var{humanReadableArgName:Gz}=$8();class R3{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),W=$._getHelpCommand();if(W&&!W._hidden)w.push(W);if(this.sortSubcommands)w.sort((Z,X)=>{return Z.name().localeCompare(X.name())});return w}compareOptions($,w){let W=(Z)=>{return Z.short?Z.short.replace(/^-/,""):Z.long.replace(/^--/,"")};return W($).localeCompare(W(w))}visibleOptions($){let w=$.options.filter((Z)=>!Z.hidden),W=$._getHelpOption();if(W&&!W.hidden){let Z=W.short&&$._findOption(W.short),X=W.long&&$._findOption(W.long);if(!Z&&!X)w.push(W);else if(W.long&&!X)w.push($.createOption(W.long,W.description));else if(W.short&&!Z)w.push($.createOption(W.short,W.description))}if(this.sortOptions)w.sort(this.compareOptions);return w}visibleGlobalOptions($){if(!this.showGlobalOptions)return[];let w=[];for(let W=$.parent;W;W=W.parent){let Z=W.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((W)=>Gz(W)).join(" ");return $._name+($._aliases[0]?"|"+$._aliases[0]:"")+($.options.length?" [options]":"")+(w?" "+w:"")}optionTerm($){return $.flags}argumentTerm($){return $.name()}longestSubcommandTermLength($,w){return w.visibleCommands($).reduce((W,Z)=>{return Math.max(W,this.displayWidth(w.styleSubcommandTerm(w.subcommandTerm(Z))))},0)}longestOptionTermLength($,w){return w.visibleOptions($).reduce((W,Z)=>{return Math.max(W,this.displayWidth(w.styleOptionTerm(w.optionTerm(Z))))},0)}longestGlobalOptionTermLength($,w){return w.visibleGlobalOptions($).reduce((W,Z)=>{return Math.max(W,this.displayWidth(w.styleOptionTerm(w.optionTerm(Z))))},0)}longestArgumentTermLength($,w){return w.visibleArguments($).reduce((W,Z)=>{return Math.max(W,this.displayWidth(w.styleArgumentTerm(w.argumentTerm(Z))))},0)}commandUsage($){let w=$._name;if($._aliases[0])w=w+"|"+$._aliases[0];let W="";for(let Z=$.parent;Z;Z=Z.parent)W=Z.name()+" "+W;return W+w+" "+$.usage()}commandDescription($){return $.description()}subcommandDescription($){return $.summary()||$.description()}optionDescription($){let w=[];if($.argChoices)w.push(`choices: ${$.argChoices.map((W)=>JSON.stringify(W)).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 W=`(${w.join(", ")})`;if($.description)return`${$.description} ${W}`;return W}return $.description}argumentDescription($){let w=[];if($.argChoices)w.push(`choices: ${$.argChoices.map((W)=>JSON.stringify(W)).join(", ")}`);if($.defaultValue!==void 0)w.push(`default: ${$.defaultValueDescription||JSON.stringify($.defaultValue)}`);if(w.length>0){let W=`(${w.join(", ")})`;if($.description)return`${$.description} ${W}`;return W}return $.description}formatItemList($,w,W){if(w.length===0)return[];return[W.styleTitle($),...w,""]}groupItems($,w,W){let Z=new Map;return $.forEach((X)=>{let Y=W(X);if(!Z.has(Y))Z.set(Y,[])}),w.forEach((X)=>{let Y=W(X);if(!Z.has(Y))Z.set(Y,[]);Z.get(Y).push(X)}),Z}formatHelp($,w){let W=w.padWidth($,w),Z=w.helpWidth??80;function X(M,z){return w.formatItem(M,W,z,w)}let Y=[`${w.styleTitle("Usage:")} ${w.styleUsage(w.commandUsage($))}`,""],G=w.commandDescription($);if(G.length>0)Y=Y.concat([w.boxWrap(w.styleCommandDescription(G),Z),""]);let J=w.visibleArguments($).map((M)=>{return X(w.styleArgumentTerm(w.argumentTerm(M)),w.styleArgumentDescription(w.argumentDescription(M)))});if(Y=Y.concat(this.formatItemList("Arguments:",J,w)),this.groupItems($.options,w.visibleOptions($),(M)=>M.helpGroupHeading??"Options:").forEach((M,z)=>{let N=M.map((B)=>{return X(w.styleOptionTerm(w.optionTerm(B)),w.styleOptionDescription(w.optionDescription(B)))});Y=Y.concat(this.formatItemList(z,N,w))}),w.showGlobalOptions){let M=w.visibleGlobalOptions($).map((z)=>{return X(w.styleOptionTerm(w.optionTerm(z)),w.styleOptionDescription(w.optionDescription(z)))});Y=Y.concat(this.formatItemList("Global Options:",M,w))}return this.groupItems($.commands,w.visibleCommands($),(M)=>M.helpGroup()||"Commands:").forEach((M,z)=>{let N=M.map((B)=>{return X(w.styleSubcommandTerm(w.subcommandTerm(B)),w.styleSubcommandDescription(w.subcommandDescription(B)))});Y=Y.concat(this.formatItemList(z,N,w))}),Y.join(`
4
- `)}displayWidth($){return C3($).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,W,Z){let Y=" ".repeat(2);if(!W)return Y+$;let G=$.padEnd(w+$.length-Z.displayWidth($)),J=2,Q=(this.helpWidth??80)-w-J-2,M;if(Q<this.minWidthToWrap||Z.preformatted(W))M=W;else M=Z.boxWrap(W,Q).replace(/\n/g,`
3
+ import{createRequire as aM}from"node:module";var cM=Object.create;var{getPrototypeOf:dM,defineProperty:AX,getOwnPropertyNames:nM}=Object;var pM=Object.prototype.hasOwnProperty;function tM($){return this[$]}var rM,sM,m1=($,w,W)=>{var Z=$!=null&&typeof $==="object";if(Z){var X=w?rM??=new WeakMap:sM??=new WeakMap,Y=X.get($);if(Y)return Y}W=$!=null?cM(dM($)):{};let G=w||!$||!$.__esModule?AX(W,"default",{value:$,enumerable:!0}):W;for(let J of nM($))if(!pM.call(G,J))AX(G,J,{get:tM.bind($,J),enumerable:!0});if(Z)X.set($,G);return G};var L=($,w)=>()=>(w||$((w={exports:{}}).exports,w),w.exports);var mw=aM(import.meta.url);var lw=L((oM)=>{class PW extends Error{constructor($,w,W){super(W);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=w,this.exitCode=$,this.nestedError=void 0}}class SX extends PW{constructor($){super(1,"commander.invalidArgument",$);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}oM.CommanderError=PW;oM.InvalidArgumentError=SX});var w8=L((Zz)=>{var{InvalidArgumentError:wz}=lw();class RX{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,W)=>{if(!this.argChoices.includes(w))throw new wz(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(w,W);return w},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function Wz($){let w=$.name()+($.variadic===!0?"...":"");return $.required?"<"+w+">":"["+w+"]"}Zz.Argument=RX;Zz.humanReadableArgName=Wz});var VW=L((Jz)=>{var{humanReadableArgName:Gz}=w8();class CX{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),W=$._getHelpCommand();if(W&&!W._hidden)w.push(W);if(this.sortSubcommands)w.sort((Z,X)=>{return Z.name().localeCompare(X.name())});return w}compareOptions($,w){let W=(Z)=>{return Z.short?Z.short.replace(/^-/,""):Z.long.replace(/^--/,"")};return W($).localeCompare(W(w))}visibleOptions($){let w=$.options.filter((Z)=>!Z.hidden),W=$._getHelpOption();if(W&&!W.hidden){let Z=W.short&&$._findOption(W.short),X=W.long&&$._findOption(W.long);if(!Z&&!X)w.push(W);else if(W.long&&!X)w.push($.createOption(W.long,W.description));else if(W.short&&!Z)w.push($.createOption(W.short,W.description))}if(this.sortOptions)w.sort(this.compareOptions);return w}visibleGlobalOptions($){if(!this.showGlobalOptions)return[];let w=[];for(let W=$.parent;W;W=W.parent){let Z=W.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((W)=>Gz(W)).join(" ");return $._name+($._aliases[0]?"|"+$._aliases[0]:"")+($.options.length?" [options]":"")+(w?" "+w:"")}optionTerm($){return $.flags}argumentTerm($){return $.name()}longestSubcommandTermLength($,w){return w.visibleCommands($).reduce((W,Z)=>{return Math.max(W,this.displayWidth(w.styleSubcommandTerm(w.subcommandTerm(Z))))},0)}longestOptionTermLength($,w){return w.visibleOptions($).reduce((W,Z)=>{return Math.max(W,this.displayWidth(w.styleOptionTerm(w.optionTerm(Z))))},0)}longestGlobalOptionTermLength($,w){return w.visibleGlobalOptions($).reduce((W,Z)=>{return Math.max(W,this.displayWidth(w.styleOptionTerm(w.optionTerm(Z))))},0)}longestArgumentTermLength($,w){return w.visibleArguments($).reduce((W,Z)=>{return Math.max(W,this.displayWidth(w.styleArgumentTerm(w.argumentTerm(Z))))},0)}commandUsage($){let w=$._name;if($._aliases[0])w=w+"|"+$._aliases[0];let W="";for(let Z=$.parent;Z;Z=Z.parent)W=Z.name()+" "+W;return W+w+" "+$.usage()}commandDescription($){return $.description()}subcommandDescription($){return $.summary()||$.description()}optionDescription($){let w=[];if($.argChoices)w.push(`choices: ${$.argChoices.map((W)=>JSON.stringify(W)).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 W=`(${w.join(", ")})`;if($.description)return`${$.description} ${W}`;return W}return $.description}argumentDescription($){let w=[];if($.argChoices)w.push(`choices: ${$.argChoices.map((W)=>JSON.stringify(W)).join(", ")}`);if($.defaultValue!==void 0)w.push(`default: ${$.defaultValueDescription||JSON.stringify($.defaultValue)}`);if(w.length>0){let W=`(${w.join(", ")})`;if($.description)return`${$.description} ${W}`;return W}return $.description}formatItemList($,w,W){if(w.length===0)return[];return[W.styleTitle($),...w,""]}groupItems($,w,W){let Z=new Map;return $.forEach((X)=>{let Y=W(X);if(!Z.has(Y))Z.set(Y,[])}),w.forEach((X)=>{let Y=W(X);if(!Z.has(Y))Z.set(Y,[]);Z.get(Y).push(X)}),Z}formatHelp($,w){let W=w.padWidth($,w),Z=w.helpWidth??80;function X(M,z){return w.formatItem(M,W,z,w)}let Y=[`${w.styleTitle("Usage:")} ${w.styleUsage(w.commandUsage($))}`,""],G=w.commandDescription($);if(G.length>0)Y=Y.concat([w.boxWrap(w.styleCommandDescription(G),Z),""]);let J=w.visibleArguments($).map((M)=>{return X(w.styleArgumentTerm(w.argumentTerm(M)),w.styleArgumentDescription(w.argumentDescription(M)))});if(Y=Y.concat(this.formatItemList("Arguments:",J,w)),this.groupItems($.options,w.visibleOptions($),(M)=>M.helpGroupHeading??"Options:").forEach((M,z)=>{let N=M.map((B)=>{return X(w.styleOptionTerm(w.optionTerm(B)),w.styleOptionDescription(w.optionDescription(B)))});Y=Y.concat(this.formatItemList(z,N,w))}),w.showGlobalOptions){let M=w.visibleGlobalOptions($).map((z)=>{return X(w.styleOptionTerm(w.optionTerm(z)),w.styleOptionDescription(w.optionDescription(z)))});Y=Y.concat(this.formatItemList("Global Options:",M,w))}return this.groupItems($.commands,w.visibleCommands($),(M)=>M.helpGroup()||"Commands:").forEach((M,z)=>{let N=M.map((B)=>{return X(w.styleSubcommandTerm(w.subcommandTerm(B)),w.styleSubcommandDescription(w.subcommandDescription(B)))});Y=Y.concat(this.formatItemList(z,N,w))}),Y.join(`
4
+ `)}displayWidth($){return jX($).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,W,Z){let Y=" ".repeat(2);if(!W)return Y+$;let G=$.padEnd(w+$.length-Z.displayWidth($)),J=2,Q=(this.helpWidth??80)-w-J-2,M;if(Q<this.minWidthToWrap||Z.preformatted(W))M=W;else M=Z.boxWrap(W,Q).replace(/\n/g,`
5
5
  `+" ".repeat(w+J));return Y+G+" ".repeat(J)+M.replace(/\n/g,`
6
6
  ${Y}`)}boxWrap($,w){if(w<this.minWidthToWrap)return $;let W=$.split(/\r\n|\n/),Z=/[\s]*[^\s]+/g,X=[];return W.forEach((Y)=>{let G=Y.match(Z);if(G===null){X.push("");return}let J=[G.shift()],T=this.displayWidth(J[0]);G.forEach((Q)=>{let M=this.displayWidth(Q);if(T+M<=w){J.push(Q),T+=M;return}X.push(J.join(""));let z=Q.trimStart();J=[z],T=this.displayWidth(z)}),X.push(J.join(""))}),X.join(`
7
- `)}}function C3($){let w=/\x1b\[\d*(;\d*)*m/g;return $.replace(w,"")}Jz.Help=R3;Jz.stripColor=C3});var VW=L((Nz)=>{var{InvalidArgumentError:Mz}=lw();class y3{constructor($,w){this.flags=$,this.description=w||"",this.required=$.includes("<"),this.optional=$.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test($),this.mandatory=!1;let W=zz($);if(this.short=W.shortFlag,this.long=W.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,W)=>{if(!this.argChoices.includes(w))throw new Mz(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(w,W);return w},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){if(this.negate)return j3(this.name().replace(/^no-/,""));return j3(this.name())}helpGroup($){return this.helpGroupHeading=$,this}is($){return this.short===$||this.long===$}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class I3{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,W)=>{if(this.positiveOptions.has(W))this.dualOptions.add(W)})}valueFromOption($,w){let W=w.attributeName();if(!this.dualOptions.has(W))return!0;let Z=this.negativeOptions.get(W).presetArg,X=Z!==void 0?Z:!1;return w.negate===(X===$)}}function j3($){return $.split("-").reduce((w,W)=>{return w+W[0].toUpperCase()+W.slice(1)})}function zz($){let w,W,Z=/^-[^-]$/,X=/^--[^-]/,Y=$.split(/[ |,]+/).concat("guard");if(Z.test(Y[0]))w=Y.shift();if(X.test(Y[0]))W=Y.shift();if(!w&&Z.test(Y[0]))w=Y.shift();if(!w&&X.test(Y[0]))w=W,W=Y.shift();if(Y[0].startsWith("-")){let G=Y[0],J=`option creation failed due to '${G}' in option flags '${$}'`;if(/^-[^-][^-]/.test(G))throw Error(`${J}
7
+ `)}}function jX($){let w=/\x1b\[\d*(;\d*)*m/g;return $.replace(w,"")}Jz.Help=CX;Jz.stripColor=jX});var fW=L((Nz)=>{var{InvalidArgumentError:Mz}=lw();class IX{constructor($,w){this.flags=$,this.description=w||"",this.required=$.includes("<"),this.optional=$.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test($),this.mandatory=!1;let W=zz($);if(this.short=W.shortFlag,this.long=W.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,W)=>{if(!this.argChoices.includes(w))throw new Mz(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(w,W);return w},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){if(this.negate)return yX(this.name().replace(/^no-/,""));return yX(this.name())}helpGroup($){return this.helpGroupHeading=$,this}is($){return this.short===$||this.long===$}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class bX{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,W)=>{if(this.positiveOptions.has(W))this.dualOptions.add(W)})}valueFromOption($,w){let W=w.attributeName();if(!this.dualOptions.has(W))return!0;let Z=this.negativeOptions.get(W).presetArg,X=Z!==void 0?Z:!1;return w.negate===(X===$)}}function yX($){return $.split("-").reduce((w,W)=>{return w+W[0].toUpperCase()+W.slice(1)})}function zz($){let w,W,Z=/^-[^-]$/,X=/^--[^-]/,Y=$.split(/[ |,]+/).concat("guard");if(Z.test(Y[0]))w=Y.shift();if(X.test(Y[0]))W=Y.shift();if(!w&&Z.test(Y[0]))w=Y.shift();if(!w&&X.test(Y[0]))w=W,W=Y.shift();if(Y[0].startsWith("-")){let G=Y[0],J=`option creation failed due to '${G}' in option flags '${$}'`;if(/^-[^-][^-]/.test(G))throw Error(`${J}
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
10
  - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(Z.test(G))throw Error(`${J}
11
11
  - too many short flags`);if(X.test(G))throw Error(`${J}
12
12
  - too many long flags`);throw Error(`${J}
13
- - unrecognised flag format`)}if(w===void 0&&W===void 0)throw Error(`option creation failed due to no flags found in '${$}'.`);return{shortFlag:w,longFlag:W}}Nz.Option=y3;Nz.DualOptions=I3});var b3=L((fz)=>{function Pz($,w){if(Math.abs($.length-w.length)>3)return Math.max($.length,w.length);let W=[];for(let Z=0;Z<=$.length;Z++)W[Z]=[Z];for(let Z=0;Z<=w.length;Z++)W[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(W[X][Z]=Math.min(W[X-1][Z]+1,W[X][Z-1]+1,W[X-1][Z-1]+Y),X>1&&Z>1&&$[X-1]===w[Z-2]&&$[X-2]===w[Z-1])W[X][Z]=Math.min(W[X][Z],W[X-2][Z-2]+1)}return W[$.length][w.length]}function Vz($,w){if(!w||w.length===0)return"";w=Array.from(new Set(w));let W=$.startsWith("--");if(W)$=$.slice(2),w=w.map((G)=>G.slice(2));let Z=[],X=3,Y=0.4;if(w.forEach((G)=>{if(G.length<=1)return;let J=Pz($,G),T=Math.max($.length,G.length);if((T-J)/T>Y){if(J<X)X=J,Z=[G];else if(J===X)Z.push(G)}}),Z.sort((G,J)=>G.localeCompare(J)),W)Z=Z.map((G)=>`--${G}`);if(Z.length>1)return`
13
+ - unrecognised flag format`)}if(w===void 0&&W===void 0)throw Error(`option creation failed due to no flags found in '${$}'.`);return{shortFlag:w,longFlag:W}}Nz.Option=IX;Nz.DualOptions=bX});var xX=L((fz)=>{function Pz($,w){if(Math.abs($.length-w.length)>3)return Math.max($.length,w.length);let W=[];for(let Z=0;Z<=$.length;Z++)W[Z]=[Z];for(let Z=0;Z<=w.length;Z++)W[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(W[X][Z]=Math.min(W[X-1][Z]+1,W[X][Z-1]+1,W[X-1][Z-1]+Y),X>1&&Z>1&&$[X-1]===w[Z-2]&&$[X-2]===w[Z-1])W[X][Z]=Math.min(W[X][Z],W[X-2][Z-2]+1)}return W[$.length][w.length]}function Vz($,w){if(!w||w.length===0)return"";w=Array.from(new Set(w));let W=$.startsWith("--");if(W)$=$.slice(2),w=w.map((G)=>G.slice(2));let Z=[],X=3,Y=0.4;if(w.forEach((G)=>{if(G.length<=1)return;let J=Pz($,G),T=Math.max($.length,G.length);if((T-J)/T>Y){if(J<X)X=J,Z=[G];else if(J===X)Z.push(G)}}),Z.sort((G,J)=>G.localeCompare(J)),W)Z=Z.map((G)=>`--${G}`);if(Z.length>1)return`
14
14
  (Did you mean one of ${Z.join(", ")}?)`;if(Z.length===1)return`
15
- (Did you mean ${Z[0]}?)`;return""}fz.suggestSimilar=Vz});var v3=L((Dz)=>{var Uz=mw("node:events").EventEmitter,fW=mw("node:child_process"),N$=mw("node:path"),w8=mw("node:fs"),p=mw("node:process"),{Argument:Hz,humanReadableArgName:Fz}=$8(),{CommanderError:qW}=lw(),{Help:Oz,stripColor:Ez}=PW(),{Option:x3,DualOptions:Lz}=VW(),{suggestSimilar:_3}=b3();class HW extends Uz{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,W)=>W(w),getOutHelpWidth:()=>p.stdout.isTTY?p.stdout.columns:void 0,getErrHelpWidth:()=>p.stderr.isTTY?p.stderr.columns:void 0,getOutHasColors:()=>UW()??(p.stdout.isTTY&&p.stdout.hasColors?.()),getErrHasColors:()=>UW()??(p.stderr.isTTY&&p.stderr.hasColors?.()),stripColor:(w)=>Ez(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,W){let Z=w,X=W;if(typeof Z==="object"&&Z!==null)X=Z,Z=null;X=X||{};let[,Y,G]=$.match(/([^ ]+) *(.*)/),J=this.createCommand(Y);if(Z)J.description(Z),J._executableHandler=!0;if(X.isDefault)this._defaultCommandName=J._name;if(J._hidden=!!(X.noHelp||X.hidden),J._executableFile=X.executableFile||null,G)J.arguments(G);if(this._registerCommand(J),J.parent=this,J.copyInheritedSettings(this),Z)return this;return J}createCommand($){return new HW($)}createHelp(){return Object.assign(new Oz,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
15
+ (Did you mean ${Z[0]}?)`;return""}fz.suggestSimilar=Vz});var uX=L((Dz)=>{var Uz=mw("node:events").EventEmitter,qW=mw("node:child_process"),N$=mw("node:path"),W8=mw("node:fs"),p=mw("node:process"),{Argument:Hz,humanReadableArgName:Fz}=w8(),{CommanderError:UW}=lw(),{Help:Oz,stripColor:Ez}=VW(),{Option:_X,DualOptions:Lz}=fW(),{suggestSimilar:gX}=xX();class FW extends Uz{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,W)=>W(w),getOutHelpWidth:()=>p.stdout.isTTY?p.stdout.columns:void 0,getErrHelpWidth:()=>p.stderr.isTTY?p.stderr.columns:void 0,getOutHasColors:()=>HW()??(p.stdout.isTTY&&p.stdout.hasColors?.()),getErrHasColors:()=>HW()??(p.stderr.isTTY&&p.stderr.hasColors?.()),stripColor:(w)=>Ez(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,W){let Z=w,X=W;if(typeof Z==="object"&&Z!==null)X=Z,Z=null;X=X||{};let[,Y,G]=$.match(/([^ ]+) *(.*)/),J=this.createCommand(Y);if(Z)J.description(Z),J._executableHandler=!0;if(X.isDefault)this._defaultCommandName=J._name;if(J._hidden=!!(X.noHelp||X.hidden),J._executableFile=X.executableFile||null,G)J.arguments(G);if(this._registerCommand(J),J.parent=this,J.copyInheritedSettings(this),Z)return this;return J}createCommand($){return new FW($)}createHelp(){return Object.assign(new Oz,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
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 Hz($,w)}argument($,w,W,Z){let X=this.createArgument($,w);if(typeof W==="function")X.default(Z).argParser(W);else X.default(W);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 W=$??"help [command]",[,Z,X]=W.match(/([^ ]+) *(.*)/),Y=w??"display help for command",G=this.createCommand(Z);if(G.helpOption(!1),X)G.arguments(X);if(Y)G.description(Y);if(this._addImplicitHelpCommand=!0,this._helpCommand=G,$||w)this._initCommandGroup(G);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 W=["preSubcommand","preAction","postAction"];if(!W.includes($))throw Error(`Unexpected value for event passed to hook : '${$}'.
17
- Expecting one of '${W.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,W){if(this._exitCallback)this._exitCallback(new qW($,w,W));p.exit($)}action($){let w=(W)=>{let Z=this.registeredArguments.length,X=W.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 x3($,w)}_callParseArg($,w,W,Z){try{return $.parseArg(w,W)}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 W=$.long&&this._findOption($.long)?$.long:$.short;throw Error(`Cannot add option '${$.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${W}'
18
- - already used by option '${w.flags}'`)}this._initOptionGroup($),this.options.push($)}_registerCommand($){let w=(Z)=>{return[Z.name()].concat(Z.aliases())},W=w($).find((Z)=>this._findCommand(Z));if(W){let Z=w(this._findCommand(W)).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(),W=$.attributeName();if($.negate){let X=$.long.replace(/^--no-/,"--");if(!this._findOption(X))this.setOptionValueWithSource(W,$.defaultValue===void 0?!0:$.defaultValue,"default")}else if($.defaultValue!==void 0)this.setOptionValueWithSource(W,$.defaultValue,"default");let Z=(X,Y,G)=>{if(X==null&&$.presetArg!==void 0)X=$.presetArg;let J=this.getOptionValue(W);if(X!==null&&$.parseArg)X=this._callParseArg($,X,J,Y);else if(X!==null&&$.variadic)X=$._collectValue(X,J);if(X==null)if($.negate)X=!1;else if($.isBoolean()||$.optional)X=!0;else X="";this.setOptionValueWithSource(W,X,G)};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,W,Z,X){if(typeof w==="object"&&w instanceof x3)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let Y=this.createOption(w,W);if(Y.makeOptionMandatory(!!$.mandatory),typeof Z==="function")Y.default(X).argParser(Z);else if(Z instanceof RegExp){let G=Z;Z=(J,T)=>{let Q=G.exec(J);return Q?Q[0]:T},Y.default(X).argParser(Z)}else Y.default(Z);return this.addOption(Y)}option($,w,W,Z){return this._optionEx({},$,w,W,Z)}requiredOption($,w,W,Z){return this._optionEx({mandatory:!0},$,w,W,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,W){if(this._storeOptionsAsProperties)this[$]=w;else this._optionValues[$]=w;return this._optionValueSources[$]=W,this}getOptionValueSource($){return this._optionValueSources[$]}getOptionValueSourceWithGlobals($){let w;return this._getCommandAndAncestors().forEach((W)=>{if(W.getOptionValueSource($)!==void 0)w=W.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 Z=p.execArgv??[];if(Z.includes("-e")||Z.includes("--eval")||Z.includes("-p")||Z.includes("--print"))w.from="eval"}if($===void 0)$=p.argv;this.rawArgs=$.slice();let W;switch(w.from){case void 0:case"node":this._scriptPath=$[1],W=$.slice(2);break;case"electron":if(p.defaultApp)this._scriptPath=$[1],W=$.slice(2);else W=$.slice(1);break;case"user":W=$.slice(0);break;case"eval":W=$.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",W}parse($,w){this._prepareForParse();let W=this._prepareUserArgs($,w);return this._parseCommand([],W),this}async parseAsync($,w){this._prepareForParse();let W=this._prepareUserArgs($,w);return await this._parseCommand([],W),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,W){if(w8.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
17
+ Expecting one of '${W.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,W){if(this._exitCallback)this._exitCallback(new UW($,w,W));p.exit($)}action($){let w=(W)=>{let Z=this.registeredArguments.length,X=W.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 _X($,w)}_callParseArg($,w,W,Z){try{return $.parseArg(w,W)}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 W=$.long&&this._findOption($.long)?$.long:$.short;throw Error(`Cannot add option '${$.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${W}'
18
+ - already used by option '${w.flags}'`)}this._initOptionGroup($),this.options.push($)}_registerCommand($){let w=(Z)=>{return[Z.name()].concat(Z.aliases())},W=w($).find((Z)=>this._findCommand(Z));if(W){let Z=w(this._findCommand(W)).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(),W=$.attributeName();if($.negate){let X=$.long.replace(/^--no-/,"--");if(!this._findOption(X))this.setOptionValueWithSource(W,$.defaultValue===void 0?!0:$.defaultValue,"default")}else if($.defaultValue!==void 0)this.setOptionValueWithSource(W,$.defaultValue,"default");let Z=(X,Y,G)=>{if(X==null&&$.presetArg!==void 0)X=$.presetArg;let J=this.getOptionValue(W);if(X!==null&&$.parseArg)X=this._callParseArg($,X,J,Y);else if(X!==null&&$.variadic)X=$._collectValue(X,J);if(X==null)if($.negate)X=!1;else if($.isBoolean()||$.optional)X=!0;else X="";this.setOptionValueWithSource(W,X,G)};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,W,Z,X){if(typeof w==="object"&&w instanceof _X)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let Y=this.createOption(w,W);if(Y.makeOptionMandatory(!!$.mandatory),typeof Z==="function")Y.default(X).argParser(Z);else if(Z instanceof RegExp){let G=Z;Z=(J,T)=>{let Q=G.exec(J);return Q?Q[0]:T},Y.default(X).argParser(Z)}else Y.default(Z);return this.addOption(Y)}option($,w,W,Z){return this._optionEx({},$,w,W,Z)}requiredOption($,w,W,Z){return this._optionEx({mandatory:!0},$,w,W,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,W){if(this._storeOptionsAsProperties)this[$]=w;else this._optionValues[$]=w;return this._optionValueSources[$]=W,this}getOptionValueSource($){return this._optionValueSources[$]}getOptionValueSourceWithGlobals($){let w;return this._getCommandAndAncestors().forEach((W)=>{if(W.getOptionValueSource($)!==void 0)w=W.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 Z=p.execArgv??[];if(Z.includes("-e")||Z.includes("--eval")||Z.includes("-p")||Z.includes("--print"))w.from="eval"}if($===void 0)$=p.argv;this.rawArgs=$.slice();let W;switch(w.from){case void 0:case"node":this._scriptPath=$[1],W=$.slice(2);break;case"electron":if(p.defaultApp)this._scriptPath=$[1],W=$.slice(2);else W=$.slice(1);break;case"user":W=$.slice(0);break;case"eval":W=$.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",W}parse($,w){this._prepareForParse();let W=this._prepareUserArgs($,w);return this._parseCommand([],W),this}async parseAsync($,w){this._prepareForParse();let W=this._prepareUserArgs($,w);return await this._parseCommand([],W),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,W){if(W8.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 '${W}' 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
- - ${Z}`;throw Error(X)}_executeSubCommand($,w){w=w.slice();let W=!1,Z=[".js",".ts",".tsx",".mjs",".cjs"];function X(Q,M){let z=N$.resolve(Q,M);if(w8.existsSync(z))return z;if(Z.includes(N$.extname(M)))return;let N=Z.find((B)=>w8.existsSync(`${z}${B}`));if(N)return`${z}${N}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let Y=$._executableFile||`${this._name}-${$._name}`,G=this._executableDir||"";if(this._scriptPath){let Q;try{Q=w8.realpathSync(this._scriptPath)}catch{Q=this._scriptPath}G=N$.resolve(N$.dirname(Q),G)}if(G){let Q=X(G,Y);if(!Q&&!$._executableFile&&this._scriptPath){let M=N$.basename(this._scriptPath,N$.extname(this._scriptPath));if(M!==this._name)Q=X(G,`${M}-${$._name}`)}Y=Q||Y}W=Z.includes(N$.extname(Y));let J;if(p.platform!=="win32")if(W)w.unshift(Y),w=g3(p.execArgv).concat(w),J=fW.spawn(p.argv[0],w,{stdio:"inherit"});else J=fW.spawn(Y,w,{stdio:"inherit"});else this._checkForMissingExecutable(Y,G,$._name),w.unshift(Y),w=g3(p.execArgv).concat(w),J=fW.spawn(p.execPath,w,{stdio:"inherit"});if(!J.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((M)=>{p.on(M,()=>{if(J.killed===!1&&J.exitCode===null)J.kill(M)})});let T=this._exitCallback;J.on("close",(Q)=>{if(Q=Q??1,!T)p.exit(Q);else T(new qW(Q,"commander.executeSubCommandAsync","(close)"))}),J.on("error",(Q)=>{if(Q.code==="ENOENT")this._checkForMissingExecutable(Y,G,$._name);else if(Q.code==="EACCES")throw Error(`'${Y}' not executable`);if(!T)p.exit(1);else{let M=new qW(1,"commander.executeSubCommandAsync","(error)");M.nestedError=Q,T(M)}}),this.runningCommand=J}_dispatchSubcommand($,w,W){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(W));else return Z._parseCommand(w,W)}),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 $=(W,Z,X)=>{let Y=Z;if(Z!==null&&W.parseArg){let G=`error: command-argument value '${Z}' is invalid for argument '${W.name()}'.`;Y=this._callParseArg(W,Z,X,G)}return Y};this._checkNumberOfArguments();let w=[];this.registeredArguments.forEach((W,Z)=>{let X=W.defaultValue;if(W.variadic){if(Z<this.args.length){if(X=this.args.slice(Z),W.parseArg)X=X.reduce((Y,G)=>{return $(W,G,Y)},W.defaultValue)}else if(X===void 0)X=[]}else if(Z<this.args.length){if(X=this.args[Z],W.parseArg)X=$(W,X,W.defaultValue)}w[Z]=X}),this.processedArgs=w}_chainOrCall($,w){if($?.then&&typeof $.then==="function")return $.then(()=>w());return w()}_chainOrCallHooks($,w){let W=$,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)=>{W=this._chainOrCall(W,()=>{return X.callback(X.hookedCommand,this)})}),W}_chainOrCallSubCommandHook($,w,W){let Z=$;if(this._lifeCycleHooks[W]!==void 0)this._lifeCycleHooks[W].forEach((X)=>{Z=this._chainOrCall(Z,()=>{return X(this,w)})});return Z}_parseCommand($,w){let W=this.parseOptions(w);if(this._parseOptionsEnv(),this._parseOptionsImplied(),$=$.concat(W.operands),w=W.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(W.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let Z=()=>{if(W.unknown.length>0)this.unknownOption(W.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((W)=>{let Z=W.attributeName();if(this.getOptionValue(Z)===void 0)return!1;return this.getOptionValueSource(Z)!=="default"});$.filter((W)=>W.conflictsWith.length>0).forEach((W)=>{let Z=$.find((X)=>W.conflictsWith.includes(X.attributeName()));if(Z)this._conflictingOption(W,Z)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(($)=>{$._checkForConflictingLocalOptions()})}parseOptions($){let w=[],W=[],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((M)=>M.options.map((z)=>z.short).some((z)=>/^-\d$/.test(z)))},G=null,J=null,T=0;while(T<$.length||J){let Q=J??$[T++];if(J=null,Q==="--"){if(Z===W)Z.push(Q);Z.push(...$.slice(T));break}if(G&&(!X(Q)||Y(Q))){this.emit(`option:${G.name()}`,Q);continue}if(G=null,X(Q)){let M=this._findOption(Q);if(M){if(M.required){let z=$[T++];if(z===void 0)this.optionMissingArgument(M);this.emit(`option:${M.name()}`,z)}else if(M.optional){let z=null;if(T<$.length&&(!X($[T])||Y($[T])))z=$[T++];this.emit(`option:${M.name()}`,z)}else this.emit(`option:${M.name()}`);G=M.variadic?M:null;continue}}if(Q.length>2&&Q[0]==="-"&&Q[1]!=="-"){let M=this._findOption(`-${Q[1]}`);if(M){if(M.required||M.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${M.name()}`,Q.slice(2));else this.emit(`option:${M.name()}`),J=`-${Q.slice(2)}`;continue}}if(/^--[^=]+=/.test(Q)){let M=Q.indexOf("="),z=this._findOption(Q.slice(0,M));if(z&&(z.required||z.optional)){this.emit(`option:${z.name()}`,Q.slice(M+1));continue}}if(Z===w&&X(Q)&&!(this.commands.length===0&&Y(Q)))Z=W;if((this._enablePositionalOptions||this._passThroughOptions)&&w.length===0&&W.length===0){if(this._findCommand(Q)){w.push(Q),W.push(...$.slice(T));break}else if(this._getHelpCommand()&&Q===this._getHelpCommand().name()){w.push(Q,...$.slice(T));break}else if(this._defaultCommandName){W.push(Q,...$.slice(T));break}}if(this._passThroughOptions){Z.push(Q,...$.slice(T));break}Z.push(Q)}return{operands:w,unknown:W}}opts(){if(this._storeOptionsAsProperties){let $={},w=this.options.length;for(let W=0;W<w;W++){let Z=this.options[W].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(`${$}
22
+ - ${Z}`;throw Error(X)}_executeSubCommand($,w){w=w.slice();let W=!1,Z=[".js",".ts",".tsx",".mjs",".cjs"];function X(Q,M){let z=N$.resolve(Q,M);if(W8.existsSync(z))return z;if(Z.includes(N$.extname(M)))return;let N=Z.find((B)=>W8.existsSync(`${z}${B}`));if(N)return`${z}${N}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let Y=$._executableFile||`${this._name}-${$._name}`,G=this._executableDir||"";if(this._scriptPath){let Q;try{Q=W8.realpathSync(this._scriptPath)}catch{Q=this._scriptPath}G=N$.resolve(N$.dirname(Q),G)}if(G){let Q=X(G,Y);if(!Q&&!$._executableFile&&this._scriptPath){let M=N$.basename(this._scriptPath,N$.extname(this._scriptPath));if(M!==this._name)Q=X(G,`${M}-${$._name}`)}Y=Q||Y}W=Z.includes(N$.extname(Y));let J;if(p.platform!=="win32")if(W)w.unshift(Y),w=vX(p.execArgv).concat(w),J=qW.spawn(p.argv[0],w,{stdio:"inherit"});else J=qW.spawn(Y,w,{stdio:"inherit"});else this._checkForMissingExecutable(Y,G,$._name),w.unshift(Y),w=vX(p.execArgv).concat(w),J=qW.spawn(p.execPath,w,{stdio:"inherit"});if(!J.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((M)=>{p.on(M,()=>{if(J.killed===!1&&J.exitCode===null)J.kill(M)})});let T=this._exitCallback;J.on("close",(Q)=>{if(Q=Q??1,!T)p.exit(Q);else T(new UW(Q,"commander.executeSubCommandAsync","(close)"))}),J.on("error",(Q)=>{if(Q.code==="ENOENT")this._checkForMissingExecutable(Y,G,$._name);else if(Q.code==="EACCES")throw Error(`'${Y}' not executable`);if(!T)p.exit(1);else{let M=new UW(1,"commander.executeSubCommandAsync","(error)");M.nestedError=Q,T(M)}}),this.runningCommand=J}_dispatchSubcommand($,w,W){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(W));else return Z._parseCommand(w,W)}),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 $=(W,Z,X)=>{let Y=Z;if(Z!==null&&W.parseArg){let G=`error: command-argument value '${Z}' is invalid for argument '${W.name()}'.`;Y=this._callParseArg(W,Z,X,G)}return Y};this._checkNumberOfArguments();let w=[];this.registeredArguments.forEach((W,Z)=>{let X=W.defaultValue;if(W.variadic){if(Z<this.args.length){if(X=this.args.slice(Z),W.parseArg)X=X.reduce((Y,G)=>{return $(W,G,Y)},W.defaultValue)}else if(X===void 0)X=[]}else if(Z<this.args.length){if(X=this.args[Z],W.parseArg)X=$(W,X,W.defaultValue)}w[Z]=X}),this.processedArgs=w}_chainOrCall($,w){if($?.then&&typeof $.then==="function")return $.then(()=>w());return w()}_chainOrCallHooks($,w){let W=$,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)=>{W=this._chainOrCall(W,()=>{return X.callback(X.hookedCommand,this)})}),W}_chainOrCallSubCommandHook($,w,W){let Z=$;if(this._lifeCycleHooks[W]!==void 0)this._lifeCycleHooks[W].forEach((X)=>{Z=this._chainOrCall(Z,()=>{return X(this,w)})});return Z}_parseCommand($,w){let W=this.parseOptions(w);if(this._parseOptionsEnv(),this._parseOptionsImplied(),$=$.concat(W.operands),w=W.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(W.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let Z=()=>{if(W.unknown.length>0)this.unknownOption(W.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((W)=>{let Z=W.attributeName();if(this.getOptionValue(Z)===void 0)return!1;return this.getOptionValueSource(Z)!=="default"});$.filter((W)=>W.conflictsWith.length>0).forEach((W)=>{let Z=$.find((X)=>W.conflictsWith.includes(X.attributeName()));if(Z)this._conflictingOption(W,Z)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(($)=>{$._checkForConflictingLocalOptions()})}parseOptions($){let w=[],W=[],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((M)=>M.options.map((z)=>z.short).some((z)=>/^-\d$/.test(z)))},G=null,J=null,T=0;while(T<$.length||J){let Q=J??$[T++];if(J=null,Q==="--"){if(Z===W)Z.push(Q);Z.push(...$.slice(T));break}if(G&&(!X(Q)||Y(Q))){this.emit(`option:${G.name()}`,Q);continue}if(G=null,X(Q)){let M=this._findOption(Q);if(M){if(M.required){let z=$[T++];if(z===void 0)this.optionMissingArgument(M);this.emit(`option:${M.name()}`,z)}else if(M.optional){let z=null;if(T<$.length&&(!X($[T])||Y($[T])))z=$[T++];this.emit(`option:${M.name()}`,z)}else this.emit(`option:${M.name()}`);G=M.variadic?M:null;continue}}if(Q.length>2&&Q[0]==="-"&&Q[1]!=="-"){let M=this._findOption(`-${Q[1]}`);if(M){if(M.required||M.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${M.name()}`,Q.slice(2));else this.emit(`option:${M.name()}`),J=`-${Q.slice(2)}`;continue}}if(/^--[^=]+=/.test(Q)){let M=Q.indexOf("="),z=this._findOption(Q.slice(0,M));if(z&&(z.required||z.optional)){this.emit(`option:${z.name()}`,Q.slice(M+1));continue}}if(Z===w&&X(Q)&&!(this.commands.length===0&&Y(Q)))Z=W;if((this._enablePositionalOptions||this._passThroughOptions)&&w.length===0&&W.length===0){if(this._findCommand(Q)){w.push(Q),W.push(...$.slice(T));break}else if(this._getHelpCommand()&&Q===this._getHelpCommand().name()){w.push(Q,...$.slice(T));break}else if(this._defaultCommandName){W.push(Q,...$.slice(T));break}}if(this._passThroughOptions){Z.push(Q,...$.slice(T));break}Z.push(Q)}return{operands:w,unknown:W}}opts(){if(this._storeOptionsAsProperties){let $={},w=this.options.length;for(let W=0;W<w;W++){let Z=this.options[W].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 W=w||{},Z=W.exitCode||1,X=W.code||"commander.error";this._exit(Z,X,$)}_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 Lz(this.options),w=(W)=>{return this.getOptionValue(W)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(W))};this.options.filter((W)=>W.implied!==void 0&&w(W.attributeName())&&$.valueFromOption(this.getOptionValue(W.attributeName()),W)).forEach((W)=>{Object.keys(W.implied).filter((Z)=>!w(Z)).forEach((Z)=>{this.setOptionValueWithSource(Z,W.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 W=(Y)=>{let G=Y.attributeName(),J=this.getOptionValue(G),T=this.options.find((M)=>M.negate&&G===M.attributeName()),Q=this.options.find((M)=>!M.negate&&G===M.attributeName());if(T&&(T.presetArg===void 0&&J===!1||T.presetArg!==void 0&&J===T.presetArg))return T;return Q||Y},Z=(Y)=>{let G=W(Y),J=G.attributeName();if(this.getOptionValueSource(J)==="env")return`environment variable '${G.envVar}'`;return`option '${G.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((G)=>G.long).map((G)=>G.long);Z=Z.concat(Y),X=X.parent}while(X&&!X._enablePositionalOptions);w=_3($,Z)}let W=`error: unknown option '${$}'${w}`;this.error(W,{code:"commander.unknownOption"})}_excessArguments($){if(this._allowExcessArguments)return;let w=this.registeredArguments.length,W=w===1?"":"s",X=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${w} argument${W} 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=_3($,Z)}let W=`error: unknown command '${$}'${w}`;this.error(W,{code:"commander.unknownCommand"})}version($,w,W){if($===void 0)return this._version;this._version=$,w=w||"-V, --version",W=W||"output the version number";let Z=this.createOption(w,W);return this._versionOptionName=Z.attributeName(),this._registerOption(Z),this.on("option:"+Z.name(),()=>{this._outputConfiguration.writeOut(`${$}
25
+ `),this.outputHelp({error:!0});let W=w||{},Z=W.exitCode||1,X=W.code||"commander.error";this._exit(Z,X,$)}_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 Lz(this.options),w=(W)=>{return this.getOptionValue(W)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(W))};this.options.filter((W)=>W.implied!==void 0&&w(W.attributeName())&&$.valueFromOption(this.getOptionValue(W.attributeName()),W)).forEach((W)=>{Object.keys(W.implied).filter((Z)=>!w(Z)).forEach((Z)=>{this.setOptionValueWithSource(Z,W.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 W=(Y)=>{let G=Y.attributeName(),J=this.getOptionValue(G),T=this.options.find((M)=>M.negate&&G===M.attributeName()),Q=this.options.find((M)=>!M.negate&&G===M.attributeName());if(T&&(T.presetArg===void 0&&J===!1||T.presetArg!==void 0&&J===T.presetArg))return T;return Q||Y},Z=(Y)=>{let G=W(Y),J=G.attributeName();if(this.getOptionValueSource(J)==="env")return`environment variable '${G.envVar}'`;return`option '${G.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((G)=>G.long).map((G)=>G.long);Z=Z.concat(Y),X=X.parent}while(X&&!X._enablePositionalOptions);w=gX($,Z)}let W=`error: unknown option '${$}'${w}`;this.error(W,{code:"commander.unknownOption"})}_excessArguments($){if(this._allowExcessArguments)return;let w=this.registeredArguments.length,W=w===1?"":"s",X=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${w} argument${W} 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=gX($,Z)}let W=`error: unknown command '${$}'${w}`;this.error(W,{code:"commander.unknownCommand"})}version($,w,W){if($===void 0)return this._version;this._version=$,w=w||"-V, --version",W=W||"output the version number";let Z=this.createOption(w,W);return this._versionOptionName=Z.attributeName(),this._registerOption(Z),this.on("option:"+Z.name(),()=>{this._outputConfiguration.writeOut(`${$}
26
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 W=this.parent?._findCommand($);if(W){let Z=[W.name()].concat(W.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((W)=>{return Fz(W)});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=N$.basename($,N$.extname($)),this}executableDir($){if($===void 0)return this._executableDir;return this._executableDir=$,this}helpInformation($){let w=this.createHelp(),W=this._getOutputContext($);w.prepareContext({error:W.error,helpWidth:W.helpWidth,outputHasColors:W.hasColors});let Z=w.formatHelp(this,w);if(W.hasColors)return Z;return this._outputConfiguration.stripColor(Z)}_getOutputContext($){$=$||{};let w=!!$.error,W,Z,X;if(w)W=(G)=>this._outputConfiguration.writeErr(G),Z=this._outputConfiguration.getErrHasColors(),X=this._outputConfiguration.getErrHelpWidth();else W=(G)=>this._outputConfiguration.writeOut(G),Z=this._outputConfiguration.getOutHasColors(),X=this._outputConfiguration.getOutHelpWidth();return{error:w,write:(G)=>{if(!Z)G=this._outputConfiguration.stripColor(G);return W(G)},hasColors:Z,helpWidth:X}}outputHelp($){let w;if(typeof $==="function")w=$,$=void 0;let W=this._getOutputContext($),Z={error:W.error,write:W.write,command:this};this._getCommandAndAncestors().reverse().forEach((Y)=>Y.emit("beforeAllHelp",Z)),this.emit("beforeHelp",Z);let X=this.helpInformation({error:W.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(W.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(p.exitCode??0);if(w===0&&$&&typeof $!=="function"&&$.error)w=1;this._exit(w,"commander.help","(outputHelp)")}addHelpText($,w){let W=["beforeAll","before","after","afterAll"];if(!W.includes($))throw Error(`Unexpected value for position to addHelpText.
27
27
  Expecting one of '${W.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 g3($){return $.map((w)=>{if(!w.startsWith("--inspect"))return w;let W,Z="127.0.0.1",X="9229",Y;if((Y=w.match(/^(--inspect(-brk)?)$/))!==null)W=Y[1];else if((Y=w.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(W=Y[1],/^\d+$/.test(Y[3]))X=Y[3];else Z=Y[3];else if((Y=w.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)W=Y[1],Z=Y[3],X=Y[4];if(W&&X!=="0")return`${W}=${Z}:${parseInt(X)+1}`;return w})}function UW(){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}Dz.Command=HW;Dz.useColor=UW});var OW=L((Cz)=>{var{Argument:h3}=$8(),{Command:FW}=v3(),{CommanderError:Sz,InvalidArgumentError:u3}=lw(),{Help:Rz}=PW(),{Option:i3}=VW();Cz.program=new FW;Cz.createCommand=($)=>new FW($);Cz.createOption=($,w)=>new i3($,w);Cz.createArgument=($,w)=>new h3($,w);Cz.Command=FW;Cz.Option=i3;Cz.Argument=h3;Cz.Help=Rz;Cz.CommanderError=Sz;Cz.InvalidArgumentError=u3;Cz.InvalidOptionArgumentError=u3});var dw=L((s3)=>{Object.defineProperty(s3,"__esModule",{value:!0});s3.regexpCode=s3.getEsmExportName=s3.getProperty=s3.safeStringify=s3.stringify=s3.strConcat=s3.addCodeArg=s3.str=s3._=s3.nil=s3._Code=s3.Name=s3.IDENTIFIER=s3._CodeOrName=void 0;class X8{}s3._CodeOrName=X8;s3.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class c1 extends X8{constructor($){super();if(!s3.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}}}s3.Name=c1;class c0 extends X8{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,W)=>`${w}${W}`,"")}get names(){var $;return($=this._names)!==null&&$!==void 0?$:this._names=this._items.reduce((w,W)=>{if(W instanceof c1)w[W.str]=(w[W.str]||0)+1;return w},{})}}s3._Code=c0;s3.nil=new c0("");function t3($,...w){let W=[$[0]],Z=0;while(Z<w.length)AW(W,w[Z]),W.push($[++Z]);return new c0(W)}s3._=t3;var kW=new c0("+");function r3($,...w){let W=[cw($[0])],Z=0;while(Z<w.length)W.push(kW),AW(W,w[Z]),W.push(kW,cw($[++Z]));return tz(W),new c0(W)}s3.str=r3;function AW($,w){if(w instanceof c0)$.push(...w._items);else if(w instanceof c1)$.push(w);else $.push(az(w))}s3.addCodeArg=AW;function tz($){let w=1;while(w<$.length-1){if($[w]===kW){let W=rz($[w-1],$[w+1]);if(W!==void 0){$.splice(w-1,3,W);continue}$[w++]="+"}w++}}function rz($,w){if(w==='""')return $;if($==='""')return w;if(typeof $=="string"){if(w instanceof c1||$[$.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 c1))return`"${$}${w.slice(1)}`;return}function sz($,w){return w.emptyStr()?$:$.emptyStr()?w:r3`${$}${w}`}s3.strConcat=sz;function az($){return typeof $=="number"||typeof $=="boolean"||$===null?$:cw(Array.isArray($)?$.join(","):$)}function oz($){return new c0(cw($))}s3.stringify=oz;function cw($){return JSON.stringify($).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}s3.safeStringify=cw;function ez($){return typeof $=="string"&&s3.IDENTIFIER.test($)?new c0(`.${$}`):t3`[${$}]`}s3.getProperty=ez;function $N($){if(typeof $=="string"&&s3.IDENTIFIER.test($))return new c0(`${$}`);throw Error(`CodeGen: invalid export name: ${$}, use explicit $id name mapping`)}s3.getEsmExportName=$N;function wN($){return new c0($.toString())}s3.regexpCode=wN});var jW=L(($X)=>{Object.defineProperty($X,"__esModule",{value:!0});$X.ValueScope=$X.ValueScopeName=$X.Scope=$X.varKinds=$X.UsedValueState=void 0;var D0=dw();class o3 extends Error{constructor($){super(`CodeGen: "code" for ${$} not defined`);this.value=$.value}}var G8;(function($){$[$.Started=0]="Started",$[$.Completed=1]="Completed"})(G8||($X.UsedValueState=G8={}));$X.varKinds={const:new D0.Name("const"),let:new D0.Name("let"),var:new D0.Name("var")};class RW{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,W;if(((W=(w=this._parent)===null||w===void 0?void 0:w._prefixes)===null||W===void 0?void 0:W.has($))||this._prefixes&&!this._prefixes.has($))throw Error(`CodeGen: prefix "${$}" is not allowed in this scope`);return this._names[$]={prefix:$,index:0}}}$X.Scope=RW;class CW extends D0.Name{constructor($,w){super(w);this.prefix=$}setValue($,{property:w,itemIndex:W}){this.value=$,this.scopePath=D0._`.${new D0.Name(w)}[${W}]`}}$X.ValueScopeName=CW;var BN=D0._`\n`;class e3 extends RW{constructor($){super($);this._values={},this._scope=$.scope,this.opts={...$,_n:$.lines?BN:D0.nil}}get(){return this._scope}name($){return new CW($,this._newName($))}value($,w){var W;if(w.ref===void 0)throw Error("CodeGen: ref must be passed in value");let Z=this.toName($),{prefix:X}=Z,Y=(W=w.key)!==null&&W!==void 0?W:w.ref,G=this._values[X];if(G){let Q=G.get(Y);if(Q)return Q}else G=this._values[X]=new Map;G.set(Y,Z);let J=this._scope[X]||(this._scope[X]=[]),T=J.length;return J[T]=w.ref,Z.setValue(w,{property:X,itemIndex:T}),Z}getValue($,w){let W=this._values[$];if(!W)return;return W.get(w)}scopeRefs($,w=this._values){return this._reduceValues(w,(W)=>{if(W.scopePath===void 0)throw Error(`CodeGen: name "${W}" has no value`);return D0._`${$}${W.scopePath}`})}scopeCode($=this._values,w,W){return this._reduceValues($,(Z)=>{if(Z.value===void 0)throw Error(`CodeGen: name "${Z}" has no value`);return Z.value.code},w,W)}_reduceValues($,w,W={},Z){let X=D0.nil;for(let Y in $){let G=$[Y];if(!G)continue;let J=W[Y]=W[Y]||new Map;G.forEach((T)=>{if(J.has(T))return;J.set(T,G8.Started);let Q=w(T);if(Q){let M=this.opts.es5?$X.varKinds.var:$X.varKinds.const;X=D0._`${X}${M} ${T} = ${Q};${this.opts._n}`}else if(Q=Z===null||Z===void 0?void 0:Z(T))X=D0._`${X}${Q}${this.opts._n}`;else throw new o3(T);J.set(T,G8.Completed)})}return X}}$X.ValueScope=e3});var u=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=dw(),d0=jW(),I$=dw();Object.defineProperty(k0,"_",{enumerable:!0,get:function(){return I$._}});Object.defineProperty(k0,"str",{enumerable:!0,get:function(){return I$.str}});Object.defineProperty(k0,"strConcat",{enumerable:!0,get:function(){return I$.strConcat}});Object.defineProperty(k0,"nil",{enumerable:!0,get:function(){return I$.nil}});Object.defineProperty(k0,"getProperty",{enumerable:!0,get:function(){return I$.getProperty}});Object.defineProperty(k0,"stringify",{enumerable:!0,get:function(){return I$.stringify}});Object.defineProperty(k0,"regexpCode",{enumerable:!0,get:function(){return I$.regexpCode}});Object.defineProperty(k0,"Name",{enumerable:!0,get:function(){return I$.Name}});var N8=jW();Object.defineProperty(k0,"Scope",{enumerable:!0,get:function(){return N8.Scope}});Object.defineProperty(k0,"ValueScope",{enumerable:!0,get:function(){return N8.ValueScope}});Object.defineProperty(k0,"ValueScopeName",{enumerable:!0,get:function(){return N8.ValueScopeName}});Object.defineProperty(k0,"varKinds",{enumerable:!0,get:function(){return N8.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 b${optimizeNodes(){return this}optimizeNames($,w){return this}}class WX extends b${constructor($,w,W){super();this.varKind=$,this.name=w,this.rhs=W}render({es5:$,_n:w}){let W=$?d0.varKinds.var:this.varKind,Z=this.rhs===void 0?"":` = ${this.rhs}`;return`${W} ${this.name}${Z};`+w}optimizeNames($,w){if(!$[this.name.str])return;if(this.rhs)this.rhs=n1(this.rhs,$,w);return this}get names(){return this.rhs instanceof l._CodeOrName?this.rhs.names:{}}}class bW extends b${constructor($,w,W){super();this.lhs=$,this.rhs=w,this.sideEffects=W}render({_n:$}){return`${this.lhs} = ${this.rhs};`+$}optimizeNames($,w){if(this.lhs instanceof l.Name&&!$[this.lhs.str]&&!this.sideEffects)return;return this.rhs=n1(this.rhs,$,w),this}get names(){let $=this.lhs instanceof l.Name?{}:{...this.lhs.names};return z8($,this.rhs)}}class ZX extends bW{constructor($,w,W,Z){super($,W,Z);this.op=w}render({_n:$}){return`${this.lhs} ${this.op}= ${this.rhs};`+$}}class XX extends b${constructor($){super();this.label=$,this.names={}}render({_n:$}){return`${this.label}:`+$}}class YX extends b${constructor($){super();this.label=$,this.names={}}render({_n:$}){return`break${this.label?` ${this.label}`:""};`+$}}class GX extends b${constructor($){super();this.error=$}render({_n:$}){return`throw ${this.error};`+$}get names(){return this.error.names}}class JX extends b${constructor($){super();this.code=$}render({_n:$}){return`${this.code};`+$}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames($,w){return this.code=n1(this.code,$,w),this}get names(){return this.code instanceof l._CodeOrName?this.code.names:{}}}class K8 extends b${constructor($=[]){super();this.nodes=$}render($){return this.nodes.reduce((w,W)=>w+W.render($),"")}optimizeNodes(){let{nodes:$}=this,w=$.length;while(w--){let W=$[w].optimizeNodes();if(Array.isArray(W))$.splice(w,1,...W);else if(W)$[w]=W;else $.splice(w,1)}return $.length>0?this:void 0}optimizeNames($,w){let{nodes:W}=this,Z=W.length;while(Z--){let X=W[Z];if(X.optimizeNames($,w))continue;qN($,X.names),W.splice(Z,1)}return W.length>0?this:void 0}get names(){return this.nodes.reduce(($,w)=>W1($,w.names),{})}}class x$ extends K8{render($){return"{"+$._n+super.render($)+"}"+$._n}}class TX extends K8{}class nw extends x${}nw.kind="else";class K$ extends x${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 W=w.optimizeNodes();w=this.else=Array.isArray(W)?new nw(W):W}if(w){if($===!1)return w instanceof K$?w:w.nodes;if(this.nodes.length)return this;return new K$(KX($),w instanceof K$?[w]:w.nodes)}if($===!1||!this.nodes.length)return;return this}optimizeNames($,w){var W;if(this.else=(W=this.else)===null||W===void 0?void 0:W.optimizeNames($,w),!(super.optimizeNames($,w)||this.else))return;return this.condition=n1(this.condition,$,w),this}get names(){let $=super.names;if(z8($,this.condition),this.else)W1($,this.else.names);return $}}K$.kind="if";class d1 extends x${}d1.kind="for";class QX extends d1{constructor($){super();this.iteration=$}render($){return`for(${this.iteration})`+super.render($)}optimizeNames($,w){if(!super.optimizeNames($,w))return;return this.iteration=n1(this.iteration,$,w),this}get names(){return W1(super.names,this.iteration.names)}}class MX extends d1{constructor($,w,W,Z){super();this.varKind=$,this.name=w,this.from=W,this.to=Z}render($){let w=$.es5?d0.varKinds.var:this.varKind,{name:W,from:Z,to:X}=this;return`for(${w} ${W}=${Z}; ${W}<${X}; ${W}++)`+super.render($)}get names(){let $=z8(super.names,this.from);return z8($,this.to)}}class yW extends d1{constructor($,w,W,Z){super();this.loop=$,this.varKind=w,this.name=W,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=n1(this.iterable,$,w),this}get names(){return W1(super.names,this.iterable.names)}}class J8 extends x${constructor($,w,W){super();this.name=$,this.args=w,this.async=W}render($){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render($)}}J8.kind="func";class T8 extends K8{render($){return"return "+super.render($)}}T8.kind="return";class zX extends x${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 W,Z;return super.optimizeNames($,w),(W=this.catch)===null||W===void 0||W.optimizeNames($,w),(Z=this.finally)===null||Z===void 0||Z.optimizeNames($,w),this}get names(){let $=super.names;if(this.catch)W1($,this.catch.names);if(this.finally)W1($,this.finally.names);return $}}class Q8 extends x${constructor($){super();this.error=$}render($){return`catch(${this.error})`+super.render($)}}Q8.kind="catch";class M8 extends x${render($){return"finally"+super.render($)}}M8.kind="finally";class NX{constructor($,w={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...w,_n:w.lines?`
29
- `:""},this._extScope=$,this._scope=new d0.Scope({parent:$}),this._nodes=[new TX]}toString(){return this._root.render(this.opts)}name($){return this._scope.name($)}scopeName($){return this._extScope.name($)}scopeValue($,w){let W=this._extScope.value($,w);return(this._values[W.prefix]||(this._values[W.prefix]=new Set)).add(W),W}getScopeValue($,w){return this._extScope.getValue($,w)}scopeRefs($){return this._extScope.scopeRefs($,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def($,w,W,Z){let X=this._scope.toName(w);if(W!==void 0&&Z)this._constants[X.str]=W;return this._leafNode(new WX($,X,W)),X}const($,w,W){return this._def(d0.varKinds.const,$,w,W)}let($,w,W){return this._def(d0.varKinds.let,$,w,W)}var($,w,W){return this._def(d0.varKinds.var,$,w,W)}assign($,w,W){return this._leafNode(new bW($,w,W))}add($,w){return this._leafNode(new ZX($,k0.operators.ADD,w))}code($){if(typeof $=="function")$();else if($!==l.nil)this._leafNode(new JX($));return this}object(...$){let w=["{"];for(let[W,Z]of $){if(w.length>1)w.push(",");if(w.push(W),W!==Z||this.opts.es5)w.push(":"),(0,l.addCodeArg)(w,Z)}return w.push("}"),new l._Code(w)}if($,w,W){if(this._blockNode(new K$($)),w&&W)this.code(w).else().code(W).endIf();else if(w)this.code(w).endIf();else if(W)throw Error('CodeGen: "else" body without "then" body');return this}elseIf($){return this._elseNode(new K$($))}else(){return this._elseNode(new nw)}endIf(){return this._endBlockNode(K$,nw)}_for($,w){if(this._blockNode($),w)this.code(w).endFor();return this}for($,w){return this._for(new QX($),w)}forRange($,w,W,Z,X=this.opts.es5?d0.varKinds.var:d0.varKinds.let){let Y=this._scope.toName($);return this._for(new MX(X,Y,w,W),()=>Z(Y))}forOf($,w,W,Z=d0.varKinds.const){let X=this._scope.toName($);if(this.opts.es5){let Y=w instanceof l.Name?w:this.var("_arr",w);return this.forRange("_i",0,l._`${Y}.length`,(G)=>{this.var(X,l._`${Y}[${G}]`),W(X)})}return this._for(new yW("of",Z,X,w),()=>W(X))}forIn($,w,W,Z=this.opts.es5?d0.varKinds.var:d0.varKinds.const){if(this.opts.ownProperties)return this.forOf($,l._`Object.keys(${w})`,W);let X=this._scope.toName($);return this._for(new yW("in",Z,X,w),()=>W(X))}endFor(){return this._endBlockNode(d1)}label($){return this._leafNode(new XX($))}break($){return this._leafNode(new YX($))}return($){let w=new T8;if(this._blockNode(w),this.code($),w.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(T8)}try($,w,W){if(!w&&!W)throw Error('CodeGen: "try" without "catch" and "finally"');let Z=new zX;if(this._blockNode(Z),this.code($),w){let X=this.name("e");this._currNode=Z.catch=new Q8(X),w(X)}if(W)this._currNode=Z.finally=new M8,this.code(W);return this._endBlockNode(Q8,M8)}throw($){return this._leafNode(new GX($))}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 W=this._nodes.length-w;if(W<0||$!==void 0&&W!==$)throw Error(`CodeGen: wrong number of nodes: ${W} vs ${$} expected`);return this._nodes.length=w,this}func($,w=l.nil,W,Z){if(this._blockNode(new J8($,w,W)),Z)this.code(Z).endFunc();return this}endFunc(){return this._endBlockNode(J8)}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 W=this._currNode;if(W instanceof $||w&&W 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 K$))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=NX;function W1($,w){for(let W in w)$[W]=($[W]||0)+(w[W]||0);return $}function z8($,w){return w instanceof l._CodeOrName?W1($,w.names):$}function n1($,w,W){if($ instanceof l.Name)return Z($);if(!X($))return $;return new l._Code($._items.reduce((Y,G)=>{if(G instanceof l.Name)G=Z(G);if(G instanceof l._Code)Y.push(...G._items);else Y.push(G);return Y},[]));function Z(Y){let G=W[Y.str];if(G===void 0||w[Y.str]!==1)return Y;return delete w[Y.str],G}function X(Y){return Y instanceof l._Code&&Y._items.some((G)=>G instanceof l.Name&&w[G.str]===1&&W[G.str]!==void 0)}}function qN($,w){for(let W in w)$[W]=($[W]||0)-(w[W]||0)}function KX($){return typeof $=="boolean"||typeof $=="number"||$===null?!$:l._`!${IW($)}`}k0.not=KX;var UN=BX(k0.operators.AND);function HN(...$){return $.reduce(UN)}k0.and=HN;var FN=BX(k0.operators.OR);function ON(...$){return $.reduce(FN)}k0.or=ON;function BX($){return(w,W)=>w===l.nil?W:W===l.nil?w:l._`${IW(w)} ${$} ${IW(W)}`}function IW($){return $ instanceof l.Name?$:l._`(${$})`}});var c=L((EX)=>{Object.defineProperty(EX,"__esModule",{value:!0});EX.checkStrictMode=EX.getErrorPath=EX.Type=EX.useFunc=EX.setEvaluated=EX.evaluatedPropsToName=EX.mergeEvaluated=EX.eachItem=EX.unescapeJsonPointer=EX.escapeJsonPointer=EX.escapeFragment=EX.unescapeFragment=EX.schemaRefOrVal=EX.schemaHasRulesButRef=EX.schemaHasRules=EX.checkUnknownRules=EX.alwaysValidSchema=EX.toHash=void 0;var r=u(),kN=dw();function AN($){let w={};for(let W of $)w[W]=!0;return w}EX.toHash=AN;function SN($,w){if(typeof w=="boolean")return w;if(Object.keys(w).length===0)return!0;return qX($,w),!UX(w,$.self.RULES.all)}EX.alwaysValidSchema=SN;function qX($,w=$.schema){let{opts:W,self:Z}=$;if(!W.strictSchema)return;if(typeof w==="boolean")return;let X=Z.RULES.keywords;for(let Y in w)if(!X[Y])OX($,`unknown keyword: "${Y}"`)}EX.checkUnknownRules=qX;function UX($,w){if(typeof $=="boolean")return!$;for(let W in $)if(w[W])return!0;return!1}EX.schemaHasRules=UX;function RN($,w){if(typeof $=="boolean")return!$;for(let W in $)if(W!=="$ref"&&w.all[W])return!0;return!1}EX.schemaHasRulesButRef=RN;function CN({topSchemaRef:$,schemaPath:w},W,Z,X){if(!X){if(typeof W=="number"||typeof W=="boolean")return W;if(typeof W=="string")return r._`${W}`}return r._`${$}${w}${(0,r.getProperty)(Z)}`}EX.schemaRefOrVal=CN;function jN($){return HX(decodeURIComponent($))}EX.unescapeFragment=jN;function yN($){return encodeURIComponent(_W($))}EX.escapeFragment=yN;function _W($){if(typeof $=="number")return`${$}`;return $.replace(/~/g,"~0").replace(/\//g,"~1")}EX.escapeJsonPointer=_W;function HX($){return $.replace(/~1/g,"/").replace(/~0/g,"~")}EX.unescapeJsonPointer=HX;function IN($,w){if(Array.isArray($))for(let W of $)w(W);else w($)}EX.eachItem=IN;function VX({mergeNames:$,mergeToName:w,mergeValues:W,resultToName:Z}){return(X,Y,G,J)=>{let T=G===void 0?Y:G instanceof r.Name?(Y instanceof r.Name?$(X,Y,G):w(X,Y,G),G):Y instanceof r.Name?(w(X,G,Y),Y):W(Y,G);return J===r.Name&&!(T instanceof r.Name)?Z(X,T):T}}EX.mergeEvaluated={props:VX({mergeNames:($,w,W)=>$.if(r._`${W} !== true && ${w} !== undefined`,()=>{$.if(r._`${w} === true`,()=>$.assign(W,!0),()=>$.assign(W,r._`${W} || {}`).code(r._`Object.assign(${W}, ${w})`))}),mergeToName:($,w,W)=>$.if(r._`${W} !== true`,()=>{if(w===!0)$.assign(W,!0);else $.assign(W,r._`${W} || {}`),gW($,W,w)}),mergeValues:($,w)=>$===!0?!0:{...$,...w},resultToName:FX}),items:VX({mergeNames:($,w,W)=>$.if(r._`${W} !== true && ${w} !== undefined`,()=>$.assign(W,r._`${w} === true ? true : ${W} > ${w} ? ${W} : ${w}`)),mergeToName:($,w,W)=>$.if(r._`${W} !== true`,()=>$.assign(W,w===!0?!0:r._`${W} > ${w} ? ${W} : ${w}`)),mergeValues:($,w)=>$===!0?!0:Math.max($,w),resultToName:($,w)=>$.var("items",w)})};function FX($,w){if(w===!0)return $.var("props",!0);let W=$.var("props",r._`{}`);if(w!==void 0)gW($,W,w);return W}EX.evaluatedPropsToName=FX;function gW($,w,W){Object.keys(W).forEach((Z)=>$.assign(r._`${w}${(0,r.getProperty)(Z)}`,!0))}EX.setEvaluated=gW;var fX={};function bN($,w){return $.scopeValue("func",{ref:w,code:fX[w.code]||(fX[w.code]=new kN._Code(w.code))})}EX.useFunc=bN;var xW;(function($){$[$.Num=0]="Num",$[$.Str=1]="Str"})(xW||(EX.Type=xW={}));function xN($,w,W){if($ instanceof r.Name){let Z=w===xW.Num;return W?Z?r._`"[" + ${$} + "]"`:r._`"['" + ${$} + "']"`:Z?r._`"/" + ${$}`:r._`"/" + ${$}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return W?(0,r.getProperty)($).toString():"/"+_W($)}EX.getErrorPath=xN;function OX($,w,W=$.opts.strictSchema){if(!W)return;if(w=`strict mode: ${w}`,W===!0)throw Error(w);$.self.logger.warn(w)}EX.checkStrictMode=OX});var B$=L((DX)=>{Object.defineProperty(DX,"__esModule",{value:!0});var P0=u(),eN={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")};DX.default=eN});var pw=L((RX)=>{Object.defineProperty(RX,"__esModule",{value:!0});RX.extendErrors=RX.resetErrorsCount=RX.reportExtraError=RX.reportError=RX.keyword$DataError=RX.keywordError=void 0;var d=u(),P8=c(),O0=B$();RX.keywordError={message:({keyword:$})=>d.str`must pass "${$}" keyword validation`};RX.keyword$DataError={message:({keyword:$,schemaType:w})=>w?d.str`"${$}" keyword must be ${w} ($data)`:d.str`"${$}" keyword is invalid ($data)`};function wK($,w=RX.keywordError,W,Z){let{it:X}=$,{gen:Y,compositeRule:G,allErrors:J}=X,T=SX($,w,W);if(Z!==null&&Z!==void 0?Z:G||J)kX(Y,T);else AX(X,d._`[${T}]`)}RX.reportError=wK;function WK($,w=RX.keywordError,W){let{it:Z}=$,{gen:X,compositeRule:Y,allErrors:G}=Z,J=SX($,w,W);if(kX(X,J),!(Y||G))AX(Z,O0.default.vErrors)}RX.reportExtraError=WK;function ZK($,w){$.assign(O0.default.errors,w),$.if(d._`${O0.default.vErrors} !== null`,()=>$.if(w,()=>$.assign(d._`${O0.default.vErrors}.length`,w),()=>$.assign(O0.default.vErrors,null)))}RX.resetErrorsCount=ZK;function XK({gen:$,keyword:w,schemaValue:W,data:Z,errsCount:X,it:Y}){if(X===void 0)throw Error("ajv implementation error");let G=$.name("err");$.forRange("i",X,O0.default.errors,(J)=>{if($.const(G,d._`${O0.default.vErrors}[${J}]`),$.if(d._`${G}.instancePath === undefined`,()=>$.assign(d._`${G}.instancePath`,(0,d.strConcat)(O0.default.instancePath,Y.errorPath))),$.assign(d._`${G}.schemaPath`,d.str`${Y.errSchemaPath}/${w}`),Y.opts.verbose)$.assign(d._`${G}.schema`,W),$.assign(d._`${G}.data`,Z)})}RX.extendErrors=XK;function kX($,w){let W=$.const("err",w);$.if(d._`${O0.default.vErrors} === null`,()=>$.assign(O0.default.vErrors,d._`[${W}]`),d._`${O0.default.vErrors}.push(${W})`),$.code(d._`${O0.default.errors}++`)}function AX($,w){let{gen:W,validateName:Z,schemaEnv:X}=$;if(X.$async)W.throw(d._`new ${$.ValidationError}(${w})`);else W.assign(d._`${Z}.errors`,w),W.return(!1)}var Z1={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 SX($,w,W){let{createErrors:Z}=$.it;if(Z===!1)return d._`{}`;return YK($,w,W)}function YK($,w,W={}){let{gen:Z,it:X}=$,Y=[GK(X,W),JK($,W)];return TK($,w,Y),Z.object(...Y)}function GK({errorPath:$},{instancePath:w}){let W=w?d.str`${$}${(0,P8.getErrorPath)(w,P8.Type.Str)}`:$;return[O0.default.instancePath,(0,d.strConcat)(O0.default.instancePath,W)]}function JK({keyword:$,it:{errSchemaPath:w}},{schemaPath:W,parentSchema:Z}){let X=Z?w:d.str`${w}/${$}`;if(W)X=d.str`${X}${(0,P8.getErrorPath)(W,P8.Type.Str)}`;return[Z1.schemaPath,X]}function TK($,{params:w,message:W},Z){let{keyword:X,data:Y,schemaValue:G,it:J}=$,{opts:T,propertyName:Q,topSchemaRef:M,schemaPath:z}=J;if(Z.push([Z1.keyword,X],[Z1.params,typeof w=="function"?w($):w||d._`{}`]),T.messages)Z.push([Z1.message,typeof W=="function"?W($):W]);if(T.verbose)Z.push([Z1.schema,G],[Z1.parentSchema,d._`${M}${z}`],[O0.default.data,Y]);if(Q)Z.push([Z1.propertyName,Q])}});var bX=L((yX)=>{Object.defineProperty(yX,"__esModule",{value:!0});yX.boolOrEmptySchema=yX.topBoolOrEmptySchema=void 0;var KK=pw(),BK=u(),PK=B$(),VK={message:"boolean schema is false"};function fK($){let{gen:w,schema:W,validateName:Z}=$;if(W===!1)jX($,!1);else if(typeof W=="object"&&W.$async===!0)w.return(PK.default.data);else w.assign(BK._`${Z}.errors`,null),w.return(!0)}yX.topBoolOrEmptySchema=fK;function qK($,w){let{gen:W,schema:Z}=$;if(Z===!1)W.var(w,!1),jX($);else W.var(w,!0)}yX.boolOrEmptySchema=qK;function jX($,w){let{gen:W,data:Z}=$,X={gen:W,keyword:"false schema",data:Z,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:$};(0,KK.reportError)(X,VK,void 0,w)}});var hW=L((xX)=>{Object.defineProperty(xX,"__esModule",{value:!0});xX.getRules=xX.isJSONType=void 0;var HK=["string","number","integer","boolean","null","object","array"],FK=new Set(HK);function OK($){return typeof $=="string"&&FK.has($)}xX.isJSONType=OK;function EK(){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:{}}}xX.getRules=EK});var uW=L((hX)=>{Object.defineProperty(hX,"__esModule",{value:!0});hX.shouldUseRule=hX.shouldUseGroup=hX.schemaHasRulesForType=void 0;function DK({schema:$,self:w},W){let Z=w.RULES.types[W];return Z&&Z!==!0&&gX($,Z)}hX.schemaHasRulesForType=DK;function gX($,w){return w.rules.some((W)=>vX($,W))}hX.shouldUseGroup=gX;function vX($,w){var W;return $[w.keyword]!==void 0||((W=w.definition.implements)===null||W===void 0?void 0:W.some((Z)=>$[Z]!==void 0))}hX.shouldUseRule=vX});var tw=L((cX)=>{Object.defineProperty(cX,"__esModule",{value:!0});cX.reportTypeError=cX.checkDataTypes=cX.checkDataType=cX.coerceAndCheckDataType=cX.getJSONTypes=cX.getSchemaTypes=cX.DataType=void 0;var SK=hW(),RK=uW(),CK=pw(),v=u(),iX=c(),p1;(function($){$[$.Correct=0]="Correct",$[$.Wrong=1]="Wrong"})(p1||(cX.DataType=p1={}));function jK($){let w=mX($.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}cX.getSchemaTypes=jK;function mX($){let w=Array.isArray($)?$:$?[$]:[];if(w.every(SK.isJSONType))return w;throw Error("type must be JSONType or JSONType[]: "+w.join(","))}cX.getJSONTypes=mX;function yK($,w){let{gen:W,data:Z,opts:X}=$,Y=IK(w,X.coerceTypes),G=w.length>0&&!(Y.length===0&&w.length===1&&(0,RK.schemaHasRulesForType)($,w[0]));if(G){let J=mW(w,Z,X.strictNumbers,p1.Wrong);W.if(J,()=>{if(Y.length)bK($,w,Y);else lW($)})}return G}cX.coerceAndCheckDataType=yK;var lX=new Set(["string","number","integer","boolean","null"]);function IK($,w){return w?$.filter((W)=>lX.has(W)||w==="array"&&W==="array"):[]}function bK($,w,W){let{gen:Z,data:X,opts:Y}=$,G=Z.let("dataType",v._`typeof ${X}`),J=Z.let("coerced",v._`undefined`);if(Y.coerceTypes==="array")Z.if(v._`${G} == 'object' && Array.isArray(${X}) && ${X}.length == 1`,()=>Z.assign(X,v._`${X}[0]`).assign(G,v._`typeof ${X}`).if(mW(w,X,Y.strictNumbers),()=>Z.assign(J,X)));Z.if(v._`${J} !== undefined`);for(let Q of W)if(lX.has(Q)||Q==="array"&&Y.coerceTypes==="array")T(Q);Z.else(),lW($),Z.endIf(),Z.if(v._`${J} !== undefined`,()=>{Z.assign(X,J),xK($,J)});function T(Q){switch(Q){case"string":Z.elseIf(v._`${G} == "number" || ${G} == "boolean"`).assign(J,v._`"" + ${X}`).elseIf(v._`${X} === null`).assign(J,v._`""`);return;case"number":Z.elseIf(v._`${G} == "boolean" || ${X} === null
28
+ `)}),this}_outputHelpIfRequested($){let w=this._getHelpOption();if(w&&$.find((Z)=>w.is(Z)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function vX($){return $.map((w)=>{if(!w.startsWith("--inspect"))return w;let W,Z="127.0.0.1",X="9229",Y;if((Y=w.match(/^(--inspect(-brk)?)$/))!==null)W=Y[1];else if((Y=w.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(W=Y[1],/^\d+$/.test(Y[3]))X=Y[3];else Z=Y[3];else if((Y=w.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)W=Y[1],Z=Y[3],X=Y[4];if(W&&X!=="0")return`${W}=${Z}:${parseInt(X)+1}`;return w})}function HW(){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}Dz.Command=FW;Dz.useColor=HW});var EW=L((Cz)=>{var{Argument:hX}=w8(),{Command:OW}=uX(),{CommanderError:Sz,InvalidArgumentError:iX}=lw(),{Help:Rz}=VW(),{Option:mX}=fW();Cz.program=new OW;Cz.createCommand=($)=>new OW($);Cz.createOption=($,w)=>new mX($,w);Cz.createArgument=($,w)=>new hX($,w);Cz.Command=OW;Cz.Option=mX;Cz.Argument=hX;Cz.Help=Rz;Cz.CommanderError=Sz;Cz.InvalidArgumentError=iX;Cz.InvalidOptionArgumentError=iX});var dw=L((aX)=>{Object.defineProperty(aX,"__esModule",{value:!0});aX.regexpCode=aX.getEsmExportName=aX.getProperty=aX.safeStringify=aX.stringify=aX.strConcat=aX.addCodeArg=aX.str=aX._=aX.nil=aX._Code=aX.Name=aX.IDENTIFIER=aX._CodeOrName=void 0;class Y8{}aX._CodeOrName=Y8;aX.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class c1 extends Y8{constructor($){super();if(!aX.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}}}aX.Name=c1;class d0 extends Y8{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,W)=>`${w}${W}`,"")}get names(){var $;return($=this._names)!==null&&$!==void 0?$:this._names=this._items.reduce((w,W)=>{if(W instanceof c1)w[W.str]=(w[W.str]||0)+1;return w},{})}}aX._Code=d0;aX.nil=new d0("");function rX($,...w){let W=[$[0]],Z=0;while(Z<w.length)SW(W,w[Z]),W.push($[++Z]);return new d0(W)}aX._=rX;var AW=new d0("+");function sX($,...w){let W=[cw($[0])],Z=0;while(Z<w.length)W.push(AW),SW(W,w[Z]),W.push(AW,cw($[++Z]));return tz(W),new d0(W)}aX.str=sX;function SW($,w){if(w instanceof d0)$.push(...w._items);else if(w instanceof c1)$.push(w);else $.push(az(w))}aX.addCodeArg=SW;function tz($){let w=1;while(w<$.length-1){if($[w]===AW){let W=rz($[w-1],$[w+1]);if(W!==void 0){$.splice(w-1,3,W);continue}$[w++]="+"}w++}}function rz($,w){if(w==='""')return $;if($==='""')return w;if(typeof $=="string"){if(w instanceof c1||$[$.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 c1))return`"${$}${w.slice(1)}`;return}function sz($,w){return w.emptyStr()?$:$.emptyStr()?w:sX`${$}${w}`}aX.strConcat=sz;function az($){return typeof $=="number"||typeof $=="boolean"||$===null?$:cw(Array.isArray($)?$.join(","):$)}function oz($){return new d0(cw($))}aX.stringify=oz;function cw($){return JSON.stringify($).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}aX.safeStringify=cw;function ez($){return typeof $=="string"&&aX.IDENTIFIER.test($)?new d0(`.${$}`):rX`[${$}]`}aX.getProperty=ez;function $N($){if(typeof $=="string"&&aX.IDENTIFIER.test($))return new d0(`${$}`);throw Error(`CodeGen: invalid export name: ${$}, use explicit $id name mapping`)}aX.getEsmExportName=$N;function wN($){return new d0($.toString())}aX.regexpCode=wN});var yW=L((w3)=>{Object.defineProperty(w3,"__esModule",{value:!0});w3.ValueScope=w3.ValueScopeName=w3.Scope=w3.varKinds=w3.UsedValueState=void 0;var D0=dw();class eX extends Error{constructor($){super(`CodeGen: "code" for ${$} not defined`);this.value=$.value}}var J8;(function($){$[$.Started=0]="Started",$[$.Completed=1]="Completed"})(J8||(w3.UsedValueState=J8={}));w3.varKinds={const:new D0.Name("const"),let:new D0.Name("let"),var:new D0.Name("var")};class CW{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,W;if(((W=(w=this._parent)===null||w===void 0?void 0:w._prefixes)===null||W===void 0?void 0:W.has($))||this._prefixes&&!this._prefixes.has($))throw Error(`CodeGen: prefix "${$}" is not allowed in this scope`);return this._names[$]={prefix:$,index:0}}}w3.Scope=CW;class jW extends D0.Name{constructor($,w){super(w);this.prefix=$}setValue($,{property:w,itemIndex:W}){this.value=$,this.scopePath=D0._`.${new D0.Name(w)}[${W}]`}}w3.ValueScopeName=jW;var BN=D0._`\n`;class $3 extends CW{constructor($){super($);this._values={},this._scope=$.scope,this.opts={...$,_n:$.lines?BN:D0.nil}}get(){return this._scope}name($){return new jW($,this._newName($))}value($,w){var W;if(w.ref===void 0)throw Error("CodeGen: ref must be passed in value");let Z=this.toName($),{prefix:X}=Z,Y=(W=w.key)!==null&&W!==void 0?W:w.ref,G=this._values[X];if(G){let Q=G.get(Y);if(Q)return Q}else G=this._values[X]=new Map;G.set(Y,Z);let J=this._scope[X]||(this._scope[X]=[]),T=J.length;return J[T]=w.ref,Z.setValue(w,{property:X,itemIndex:T}),Z}getValue($,w){let W=this._values[$];if(!W)return;return W.get(w)}scopeRefs($,w=this._values){return this._reduceValues(w,(W)=>{if(W.scopePath===void 0)throw Error(`CodeGen: name "${W}" has no value`);return D0._`${$}${W.scopePath}`})}scopeCode($=this._values,w,W){return this._reduceValues($,(Z)=>{if(Z.value===void 0)throw Error(`CodeGen: name "${Z}" has no value`);return Z.value.code},w,W)}_reduceValues($,w,W={},Z){let X=D0.nil;for(let Y in $){let G=$[Y];if(!G)continue;let J=W[Y]=W[Y]||new Map;G.forEach((T)=>{if(J.has(T))return;J.set(T,J8.Started);let Q=w(T);if(Q){let M=this.opts.es5?w3.varKinds.var:w3.varKinds.const;X=D0._`${X}${M} ${T} = ${Q};${this.opts._n}`}else if(Q=Z===null||Z===void 0?void 0:Z(T))X=D0._`${X}${Q}${this.opts._n}`;else throw new eX(T);J.set(T,J8.Completed)})}return X}}w3.ValueScope=$3});var h=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=dw(),n0=yW(),I$=dw();Object.defineProperty(k0,"_",{enumerable:!0,get:function(){return I$._}});Object.defineProperty(k0,"str",{enumerable:!0,get:function(){return I$.str}});Object.defineProperty(k0,"strConcat",{enumerable:!0,get:function(){return I$.strConcat}});Object.defineProperty(k0,"nil",{enumerable:!0,get:function(){return I$.nil}});Object.defineProperty(k0,"getProperty",{enumerable:!0,get:function(){return I$.getProperty}});Object.defineProperty(k0,"stringify",{enumerable:!0,get:function(){return I$.stringify}});Object.defineProperty(k0,"regexpCode",{enumerable:!0,get:function(){return I$.regexpCode}});Object.defineProperty(k0,"Name",{enumerable:!0,get:function(){return I$.Name}});var K8=yW();Object.defineProperty(k0,"Scope",{enumerable:!0,get:function(){return K8.Scope}});Object.defineProperty(k0,"ValueScope",{enumerable:!0,get:function(){return K8.ValueScope}});Object.defineProperty(k0,"ValueScopeName",{enumerable:!0,get:function(){return K8.ValueScopeName}});Object.defineProperty(k0,"varKinds",{enumerable:!0,get:function(){return K8.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 b${optimizeNodes(){return this}optimizeNames($,w){return this}}class Z3 extends b${constructor($,w,W){super();this.varKind=$,this.name=w,this.rhs=W}render({es5:$,_n:w}){let W=$?n0.varKinds.var:this.varKind,Z=this.rhs===void 0?"":` = ${this.rhs}`;return`${W} ${this.name}${Z};`+w}optimizeNames($,w){if(!$[this.name.str])return;if(this.rhs)this.rhs=n1(this.rhs,$,w);return this}get names(){return this.rhs instanceof l._CodeOrName?this.rhs.names:{}}}class xW extends b${constructor($,w,W){super();this.lhs=$,this.rhs=w,this.sideEffects=W}render({_n:$}){return`${this.lhs} = ${this.rhs};`+$}optimizeNames($,w){if(this.lhs instanceof l.Name&&!$[this.lhs.str]&&!this.sideEffects)return;return this.rhs=n1(this.rhs,$,w),this}get names(){let $=this.lhs instanceof l.Name?{}:{...this.lhs.names};return N8($,this.rhs)}}class X3 extends xW{constructor($,w,W,Z){super($,W,Z);this.op=w}render({_n:$}){return`${this.lhs} ${this.op}= ${this.rhs};`+$}}class Y3 extends b${constructor($){super();this.label=$,this.names={}}render({_n:$}){return`${this.label}:`+$}}class G3 extends b${constructor($){super();this.label=$,this.names={}}render({_n:$}){return`break${this.label?` ${this.label}`:""};`+$}}class J3 extends b${constructor($){super();this.error=$}render({_n:$}){return`throw ${this.error};`+$}get names(){return this.error.names}}class T3 extends b${constructor($){super();this.code=$}render({_n:$}){return`${this.code};`+$}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames($,w){return this.code=n1(this.code,$,w),this}get names(){return this.code instanceof l._CodeOrName?this.code.names:{}}}class B8 extends b${constructor($=[]){super();this.nodes=$}render($){return this.nodes.reduce((w,W)=>w+W.render($),"")}optimizeNodes(){let{nodes:$}=this,w=$.length;while(w--){let W=$[w].optimizeNodes();if(Array.isArray(W))$.splice(w,1,...W);else if(W)$[w]=W;else $.splice(w,1)}return $.length>0?this:void 0}optimizeNames($,w){let{nodes:W}=this,Z=W.length;while(Z--){let X=W[Z];if(X.optimizeNames($,w))continue;qN($,X.names),W.splice(Z,1)}return W.length>0?this:void 0}get names(){return this.nodes.reduce(($,w)=>W1($,w.names),{})}}class x$ extends B8{render($){return"{"+$._n+super.render($)+"}"+$._n}}class Q3 extends B8{}class nw extends x${}nw.kind="else";class K$ extends x${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 W=w.optimizeNodes();w=this.else=Array.isArray(W)?new nw(W):W}if(w){if($===!1)return w instanceof K$?w:w.nodes;if(this.nodes.length)return this;return new K$(B3($),w instanceof K$?[w]:w.nodes)}if($===!1||!this.nodes.length)return;return this}optimizeNames($,w){var W;if(this.else=(W=this.else)===null||W===void 0?void 0:W.optimizeNames($,w),!(super.optimizeNames($,w)||this.else))return;return this.condition=n1(this.condition,$,w),this}get names(){let $=super.names;if(N8($,this.condition),this.else)W1($,this.else.names);return $}}K$.kind="if";class d1 extends x${}d1.kind="for";class M3 extends d1{constructor($){super();this.iteration=$}render($){return`for(${this.iteration})`+super.render($)}optimizeNames($,w){if(!super.optimizeNames($,w))return;return this.iteration=n1(this.iteration,$,w),this}get names(){return W1(super.names,this.iteration.names)}}class z3 extends d1{constructor($,w,W,Z){super();this.varKind=$,this.name=w,this.from=W,this.to=Z}render($){let w=$.es5?n0.varKinds.var:this.varKind,{name:W,from:Z,to:X}=this;return`for(${w} ${W}=${Z}; ${W}<${X}; ${W}++)`+super.render($)}get names(){let $=N8(super.names,this.from);return N8($,this.to)}}class IW extends d1{constructor($,w,W,Z){super();this.loop=$,this.varKind=w,this.name=W,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=n1(this.iterable,$,w),this}get names(){return W1(super.names,this.iterable.names)}}class T8 extends x${constructor($,w,W){super();this.name=$,this.args=w,this.async=W}render($){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render($)}}T8.kind="func";class Q8 extends B8{render($){return"return "+super.render($)}}Q8.kind="return";class N3 extends x${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 W,Z;return super.optimizeNames($,w),(W=this.catch)===null||W===void 0||W.optimizeNames($,w),(Z=this.finally)===null||Z===void 0||Z.optimizeNames($,w),this}get names(){let $=super.names;if(this.catch)W1($,this.catch.names);if(this.finally)W1($,this.finally.names);return $}}class M8 extends x${constructor($){super();this.error=$}render($){return`catch(${this.error})`+super.render($)}}M8.kind="catch";class z8 extends x${render($){return"finally"+super.render($)}}z8.kind="finally";class K3{constructor($,w={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...w,_n:w.lines?`
29
+ `:""},this._extScope=$,this._scope=new n0.Scope({parent:$}),this._nodes=[new Q3]}toString(){return this._root.render(this.opts)}name($){return this._scope.name($)}scopeName($){return this._extScope.name($)}scopeValue($,w){let W=this._extScope.value($,w);return(this._values[W.prefix]||(this._values[W.prefix]=new Set)).add(W),W}getScopeValue($,w){return this._extScope.getValue($,w)}scopeRefs($){return this._extScope.scopeRefs($,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def($,w,W,Z){let X=this._scope.toName(w);if(W!==void 0&&Z)this._constants[X.str]=W;return this._leafNode(new Z3($,X,W)),X}const($,w,W){return this._def(n0.varKinds.const,$,w,W)}let($,w,W){return this._def(n0.varKinds.let,$,w,W)}var($,w,W){return this._def(n0.varKinds.var,$,w,W)}assign($,w,W){return this._leafNode(new xW($,w,W))}add($,w){return this._leafNode(new X3($,k0.operators.ADD,w))}code($){if(typeof $=="function")$();else if($!==l.nil)this._leafNode(new T3($));return this}object(...$){let w=["{"];for(let[W,Z]of $){if(w.length>1)w.push(",");if(w.push(W),W!==Z||this.opts.es5)w.push(":"),(0,l.addCodeArg)(w,Z)}return w.push("}"),new l._Code(w)}if($,w,W){if(this._blockNode(new K$($)),w&&W)this.code(w).else().code(W).endIf();else if(w)this.code(w).endIf();else if(W)throw Error('CodeGen: "else" body without "then" body');return this}elseIf($){return this._elseNode(new K$($))}else(){return this._elseNode(new nw)}endIf(){return this._endBlockNode(K$,nw)}_for($,w){if(this._blockNode($),w)this.code(w).endFor();return this}for($,w){return this._for(new M3($),w)}forRange($,w,W,Z,X=this.opts.es5?n0.varKinds.var:n0.varKinds.let){let Y=this._scope.toName($);return this._for(new z3(X,Y,w,W),()=>Z(Y))}forOf($,w,W,Z=n0.varKinds.const){let X=this._scope.toName($);if(this.opts.es5){let Y=w instanceof l.Name?w:this.var("_arr",w);return this.forRange("_i",0,l._`${Y}.length`,(G)=>{this.var(X,l._`${Y}[${G}]`),W(X)})}return this._for(new IW("of",Z,X,w),()=>W(X))}forIn($,w,W,Z=this.opts.es5?n0.varKinds.var:n0.varKinds.const){if(this.opts.ownProperties)return this.forOf($,l._`Object.keys(${w})`,W);let X=this._scope.toName($);return this._for(new IW("in",Z,X,w),()=>W(X))}endFor(){return this._endBlockNode(d1)}label($){return this._leafNode(new Y3($))}break($){return this._leafNode(new G3($))}return($){let w=new Q8;if(this._blockNode(w),this.code($),w.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(Q8)}try($,w,W){if(!w&&!W)throw Error('CodeGen: "try" without "catch" and "finally"');let Z=new N3;if(this._blockNode(Z),this.code($),w){let X=this.name("e");this._currNode=Z.catch=new M8(X),w(X)}if(W)this._currNode=Z.finally=new z8,this.code(W);return this._endBlockNode(M8,z8)}throw($){return this._leafNode(new J3($))}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 W=this._nodes.length-w;if(W<0||$!==void 0&&W!==$)throw Error(`CodeGen: wrong number of nodes: ${W} vs ${$} expected`);return this._nodes.length=w,this}func($,w=l.nil,W,Z){if(this._blockNode(new T8($,w,W)),Z)this.code(Z).endFunc();return this}endFunc(){return this._endBlockNode(T8)}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 W=this._currNode;if(W instanceof $||w&&W 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 K$))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=K3;function W1($,w){for(let W in w)$[W]=($[W]||0)+(w[W]||0);return $}function N8($,w){return w instanceof l._CodeOrName?W1($,w.names):$}function n1($,w,W){if($ instanceof l.Name)return Z($);if(!X($))return $;return new l._Code($._items.reduce((Y,G)=>{if(G instanceof l.Name)G=Z(G);if(G instanceof l._Code)Y.push(...G._items);else Y.push(G);return Y},[]));function Z(Y){let G=W[Y.str];if(G===void 0||w[Y.str]!==1)return Y;return delete w[Y.str],G}function X(Y){return Y instanceof l._Code&&Y._items.some((G)=>G instanceof l.Name&&w[G.str]===1&&W[G.str]!==void 0)}}function qN($,w){for(let W in w)$[W]=($[W]||0)-(w[W]||0)}function B3($){return typeof $=="boolean"||typeof $=="number"||$===null?!$:l._`!${bW($)}`}k0.not=B3;var UN=P3(k0.operators.AND);function HN(...$){return $.reduce(UN)}k0.and=HN;var FN=P3(k0.operators.OR);function ON(...$){return $.reduce(FN)}k0.or=ON;function P3($){return(w,W)=>w===l.nil?W:W===l.nil?w:l._`${bW(w)} ${$} ${bW(W)}`}function bW($){return $ instanceof l.Name?$:l._`(${$})`}});var c=L((L3)=>{Object.defineProperty(L3,"__esModule",{value:!0});L3.checkStrictMode=L3.getErrorPath=L3.Type=L3.useFunc=L3.setEvaluated=L3.evaluatedPropsToName=L3.mergeEvaluated=L3.eachItem=L3.unescapeJsonPointer=L3.escapeJsonPointer=L3.escapeFragment=L3.unescapeFragment=L3.schemaRefOrVal=L3.schemaHasRulesButRef=L3.schemaHasRules=L3.checkUnknownRules=L3.alwaysValidSchema=L3.toHash=void 0;var r=h(),kN=dw();function AN($){let w={};for(let W of $)w[W]=!0;return w}L3.toHash=AN;function SN($,w){if(typeof w=="boolean")return w;if(Object.keys(w).length===0)return!0;return U3($,w),!H3(w,$.self.RULES.all)}L3.alwaysValidSchema=SN;function U3($,w=$.schema){let{opts:W,self:Z}=$;if(!W.strictSchema)return;if(typeof w==="boolean")return;let X=Z.RULES.keywords;for(let Y in w)if(!X[Y])E3($,`unknown keyword: "${Y}"`)}L3.checkUnknownRules=U3;function H3($,w){if(typeof $=="boolean")return!$;for(let W in $)if(w[W])return!0;return!1}L3.schemaHasRules=H3;function RN($,w){if(typeof $=="boolean")return!$;for(let W in $)if(W!=="$ref"&&w.all[W])return!0;return!1}L3.schemaHasRulesButRef=RN;function CN({topSchemaRef:$,schemaPath:w},W,Z,X){if(!X){if(typeof W=="number"||typeof W=="boolean")return W;if(typeof W=="string")return r._`${W}`}return r._`${$}${w}${(0,r.getProperty)(Z)}`}L3.schemaRefOrVal=CN;function jN($){return F3(decodeURIComponent($))}L3.unescapeFragment=jN;function yN($){return encodeURIComponent(gW($))}L3.escapeFragment=yN;function gW($){if(typeof $=="number")return`${$}`;return $.replace(/~/g,"~0").replace(/\//g,"~1")}L3.escapeJsonPointer=gW;function F3($){return $.replace(/~1/g,"/").replace(/~0/g,"~")}L3.unescapeJsonPointer=F3;function IN($,w){if(Array.isArray($))for(let W of $)w(W);else w($)}L3.eachItem=IN;function f3({mergeNames:$,mergeToName:w,mergeValues:W,resultToName:Z}){return(X,Y,G,J)=>{let T=G===void 0?Y:G instanceof r.Name?(Y instanceof r.Name?$(X,Y,G):w(X,Y,G),G):Y instanceof r.Name?(w(X,G,Y),Y):W(Y,G);return J===r.Name&&!(T instanceof r.Name)?Z(X,T):T}}L3.mergeEvaluated={props:f3({mergeNames:($,w,W)=>$.if(r._`${W} !== true && ${w} !== undefined`,()=>{$.if(r._`${w} === true`,()=>$.assign(W,!0),()=>$.assign(W,r._`${W} || {}`).code(r._`Object.assign(${W}, ${w})`))}),mergeToName:($,w,W)=>$.if(r._`${W} !== true`,()=>{if(w===!0)$.assign(W,!0);else $.assign(W,r._`${W} || {}`),vW($,W,w)}),mergeValues:($,w)=>$===!0?!0:{...$,...w},resultToName:O3}),items:f3({mergeNames:($,w,W)=>$.if(r._`${W} !== true && ${w} !== undefined`,()=>$.assign(W,r._`${w} === true ? true : ${W} > ${w} ? ${W} : ${w}`)),mergeToName:($,w,W)=>$.if(r._`${W} !== true`,()=>$.assign(W,w===!0?!0:r._`${W} > ${w} ? ${W} : ${w}`)),mergeValues:($,w)=>$===!0?!0:Math.max($,w),resultToName:($,w)=>$.var("items",w)})};function O3($,w){if(w===!0)return $.var("props",!0);let W=$.var("props",r._`{}`);if(w!==void 0)vW($,W,w);return W}L3.evaluatedPropsToName=O3;function vW($,w,W){Object.keys(W).forEach((Z)=>$.assign(r._`${w}${(0,r.getProperty)(Z)}`,!0))}L3.setEvaluated=vW;var q3={};function bN($,w){return $.scopeValue("func",{ref:w,code:q3[w.code]||(q3[w.code]=new kN._Code(w.code))})}L3.useFunc=bN;var _W;(function($){$[$.Num=0]="Num",$[$.Str=1]="Str"})(_W||(L3.Type=_W={}));function xN($,w,W){if($ instanceof r.Name){let Z=w===_W.Num;return W?Z?r._`"[" + ${$} + "]"`:r._`"['" + ${$} + "']"`:Z?r._`"/" + ${$}`:r._`"/" + ${$}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return W?(0,r.getProperty)($).toString():"/"+gW($)}L3.getErrorPath=xN;function E3($,w,W=$.opts.strictSchema){if(!W)return;if(w=`strict mode: ${w}`,W===!0)throw Error(w);$.self.logger.warn(w)}L3.checkStrictMode=E3});var B$=L((k3)=>{Object.defineProperty(k3,"__esModule",{value:!0});var P0=h(),eN={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")};k3.default=eN});var pw=L((C3)=>{Object.defineProperty(C3,"__esModule",{value:!0});C3.extendErrors=C3.resetErrorsCount=C3.reportExtraError=C3.reportError=C3.keyword$DataError=C3.keywordError=void 0;var d=h(),V8=c(),O0=B$();C3.keywordError={message:({keyword:$})=>d.str`must pass "${$}" keyword validation`};C3.keyword$DataError={message:({keyword:$,schemaType:w})=>w?d.str`"${$}" keyword must be ${w} ($data)`:d.str`"${$}" keyword is invalid ($data)`};function wK($,w=C3.keywordError,W,Z){let{it:X}=$,{gen:Y,compositeRule:G,allErrors:J}=X,T=R3($,w,W);if(Z!==null&&Z!==void 0?Z:G||J)A3(Y,T);else S3(X,d._`[${T}]`)}C3.reportError=wK;function WK($,w=C3.keywordError,W){let{it:Z}=$,{gen:X,compositeRule:Y,allErrors:G}=Z,J=R3($,w,W);if(A3(X,J),!(Y||G))S3(Z,O0.default.vErrors)}C3.reportExtraError=WK;function ZK($,w){$.assign(O0.default.errors,w),$.if(d._`${O0.default.vErrors} !== null`,()=>$.if(w,()=>$.assign(d._`${O0.default.vErrors}.length`,w),()=>$.assign(O0.default.vErrors,null)))}C3.resetErrorsCount=ZK;function XK({gen:$,keyword:w,schemaValue:W,data:Z,errsCount:X,it:Y}){if(X===void 0)throw Error("ajv implementation error");let G=$.name("err");$.forRange("i",X,O0.default.errors,(J)=>{if($.const(G,d._`${O0.default.vErrors}[${J}]`),$.if(d._`${G}.instancePath === undefined`,()=>$.assign(d._`${G}.instancePath`,(0,d.strConcat)(O0.default.instancePath,Y.errorPath))),$.assign(d._`${G}.schemaPath`,d.str`${Y.errSchemaPath}/${w}`),Y.opts.verbose)$.assign(d._`${G}.schema`,W),$.assign(d._`${G}.data`,Z)})}C3.extendErrors=XK;function A3($,w){let W=$.const("err",w);$.if(d._`${O0.default.vErrors} === null`,()=>$.assign(O0.default.vErrors,d._`[${W}]`),d._`${O0.default.vErrors}.push(${W})`),$.code(d._`${O0.default.errors}++`)}function S3($,w){let{gen:W,validateName:Z,schemaEnv:X}=$;if(X.$async)W.throw(d._`new ${$.ValidationError}(${w})`);else W.assign(d._`${Z}.errors`,w),W.return(!1)}var Z1={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 R3($,w,W){let{createErrors:Z}=$.it;if(Z===!1)return d._`{}`;return YK($,w,W)}function YK($,w,W={}){let{gen:Z,it:X}=$,Y=[GK(X,W),JK($,W)];return TK($,w,Y),Z.object(...Y)}function GK({errorPath:$},{instancePath:w}){let W=w?d.str`${$}${(0,V8.getErrorPath)(w,V8.Type.Str)}`:$;return[O0.default.instancePath,(0,d.strConcat)(O0.default.instancePath,W)]}function JK({keyword:$,it:{errSchemaPath:w}},{schemaPath:W,parentSchema:Z}){let X=Z?w:d.str`${w}/${$}`;if(W)X=d.str`${X}${(0,V8.getErrorPath)(W,V8.Type.Str)}`;return[Z1.schemaPath,X]}function TK($,{params:w,message:W},Z){let{keyword:X,data:Y,schemaValue:G,it:J}=$,{opts:T,propertyName:Q,topSchemaRef:M,schemaPath:z}=J;if(Z.push([Z1.keyword,X],[Z1.params,typeof w=="function"?w($):w||d._`{}`]),T.messages)Z.push([Z1.message,typeof W=="function"?W($):W]);if(T.verbose)Z.push([Z1.schema,G],[Z1.parentSchema,d._`${M}${z}`],[O0.default.data,Y]);if(Q)Z.push([Z1.propertyName,Q])}});var x3=L((I3)=>{Object.defineProperty(I3,"__esModule",{value:!0});I3.boolOrEmptySchema=I3.topBoolOrEmptySchema=void 0;var KK=pw(),BK=h(),PK=B$(),VK={message:"boolean schema is false"};function fK($){let{gen:w,schema:W,validateName:Z}=$;if(W===!1)y3($,!1);else if(typeof W=="object"&&W.$async===!0)w.return(PK.default.data);else w.assign(BK._`${Z}.errors`,null),w.return(!0)}I3.topBoolOrEmptySchema=fK;function qK($,w){let{gen:W,schema:Z}=$;if(Z===!1)W.var(w,!1),y3($);else W.var(w,!0)}I3.boolOrEmptySchema=qK;function y3($,w){let{gen:W,data:Z}=$,X={gen:W,keyword:"false schema",data:Z,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:$};(0,KK.reportError)(X,VK,void 0,w)}});var hW=L((_3)=>{Object.defineProperty(_3,"__esModule",{value:!0});_3.getRules=_3.isJSONType=void 0;var HK=["string","number","integer","boolean","null","object","array"],FK=new Set(HK);function OK($){return typeof $=="string"&&FK.has($)}_3.isJSONType=OK;function EK(){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:{}}}_3.getRules=EK});var iW=L((h3)=>{Object.defineProperty(h3,"__esModule",{value:!0});h3.shouldUseRule=h3.shouldUseGroup=h3.schemaHasRulesForType=void 0;function DK({schema:$,self:w},W){let Z=w.RULES.types[W];return Z&&Z!==!0&&v3($,Z)}h3.schemaHasRulesForType=DK;function v3($,w){return w.rules.some((W)=>u3($,W))}h3.shouldUseGroup=v3;function u3($,w){var W;return $[w.keyword]!==void 0||((W=w.definition.implements)===null||W===void 0?void 0:W.some((Z)=>$[Z]!==void 0))}h3.shouldUseRule=u3});var tw=L((d3)=>{Object.defineProperty(d3,"__esModule",{value:!0});d3.reportTypeError=d3.checkDataTypes=d3.checkDataType=d3.coerceAndCheckDataType=d3.getJSONTypes=d3.getSchemaTypes=d3.DataType=void 0;var SK=hW(),RK=iW(),CK=pw(),v=h(),m3=c(),p1;(function($){$[$.Correct=0]="Correct",$[$.Wrong=1]="Wrong"})(p1||(d3.DataType=p1={}));function jK($){let w=l3($.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}d3.getSchemaTypes=jK;function l3($){let w=Array.isArray($)?$:$?[$]:[];if(w.every(SK.isJSONType))return w;throw Error("type must be JSONType or JSONType[]: "+w.join(","))}d3.getJSONTypes=l3;function yK($,w){let{gen:W,data:Z,opts:X}=$,Y=IK(w,X.coerceTypes),G=w.length>0&&!(Y.length===0&&w.length===1&&(0,RK.schemaHasRulesForType)($,w[0]));if(G){let J=lW(w,Z,X.strictNumbers,p1.Wrong);W.if(J,()=>{if(Y.length)bK($,w,Y);else cW($)})}return G}d3.coerceAndCheckDataType=yK;var c3=new Set(["string","number","integer","boolean","null"]);function IK($,w){return w?$.filter((W)=>c3.has(W)||w==="array"&&W==="array"):[]}function bK($,w,W){let{gen:Z,data:X,opts:Y}=$,G=Z.let("dataType",v._`typeof ${X}`),J=Z.let("coerced",v._`undefined`);if(Y.coerceTypes==="array")Z.if(v._`${G} == 'object' && Array.isArray(${X}) && ${X}.length == 1`,()=>Z.assign(X,v._`${X}[0]`).assign(G,v._`typeof ${X}`).if(lW(w,X,Y.strictNumbers),()=>Z.assign(J,X)));Z.if(v._`${J} !== undefined`);for(let Q of W)if(c3.has(Q)||Q==="array"&&Y.coerceTypes==="array")T(Q);Z.else(),cW($),Z.endIf(),Z.if(v._`${J} !== undefined`,()=>{Z.assign(X,J),xK($,J)});function T(Q){switch(Q){case"string":Z.elseIf(v._`${G} == "number" || ${G} == "boolean"`).assign(J,v._`"" + ${X}`).elseIf(v._`${X} === null`).assign(J,v._`""`);return;case"number":Z.elseIf(v._`${G} == "boolean" || ${X} === null
30
30
  || (${G} == "string" && ${X} && ${X} == +${X})`).assign(J,v._`+${X}`);return;case"integer":Z.elseIf(v._`${G} === "boolean" || ${X} === null
31
31
  || (${G} === "string" && ${X} && ${X} == +${X} && !(${X} % 1))`).assign(J,v._`+${X}`);return;case"boolean":Z.elseIf(v._`${X} === "false" || ${X} === 0 || ${X} === null`).assign(J,!1).elseIf(v._`${X} === "true" || ${X} === 1`).assign(J,!0);return;case"null":Z.elseIf(v._`${X} === "" || ${X} === 0 || ${X} === false`),Z.assign(J,null);return;case"array":Z.elseIf(v._`${G} === "string" || ${G} === "number"
32
- || ${G} === "boolean" || ${X} === null`).assign(J,v._`[${X}]`)}}}function xK({gen:$,parentData:w,parentDataProperty:W},Z){$.if(v._`${w} !== undefined`,()=>$.assign(v._`${w}[${W}]`,Z))}function iW($,w,W,Z=p1.Correct){let X=Z===p1.Correct?v.operators.EQ:v.operators.NEQ,Y;switch($){case"null":return v._`${w} ${X} null`;case"array":Y=v._`Array.isArray(${w})`;break;case"object":Y=v._`${w} && typeof ${w} == "object" && !Array.isArray(${w})`;break;case"integer":Y=G(v._`!(${w} % 1) && !isNaN(${w})`);break;case"number":Y=G();break;default:return v._`typeof ${w} ${X} ${$}`}return Z===p1.Correct?Y:(0,v.not)(Y);function G(J=v.nil){return(0,v.and)(v._`typeof ${w} == "number"`,J,W?v._`isFinite(${w})`:v.nil)}}cX.checkDataType=iW;function mW($,w,W,Z){if($.length===1)return iW($[0],w,W,Z);let X,Y=(0,iX.toHash)($);if(Y.array&&Y.object){let G=v._`typeof ${w} != "object"`;X=Y.null?G:v._`!${w} || ${G}`,delete Y.null,delete Y.array,delete Y.object}else X=v.nil;if(Y.number)delete Y.integer;for(let G in Y)X=(0,v.and)(X,iW(G,w,W,Z));return X}cX.checkDataTypes=mW;var _K={message:({schema:$})=>`must be ${$}`,params:({schema:$,schemaValue:w})=>typeof $=="string"?v._`{type: ${$}}`:v._`{type: ${w}}`};function lW($){let w=gK($);(0,CK.reportError)(w,_K)}cX.reportTypeError=lW;function gK($){let{gen:w,data:W,schema:Z}=$,X=(0,iX.schemaRefOrVal)($,Z,"type");return{gen:w,keyword:"type",data:W,schema:Z.type,schemaCode:X,schemaValue:X,parentSchema:Z,params:{},it:$}}});var rX=L((pX)=>{Object.defineProperty(pX,"__esModule",{value:!0});pX.assignDefaults=void 0;var t1=u(),cK=c();function dK($,w){let{properties:W,items:Z}=$.schema;if(w==="object"&&W)for(let X in W)nX($,X,W[X].default);else if(w==="array"&&Array.isArray(Z))Z.forEach((X,Y)=>nX($,Y,X.default))}pX.assignDefaults=dK;function nX($,w,W){let{gen:Z,compositeRule:X,data:Y,opts:G}=$;if(W===void 0)return;let J=t1._`${Y}${(0,t1.getProperty)(w)}`;if(X){(0,cK.checkStrictMode)($,`default is ignored for: ${J}`);return}let T=t1._`${J} === undefined`;if(G.useDefaults==="empty")T=t1._`${T} || ${J} === null || ${J} === ""`;Z.if(T,t1._`${J} = ${(0,t1.stringify)(W)}`)}});var u0=L((oX)=>{Object.defineProperty(oX,"__esModule",{value:!0});oX.validateUnion=oX.validateArray=oX.usePattern=oX.callValidateCode=oX.schemaProperties=oX.allSchemaProperties=oX.noPropertyInData=oX.propertyInData=oX.isOwnProperty=oX.hasPropFunc=oX.reportMissingProp=oX.checkMissingProp=oX.checkReportMissingProp=void 0;var a=u(),cW=c(),_$=B$(),nK=c();function pK($,w){let{gen:W,data:Z,it:X}=$;W.if(nW(W,Z,w,X.opts.ownProperties),()=>{$.setParams({missingProperty:a._`${w}`},!0),$.error()})}oX.checkReportMissingProp=pK;function tK({gen:$,data:w,it:{opts:W}},Z,X){return(0,a.or)(...Z.map((Y)=>(0,a.and)(nW($,w,Y,W.ownProperties),a._`${X} = ${Y}`)))}oX.checkMissingProp=tK;function rK($,w){$.setParams({missingProperty:w},!0),$.error()}oX.reportMissingProp=rK;function sX($){return $.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:a._`Object.prototype.hasOwnProperty`})}oX.hasPropFunc=sX;function dW($,w,W){return a._`${sX($)}.call(${w}, ${W})`}oX.isOwnProperty=dW;function sK($,w,W,Z){let X=a._`${w}${(0,a.getProperty)(W)} !== undefined`;return Z?a._`${X} && ${dW($,w,W)}`:X}oX.propertyInData=sK;function nW($,w,W,Z){let X=a._`${w}${(0,a.getProperty)(W)} === undefined`;return Z?(0,a.or)(X,(0,a.not)(dW($,w,W))):X}oX.noPropertyInData=nW;function aX($){return $?Object.keys($).filter((w)=>w!=="__proto__"):[]}oX.allSchemaProperties=aX;function aK($,w){return aX(w).filter((W)=>!(0,cW.alwaysValidSchema)($,w[W]))}oX.schemaProperties=aK;function oK({schemaCode:$,data:w,it:{gen:W,topSchemaRef:Z,schemaPath:X,errorPath:Y},it:G},J,T,Q){let M=Q?a._`${$}, ${w}, ${Z}${X}`:w,z=[[_$.default.instancePath,(0,a.strConcat)(_$.default.instancePath,Y)],[_$.default.parentData,G.parentData],[_$.default.parentDataProperty,G.parentDataProperty],[_$.default.rootData,_$.default.rootData]];if(G.opts.dynamicRef)z.push([_$.default.dynamicAnchors,_$.default.dynamicAnchors]);let N=a._`${M}, ${W.object(...z)}`;return T!==a.nil?a._`${J}.call(${T}, ${N})`:a._`${J}(${N})`}oX.callValidateCode=oK;var eK=a._`new RegExp`;function $B({gen:$,it:{opts:w}},W){let Z=w.unicodeRegExp?"u":"",{regExp:X}=w.code,Y=X(W,Z);return $.scopeValue("pattern",{key:Y.toString(),ref:Y,code:a._`${X.code==="new RegExp"?eK:(0,nK.useFunc)($,X)}(${W}, ${Z})`})}oX.usePattern=$B;function wB($){let{gen:w,data:W,keyword:Z,it:X}=$,Y=w.name("valid");if(X.allErrors){let J=w.let("valid",!0);return G(()=>w.assign(J,!1)),J}return w.var(Y,!0),G(()=>w.break()),Y;function G(J){let T=w.const("len",a._`${W}.length`);w.forRange("i",0,T,(Q)=>{$.subschema({keyword:Z,dataProp:Q,dataPropType:cW.Type.Num},Y),w.if((0,a.not)(Y),J)})}}oX.validateArray=wB;function WB($){let{gen:w,schema:W,keyword:Z,it:X}=$;if(!Array.isArray(W))throw Error("ajv implementation error");if(W.some((T)=>(0,cW.alwaysValidSchema)(X,T))&&!X.opts.unevaluated)return;let G=w.let("valid",!1),J=w.name("_valid");w.block(()=>W.forEach((T,Q)=>{let M=$.subschema({keyword:Z,schemaProp:Q,compositeRule:!0},J);if(w.assign(G,a._`${G} || ${J}`),!$.mergeValidEvaluated(M,J))w.if((0,a.not)(G))})),$.result(G,()=>$.reset(),()=>$.error(!0))}oX.validateUnion=WB});var XY=L((WY)=>{Object.defineProperty(WY,"__esModule",{value:!0});WY.validateKeywordUsage=WY.validSchemaType=WY.funcKeywordCode=WY.macroKeywordCode=void 0;var E0=u(),X1=B$(),PB=u0(),VB=pw();function fB($,w){let{gen:W,keyword:Z,schema:X,parentSchema:Y,it:G}=$,J=w.macro.call(G.self,X,Y,G),T=wY(W,Z,J);if(G.opts.validateSchema!==!1)G.self.validateSchema(J,!0);let Q=W.name("valid");$.subschema({schema:J,schemaPath:E0.nil,errSchemaPath:`${G.errSchemaPath}/${Z}`,topSchemaRef:T,compositeRule:!0},Q),$.pass(Q,()=>$.error(!0))}WY.macroKeywordCode=fB;function qB($,w){var W;let{gen:Z,keyword:X,schema:Y,parentSchema:G,$data:J,it:T}=$;HB(T,w);let Q=!J&&w.compile?w.compile.call(T.self,Y,G,T):w.validate,M=wY(Z,X,Q),z=Z.let("valid");$.block$data(z,N),$.ok((W=w.valid)!==null&&W!==void 0?W:z);function N(){if(w.errors===!1){if(P(),w.modifying)$Y($);q(()=>$.error())}else{let f=w.async?B():K();if(w.modifying)$Y($);q(()=>UB($,f))}}function B(){let f=Z.let("ruleErrs",null);return Z.try(()=>P(E0._`await `),(H)=>Z.assign(z,!1).if(E0._`${H} instanceof ${T.ValidationError}`,()=>Z.assign(f,E0._`${H}.errors`),()=>Z.throw(H))),f}function K(){let f=E0._`${M}.errors`;return Z.assign(f,null),P(E0.nil),f}function P(f=w.async?E0._`await `:E0.nil){let H=T.opts.passContext?X1.default.this:X1.default.self,E=!(("compile"in w)&&!J||w.schema===!1);Z.assign(z,E0._`${f}${(0,PB.callValidateCode)($,M,H,E)}`,w.modifying)}function q(f){var H;Z.if((0,E0.not)((H=w.valid)!==null&&H!==void 0?H:z),f)}}WY.funcKeywordCode=qB;function $Y($){let{gen:w,data:W,it:Z}=$;w.if(Z.parentData,()=>w.assign(W,E0._`${Z.parentData}[${Z.parentDataProperty}]`))}function UB($,w){let{gen:W}=$;W.if(E0._`Array.isArray(${w})`,()=>{W.assign(X1.default.vErrors,E0._`${X1.default.vErrors} === null ? ${w} : ${X1.default.vErrors}.concat(${w})`).assign(X1.default.errors,E0._`${X1.default.vErrors}.length`),(0,VB.extendErrors)($)},()=>$.error())}function HB({schemaEnv:$},w){if(w.async&&!$.$async)throw Error("async keyword in sync schema")}function wY($,w,W){if(W===void 0)throw Error(`keyword "${w}" failed to compile`);return $.scopeValue("keyword",typeof W=="function"?{ref:W}:{ref:W,code:(0,E0.stringify)(W)})}function FB($,w,W=!1){return!w.length||w.some((Z)=>Z==="array"?Array.isArray($):Z==="object"?$&&typeof $=="object"&&!Array.isArray($):typeof $==Z||W&&typeof $>"u")}WY.validSchemaType=FB;function OB({schema:$,opts:w,self:W,errSchemaPath:Z},X,Y){if(Array.isArray(X.keyword)?!X.keyword.includes(Y):X.keyword!==Y)throw Error("ajv implementation error");let G=X.dependencies;if(G===null||G===void 0?void 0:G.some((J)=>!Object.prototype.hasOwnProperty.call($,J)))throw Error(`parent schema must have dependencies of ${Y}: ${G.join(",")}`);if(X.validateSchema){if(!X.validateSchema($[Y])){let T=`keyword "${Y}" value is invalid at path "${Z}": `+W.errorsText(X.validateSchema.errors);if(w.validateSchema==="log")W.logger.error(T);else throw Error(T)}}}WY.validateKeywordUsage=OB});var TY=L((GY)=>{Object.defineProperty(GY,"__esModule",{value:!0});GY.extendSubschemaMode=GY.extendSubschemaData=GY.getSubschema=void 0;var w$=u(),YY=c();function kB($,{keyword:w,schemaProp:W,schema:Z,schemaPath:X,errSchemaPath:Y,topSchemaRef:G}){if(w!==void 0&&Z!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(w!==void 0){let J=$.schema[w];return W===void 0?{schema:J,schemaPath:w$._`${$.schemaPath}${(0,w$.getProperty)(w)}`,errSchemaPath:`${$.errSchemaPath}/${w}`}:{schema:J[W],schemaPath:w$._`${$.schemaPath}${(0,w$.getProperty)(w)}${(0,w$.getProperty)(W)}`,errSchemaPath:`${$.errSchemaPath}/${w}/${(0,YY.escapeFragment)(W)}`}}if(Z!==void 0){if(X===void 0||Y===void 0||G===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:Z,schemaPath:X,topSchemaRef:G,errSchemaPath:Y}}throw Error('either "keyword" or "schema" must be passed')}GY.getSubschema=kB;function AB($,w,{dataProp:W,dataPropType:Z,data:X,dataTypes:Y,propertyName:G}){if(X!==void 0&&W!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:J}=w;if(W!==void 0){let{errorPath:Q,dataPathArr:M,opts:z}=w,N=J.let("data",w$._`${w.data}${(0,w$.getProperty)(W)}`,!0);T(N),$.errorPath=w$.str`${Q}${(0,YY.getErrorPath)(W,Z,z.jsPropertySyntax)}`,$.parentDataProperty=w$._`${W}`,$.dataPathArr=[...M,$.parentDataProperty]}if(X!==void 0){let Q=X instanceof w$.Name?X:J.let("data",X,!0);if(T(Q),G!==void 0)$.propertyName=G}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]}}GY.extendSubschemaData=AB;function SB($,{jtdDiscriminator:w,jtdMetadata:W,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=W}GY.extendSubschemaMode=SB});var pW=L(($k,QY)=>{QY.exports=function $(w,W){if(w===W)return!0;if(w&&W&&typeof w=="object"&&typeof W=="object"){if(w.constructor!==W.constructor)return!1;var Z,X,Y;if(Array.isArray(w)){if(Z=w.length,Z!=W.length)return!1;for(X=Z;X--!==0;)if(!$(w[X],W[X]))return!1;return!0}if(w.constructor===RegExp)return w.source===W.source&&w.flags===W.flags;if(w.valueOf!==Object.prototype.valueOf)return w.valueOf()===W.valueOf();if(w.toString!==Object.prototype.toString)return w.toString()===W.toString();if(Y=Object.keys(w),Z=Y.length,Z!==Object.keys(W).length)return!1;for(X=Z;X--!==0;)if(!Object.prototype.hasOwnProperty.call(W,Y[X]))return!1;for(X=Z;X--!==0;){var G=Y[X];if(!$(w[G],W[G]))return!1}return!0}return w!==w&&W!==W}});var zY=L((wk,MY)=>{var g$=MY.exports=function($,w,W){if(typeof w=="function")W=w,w={};W=w.cb||W;var Z=typeof W=="function"?W:W.pre||function(){},X=W.post||function(){};V8(w,Z,X,$,"",$)};g$.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};g$.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};g$.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};g$.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 V8($,w,W,Z,X,Y,G,J,T,Q){if(Z&&typeof Z=="object"&&!Array.isArray(Z)){w(Z,X,Y,G,J,T,Q);for(var M in Z){var z=Z[M];if(Array.isArray(z)){if(M in g$.arrayKeywords)for(var N=0;N<z.length;N++)V8($,w,W,z[N],X+"/"+M+"/"+N,Y,X,M,Z,N)}else if(M in g$.propsKeywords){if(z&&typeof z=="object")for(var B in z)V8($,w,W,z[B],X+"/"+M+"/"+jB(B),Y,X,M,Z,B)}else if(M in g$.keywords||$.allKeys&&!(M in g$.skipKeywords))V8($,w,W,z,X+"/"+M,Y,X,M,Z)}W(Z,X,Y,G,J,T,Q)}}function jB($){return $.replace(/~/g,"~0").replace(/\//g,"~1")}});var rw=L((PY)=>{Object.defineProperty(PY,"__esModule",{value:!0});PY.getSchemaRefs=PY.resolveUrl=PY.normalizeId=PY._getFullPath=PY.getFullPath=PY.inlineRef=void 0;var yB=c(),IB=pW(),bB=zY(),xB=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function _B($,w=!0){if(typeof $=="boolean")return!0;if(w===!0)return!tW($);if(!w)return!1;return NY($)<=w}PY.inlineRef=_B;var gB=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function tW($){for(let w in $){if(gB.has(w))return!0;let W=$[w];if(Array.isArray(W)&&W.some(tW))return!0;if(typeof W=="object"&&tW(W))return!0}return!1}function NY($){let w=0;for(let W in $){if(W==="$ref")return 1/0;if(w++,xB.has(W))continue;if(typeof $[W]=="object")(0,yB.eachItem)($[W],(Z)=>w+=NY(Z));if(w===1/0)return 1/0}return w}function KY($,w="",W){if(W!==!1)w=r1(w);let Z=$.parse(w);return BY($,Z)}PY.getFullPath=KY;function BY($,w){return $.serialize(w).split("#")[0]+"#"}PY._getFullPath=BY;var vB=/#\/?$/;function r1($){return $?$.replace(vB,""):""}PY.normalizeId=r1;function hB($,w,W){return W=r1(W),$.resolve(w,W)}PY.resolveUrl=hB;var uB=/^[a-z_][-a-z0-9._]*$/i;function iB($,w){if(typeof $=="boolean")return{};let{schemaId:W,uriResolver:Z}=this.opts,X=r1($[W]||w),Y={"":X},G=KY(Z,X,!1),J={},T=new Set;return bB($,{allKeys:!0},(z,N,B,K)=>{if(K===void 0)return;let P=G+N,q=Y[K];if(typeof z[W]=="string")q=f.call(this,z[W]);H.call(this,z.$anchor),H.call(this,z.$dynamicAnchor),Y[N]=q;function f(E){let S=this.opts.uriResolver.resolve;if(E=r1(q?S(q,E):E),T.has(E))throw M(E);T.add(E);let A=this.refs[E];if(typeof A=="string")A=this.refs[A];if(typeof A=="object")Q(z,A.schema,E);else if(E!==r1(P))if(E[0]==="#")Q(z,J[E],E),J[E]=z;else this.refs[E]=P;return E}function H(E){if(typeof E=="string"){if(!uB.test(E))throw Error(`invalid anchor "${E}"`);f.call(this,`#${E}`)}}}),J;function Q(z,N,B){if(N!==void 0&&!IB(z,N))throw M(B)}function M(z){return Error(`reference "${z}" resolves to more than one schema`)}}PY.getSchemaRefs=iB});var ow=L((jY)=>{Object.defineProperty(jY,"__esModule",{value:!0});jY.getData=jY.KeywordCxt=jY.validateFunctionCode=void 0;var FY=bX(),fY=tw(),sW=uW(),f8=tw(),pB=rX(),aw=XY(),rW=TY(),R=u(),x=B$(),tB=rw(),P$=c(),sw=pw();function rB($){if(LY($)){if(DY($),EY($)){oB($);return}}OY($,()=>(0,FY.topBoolOrEmptySchema)($))}jY.validateFunctionCode=rB;function OY({gen:$,validateName:w,schema:W,schemaEnv:Z,opts:X},Y){if(X.code.es5)$.func(w,R._`${x.default.data}, ${x.default.valCxt}`,Z.$async,()=>{$.code(R._`"use strict"; ${qY(W,X)}`),aB($,X),$.code(Y)});else $.func(w,R._`${x.default.data}, ${sB(X)}`,Z.$async,()=>$.code(qY(W,X)).code(Y))}function sB($){return R._`{${x.default.instancePath}="", ${x.default.parentData}, ${x.default.parentDataProperty}, ${x.default.rootData}=${x.default.data}${$.dynamicRef?R._`, ${x.default.dynamicAnchors}={}`:R.nil}}={}`}function aB($,w){$.if(x.default.valCxt,()=>{if($.var(x.default.instancePath,R._`${x.default.valCxt}.${x.default.instancePath}`),$.var(x.default.parentData,R._`${x.default.valCxt}.${x.default.parentData}`),$.var(x.default.parentDataProperty,R._`${x.default.valCxt}.${x.default.parentDataProperty}`),$.var(x.default.rootData,R._`${x.default.valCxt}.${x.default.rootData}`),w.dynamicRef)$.var(x.default.dynamicAnchors,R._`${x.default.valCxt}.${x.default.dynamicAnchors}`)},()=>{if($.var(x.default.instancePath,R._`""`),$.var(x.default.parentData,R._`undefined`),$.var(x.default.parentDataProperty,R._`undefined`),$.var(x.default.rootData,x.default.data),w.dynamicRef)$.var(x.default.dynamicAnchors,R._`{}`)})}function oB($){let{schema:w,opts:W,gen:Z}=$;OY($,()=>{if(W.$comment&&w.$comment)AY($);if(ZP($),Z.let(x.default.vErrors,null),Z.let(x.default.errors,0),W.unevaluated)eB($);kY($),GP($)});return}function eB($){let{gen:w,validateName:W}=$;$.evaluated=w.const("evaluated",R._`${W}.evaluated`),w.if(R._`${$.evaluated}.dynamicProps`,()=>w.assign(R._`${$.evaluated}.props`,R._`undefined`)),w.if(R._`${$.evaluated}.dynamicItems`,()=>w.assign(R._`${$.evaluated}.items`,R._`undefined`))}function qY($,w){let W=typeof $=="object"&&$[w.schemaId];return W&&(w.code.source||w.code.process)?R._`/*# sourceURL=${W} */`:R.nil}function $P($,w){if(LY($)){if(DY($),EY($)){wP($,w);return}}(0,FY.boolOrEmptySchema)($,w)}function EY({schema:$,self:w}){if(typeof $=="boolean")return!$;for(let W in $)if(w.RULES.all[W])return!0;return!1}function LY($){return typeof $.schema!="boolean"}function wP($,w){let{schema:W,gen:Z,opts:X}=$;if(X.$comment&&W.$comment)AY($);XP($),YP($);let Y=Z.const("_errs",x.default.errors);kY($,Y),Z.var(w,R._`${Y} === ${x.default.errors}`)}function DY($){(0,P$.checkUnknownRules)($),WP($)}function kY($,w){if($.opts.jtd)return UY($,[],!1,w);let W=(0,fY.getSchemaTypes)($.schema),Z=(0,fY.coerceAndCheckDataType)($,W);UY($,W,!Z,w)}function WP($){let{schema:w,errSchemaPath:W,opts:Z,self:X}=$;if(w.$ref&&Z.ignoreKeywordsWithRef&&(0,P$.schemaHasRulesButRef)(w,X.RULES))X.logger.warn(`$ref: keywords ignored in schema at path "${W}"`)}function ZP($){let{schema:w,opts:W}=$;if(w.default!==void 0&&W.useDefaults&&W.strictSchema)(0,P$.checkStrictMode)($,"default is ignored in the schema root")}function XP($){let w=$.schema[$.opts.schemaId];if(w)$.baseId=(0,tB.resolveUrl)($.opts.uriResolver,$.baseId,w)}function YP($){if($.schema.$async&&!$.schemaEnv.$async)throw Error("async schema in sync schema")}function AY({gen:$,schemaEnv:w,schema:W,errSchemaPath:Z,opts:X}){let Y=W.$comment;if(X.$comment===!0)$.code(R._`${x.default.self}.logger.log(${Y})`);else if(typeof X.$comment=="function"){let G=R.str`${Z}/$comment`,J=$.scopeValue("root",{ref:w.root});$.code(R._`${x.default.self}.opts.$comment(${Y}, ${G}, ${J}.schema)`)}}function GP($){let{gen:w,schemaEnv:W,validateName:Z,ValidationError:X,opts:Y}=$;if(W.$async)w.if(R._`${x.default.errors} === 0`,()=>w.return(x.default.data),()=>w.throw(R._`new ${X}(${x.default.vErrors})`));else{if(w.assign(R._`${Z}.errors`,x.default.vErrors),Y.unevaluated)JP($);w.return(R._`${x.default.errors} === 0`)}}function JP({gen:$,evaluated:w,props:W,items:Z}){if(W instanceof R.Name)$.assign(R._`${w}.props`,W);if(Z instanceof R.Name)$.assign(R._`${w}.items`,Z)}function UY($,w,W,Z){let{gen:X,schema:Y,data:G,allErrors:J,opts:T,self:Q}=$,{RULES:M}=Q;if(Y.$ref&&(T.ignoreKeywordsWithRef||!(0,P$.schemaHasRulesButRef)(Y,M))){X.block(()=>RY($,"$ref",M.all.$ref.definition));return}if(!T.jtd)TP($,w);X.block(()=>{for(let N of M.rules)z(N);z(M.post)});function z(N){if(!(0,sW.shouldUseGroup)(Y,N))return;if(N.type){if(X.if((0,f8.checkDataType)(N.type,G,T.strictNumbers)),HY($,N),w.length===1&&w[0]===N.type&&W)X.else(),(0,f8.reportTypeError)($);X.endIf()}else HY($,N);if(!J)X.if(R._`${x.default.errors} === ${Z||0}`)}}function HY($,w){let{gen:W,schema:Z,opts:{useDefaults:X}}=$;if(X)(0,pB.assignDefaults)($,w.type);W.block(()=>{for(let Y of w.rules)if((0,sW.shouldUseRule)(Z,Y))RY($,Y.keyword,Y.definition,w.type)})}function TP($,w){if($.schemaEnv.meta||!$.opts.strictTypes)return;if(QP($,w),!$.opts.allowUnionTypes)MP($,w);zP($,$.dataTypes)}function QP($,w){if(!w.length)return;if(!$.dataTypes.length){$.dataTypes=w;return}w.forEach((W)=>{if(!SY($.dataTypes,W))aW($,`type "${W}" not allowed by context "${$.dataTypes.join(",")}"`)}),KP($,w)}function MP($,w){if(w.length>1&&!(w.length===2&&w.includes("null")))aW($,"use allowUnionTypes to allow union type keyword")}function zP($,w){let W=$.self.RULES.all;for(let Z in W){let X=W[Z];if(typeof X=="object"&&(0,sW.shouldUseRule)($.schema,X)){let{type:Y}=X.definition;if(Y.length&&!Y.some((G)=>NP(w,G)))aW($,`missing type "${Y.join(",")}" for keyword "${Z}"`)}}}function NP($,w){return $.includes(w)||w==="number"&&$.includes("integer")}function SY($,w){return $.includes(w)||w==="integer"&&$.includes("number")}function KP($,w){let W=[];for(let Z of $.dataTypes)if(SY(w,Z))W.push(Z);else if(w.includes("integer")&&Z==="number")W.push("integer");$.dataTypes=W}function aW($,w){let W=$.schemaEnv.baseId+$.errSchemaPath;w+=` at "${W}" (strictTypes)`,(0,P$.checkStrictMode)($,w,$.opts.strictTypes)}class oW{constructor($,w,W){if((0,aw.validateKeywordUsage)($,w,W),this.gen=$.gen,this.allErrors=$.allErrors,this.keyword=W,this.data=$.data,this.schema=$.schema[W],this.$data=w.$data&&$.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,P$.schemaRefOrVal)($,this.schema,W,this.$data),this.schemaType=w.schemaType,this.parentSchema=$.schema,this.params={},this.it=$,this.def=w,this.$data)this.schemaCode=$.gen.const("vSchema",CY(this.$data,$));else if(this.schemaCode=this.schemaValue,!(0,aw.validSchemaType)(this.schema,w.schemaType,w.allowUndefined))throw Error(`${W} 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,W){this.failResult((0,R.not)($),w,W)}failResult($,w,W){if(this.gen.if($),W)W();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,R.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(R._`${w} !== undefined && (${(0,R.or)(this.invalid$data(),$)})`)}error($,w,W){if(w){this.setParams(w),this._error($,W),this.setParams({});return}this._error($,W)}_error($,w){($?sw.reportExtraError:sw.reportError)(this,this.def.error,w)}$dataError(){(0,sw.reportError)(this,this.def.$dataError||sw.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,sw.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,W=R.nil){this.gen.block(()=>{this.check$data($,W),w()})}check$data($=R.nil,w=R.nil){if(!this.$data)return;let{gen:W,schemaCode:Z,schemaType:X,def:Y}=this;if(W.if((0,R.or)(R._`${Z} === undefined`,w)),$!==R.nil)W.assign($,!0);if(X.length||Y.validateSchema){if(W.elseIf(this.invalid$data()),this.$dataError(),$!==R.nil)W.assign($,!1)}W.else()}invalid$data(){let{gen:$,schemaCode:w,schemaType:W,def:Z,it:X}=this;return(0,R.or)(Y(),G());function Y(){if(W.length){if(!(w instanceof R.Name))throw Error("ajv implementation error");let J=Array.isArray(W)?W:[W];return R._`${(0,f8.checkDataTypes)(J,w,X.opts.strictNumbers,f8.DataType.Wrong)}`}return R.nil}function G(){if(Z.validateSchema){let J=$.scopeValue("validate$data",{ref:Z.validateSchema});return R._`!${J}(${w})`}return R.nil}}subschema($,w){let W=(0,rW.getSubschema)(this.it,$);(0,rW.extendSubschemaData)(W,this.it,$),(0,rW.extendSubschemaMode)(W,$);let Z={...this.it,...W,items:void 0,props:void 0};return $P(Z,w),Z}mergeEvaluated($,w){let{it:W,gen:Z}=this;if(!W.opts.unevaluated)return;if(W.props!==!0&&$.props!==void 0)W.props=P$.mergeEvaluated.props(Z,$.props,W.props,w);if(W.items!==!0&&$.items!==void 0)W.items=P$.mergeEvaluated.items(Z,$.items,W.items,w)}mergeValidEvaluated($,w){let{it:W,gen:Z}=this;if(W.opts.unevaluated&&(W.props!==!0||W.items!==!0))return Z.if(w,()=>this.mergeEvaluated($,R.Name)),!0}}jY.KeywordCxt=oW;function RY($,w,W,Z){let X=new oW($,W,w);if("code"in W)W.code(X,Z);else if(X.$data&&W.validate)(0,aw.funcKeywordCode)(X,W);else if("macro"in W)(0,aw.macroKeywordCode)(X,W);else if(W.compile||W.validate)(0,aw.funcKeywordCode)(X,W)}var BP=/^\/(?:[^~]|~0|~1)*$/,PP=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function CY($,{dataLevel:w,dataNames:W,dataPathArr:Z}){let X,Y;if($==="")return x.default.rootData;if($[0]==="/"){if(!BP.test($))throw Error(`Invalid JSON-pointer: ${$}`);X=$,Y=x.default.rootData}else{let Q=PP.exec($);if(!Q)throw Error(`Invalid JSON-pointer: ${$}`);let M=+Q[1];if(X=Q[2],X==="#"){if(M>=w)throw Error(T("property/index",M));return Z[w-M]}if(M>w)throw Error(T("data",M));if(Y=W[w-M],!X)return Y}let G=Y,J=X.split("/");for(let Q of J)if(Q)Y=R._`${Y}${(0,R.getProperty)((0,P$.unescapeJsonPointer)(Q))}`,G=R._`${G} && ${Y}`;return G;function T(Q,M){return`Cannot access ${Q} ${M} levels up, current level is ${w}`}}jY.getData=CY});var q8=L((bY)=>{Object.defineProperty(bY,"__esModule",{value:!0});class IY extends Error{constructor($){super("validation failed");this.errors=$,this.ajv=this.validation=!0}}bY.default=IY});var ew=L((_Y)=>{Object.defineProperty(_Y,"__esModule",{value:!0});var eW=rw();class xY extends Error{constructor($,w,W,Z){super(Z||`can't resolve reference ${W} from id ${w}`);this.missingRef=(0,eW.resolveUrl)($,w,W),this.missingSchema=(0,eW.normalizeId)((0,eW.getFullPath)($,this.missingRef))}}_Y.default=xY});var H8=L((hY)=>{Object.defineProperty(hY,"__esModule",{value:!0});hY.resolveSchema=hY.getCompilingSchema=hY.resolveRef=hY.compileSchema=hY.SchemaEnv=void 0;var n0=u(),HP=q8(),Y1=B$(),p0=rw(),gY=c(),FP=ow();class $9{constructor($){var w;this.refs={},this.dynamicAnchors={};let W;if(typeof $.schema=="object")W=$.schema;this.schema=$.schema,this.schemaId=$.schemaId,this.root=$.root||this,this.baseId=(w=$.baseId)!==null&&w!==void 0?w:(0,p0.normalizeId)(W===null||W===void 0?void 0:W[$.schemaId||"$id"]),this.schemaPath=$.schemaPath,this.localRefs=$.localRefs,this.meta=$.meta,this.$async=W===null||W===void 0?void 0:W.$async,this.refs={}}}hY.SchemaEnv=$9;function w5($){let w=vY.call(this,$);if(w)return w;let W=(0,p0.getFullPath)(this.opts.uriResolver,$.root.baseId),{es5:Z,lines:X}=this.opts.code,{ownProperties:Y}=this.opts,G=new n0.CodeGen(this.scope,{es5:Z,lines:X,ownProperties:Y}),J;if($.$async)J=G.scopeValue("Error",{ref:HP.default,code:n0._`require("ajv/dist/runtime/validation_error").default`});let T=G.scopeName("validate");$.validateName=T;let Q={gen:G,allErrors:this.opts.allErrors,data:Y1.default.data,parentData:Y1.default.parentData,parentDataProperty:Y1.default.parentDataProperty,dataNames:[Y1.default.data],dataPathArr:[n0.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:G.scopeValue("schema",this.opts.code.source===!0?{ref:$.schema,code:(0,n0.stringify)($.schema)}:{ref:$.schema}),validateName:T,ValidationError:J,schema:$.schema,schemaEnv:$,rootId:W,baseId:$.baseId||W,schemaPath:n0.nil,errSchemaPath:$.schemaPath||(this.opts.jtd?"":"#"),errorPath:n0._`""`,opts:this.opts,self:this},M;try{this._compilations.add($),(0,FP.validateFunctionCode)(Q),G.optimize(this.opts.code.optimize);let z=G.toString();if(M=`${G.scopeRefs(Y1.default.scope)}return ${z}`,this.opts.code.process)M=this.opts.code.process(M,$);let B=Function(`${Y1.default.self}`,`${Y1.default.scope}`,M)(this,this.scope.get());if(this.scope.value(T,{ref:B}),B.errors=null,B.schema=$.schema,B.schemaEnv=$,$.$async)B.$async=!0;if(this.opts.code.source===!0)B.source={validateName:T,validateCode:z,scopeValues:G._values};if(this.opts.unevaluated){let{props:K,items:P}=Q;if(B.evaluated={props:K instanceof n0.Name?void 0:K,items:P instanceof n0.Name?void 0:P,dynamicProps:K instanceof n0.Name,dynamicItems:P instanceof n0.Name},B.source)B.source.evaluated=(0,n0.stringify)(B.evaluated)}return $.validate=B,$}catch(z){if(delete $.validate,delete $.validateName,M)this.logger.error("Error compiling schema, function code:",M);throw z}finally{this._compilations.delete($)}}hY.compileSchema=w5;function OP($,w,W){var Z;W=(0,p0.resolveUrl)(this.opts.uriResolver,w,W);let X=$.refs[W];if(X)return X;let Y=DP.call(this,$,W);if(Y===void 0){let G=(Z=$.localRefs)===null||Z===void 0?void 0:Z[W],{schemaId:J}=this.opts;if(G)Y=new $9({schema:G,schemaId:J,root:$,baseId:w})}if(Y===void 0)return;return $.refs[W]=EP.call(this,Y)}hY.resolveRef=OP;function EP($){if((0,p0.inlineRef)($.schema,this.opts.inlineRefs))return $.schema;return $.validate?$:w5.call(this,$)}function vY($){for(let w of this._compilations)if(LP(w,$))return w}hY.getCompilingSchema=vY;function LP($,w){return $.schema===w.schema&&$.root===w.root&&$.baseId===w.baseId}function DP($,w){let W;while(typeof(W=this.refs[w])=="string")w=W;return W||this.schemas[w]||U8.call(this,$,w)}function U8($,w){let W=this.opts.uriResolver.parse(w),Z=(0,p0._getFullPath)(this.opts.uriResolver,W),X=(0,p0.getFullPath)(this.opts.uriResolver,$.baseId,void 0);if(Object.keys($.schema).length>0&&Z===X)return $5.call(this,W,$);let Y=(0,p0.normalizeId)(Z),G=this.refs[Y]||this.schemas[Y];if(typeof G=="string"){let J=U8.call(this,$,G);if(typeof(J===null||J===void 0?void 0:J.schema)!=="object")return;return $5.call(this,W,J)}if(typeof(G===null||G===void 0?void 0:G.schema)!=="object")return;if(!G.validate)w5.call(this,G);if(Y===(0,p0.normalizeId)(w)){let{schema:J}=G,{schemaId:T}=this.opts,Q=J[T];if(Q)X=(0,p0.resolveUrl)(this.opts.uriResolver,X,Q);return new $9({schema:J,schemaId:T,root:$,baseId:X})}return $5.call(this,W,G)}hY.resolveSchema=U8;var kP=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function $5($,{baseId:w,schema:W,root:Z}){var X;if(((X=$.fragment)===null||X===void 0?void 0:X[0])!=="/")return;for(let J of $.fragment.slice(1).split("/")){if(typeof W==="boolean")return;let T=W[(0,gY.unescapeFragment)(J)];if(T===void 0)return;W=T;let Q=typeof W==="object"&&W[this.opts.schemaId];if(!kP.has(J)&&Q)w=(0,p0.resolveUrl)(this.opts.uriResolver,w,Q)}let Y;if(typeof W!="boolean"&&W.$ref&&!(0,gY.schemaHasRulesButRef)(W,this.RULES)){let J=(0,p0.resolveUrl)(this.opts.uriResolver,w,W.$ref);Y=U8.call(this,Z,J)}let{schemaId:G}=this.opts;if(Y=Y||new $9({schema:W,schemaId:G,root:Z,baseId:w}),Y.schema!==Y.root.schema)return Y;return}});var iY=L((Jk,jP)=>{jP.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 J5=L((Tk,tY)=>{var yP=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Z5=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),G1=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),X5=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),lY=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),Y5=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),IP=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 V0($){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 bP($){let w="",W=0,Z=0;for(Z=0;Z<$.length;Z++){if(W=$[Z].charCodeAt(0),W===48)continue;if(!(W>=48&&W<=57||W>=65&&W<=70||W>=97&&W<=102))return"";w+=$[Z];break}for(Z+=1;Z<$.length;Z++){if(W=$[Z].charCodeAt(0),!(W>=48&&W<=57||W>=65&&W<=70||W>=97&&W<=102))return"";w+=$[Z]}return w}var xP=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),_P=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),gP=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),vP=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function hP($){if($.length===0)return!1;for(let w=0;w<$.length;w++){if(gP($[w]))continue;if($[w]==="%"&&w+2<$.length&&G1($.slice(w+1,w+3))){w+=2;continue}return!1}return!0}function mY($){let w=-1,W=0,Z=-1,X=0;for(let J=0;J<$.length;J++)if($[J]==="0"){if(Z===-1)Z=J;if(X++,X>W)W=X,w=Z}else Z=-1,X=0;if(W<2)return $.join(":");let Y=$.slice(0,w).join(":"),G=$.slice(w+W).join(":");return Y+"::"+G}function uP($){let w=$.indexOf("::");if(w!==-1&&$.indexOf("::",w+1)!==-1)return;let W=w===-1?$.split(":"):$.slice(0,w).split(":"),Z=w===-1?[]:$.slice(w+2).split(":");if(w!==-1){if(W.length===1&&W[0]==="")W.length=0;if(Z.length===1&&Z[0]==="")Z.length=0}let X=W.concat(Z),Y=0;for(let J=0;J<X.length;J++){let T=X[J];if(T==="")return;if(T.indexOf(".")!==-1){if(J!==X.length-1||w!==-1&&Z.length===0||!Z5(T))return;Y+=2;continue}if(!xP(T))return;X[J]=parseInt(T,16).toString(16),Y++}if(w===-1){if(Y!==8)return;return mY(X)}if(Y>=8)return;let G=X.slice(0,W.length);for(let J=Y;J<8;J++)G.push("0");for(let J=W.length;J<X.length;J++)G.push(X[J]);return mY(G)}function W5($){let w=$[0]==="["&&$[$.length-1]==="]";if(($[0]==="["||$[$.length-1]==="]")&&!w)return{host:$,isIPV6:!1,error:!0};let Z=w?$.slice(1,-1):$;if(w&&_P(Z))return Z=Z.toLowerCase(),{host:`[${Z}]`,escapedHost:Z,isIPV6:!1,isIPVFuture:!0};if(iP(Z,":")<2)return{host:$,isIPV6:!1,error:w};let X="",Y=Z.indexOf("%");if(Y!==-1){let J=Z.slice(Y,Y+3).toLowerCase()==="%25"?3:1;if(X=Z.slice(Y+J),!hP(X))return{host:$,isIPV6:!1,error:!0};Z=Z.slice(0,Y)}let G=uP(Z);if(G===void 0)return{host:$,isIPV6:!1,error:!0};return{host:G+(X?"%"+X:""),escapedHost:G+(X?"%25"+X:""),isIPV6:!0}}function iP($,w){let W=0;for(let Z=0;Z<$.length;Z++)if($[Z]===w)W++;return W}function mP($){let w=$,W=[],Z=-1,X=0;while(X=w.length){if(X===1)if(w===".")break;else if(w==="/"){W.push("/");break}else{W.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]==="/"){W.push("/");break}}}else if(X===3){if(w==="/.."){if(W.length!==0)W.pop();W.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),W.length!==0)W.pop();continue}}}}if((Z=w.indexOf("/",1))===-1){W.push(w);break}else W.push(w.slice(0,Z)),w=w.slice(Z)}return W.join("")}var lP={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},cP=/[@/?#:]/g,dP=/[@/?#]/g;function cY($,w){let W=w?dP:cP;return W.lastIndex=0,$.replace(W,(Z)=>lP[Z])}function dY($,w=!1){if($.indexOf("%")===-1)return $;let W="";for(let Z=0;Z<$.length;Z++){if($[Z]==="%"&&Z+2<$.length){let X=$.slice(Z+1,Z+3);if(G1(X)){let Y=X.toUpperCase(),G=String.fromCharCode(parseInt(Y,16));if(w&&X5(G))W+=G;else W+="%"+Y;Z+=2;continue}}W+=$[Z]}return W}function nP($){let w="";for(let W=0;W<$.length;W++){let Z=$[W];if(Z==="%"&&W+2<$.length){let X=$.slice(W+1,W+3);if(G1(X)){let Y=X.toUpperCase(),G=String.fromCharCode(parseInt(Y,16));if(G!=="."&&X5(G))w+=G;else w+="%"+Y;W+=2;continue}}if(lY(Z))w+=Z;else{let X=$.charCodeAt(W);if(X<128)w+=pY(X)?Z:A0[X];else if(X<55296||X>57343)w+=V0(X);else if(X<=56319&&W+1<$.length){let Y=$.charCodeAt(W+1);if(Y>=56320&&Y<=57343)w+=V0(65536+(X-55296<<10)+(Y-56320)),W++;else w+=V0(65533)}else w+=V0(65533)}}return w}function pP($,w=!1){let W="",Z=w&&$[0]!=="/";for(let X=0;X<$.length;X++){let Y=$[X];if(Y==="%"&&X+2<$.length){let G=$.slice(X+1,X+3);if(G1(G)){W+="%"+G.toUpperCase(),X+=2;continue}}if(Y==="/")Z=!1;if(lY(Y)&&(Y!==":"||!Z))W+=Y;else{let G=$.charCodeAt(X);if(G<128)W+=A0[G];else if(G<55296||G>57343)W+=V0(G);else if(G<=56319&&X+1<$.length){let J=$.charCodeAt(X+1);if(J>=56320&&J<=57343)W+=V0(65536+(G-55296<<10)+(J-56320)),X++;else W+=V0(65533)}else W+=V0(65533)}}return W}function G5($,w){let W="";for(let Z=0;Z<$.length;Z++){let X=$[Z];if(X==="%"&&Z+2<$.length){let Y=$.slice(Z+1,Z+3);if(G1(Y)){W+="%"+Y.toUpperCase(),Z+=2;continue}}if(w(X))W+=X;else{let Y=$.charCodeAt(Z);if(Y<128)W+=A0[Y];else if(Y<55296||Y>57343)W+=V0(Y);else if(Y<=56319&&Z+1<$.length){let G=$.charCodeAt(Z+1);if(G>=56320&&G<=57343)W+=V0(65536+(Y-55296<<10)+(G-56320)),Z++;else W+=V0(65533)}else W+=V0(65533)}}return W}function nY($){return G5($,IP)}function tP($){return G5($,Y5)}function rP($){return G5($,Y5)}function pY($){return $>=48&&$<=57||$>=65&&$<=90||$>=97&&$<=122||$===42||$===43||$===45||$===46||$===47||$===64||$===95}function sP($){let w="";for(let W=0;W<$.length;W++){let Z=$[W];if(Z==="%"&&W+2<$.length){let X=$.slice(W+1,W+3);if(G1(X)){let Y=X.toUpperCase(),G=String.fromCharCode(parseInt(Y,16));if(X5(G))w+=G;else w+="%"+Y;W+=2;continue}}if(Y5(Z))w+=Z;else{let X=$.charCodeAt(W);if(X<128)w+=pY(X)?Z:A0[X];else if(X<55296||X>57343)w+=V0(X);else if(X<=56319&&W+1<$.length){let Y=$.charCodeAt(W+1);if(Y>=56320&&Y<=57343)w+=V0(65536+(X-55296<<10)+(Y-56320)),W++;else w+=V0(65533)}else w+=V0(65533)}}return w}function aP($){let w="";for(let W=0;W<$.length;W++){if($[W]==="%"&&W+2<$.length){let Z=$.slice(W+1,W+3);if(G1(Z)){w+="%"+Z.toUpperCase(),W+=2;continue}}w+=escape($[W])}return w}function oP($){let w=[];if($.userinfo!==void 0)w.push(nY($.userinfo)),w.push("@");if($.host!==void 0){let W=$.host;if(!Z5(W)){let Z=W5(W);if(Z.isIPV6!==!0&&Z.isIPVFuture!==!0)W=dY(W,!0),Z=W5(W);if(Z.isIPV6===!0||Z.isIPVFuture===!0)W=`[${Z.escapedHost}]`;else W=cY(W,!1)}w.push(W)}if(typeof $.port==="number"||typeof $.port==="string")w.push(":"),w.push(String($.port));return w.length?w.join(""):void 0}tY.exports={nonSimpleDomain:vP,recomposeAuthority:oP,reescapeHostDelimiters:cY,normalizePercentEncoding:dY,normalizePathEncoding:nP,serializePathEncoding:pP,normalizeQueryFragmentEncoding:sP,encodeUserinfo:nY,encodeQuery:tP,encodeFragment:rP,escapePreservingEscapes:aP,removeDotSegments:mP,isIPv4:Z5,isUUID:yP,normalizeIPv6:W5,stringArrayToHexStripped:bP}});var eY=L((Qk,oY)=>{var{isUUID:eP}=J5(),$V=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,wV=["http","https","ws","wss","urn","urn:uuid"];function WV($){return wV.indexOf($)!==-1}function T5($){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 rY($){if(!$.host)$.error=$.error||"HTTP URIs must have a host.";return $}function sY($){let w=String($.scheme).toLowerCase()==="https";if($.port===(w?443:80)||$.port==="")$.port=void 0;if(!$.path)$.path="/";return $}function ZV($){return $.secure=T5($),$.resourceName=($.path||"/")+($.query?"?"+$.query:""),$.path=void 0,$.query=void 0,$}function XV($){if($.port===(T5($)?443:80)||$.port==="")$.port=void 0;if(typeof $.secure==="boolean")$.scheme=$.secure?"wss":"ws",$.secure=void 0;if($.resourceName){let w=$.resourceName.indexOf("?"),W=w===-1?$.resourceName:$.resourceName.slice(0,w);$.path=W&&W!=="/"?W:void 0,$.query=w===-1?void 0:$.resourceName.slice(w+1),$.resourceName=void 0}return $.fragment=void 0,$}function YV($,w){if(!$.path)return $.error="URN can not be parsed",$;let W=$.path.match($V);if(W&&W[0]===$.path){let Z=w.scheme||$.scheme||"urn";$.nid=W[1].toLowerCase(),$.nss=W[2];let X=`${Z}:${w.nid||$.nid}`,Y=Q5(X);if($.path=void 0,Y)$=Y.parse($,w)}else $.error=$.error||"URN can not be parsed.";return $}function GV($,w){if($.nid===void 0)throw Error("URN without nid cannot be serialized");let W=w.scheme||$.scheme||"urn",Z=$.nid.toLowerCase(),X=`${W}:${w.nid||Z}`,Y=Q5(X);if(Y)$=Y.serialize($,w);let G=$,J=$.nss;return G.path=`${Z||w.nid}:${J}`,w.skipEscape=!0,G}function JV($,w){let W=$;if(W.uuid=W.nss,W.nss=void 0,!w.tolerant&&(!W.uuid||!eP(W.uuid)))W.error=W.error||"UUID is not valid.";return W}function TV($){let w=$;return w.nss=($.uuid||"").toLowerCase(),w}var aY={scheme:"http",domainHost:!0,parse:rY,serialize:sY},QV={scheme:"https",domainHost:aY.domainHost,parse:rY,serialize:sY},F8={scheme:"ws",domainHost:!0,parse:ZV,serialize:XV},MV={scheme:"wss",domainHost:F8.domainHost,parse:F8.parse,serialize:F8.serialize},zV={scheme:"urn",parse:YV,serialize:GV,skipNormalize:!0},NV={scheme:"urn:uuid",parse:JV,serialize:TV,skipNormalize:!0},O8={http:aY,https:QV,ws:F8,wss:MV,urn:zV,"urn:uuid":NV};Object.setPrototypeOf(O8,null);function Q5($){return $&&(O8[$]||O8[$.toLowerCase()])||void 0}oY.exports={wsIsSecure:T5,SCHEMES:O8,isValidSchemeName:WV,getSchemeHandler:Q5}});var NG=L((Mk,D8)=>{var{normalizeIPv6:XG,removeDotSegments:W9,recomposeAuthority:KV,normalizePercentEncoding:YG,normalizePathEncoding:BV,serializePathEncoding:$G,normalizeQueryFragmentEncoding:wG,encodeQuery:PV,encodeFragment:VV,reescapeHostDelimiters:fV,isIPv4:GG,nonSimpleDomain:qV}=J5(),{SCHEMES:JG,getSchemeHandler:M5}=eY(),TG=/^[A-Za-z][A-Za-z0-9+.-]*$/u;function WG($){let w=unescape(String($));if(!TG.test(w))throw TypeError("URI scheme is malformed.");return w}function UV($,w){if(typeof $==="string")$=AV($,w);else if(typeof $==="object")$=L8(J1($,w),w);return $}function HV($,w,W){let Z=W?Object.assign({scheme:"null"},W):{scheme:"null"},{parsed:X,malformedAuthorityOrPort:Y,malformedPercentEncoding:G,malformedSchemeSpecific:J,malformedHost:T,malformedScheme:Q}=E8($,Z),{parsed:M,malformedAuthorityOrPort:z,malformedPercentEncoding:N,malformedSchemeSpecific:B,malformedHost:K,malformedScheme:P}=E8(w,Z);if(Y||z||G||N||J||B||T||K||Q||P)throw Error(X.error||M.error||"URI is malformed.");let q=QG(X,M,Z,!0),f=M5(W&&W.scheme||q.scheme),H=q.host,E=H!==void 0&&H!==""&&(GG(H)||XG(H).isIPV6);MG(q,W||{},f,E);let S=H&&H.indexOf("%")!==-1&&!/\P{ASCII}/u.test(H);if(q.error&&!S)throw Error(q.error);return Z.skipEscape=!0,J1(q,Z)}function QG($,w,W,Z){let X={};if(!Z)$=L8(J1($,W),W),w=L8(J1(w,W),W);if(W=W||{},!W.tolerant&&w.scheme)X.scheme=w.scheme,X.userinfo=w.userinfo,X.host=w.host,X.port=w.port,X.path=W9(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=W9(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=W9(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=W9(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 FV($,w,W){let Z=ZG($,W),X=ZG(w,W);return Z!==void 0&&X!==void 0&&Z===X}function J1($,w){let W={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(W.scheme)W.scheme=WG(W.scheme);let Y=M5(Z.scheme||W.scheme);if(Y&&Y.serialize)Y.serialize(W,Z);let G=W.userinfo!==void 0||W.host!==void 0||W.port!==void 0,J=!Z.skipEscape&&W.scheme===void 0&&!G;if(W.path!==void 0)if(!Z.skipEscape)W.path=$G(W.path,J);else W.path=YG(W.path);if(Z.reference!=="suffix"&&W.scheme)W.scheme=WG(W.scheme),X.push(W.scheme,":");let T=KV(W);if(T!==void 0){if(Z.reference!=="suffix")X.push("//");if(X.push(T),W.path&&W.path[0]!=="/")X.push("/")}if(W.path!==void 0){let Q=W.path;if(!Z.absolutePath&&(!Y||!Y.absolutePath))Q=W9(Q);if(J)Q=$G(Q,!0);if(T===void 0&&Q[0]==="/"&&Q[1]==="/")Q="/%2F"+Q.slice(2);X.push(Q)}if(W.query!==void 0)X.push("?",PV(W.query));if(W.fragment!==void 0)X.push("#",VV(W.fragment));return X.join("")}var OV=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,EV=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,LV=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function DV($,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 w9($){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 kV($){let w=$[4];return w9($[3])||w!==void 0&&!(w[0]==="["&&w[w.length-1]==="]")&&w9(w)||w9($[6])||w9($[7])||w9($[8])}function MG($,w,W,Z){if(!w.unicodeSupport&&(!W||!W.unicodeSupport)&&$.host&&$.host[0]!=="["&&(w.domainHost||W&&W.domainHost)&&Z===!1&&qV($.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 E8($,w){let W=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,G=!1,J=!1,T=!1,Q=!1,M=!1;if(W.reference==="suffix")if(W.scheme)$=W.scheme+":"+$;else $="//"+$;let z=$.match(EV);if(z!==null&&z[1].indexOf("\\")!==-1)Z.error="URI authority must not contain a literal backslash.",X=!0;let N=$.match(LV);if(N!==null){let K=N[1],P=K.replace(/[\t\n\r]/g,"");if(P.length>=2){if(P.slice(0,2)!=="//")Z.error=Z.error||"URI authority must not contain a literal backslash.",X=!0;else if(K.length!==P.length)Z.error=Z.error||"URI authority introducer must not contain whitespace.",X=!0}}let B=$.match(OV);if(B){if(Z.scheme=B[1],Z.userinfo=B[3],Z.host=B[4],Z.port=parseInt(B[5],10),Z.path=B[6]||"",Z.query=B[7],Z.fragment=B[8],Z.scheme!==void 0){let q=unescape(Z.scheme);if(TG.test(q))Z.scheme=q.toLowerCase();else Z.error=Z.error||"URI scheme is malformed.",Q=!0}if(Y=kV(B),Y)Z.error=Z.error||"URI contains malformed percent-encoding.";if(isNaN(Z.port))Z.port=B[5];let K=DV(Z,B);if(K!==void 0)Z.error=Z.error||K,X=!0;if(Z.host)if(GG(Z.host)===!1){let f=Z.host[0]==="["&&Z.host[Z.host.length-1]==="]",H=XG(Z.host);if(M=H.isIPV6||H.isIPVFuture===!0,T=f&&H.error===!0,Z.host=M?H.host:H.host.toLowerCase(),T)Z.error=Z.error||"URI host is malformed.",X=!0}else M=!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(W.reference&&W.reference!=="suffix"&&W.reference!==Z.reference)Z.error=Z.error||"URI is not a "+W.reference+" reference.";let P=M5(W.scheme||Z.scheme);if(J=MG(Z,W,P,M),!P||P&&!P.skipNormalize){if($.indexOf("%")!==-1){if(Z.host!==void 0&&!T){let q=M?Z.host:YG(Z.host,!0);Z.host=fV(q,M)}}if(Z.path)Z.path=BV(Z.path);if(Z.query)Z.query=wG(Z.query);if(Z.fragment)Z.fragment=wG(Z.fragment)}if(P&&P.parse){if(P.parse(Z,W),P===JG.urn&&Z.nid===void 0)G=!0}}else Z.error=Z.error||"URI can not be parsed.";return{parsed:Z,malformedAuthorityOrPort:X,malformedPercentEncoding:Y,malformedSchemeSpecific:G,malformedHost:J,malformedScheme:Q}}function L8($,w){return E8($,w).parsed}function AV($,w){return zG($,w).normalized}function zG($,w){let{parsed:W,malformedAuthorityOrPort:Z,malformedPercentEncoding:X,malformedSchemeSpecific:Y,malformedHost:G,malformedScheme:J}=E8($,w);return{normalized:Z||X||Y||G||J?$:J1(W,w),malformedAuthorityOrPort:Z,malformedPercentEncoding:X,malformedSchemeSpecific:Y,malformedHost:G,malformedScheme:J}}function ZG($,w){if(typeof $!=="string"&&typeof $!=="object")return;let W;try{W=typeof $==="string"?$:J1($,w)}catch{return}let{normalized:Z,malformedAuthorityOrPort:X,malformedPercentEncoding:Y,malformedSchemeSpecific:G,malformedHost:J,malformedScheme:T}=zG(W,w);return X||Y||G||J||T?void 0:Z}var z5={SCHEMES:JG,normalize:UV,resolve:HV,resolveComponent:QG,equal:FV,serialize:J1,parse:L8};D8.exports=z5;D8.exports.default=z5;D8.exports.fastUri=z5});var PG=L((BG)=>{Object.defineProperty(BG,"__esModule",{value:!0});var KG=NG();KG.code='require("ajv/dist/runtime/uri").default';BG.default=KG});var EG=L((V$)=>{Object.defineProperty(V$,"__esModule",{value:!0});V$.CodeGen=V$.Name=V$.nil=V$.stringify=V$.str=V$._=V$.KeywordCxt=void 0;var RV=ow();Object.defineProperty(V$,"KeywordCxt",{enumerable:!0,get:function(){return RV.KeywordCxt}});var s1=u();Object.defineProperty(V$,"_",{enumerable:!0,get:function(){return s1._}});Object.defineProperty(V$,"str",{enumerable:!0,get:function(){return s1.str}});Object.defineProperty(V$,"stringify",{enumerable:!0,get:function(){return s1.stringify}});Object.defineProperty(V$,"nil",{enumerable:!0,get:function(){return s1.nil}});Object.defineProperty(V$,"Name",{enumerable:!0,get:function(){return s1.Name}});Object.defineProperty(V$,"CodeGen",{enumerable:!0,get:function(){return s1.CodeGen}});var CV=q8(),HG=ew(),jV=hW(),Z9=H8(),yV=u(),X9=rw(),k8=tw(),K5=c(),VG=iY(),IV=PG(),FG=($,w)=>new RegExp($,w);FG.code="new RegExp";var bV=["removeAdditional","useDefaults","coerceTypes"],xV=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),_V={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."},gV={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},fG=200;function vV($){var w,W,Z,X,Y,G,J,T,Q,M,z,N,B,K,P,q,f,H,E,S,A,j,g,s,e;let i=$.strict,F0=(w=$.code)===null||w===void 0?void 0:w.optimize,w1=F0===!0||F0===void 0?1:F0||0,z$=(Z=(W=$.code)===null||W===void 0?void 0:W.regExp)!==null&&Z!==void 0?Z:FG,i1=(X=$.uriResolver)!==null&&X!==void 0?X:IV.default;return{strictSchema:(G=(Y=$.strictSchema)!==null&&Y!==void 0?Y:i)!==null&&G!==void 0?G:!0,strictNumbers:(T=(J=$.strictNumbers)!==null&&J!==void 0?J:i)!==null&&T!==void 0?T:!0,strictTypes:(M=(Q=$.strictTypes)!==null&&Q!==void 0?Q:i)!==null&&M!==void 0?M:"log",strictTuples:(N=(z=$.strictTuples)!==null&&z!==void 0?z:i)!==null&&N!==void 0?N:"log",strictRequired:(K=(B=$.strictRequired)!==null&&B!==void 0?B:i)!==null&&K!==void 0?K:!1,code:$.code?{...$.code,optimize:w1,regExp:z$}:{optimize:w1,regExp:z$},loopRequired:(P=$.loopRequired)!==null&&P!==void 0?P:fG,loopEnum:(q=$.loopEnum)!==null&&q!==void 0?q:fG,meta:(f=$.meta)!==null&&f!==void 0?f:!0,messages:(H=$.messages)!==null&&H!==void 0?H:!0,inlineRefs:(E=$.inlineRefs)!==null&&E!==void 0?E:!0,schemaId:(S=$.schemaId)!==null&&S!==void 0?S:"$id",addUsedSchema:(A=$.addUsedSchema)!==null&&A!==void 0?A:!0,validateSchema:(j=$.validateSchema)!==null&&j!==void 0?j:!0,validateFormats:(g=$.validateFormats)!==null&&g!==void 0?g:!0,unicodeRegExp:(s=$.unicodeRegExp)!==null&&s!==void 0?s:!0,int32range:(e=$.int32range)!==null&&e!==void 0?e:!0,uriResolver:i1}}class A8{constructor($={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,$=this.opts={...$,...vV($)};let{es5:w,lines:W}=this.opts.code;this.scope=new yV.ValueScope({scope:{},prefixes:xV,es5:w,lines:W}),this.logger=cV($.logger);let Z=$.validateFormats;if($.validateFormats=!1,this.RULES=(0,jV.getRules)(),qG.call(this,_V,$,"NOT SUPPORTED"),qG.call(this,gV,$,"DEPRECATED","warn"),this._metaOpts=mV.call(this),$.formats)uV.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),$.keywords)iV.call(this,$.keywords);if(typeof $.meta=="object")this.addMetaSchema($.meta);hV.call(this),$.validateFormats=Z}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:$,meta:w,schemaId:W}=this.opts,Z=VG;if(W==="id")Z={...VG},Z.id=Z.$id,delete Z.$id;if(w&&$)this.addMetaSchema(Z,Z[W],!1)}defaultMeta(){let{meta:$,schemaId:w}=this.opts;return this.opts.defaultMeta=typeof $=="object"?$[w]||$:void 0}validate($,w){let W;if(typeof $=="string"){if(W=this.getSchema($),!W)throw Error(`no schema with key or ref "${$}"`)}else W=this.compile($);let Z=W(w);if(!("$async"in W))this.errors=W.errors;return Z}compile($,w){let W=this._addSchema($,w);return W.validate||this._compileSchemaEnv(W)}compileAsync($,w){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema:W}=this.opts;return Z.call(this,$,w);async function Z(Q,M){await X.call(this,Q.$schema);let z=this._addSchema(Q,M);return z.validate||Y.call(this,z)}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(M){if(!(M instanceof HG.default))throw M;return G.call(this,M),await J.call(this,M.missingSchema),Y.call(this,Q)}}function G({missingSchema:Q,missingRef:M}){if(this.refs[Q])throw Error(`AnySchema ${Q} is loaded but ${M} cannot be resolved`)}async function J(Q){let M=await T.call(this,Q);if(!this.refs[Q])await X.call(this,M.$schema);if(!this.refs[Q])this.addSchema(M,Q,w)}async function T(Q){let M=this._loading[Q];if(M)return M;try{return await(this._loading[Q]=W(Q))}finally{delete this._loading[Q]}}}addSchema($,w,W,Z=this.opts.validateSchema){if(Array.isArray($)){for(let Y of $)this.addSchema(Y,void 0,W,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,X9.normalizeId)(w||X),this._checkUnique(w),this.schemas[w]=this._addSchema($,W,w,Z,!0),this}addMetaSchema($,w,W=this.opts.validateSchema){return this.addSchema($,w,!0,W),this}validateSchema($,w){if(typeof $=="boolean")return!0;let W;if(W=$.$schema,W!==void 0&&typeof W!="string")throw Error("$schema must be a string");if(W=W||this.opts.defaultMeta||this.defaultMeta(),!W)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let Z=this.validate(W,$);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=UG.call(this,$))=="string")$=w;if(w===void 0){let{schemaId:W}=this.opts,Z=new Z9.SchemaEnv({schema:{},schemaId:W});if(w=Z9.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=UG.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 W=$[this.opts.schemaId];if(W)W=(0,X9.normalizeId)(W),delete this.schemas[W],delete this.refs[W];return this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary($){for(let w of $)this.addKeyword(w);return this}addKeyword($,w){let W;if(typeof $=="string"){if(W=$,typeof w=="object")this.logger.warn("these parameters are deprecated, see docs for addKeyword"),w.keyword=W}else if(typeof $=="object"&&w===void 0){if(w=$,W=w.keyword,Array.isArray(W)&&!W.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(nV.call(this,W,w),!w)return(0,K5.eachItem)(W,(X)=>N5.call(this,X)),this;tV.call(this,w);let Z={...w,type:(0,k8.getJSONTypes)(w.type),schemaType:(0,k8.getJSONTypes)(w.schemaType)};return(0,K5.eachItem)(W,Z.type.length===0?(X)=>N5.call(this,X,Z):(X)=>Z.type.forEach((Y)=>N5.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 W of w.rules){let Z=W.rules.findIndex((X)=>X.keyword===$);if(Z>=0)W.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:W="data"}={}){if(!$||$.length===0)return"No errors";return $.map((Z)=>`${W}${Z.instancePath} ${Z.message}`).reduce((Z,X)=>Z+w+X)}$dataMetaSchema($,w){let W=this.RULES.all;$=JSON.parse(JSON.stringify($));for(let Z of w){let X=Z.split("/").slice(1),Y=$;for(let G of X)Y=Y[G];for(let G in W){let J=W[G];if(typeof J!="object")continue;let{$data:T}=J.definition,Q=Y[G];if(T&&Q)Y[G]=OG(Q)}}return $}_removeAllSchemas($,w){for(let W in $){let Z=$[W];if(!w||w.test(W)){if(typeof Z=="string")delete $[W];else if(Z&&!Z.meta)this._cache.delete(Z.schema),delete $[W]}}}_addSchema($,w,W,Z=this.opts.validateSchema,X=this.opts.addUsedSchema){let Y,{schemaId:G}=this.opts;if(typeof $=="object")Y=$[G];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;W=(0,X9.normalizeId)(Y||W);let T=X9.getSchemaRefs.call(this,$,W);if(J=new Z9.SchemaEnv({schema:$,schemaId:G,meta:w,baseId:W,localRefs:T}),this._cache.set(J.schema,J),X&&!W.startsWith("#")){if(W)this._checkUnique(W);this.refs[W]=J}if(Z)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 Z9.compileSchema.call(this,$);if(!$.validate)throw Error("ajv implementation error");return $.validate}_compileMetaSchema($){let w=this.opts;this.opts=this._metaOpts;try{Z9.compileSchema.call(this,$)}finally{this.opts=w}}}A8.ValidationError=CV.default;A8.MissingRefError=HG.default;V$.default=A8;function qG($,w,W,Z="error"){for(let X in $){let Y=X;if(Y in w)this.logger[Z](`${W}: option ${X}. ${$[Y]}`)}}function UG($){return $=(0,X9.normalizeId)($),this.schemas[$]||this.refs[$]}function hV(){let $=this.opts.schemas;if(!$)return;if(Array.isArray($))this.addSchema($);else for(let w in $)this.addSchema($[w],w)}function uV(){for(let $ in this.opts.formats){let w=this.opts.formats[$];if(w)this.addFormat($,w)}}function iV($){if(Array.isArray($)){this.addVocabulary($);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let w in $){let W=$[w];if(!W.keyword)W.keyword=w;this.addKeyword(W)}}function mV(){let $={...this.opts};for(let w of bV)delete $[w];return $}var lV={log(){},warn(){},error(){}};function cV($){if($===!1)return lV;if($===void 0)return console;if($.log&&$.warn&&$.error)return $;throw Error("logger must implement log, warn and error methods")}var dV=/^[a-z_$][a-z0-9_$:-]*$/i;function nV($,w){let{RULES:W}=this;if((0,K5.eachItem)($,(Z)=>{if(W.keywords[Z])throw Error(`Keyword ${Z} is already defined`);if(!dV.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 N5($,w,W){var Z;let X=w===null||w===void 0?void 0:w.post;if(W&&X)throw Error('keyword with "post" flag cannot have "type"');let{RULES:Y}=this,G=X?Y.post:Y.rules.find(({type:T})=>T===W);if(!G)G={type:W,rules:[]},Y.rules.push(G);if(Y.keywords[$]=!0,!w)return;let J={keyword:$,definition:{...w,type:(0,k8.getJSONTypes)(w.type),schemaType:(0,k8.getJSONTypes)(w.schemaType)}};if(w.before)pV.call(this,G,J,w.before);else G.rules.push(J);Y.all[$]=J,(Z=w.implements)===null||Z===void 0||Z.forEach((T)=>this.addKeyword(T))}function pV($,w,W){let Z=$.rules.findIndex((X)=>X.keyword===W);if(Z>=0)$.rules.splice(Z,0,w);else $.rules.push(w),this.logger.warn(`rule ${W} is not defined`)}function tV($){let{metaSchema:w}=$;if(w===void 0)return;if($.$data&&this.opts.$data)w=OG(w);$.validateSchema=this.compile(w,!0)}var rV={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function OG($){return{anyOf:[$,rV]}}});var DG=L((LG)=>{Object.defineProperty(LG,"__esModule",{value:!0});var oV={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};LG.default=oV});var jG=L((RG)=>{Object.defineProperty(RG,"__esModule",{value:!0});RG.callRef=RG.getValidate=void 0;var $f=ew(),kG=u0(),S0=u(),a1=B$(),AG=H8(),S8=c(),wf={keyword:"$ref",schemaType:"string",code($){let{gen:w,schema:W,it:Z}=$,{baseId:X,schemaEnv:Y,validateName:G,opts:J,self:T}=Z,{root:Q}=Y;if((W==="#"||W==="#/")&&X===Q.baseId)return z();let M=AG.resolveRef.call(T,Q,X,W);if(M===void 0)throw new $f.default(Z.opts.uriResolver,X,W);if(M instanceof AG.SchemaEnv)return N(M);return B(M);function z(){if(Y===Q)return R8($,G,Y,Y.$async);let K=w.scopeValue("root",{ref:Q});return R8($,S0._`${K}.validate`,Q,Q.$async)}function N(K){let P=SG($,K);R8($,P,K,K.$async)}function B(K){let P=w.scopeValue("schema",J.code.source===!0?{ref:K,code:(0,S0.stringify)(K)}:{ref:K}),q=w.name("valid"),f=$.subschema({schema:K,dataTypes:[],schemaPath:S0.nil,topSchemaRef:P,errSchemaPath:W},q);$.mergeEvaluated(f),$.ok(q)}}};function SG($,w){let{gen:W}=$;return w.validate?W.scopeValue("validate",{ref:w.validate}):S0._`${W.scopeValue("wrapper",{ref:w})}.validate`}RG.getValidate=SG;function R8($,w,W,Z){let{gen:X,it:Y}=$,{allErrors:G,schemaEnv:J,opts:T}=Y,Q=T.passContext?a1.default.this:S0.nil;if(Z)M();else z();function M(){if(!J.$async)throw Error("async schema referenced by sync schema");let K=X.let("valid");X.try(()=>{if(X.code(S0._`await ${(0,kG.callValidateCode)($,w,Q)}`),B(w),!G)X.assign(K,!0)},(P)=>{if(X.if(S0._`!(${P} instanceof ${Y.ValidationError})`,()=>X.throw(P)),N(P),!G)X.assign(K,!1)}),$.ok(K)}function z(){$.result((0,kG.callValidateCode)($,w,Q),()=>B(w),()=>N(w))}function N(K){let P=S0._`${K}.errors`;X.assign(a1.default.vErrors,S0._`${a1.default.vErrors} === null ? ${P} : ${a1.default.vErrors}.concat(${P})`),X.assign(a1.default.errors,S0._`${a1.default.vErrors}.length`)}function B(K){var P;if(!Y.opts.unevaluated)return;let q=(P=W===null||W===void 0?void 0:W.validate)===null||P===void 0?void 0:P.evaluated;if(Y.props!==!0)if(q&&!q.dynamicProps){if(q.props!==void 0)Y.props=S8.mergeEvaluated.props(X,q.props,Y.props)}else{let f=X.var("props",S0._`${K}.evaluated.props`);Y.props=S8.mergeEvaluated.props(X,f,Y.props,S0.Name)}if(Y.items!==!0)if(q&&!q.dynamicItems){if(q.items!==void 0)Y.items=S8.mergeEvaluated.items(X,q.items,Y.items)}else{let f=X.var("items",S0._`${K}.evaluated.items`);Y.items=S8.mergeEvaluated.items(X,f,Y.items,S0.Name)}}}RG.callRef=R8;RG.default=wf});var IG=L((yG)=>{Object.defineProperty(yG,"__esModule",{value:!0});var Xf=DG(),Yf=jG(),Gf=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Xf.default,Yf.default];yG.default=Gf});var xG=L((bG)=>{Object.defineProperty(bG,"__esModule",{value:!0});var C8=u(),v$=C8.operators,j8={maximum:{okStr:"<=",ok:v$.LTE,fail:v$.GT},minimum:{okStr:">=",ok:v$.GTE,fail:v$.LT},exclusiveMaximum:{okStr:"<",ok:v$.LT,fail:v$.GTE},exclusiveMinimum:{okStr:">",ok:v$.GT,fail:v$.LTE}},Tf={message:({keyword:$,schemaCode:w})=>C8.str`must be ${j8[$].okStr} ${w}`,params:({keyword:$,schemaCode:w})=>C8._`{comparison: ${j8[$].okStr}, limit: ${w}}`},Qf={keyword:Object.keys(j8),type:"number",schemaType:"number",$data:!0,error:Tf,code($){let{keyword:w,data:W,schemaCode:Z}=$;$.fail$data(C8._`${W} ${j8[w].fail} ${Z} || isNaN(${W})`)}};bG.default=Qf});var gG=L((_G)=>{Object.defineProperty(_G,"__esModule",{value:!0});var Y9=u(),zf={message:({schemaCode:$})=>Y9.str`must be multiple of ${$}`,params:({schemaCode:$})=>Y9._`{multipleOf: ${$}}`},Nf={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:zf,code($){let{gen:w,data:W,schemaCode:Z,it:X}=$,Y=X.opts.multipleOfPrecision,G=w.let("res"),J=Y?Y9._`Math.abs(Math.round(${G}) - ${G}) > 1e-${Y}`:Y9._`${G} !== parseInt(${G})`;$.fail$data(Y9._`(${Z} === 0 || (${G} = ${W}/${Z}, ${J}))`)}};_G.default=Nf});var uG=L((hG)=>{Object.defineProperty(hG,"__esModule",{value:!0});function vG($){let w=$.length,W=0,Z=0,X;while(Z<w)if(W++,X=$.charCodeAt(Z++),X>=55296&&X<=56319&&Z<w){if(X=$.charCodeAt(Z),(X&64512)===56320)Z++}return W}hG.default=vG;vG.code='require("ajv/dist/runtime/ucs2length").default'});var mG=L((iG)=>{Object.defineProperty(iG,"__esModule",{value:!0});var T1=u(),Pf=c(),Vf=uG(),ff={message({keyword:$,schemaCode:w}){let W=$==="maxLength"?"more":"fewer";return T1.str`must NOT have ${W} than ${w} characters`},params:({schemaCode:$})=>T1._`{limit: ${$}}`},qf={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:ff,code($){let{keyword:w,data:W,schemaCode:Z,it:X}=$,Y=w==="maxLength"?T1.operators.GT:T1.operators.LT,G=X.opts.unicode===!1?T1._`${W}.length`:T1._`${(0,Pf.useFunc)($.gen,Vf.default)}(${W})`;$.fail$data(T1._`${G} ${Y} ${Z}`)}};iG.default=qf});var cG=L((lG)=>{Object.defineProperty(lG,"__esModule",{value:!0});var Hf=u0(),Ff=c(),o1=u(),Of={message:({schemaCode:$})=>o1.str`must match pattern "${$}"`,params:({schemaCode:$})=>o1._`{pattern: ${$}}`},Ef={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Of,code($){let{gen:w,data:W,$data:Z,schema:X,schemaCode:Y,it:G}=$,J=G.opts.unicodeRegExp?"u":"";if(Z){let{regExp:T}=G.opts.code,Q=T.code==="new RegExp"?o1._`new RegExp`:(0,Ff.useFunc)(w,T),M=w.let("valid");w.try(()=>w.assign(M,o1._`${Q}(${Y}, ${J}).test(${W})`),()=>w.assign(M,!1)),$.fail$data(o1._`!${M}`)}else{let T=(0,Hf.usePattern)($,X);$.fail$data(o1._`!${T}.test(${W})`)}}};lG.default=Ef});var nG=L((dG)=>{Object.defineProperty(dG,"__esModule",{value:!0});var G9=u(),Df={message({keyword:$,schemaCode:w}){let W=$==="maxProperties"?"more":"fewer";return G9.str`must NOT have ${W} than ${w} properties`},params:({schemaCode:$})=>G9._`{limit: ${$}}`},kf={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:Df,code($){let{keyword:w,data:W,schemaCode:Z}=$,X=w==="maxProperties"?G9.operators.GT:G9.operators.LT;$.fail$data(G9._`Object.keys(${W}).length ${X} ${Z}`)}};dG.default=kf});var tG=L((pG)=>{Object.defineProperty(pG,"__esModule",{value:!0});var J9=u0(),T9=u(),Sf=c(),Rf={message:({params:{missingProperty:$}})=>T9.str`must have required property '${$}'`,params:({params:{missingProperty:$}})=>T9._`{missingProperty: ${$}}`},Cf={keyword:"required",type:"object",schemaType:"array",$data:!0,error:Rf,code($){let{gen:w,schema:W,schemaCode:Z,data:X,$data:Y,it:G}=$,{opts:J}=G;if(!Y&&W.length===0)return;let T=W.length>=J.loopRequired;if(G.allErrors)Q();else M();if(J.strictRequired){let B=$.parentSchema.properties,{definedProperties:K}=$.it;for(let P of W)if((B===null||B===void 0?void 0:B[P])===void 0&&!K.has(P)){let q=G.schemaEnv.baseId+G.errSchemaPath,f=`required property "${P}" is not defined at "${q}" (strictRequired)`;(0,Sf.checkStrictMode)(G,f,G.opts.strictRequired)}}function Q(){if(T||Y)$.block$data(T9.nil,z);else for(let B of W)(0,J9.checkReportMissingProp)($,B)}function M(){let B=w.let("missing");if(T||Y){let K=w.let("valid",!0);$.block$data(K,()=>N(B,K)),$.ok(K)}else w.if((0,J9.checkMissingProp)($,W,B)),(0,J9.reportMissingProp)($,B),w.else()}function z(){w.forOf("prop",Z,(B)=>{$.setParams({missingProperty:B}),w.if((0,J9.noPropertyInData)(w,X,B,J.ownProperties),()=>$.error())})}function N(B,K){$.setParams({missingProperty:B}),w.forOf(B,Z,()=>{w.assign(K,(0,J9.propertyInData)(w,X,B,J.ownProperties)),w.if((0,T9.not)(K),()=>{$.error(),w.break()})},T9.nil)}}};pG.default=Cf});var sG=L((rG)=>{Object.defineProperty(rG,"__esModule",{value:!0});var Q9=u(),yf={message({keyword:$,schemaCode:w}){let W=$==="maxItems"?"more":"fewer";return Q9.str`must NOT have ${W} than ${w} items`},params:({schemaCode:$})=>Q9._`{limit: ${$}}`},If={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:yf,code($){let{keyword:w,data:W,schemaCode:Z}=$,X=w==="maxItems"?Q9.operators.GT:Q9.operators.LT;$.fail$data(Q9._`${W}.length ${X} ${Z}`)}};rG.default=If});var y8=L((oG)=>{Object.defineProperty(oG,"__esModule",{value:!0});var aG=pW();aG.code='require("ajv/dist/runtime/equal").default';oG.default=aG});var $7=L((eG)=>{Object.defineProperty(eG,"__esModule",{value:!0});var B5=tw(),K0=u(),_f=c(),gf=y8(),vf={message:({params:{i:$,j:w}})=>K0.str`must NOT have duplicate items (items ## ${w} and ${$} are identical)`,params:({params:{i:$,j:w}})=>K0._`{i: ${$}, j: ${w}}`},hf={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:vf,code($){let{gen:w,data:W,$data:Z,schema:X,parentSchema:Y,schemaCode:G,it:J}=$;if(!Z&&!X)return;let T=w.let("valid"),Q=Y.items?(0,B5.getSchemaTypes)(Y.items):[];$.block$data(T,M,K0._`${G} === false`),$.ok(T);function M(){let K=w.let("i",K0._`${W}.length`),P=w.let("j");$.setParams({i:K,j:P}),w.assign(T,!0),w.if(K0._`${K} > 1`,()=>(z()?N:B)(K,P))}function z(){return Q.length>0&&!Q.some((K)=>K==="object"||K==="array")}function N(K,P){let q=w.name("item"),f=(0,B5.checkDataTypes)(Q,q,J.opts.strictNumbers,B5.DataType.Wrong),H=w.const("indices",K0._`{}`);w.for(K0._`;${K}--;`,()=>{if(w.let(q,K0._`${W}[${K}]`),w.if(f,K0._`continue`),Q.length>1)w.if(K0._`typeof ${q} == "string"`,K0._`${q} += "_"`);w.if(K0._`typeof ${H}[${q}] == "number"`,()=>{w.assign(P,K0._`${H}[${q}]`),$.error(),w.assign(T,!1).break()}).code(K0._`${H}[${q}] = ${K}`)})}function B(K,P){let q=(0,_f.useFunc)(w,gf.default),f=w.name("outer");w.label(f).for(K0._`;${K}--;`,()=>w.for(K0._`${P} = ${K}; ${P}--;`,()=>w.if(K0._`${q}(${W}[${K}], ${W}[${P}])`,()=>{$.error(),w.assign(T,!1).break(f)})))}}};eG.default=hf});var W7=L((w7)=>{Object.defineProperty(w7,"__esModule",{value:!0});var P5=u(),mf=c(),lf=y8(),cf={message:"must be equal to constant",params:({schemaCode:$})=>P5._`{allowedValue: ${$}}`},df={keyword:"const",$data:!0,error:cf,code($){let{gen:w,data:W,$data:Z,schemaCode:X,schema:Y}=$;if(Z||Y&&typeof Y=="object")$.fail$data(P5._`!${(0,mf.useFunc)(w,lf.default)}(${W}, ${X})`);else $.fail(P5._`${Y} !== ${W}`)}};w7.default=df});var X7=L((Z7)=>{Object.defineProperty(Z7,"__esModule",{value:!0});var M9=u(),pf=c(),tf=y8(),rf={message:"must be equal to one of the allowed values",params:({schemaCode:$})=>M9._`{allowedValues: ${$}}`},sf={keyword:"enum",schemaType:"array",$data:!0,error:rf,code($){let{gen:w,data:W,$data:Z,schema:X,schemaCode:Y,it:G}=$;if(!Z&&X.length===0)throw Error("enum must have non-empty array");let J=X.length>=G.opts.loopEnum,T,Q=()=>T!==null&&T!==void 0?T:T=(0,pf.useFunc)(w,tf.default),M;if(J||Z)M=w.let("valid"),$.block$data(M,z);else{if(!Array.isArray(X))throw Error("ajv implementation error");let B=w.const("vSchema",Y);M=(0,M9.or)(...X.map((K,P)=>N(B,P)))}$.pass(M);function z(){w.assign(M,!1),w.forOf("v",Y,(B)=>w.if(M9._`${Q()}(${W}, ${B})`,()=>w.assign(M,!0).break()))}function N(B,K){let P=X[K];return typeof P==="object"&&P!==null?M9._`${Q()}(${W}, ${B}[${K}])`:M9._`${W} === ${P}`}}};Z7.default=sf});var G7=L((Y7)=>{Object.defineProperty(Y7,"__esModule",{value:!0});var of=xG(),ef=gG(),$q=mG(),wq=cG(),Wq=nG(),Zq=tG(),Xq=sG(),Yq=$7(),Gq=W7(),Jq=X7(),Tq=[of.default,ef.default,$q.default,wq.default,Wq.default,Zq.default,Xq.default,Yq.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Gq.default,Jq.default];Y7.default=Tq});var f5=L((T7)=>{Object.defineProperty(T7,"__esModule",{value:!0});T7.validateAdditionalItems=void 0;var Q1=u(),V5=c(),Mq={message:({params:{len:$}})=>Q1.str`must NOT have more than ${$} items`,params:({params:{len:$}})=>Q1._`{limit: ${$}}`},zq={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Mq,code($){let{parentSchema:w,it:W}=$,{items:Z}=w;if(!Array.isArray(Z)){(0,V5.checkStrictMode)(W,'"additionalItems" is ignored when "items" is not an array of schemas');return}J7($,Z)}};function J7($,w){let{gen:W,schema:Z,data:X,keyword:Y,it:G}=$;G.items=!0;let J=W.const("len",Q1._`${X}.length`);if(Z===!1)$.setParams({len:w.length}),$.pass(Q1._`${J} <= ${w.length}`);else if(typeof Z=="object"&&!(0,V5.alwaysValidSchema)(G,Z)){let Q=W.var("valid",Q1._`${J} <= ${w.length}`);W.if((0,Q1.not)(Q),()=>T(Q)),$.ok(Q)}function T(Q){W.forRange("i",w.length,J,(M)=>{if($.subschema({keyword:Y,dataProp:M,dataPropType:V5.Type.Num},Q),!G.allErrors)W.if((0,Q1.not)(Q),()=>W.break())})}}T7.validateAdditionalItems=J7;T7.default=zq});var q5=L((N7)=>{Object.defineProperty(N7,"__esModule",{value:!0});N7.validateTuple=void 0;var M7=u(),I8=c(),Kq=u0(),Bq={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code($){let{schema:w,it:W}=$;if(Array.isArray(w))return z7($,"additionalItems",w);if(W.items=!0,(0,I8.alwaysValidSchema)(W,w))return;$.ok((0,Kq.validateArray)($))}};function z7($,w,W=$.schema){let{gen:Z,parentSchema:X,data:Y,keyword:G,it:J}=$;if(M(X),J.opts.unevaluated&&W.length&&J.items!==!0)J.items=I8.mergeEvaluated.items(Z,W.length,J.items);let T=Z.name("valid"),Q=Z.const("len",M7._`${Y}.length`);W.forEach((z,N)=>{if((0,I8.alwaysValidSchema)(J,z))return;Z.if(M7._`${Q} > ${N}`,()=>$.subschema({keyword:G,schemaProp:N,dataProp:N},T)),$.ok(T)});function M(z){let{opts:N,errSchemaPath:B}=J,K=W.length,P=K===z.minItems&&(K===z.maxItems||z[w]===!1);if(N.strictTuples&&!P){let q=`"${G}" is ${K}-tuple, but minItems or maxItems/${w} are not specified or different at path "${B}"`;(0,I8.checkStrictMode)(J,q,N.strictTuples)}}}N7.validateTuple=z7;N7.default=Bq});var P7=L((B7)=>{Object.defineProperty(B7,"__esModule",{value:!0});var Vq=q5(),fq={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:($)=>(0,Vq.validateTuple)($,"items")};B7.default=fq});var q7=L((f7)=>{Object.defineProperty(f7,"__esModule",{value:!0});var V7=u(),Uq=c(),Hq=u0(),Fq=f5(),Oq={message:({params:{len:$}})=>V7.str`must NOT have more than ${$} items`,params:({params:{len:$}})=>V7._`{limit: ${$}}`},Eq={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Oq,code($){let{schema:w,parentSchema:W,it:Z}=$,{prefixItems:X}=W;if(Z.items=!0,(0,Uq.alwaysValidSchema)(Z,w))return;if(X)(0,Fq.validateAdditionalItems)($,X);else $.ok((0,Hq.validateArray)($))}};f7.default=Eq});var H7=L((U7)=>{Object.defineProperty(U7,"__esModule",{value:!0});var i0=u(),b8=c(),Dq={message:({params:{min:$,max:w}})=>w===void 0?i0.str`must contain at least ${$} valid item(s)`:i0.str`must contain at least ${$} and no more than ${w} valid item(s)`,params:({params:{min:$,max:w}})=>w===void 0?i0._`{minContains: ${$}}`:i0._`{minContains: ${$}, maxContains: ${w}}`},kq={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Dq,code($){let{gen:w,schema:W,parentSchema:Z,data:X,it:Y}=$,G,J,{minContains:T,maxContains:Q}=Z;if(Y.opts.next)G=T===void 0?1:T,J=Q;else G=1;let M=w.const("len",i0._`${X}.length`);if($.setParams({min:G,max:J}),J===void 0&&G===0){(0,b8.checkStrictMode)(Y,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(J!==void 0&&G>J){(0,b8.checkStrictMode)(Y,'"minContains" > "maxContains" is always invalid'),$.fail();return}if((0,b8.alwaysValidSchema)(Y,W)){let P=i0._`${M} >= ${G}`;if(J!==void 0)P=i0._`${P} && ${M} <= ${J}`;$.pass(P);return}Y.items=!0;let z=w.name("valid");if(J===void 0&&G===1)B(z,()=>w.if(z,()=>w.break()));else if(G===0){if(w.let(z,!0),J!==void 0)w.if(i0._`${X}.length > 0`,N)}else w.let(z,!1),N();$.result(z,()=>$.reset());function N(){let P=w.name("_valid"),q=w.let("count",0);B(P,()=>w.if(P,()=>K(q)))}function B(P,q){w.forRange("i",0,M,(f)=>{$.subschema({keyword:"contains",dataProp:f,dataPropType:b8.Type.Num,compositeRule:!0},P),q()})}function K(P){if(w.code(i0._`${P}++`),J===void 0)w.if(i0._`${P} >= ${G}`,()=>w.assign(z,!0).break());else if(w.if(i0._`${P} > ${J}`,()=>w.assign(z,!1).break()),G===1)w.assign(z,!0);else w.if(i0._`${P} >= ${G}`,()=>w.assign(z,!0))}}};U7.default=kq});var k7=L((E7)=>{Object.defineProperty(E7,"__esModule",{value:!0});E7.validateSchemaDeps=E7.validatePropertyDeps=E7.error=void 0;var U5=u(),Sq=c(),z9=u0();E7.error={message:({params:{property:$,depsCount:w,deps:W}})=>{let Z=w===1?"property":"properties";return U5.str`must have ${Z} ${W} when property ${$} is present`},params:({params:{property:$,depsCount:w,deps:W,missingProperty:Z}})=>U5._`{property: ${$},
32
+ || ${G} === "boolean" || ${X} === null`).assign(J,v._`[${X}]`)}}}function xK({gen:$,parentData:w,parentDataProperty:W},Z){$.if(v._`${w} !== undefined`,()=>$.assign(v._`${w}[${W}]`,Z))}function mW($,w,W,Z=p1.Correct){let X=Z===p1.Correct?v.operators.EQ:v.operators.NEQ,Y;switch($){case"null":return v._`${w} ${X} null`;case"array":Y=v._`Array.isArray(${w})`;break;case"object":Y=v._`${w} && typeof ${w} == "object" && !Array.isArray(${w})`;break;case"integer":Y=G(v._`!(${w} % 1) && !isNaN(${w})`);break;case"number":Y=G();break;default:return v._`typeof ${w} ${X} ${$}`}return Z===p1.Correct?Y:(0,v.not)(Y);function G(J=v.nil){return(0,v.and)(v._`typeof ${w} == "number"`,J,W?v._`isFinite(${w})`:v.nil)}}d3.checkDataType=mW;function lW($,w,W,Z){if($.length===1)return mW($[0],w,W,Z);let X,Y=(0,m3.toHash)($);if(Y.array&&Y.object){let G=v._`typeof ${w} != "object"`;X=Y.null?G:v._`!${w} || ${G}`,delete Y.null,delete Y.array,delete Y.object}else X=v.nil;if(Y.number)delete Y.integer;for(let G in Y)X=(0,v.and)(X,mW(G,w,W,Z));return X}d3.checkDataTypes=lW;var _K={message:({schema:$})=>`must be ${$}`,params:({schema:$,schemaValue:w})=>typeof $=="string"?v._`{type: ${$}}`:v._`{type: ${w}}`};function cW($){let w=gK($);(0,CK.reportError)(w,_K)}d3.reportTypeError=cW;function gK($){let{gen:w,data:W,schema:Z}=$,X=(0,m3.schemaRefOrVal)($,Z,"type");return{gen:w,keyword:"type",data:W,schema:Z.type,schemaCode:X,schemaValue:X,parentSchema:Z,params:{},it:$}}});var s3=L((t3)=>{Object.defineProperty(t3,"__esModule",{value:!0});t3.assignDefaults=void 0;var t1=h(),cK=c();function dK($,w){let{properties:W,items:Z}=$.schema;if(w==="object"&&W)for(let X in W)p3($,X,W[X].default);else if(w==="array"&&Array.isArray(Z))Z.forEach((X,Y)=>p3($,Y,X.default))}t3.assignDefaults=dK;function p3($,w,W){let{gen:Z,compositeRule:X,data:Y,opts:G}=$;if(W===void 0)return;let J=t1._`${Y}${(0,t1.getProperty)(w)}`;if(X){(0,cK.checkStrictMode)($,`default is ignored for: ${J}`);return}let T=t1._`${J} === undefined`;if(G.useDefaults==="empty")T=t1._`${T} || ${J} === null || ${J} === ""`;Z.if(T,t1._`${J} = ${(0,t1.stringify)(W)}`)}});var h0=L((e3)=>{Object.defineProperty(e3,"__esModule",{value:!0});e3.validateUnion=e3.validateArray=e3.usePattern=e3.callValidateCode=e3.schemaProperties=e3.allSchemaProperties=e3.noPropertyInData=e3.propertyInData=e3.isOwnProperty=e3.hasPropFunc=e3.reportMissingProp=e3.checkMissingProp=e3.checkReportMissingProp=void 0;var a=h(),dW=c(),_$=B$(),nK=c();function pK($,w){let{gen:W,data:Z,it:X}=$;W.if(pW(W,Z,w,X.opts.ownProperties),()=>{$.setParams({missingProperty:a._`${w}`},!0),$.error()})}e3.checkReportMissingProp=pK;function tK({gen:$,data:w,it:{opts:W}},Z,X){return(0,a.or)(...Z.map((Y)=>(0,a.and)(pW($,w,Y,W.ownProperties),a._`${X} = ${Y}`)))}e3.checkMissingProp=tK;function rK($,w){$.setParams({missingProperty:w},!0),$.error()}e3.reportMissingProp=rK;function a3($){return $.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:a._`Object.prototype.hasOwnProperty`})}e3.hasPropFunc=a3;function nW($,w,W){return a._`${a3($)}.call(${w}, ${W})`}e3.isOwnProperty=nW;function sK($,w,W,Z){let X=a._`${w}${(0,a.getProperty)(W)} !== undefined`;return Z?a._`${X} && ${nW($,w,W)}`:X}e3.propertyInData=sK;function pW($,w,W,Z){let X=a._`${w}${(0,a.getProperty)(W)} === undefined`;return Z?(0,a.or)(X,(0,a.not)(nW($,w,W))):X}e3.noPropertyInData=pW;function o3($){return $?Object.keys($).filter((w)=>w!=="__proto__"):[]}e3.allSchemaProperties=o3;function aK($,w){return o3(w).filter((W)=>!(0,dW.alwaysValidSchema)($,w[W]))}e3.schemaProperties=aK;function oK({schemaCode:$,data:w,it:{gen:W,topSchemaRef:Z,schemaPath:X,errorPath:Y},it:G},J,T,Q){let M=Q?a._`${$}, ${w}, ${Z}${X}`:w,z=[[_$.default.instancePath,(0,a.strConcat)(_$.default.instancePath,Y)],[_$.default.parentData,G.parentData],[_$.default.parentDataProperty,G.parentDataProperty],[_$.default.rootData,_$.default.rootData]];if(G.opts.dynamicRef)z.push([_$.default.dynamicAnchors,_$.default.dynamicAnchors]);let N=a._`${M}, ${W.object(...z)}`;return T!==a.nil?a._`${J}.call(${T}, ${N})`:a._`${J}(${N})`}e3.callValidateCode=oK;var eK=a._`new RegExp`;function $B({gen:$,it:{opts:w}},W){let Z=w.unicodeRegExp?"u":"",{regExp:X}=w.code,Y=X(W,Z);return $.scopeValue("pattern",{key:Y.toString(),ref:Y,code:a._`${X.code==="new RegExp"?eK:(0,nK.useFunc)($,X)}(${W}, ${Z})`})}e3.usePattern=$B;function wB($){let{gen:w,data:W,keyword:Z,it:X}=$,Y=w.name("valid");if(X.allErrors){let J=w.let("valid",!0);return G(()=>w.assign(J,!1)),J}return w.var(Y,!0),G(()=>w.break()),Y;function G(J){let T=w.const("len",a._`${W}.length`);w.forRange("i",0,T,(Q)=>{$.subschema({keyword:Z,dataProp:Q,dataPropType:dW.Type.Num},Y),w.if((0,a.not)(Y),J)})}}e3.validateArray=wB;function WB($){let{gen:w,schema:W,keyword:Z,it:X}=$;if(!Array.isArray(W))throw Error("ajv implementation error");if(W.some((T)=>(0,dW.alwaysValidSchema)(X,T))&&!X.opts.unevaluated)return;let G=w.let("valid",!1),J=w.name("_valid");w.block(()=>W.forEach((T,Q)=>{let M=$.subschema({keyword:Z,schemaProp:Q,compositeRule:!0},J);if(w.assign(G,a._`${G} || ${J}`),!$.mergeValidEvaluated(M,J))w.if((0,a.not)(G))})),$.result(G,()=>$.reset(),()=>$.error(!0))}e3.validateUnion=WB});var YY=L((ZY)=>{Object.defineProperty(ZY,"__esModule",{value:!0});ZY.validateKeywordUsage=ZY.validSchemaType=ZY.funcKeywordCode=ZY.macroKeywordCode=void 0;var E0=h(),X1=B$(),PB=h0(),VB=pw();function fB($,w){let{gen:W,keyword:Z,schema:X,parentSchema:Y,it:G}=$,J=w.macro.call(G.self,X,Y,G),T=WY(W,Z,J);if(G.opts.validateSchema!==!1)G.self.validateSchema(J,!0);let Q=W.name("valid");$.subschema({schema:J,schemaPath:E0.nil,errSchemaPath:`${G.errSchemaPath}/${Z}`,topSchemaRef:T,compositeRule:!0},Q),$.pass(Q,()=>$.error(!0))}ZY.macroKeywordCode=fB;function qB($,w){var W;let{gen:Z,keyword:X,schema:Y,parentSchema:G,$data:J,it:T}=$;HB(T,w);let Q=!J&&w.compile?w.compile.call(T.self,Y,G,T):w.validate,M=WY(Z,X,Q),z=Z.let("valid");$.block$data(z,N),$.ok((W=w.valid)!==null&&W!==void 0?W:z);function N(){if(w.errors===!1){if(P(),w.modifying)wY($);q(()=>$.error())}else{let f=w.async?B():K();if(w.modifying)wY($);q(()=>UB($,f))}}function B(){let f=Z.let("ruleErrs",null);return Z.try(()=>P(E0._`await `),(H)=>Z.assign(z,!1).if(E0._`${H} instanceof ${T.ValidationError}`,()=>Z.assign(f,E0._`${H}.errors`),()=>Z.throw(H))),f}function K(){let f=E0._`${M}.errors`;return Z.assign(f,null),P(E0.nil),f}function P(f=w.async?E0._`await `:E0.nil){let H=T.opts.passContext?X1.default.this:X1.default.self,E=!(("compile"in w)&&!J||w.schema===!1);Z.assign(z,E0._`${f}${(0,PB.callValidateCode)($,M,H,E)}`,w.modifying)}function q(f){var H;Z.if((0,E0.not)((H=w.valid)!==null&&H!==void 0?H:z),f)}}ZY.funcKeywordCode=qB;function wY($){let{gen:w,data:W,it:Z}=$;w.if(Z.parentData,()=>w.assign(W,E0._`${Z.parentData}[${Z.parentDataProperty}]`))}function UB($,w){let{gen:W}=$;W.if(E0._`Array.isArray(${w})`,()=>{W.assign(X1.default.vErrors,E0._`${X1.default.vErrors} === null ? ${w} : ${X1.default.vErrors}.concat(${w})`).assign(X1.default.errors,E0._`${X1.default.vErrors}.length`),(0,VB.extendErrors)($)},()=>$.error())}function HB({schemaEnv:$},w){if(w.async&&!$.$async)throw Error("async keyword in sync schema")}function WY($,w,W){if(W===void 0)throw Error(`keyword "${w}" failed to compile`);return $.scopeValue("keyword",typeof W=="function"?{ref:W}:{ref:W,code:(0,E0.stringify)(W)})}function FB($,w,W=!1){return!w.length||w.some((Z)=>Z==="array"?Array.isArray($):Z==="object"?$&&typeof $=="object"&&!Array.isArray($):typeof $==Z||W&&typeof $>"u")}ZY.validSchemaType=FB;function OB({schema:$,opts:w,self:W,errSchemaPath:Z},X,Y){if(Array.isArray(X.keyword)?!X.keyword.includes(Y):X.keyword!==Y)throw Error("ajv implementation error");let G=X.dependencies;if(G===null||G===void 0?void 0:G.some((J)=>!Object.prototype.hasOwnProperty.call($,J)))throw Error(`parent schema must have dependencies of ${Y}: ${G.join(",")}`);if(X.validateSchema){if(!X.validateSchema($[Y])){let T=`keyword "${Y}" value is invalid at path "${Z}": `+W.errorsText(X.validateSchema.errors);if(w.validateSchema==="log")W.logger.error(T);else throw Error(T)}}}ZY.validateKeywordUsage=OB});var QY=L((JY)=>{Object.defineProperty(JY,"__esModule",{value:!0});JY.extendSubschemaMode=JY.extendSubschemaData=JY.getSubschema=void 0;var w$=h(),GY=c();function kB($,{keyword:w,schemaProp:W,schema:Z,schemaPath:X,errSchemaPath:Y,topSchemaRef:G}){if(w!==void 0&&Z!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(w!==void 0){let J=$.schema[w];return W===void 0?{schema:J,schemaPath:w$._`${$.schemaPath}${(0,w$.getProperty)(w)}`,errSchemaPath:`${$.errSchemaPath}/${w}`}:{schema:J[W],schemaPath:w$._`${$.schemaPath}${(0,w$.getProperty)(w)}${(0,w$.getProperty)(W)}`,errSchemaPath:`${$.errSchemaPath}/${w}/${(0,GY.escapeFragment)(W)}`}}if(Z!==void 0){if(X===void 0||Y===void 0||G===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:Z,schemaPath:X,topSchemaRef:G,errSchemaPath:Y}}throw Error('either "keyword" or "schema" must be passed')}JY.getSubschema=kB;function AB($,w,{dataProp:W,dataPropType:Z,data:X,dataTypes:Y,propertyName:G}){if(X!==void 0&&W!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:J}=w;if(W!==void 0){let{errorPath:Q,dataPathArr:M,opts:z}=w,N=J.let("data",w$._`${w.data}${(0,w$.getProperty)(W)}`,!0);T(N),$.errorPath=w$.str`${Q}${(0,GY.getErrorPath)(W,Z,z.jsPropertySyntax)}`,$.parentDataProperty=w$._`${W}`,$.dataPathArr=[...M,$.parentDataProperty]}if(X!==void 0){let Q=X instanceof w$.Name?X:J.let("data",X,!0);if(T(Q),G!==void 0)$.propertyName=G}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]}}JY.extendSubschemaData=AB;function SB($,{jtdDiscriminator:w,jtdMetadata:W,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=W}JY.extendSubschemaMode=SB});var tW=L((Gk,MY)=>{MY.exports=function $(w,W){if(w===W)return!0;if(w&&W&&typeof w=="object"&&typeof W=="object"){if(w.constructor!==W.constructor)return!1;var Z,X,Y;if(Array.isArray(w)){if(Z=w.length,Z!=W.length)return!1;for(X=Z;X--!==0;)if(!$(w[X],W[X]))return!1;return!0}if(w.constructor===RegExp)return w.source===W.source&&w.flags===W.flags;if(w.valueOf!==Object.prototype.valueOf)return w.valueOf()===W.valueOf();if(w.toString!==Object.prototype.toString)return w.toString()===W.toString();if(Y=Object.keys(w),Z=Y.length,Z!==Object.keys(W).length)return!1;for(X=Z;X--!==0;)if(!Object.prototype.hasOwnProperty.call(W,Y[X]))return!1;for(X=Z;X--!==0;){var G=Y[X];if(!$(w[G],W[G]))return!1}return!0}return w!==w&&W!==W}});var NY=L((Jk,zY)=>{var g$=zY.exports=function($,w,W){if(typeof w=="function")W=w,w={};W=w.cb||W;var Z=typeof W=="function"?W:W.pre||function(){},X=W.post||function(){};f8(w,Z,X,$,"",$)};g$.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};g$.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};g$.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};g$.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 f8($,w,W,Z,X,Y,G,J,T,Q){if(Z&&typeof Z=="object"&&!Array.isArray(Z)){w(Z,X,Y,G,J,T,Q);for(var M in Z){var z=Z[M];if(Array.isArray(z)){if(M in g$.arrayKeywords)for(var N=0;N<z.length;N++)f8($,w,W,z[N],X+"/"+M+"/"+N,Y,X,M,Z,N)}else if(M in g$.propsKeywords){if(z&&typeof z=="object")for(var B in z)f8($,w,W,z[B],X+"/"+M+"/"+jB(B),Y,X,M,Z,B)}else if(M in g$.keywords||$.allKeys&&!(M in g$.skipKeywords))f8($,w,W,z,X+"/"+M,Y,X,M,Z)}W(Z,X,Y,G,J,T,Q)}}function jB($){return $.replace(/~/g,"~0").replace(/\//g,"~1")}});var rw=L((VY)=>{Object.defineProperty(VY,"__esModule",{value:!0});VY.getSchemaRefs=VY.resolveUrl=VY.normalizeId=VY._getFullPath=VY.getFullPath=VY.inlineRef=void 0;var yB=c(),IB=tW(),bB=NY(),xB=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function _B($,w=!0){if(typeof $=="boolean")return!0;if(w===!0)return!rW($);if(!w)return!1;return KY($)<=w}VY.inlineRef=_B;var gB=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function rW($){for(let w in $){if(gB.has(w))return!0;let W=$[w];if(Array.isArray(W)&&W.some(rW))return!0;if(typeof W=="object"&&rW(W))return!0}return!1}function KY($){let w=0;for(let W in $){if(W==="$ref")return 1/0;if(w++,xB.has(W))continue;if(typeof $[W]=="object")(0,yB.eachItem)($[W],(Z)=>w+=KY(Z));if(w===1/0)return 1/0}return w}function BY($,w="",W){if(W!==!1)w=r1(w);let Z=$.parse(w);return PY($,Z)}VY.getFullPath=BY;function PY($,w){return $.serialize(w).split("#")[0]+"#"}VY._getFullPath=PY;var vB=/#\/?$/;function r1($){return $?$.replace(vB,""):""}VY.normalizeId=r1;function uB($,w,W){return W=r1(W),$.resolve(w,W)}VY.resolveUrl=uB;var hB=/^[a-z_][-a-z0-9._]*$/i;function iB($,w){if(typeof $=="boolean")return{};let{schemaId:W,uriResolver:Z}=this.opts,X=r1($[W]||w),Y={"":X},G=BY(Z,X,!1),J={},T=new Set;return bB($,{allKeys:!0},(z,N,B,K)=>{if(K===void 0)return;let P=G+N,q=Y[K];if(typeof z[W]=="string")q=f.call(this,z[W]);H.call(this,z.$anchor),H.call(this,z.$dynamicAnchor),Y[N]=q;function f(E){let S=this.opts.uriResolver.resolve;if(E=r1(q?S(q,E):E),T.has(E))throw M(E);T.add(E);let A=this.refs[E];if(typeof A=="string")A=this.refs[A];if(typeof A=="object")Q(z,A.schema,E);else if(E!==r1(P))if(E[0]==="#")Q(z,J[E],E),J[E]=z;else this.refs[E]=P;return E}function H(E){if(typeof E=="string"){if(!hB.test(E))throw Error(`invalid anchor "${E}"`);f.call(this,`#${E}`)}}}),J;function Q(z,N,B){if(N!==void 0&&!IB(z,N))throw M(B)}function M(z){return Error(`reference "${z}" resolves to more than one schema`)}}VY.getSchemaRefs=iB});var ow=L((yY)=>{Object.defineProperty(yY,"__esModule",{value:!0});yY.getData=yY.KeywordCxt=yY.validateFunctionCode=void 0;var OY=x3(),qY=tw(),aW=iW(),q8=tw(),pB=s3(),aw=YY(),sW=QY(),R=h(),x=B$(),tB=rw(),P$=c(),sw=pw();function rB($){if(DY($)){if(kY($),LY($)){oB($);return}}EY($,()=>(0,OY.topBoolOrEmptySchema)($))}yY.validateFunctionCode=rB;function EY({gen:$,validateName:w,schema:W,schemaEnv:Z,opts:X},Y){if(X.code.es5)$.func(w,R._`${x.default.data}, ${x.default.valCxt}`,Z.$async,()=>{$.code(R._`"use strict"; ${UY(W,X)}`),aB($,X),$.code(Y)});else $.func(w,R._`${x.default.data}, ${sB(X)}`,Z.$async,()=>$.code(UY(W,X)).code(Y))}function sB($){return R._`{${x.default.instancePath}="", ${x.default.parentData}, ${x.default.parentDataProperty}, ${x.default.rootData}=${x.default.data}${$.dynamicRef?R._`, ${x.default.dynamicAnchors}={}`:R.nil}}={}`}function aB($,w){$.if(x.default.valCxt,()=>{if($.var(x.default.instancePath,R._`${x.default.valCxt}.${x.default.instancePath}`),$.var(x.default.parentData,R._`${x.default.valCxt}.${x.default.parentData}`),$.var(x.default.parentDataProperty,R._`${x.default.valCxt}.${x.default.parentDataProperty}`),$.var(x.default.rootData,R._`${x.default.valCxt}.${x.default.rootData}`),w.dynamicRef)$.var(x.default.dynamicAnchors,R._`${x.default.valCxt}.${x.default.dynamicAnchors}`)},()=>{if($.var(x.default.instancePath,R._`""`),$.var(x.default.parentData,R._`undefined`),$.var(x.default.parentDataProperty,R._`undefined`),$.var(x.default.rootData,x.default.data),w.dynamicRef)$.var(x.default.dynamicAnchors,R._`{}`)})}function oB($){let{schema:w,opts:W,gen:Z}=$;EY($,()=>{if(W.$comment&&w.$comment)SY($);if(ZP($),Z.let(x.default.vErrors,null),Z.let(x.default.errors,0),W.unevaluated)eB($);AY($),GP($)});return}function eB($){let{gen:w,validateName:W}=$;$.evaluated=w.const("evaluated",R._`${W}.evaluated`),w.if(R._`${$.evaluated}.dynamicProps`,()=>w.assign(R._`${$.evaluated}.props`,R._`undefined`)),w.if(R._`${$.evaluated}.dynamicItems`,()=>w.assign(R._`${$.evaluated}.items`,R._`undefined`))}function UY($,w){let W=typeof $=="object"&&$[w.schemaId];return W&&(w.code.source||w.code.process)?R._`/*# sourceURL=${W} */`:R.nil}function $P($,w){if(DY($)){if(kY($),LY($)){wP($,w);return}}(0,OY.boolOrEmptySchema)($,w)}function LY({schema:$,self:w}){if(typeof $=="boolean")return!$;for(let W in $)if(w.RULES.all[W])return!0;return!1}function DY($){return typeof $.schema!="boolean"}function wP($,w){let{schema:W,gen:Z,opts:X}=$;if(X.$comment&&W.$comment)SY($);XP($),YP($);let Y=Z.const("_errs",x.default.errors);AY($,Y),Z.var(w,R._`${Y} === ${x.default.errors}`)}function kY($){(0,P$.checkUnknownRules)($),WP($)}function AY($,w){if($.opts.jtd)return HY($,[],!1,w);let W=(0,qY.getSchemaTypes)($.schema),Z=(0,qY.coerceAndCheckDataType)($,W);HY($,W,!Z,w)}function WP($){let{schema:w,errSchemaPath:W,opts:Z,self:X}=$;if(w.$ref&&Z.ignoreKeywordsWithRef&&(0,P$.schemaHasRulesButRef)(w,X.RULES))X.logger.warn(`$ref: keywords ignored in schema at path "${W}"`)}function ZP($){let{schema:w,opts:W}=$;if(w.default!==void 0&&W.useDefaults&&W.strictSchema)(0,P$.checkStrictMode)($,"default is ignored in the schema root")}function XP($){let w=$.schema[$.opts.schemaId];if(w)$.baseId=(0,tB.resolveUrl)($.opts.uriResolver,$.baseId,w)}function YP($){if($.schema.$async&&!$.schemaEnv.$async)throw Error("async schema in sync schema")}function SY({gen:$,schemaEnv:w,schema:W,errSchemaPath:Z,opts:X}){let Y=W.$comment;if(X.$comment===!0)$.code(R._`${x.default.self}.logger.log(${Y})`);else if(typeof X.$comment=="function"){let G=R.str`${Z}/$comment`,J=$.scopeValue("root",{ref:w.root});$.code(R._`${x.default.self}.opts.$comment(${Y}, ${G}, ${J}.schema)`)}}function GP($){let{gen:w,schemaEnv:W,validateName:Z,ValidationError:X,opts:Y}=$;if(W.$async)w.if(R._`${x.default.errors} === 0`,()=>w.return(x.default.data),()=>w.throw(R._`new ${X}(${x.default.vErrors})`));else{if(w.assign(R._`${Z}.errors`,x.default.vErrors),Y.unevaluated)JP($);w.return(R._`${x.default.errors} === 0`)}}function JP({gen:$,evaluated:w,props:W,items:Z}){if(W instanceof R.Name)$.assign(R._`${w}.props`,W);if(Z instanceof R.Name)$.assign(R._`${w}.items`,Z)}function HY($,w,W,Z){let{gen:X,schema:Y,data:G,allErrors:J,opts:T,self:Q}=$,{RULES:M}=Q;if(Y.$ref&&(T.ignoreKeywordsWithRef||!(0,P$.schemaHasRulesButRef)(Y,M))){X.block(()=>CY($,"$ref",M.all.$ref.definition));return}if(!T.jtd)TP($,w);X.block(()=>{for(let N of M.rules)z(N);z(M.post)});function z(N){if(!(0,aW.shouldUseGroup)(Y,N))return;if(N.type){if(X.if((0,q8.checkDataType)(N.type,G,T.strictNumbers)),FY($,N),w.length===1&&w[0]===N.type&&W)X.else(),(0,q8.reportTypeError)($);X.endIf()}else FY($,N);if(!J)X.if(R._`${x.default.errors} === ${Z||0}`)}}function FY($,w){let{gen:W,schema:Z,opts:{useDefaults:X}}=$;if(X)(0,pB.assignDefaults)($,w.type);W.block(()=>{for(let Y of w.rules)if((0,aW.shouldUseRule)(Z,Y))CY($,Y.keyword,Y.definition,w.type)})}function TP($,w){if($.schemaEnv.meta||!$.opts.strictTypes)return;if(QP($,w),!$.opts.allowUnionTypes)MP($,w);zP($,$.dataTypes)}function QP($,w){if(!w.length)return;if(!$.dataTypes.length){$.dataTypes=w;return}w.forEach((W)=>{if(!RY($.dataTypes,W))oW($,`type "${W}" not allowed by context "${$.dataTypes.join(",")}"`)}),KP($,w)}function MP($,w){if(w.length>1&&!(w.length===2&&w.includes("null")))oW($,"use allowUnionTypes to allow union type keyword")}function zP($,w){let W=$.self.RULES.all;for(let Z in W){let X=W[Z];if(typeof X=="object"&&(0,aW.shouldUseRule)($.schema,X)){let{type:Y}=X.definition;if(Y.length&&!Y.some((G)=>NP(w,G)))oW($,`missing type "${Y.join(",")}" for keyword "${Z}"`)}}}function NP($,w){return $.includes(w)||w==="number"&&$.includes("integer")}function RY($,w){return $.includes(w)||w==="integer"&&$.includes("number")}function KP($,w){let W=[];for(let Z of $.dataTypes)if(RY(w,Z))W.push(Z);else if(w.includes("integer")&&Z==="number")W.push("integer");$.dataTypes=W}function oW($,w){let W=$.schemaEnv.baseId+$.errSchemaPath;w+=` at "${W}" (strictTypes)`,(0,P$.checkStrictMode)($,w,$.opts.strictTypes)}class eW{constructor($,w,W){if((0,aw.validateKeywordUsage)($,w,W),this.gen=$.gen,this.allErrors=$.allErrors,this.keyword=W,this.data=$.data,this.schema=$.schema[W],this.$data=w.$data&&$.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,P$.schemaRefOrVal)($,this.schema,W,this.$data),this.schemaType=w.schemaType,this.parentSchema=$.schema,this.params={},this.it=$,this.def=w,this.$data)this.schemaCode=$.gen.const("vSchema",jY(this.$data,$));else if(this.schemaCode=this.schemaValue,!(0,aw.validSchemaType)(this.schema,w.schemaType,w.allowUndefined))throw Error(`${W} 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,W){this.failResult((0,R.not)($),w,W)}failResult($,w,W){if(this.gen.if($),W)W();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,R.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(R._`${w} !== undefined && (${(0,R.or)(this.invalid$data(),$)})`)}error($,w,W){if(w){this.setParams(w),this._error($,W),this.setParams({});return}this._error($,W)}_error($,w){($?sw.reportExtraError:sw.reportError)(this,this.def.error,w)}$dataError(){(0,sw.reportError)(this,this.def.$dataError||sw.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,sw.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,W=R.nil){this.gen.block(()=>{this.check$data($,W),w()})}check$data($=R.nil,w=R.nil){if(!this.$data)return;let{gen:W,schemaCode:Z,schemaType:X,def:Y}=this;if(W.if((0,R.or)(R._`${Z} === undefined`,w)),$!==R.nil)W.assign($,!0);if(X.length||Y.validateSchema){if(W.elseIf(this.invalid$data()),this.$dataError(),$!==R.nil)W.assign($,!1)}W.else()}invalid$data(){let{gen:$,schemaCode:w,schemaType:W,def:Z,it:X}=this;return(0,R.or)(Y(),G());function Y(){if(W.length){if(!(w instanceof R.Name))throw Error("ajv implementation error");let J=Array.isArray(W)?W:[W];return R._`${(0,q8.checkDataTypes)(J,w,X.opts.strictNumbers,q8.DataType.Wrong)}`}return R.nil}function G(){if(Z.validateSchema){let J=$.scopeValue("validate$data",{ref:Z.validateSchema});return R._`!${J}(${w})`}return R.nil}}subschema($,w){let W=(0,sW.getSubschema)(this.it,$);(0,sW.extendSubschemaData)(W,this.it,$),(0,sW.extendSubschemaMode)(W,$);let Z={...this.it,...W,items:void 0,props:void 0};return $P(Z,w),Z}mergeEvaluated($,w){let{it:W,gen:Z}=this;if(!W.opts.unevaluated)return;if(W.props!==!0&&$.props!==void 0)W.props=P$.mergeEvaluated.props(Z,$.props,W.props,w);if(W.items!==!0&&$.items!==void 0)W.items=P$.mergeEvaluated.items(Z,$.items,W.items,w)}mergeValidEvaluated($,w){let{it:W,gen:Z}=this;if(W.opts.unevaluated&&(W.props!==!0||W.items!==!0))return Z.if(w,()=>this.mergeEvaluated($,R.Name)),!0}}yY.KeywordCxt=eW;function CY($,w,W,Z){let X=new eW($,W,w);if("code"in W)W.code(X,Z);else if(X.$data&&W.validate)(0,aw.funcKeywordCode)(X,W);else if("macro"in W)(0,aw.macroKeywordCode)(X,W);else if(W.compile||W.validate)(0,aw.funcKeywordCode)(X,W)}var BP=/^\/(?:[^~]|~0|~1)*$/,PP=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function jY($,{dataLevel:w,dataNames:W,dataPathArr:Z}){let X,Y;if($==="")return x.default.rootData;if($[0]==="/"){if(!BP.test($))throw Error(`Invalid JSON-pointer: ${$}`);X=$,Y=x.default.rootData}else{let Q=PP.exec($);if(!Q)throw Error(`Invalid JSON-pointer: ${$}`);let M=+Q[1];if(X=Q[2],X==="#"){if(M>=w)throw Error(T("property/index",M));return Z[w-M]}if(M>w)throw Error(T("data",M));if(Y=W[w-M],!X)return Y}let G=Y,J=X.split("/");for(let Q of J)if(Q)Y=R._`${Y}${(0,R.getProperty)((0,P$.unescapeJsonPointer)(Q))}`,G=R._`${G} && ${Y}`;return G;function T(Q,M){return`Cannot access ${Q} ${M} levels up, current level is ${w}`}}yY.getData=jY});var U8=L((xY)=>{Object.defineProperty(xY,"__esModule",{value:!0});class bY extends Error{constructor($){super("validation failed");this.errors=$,this.ajv=this.validation=!0}}xY.default=bY});var ew=L((gY)=>{Object.defineProperty(gY,"__esModule",{value:!0});var $5=rw();class _Y extends Error{constructor($,w,W,Z){super(Z||`can't resolve reference ${W} from id ${w}`);this.missingRef=(0,$5.resolveUrl)($,w,W),this.missingSchema=(0,$5.normalizeId)((0,$5.getFullPath)($,this.missingRef))}}gY.default=_Y});var F8=L((hY)=>{Object.defineProperty(hY,"__esModule",{value:!0});hY.resolveSchema=hY.getCompilingSchema=hY.resolveRef=hY.compileSchema=hY.SchemaEnv=void 0;var p0=h(),HP=U8(),Y1=B$(),t0=rw(),vY=c(),FP=ow();class $4{constructor($){var w;this.refs={},this.dynamicAnchors={};let W;if(typeof $.schema=="object")W=$.schema;this.schema=$.schema,this.schemaId=$.schemaId,this.root=$.root||this,this.baseId=(w=$.baseId)!==null&&w!==void 0?w:(0,t0.normalizeId)(W===null||W===void 0?void 0:W[$.schemaId||"$id"]),this.schemaPath=$.schemaPath,this.localRefs=$.localRefs,this.meta=$.meta,this.$async=W===null||W===void 0?void 0:W.$async,this.refs={}}}hY.SchemaEnv=$4;function W5($){let w=uY.call(this,$);if(w)return w;let W=(0,t0.getFullPath)(this.opts.uriResolver,$.root.baseId),{es5:Z,lines:X}=this.opts.code,{ownProperties:Y}=this.opts,G=new p0.CodeGen(this.scope,{es5:Z,lines:X,ownProperties:Y}),J;if($.$async)J=G.scopeValue("Error",{ref:HP.default,code:p0._`require("ajv/dist/runtime/validation_error").default`});let T=G.scopeName("validate");$.validateName=T;let Q={gen:G,allErrors:this.opts.allErrors,data:Y1.default.data,parentData:Y1.default.parentData,parentDataProperty:Y1.default.parentDataProperty,dataNames:[Y1.default.data],dataPathArr:[p0.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:G.scopeValue("schema",this.opts.code.source===!0?{ref:$.schema,code:(0,p0.stringify)($.schema)}:{ref:$.schema}),validateName:T,ValidationError:J,schema:$.schema,schemaEnv:$,rootId:W,baseId:$.baseId||W,schemaPath:p0.nil,errSchemaPath:$.schemaPath||(this.opts.jtd?"":"#"),errorPath:p0._`""`,opts:this.opts,self:this},M;try{this._compilations.add($),(0,FP.validateFunctionCode)(Q),G.optimize(this.opts.code.optimize);let z=G.toString();if(M=`${G.scopeRefs(Y1.default.scope)}return ${z}`,this.opts.code.process)M=this.opts.code.process(M,$);let B=Function(`${Y1.default.self}`,`${Y1.default.scope}`,M)(this,this.scope.get());if(this.scope.value(T,{ref:B}),B.errors=null,B.schema=$.schema,B.schemaEnv=$,$.$async)B.$async=!0;if(this.opts.code.source===!0)B.source={validateName:T,validateCode:z,scopeValues:G._values};if(this.opts.unevaluated){let{props:K,items:P}=Q;if(B.evaluated={props:K instanceof p0.Name?void 0:K,items:P instanceof p0.Name?void 0:P,dynamicProps:K instanceof p0.Name,dynamicItems:P instanceof p0.Name},B.source)B.source.evaluated=(0,p0.stringify)(B.evaluated)}return $.validate=B,$}catch(z){if(delete $.validate,delete $.validateName,M)this.logger.error("Error compiling schema, function code:",M);throw z}finally{this._compilations.delete($)}}hY.compileSchema=W5;function OP($,w,W){var Z;W=(0,t0.resolveUrl)(this.opts.uriResolver,w,W);let X=$.refs[W];if(X)return X;let Y=DP.call(this,$,W);if(Y===void 0){let G=(Z=$.localRefs)===null||Z===void 0?void 0:Z[W],{schemaId:J}=this.opts;if(G)Y=new $4({schema:G,schemaId:J,root:$,baseId:w})}if(Y===void 0)return;return $.refs[W]=EP.call(this,Y)}hY.resolveRef=OP;function EP($){if((0,t0.inlineRef)($.schema,this.opts.inlineRefs))return $.schema;return $.validate?$:W5.call(this,$)}function uY($){for(let w of this._compilations)if(LP(w,$))return w}hY.getCompilingSchema=uY;function LP($,w){return $.schema===w.schema&&$.root===w.root&&$.baseId===w.baseId}function DP($,w){let W;while(typeof(W=this.refs[w])=="string")w=W;return W||this.schemas[w]||H8.call(this,$,w)}function H8($,w){let W=this.opts.uriResolver.parse(w),Z=(0,t0._getFullPath)(this.opts.uriResolver,W),X=(0,t0.getFullPath)(this.opts.uriResolver,$.baseId,void 0);if(Object.keys($.schema).length>0&&Z===X)return w5.call(this,W,$);let Y=(0,t0.normalizeId)(Z),G=this.refs[Y]||this.schemas[Y];if(typeof G=="string"){let J=H8.call(this,$,G);if(typeof(J===null||J===void 0?void 0:J.schema)!=="object")return;return w5.call(this,W,J)}if(typeof(G===null||G===void 0?void 0:G.schema)!=="object")return;if(!G.validate)W5.call(this,G);if(Y===(0,t0.normalizeId)(w)){let{schema:J}=G,{schemaId:T}=this.opts,Q=J[T];if(Q)X=(0,t0.resolveUrl)(this.opts.uriResolver,X,Q);return new $4({schema:J,schemaId:T,root:$,baseId:X})}return w5.call(this,W,G)}hY.resolveSchema=H8;var kP=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function w5($,{baseId:w,schema:W,root:Z}){var X;if(((X=$.fragment)===null||X===void 0?void 0:X[0])!=="/")return;for(let J of $.fragment.slice(1).split("/")){if(typeof W==="boolean")return;let T=W[(0,vY.unescapeFragment)(J)];if(T===void 0)return;W=T;let Q=typeof W==="object"&&W[this.opts.schemaId];if(!kP.has(J)&&Q)w=(0,t0.resolveUrl)(this.opts.uriResolver,w,Q)}let Y;if(typeof W!="boolean"&&W.$ref&&!(0,vY.schemaHasRulesButRef)(W,this.RULES)){let J=(0,t0.resolveUrl)(this.opts.uriResolver,w,W.$ref);Y=H8.call(this,Z,J)}let{schemaId:G}=this.opts;if(Y=Y||new $4({schema:W,schemaId:G,root:Z,baseId:w}),Y.schema!==Y.root.schema)return Y;return}});var mY=L((Kk,jP)=>{jP.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 T5=L((Bk,rY)=>{var yP=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),X5=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),G1=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Y5=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),cY=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),G5=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),IP=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 V0($){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 bP($){let w="",W=0,Z=0;for(Z=0;Z<$.length;Z++){if(W=$[Z].charCodeAt(0),W===48)continue;if(!(W>=48&&W<=57||W>=65&&W<=70||W>=97&&W<=102))return"";w+=$[Z];break}for(Z+=1;Z<$.length;Z++){if(W=$[Z].charCodeAt(0),!(W>=48&&W<=57||W>=65&&W<=70||W>=97&&W<=102))return"";w+=$[Z]}return w}var xP=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),_P=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),gP=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),vP=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function uP($){if($.length===0)return!1;for(let w=0;w<$.length;w++){if(gP($[w]))continue;if($[w]==="%"&&w+2<$.length&&G1($.slice(w+1,w+3))){w+=2;continue}return!1}return!0}function lY($){let w=-1,W=0,Z=-1,X=0;for(let J=0;J<$.length;J++)if($[J]==="0"){if(Z===-1)Z=J;if(X++,X>W)W=X,w=Z}else Z=-1,X=0;if(W<2)return $.join(":");let Y=$.slice(0,w).join(":"),G=$.slice(w+W).join(":");return Y+"::"+G}function hP($){let w=$.indexOf("::");if(w!==-1&&$.indexOf("::",w+1)!==-1)return;let W=w===-1?$.split(":"):$.slice(0,w).split(":"),Z=w===-1?[]:$.slice(w+2).split(":");if(w!==-1){if(W.length===1&&W[0]==="")W.length=0;if(Z.length===1&&Z[0]==="")Z.length=0}let X=W.concat(Z),Y=0;for(let J=0;J<X.length;J++){let T=X[J];if(T==="")return;if(T.indexOf(".")!==-1){if(J!==X.length-1||w!==-1&&Z.length===0||!X5(T))return;Y+=2;continue}if(!xP(T))return;X[J]=parseInt(T,16).toString(16),Y++}if(w===-1){if(Y!==8)return;return lY(X)}if(Y>=8)return;let G=X.slice(0,W.length);for(let J=Y;J<8;J++)G.push("0");for(let J=W.length;J<X.length;J++)G.push(X[J]);return lY(G)}function Z5($){let w=$[0]==="["&&$[$.length-1]==="]";if(($[0]==="["||$[$.length-1]==="]")&&!w)return{host:$,isIPV6:!1,error:!0};let Z=w?$.slice(1,-1):$;if(w&&_P(Z))return Z=Z.toLowerCase(),{host:`[${Z}]`,escapedHost:Z,isIPV6:!1,isIPVFuture:!0};if(iP(Z,":")<2)return{host:$,isIPV6:!1,error:w};let X="",Y=Z.indexOf("%");if(Y!==-1){let J=Z.slice(Y,Y+3).toLowerCase()==="%25"?3:1;if(X=Z.slice(Y+J),!uP(X))return{host:$,isIPV6:!1,error:!0};Z=Z.slice(0,Y)}let G=hP(Z);if(G===void 0)return{host:$,isIPV6:!1,error:!0};return{host:G+(X?"%"+X:""),escapedHost:G+(X?"%25"+X:""),isIPV6:!0}}function iP($,w){let W=0;for(let Z=0;Z<$.length;Z++)if($[Z]===w)W++;return W}function mP($){let w=$,W=[],Z=-1,X=0;while(X=w.length){if(X===1)if(w===".")break;else if(w==="/"){W.push("/");break}else{W.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]==="/"){W.push("/");break}}}else if(X===3){if(w==="/.."){if(W.length!==0)W.pop();W.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),W.length!==0)W.pop();continue}}}}if((Z=w.indexOf("/",1))===-1){W.push(w);break}else W.push(w.slice(0,Z)),w=w.slice(Z)}return W.join("")}var lP={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},cP=/[@/?#:]/g,dP=/[@/?#]/g;function dY($,w){let W=w?dP:cP;return W.lastIndex=0,$.replace(W,(Z)=>lP[Z])}function nY($,w=!1){if($.indexOf("%")===-1)return $;let W="";for(let Z=0;Z<$.length;Z++){if($[Z]==="%"&&Z+2<$.length){let X=$.slice(Z+1,Z+3);if(G1(X)){let Y=X.toUpperCase(),G=String.fromCharCode(parseInt(Y,16));if(w&&Y5(G))W+=G;else W+="%"+Y;Z+=2;continue}}W+=$[Z]}return W}function nP($){let w="";for(let W=0;W<$.length;W++){let Z=$[W];if(Z==="%"&&W+2<$.length){let X=$.slice(W+1,W+3);if(G1(X)){let Y=X.toUpperCase(),G=String.fromCharCode(parseInt(Y,16));if(G!=="."&&Y5(G))w+=G;else w+="%"+Y;W+=2;continue}}if(cY(Z))w+=Z;else{let X=$.charCodeAt(W);if(X<128)w+=tY(X)?Z:A0[X];else if(X<55296||X>57343)w+=V0(X);else if(X<=56319&&W+1<$.length){let Y=$.charCodeAt(W+1);if(Y>=56320&&Y<=57343)w+=V0(65536+(X-55296<<10)+(Y-56320)),W++;else w+=V0(65533)}else w+=V0(65533)}}return w}function pP($,w=!1){let W="",Z=w&&$[0]!=="/";for(let X=0;X<$.length;X++){let Y=$[X];if(Y==="%"&&X+2<$.length){let G=$.slice(X+1,X+3);if(G1(G)){W+="%"+G.toUpperCase(),X+=2;continue}}if(Y==="/")Z=!1;if(cY(Y)&&(Y!==":"||!Z))W+=Y;else{let G=$.charCodeAt(X);if(G<128)W+=A0[G];else if(G<55296||G>57343)W+=V0(G);else if(G<=56319&&X+1<$.length){let J=$.charCodeAt(X+1);if(J>=56320&&J<=57343)W+=V0(65536+(G-55296<<10)+(J-56320)),X++;else W+=V0(65533)}else W+=V0(65533)}}return W}function J5($,w){let W="";for(let Z=0;Z<$.length;Z++){let X=$[Z];if(X==="%"&&Z+2<$.length){let Y=$.slice(Z+1,Z+3);if(G1(Y)){W+="%"+Y.toUpperCase(),Z+=2;continue}}if(w(X))W+=X;else{let Y=$.charCodeAt(Z);if(Y<128)W+=A0[Y];else if(Y<55296||Y>57343)W+=V0(Y);else if(Y<=56319&&Z+1<$.length){let G=$.charCodeAt(Z+1);if(G>=56320&&G<=57343)W+=V0(65536+(Y-55296<<10)+(G-56320)),Z++;else W+=V0(65533)}else W+=V0(65533)}}return W}function pY($){return J5($,IP)}function tP($){return J5($,G5)}function rP($){return J5($,G5)}function tY($){return $>=48&&$<=57||$>=65&&$<=90||$>=97&&$<=122||$===42||$===43||$===45||$===46||$===47||$===64||$===95}function sP($){let w="";for(let W=0;W<$.length;W++){let Z=$[W];if(Z==="%"&&W+2<$.length){let X=$.slice(W+1,W+3);if(G1(X)){let Y=X.toUpperCase(),G=String.fromCharCode(parseInt(Y,16));if(Y5(G))w+=G;else w+="%"+Y;W+=2;continue}}if(G5(Z))w+=Z;else{let X=$.charCodeAt(W);if(X<128)w+=tY(X)?Z:A0[X];else if(X<55296||X>57343)w+=V0(X);else if(X<=56319&&W+1<$.length){let Y=$.charCodeAt(W+1);if(Y>=56320&&Y<=57343)w+=V0(65536+(X-55296<<10)+(Y-56320)),W++;else w+=V0(65533)}else w+=V0(65533)}}return w}function aP($){let w="";for(let W=0;W<$.length;W++){if($[W]==="%"&&W+2<$.length){let Z=$.slice(W+1,W+3);if(G1(Z)){w+="%"+Z.toUpperCase(),W+=2;continue}}w+=escape($[W])}return w}function oP($){let w=[];if($.userinfo!==void 0)w.push(pY($.userinfo)),w.push("@");if($.host!==void 0){let W=$.host;if(!X5(W)){let Z=Z5(W);if(Z.isIPV6!==!0&&Z.isIPVFuture!==!0)W=nY(W,!0),Z=Z5(W);if(Z.isIPV6===!0||Z.isIPVFuture===!0)W=`[${Z.escapedHost}]`;else W=dY(W,!1)}w.push(W)}if(typeof $.port==="number"||typeof $.port==="string")w.push(":"),w.push(String($.port));return w.length?w.join(""):void 0}rY.exports={nonSimpleDomain:vP,recomposeAuthority:oP,reescapeHostDelimiters:dY,normalizePercentEncoding:nY,normalizePathEncoding:nP,serializePathEncoding:pP,normalizeQueryFragmentEncoding:sP,encodeUserinfo:pY,encodeQuery:tP,encodeFragment:rP,escapePreservingEscapes:aP,removeDotSegments:mP,isIPv4:X5,isUUID:yP,normalizeIPv6:Z5,stringArrayToHexStripped:bP}});var $G=L((Pk,eY)=>{var{isUUID:eP}=T5(),$V=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,wV=["http","https","ws","wss","urn","urn:uuid"];function WV($){return wV.indexOf($)!==-1}function Q5($){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 sY($){if(!$.host)$.error=$.error||"HTTP URIs must have a host.";return $}function aY($){let w=String($.scheme).toLowerCase()==="https";if($.port===(w?443:80)||$.port==="")$.port=void 0;if(!$.path)$.path="/";return $}function ZV($){return $.secure=Q5($),$.resourceName=($.path||"/")+($.query?"?"+$.query:""),$.path=void 0,$.query=void 0,$}function XV($){if($.port===(Q5($)?443:80)||$.port==="")$.port=void 0;if(typeof $.secure==="boolean")$.scheme=$.secure?"wss":"ws",$.secure=void 0;if($.resourceName){let w=$.resourceName.indexOf("?"),W=w===-1?$.resourceName:$.resourceName.slice(0,w);$.path=W&&W!=="/"?W:void 0,$.query=w===-1?void 0:$.resourceName.slice(w+1),$.resourceName=void 0}return $.fragment=void 0,$}function YV($,w){if(!$.path)return $.error="URN can not be parsed",$;let W=$.path.match($V);if(W&&W[0]===$.path){let Z=w.scheme||$.scheme||"urn";$.nid=W[1].toLowerCase(),$.nss=W[2];let X=`${Z}:${w.nid||$.nid}`,Y=M5(X);if($.path=void 0,Y)$=Y.parse($,w)}else $.error=$.error||"URN can not be parsed.";return $}function GV($,w){if($.nid===void 0)throw Error("URN without nid cannot be serialized");let W=w.scheme||$.scheme||"urn",Z=$.nid.toLowerCase(),X=`${W}:${w.nid||Z}`,Y=M5(X);if(Y)$=Y.serialize($,w);let G=$,J=$.nss;return G.path=`${Z||w.nid}:${J}`,w.skipEscape=!0,G}function JV($,w){let W=$;if(W.uuid=W.nss,W.nss=void 0,!w.tolerant&&(!W.uuid||!eP(W.uuid)))W.error=W.error||"UUID is not valid.";return W}function TV($){let w=$;return w.nss=($.uuid||"").toLowerCase(),w}var oY={scheme:"http",domainHost:!0,parse:sY,serialize:aY},QV={scheme:"https",domainHost:oY.domainHost,parse:sY,serialize:aY},O8={scheme:"ws",domainHost:!0,parse:ZV,serialize:XV},MV={scheme:"wss",domainHost:O8.domainHost,parse:O8.parse,serialize:O8.serialize},zV={scheme:"urn",parse:YV,serialize:GV,skipNormalize:!0},NV={scheme:"urn:uuid",parse:JV,serialize:TV,skipNormalize:!0},E8={http:oY,https:QV,ws:O8,wss:MV,urn:zV,"urn:uuid":NV};Object.setPrototypeOf(E8,null);function M5($){return $&&(E8[$]||E8[$.toLowerCase()])||void 0}eY.exports={wsIsSecure:Q5,SCHEMES:E8,isValidSchemeName:WV,getSchemeHandler:M5}});var KG=L((Vk,k8)=>{var{normalizeIPv6:YG,removeDotSegments:W4,recomposeAuthority:KV,normalizePercentEncoding:GG,normalizePathEncoding:BV,serializePathEncoding:wG,normalizeQueryFragmentEncoding:WG,encodeQuery:PV,encodeFragment:VV,reescapeHostDelimiters:fV,isIPv4:JG,nonSimpleDomain:qV}=T5(),{SCHEMES:TG,getSchemeHandler:z5}=$G(),QG=/^[A-Za-z][A-Za-z0-9+.-]*$/u;function ZG($){let w=unescape(String($));if(!QG.test(w))throw TypeError("URI scheme is malformed.");return w}function UV($,w){if(typeof $==="string")$=AV($,w);else if(typeof $==="object")$=D8(J1($,w),w);return $}function HV($,w,W){let Z=W?Object.assign({scheme:"null"},W):{scheme:"null"},{parsed:X,malformedAuthorityOrPort:Y,malformedPercentEncoding:G,malformedSchemeSpecific:J,malformedHost:T,malformedScheme:Q}=L8($,Z),{parsed:M,malformedAuthorityOrPort:z,malformedPercentEncoding:N,malformedSchemeSpecific:B,malformedHost:K,malformedScheme:P}=L8(w,Z);if(Y||z||G||N||J||B||T||K||Q||P)throw Error(X.error||M.error||"URI is malformed.");let q=MG(X,M,Z,!0),f=z5(W&&W.scheme||q.scheme),H=q.host,E=H!==void 0&&H!==""&&(JG(H)||YG(H).isIPV6);zG(q,W||{},f,E);let S=H&&H.indexOf("%")!==-1&&!/\P{ASCII}/u.test(H);if(q.error&&!S)throw Error(q.error);return Z.skipEscape=!0,J1(q,Z)}function MG($,w,W,Z){let X={};if(!Z)$=D8(J1($,W),W),w=D8(J1(w,W),W);if(W=W||{},!W.tolerant&&w.scheme)X.scheme=w.scheme,X.userinfo=w.userinfo,X.host=w.host,X.port=w.port,X.path=W4(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=W4(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=W4(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=W4(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 FV($,w,W){let Z=XG($,W),X=XG(w,W);return Z!==void 0&&X!==void 0&&Z===X}function J1($,w){let W={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(W.scheme)W.scheme=ZG(W.scheme);let Y=z5(Z.scheme||W.scheme);if(Y&&Y.serialize)Y.serialize(W,Z);let G=W.userinfo!==void 0||W.host!==void 0||W.port!==void 0,J=!Z.skipEscape&&W.scheme===void 0&&!G;if(W.path!==void 0)if(!Z.skipEscape)W.path=wG(W.path,J);else W.path=GG(W.path);if(Z.reference!=="suffix"&&W.scheme)W.scheme=ZG(W.scheme),X.push(W.scheme,":");let T=KV(W);if(T!==void 0){if(Z.reference!=="suffix")X.push("//");if(X.push(T),W.path&&W.path[0]!=="/")X.push("/")}if(W.path!==void 0){let Q=W.path;if(!Z.absolutePath&&(!Y||!Y.absolutePath))Q=W4(Q);if(J)Q=wG(Q,!0);if(T===void 0&&Q[0]==="/"&&Q[1]==="/")Q="/%2F"+Q.slice(2);X.push(Q)}if(W.query!==void 0)X.push("?",PV(W.query));if(W.fragment!==void 0)X.push("#",VV(W.fragment));return X.join("")}var OV=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,EV=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,LV=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function DV($,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 w4($){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 kV($){let w=$[4];return w4($[3])||w!==void 0&&!(w[0]==="["&&w[w.length-1]==="]")&&w4(w)||w4($[6])||w4($[7])||w4($[8])}function zG($,w,W,Z){if(!w.unicodeSupport&&(!W||!W.unicodeSupport)&&$.host&&$.host[0]!=="["&&(w.domainHost||W&&W.domainHost)&&Z===!1&&qV($.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 L8($,w){let W=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,G=!1,J=!1,T=!1,Q=!1,M=!1;if(W.reference==="suffix")if(W.scheme)$=W.scheme+":"+$;else $="//"+$;let z=$.match(EV);if(z!==null&&z[1].indexOf("\\")!==-1)Z.error="URI authority must not contain a literal backslash.",X=!0;let N=$.match(LV);if(N!==null){let K=N[1],P=K.replace(/[\t\n\r]/g,"");if(P.length>=2){if(P.slice(0,2)!=="//")Z.error=Z.error||"URI authority must not contain a literal backslash.",X=!0;else if(K.length!==P.length)Z.error=Z.error||"URI authority introducer must not contain whitespace.",X=!0}}let B=$.match(OV);if(B){if(Z.scheme=B[1],Z.userinfo=B[3],Z.host=B[4],Z.port=parseInt(B[5],10),Z.path=B[6]||"",Z.query=B[7],Z.fragment=B[8],Z.scheme!==void 0){let q=unescape(Z.scheme);if(QG.test(q))Z.scheme=q.toLowerCase();else Z.error=Z.error||"URI scheme is malformed.",Q=!0}if(Y=kV(B),Y)Z.error=Z.error||"URI contains malformed percent-encoding.";if(isNaN(Z.port))Z.port=B[5];let K=DV(Z,B);if(K!==void 0)Z.error=Z.error||K,X=!0;if(Z.host)if(JG(Z.host)===!1){let f=Z.host[0]==="["&&Z.host[Z.host.length-1]==="]",H=YG(Z.host);if(M=H.isIPV6||H.isIPVFuture===!0,T=f&&H.error===!0,Z.host=M?H.host:H.host.toLowerCase(),T)Z.error=Z.error||"URI host is malformed.",X=!0}else M=!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(W.reference&&W.reference!=="suffix"&&W.reference!==Z.reference)Z.error=Z.error||"URI is not a "+W.reference+" reference.";let P=z5(W.scheme||Z.scheme);if(J=zG(Z,W,P,M),!P||P&&!P.skipNormalize){if($.indexOf("%")!==-1){if(Z.host!==void 0&&!T){let q=M?Z.host:GG(Z.host,!0);Z.host=fV(q,M)}}if(Z.path)Z.path=BV(Z.path);if(Z.query)Z.query=WG(Z.query);if(Z.fragment)Z.fragment=WG(Z.fragment)}if(P&&P.parse){if(P.parse(Z,W),P===TG.urn&&Z.nid===void 0)G=!0}}else Z.error=Z.error||"URI can not be parsed.";return{parsed:Z,malformedAuthorityOrPort:X,malformedPercentEncoding:Y,malformedSchemeSpecific:G,malformedHost:J,malformedScheme:Q}}function D8($,w){return L8($,w).parsed}function AV($,w){return NG($,w).normalized}function NG($,w){let{parsed:W,malformedAuthorityOrPort:Z,malformedPercentEncoding:X,malformedSchemeSpecific:Y,malformedHost:G,malformedScheme:J}=L8($,w);return{normalized:Z||X||Y||G||J?$:J1(W,w),malformedAuthorityOrPort:Z,malformedPercentEncoding:X,malformedSchemeSpecific:Y,malformedHost:G,malformedScheme:J}}function XG($,w){if(typeof $!=="string"&&typeof $!=="object")return;let W;try{W=typeof $==="string"?$:J1($,w)}catch{return}let{normalized:Z,malformedAuthorityOrPort:X,malformedPercentEncoding:Y,malformedSchemeSpecific:G,malformedHost:J,malformedScheme:T}=NG(W,w);return X||Y||G||J||T?void 0:Z}var N5={SCHEMES:TG,normalize:UV,resolve:HV,resolveComponent:MG,equal:FV,serialize:J1,parse:D8};k8.exports=N5;k8.exports.default=N5;k8.exports.fastUri=N5});var VG=L((PG)=>{Object.defineProperty(PG,"__esModule",{value:!0});var BG=KG();BG.code='require("ajv/dist/runtime/uri").default';PG.default=BG});var LG=L((V$)=>{Object.defineProperty(V$,"__esModule",{value:!0});V$.CodeGen=V$.Name=V$.nil=V$.stringify=V$.str=V$._=V$.KeywordCxt=void 0;var RV=ow();Object.defineProperty(V$,"KeywordCxt",{enumerable:!0,get:function(){return RV.KeywordCxt}});var s1=h();Object.defineProperty(V$,"_",{enumerable:!0,get:function(){return s1._}});Object.defineProperty(V$,"str",{enumerable:!0,get:function(){return s1.str}});Object.defineProperty(V$,"stringify",{enumerable:!0,get:function(){return s1.stringify}});Object.defineProperty(V$,"nil",{enumerable:!0,get:function(){return s1.nil}});Object.defineProperty(V$,"Name",{enumerable:!0,get:function(){return s1.Name}});Object.defineProperty(V$,"CodeGen",{enumerable:!0,get:function(){return s1.CodeGen}});var CV=U8(),FG=ew(),jV=hW(),Z4=F8(),yV=h(),X4=rw(),A8=tw(),B5=c(),fG=mY(),IV=VG(),OG=($,w)=>new RegExp($,w);OG.code="new RegExp";var bV=["removeAdditional","useDefaults","coerceTypes"],xV=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),_V={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."},gV={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},qG=200;function vV($){var w,W,Z,X,Y,G,J,T,Q,M,z,N,B,K,P,q,f,H,E,S,A,j,g,s,e;let i=$.strict,F0=(w=$.code)===null||w===void 0?void 0:w.optimize,w1=F0===!0||F0===void 0?1:F0||0,z$=(Z=(W=$.code)===null||W===void 0?void 0:W.regExp)!==null&&Z!==void 0?Z:OG,i1=(X=$.uriResolver)!==null&&X!==void 0?X:IV.default;return{strictSchema:(G=(Y=$.strictSchema)!==null&&Y!==void 0?Y:i)!==null&&G!==void 0?G:!0,strictNumbers:(T=(J=$.strictNumbers)!==null&&J!==void 0?J:i)!==null&&T!==void 0?T:!0,strictTypes:(M=(Q=$.strictTypes)!==null&&Q!==void 0?Q:i)!==null&&M!==void 0?M:"log",strictTuples:(N=(z=$.strictTuples)!==null&&z!==void 0?z:i)!==null&&N!==void 0?N:"log",strictRequired:(K=(B=$.strictRequired)!==null&&B!==void 0?B:i)!==null&&K!==void 0?K:!1,code:$.code?{...$.code,optimize:w1,regExp:z$}:{optimize:w1,regExp:z$},loopRequired:(P=$.loopRequired)!==null&&P!==void 0?P:qG,loopEnum:(q=$.loopEnum)!==null&&q!==void 0?q:qG,meta:(f=$.meta)!==null&&f!==void 0?f:!0,messages:(H=$.messages)!==null&&H!==void 0?H:!0,inlineRefs:(E=$.inlineRefs)!==null&&E!==void 0?E:!0,schemaId:(S=$.schemaId)!==null&&S!==void 0?S:"$id",addUsedSchema:(A=$.addUsedSchema)!==null&&A!==void 0?A:!0,validateSchema:(j=$.validateSchema)!==null&&j!==void 0?j:!0,validateFormats:(g=$.validateFormats)!==null&&g!==void 0?g:!0,unicodeRegExp:(s=$.unicodeRegExp)!==null&&s!==void 0?s:!0,int32range:(e=$.int32range)!==null&&e!==void 0?e:!0,uriResolver:i1}}class S8{constructor($={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,$=this.opts={...$,...vV($)};let{es5:w,lines:W}=this.opts.code;this.scope=new yV.ValueScope({scope:{},prefixes:xV,es5:w,lines:W}),this.logger=cV($.logger);let Z=$.validateFormats;if($.validateFormats=!1,this.RULES=(0,jV.getRules)(),UG.call(this,_V,$,"NOT SUPPORTED"),UG.call(this,gV,$,"DEPRECATED","warn"),this._metaOpts=mV.call(this),$.formats)hV.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),$.keywords)iV.call(this,$.keywords);if(typeof $.meta=="object")this.addMetaSchema($.meta);uV.call(this),$.validateFormats=Z}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:$,meta:w,schemaId:W}=this.opts,Z=fG;if(W==="id")Z={...fG},Z.id=Z.$id,delete Z.$id;if(w&&$)this.addMetaSchema(Z,Z[W],!1)}defaultMeta(){let{meta:$,schemaId:w}=this.opts;return this.opts.defaultMeta=typeof $=="object"?$[w]||$:void 0}validate($,w){let W;if(typeof $=="string"){if(W=this.getSchema($),!W)throw Error(`no schema with key or ref "${$}"`)}else W=this.compile($);let Z=W(w);if(!("$async"in W))this.errors=W.errors;return Z}compile($,w){let W=this._addSchema($,w);return W.validate||this._compileSchemaEnv(W)}compileAsync($,w){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema:W}=this.opts;return Z.call(this,$,w);async function Z(Q,M){await X.call(this,Q.$schema);let z=this._addSchema(Q,M);return z.validate||Y.call(this,z)}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(M){if(!(M instanceof FG.default))throw M;return G.call(this,M),await J.call(this,M.missingSchema),Y.call(this,Q)}}function G({missingSchema:Q,missingRef:M}){if(this.refs[Q])throw Error(`AnySchema ${Q} is loaded but ${M} cannot be resolved`)}async function J(Q){let M=await T.call(this,Q);if(!this.refs[Q])await X.call(this,M.$schema);if(!this.refs[Q])this.addSchema(M,Q,w)}async function T(Q){let M=this._loading[Q];if(M)return M;try{return await(this._loading[Q]=W(Q))}finally{delete this._loading[Q]}}}addSchema($,w,W,Z=this.opts.validateSchema){if(Array.isArray($)){for(let Y of $)this.addSchema(Y,void 0,W,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,X4.normalizeId)(w||X),this._checkUnique(w),this.schemas[w]=this._addSchema($,W,w,Z,!0),this}addMetaSchema($,w,W=this.opts.validateSchema){return this.addSchema($,w,!0,W),this}validateSchema($,w){if(typeof $=="boolean")return!0;let W;if(W=$.$schema,W!==void 0&&typeof W!="string")throw Error("$schema must be a string");if(W=W||this.opts.defaultMeta||this.defaultMeta(),!W)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let Z=this.validate(W,$);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=HG.call(this,$))=="string")$=w;if(w===void 0){let{schemaId:W}=this.opts,Z=new Z4.SchemaEnv({schema:{},schemaId:W});if(w=Z4.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=HG.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 W=$[this.opts.schemaId];if(W)W=(0,X4.normalizeId)(W),delete this.schemas[W],delete this.refs[W];return this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary($){for(let w of $)this.addKeyword(w);return this}addKeyword($,w){let W;if(typeof $=="string"){if(W=$,typeof w=="object")this.logger.warn("these parameters are deprecated, see docs for addKeyword"),w.keyword=W}else if(typeof $=="object"&&w===void 0){if(w=$,W=w.keyword,Array.isArray(W)&&!W.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(nV.call(this,W,w),!w)return(0,B5.eachItem)(W,(X)=>K5.call(this,X)),this;tV.call(this,w);let Z={...w,type:(0,A8.getJSONTypes)(w.type),schemaType:(0,A8.getJSONTypes)(w.schemaType)};return(0,B5.eachItem)(W,Z.type.length===0?(X)=>K5.call(this,X,Z):(X)=>Z.type.forEach((Y)=>K5.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 W of w.rules){let Z=W.rules.findIndex((X)=>X.keyword===$);if(Z>=0)W.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:W="data"}={}){if(!$||$.length===0)return"No errors";return $.map((Z)=>`${W}${Z.instancePath} ${Z.message}`).reduce((Z,X)=>Z+w+X)}$dataMetaSchema($,w){let W=this.RULES.all;$=JSON.parse(JSON.stringify($));for(let Z of w){let X=Z.split("/").slice(1),Y=$;for(let G of X)Y=Y[G];for(let G in W){let J=W[G];if(typeof J!="object")continue;let{$data:T}=J.definition,Q=Y[G];if(T&&Q)Y[G]=EG(Q)}}return $}_removeAllSchemas($,w){for(let W in $){let Z=$[W];if(!w||w.test(W)){if(typeof Z=="string")delete $[W];else if(Z&&!Z.meta)this._cache.delete(Z.schema),delete $[W]}}}_addSchema($,w,W,Z=this.opts.validateSchema,X=this.opts.addUsedSchema){let Y,{schemaId:G}=this.opts;if(typeof $=="object")Y=$[G];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;W=(0,X4.normalizeId)(Y||W);let T=X4.getSchemaRefs.call(this,$,W);if(J=new Z4.SchemaEnv({schema:$,schemaId:G,meta:w,baseId:W,localRefs:T}),this._cache.set(J.schema,J),X&&!W.startsWith("#")){if(W)this._checkUnique(W);this.refs[W]=J}if(Z)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 Z4.compileSchema.call(this,$);if(!$.validate)throw Error("ajv implementation error");return $.validate}_compileMetaSchema($){let w=this.opts;this.opts=this._metaOpts;try{Z4.compileSchema.call(this,$)}finally{this.opts=w}}}S8.ValidationError=CV.default;S8.MissingRefError=FG.default;V$.default=S8;function UG($,w,W,Z="error"){for(let X in $){let Y=X;if(Y in w)this.logger[Z](`${W}: option ${X}. ${$[Y]}`)}}function HG($){return $=(0,X4.normalizeId)($),this.schemas[$]||this.refs[$]}function uV(){let $=this.opts.schemas;if(!$)return;if(Array.isArray($))this.addSchema($);else for(let w in $)this.addSchema($[w],w)}function hV(){for(let $ in this.opts.formats){let w=this.opts.formats[$];if(w)this.addFormat($,w)}}function iV($){if(Array.isArray($)){this.addVocabulary($);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let w in $){let W=$[w];if(!W.keyword)W.keyword=w;this.addKeyword(W)}}function mV(){let $={...this.opts};for(let w of bV)delete $[w];return $}var lV={log(){},warn(){},error(){}};function cV($){if($===!1)return lV;if($===void 0)return console;if($.log&&$.warn&&$.error)return $;throw Error("logger must implement log, warn and error methods")}var dV=/^[a-z_$][a-z0-9_$:-]*$/i;function nV($,w){let{RULES:W}=this;if((0,B5.eachItem)($,(Z)=>{if(W.keywords[Z])throw Error(`Keyword ${Z} is already defined`);if(!dV.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 K5($,w,W){var Z;let X=w===null||w===void 0?void 0:w.post;if(W&&X)throw Error('keyword with "post" flag cannot have "type"');let{RULES:Y}=this,G=X?Y.post:Y.rules.find(({type:T})=>T===W);if(!G)G={type:W,rules:[]},Y.rules.push(G);if(Y.keywords[$]=!0,!w)return;let J={keyword:$,definition:{...w,type:(0,A8.getJSONTypes)(w.type),schemaType:(0,A8.getJSONTypes)(w.schemaType)}};if(w.before)pV.call(this,G,J,w.before);else G.rules.push(J);Y.all[$]=J,(Z=w.implements)===null||Z===void 0||Z.forEach((T)=>this.addKeyword(T))}function pV($,w,W){let Z=$.rules.findIndex((X)=>X.keyword===W);if(Z>=0)$.rules.splice(Z,0,w);else $.rules.push(w),this.logger.warn(`rule ${W} is not defined`)}function tV($){let{metaSchema:w}=$;if(w===void 0)return;if($.$data&&this.opts.$data)w=EG(w);$.validateSchema=this.compile(w,!0)}var rV={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function EG($){return{anyOf:[$,rV]}}});var kG=L((DG)=>{Object.defineProperty(DG,"__esModule",{value:!0});var oV={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};DG.default=oV});var yG=L((CG)=>{Object.defineProperty(CG,"__esModule",{value:!0});CG.callRef=CG.getValidate=void 0;var $f=ew(),AG=h0(),S0=h(),a1=B$(),SG=F8(),R8=c(),wf={keyword:"$ref",schemaType:"string",code($){let{gen:w,schema:W,it:Z}=$,{baseId:X,schemaEnv:Y,validateName:G,opts:J,self:T}=Z,{root:Q}=Y;if((W==="#"||W==="#/")&&X===Q.baseId)return z();let M=SG.resolveRef.call(T,Q,X,W);if(M===void 0)throw new $f.default(Z.opts.uriResolver,X,W);if(M instanceof SG.SchemaEnv)return N(M);return B(M);function z(){if(Y===Q)return C8($,G,Y,Y.$async);let K=w.scopeValue("root",{ref:Q});return C8($,S0._`${K}.validate`,Q,Q.$async)}function N(K){let P=RG($,K);C8($,P,K,K.$async)}function B(K){let P=w.scopeValue("schema",J.code.source===!0?{ref:K,code:(0,S0.stringify)(K)}:{ref:K}),q=w.name("valid"),f=$.subschema({schema:K,dataTypes:[],schemaPath:S0.nil,topSchemaRef:P,errSchemaPath:W},q);$.mergeEvaluated(f),$.ok(q)}}};function RG($,w){let{gen:W}=$;return w.validate?W.scopeValue("validate",{ref:w.validate}):S0._`${W.scopeValue("wrapper",{ref:w})}.validate`}CG.getValidate=RG;function C8($,w,W,Z){let{gen:X,it:Y}=$,{allErrors:G,schemaEnv:J,opts:T}=Y,Q=T.passContext?a1.default.this:S0.nil;if(Z)M();else z();function M(){if(!J.$async)throw Error("async schema referenced by sync schema");let K=X.let("valid");X.try(()=>{if(X.code(S0._`await ${(0,AG.callValidateCode)($,w,Q)}`),B(w),!G)X.assign(K,!0)},(P)=>{if(X.if(S0._`!(${P} instanceof ${Y.ValidationError})`,()=>X.throw(P)),N(P),!G)X.assign(K,!1)}),$.ok(K)}function z(){$.result((0,AG.callValidateCode)($,w,Q),()=>B(w),()=>N(w))}function N(K){let P=S0._`${K}.errors`;X.assign(a1.default.vErrors,S0._`${a1.default.vErrors} === null ? ${P} : ${a1.default.vErrors}.concat(${P})`),X.assign(a1.default.errors,S0._`${a1.default.vErrors}.length`)}function B(K){var P;if(!Y.opts.unevaluated)return;let q=(P=W===null||W===void 0?void 0:W.validate)===null||P===void 0?void 0:P.evaluated;if(Y.props!==!0)if(q&&!q.dynamicProps){if(q.props!==void 0)Y.props=R8.mergeEvaluated.props(X,q.props,Y.props)}else{let f=X.var("props",S0._`${K}.evaluated.props`);Y.props=R8.mergeEvaluated.props(X,f,Y.props,S0.Name)}if(Y.items!==!0)if(q&&!q.dynamicItems){if(q.items!==void 0)Y.items=R8.mergeEvaluated.items(X,q.items,Y.items)}else{let f=X.var("items",S0._`${K}.evaluated.items`);Y.items=R8.mergeEvaluated.items(X,f,Y.items,S0.Name)}}}CG.callRef=C8;CG.default=wf});var bG=L((IG)=>{Object.defineProperty(IG,"__esModule",{value:!0});var Xf=kG(),Yf=yG(),Gf=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Xf.default,Yf.default];IG.default=Gf});var _G=L((xG)=>{Object.defineProperty(xG,"__esModule",{value:!0});var j8=h(),v$=j8.operators,y8={maximum:{okStr:"<=",ok:v$.LTE,fail:v$.GT},minimum:{okStr:">=",ok:v$.GTE,fail:v$.LT},exclusiveMaximum:{okStr:"<",ok:v$.LT,fail:v$.GTE},exclusiveMinimum:{okStr:">",ok:v$.GT,fail:v$.LTE}},Tf={message:({keyword:$,schemaCode:w})=>j8.str`must be ${y8[$].okStr} ${w}`,params:({keyword:$,schemaCode:w})=>j8._`{comparison: ${y8[$].okStr}, limit: ${w}}`},Qf={keyword:Object.keys(y8),type:"number",schemaType:"number",$data:!0,error:Tf,code($){let{keyword:w,data:W,schemaCode:Z}=$;$.fail$data(j8._`${W} ${y8[w].fail} ${Z} || isNaN(${W})`)}};xG.default=Qf});var vG=L((gG)=>{Object.defineProperty(gG,"__esModule",{value:!0});var Y4=h(),zf={message:({schemaCode:$})=>Y4.str`must be multiple of ${$}`,params:({schemaCode:$})=>Y4._`{multipleOf: ${$}}`},Nf={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:zf,code($){let{gen:w,data:W,schemaCode:Z,it:X}=$,Y=X.opts.multipleOfPrecision,G=w.let("res"),J=Y?Y4._`Math.abs(Math.round(${G}) - ${G}) > 1e-${Y}`:Y4._`${G} !== parseInt(${G})`;$.fail$data(Y4._`(${Z} === 0 || (${G} = ${W}/${Z}, ${J}))`)}};gG.default=Nf});var iG=L((hG)=>{Object.defineProperty(hG,"__esModule",{value:!0});function uG($){let w=$.length,W=0,Z=0,X;while(Z<w)if(W++,X=$.charCodeAt(Z++),X>=55296&&X<=56319&&Z<w){if(X=$.charCodeAt(Z),(X&64512)===56320)Z++}return W}hG.default=uG;uG.code='require("ajv/dist/runtime/ucs2length").default'});var lG=L((mG)=>{Object.defineProperty(mG,"__esModule",{value:!0});var T1=h(),Pf=c(),Vf=iG(),ff={message({keyword:$,schemaCode:w}){let W=$==="maxLength"?"more":"fewer";return T1.str`must NOT have ${W} than ${w} characters`},params:({schemaCode:$})=>T1._`{limit: ${$}}`},qf={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:ff,code($){let{keyword:w,data:W,schemaCode:Z,it:X}=$,Y=w==="maxLength"?T1.operators.GT:T1.operators.LT,G=X.opts.unicode===!1?T1._`${W}.length`:T1._`${(0,Pf.useFunc)($.gen,Vf.default)}(${W})`;$.fail$data(T1._`${G} ${Y} ${Z}`)}};mG.default=qf});var dG=L((cG)=>{Object.defineProperty(cG,"__esModule",{value:!0});var Hf=h0(),Ff=c(),o1=h(),Of={message:({schemaCode:$})=>o1.str`must match pattern "${$}"`,params:({schemaCode:$})=>o1._`{pattern: ${$}}`},Ef={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Of,code($){let{gen:w,data:W,$data:Z,schema:X,schemaCode:Y,it:G}=$,J=G.opts.unicodeRegExp?"u":"";if(Z){let{regExp:T}=G.opts.code,Q=T.code==="new RegExp"?o1._`new RegExp`:(0,Ff.useFunc)(w,T),M=w.let("valid");w.try(()=>w.assign(M,o1._`${Q}(${Y}, ${J}).test(${W})`),()=>w.assign(M,!1)),$.fail$data(o1._`!${M}`)}else{let T=(0,Hf.usePattern)($,X);$.fail$data(o1._`!${T}.test(${W})`)}}};cG.default=Ef});var pG=L((nG)=>{Object.defineProperty(nG,"__esModule",{value:!0});var G4=h(),Df={message({keyword:$,schemaCode:w}){let W=$==="maxProperties"?"more":"fewer";return G4.str`must NOT have ${W} than ${w} properties`},params:({schemaCode:$})=>G4._`{limit: ${$}}`},kf={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:Df,code($){let{keyword:w,data:W,schemaCode:Z}=$,X=w==="maxProperties"?G4.operators.GT:G4.operators.LT;$.fail$data(G4._`Object.keys(${W}).length ${X} ${Z}`)}};nG.default=kf});var rG=L((tG)=>{Object.defineProperty(tG,"__esModule",{value:!0});var J4=h0(),T4=h(),Sf=c(),Rf={message:({params:{missingProperty:$}})=>T4.str`must have required property '${$}'`,params:({params:{missingProperty:$}})=>T4._`{missingProperty: ${$}}`},Cf={keyword:"required",type:"object",schemaType:"array",$data:!0,error:Rf,code($){let{gen:w,schema:W,schemaCode:Z,data:X,$data:Y,it:G}=$,{opts:J}=G;if(!Y&&W.length===0)return;let T=W.length>=J.loopRequired;if(G.allErrors)Q();else M();if(J.strictRequired){let B=$.parentSchema.properties,{definedProperties:K}=$.it;for(let P of W)if((B===null||B===void 0?void 0:B[P])===void 0&&!K.has(P)){let q=G.schemaEnv.baseId+G.errSchemaPath,f=`required property "${P}" is not defined at "${q}" (strictRequired)`;(0,Sf.checkStrictMode)(G,f,G.opts.strictRequired)}}function Q(){if(T||Y)$.block$data(T4.nil,z);else for(let B of W)(0,J4.checkReportMissingProp)($,B)}function M(){let B=w.let("missing");if(T||Y){let K=w.let("valid",!0);$.block$data(K,()=>N(B,K)),$.ok(K)}else w.if((0,J4.checkMissingProp)($,W,B)),(0,J4.reportMissingProp)($,B),w.else()}function z(){w.forOf("prop",Z,(B)=>{$.setParams({missingProperty:B}),w.if((0,J4.noPropertyInData)(w,X,B,J.ownProperties),()=>$.error())})}function N(B,K){$.setParams({missingProperty:B}),w.forOf(B,Z,()=>{w.assign(K,(0,J4.propertyInData)(w,X,B,J.ownProperties)),w.if((0,T4.not)(K),()=>{$.error(),w.break()})},T4.nil)}}};tG.default=Cf});var aG=L((sG)=>{Object.defineProperty(sG,"__esModule",{value:!0});var Q4=h(),yf={message({keyword:$,schemaCode:w}){let W=$==="maxItems"?"more":"fewer";return Q4.str`must NOT have ${W} than ${w} items`},params:({schemaCode:$})=>Q4._`{limit: ${$}}`},If={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:yf,code($){let{keyword:w,data:W,schemaCode:Z}=$,X=w==="maxItems"?Q4.operators.GT:Q4.operators.LT;$.fail$data(Q4._`${W}.length ${X} ${Z}`)}};sG.default=If});var I8=L((eG)=>{Object.defineProperty(eG,"__esModule",{value:!0});var oG=tW();oG.code='require("ajv/dist/runtime/equal").default';eG.default=oG});var w7=L(($7)=>{Object.defineProperty($7,"__esModule",{value:!0});var P5=tw(),K0=h(),_f=c(),gf=I8(),vf={message:({params:{i:$,j:w}})=>K0.str`must NOT have duplicate items (items ## ${w} and ${$} are identical)`,params:({params:{i:$,j:w}})=>K0._`{i: ${$}, j: ${w}}`},uf={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:vf,code($){let{gen:w,data:W,$data:Z,schema:X,parentSchema:Y,schemaCode:G,it:J}=$;if(!Z&&!X)return;let T=w.let("valid"),Q=Y.items?(0,P5.getSchemaTypes)(Y.items):[];$.block$data(T,M,K0._`${G} === false`),$.ok(T);function M(){let K=w.let("i",K0._`${W}.length`),P=w.let("j");$.setParams({i:K,j:P}),w.assign(T,!0),w.if(K0._`${K} > 1`,()=>(z()?N:B)(K,P))}function z(){return Q.length>0&&!Q.some((K)=>K==="object"||K==="array")}function N(K,P){let q=w.name("item"),f=(0,P5.checkDataTypes)(Q,q,J.opts.strictNumbers,P5.DataType.Wrong),H=w.const("indices",K0._`{}`);w.for(K0._`;${K}--;`,()=>{if(w.let(q,K0._`${W}[${K}]`),w.if(f,K0._`continue`),Q.length>1)w.if(K0._`typeof ${q} == "string"`,K0._`${q} += "_"`);w.if(K0._`typeof ${H}[${q}] == "number"`,()=>{w.assign(P,K0._`${H}[${q}]`),$.error(),w.assign(T,!1).break()}).code(K0._`${H}[${q}] = ${K}`)})}function B(K,P){let q=(0,_f.useFunc)(w,gf.default),f=w.name("outer");w.label(f).for(K0._`;${K}--;`,()=>w.for(K0._`${P} = ${K}; ${P}--;`,()=>w.if(K0._`${q}(${W}[${K}], ${W}[${P}])`,()=>{$.error(),w.assign(T,!1).break(f)})))}}};$7.default=uf});var Z7=L((W7)=>{Object.defineProperty(W7,"__esModule",{value:!0});var V5=h(),mf=c(),lf=I8(),cf={message:"must be equal to constant",params:({schemaCode:$})=>V5._`{allowedValue: ${$}}`},df={keyword:"const",$data:!0,error:cf,code($){let{gen:w,data:W,$data:Z,schemaCode:X,schema:Y}=$;if(Z||Y&&typeof Y=="object")$.fail$data(V5._`!${(0,mf.useFunc)(w,lf.default)}(${W}, ${X})`);else $.fail(V5._`${Y} !== ${W}`)}};W7.default=df});var Y7=L((X7)=>{Object.defineProperty(X7,"__esModule",{value:!0});var M4=h(),pf=c(),tf=I8(),rf={message:"must be equal to one of the allowed values",params:({schemaCode:$})=>M4._`{allowedValues: ${$}}`},sf={keyword:"enum",schemaType:"array",$data:!0,error:rf,code($){let{gen:w,data:W,$data:Z,schema:X,schemaCode:Y,it:G}=$;if(!Z&&X.length===0)throw Error("enum must have non-empty array");let J=X.length>=G.opts.loopEnum,T,Q=()=>T!==null&&T!==void 0?T:T=(0,pf.useFunc)(w,tf.default),M;if(J||Z)M=w.let("valid"),$.block$data(M,z);else{if(!Array.isArray(X))throw Error("ajv implementation error");let B=w.const("vSchema",Y);M=(0,M4.or)(...X.map((K,P)=>N(B,P)))}$.pass(M);function z(){w.assign(M,!1),w.forOf("v",Y,(B)=>w.if(M4._`${Q()}(${W}, ${B})`,()=>w.assign(M,!0).break()))}function N(B,K){let P=X[K];return typeof P==="object"&&P!==null?M4._`${Q()}(${W}, ${B}[${K}])`:M4._`${W} === ${P}`}}};X7.default=sf});var J7=L((G7)=>{Object.defineProperty(G7,"__esModule",{value:!0});var of=_G(),ef=vG(),$q=lG(),wq=dG(),Wq=pG(),Zq=rG(),Xq=aG(),Yq=w7(),Gq=Z7(),Jq=Y7(),Tq=[of.default,ef.default,$q.default,wq.default,Wq.default,Zq.default,Xq.default,Yq.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Gq.default,Jq.default];G7.default=Tq});var q5=L((Q7)=>{Object.defineProperty(Q7,"__esModule",{value:!0});Q7.validateAdditionalItems=void 0;var Q1=h(),f5=c(),Mq={message:({params:{len:$}})=>Q1.str`must NOT have more than ${$} items`,params:({params:{len:$}})=>Q1._`{limit: ${$}}`},zq={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Mq,code($){let{parentSchema:w,it:W}=$,{items:Z}=w;if(!Array.isArray(Z)){(0,f5.checkStrictMode)(W,'"additionalItems" is ignored when "items" is not an array of schemas');return}T7($,Z)}};function T7($,w){let{gen:W,schema:Z,data:X,keyword:Y,it:G}=$;G.items=!0;let J=W.const("len",Q1._`${X}.length`);if(Z===!1)$.setParams({len:w.length}),$.pass(Q1._`${J} <= ${w.length}`);else if(typeof Z=="object"&&!(0,f5.alwaysValidSchema)(G,Z)){let Q=W.var("valid",Q1._`${J} <= ${w.length}`);W.if((0,Q1.not)(Q),()=>T(Q)),$.ok(Q)}function T(Q){W.forRange("i",w.length,J,(M)=>{if($.subschema({keyword:Y,dataProp:M,dataPropType:f5.Type.Num},Q),!G.allErrors)W.if((0,Q1.not)(Q),()=>W.break())})}}Q7.validateAdditionalItems=T7;Q7.default=zq});var U5=L((K7)=>{Object.defineProperty(K7,"__esModule",{value:!0});K7.validateTuple=void 0;var z7=h(),b8=c(),Kq=h0(),Bq={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code($){let{schema:w,it:W}=$;if(Array.isArray(w))return N7($,"additionalItems",w);if(W.items=!0,(0,b8.alwaysValidSchema)(W,w))return;$.ok((0,Kq.validateArray)($))}};function N7($,w,W=$.schema){let{gen:Z,parentSchema:X,data:Y,keyword:G,it:J}=$;if(M(X),J.opts.unevaluated&&W.length&&J.items!==!0)J.items=b8.mergeEvaluated.items(Z,W.length,J.items);let T=Z.name("valid"),Q=Z.const("len",z7._`${Y}.length`);W.forEach((z,N)=>{if((0,b8.alwaysValidSchema)(J,z))return;Z.if(z7._`${Q} > ${N}`,()=>$.subschema({keyword:G,schemaProp:N,dataProp:N},T)),$.ok(T)});function M(z){let{opts:N,errSchemaPath:B}=J,K=W.length,P=K===z.minItems&&(K===z.maxItems||z[w]===!1);if(N.strictTuples&&!P){let q=`"${G}" is ${K}-tuple, but minItems or maxItems/${w} are not specified or different at path "${B}"`;(0,b8.checkStrictMode)(J,q,N.strictTuples)}}}K7.validateTuple=N7;K7.default=Bq});var V7=L((P7)=>{Object.defineProperty(P7,"__esModule",{value:!0});var Vq=U5(),fq={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:($)=>(0,Vq.validateTuple)($,"items")};P7.default=fq});var U7=L((q7)=>{Object.defineProperty(q7,"__esModule",{value:!0});var f7=h(),Uq=c(),Hq=h0(),Fq=q5(),Oq={message:({params:{len:$}})=>f7.str`must NOT have more than ${$} items`,params:({params:{len:$}})=>f7._`{limit: ${$}}`},Eq={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Oq,code($){let{schema:w,parentSchema:W,it:Z}=$,{prefixItems:X}=W;if(Z.items=!0,(0,Uq.alwaysValidSchema)(Z,w))return;if(X)(0,Fq.validateAdditionalItems)($,X);else $.ok((0,Hq.validateArray)($))}};q7.default=Eq});var F7=L((H7)=>{Object.defineProperty(H7,"__esModule",{value:!0});var i0=h(),x8=c(),Dq={message:({params:{min:$,max:w}})=>w===void 0?i0.str`must contain at least ${$} valid item(s)`:i0.str`must contain at least ${$} and no more than ${w} valid item(s)`,params:({params:{min:$,max:w}})=>w===void 0?i0._`{minContains: ${$}}`:i0._`{minContains: ${$}, maxContains: ${w}}`},kq={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Dq,code($){let{gen:w,schema:W,parentSchema:Z,data:X,it:Y}=$,G,J,{minContains:T,maxContains:Q}=Z;if(Y.opts.next)G=T===void 0?1:T,J=Q;else G=1;let M=w.const("len",i0._`${X}.length`);if($.setParams({min:G,max:J}),J===void 0&&G===0){(0,x8.checkStrictMode)(Y,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(J!==void 0&&G>J){(0,x8.checkStrictMode)(Y,'"minContains" > "maxContains" is always invalid'),$.fail();return}if((0,x8.alwaysValidSchema)(Y,W)){let P=i0._`${M} >= ${G}`;if(J!==void 0)P=i0._`${P} && ${M} <= ${J}`;$.pass(P);return}Y.items=!0;let z=w.name("valid");if(J===void 0&&G===1)B(z,()=>w.if(z,()=>w.break()));else if(G===0){if(w.let(z,!0),J!==void 0)w.if(i0._`${X}.length > 0`,N)}else w.let(z,!1),N();$.result(z,()=>$.reset());function N(){let P=w.name("_valid"),q=w.let("count",0);B(P,()=>w.if(P,()=>K(q)))}function B(P,q){w.forRange("i",0,M,(f)=>{$.subschema({keyword:"contains",dataProp:f,dataPropType:x8.Type.Num,compositeRule:!0},P),q()})}function K(P){if(w.code(i0._`${P}++`),J===void 0)w.if(i0._`${P} >= ${G}`,()=>w.assign(z,!0).break());else if(w.if(i0._`${P} > ${J}`,()=>w.assign(z,!1).break()),G===1)w.assign(z,!0);else w.if(i0._`${P} >= ${G}`,()=>w.assign(z,!0))}}};H7.default=kq});var A7=L((L7)=>{Object.defineProperty(L7,"__esModule",{value:!0});L7.validateSchemaDeps=L7.validatePropertyDeps=L7.error=void 0;var H5=h(),Sq=c(),z4=h0();L7.error={message:({params:{property:$,depsCount:w,deps:W}})=>{let Z=w===1?"property":"properties";return H5.str`must have ${Z} ${W} when property ${$} is present`},params:({params:{property:$,depsCount:w,deps:W,missingProperty:Z}})=>H5._`{property: ${$},
33
33
  missingProperty: ${Z},
34
34
  depsCount: ${w},
35
- deps: ${W}}`};var Rq={keyword:"dependencies",type:"object",schemaType:"object",error:E7.error,code($){let[w,W]=Cq($);F7($,w),O7($,W)}};function Cq({schema:$}){let w={},W={};for(let Z in $){if(Z==="__proto__")continue;let X=Array.isArray($[Z])?w:W;X[Z]=$[Z]}return[w,W]}function F7($,w=$.schema){let{gen:W,data:Z,it:X}=$;if(Object.keys(w).length===0)return;let Y=W.let("missing");for(let G in w){let J=w[G];if(J.length===0)continue;let T=(0,z9.propertyInData)(W,Z,G,X.opts.ownProperties);if($.setParams({property:G,depsCount:J.length,deps:J.join(", ")}),X.allErrors)W.if(T,()=>{for(let Q of J)(0,z9.checkReportMissingProp)($,Q)});else W.if(U5._`${T} && (${(0,z9.checkMissingProp)($,J,Y)})`),(0,z9.reportMissingProp)($,Y),W.else()}}E7.validatePropertyDeps=F7;function O7($,w=$.schema){let{gen:W,data:Z,keyword:X,it:Y}=$,G=W.name("valid");for(let J in w){if((0,Sq.alwaysValidSchema)(Y,w[J]))continue;W.if((0,z9.propertyInData)(W,Z,J,Y.opts.ownProperties),()=>{let T=$.subschema({keyword:X,schemaProp:J},G);$.mergeValidEvaluated(T,G)},()=>W.var(G,!0)),$.ok(G)}}E7.validateSchemaDeps=O7;E7.default=Rq});var R7=L((S7)=>{Object.defineProperty(S7,"__esModule",{value:!0});var A7=u(),Iq=c(),bq={message:"property name must be valid",params:({params:$})=>A7._`{propertyName: ${$.propertyName}}`},xq={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:bq,code($){let{gen:w,schema:W,data:Z,it:X}=$;if((0,Iq.alwaysValidSchema)(X,W))return;let Y=w.name("valid");w.forIn("key",Z,(G)=>{$.setParams({propertyName:G}),$.subschema({keyword:"propertyNames",data:G,dataTypes:["string"],propertyName:G,compositeRule:!0},Y),w.if((0,A7.not)(Y),()=>{if($.error(!0),!X.allErrors)w.break()})}),$.ok(Y)}};S7.default=xq});var H5=L((C7)=>{Object.defineProperty(C7,"__esModule",{value:!0});var x8=u0(),t0=u(),gq=B$(),_8=c(),vq={message:"must NOT have additional properties",params:({params:$})=>t0._`{additionalProperty: ${$.additionalProperty}}`},hq={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:vq,code($){let{gen:w,schema:W,parentSchema:Z,data:X,errsCount:Y,it:G}=$;if(!Y)throw Error("ajv implementation error");let{allErrors:J,opts:T}=G;if(G.props=!0,T.removeAdditional!=="all"&&(0,_8.alwaysValidSchema)(G,W))return;let Q=(0,x8.allSchemaProperties)(Z.properties),M=(0,x8.allSchemaProperties)(Z.patternProperties);z(),$.ok(t0._`${Y} === ${gq.default.errors}`);function z(){w.forIn("key",X,(q)=>{if(!Q.length&&!M.length)K(q);else w.if(N(q),()=>K(q))})}function N(q){let f;if(Q.length>8){let H=(0,_8.schemaRefOrVal)(G,Z.properties,"properties");f=(0,x8.isOwnProperty)(w,H,q)}else if(Q.length)f=(0,t0.or)(...Q.map((H)=>t0._`${q} === ${H}`));else f=t0.nil;if(M.length)f=(0,t0.or)(f,...M.map((H)=>t0._`${(0,x8.usePattern)($,H)}.test(${q})`));return(0,t0.not)(f)}function B(q){w.code(t0._`delete ${X}[${q}]`)}function K(q){if(T.removeAdditional==="all"||T.removeAdditional&&W===!1){B(q);return}if(W===!1){if($.setParams({additionalProperty:q}),$.error(),!J)w.break();return}if(typeof W=="object"&&!(0,_8.alwaysValidSchema)(G,W)){let f=w.name("valid");if(T.removeAdditional==="failing")P(q,f,!1),w.if((0,t0.not)(f),()=>{$.reset(),B(q)});else if(P(q,f),!J)w.if((0,t0.not)(f),()=>w.break())}}function P(q,f,H){let E={keyword:"additionalProperties",dataProp:q,dataPropType:_8.Type.Str};if(H===!1)Object.assign(E,{compositeRule:!0,createErrors:!1,allErrors:!1});$.subschema(E,f)}}};C7.default=hq});var b7=L((I7)=>{Object.defineProperty(I7,"__esModule",{value:!0});var iq=ow(),j7=u0(),F5=c(),y7=H5(),mq={keyword:"properties",type:"object",schemaType:"object",code($){let{gen:w,schema:W,parentSchema:Z,data:X,it:Y}=$;if(Y.opts.removeAdditional==="all"&&Z.additionalProperties===void 0)y7.default.code(new iq.KeywordCxt(Y,y7.default,"additionalProperties"));let G=(0,j7.allSchemaProperties)(W);for(let z of G)Y.definedProperties.add(z);if(Y.opts.unevaluated&&G.length&&Y.props!==!0)Y.props=F5.mergeEvaluated.props(w,(0,F5.toHash)(G),Y.props);let J=G.filter((z)=>!(0,F5.alwaysValidSchema)(Y,W[z]));if(J.length===0)return;let T=w.name("valid");for(let z of J){if(Q(z))M(z);else{if(w.if((0,j7.propertyInData)(w,X,z,Y.opts.ownProperties)),M(z),!Y.allErrors)w.else().var(T,!0);w.endIf()}$.it.definedProperties.add(z),$.ok(T)}function Q(z){return Y.opts.useDefaults&&!Y.compositeRule&&W[z].default!==void 0}function M(z){$.subschema({keyword:"properties",schemaProp:z,dataProp:z},T)}}};I7.default=mq});var h7=L((v7)=>{Object.defineProperty(v7,"__esModule",{value:!0});var x7=u0(),g8=u(),_7=c(),g7=c(),cq={keyword:"patternProperties",type:"object",schemaType:"object",code($){let{gen:w,schema:W,data:Z,parentSchema:X,it:Y}=$,{opts:G}=Y,J=(0,x7.allSchemaProperties)(W),T=J.filter((P)=>(0,_7.alwaysValidSchema)(Y,W[P]));if(J.length===0||T.length===J.length&&(!Y.opts.unevaluated||Y.props===!0))return;let Q=G.strictSchema&&!G.allowMatchingProperties&&X.properties,M=w.name("valid");if(Y.props!==!0&&!(Y.props instanceof g8.Name))Y.props=(0,g7.evaluatedPropsToName)(w,Y.props);let{props:z}=Y;N();function N(){for(let P of J){if(Q)B(P);if(Y.allErrors)K(P);else w.var(M,!0),K(P),w.if(M)}}function B(P){for(let q in Q)if(new RegExp(P).test(q))(0,_7.checkStrictMode)(Y,`property ${q} matches pattern ${P} (use allowMatchingProperties)`)}function K(P){w.forIn("key",Z,(q)=>{w.if(g8._`${(0,x7.usePattern)($,P)}.test(${q})`,()=>{let f=T.includes(P);if(!f)$.subschema({keyword:"patternProperties",schemaProp:P,dataProp:q,dataPropType:g7.Type.Str},M);if(Y.opts.unevaluated&&z!==!0)w.assign(g8._`${z}[${q}]`,!0);else if(!f&&!Y.allErrors)w.if((0,g8.not)(M),()=>w.break())})})}}};v7.default=cq});var i7=L((u7)=>{Object.defineProperty(u7,"__esModule",{value:!0});var nq=c(),pq={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code($){let{gen:w,schema:W,it:Z}=$;if((0,nq.alwaysValidSchema)(Z,W)){$.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"}};u7.default=pq});var l7=L((m7)=>{Object.defineProperty(m7,"__esModule",{value:!0});var rq=u0(),sq={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:rq.validateUnion,error:{message:"must match a schema in anyOf"}};m7.default=sq});var d7=L((c7)=>{Object.defineProperty(c7,"__esModule",{value:!0});var v8=u(),oq=c(),eq={message:"must match exactly one schema in oneOf",params:({params:$})=>v8._`{passingSchemas: ${$.passing}}`},$U={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:eq,code($){let{gen:w,schema:W,parentSchema:Z,it:X}=$;if(!Array.isArray(W))throw Error("ajv implementation error");if(X.opts.discriminator&&Z.discriminator)return;let Y=W,G=w.let("valid",!1),J=w.let("passing",null),T=w.name("_valid");$.setParams({passing:J}),w.block(Q),$.result(G,()=>$.reset(),()=>$.error(!0));function Q(){Y.forEach((M,z)=>{let N;if((0,oq.alwaysValidSchema)(X,M))w.var(T,!0);else N=$.subschema({keyword:"oneOf",schemaProp:z,compositeRule:!0},T);if(z>0)w.if(v8._`${T} && ${G}`).assign(G,!1).assign(J,v8._`[${J}, ${z}]`).else();w.if(T,()=>{if(w.assign(G,!0),w.assign(J,z),N)$.mergeEvaluated(N,v8.Name)})})}}};c7.default=$U});var p7=L((n7)=>{Object.defineProperty(n7,"__esModule",{value:!0});var WU=c(),ZU={keyword:"allOf",schemaType:"array",code($){let{gen:w,schema:W,it:Z}=$;if(!Array.isArray(W))throw Error("ajv implementation error");let X=w.name("valid");W.forEach((Y,G)=>{if((0,WU.alwaysValidSchema)(Z,Y))return;let J=$.subschema({keyword:"allOf",schemaProp:G},X);$.ok(X),$.mergeEvaluated(J)})}};n7.default=ZU});var a7=L((s7)=>{Object.defineProperty(s7,"__esModule",{value:!0});var h8=u(),r7=c(),YU={message:({params:$})=>h8.str`must match "${$.ifClause}" schema`,params:({params:$})=>h8._`{failingKeyword: ${$.ifClause}}`},GU={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:YU,code($){let{gen:w,parentSchema:W,it:Z}=$;if(W.then===void 0&&W.else===void 0)(0,r7.checkStrictMode)(Z,'"if" without "then" and "else" is ignored');let X=t7(Z,"then"),Y=t7(Z,"else");if(!X&&!Y)return;let G=w.let("valid",!0),J=w.name("_valid");if(T(),$.reset(),X&&Y){let M=w.let("ifClause");$.setParams({ifClause:M}),w.if(J,Q("then",M),Q("else",M))}else if(X)w.if(J,Q("then"));else w.if((0,h8.not)(J),Q("else"));$.pass(G,()=>$.error(!0));function T(){let M=$.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},J);$.mergeEvaluated(M)}function Q(M,z){return()=>{let N=$.subschema({keyword:M},J);if(w.assign(G,J),$.mergeValidEvaluated(N,G),z)w.assign(z,h8._`${M}`);else $.setParams({ifClause:M})}}}};function t7($,w){let W=$.schema[w];return W!==void 0&&!(0,r7.alwaysValidSchema)($,W)}s7.default=GU});var e7=L((o7)=>{Object.defineProperty(o7,"__esModule",{value:!0});var TU=c(),QU={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:$,parentSchema:w,it:W}){if(w.if===void 0)(0,TU.checkStrictMode)(W,`"${$}" without "if" is ignored`)}};o7.default=QU});var wJ=L(($J)=>{Object.defineProperty($J,"__esModule",{value:!0});var zU=f5(),NU=P7(),KU=q5(),BU=q7(),PU=H7(),VU=k7(),fU=R7(),qU=H5(),UU=b7(),HU=h7(),FU=i7(),OU=l7(),EU=d7(),LU=p7(),DU=a7(),kU=e7();function AU($=!1){let w=[FU.default,OU.default,EU.default,LU.default,DU.default,kU.default,fU.default,qU.default,VU.default,UU.default,HU.default];if($)w.push(NU.default,BU.default);else w.push(zU.default,KU.default);return w.push(PU.default),w}$J.default=AU});var ZJ=L((WJ)=>{Object.defineProperty(WJ,"__esModule",{value:!0});var w0=u(),RU={message:({schemaCode:$})=>w0.str`must match format "${$}"`,params:({schemaCode:$})=>w0._`{format: ${$}}`},CU={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:RU,code($,w){let{gen:W,data:Z,$data:X,schema:Y,schemaCode:G,it:J}=$,{opts:T,errSchemaPath:Q,schemaEnv:M,self:z}=J;if(!T.validateFormats)return;if(X)N();else B();function N(){let K=W.scopeValue("formats",{ref:z.formats,code:T.code.formats}),P=W.const("fDef",w0._`${K}[${G}]`),q=W.let("fType"),f=W.let("format");W.if(w0._`typeof ${P} == "object" && !(${P} instanceof RegExp)`,()=>W.assign(q,w0._`${P}.type || "string"`).assign(f,w0._`${P}.validate`),()=>W.assign(q,w0._`"string"`).assign(f,P)),$.fail$data((0,w0.or)(H(),E()));function H(){if(T.strictSchema===!1)return w0.nil;return w0._`${G} && !${f}`}function E(){let S=M.$async?w0._`(${P}.async ? await ${f}(${Z}) : ${f}(${Z}))`:w0._`${f}(${Z})`,A=w0._`(typeof ${f} == "function" ? ${S} : ${f}.test(${Z}))`;return w0._`${f} && ${f} !== true && ${q} === ${w} && !${A}`}}function B(){let K=z.formats[Y];if(!K){H();return}if(K===!0)return;let[P,q,f]=E(K);if(P===w)$.pass(S());function H(){if(T.strictSchema===!1){z.logger.warn(A());return}throw Error(A());function A(){return`unknown format "${Y}" ignored in schema at path "${Q}"`}}function E(A){let j=A instanceof RegExp?(0,w0.regexpCode)(A):T.code.formats?w0._`${T.code.formats}${(0,w0.getProperty)(Y)}`:void 0,g=W.scopeValue("formats",{key:Y,ref:A,code:j});if(typeof A=="object"&&!(A instanceof RegExp))return[A.type||"string",A.validate,w0._`${g}.validate`];return["string",A,g]}function S(){if(typeof K=="object"&&!(K instanceof RegExp)&&K.async){if(!M.$async)throw Error("async format in sync schema");return w0._`await ${f}(${Z})`}return typeof q=="function"?w0._`${f}(${Z})`:w0._`${f}.test(${Z})`}}}};WJ.default=CU});var YJ=L((XJ)=>{Object.defineProperty(XJ,"__esModule",{value:!0});var yU=ZJ(),IU=[yU.default];XJ.default=IU});var TJ=L((GJ)=>{Object.defineProperty(GJ,"__esModule",{value:!0});GJ.contentVocabulary=GJ.metadataVocabulary=void 0;GJ.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];GJ.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var zJ=L((MJ)=>{Object.defineProperty(MJ,"__esModule",{value:!0});var _U=IG(),gU=G7(),vU=wJ(),hU=YJ(),QJ=TJ(),uU=[_U.default,gU.default,(0,vU.default)(),hU.default,QJ.metadataVocabulary,QJ.contentVocabulary];MJ.default=uU});var PJ=L((KJ)=>{Object.defineProperty(KJ,"__esModule",{value:!0});KJ.DiscrError=void 0;var NJ;(function($){$.Tag="tag",$.Mapping="mapping"})(NJ||(KJ.DiscrError=NJ={}))});var qJ=L((fJ)=>{Object.defineProperty(fJ,"__esModule",{value:!0});var e1=u(),O5=PJ(),VJ=H8(),mU=ew(),lU=c(),cU={message:({params:{discrError:$,tagName:w}})=>$===O5.DiscrError.Tag?`tag "${w}" must be string`:`value of tag "${w}" must be in oneOf`,params:({params:{discrError:$,tag:w,tagName:W}})=>e1._`{error: ${$}, tag: ${W}, tagValue: ${w}}`},dU={keyword:"discriminator",type:"object",schemaType:"object",error:cU,code($){let{gen:w,data:W,schema:Z,parentSchema:X,it:Y}=$,{oneOf:G}=X;if(!Y.opts.discriminator)throw Error("discriminator: requires discriminator option");let J=Z.propertyName;if(typeof J!="string")throw Error("discriminator: requires propertyName");if(Z.mapping)throw Error("discriminator: mapping is not supported");if(!G)throw Error("discriminator: requires oneOf keyword");let T=w.let("valid",!1),Q=w.const("tag",e1._`${W}${(0,e1.getProperty)(J)}`);w.if(e1._`typeof ${Q} == "string"`,()=>M(),()=>$.error(!1,{discrError:O5.DiscrError.Tag,tag:Q,tagName:J})),$.ok(T);function M(){let B=N();w.if(!1);for(let K in B)w.elseIf(e1._`${Q} === ${K}`),w.assign(T,z(B[K]));w.else(),$.error(!1,{discrError:O5.DiscrError.Mapping,tag:Q,tagName:J}),w.endIf()}function z(B){let K=w.name("valid"),P=$.subschema({keyword:"oneOf",schemaProp:B},K);return $.mergeEvaluated(P,e1.Name),K}function N(){var B;let K={},P=f(X),q=!0;for(let S=0;S<G.length;S++){let A=G[S];if((A===null||A===void 0?void 0:A.$ref)&&!(0,lU.schemaHasRulesButRef)(A,Y.self.RULES)){let g=A.$ref;if(A=VJ.resolveRef.call(Y.self,Y.schemaEnv.root,Y.baseId,g),A instanceof VJ.SchemaEnv)A=A.schema;if(A===void 0)throw new mU.default(Y.opts.uriResolver,Y.baseId,g)}let j=(B=A===null||A===void 0?void 0:A.properties)===null||B===void 0?void 0:B[J];if(typeof j!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${J}"`);q=q&&(P||f(A)),H(j,S)}if(!q)throw Error(`discriminator: "${J}" must be required`);return K;function f({required:S}){return Array.isArray(S)&&S.includes(J)}function H(S,A){if(S.const)E(S.const,A);else if(S.enum)for(let j of S.enum)E(j,A);else throw Error(`discriminator: "properties/${J}" must have "const" or "enum"`)}function E(S,A){if(typeof S!="string"||S in K)throw Error(`discriminator: "${J}" values must be unique strings`);K[S]=A}}}};fJ.default=dU});var UJ=L((XA,pU)=>{pU.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 FJ=L((R0,E5)=>{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 tU=EG(),rU=zJ(),sU=qJ(),HJ=UJ(),aU=["/properties"],u8="http://json-schema.org/draft-07/schema";class N9 extends tU.default{_addVocabularies(){if(super._addVocabularies(),rU.default.forEach(($)=>this.addVocabulary($)),this.opts.discriminator)this.addKeyword(sU.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let $=this.opts.$data?this.$dataMetaSchema(HJ,aU):HJ;this.addMetaSchema($,u8,!1),this.refs["http://json-schema.org/schema"]=u8}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(u8)?u8:void 0)}}R0.Ajv=N9;E5.exports=R0=N9;E5.exports.Ajv=N9;Object.defineProperty(R0,"__esModule",{value:!0});R0.default=N9;var oU=ow();Object.defineProperty(R0,"KeywordCxt",{enumerable:!0,get:function(){return oU.KeywordCxt}});var $w=u();Object.defineProperty(R0,"_",{enumerable:!0,get:function(){return $w._}});Object.defineProperty(R0,"str",{enumerable:!0,get:function(){return $w.str}});Object.defineProperty(R0,"stringify",{enumerable:!0,get:function(){return $w.stringify}});Object.defineProperty(R0,"nil",{enumerable:!0,get:function(){return $w.nil}});Object.defineProperty(R0,"Name",{enumerable:!0,get:function(){return $w.Name}});Object.defineProperty(R0,"CodeGen",{enumerable:!0,get:function(){return $w.CodeGen}});var eU=q8();Object.defineProperty(R0,"ValidationError",{enumerable:!0,get:function(){return eU.default}});var $H=ew();Object.defineProperty(R0,"MissingRefError",{enumerable:!0,get:function(){return $H.default}})});var w6=L((MR,c5)=>{var $6=process||{},wT=$6.argv||[],e8=$6.env||{},eH=!(!!e8.NO_COLOR||wT.includes("--no-color"))&&(!!e8.FORCE_COLOR||wT.includes("--color")||$6.platform==="win32"||($6.stdout||{}).isTTY&&e8.TERM!=="dumb"||!!e8.CI),$F=($,w,W=$)=>(Z)=>{let X=""+Z,Y=X.indexOf(w,$.length);return~Y?$+wF(X,w,W,Y)+w:$+X+w},wF=($,w,W,Z)=>{let X="",Y=0;do X+=$.substring(Y,Z)+W,Y=Z+w.length,Z=$.indexOf(w,Y);while(~Z);return X+$.substring(Y)},WT=($=eH)=>{let w=$?$F:()=>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")}};c5.exports=WT();c5.exports.createColors=WT});import{realpathSync as iM}from"fs";import{realpath as uL}from"fs/promises";import iL from"path";import{createInterface as mL}from"readline/promises";import{fileURLToPath as lL}from"url";var m3=m1(OW(),1),{program:ZD,createCommand:XD,createArgument:YD,createOption:GD,CommanderError:JD,InvalidArgumentError:TD,InvalidOptionArgumentError:QD,Command:l3,Argument:MD,Option:zD,Help:ND}=m3.default;import c3 from"node:os";import W8 from"node:path";function d3(){return process.env.XDG_CONFIG_HOME?W8.join(process.env.XDG_CONFIG_HOME,"coden"):W8.join(c3.homedir(),".config","coden")}function n3(){return process.env.XDG_DATA_HOME?W8.join(process.env.XDG_DATA_HOME,"coden"):W8.join(c3.homedir(),".local","share","coden")}import{mkdir as mz,readFile as lz,realpath as p3,writeFile as cz}from"node:fs/promises";import dz from"node:path";class EW{file;constructor($){this.file=$}async isTrusted($){return(await this.read()).includes($)}async isWorkspaceTrusted($){return this.isTrusted(await p3($))}async trustWorkspace($){return this.trust(await p3($))}async trust($){let w=await this.read();if(!w.includes($))w.push($);await mz(dz.dirname(this.file),{recursive:!0}),await cz(this.file,`${JSON.stringify(w,null,2)}
35
+ deps: ${W}}`};var Rq={keyword:"dependencies",type:"object",schemaType:"object",error:L7.error,code($){let[w,W]=Cq($);O7($,w),E7($,W)}};function Cq({schema:$}){let w={},W={};for(let Z in $){if(Z==="__proto__")continue;let X=Array.isArray($[Z])?w:W;X[Z]=$[Z]}return[w,W]}function O7($,w=$.schema){let{gen:W,data:Z,it:X}=$;if(Object.keys(w).length===0)return;let Y=W.let("missing");for(let G in w){let J=w[G];if(J.length===0)continue;let T=(0,z4.propertyInData)(W,Z,G,X.opts.ownProperties);if($.setParams({property:G,depsCount:J.length,deps:J.join(", ")}),X.allErrors)W.if(T,()=>{for(let Q of J)(0,z4.checkReportMissingProp)($,Q)});else W.if(H5._`${T} && (${(0,z4.checkMissingProp)($,J,Y)})`),(0,z4.reportMissingProp)($,Y),W.else()}}L7.validatePropertyDeps=O7;function E7($,w=$.schema){let{gen:W,data:Z,keyword:X,it:Y}=$,G=W.name("valid");for(let J in w){if((0,Sq.alwaysValidSchema)(Y,w[J]))continue;W.if((0,z4.propertyInData)(W,Z,J,Y.opts.ownProperties),()=>{let T=$.subschema({keyword:X,schemaProp:J},G);$.mergeValidEvaluated(T,G)},()=>W.var(G,!0)),$.ok(G)}}L7.validateSchemaDeps=E7;L7.default=Rq});var C7=L((R7)=>{Object.defineProperty(R7,"__esModule",{value:!0});var S7=h(),Iq=c(),bq={message:"property name must be valid",params:({params:$})=>S7._`{propertyName: ${$.propertyName}}`},xq={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:bq,code($){let{gen:w,schema:W,data:Z,it:X}=$;if((0,Iq.alwaysValidSchema)(X,W))return;let Y=w.name("valid");w.forIn("key",Z,(G)=>{$.setParams({propertyName:G}),$.subschema({keyword:"propertyNames",data:G,dataTypes:["string"],propertyName:G,compositeRule:!0},Y),w.if((0,S7.not)(Y),()=>{if($.error(!0),!X.allErrors)w.break()})}),$.ok(Y)}};R7.default=xq});var F5=L((j7)=>{Object.defineProperty(j7,"__esModule",{value:!0});var _8=h0(),r0=h(),gq=B$(),g8=c(),vq={message:"must NOT have additional properties",params:({params:$})=>r0._`{additionalProperty: ${$.additionalProperty}}`},uq={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:vq,code($){let{gen:w,schema:W,parentSchema:Z,data:X,errsCount:Y,it:G}=$;if(!Y)throw Error("ajv implementation error");let{allErrors:J,opts:T}=G;if(G.props=!0,T.removeAdditional!=="all"&&(0,g8.alwaysValidSchema)(G,W))return;let Q=(0,_8.allSchemaProperties)(Z.properties),M=(0,_8.allSchemaProperties)(Z.patternProperties);z(),$.ok(r0._`${Y} === ${gq.default.errors}`);function z(){w.forIn("key",X,(q)=>{if(!Q.length&&!M.length)K(q);else w.if(N(q),()=>K(q))})}function N(q){let f;if(Q.length>8){let H=(0,g8.schemaRefOrVal)(G,Z.properties,"properties");f=(0,_8.isOwnProperty)(w,H,q)}else if(Q.length)f=(0,r0.or)(...Q.map((H)=>r0._`${q} === ${H}`));else f=r0.nil;if(M.length)f=(0,r0.or)(f,...M.map((H)=>r0._`${(0,_8.usePattern)($,H)}.test(${q})`));return(0,r0.not)(f)}function B(q){w.code(r0._`delete ${X}[${q}]`)}function K(q){if(T.removeAdditional==="all"||T.removeAdditional&&W===!1){B(q);return}if(W===!1){if($.setParams({additionalProperty:q}),$.error(),!J)w.break();return}if(typeof W=="object"&&!(0,g8.alwaysValidSchema)(G,W)){let f=w.name("valid");if(T.removeAdditional==="failing")P(q,f,!1),w.if((0,r0.not)(f),()=>{$.reset(),B(q)});else if(P(q,f),!J)w.if((0,r0.not)(f),()=>w.break())}}function P(q,f,H){let E={keyword:"additionalProperties",dataProp:q,dataPropType:g8.Type.Str};if(H===!1)Object.assign(E,{compositeRule:!0,createErrors:!1,allErrors:!1});$.subschema(E,f)}}};j7.default=uq});var x7=L((b7)=>{Object.defineProperty(b7,"__esModule",{value:!0});var iq=ow(),y7=h0(),O5=c(),I7=F5(),mq={keyword:"properties",type:"object",schemaType:"object",code($){let{gen:w,schema:W,parentSchema:Z,data:X,it:Y}=$;if(Y.opts.removeAdditional==="all"&&Z.additionalProperties===void 0)I7.default.code(new iq.KeywordCxt(Y,I7.default,"additionalProperties"));let G=(0,y7.allSchemaProperties)(W);for(let z of G)Y.definedProperties.add(z);if(Y.opts.unevaluated&&G.length&&Y.props!==!0)Y.props=O5.mergeEvaluated.props(w,(0,O5.toHash)(G),Y.props);let J=G.filter((z)=>!(0,O5.alwaysValidSchema)(Y,W[z]));if(J.length===0)return;let T=w.name("valid");for(let z of J){if(Q(z))M(z);else{if(w.if((0,y7.propertyInData)(w,X,z,Y.opts.ownProperties)),M(z),!Y.allErrors)w.else().var(T,!0);w.endIf()}$.it.definedProperties.add(z),$.ok(T)}function Q(z){return Y.opts.useDefaults&&!Y.compositeRule&&W[z].default!==void 0}function M(z){$.subschema({keyword:"properties",schemaProp:z,dataProp:z},T)}}};b7.default=mq});var h7=L((u7)=>{Object.defineProperty(u7,"__esModule",{value:!0});var _7=h0(),v8=h(),g7=c(),v7=c(),cq={keyword:"patternProperties",type:"object",schemaType:"object",code($){let{gen:w,schema:W,data:Z,parentSchema:X,it:Y}=$,{opts:G}=Y,J=(0,_7.allSchemaProperties)(W),T=J.filter((P)=>(0,g7.alwaysValidSchema)(Y,W[P]));if(J.length===0||T.length===J.length&&(!Y.opts.unevaluated||Y.props===!0))return;let Q=G.strictSchema&&!G.allowMatchingProperties&&X.properties,M=w.name("valid");if(Y.props!==!0&&!(Y.props instanceof v8.Name))Y.props=(0,v7.evaluatedPropsToName)(w,Y.props);let{props:z}=Y;N();function N(){for(let P of J){if(Q)B(P);if(Y.allErrors)K(P);else w.var(M,!0),K(P),w.if(M)}}function B(P){for(let q in Q)if(new RegExp(P).test(q))(0,g7.checkStrictMode)(Y,`property ${q} matches pattern ${P} (use allowMatchingProperties)`)}function K(P){w.forIn("key",Z,(q)=>{w.if(v8._`${(0,_7.usePattern)($,P)}.test(${q})`,()=>{let f=T.includes(P);if(!f)$.subschema({keyword:"patternProperties",schemaProp:P,dataProp:q,dataPropType:v7.Type.Str},M);if(Y.opts.unevaluated&&z!==!0)w.assign(v8._`${z}[${q}]`,!0);else if(!f&&!Y.allErrors)w.if((0,v8.not)(M),()=>w.break())})})}}};u7.default=cq});var m7=L((i7)=>{Object.defineProperty(i7,"__esModule",{value:!0});var nq=c(),pq={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code($){let{gen:w,schema:W,it:Z}=$;if((0,nq.alwaysValidSchema)(Z,W)){$.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"}};i7.default=pq});var c7=L((l7)=>{Object.defineProperty(l7,"__esModule",{value:!0});var rq=h0(),sq={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:rq.validateUnion,error:{message:"must match a schema in anyOf"}};l7.default=sq});var n7=L((d7)=>{Object.defineProperty(d7,"__esModule",{value:!0});var u8=h(),oq=c(),eq={message:"must match exactly one schema in oneOf",params:({params:$})=>u8._`{passingSchemas: ${$.passing}}`},$U={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:eq,code($){let{gen:w,schema:W,parentSchema:Z,it:X}=$;if(!Array.isArray(W))throw Error("ajv implementation error");if(X.opts.discriminator&&Z.discriminator)return;let Y=W,G=w.let("valid",!1),J=w.let("passing",null),T=w.name("_valid");$.setParams({passing:J}),w.block(Q),$.result(G,()=>$.reset(),()=>$.error(!0));function Q(){Y.forEach((M,z)=>{let N;if((0,oq.alwaysValidSchema)(X,M))w.var(T,!0);else N=$.subschema({keyword:"oneOf",schemaProp:z,compositeRule:!0},T);if(z>0)w.if(u8._`${T} && ${G}`).assign(G,!1).assign(J,u8._`[${J}, ${z}]`).else();w.if(T,()=>{if(w.assign(G,!0),w.assign(J,z),N)$.mergeEvaluated(N,u8.Name)})})}}};d7.default=$U});var t7=L((p7)=>{Object.defineProperty(p7,"__esModule",{value:!0});var WU=c(),ZU={keyword:"allOf",schemaType:"array",code($){let{gen:w,schema:W,it:Z}=$;if(!Array.isArray(W))throw Error("ajv implementation error");let X=w.name("valid");W.forEach((Y,G)=>{if((0,WU.alwaysValidSchema)(Z,Y))return;let J=$.subschema({keyword:"allOf",schemaProp:G},X);$.ok(X),$.mergeEvaluated(J)})}};p7.default=ZU});var o7=L((a7)=>{Object.defineProperty(a7,"__esModule",{value:!0});var h8=h(),s7=c(),YU={message:({params:$})=>h8.str`must match "${$.ifClause}" schema`,params:({params:$})=>h8._`{failingKeyword: ${$.ifClause}}`},GU={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:YU,code($){let{gen:w,parentSchema:W,it:Z}=$;if(W.then===void 0&&W.else===void 0)(0,s7.checkStrictMode)(Z,'"if" without "then" and "else" is ignored');let X=r7(Z,"then"),Y=r7(Z,"else");if(!X&&!Y)return;let G=w.let("valid",!0),J=w.name("_valid");if(T(),$.reset(),X&&Y){let M=w.let("ifClause");$.setParams({ifClause:M}),w.if(J,Q("then",M),Q("else",M))}else if(X)w.if(J,Q("then"));else w.if((0,h8.not)(J),Q("else"));$.pass(G,()=>$.error(!0));function T(){let M=$.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},J);$.mergeEvaluated(M)}function Q(M,z){return()=>{let N=$.subschema({keyword:M},J);if(w.assign(G,J),$.mergeValidEvaluated(N,G),z)w.assign(z,h8._`${M}`);else $.setParams({ifClause:M})}}}};function r7($,w){let W=$.schema[w];return W!==void 0&&!(0,s7.alwaysValidSchema)($,W)}a7.default=GU});var $J=L((e7)=>{Object.defineProperty(e7,"__esModule",{value:!0});var TU=c(),QU={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:$,parentSchema:w,it:W}){if(w.if===void 0)(0,TU.checkStrictMode)(W,`"${$}" without "if" is ignored`)}};e7.default=QU});var WJ=L((wJ)=>{Object.defineProperty(wJ,"__esModule",{value:!0});var zU=q5(),NU=V7(),KU=U5(),BU=U7(),PU=F7(),VU=A7(),fU=C7(),qU=F5(),UU=x7(),HU=h7(),FU=m7(),OU=c7(),EU=n7(),LU=t7(),DU=o7(),kU=$J();function AU($=!1){let w=[FU.default,OU.default,EU.default,LU.default,DU.default,kU.default,fU.default,qU.default,VU.default,UU.default,HU.default];if($)w.push(NU.default,BU.default);else w.push(zU.default,KU.default);return w.push(PU.default),w}wJ.default=AU});var XJ=L((ZJ)=>{Object.defineProperty(ZJ,"__esModule",{value:!0});var w0=h(),RU={message:({schemaCode:$})=>w0.str`must match format "${$}"`,params:({schemaCode:$})=>w0._`{format: ${$}}`},CU={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:RU,code($,w){let{gen:W,data:Z,$data:X,schema:Y,schemaCode:G,it:J}=$,{opts:T,errSchemaPath:Q,schemaEnv:M,self:z}=J;if(!T.validateFormats)return;if(X)N();else B();function N(){let K=W.scopeValue("formats",{ref:z.formats,code:T.code.formats}),P=W.const("fDef",w0._`${K}[${G}]`),q=W.let("fType"),f=W.let("format");W.if(w0._`typeof ${P} == "object" && !(${P} instanceof RegExp)`,()=>W.assign(q,w0._`${P}.type || "string"`).assign(f,w0._`${P}.validate`),()=>W.assign(q,w0._`"string"`).assign(f,P)),$.fail$data((0,w0.or)(H(),E()));function H(){if(T.strictSchema===!1)return w0.nil;return w0._`${G} && !${f}`}function E(){let S=M.$async?w0._`(${P}.async ? await ${f}(${Z}) : ${f}(${Z}))`:w0._`${f}(${Z})`,A=w0._`(typeof ${f} == "function" ? ${S} : ${f}.test(${Z}))`;return w0._`${f} && ${f} !== true && ${q} === ${w} && !${A}`}}function B(){let K=z.formats[Y];if(!K){H();return}if(K===!0)return;let[P,q,f]=E(K);if(P===w)$.pass(S());function H(){if(T.strictSchema===!1){z.logger.warn(A());return}throw Error(A());function A(){return`unknown format "${Y}" ignored in schema at path "${Q}"`}}function E(A){let j=A instanceof RegExp?(0,w0.regexpCode)(A):T.code.formats?w0._`${T.code.formats}${(0,w0.getProperty)(Y)}`:void 0,g=W.scopeValue("formats",{key:Y,ref:A,code:j});if(typeof A=="object"&&!(A instanceof RegExp))return[A.type||"string",A.validate,w0._`${g}.validate`];return["string",A,g]}function S(){if(typeof K=="object"&&!(K instanceof RegExp)&&K.async){if(!M.$async)throw Error("async format in sync schema");return w0._`await ${f}(${Z})`}return typeof q=="function"?w0._`${f}(${Z})`:w0._`${f}.test(${Z})`}}}};ZJ.default=CU});var GJ=L((YJ)=>{Object.defineProperty(YJ,"__esModule",{value:!0});var yU=XJ(),IU=[yU.default];YJ.default=IU});var QJ=L((JJ)=>{Object.defineProperty(JJ,"__esModule",{value:!0});JJ.contentVocabulary=JJ.metadataVocabulary=void 0;JJ.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];JJ.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var NJ=L((zJ)=>{Object.defineProperty(zJ,"__esModule",{value:!0});var _U=bG(),gU=J7(),vU=WJ(),uU=GJ(),MJ=QJ(),hU=[_U.default,gU.default,(0,vU.default)(),uU.default,MJ.metadataVocabulary,MJ.contentVocabulary];zJ.default=hU});var VJ=L((BJ)=>{Object.defineProperty(BJ,"__esModule",{value:!0});BJ.DiscrError=void 0;var KJ;(function($){$.Tag="tag",$.Mapping="mapping"})(KJ||(BJ.DiscrError=KJ={}))});var UJ=L((qJ)=>{Object.defineProperty(qJ,"__esModule",{value:!0});var e1=h(),E5=VJ(),fJ=F8(),mU=ew(),lU=c(),cU={message:({params:{discrError:$,tagName:w}})=>$===E5.DiscrError.Tag?`tag "${w}" must be string`:`value of tag "${w}" must be in oneOf`,params:({params:{discrError:$,tag:w,tagName:W}})=>e1._`{error: ${$}, tag: ${W}, tagValue: ${w}}`},dU={keyword:"discriminator",type:"object",schemaType:"object",error:cU,code($){let{gen:w,data:W,schema:Z,parentSchema:X,it:Y}=$,{oneOf:G}=X;if(!Y.opts.discriminator)throw Error("discriminator: requires discriminator option");let J=Z.propertyName;if(typeof J!="string")throw Error("discriminator: requires propertyName");if(Z.mapping)throw Error("discriminator: mapping is not supported");if(!G)throw Error("discriminator: requires oneOf keyword");let T=w.let("valid",!1),Q=w.const("tag",e1._`${W}${(0,e1.getProperty)(J)}`);w.if(e1._`typeof ${Q} == "string"`,()=>M(),()=>$.error(!1,{discrError:E5.DiscrError.Tag,tag:Q,tagName:J})),$.ok(T);function M(){let B=N();w.if(!1);for(let K in B)w.elseIf(e1._`${Q} === ${K}`),w.assign(T,z(B[K]));w.else(),$.error(!1,{discrError:E5.DiscrError.Mapping,tag:Q,tagName:J}),w.endIf()}function z(B){let K=w.name("valid"),P=$.subschema({keyword:"oneOf",schemaProp:B},K);return $.mergeEvaluated(P,e1.Name),K}function N(){var B;let K={},P=f(X),q=!0;for(let S=0;S<G.length;S++){let A=G[S];if((A===null||A===void 0?void 0:A.$ref)&&!(0,lU.schemaHasRulesButRef)(A,Y.self.RULES)){let g=A.$ref;if(A=fJ.resolveRef.call(Y.self,Y.schemaEnv.root,Y.baseId,g),A instanceof fJ.SchemaEnv)A=A.schema;if(A===void 0)throw new mU.default(Y.opts.uriResolver,Y.baseId,g)}let j=(B=A===null||A===void 0?void 0:A.properties)===null||B===void 0?void 0:B[J];if(typeof j!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${J}"`);q=q&&(P||f(A)),H(j,S)}if(!q)throw Error(`discriminator: "${J}" must be required`);return K;function f({required:S}){return Array.isArray(S)&&S.includes(J)}function H(S,A){if(S.const)E(S.const,A);else if(S.enum)for(let j of S.enum)E(j,A);else throw Error(`discriminator: "properties/${J}" must have "const" or "enum"`)}function E(S,A){if(typeof S!="string"||S in K)throw Error(`discriminator: "${J}" values must be unique strings`);K[S]=A}}}};qJ.default=dU});var HJ=L((MA,pU)=>{pU.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 OJ=L((R0,L5)=>{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 tU=LG(),rU=NJ(),sU=UJ(),FJ=HJ(),aU=["/properties"],i8="http://json-schema.org/draft-07/schema";class N4 extends tU.default{_addVocabularies(){if(super._addVocabularies(),rU.default.forEach(($)=>this.addVocabulary($)),this.opts.discriminator)this.addKeyword(sU.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let $=this.opts.$data?this.$dataMetaSchema(FJ,aU):FJ;this.addMetaSchema($,i8,!1),this.refs["http://json-schema.org/schema"]=i8}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(i8)?i8:void 0)}}R0.Ajv=N4;L5.exports=R0=N4;L5.exports.Ajv=N4;Object.defineProperty(R0,"__esModule",{value:!0});R0.default=N4;var oU=ow();Object.defineProperty(R0,"KeywordCxt",{enumerable:!0,get:function(){return oU.KeywordCxt}});var $w=h();Object.defineProperty(R0,"_",{enumerable:!0,get:function(){return $w._}});Object.defineProperty(R0,"str",{enumerable:!0,get:function(){return $w.str}});Object.defineProperty(R0,"stringify",{enumerable:!0,get:function(){return $w.stringify}});Object.defineProperty(R0,"nil",{enumerable:!0,get:function(){return $w.nil}});Object.defineProperty(R0,"Name",{enumerable:!0,get:function(){return $w.Name}});Object.defineProperty(R0,"CodeGen",{enumerable:!0,get:function(){return $w.CodeGen}});var eU=U8();Object.defineProperty(R0,"ValidationError",{enumerable:!0,get:function(){return eU.default}});var $H=ew();Object.defineProperty(R0,"MissingRefError",{enumerable:!0,get:function(){return $H.default}})});var W6=L((VR,d5)=>{var w6=process||{},WT=w6.argv||[],$6=w6.env||{},eH=!(!!$6.NO_COLOR||WT.includes("--no-color"))&&(!!$6.FORCE_COLOR||WT.includes("--color")||w6.platform==="win32"||(w6.stdout||{}).isTTY&&$6.TERM!=="dumb"||!!$6.CI),$F=($,w,W=$)=>(Z)=>{let X=""+Z,Y=X.indexOf(w,$.length);return~Y?$+wF(X,w,W,Y)+w:$+X+w},wF=($,w,W,Z)=>{let X="",Y=0;do X+=$.substring(Y,Z)+W,Y=Z+w.length,Z=$.indexOf(w,Y);while(~Z);return X+$.substring(Y)},ZT=($=eH)=>{let w=$?$F:()=>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")}};d5.exports=ZT();d5.exports.createColors=ZT});import{realpathSync as iM}from"fs";import{realpath as nL}from"fs/promises";import pL from"path";import{createInterface as tL}from"readline/promises";import{fileURLToPath as rL}from"url";var lX=m1(EW(),1),{program:QD,createCommand:MD,createArgument:zD,createOption:ND,CommanderError:KD,InvalidArgumentError:BD,InvalidOptionArgumentError:PD,Command:cX,Argument:VD,Option:fD,Help:qD}=lX.default;import dX from"node:os";import Z8 from"node:path";function nX(){return process.env.XDG_CONFIG_HOME?Z8.join(process.env.XDG_CONFIG_HOME,"coden"):Z8.join(dX.homedir(),".config","coden")}function pX(){return process.env.XDG_DATA_HOME?Z8.join(process.env.XDG_DATA_HOME,"coden"):Z8.join(dX.homedir(),".local","share","coden")}import{mkdir as mz,readFile as lz,realpath as tX,writeFile as cz}from"node:fs/promises";import dz from"node:path";class LW{file;constructor($){this.file=$}async isTrusted($){return(await this.read()).includes($)}async isWorkspaceTrusted($){return this.isTrusted(await tX($))}async trustWorkspace($){return this.trust(await tX($))}async trust($){let w=await this.read();if(!w.includes($))w.push($);await mz(dz.dirname(this.file),{recursive:!0}),await cz(this.file,`${JSON.stringify(w,null,2)}
36
36
  `,{encoding:"utf8",mode:384})}async read(){try{let $=JSON.parse(await lz(this.file,"utf8"));return Array.isArray($)?$.filter((w)=>typeof w==="string"):[]}catch($){if($.code==="ENOENT")return[];throw $}}}function l1($,w){if($.length<=w)return $;let Z=Math.max(0,w-80),X=Math.ceil(Z/2),Y=Math.floor(Z/2),G=$.length-X-Y;return`${$.slice(0,X)}
37
37
  ... [${G} characters omitted] ...
38
- ${$.slice($.length-Y)}`}class y extends Error{category;code;retryable;details;constructor($,w,W,Z=!1,X,Y){super(W,Y);this.category=$;this.code=w;this.retryable=Z;this.details=X;this.name="CodeNError"}}import{spawn as nz}from"node:child_process";class LW{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 W=$.slice(w);if(W)this.tail=`${this.tail}${W}`.slice(-this.tailLimit)}value(){let $=this.total-this.head.length-this.tail.length;return $>0?`${this.head}
38
+ ${$.slice($.length-Y)}`}class y extends Error{category;code;retryable;details;constructor($,w,W,Z=!1,X,Y){super(W,Y);this.category=$;this.code=w;this.retryable=Z;this.details=X;this.name="CodeNError"}}import{spawn as nz}from"node:child_process";class DW{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 W=$.slice(w);if(W)this.tail=`${this.tail}${W}`.slice(-this.tailLimit)}value(){let $=this.total-this.head.length-this.tail.length;return $>0?`${this.head}
39
39
  ... [${$} characters omitted while capturing] ...
40
- ${this.tail}`:`${this.head}${this.tail}`}}var Z8=($,w,W)=>new Promise((Z)=>{let X=process.platform!=="win32",Y=nz($,w,{cwd:W.cwd,env:W.env,stdio:["ignore","pipe","pipe"],detached:X}),G=new LW(W.maxOutputChars),J=new LW(W.maxOutputChars),T=!1,Q=!1,M=!1,z,N,B=(f)=>{if(X&&Y.pid)try{process.kill(-Y.pid,f);return}catch{}Y.kill(f)},K=(f,H)=>{if(M)return;if((T||Q)&&X&&Y.pid)try{process.kill(-Y.pid,"SIGKILL")}catch{}if(M=!0,clearTimeout(N),z)clearTimeout(z);W.signal?.removeEventListener("abort",q),Z({ok:!T&&!Q&&f===0,stdout:G.value(),stderr:J.value(),exitCode:f,signal:H,timedOut:T,cancelled:Q})},P=()=>{if(z)return;z=setTimeout(()=>B("SIGKILL"),500),z.unref()},q=()=>{if(Q)return;Q=!0,B("SIGTERM"),P()};if(Y.stdout.setEncoding("utf8"),Y.stderr.setEncoding("utf8"),Y.stdout.on("data",(f)=>G.add(f)),Y.stderr.on("data",(f)=>J.add(f)),Y.once("error",(f)=>{J.add(f.message),K(null,null)}),Y.once("close",K),W.signal?.aborted)q();else W.signal?.addEventListener("abort",q,{once:!0});N=setTimeout(()=>{T=!0,B("SIGTERM"),P()},W.timeoutMs)});function pz($){let w=$.timedOut?"bun install timed out":$.cancelled?"bun install cancelled":`bun install exited with code ${$.exitCode??"null"}${$.signal?` (signal ${$.signal})`:""}`;return l1([w,$.stderr?`stderr:
40
+ ${this.tail}`:`${this.head}${this.tail}`}}var X8=($,w,W)=>new Promise((Z)=>{let X=process.platform!=="win32",Y=nz($,w,{cwd:W.cwd,env:W.env,stdio:["ignore","pipe","pipe"],detached:X}),G=new DW(W.maxOutputChars),J=new DW(W.maxOutputChars),T=!1,Q=!1,M=!1,z,N,B=(f)=>{if(X&&Y.pid)try{process.kill(-Y.pid,f);return}catch{}Y.kill(f)},K=(f,H)=>{if(M)return;if((T||Q)&&X&&Y.pid)try{process.kill(-Y.pid,"SIGKILL")}catch{}if(M=!0,clearTimeout(N),z)clearTimeout(z);W.signal?.removeEventListener("abort",q),Z({ok:!T&&!Q&&f===0,stdout:G.value(),stderr:J.value(),exitCode:f,signal:H,timedOut:T,cancelled:Q})},P=()=>{if(z)return;z=setTimeout(()=>B("SIGKILL"),500),z.unref()},q=()=>{if(Q)return;Q=!0,B("SIGTERM"),P()};if(Y.stdout.setEncoding("utf8"),Y.stderr.setEncoding("utf8"),Y.stdout.on("data",(f)=>G.add(f)),Y.stderr.on("data",(f)=>J.add(f)),Y.once("error",(f)=>{J.add(f.message),K(null,null)}),Y.once("close",K),W.signal?.aborted)q();else W.signal?.addEventListener("abort",q,{once:!0});N=setTimeout(()=>{T=!0,B("SIGTERM"),P()},W.timeoutMs)});function pz($){let w=$.timedOut?"bun install timed out":$.cancelled?"bun install cancelled":`bun install exited with code ${$.exitCode??"null"}${$.signal?` (signal ${$.signal})`:""}`;return l1([w,$.stderr?`stderr:
41
41
  ${$.stderr}`:`stderr:
42
42
  <empty>`].join(`
43
- `),4000)}class DW{runner;constructor($=Z8){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 W=await this.runner("bun",w,{cwd:$.cwd,env:process.env,...$.signal?{signal:$.signal}:{},timeoutMs:120000,maxOutputChars:30000});if(!W.ok)throw new y("plugin","plugin.install_failed",pz(W))}}import BH from"node:path";import{pathToFileURL as PH}from"node:url";var EJ=m1(FJ(),1);var L5=new EJ.default({allErrors:!0,strict:!1,useDefaults:!0});class W${#$=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 W=this.#$.get($.name);if(W)throw new y("plugin","tool.duplicate",`Duplicate tool: ${$.name} from ${OJ(W.source)} and ${OJ(w)}`);try{L5.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 W$;return $.#$=new Map(this.#$),$}replaceWith($){this.#$=new Map($.#$)}validate($,w){let W=this.get($);if(!W)return{valid:!1,errors:`Unknown tool: ${$}`};let Z=L5.compile(W.inputSchema);return Z(w)?{valid:!0}:{valid:!1,errors:L5.errorsText(Z.errors)}}}function OJ($){switch($.kind){case"builtin":return"builtin";case"local":return $.path?`local:${$.path}`:"local";case"npm":return $.path?`${$.pluginName}@${$.pluginVersion}:${$.path}`:`${$.pluginName}@${$.pluginVersion}`}}var D5=1;function i8($,w){if(LJ($))return[$];if(!$||typeof $!=="object")throw new y("plugin","plugin.export_invalid","plugin.export_invalid: default export must be a tool or CodeNPlugin");let W=$;if(W.apiVersion!==D5)throw new y("plugin","plugin.api_unsupported",`plugin.api_unsupported: ${String(W.apiVersion)}`);if(W.name!==w)throw new y("plugin","plugin.name_mismatch",`plugin.name_mismatch: expected ${w}, received ${String(W.name)}`);if(!Array.isArray(W.tools)||W.tools.length===0)throw new y("plugin","plugin.export_invalid","plugin.export_invalid: tools must be a non-empty array");if(!W.tools.every(LJ))throw new y("plugin","plugin.export_invalid","plugin.export_invalid: every tool must match ToolDefinition");return W.tools}function LJ($){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 YH}from"node:fs/promises";var ZH=/^(?:@[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*|[a-z0-9][a-z0-9._-]*)$/;function M1($){return ZH.test($)&&!$.includes("..")&&!$.includes("\\")}function DJ($){if(typeof $!=="string"||!$.startsWith("npm:"))throw K9($);let w=$.slice(4);if(!w||/\s/.test(w)||w.includes("\\")||w.includes("://"))throw K9($);let{packageName:W,requested:Z}=XH(w);if(!M1(W))throw K9($);if(!Z||/\s/.test(Z)||Z.includes("\\")||Z.includes("/")||Z.includes(":")||Z.includes(".."))throw K9($);return{source:"npm",packageName:W,requested:Z,raw:$}}function XH($){if($.startsWith("@")){let W=$.indexOf("/");if(W<2)throw K9($);let Z=$.lastIndexOf("@");if(Z<=W)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 K9($){return new y("plugin","plugin.specifier_invalid",`plugin.specifier_invalid: ${String($)}`)}var GH=()=>({schemaVersion:1,plugins:{}});async function f$($){try{let w=JSON.parse(await YH($,"utf8"));return A5(w)}catch(w){if(JH(w))return GH();if(w instanceof y)throw w;throw z1(w,$)}}function k5($){return`${JSON.stringify(A5($),null,2)}
44
- `}function kJ($){let w=A5($),W={};for(let[Z,X]of Object.entries(w.plugins))W[Z]=X.requested;return{private:!0,dependencies:W}}function A5($){if(!$||typeof $!=="object")throw z1();let w=$;if(w.schemaVersion!==1)throw z1();if(!w.plugins||typeof w.plugins!=="object"||Array.isArray(w.plugins))throw z1();let W={};for(let Z of Object.keys(w.plugins).sort()){if(!M1(Z))throw z1();let X=w.plugins[Z];if(!X||typeof X!=="object"||Array.isArray(X))throw z1();let Y=X;if(Y.source!=="npm"||typeof Y.requested!=="string"||!Y.requested)throw z1();W[Z]={source:"npm",requested:Y.requested}}return{schemaVersion:1,plugins:W}}function JH($){return typeof $==="object"&&$!==null&&"code"in $&&$.code==="ENOENT"}function z1($,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 TH,realpath as QH}from"node:fs/promises";import m8 from"node:path";async function ww($,w){if(!M1(w))throw N1();let W=m8.join($,"node_modules",...w.split("/")),Z=m8.join(W,"package.json"),X;try{X=JSON.parse(await TH(Z,"utf8"))}catch{throw N1()}let Y=MH(X,w),G=await AJ(W),J=m8.resolve(W,Y.entry),T=await AJ(J,!0);if(!zH(G,T))throw S5();return{packageName:w,version:Y.version,packageDirectory:G,entryPath:T,apiVersion:1}}function MH($,w){if(!$||typeof $!=="object")throw N1();let W=$;if(W.name!==w||typeof W.version!=="string"||!W.version)throw N1();if(W.type!=="module")throw N1();if(!W.coden||typeof W.coden!=="object"||Array.isArray(W.coden))throw N1();let Z=W.coden;if(Z.apiVersion!==1)throw KH(Z.apiVersion);if(typeof Z.plugin!=="string"||!NH(Z.plugin))throw S5();return{version:W.version,entry:Z.plugin}}async function AJ($,w=!1){try{return await QH($)}catch{if(w)throw S5();throw N1()}}function zH($,w){return w===$||w.startsWith(`${$}${m8.sep}`)}function NH($){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 N1(){return new y("plugin","plugin.metadata_missing","plugin.metadata_missing")}function KH($){return new y("plugin","plugin.api_unsupported",`plugin.api_unsupported: ${String($)}`)}function S5(){return new y("plugin","plugin.entry_invalid","plugin.entry_invalid")}class R5{importer;constructor($=(w)=>import(w)){this.importer=$}async loadScope($){let w=await f$($.manifestPath),W=[],Z=[];for(let X of Object.keys(w.plugins).sort()){let Y=VH($.runtimeDir,X);try{let G=await ww($.runtimeDir,X);try{let J=await this.importer(PH(G.entryPath).href),T=i8(J.default,X);W.push({packageName:X,version:G.version,entryPath:G.entryPath,tools:T})}catch(J){Z.push({packageName:X,path:G.entryPath,message:SJ(J)})}}catch(G){Z.push({packageName:X,path:Y,message:SJ(G)})}}return{loaded:W,failed:Z}}}function VH($,w){return BH.join($,"node_modules",...w.split("/"))}function SJ($){return $ instanceof Error?$.message:String($)}import{constants as AH}from"node:fs";import{access as SH,copyFile as RH,mkdir as CH,writeFile as d8}from"node:fs/promises";import i$ from"node:path";import fH from"node:path";import{pathToFileURL as qH}from"node:url";class C5{importer;constructor($=(w)=>import(w)){this.importer=$}async loadScope($){let w=await f$($.manifestPath),W=[],Z=[];for(let X of Object.keys(w.plugins).sort()){let Y=HH($.runtimeDir,X);try{let G=await ww($.runtimeDir,X);try{let J=await this.importer(qH(G.entryPath).href),T=i8(J.default,X);W.push({packageName:X,version:G.version,entryPath:G.entryPath,tools:T})}catch(J){Z.push({packageName:X,path:G.entryPath,message:CJ(J)})}}catch(G){Z.push({packageName:X,path:Y,message:CJ(G)})}}return{loaded:W,failed:Z}}}function j5($,w,W){let Z=new W$($),X=new Map(W.map((T)=>[T.packageName,T])),Y=[],G=[];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}G.push(T)}let J=[...G,...W];for(let T of J)UH(Z,T);return{registry:Z,effective:J,shadowed:Y}}function UH($,w){let W={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 ${RJ(X)} conflicts with ${RJ(W)}`);$.register(Z,W)}}function HH($,w){return fH.join($,"node_modules",...w.split("/"))}function RJ($){switch($.kind){case"builtin":return"builtin";case"local":return $.path?`local:${$.path}`:"local";case"npm":return $.path?`${$.pluginName}@${$.pluginVersion}:${$.path}`:`${$.pluginName}@${$.pluginVersion}`}}function CJ($){return $ instanceof Error?$.message:String($)}import Z$ from"node:path";import{readFile as FH}from"node:fs/promises";import IJ from"node:os";import Ww from"node:path";function l8(){return process.env.XDG_CONFIG_HOME?Ww.join(process.env.XDG_CONFIG_HOME,"coden"):Ww.join(IJ.homedir(),".config","coden")}function y5(){return process.env.XDG_DATA_HOME?Ww.join(process.env.XDG_DATA_HOME,"coden"):Ww.join(IJ.homedir(),".local","share","coden")}async function jJ($){try{let w=JSON.parse(await FH($,"utf8"));return OH(w)}catch(w){if(w.code==="ENOENT")return{};throw Error(`Cannot read config ${$}: ${w instanceof Error?w.message:String(w)}`)}}function OH($){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((W)=>typeof W==="string");if($.env!==void 0){if(typeof $.env!=="object"||$.env===null||Array.isArray($.env))throw Error("env must be an object");let W={};for(let[Z,X]of Object.entries($.env)){if(typeof X!=="string")throw Error(`env "${Z}" must be a string`);W[Z]=X}w.env=W}return w}function yJ($){let{env:w,...W}=$;return W}async function bJ($,w={}){let W={provider:"openai",model:"gpt-5-mini",maxSteps:20,contextWindow:128000,reservedOutputTokens:8192,safetyMargin:4096,plugins:[],dataDir:y5(),env:{}},Z=await jJ(Ww.join(l8(),"config.json")),X=await jJ(Ww.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 G={...Z.env??{},...X.env??{}};for(let[T,Q]of Object.entries(G))if(process.env[T]===void 0)process.env[T]=Q;let J={...W,...yJ(Z),...yJ(X),...Y,...w,env:G};if(J.plugins=[...Z.plugins??[],...X.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 B9($,w,W=y5()){if(w==="project"){let Y=Z$.join($,".coden"),G=Z$.join(Y,"plugin-runtime");return{scope:w,root:Y,manifestPath:Z$.join(Y,"plugins.json"),runtimeDir:G,lockPath:Z$.join(Y,"plugin-lock"),transactionPath:Z$.join(Y,"plugin-transaction.json")}}let Z=Z$.join(W,"plugins"),X=Z$.join(Z,"runtime");return{scope:w,root:Z,manifestPath:Z$.join(Z,"plugins.json"),runtimeDir:X,lockPath:Z$.join(Z,"plugin-lock"),transactionPath:Z$.join(Z,"plugin-transaction.json")}}import{randomUUID as EH}from"node:crypto";import{constants as LH}from"node:fs";import{access as DH,mkdir as c8,readFile as xJ,rename as h$,rm as W0,writeFile as _J}from"node:fs/promises";import u$ from"node:path";class b5 extends Error{constructor($){super($ instanceof Error?$.message:String($),$ instanceof Error?{cause:$}:void 0);this.name="FaultInterruption"}}class j0{paths;options;constructor($,w={}){this.paths=$;this.options=w}async run($){let w=!1,W;try{await this.acquireLock(),w=!0,await this.recoverLocked();let Z=EH(),X=u$.join(this.paths.root,`.transaction-${Z}-stage`);W={version:1,id:Z,phase:"prepared",stageDirectory:X,backupManifestPath:u$.join(this.paths.root,`.transaction-${Z}-plugins.json.bak`),backupRuntimeDir:u$.join(this.paths.root,`.transaction-${Z}-runtime.bak`),hadManifest:await P9(this.paths.manifestPath),hadRuntime:await P9(this.paths.runtimeDir)},await c8(X,{recursive:!0});let Y={manifestPath:u$.join(X,"plugins.json"),runtimeDir:u$.join(X,"runtime")},G=await $(Y);await this.verifyCandidate(Y),await this.writeMarker(W),await this.backupCurrent(W);let J={...W,phase:"backed-up"};await this.writeMarker(J),W=J,this.fault("after-backup"),await h$(Y.runtimeDir,this.paths.runtimeDir);let T={...W,phase:"runtime-committed"};await this.writeMarker(T),W=T,this.fault("after-runtime-commit"),await h$(Y.manifestPath,this.paths.manifestPath);let Q={...W,phase:"manifest-committed"};return await this.writeMarker(Q),W=Q,this.fault("after-manifest-commit"),await this.cleanupCommitted(W),G}catch(Z){if(Z instanceof b5)throw Z.cause??Z;throw await this.rollbackAfterError(W),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 c8(this.paths.root,{recursive:!0});for(let $=0;$<2;$++){try{await c8(this.paths.lockPath)}catch(w){if(!I5(w,"EEXIST"))throw w;let W=await this.readLockOwner();if(!W||this.isProcessAlive(W.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 W0(this.paths.lockPath,{recursive:!0,force:!0});continue}try{await _J(u$.join(this.paths.lockPath,"owner.json"),`${JSON.stringify({pid:process.pid,createdAt:this.now()})}
45
- `,{mode:384});return}catch(w){throw await W0(this.paths.lockPath,{recursive:!0,force:!0}),w}}}async readLockOwner(){try{let $=JSON.parse(await xJ(u$.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 W0(this.paths.lockPath,{recursive:!0,force:!0})}async verifyCandidate($){if(!await P9($.manifestPath)||!await P9($.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 W0($.backupManifestPath,{force:!0}),await W0($.backupRuntimeDir,{recursive:!0,force:!0}),$.hadManifest)await h$(this.paths.manifestPath,$.backupManifestPath);if($.hadRuntime)await h$(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 W0($.stageDirectory,{recursive:!0,force:!0}),await W0(this.paths.transactionPath,{force:!0});return}if($.phase==="backed-up"||$.phase==="runtime-committed"){await this.removeCurrentTargets(),await this.restoreBackups($),await this.cleanupRecoveryArtifacts($);return}await W0($.backupManifestPath,{force:!0}),await W0($.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 xJ(this.paths.transactionPath,"utf8"));if(!kH($))throw Error("invalid transaction marker");return $}catch($){if(I5($,"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 c8(u$.dirname(this.paths.transactionPath),{recursive:!0});let w=`${this.paths.transactionPath}.tmp`;await _J(w,`${JSON.stringify($,null,2)}
46
- `,{mode:384}),await h$(w,this.paths.transactionPath)}async cleanupCommitted($){await W0($.backupManifestPath,{force:!0}),await W0($.backupRuntimeDir,{recursive:!0,force:!0}),await W0($.stageDirectory,{recursive:!0,force:!0}),await W0(this.paths.transactionPath,{force:!0}),await W0(`${this.paths.transactionPath}.tmp`,{recursive:!0,force:!0})}async cleanupRecoveryArtifacts($){await W0($.stageDirectory,{recursive:!0,force:!0}),await W0(this.paths.transactionPath,{force:!0}),await W0(`${this.paths.transactionPath}.tmp`,{recursive:!0,force:!0})}async removeCurrentTargets(){await W0(this.paths.manifestPath,{force:!0}),await W0(this.paths.runtimeDir,{recursive:!0,force:!0})}async restoreBackups($){if($.hadManifest)await h$($.backupManifestPath,this.paths.manifestPath);if($.hadRuntime)await h$($.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 P9($.backupPath)){await W0($.targetPath,{recursive:$.directory,force:!0}),await h$($.backupPath,$.targetPath);return}if(!$.hadTarget)await W0($.targetPath,{recursive:$.directory,force:!0})}fault($){try{this.options.fault?.($)}catch(w){throw new b5(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!I5(w,"ESRCH")}}}function kH($){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 P9($){try{return await DH($,LH.F_OK),!0}catch{return!1}}function I5($,w){return typeof $==="object"&&$!==null&&"code"in $&&$.code===w}class g5{workspace;dataDir;packageManager;loader;builtins;constructor($,w,W,Z,X){this.workspace=$;this.dataDir=w;this.packageManager=W;this.loader=Z;this.builtins=X}async install($,w){let W=DJ($),Z=this.paths(w.scope);await new j0(Z).recover();let X=await f$(Z.manifestPath);if(X.plugins[W.packageName]?.requested===W.requested){let T=await this.loader.loadScope(Z),Q=T.loaded.find((M)=>M.packageName===W.packageName);if(T.failed.length===0&&Q)return x5(Q,W.requested,w.scope)}let Y=gJ(X);Y.plugins[W.packageName]={source:"npm",requested:W.requested};let G=[];await new j0(Z).run(async(T)=>{G=await this.buildCandidate(T,Y,Z,w,!1),await this.validateCandidate(Z.scope,G)});let J=G.find((T)=>T.packageName===W.packageName);if(!J)throw _5([{packageName:W.packageName,path:Z.runtimeDir,message:"plugin did not load"}]);return x5(J,W.requested,w.scope)}async remove($,w){if(!M1($))throw IH($);let W=this.paths(w.scope);await new j0(W).recover();let Z=await f$(W.manifestPath);if(!Z.plugins[$])throw new y("plugin","plugin.install_failed",`plugin.install_failed: ${$} is not installed in ${w.scope} scope`);let X=gJ(Z);delete X.plugins[$],await new j0(W).run(async(Y)=>{let G=await this.buildCandidate(Y,X,W,w,!1);await this.validateCandidate(W.scope,G)})}async sync($){let w=this.paths($.scope);await new j0(w).recover();let W=await f$(w.manifestPath);if($.scope==="project"&&Object.keys(W.plugins).length>0&&!await vJ(i$.join(w.runtimeDir,"bun.lock")))throw new y("plugin","plugin.lock_missing",`plugin.lock_missing: ${$.scope} plugin sync requires ${i$.join(w.runtimeDir,"bun.lock")}`);let Z=[];return await new j0(w).run(async(X)=>{Z=await this.buildCandidate(X,W,w,$,!0),await this.validateCandidate(w.scope,Z)}),Z.map((X)=>x5(X,W.plugins[X.packageName]?.requested??"latest",$.scope))}async list(){let[$,w]=await Promise.all([this.listScope(this.paths("project")),this.listScope(this.paths("global"))]),W=new Set($.map((Z)=>Z.packageName));return{project:$,global:w.map((Z)=>({...Z,shadowedByProject:W.has(Z.packageName)}))}}paths($){return B9(this.workspace,$,this.dataDir)}async buildCandidate($,w,W,Z,X){if(await CH($.runtimeDir,{recursive:!0}),await d8($.manifestPath,k5(w),"utf8"),await d8(i$.join($.runtimeDir,"package.json"),`${JSON.stringify(kJ(w),null,2)}
47
- `,"utf8"),await vJ(i$.join(W.runtimeDir,"bun.lock")))await RH(i$.join(W.runtimeDir,"bun.lock"),i$.join($.runtimeDir,"bun.lock"));try{await this.packageManager.install({cwd:$.runtimeDir,frozenLockfile:X,allowScripts:Z.allowScripts,...Z.signal?{signal:Z.signal}:{}})}catch(G){throw bH(G,X)}await jH($.runtimeDir,w),await yH($.runtimeDir,W.scope);let Y=await this.loader.loadScope({...W,manifestPath:$.manifestPath,runtimeDir:$.runtimeDir});if(Y.failed.length>0)throw _5(Y.failed);return Y.loaded}async validateCandidate($,w){if($==="global"){j5(this.builtins,w,[]);return}let W=this.paths("global");await new j0(W).recover();let Z=await this.loadScopeOrThrow(W);j5(this.builtins,Z,w)}async loadScopeOrThrow($){let w=await this.loader.loadScope($);if(w.failed.length>0)throw _5(w.failed);return w.loaded}async listScope($){await new j0($).recover();let w=await f$($.manifestPath),W=[];for(let Z of Object.keys(w.plugins).sort()){let X=await ww($.runtimeDir,Z);W.push({packageName:Z,requested:w.plugins[Z]?.requested??"latest",version:X.version,tools:[],scope:$.scope,shadowedByProject:!1})}return W}}async function jH($,w){if(Object.keys(w.plugins).length>0)return;await d8(i$.join($,"bun.lock"),"","utf8")}async function yH($,w){if(w!=="project")return;await d8(i$.join($,".gitignore"),`*
43
+ `),4000)}class kW{runner;constructor($=X8){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 W=await this.runner("bun",w,{cwd:$.cwd,env:process.env,...$.signal?{signal:$.signal}:{},timeoutMs:120000,maxOutputChars:30000});if(!W.ok)throw new y("plugin","plugin.install_failed",pz(W))}}import BH from"node:path";import{pathToFileURL as PH}from"node:url";var LJ=m1(OJ(),1);var D5=new LJ.default({allErrors:!0,strict:!1,useDefaults:!0});class W${#$=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 W=this.#$.get($.name);if(W)throw new y("plugin","tool.duplicate",`Duplicate tool: ${$.name} from ${EJ(W.source)} and ${EJ(w)}`);try{D5.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 W$;return $.#$=new Map(this.#$),$}replaceWith($){this.#$=new Map($.#$)}validate($,w){let W=this.get($);if(!W)return{valid:!1,errors:`Unknown tool: ${$}`};let Z=D5.compile(W.inputSchema);return Z(w)?{valid:!0}:{valid:!1,errors:D5.errorsText(Z.errors)}}}function EJ($){switch($.kind){case"builtin":return"builtin";case"local":return $.path?`local:${$.path}`:"local";case"npm":return $.path?`${$.pluginName}@${$.pluginVersion}:${$.path}`:`${$.pluginName}@${$.pluginVersion}`}}var k5=1;function m8($,w){if(DJ($))return[$];if(!$||typeof $!=="object")throw new y("plugin","plugin.export_invalid","plugin.export_invalid: default export must be a tool or CodeNPlugin");let W=$;if(W.apiVersion!==k5)throw new y("plugin","plugin.api_unsupported",`plugin.api_unsupported: ${String(W.apiVersion)}`);if(W.name!==w)throw new y("plugin","plugin.name_mismatch",`plugin.name_mismatch: expected ${w}, received ${String(W.name)}`);if(!Array.isArray(W.tools)||W.tools.length===0)throw new y("plugin","plugin.export_invalid","plugin.export_invalid: tools must be a non-empty array");if(!W.tools.every(DJ))throw new y("plugin","plugin.export_invalid","plugin.export_invalid: every tool must match ToolDefinition");return W.tools}function DJ($){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 YH}from"node:fs/promises";var ZH=/^(?:@[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*|[a-z0-9][a-z0-9._-]*)$/;function M1($){return ZH.test($)&&!$.includes("..")&&!$.includes("\\")}function kJ($){if(typeof $!=="string"||!$.startsWith("npm:"))throw K4($);let w=$.slice(4);if(!w||/\s/.test(w)||w.includes("\\")||w.includes("://"))throw K4($);let{packageName:W,requested:Z}=XH(w);if(!M1(W))throw K4($);if(!Z||/\s/.test(Z)||Z.includes("\\")||Z.includes("/")||Z.includes(":")||Z.includes(".."))throw K4($);return{source:"npm",packageName:W,requested:Z,raw:$}}function XH($){if($.startsWith("@")){let W=$.indexOf("/");if(W<2)throw K4($);let Z=$.lastIndexOf("@");if(Z<=W)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 K4($){return new y("plugin","plugin.specifier_invalid",`plugin.specifier_invalid: ${String($)}`)}var GH=()=>({schemaVersion:1,plugins:{}});async function f$($){try{let w=JSON.parse(await YH($,"utf8"));return S5(w)}catch(w){if(JH(w))return GH();if(w instanceof y)throw w;throw z1(w,$)}}function A5($){return`${JSON.stringify(S5($),null,2)}
44
+ `}function AJ($){let w=S5($),W={};for(let[Z,X]of Object.entries(w.plugins))W[Z]=X.requested;return{private:!0,dependencies:W}}function S5($){if(!$||typeof $!=="object")throw z1();let w=$;if(w.schemaVersion!==1)throw z1();if(!w.plugins||typeof w.plugins!=="object"||Array.isArray(w.plugins))throw z1();let W={};for(let Z of Object.keys(w.plugins).sort()){if(!M1(Z))throw z1();let X=w.plugins[Z];if(!X||typeof X!=="object"||Array.isArray(X))throw z1();let Y=X;if(Y.source!=="npm"||typeof Y.requested!=="string"||!Y.requested)throw z1();W[Z]={source:"npm",requested:Y.requested}}return{schemaVersion:1,plugins:W}}function JH($){return typeof $==="object"&&$!==null&&"code"in $&&$.code==="ENOENT"}function z1($,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 TH,realpath as QH}from"node:fs/promises";import l8 from"node:path";async function ww($,w){if(!M1(w))throw N1();let W=l8.join($,"node_modules",...w.split("/")),Z=l8.join(W,"package.json"),X;try{X=JSON.parse(await TH(Z,"utf8"))}catch{throw N1()}let Y=MH(X,w),G=await SJ(W),J=l8.resolve(W,Y.entry),T=await SJ(J,!0);if(!zH(G,T))throw R5();return{packageName:w,version:Y.version,packageDirectory:G,entryPath:T,apiVersion:1}}function MH($,w){if(!$||typeof $!=="object")throw N1();let W=$;if(W.name!==w||typeof W.version!=="string"||!W.version)throw N1();if(W.type!=="module")throw N1();if(!W.coden||typeof W.coden!=="object"||Array.isArray(W.coden))throw N1();let Z=W.coden;if(Z.apiVersion!==1)throw KH(Z.apiVersion);if(typeof Z.plugin!=="string"||!NH(Z.plugin))throw R5();return{version:W.version,entry:Z.plugin}}async function SJ($,w=!1){try{return await QH($)}catch{if(w)throw R5();throw N1()}}function zH($,w){return w===$||w.startsWith(`${$}${l8.sep}`)}function NH($){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 N1(){return new y("plugin","plugin.metadata_missing","plugin.metadata_missing")}function KH($){return new y("plugin","plugin.api_unsupported",`plugin.api_unsupported: ${String($)}`)}function R5(){return new y("plugin","plugin.entry_invalid","plugin.entry_invalid")}class C5{importer;constructor($=(w)=>import(w)){this.importer=$}async loadScope($){let w=await f$($.manifestPath),W=[],Z=[];for(let X of Object.keys(w.plugins).sort()){let Y=VH($.runtimeDir,X);try{let G=await ww($.runtimeDir,X);try{let J=await this.importer(PH(G.entryPath).href),T=m8(J.default,X);W.push({packageName:X,version:G.version,entryPath:G.entryPath,tools:T})}catch(J){Z.push({packageName:X,path:G.entryPath,message:RJ(J)})}}catch(G){Z.push({packageName:X,path:Y,message:RJ(G)})}}return{loaded:W,failed:Z}}}function VH($,w){return BH.join($,"node_modules",...w.split("/"))}function RJ($){return $ instanceof Error?$.message:String($)}import{constants as AH}from"node:fs";import{access as SH,copyFile as RH,mkdir as CH,writeFile as n8}from"node:fs/promises";import i$ from"node:path";import fH from"node:path";import{pathToFileURL as qH}from"node:url";class j5{importer;constructor($=(w)=>import(w)){this.importer=$}async loadScope($){let w=await f$($.manifestPath),W=[],Z=[];for(let X of Object.keys(w.plugins).sort()){let Y=HH($.runtimeDir,X);try{let G=await ww($.runtimeDir,X);try{let J=await this.importer(qH(G.entryPath).href),T=m8(J.default,X);W.push({packageName:X,version:G.version,entryPath:G.entryPath,tools:T})}catch(J){Z.push({packageName:X,path:G.entryPath,message:jJ(J)})}}catch(G){Z.push({packageName:X,path:Y,message:jJ(G)})}}return{loaded:W,failed:Z}}}function y5($,w,W){let Z=new W$($),X=new Map(W.map((T)=>[T.packageName,T])),Y=[],G=[];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}G.push(T)}let J=[...G,...W];for(let T of J)UH(Z,T);return{registry:Z,effective:J,shadowed:Y}}function UH($,w){let W={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 ${CJ(X)} conflicts with ${CJ(W)}`);$.register(Z,W)}}function HH($,w){return fH.join($,"node_modules",...w.split("/"))}function CJ($){switch($.kind){case"builtin":return"builtin";case"local":return $.path?`local:${$.path}`:"local";case"npm":return $.path?`${$.pluginName}@${$.pluginVersion}:${$.path}`:`${$.pluginName}@${$.pluginVersion}`}}function jJ($){return $ instanceof Error?$.message:String($)}import Z$ from"node:path";import{readFile as FH}from"node:fs/promises";import bJ from"node:os";import Ww from"node:path";function c8(){return process.env.XDG_CONFIG_HOME?Ww.join(process.env.XDG_CONFIG_HOME,"coden"):Ww.join(bJ.homedir(),".config","coden")}function I5(){return process.env.XDG_DATA_HOME?Ww.join(process.env.XDG_DATA_HOME,"coden"):Ww.join(bJ.homedir(),".local","share","coden")}async function yJ($){try{let w=JSON.parse(await FH($,"utf8"));return OH(w)}catch(w){if(w.code==="ENOENT")return{};throw Error(`Cannot read config ${$}: ${w instanceof Error?w.message:String(w)}`)}}function OH($){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((W)=>typeof W==="string");if($.env!==void 0){if(typeof $.env!=="object"||$.env===null||Array.isArray($.env))throw Error("env must be an object");let W={};for(let[Z,X]of Object.entries($.env)){if(typeof X!=="string")throw Error(`env "${Z}" must be a string`);W[Z]=X}w.env=W}return w}function IJ($){let{env:w,...W}=$;return W}async function xJ($,w={}){let W={provider:"openai",model:"gpt-5-mini",maxSteps:20,contextWindow:128000,reservedOutputTokens:8192,safetyMargin:4096,plugins:[],dataDir:I5(),env:{}},Z=await yJ(Ww.join(c8(),"config.json")),X=await yJ(Ww.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 G={...Z.env??{},...X.env??{}};for(let[T,Q]of Object.entries(G))if(process.env[T]===void 0)process.env[T]=Q;let J={...W,...IJ(Z),...IJ(X),...Y,...w,env:G};if(J.plugins=[...Z.plugins??[],...X.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 B4($,w,W=I5()){if(w==="project"){let Y=Z$.join($,".coden"),G=Z$.join(Y,"plugin-runtime");return{scope:w,root:Y,manifestPath:Z$.join(Y,"plugins.json"),runtimeDir:G,lockPath:Z$.join(Y,"plugin-lock"),transactionPath:Z$.join(Y,"plugin-transaction.json")}}let Z=Z$.join(W,"plugins"),X=Z$.join(Z,"runtime");return{scope:w,root:Z,manifestPath:Z$.join(Z,"plugins.json"),runtimeDir:X,lockPath:Z$.join(Z,"plugin-lock"),transactionPath:Z$.join(Z,"plugin-transaction.json")}}import{randomUUID as EH}from"node:crypto";import{constants as LH}from"node:fs";import{access as DH,mkdir as d8,readFile as _J,rename as u$,rm as W0,writeFile as gJ}from"node:fs/promises";import h$ from"node:path";class x5 extends Error{constructor($){super($ instanceof Error?$.message:String($),$ instanceof Error?{cause:$}:void 0);this.name="FaultInterruption"}}class j0{paths;options;constructor($,w={}){this.paths=$;this.options=w}async run($){let w=!1,W;try{await this.acquireLock(),w=!0,await this.recoverLocked();let Z=EH(),X=h$.join(this.paths.root,`.transaction-${Z}-stage`);W={version:1,id:Z,phase:"prepared",stageDirectory:X,backupManifestPath:h$.join(this.paths.root,`.transaction-${Z}-plugins.json.bak`),backupRuntimeDir:h$.join(this.paths.root,`.transaction-${Z}-runtime.bak`),hadManifest:await P4(this.paths.manifestPath),hadRuntime:await P4(this.paths.runtimeDir)},await d8(X,{recursive:!0});let Y={manifestPath:h$.join(X,"plugins.json"),runtimeDir:h$.join(X,"runtime")},G=await $(Y);await this.verifyCandidate(Y),await this.writeMarker(W),await this.backupCurrent(W);let J={...W,phase:"backed-up"};await this.writeMarker(J),W=J,this.fault("after-backup"),await u$(Y.runtimeDir,this.paths.runtimeDir);let T={...W,phase:"runtime-committed"};await this.writeMarker(T),W=T,this.fault("after-runtime-commit"),await u$(Y.manifestPath,this.paths.manifestPath);let Q={...W,phase:"manifest-committed"};return await this.writeMarker(Q),W=Q,this.fault("after-manifest-commit"),await this.cleanupCommitted(W),G}catch(Z){if(Z instanceof x5)throw Z.cause??Z;throw await this.rollbackAfterError(W),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 d8(this.paths.root,{recursive:!0});for(let $=0;$<2;$++){try{await d8(this.paths.lockPath)}catch(w){if(!b5(w,"EEXIST"))throw w;let W=await this.readLockOwner();if(!W||this.isProcessAlive(W.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 W0(this.paths.lockPath,{recursive:!0,force:!0});continue}try{await gJ(h$.join(this.paths.lockPath,"owner.json"),`${JSON.stringify({pid:process.pid,createdAt:this.now()})}
45
+ `,{mode:384});return}catch(w){throw await W0(this.paths.lockPath,{recursive:!0,force:!0}),w}}}async readLockOwner(){try{let $=JSON.parse(await _J(h$.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 W0(this.paths.lockPath,{recursive:!0,force:!0})}async verifyCandidate($){if(!await P4($.manifestPath)||!await P4($.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 W0($.backupManifestPath,{force:!0}),await W0($.backupRuntimeDir,{recursive:!0,force:!0}),$.hadManifest)await u$(this.paths.manifestPath,$.backupManifestPath);if($.hadRuntime)await u$(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 W0($.stageDirectory,{recursive:!0,force:!0}),await W0(this.paths.transactionPath,{force:!0});return}if($.phase==="backed-up"||$.phase==="runtime-committed"){await this.removeCurrentTargets(),await this.restoreBackups($),await this.cleanupRecoveryArtifacts($);return}await W0($.backupManifestPath,{force:!0}),await W0($.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 _J(this.paths.transactionPath,"utf8"));if(!kH($))throw Error("invalid transaction marker");return $}catch($){if(b5($,"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 d8(h$.dirname(this.paths.transactionPath),{recursive:!0});let w=`${this.paths.transactionPath}.tmp`;await gJ(w,`${JSON.stringify($,null,2)}
46
+ `,{mode:384}),await u$(w,this.paths.transactionPath)}async cleanupCommitted($){await W0($.backupManifestPath,{force:!0}),await W0($.backupRuntimeDir,{recursive:!0,force:!0}),await W0($.stageDirectory,{recursive:!0,force:!0}),await W0(this.paths.transactionPath,{force:!0}),await W0(`${this.paths.transactionPath}.tmp`,{recursive:!0,force:!0})}async cleanupRecoveryArtifacts($){await W0($.stageDirectory,{recursive:!0,force:!0}),await W0(this.paths.transactionPath,{force:!0}),await W0(`${this.paths.transactionPath}.tmp`,{recursive:!0,force:!0})}async removeCurrentTargets(){await W0(this.paths.manifestPath,{force:!0}),await W0(this.paths.runtimeDir,{recursive:!0,force:!0})}async restoreBackups($){if($.hadManifest)await u$($.backupManifestPath,this.paths.manifestPath);if($.hadRuntime)await u$($.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 P4($.backupPath)){await W0($.targetPath,{recursive:$.directory,force:!0}),await u$($.backupPath,$.targetPath);return}if(!$.hadTarget)await W0($.targetPath,{recursive:$.directory,force:!0})}fault($){try{this.options.fault?.($)}catch(w){throw new x5(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!b5(w,"ESRCH")}}}function kH($){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 P4($){try{return await DH($,LH.F_OK),!0}catch{return!1}}function b5($,w){return typeof $==="object"&&$!==null&&"code"in $&&$.code===w}class v5{workspace;dataDir;packageManager;loader;builtins;constructor($,w,W,Z,X){this.workspace=$;this.dataDir=w;this.packageManager=W;this.loader=Z;this.builtins=X}async install($,w){let W=kJ($),Z=this.paths(w.scope);await new j0(Z).recover();let X=await f$(Z.manifestPath);if(X.plugins[W.packageName]?.requested===W.requested){let T=await this.loader.loadScope(Z),Q=T.loaded.find((M)=>M.packageName===W.packageName);if(T.failed.length===0&&Q)return _5(Q,W.requested,w.scope)}let Y=vJ(X);Y.plugins[W.packageName]={source:"npm",requested:W.requested};let G=[];await new j0(Z).run(async(T)=>{G=await this.buildCandidate(T,Y,Z,w,!1),await this.validateCandidate(Z.scope,G)});let J=G.find((T)=>T.packageName===W.packageName);if(!J)throw g5([{packageName:W.packageName,path:Z.runtimeDir,message:"plugin did not load"}]);return _5(J,W.requested,w.scope)}async remove($,w){if(!M1($))throw IH($);let W=this.paths(w.scope);await new j0(W).recover();let Z=await f$(W.manifestPath);if(!Z.plugins[$])throw new y("plugin","plugin.install_failed",`plugin.install_failed: ${$} is not installed in ${w.scope} scope`);let X=vJ(Z);delete X.plugins[$],await new j0(W).run(async(Y)=>{let G=await this.buildCandidate(Y,X,W,w,!1);await this.validateCandidate(W.scope,G)})}async sync($){let w=this.paths($.scope);await new j0(w).recover();let W=await f$(w.manifestPath);if($.scope==="project"&&Object.keys(W.plugins).length>0&&!await uJ(i$.join(w.runtimeDir,"bun.lock")))throw new y("plugin","plugin.lock_missing",`plugin.lock_missing: ${$.scope} plugin sync requires ${i$.join(w.runtimeDir,"bun.lock")}`);let Z=[];return await new j0(w).run(async(X)=>{Z=await this.buildCandidate(X,W,w,$,!0),await this.validateCandidate(w.scope,Z)}),Z.map((X)=>_5(X,W.plugins[X.packageName]?.requested??"latest",$.scope))}async list(){let[$,w]=await Promise.all([this.listScope(this.paths("project")),this.listScope(this.paths("global"))]),W=new Set($.map((Z)=>Z.packageName));return{project:$,global:w.map((Z)=>({...Z,shadowedByProject:W.has(Z.packageName)}))}}paths($){return B4(this.workspace,$,this.dataDir)}async buildCandidate($,w,W,Z,X){if(await CH($.runtimeDir,{recursive:!0}),await n8($.manifestPath,A5(w),"utf8"),await n8(i$.join($.runtimeDir,"package.json"),`${JSON.stringify(AJ(w),null,2)}
47
+ `,"utf8"),await uJ(i$.join(W.runtimeDir,"bun.lock")))await RH(i$.join(W.runtimeDir,"bun.lock"),i$.join($.runtimeDir,"bun.lock"));try{await this.packageManager.install({cwd:$.runtimeDir,frozenLockfile:X,allowScripts:Z.allowScripts,...Z.signal?{signal:Z.signal}:{}})}catch(G){throw bH(G,X)}await jH($.runtimeDir,w),await yH($.runtimeDir,W.scope);let Y=await this.loader.loadScope({...W,manifestPath:$.manifestPath,runtimeDir:$.runtimeDir});if(Y.failed.length>0)throw g5(Y.failed);return Y.loaded}async validateCandidate($,w){if($==="global"){y5(this.builtins,w,[]);return}let W=this.paths("global");await new j0(W).recover();let Z=await this.loadScopeOrThrow(W);y5(this.builtins,Z,w)}async loadScopeOrThrow($){let w=await this.loader.loadScope($);if(w.failed.length>0)throw g5(w.failed);return w.loaded}async listScope($){await new j0($).recover();let w=await f$($.manifestPath),W=[];for(let Z of Object.keys(w.plugins).sort()){let X=await ww($.runtimeDir,Z);W.push({packageName:Z,requested:w.plugins[Z]?.requested??"latest",version:X.version,tools:[],scope:$.scope,shadowedByProject:!1})}return W}}async function jH($,w){if(Object.keys(w.plugins).length>0)return;await n8(i$.join($,"bun.lock"),"","utf8")}async function yH($,w){if(w!=="project")return;await n8(i$.join($,".gitignore"),`*
48
48
  !.gitignore
49
49
  !bun.lock
50
- `,"utf8")}function x5($,w,W){return{packageName:$.packageName,requested:w,version:$.version,tools:$.tools.map((Z)=>Z.name).sort(),scope:W}}function gJ($){return JSON.parse(k5($))}function _5($){let w=$.map((W)=>`${W.packageName}: ${W.message} (${W.path})`).join("; ");return new y("plugin","plugin.sync_failed",`plugin.sync_failed: ${w}`)}function IH($){return new y("plugin","plugin.specifier_invalid",`plugin.specifier_invalid: ${$}`)}function bH($,w){if(w&&xH($))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 xH($){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 vJ($){try{return await SH($,AH.F_OK),!0}catch{return!1}}var n8={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:W,timeout:Z=30000,maxOutput:X=30000}=$,Y=await Z8("bash",["-lc",W],{cwd:w.workspace,env:process.env,signal:w.signal,timeoutMs:Z,maxOutputChars:X}),G=[Y.stdout&&`stdout:
50
+ `,"utf8")}function _5($,w,W){return{packageName:$.packageName,requested:w,version:$.version,tools:$.tools.map((Z)=>Z.name).sort(),scope:W}}function vJ($){return JSON.parse(A5($))}function g5($){let w=$.map((W)=>`${W.packageName}: ${W.message} (${W.path})`).join("; ");return new y("plugin","plugin.sync_failed",`plugin.sync_failed: ${w}`)}function IH($){return new y("plugin","plugin.specifier_invalid",`plugin.specifier_invalid: ${$}`)}function bH($,w){if(w&&xH($))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 xH($){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 uJ($){try{return await SH($,AH.F_OK),!0}catch{return!1}}var p8={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:W,timeout:Z=30000,maxOutput:X=30000}=$,Y=await X8("bash",["-lc",W],{cwd:w.workspace,env:process.env,signal:w.signal,timeoutMs:Z,maxOutputChars:X}),G=[Y.stdout&&`stdout:
52
52
  ${Y.stdout}`,Y.stderr&&`stderr:
53
53
  ${Y.stderr}`].filter(Boolean).join(`
54
54
  `);if(Y.exitCode===null&&!Y.timedOut&&!Y.cancelled&&Y.signal===null)return{content:`bash.spawn_error: ${Y.stderr||"unknown error"}`,isError:!0};let J=Y.timedOut?`Timed out after ${Z}ms`:Y.cancelled?"Cancelled":`Exit code: ${Y.exitCode??"null"}${Y.signal?` (signal ${Y.signal})`:""}`;return{content:l1(`${J}
55
- ${G}`.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 cJ}from"node:fs";import{open as hH}from"node:fs/promises";import{constants as hJ}from"node:fs";import{lstat as uJ,open as _H,readlink as iJ,realpath as p8}from"node:fs/promises";import C0 from"node:path";function t8($,w){let W=C0.relative(w,$);return W===""||!W.startsWith("..")&&!C0.isAbsolute(W)}async function mJ($,w,W=1e6){let Z=await X$($,w),X=await _H(Z,hJ.O_RDONLY|hJ.O_NOFOLLOW);try{if((await X.stat()).size>W)throw new y("context","workspace.instructions_too_large",`${w} exceeds the ${W}-byte instruction limit`);return await X.readFile("utf8")}finally{await X.close()}}async function X$($,w){let W=await p8($),Z=C0.resolve(W,w);if(!t8(Z,W))throw new y("permission","workspace.outside",`Path is outside workspace: ${w}`);try{let X=await p8(Z);if(!t8(X,W))throw new y("permission","workspace.symlink_escape",`Path escapes workspace through a symlink: ${w}`);return X}catch(X){if(X instanceof y)throw X;try{if((await uJ(Z)).isSymbolicLink()){let G=C0.resolve(C0.dirname(Z),await iJ(Z));await lJ(G,W,w,"dangling symlink")}}catch(Y){if(Y instanceof y)throw Y}return await gH(Z,W,w),Z}}async function lJ($,w,W,Z){let X=await vH($);if(!X||!t8(X,w))throw new y("permission","workspace.symlink_escape",`Path escapes workspace through a ${Z}: ${W}`)}async function gH($,w,W){let Z=C0.dirname($);while(Z!==C0.dirname(Z)){let X;try{X=await uJ(Z)}catch{Z=C0.dirname(Z);continue}if(!X){Z=C0.dirname(Z);continue}if(X.isSymbolicLink()){let Y=C0.resolve(C0.dirname(Z),await iJ(Z));await lJ(Y,w,W,"symlink")}else{let Y;try{Y=await p8(Z)}catch{Z=C0.dirname(Z);continue}if(!Y)continue;if(t8(Y,w))return;throw new y("permission","workspace.symlink_escape",`Parent escapes workspace: ${W}`)}Z=C0.dirname(Z)}}async function vH($){let w=$;while(!0)try{return await p8(w)}catch{let W=C0.dirname(w);if(W===w)return;w=W}}var r8={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:W,oldText:Z,newText:X}=$,Y=await X$(w.workspace,W),G=await hH(Y,cJ.O_RDWR|cJ.O_NOFOLLOW);try{let J=await G.readFile("utf8"),T=J.indexOf(Z);if(T<0)return{content:"edit.no_match: oldText was not found",isError:!0};if(J.indexOf(Z,T+1)>=0)return{content:"edit.multiple_matches: oldText is not unique",isError:!0};let Q=`${J.slice(0,T)}${X}${J.slice(T+Z.length)}`;await G.truncate(0),await G.write(Q,0,"utf8")}finally{await G.close()}return{content:`Edited ${W}`}}};import{constants as dJ}from"node:fs";import{open as uH}from"node:fs/promises";class nJ{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 s8={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:W,offset:Z=1,limit:X=500}=$,Y=await X$(w.workspace,W),G=new nJ(50000),J=1,T=0,Q=!1,M=()=>J>=Z&&J<Z+X,z=(P)=>{if(!M())return;if(!Q){if(T>0)G.add(`
57
- `);T++,Q=!0}G.add(P)},N=await uH(Y,dJ.O_RDONLY|dJ.O_NOFOLLOW);try{let P=N.createReadStream({encoding:"utf8",autoClose:!1,highWaterMark:65536,signal:w.signal});for await(let q of P){let f=String(q),H=0;for(let E=f.indexOf(`
55
+ ${G}`.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 dJ}from"node:fs";import{open as uH}from"node:fs/promises";import{constants as hJ}from"node:fs";import{lstat as iJ,open as _H,readlink as mJ,realpath as t8}from"node:fs/promises";import C0 from"node:path";function r8($,w){let W=C0.relative(w,$);return W===""||!W.startsWith("..")&&!C0.isAbsolute(W)}async function lJ($,w,W=1e6){let Z=await X$($,w),X=await _H(Z,hJ.O_RDONLY|hJ.O_NOFOLLOW);try{if((await X.stat()).size>W)throw new y("context","workspace.instructions_too_large",`${w} exceeds the ${W}-byte instruction limit`);return await X.readFile("utf8")}finally{await X.close()}}async function X$($,w){let W=await t8($),Z=C0.resolve(W,w);if(!r8(Z,W))throw new y("permission","workspace.outside",`Path is outside workspace: ${w}`);try{let X=await t8(Z);if(!r8(X,W))throw new y("permission","workspace.symlink_escape",`Path escapes workspace through a symlink: ${w}`);return X}catch(X){if(X instanceof y)throw X;try{if((await iJ(Z)).isSymbolicLink()){let G=C0.resolve(C0.dirname(Z),await mJ(Z));await cJ(G,W,w,"dangling symlink")}}catch(Y){if(Y instanceof y)throw Y}return await gH(Z,W,w),Z}}async function cJ($,w,W,Z){let X=await vH($);if(!X||!r8(X,w))throw new y("permission","workspace.symlink_escape",`Path escapes workspace through a ${Z}: ${W}`)}async function gH($,w,W){let Z=C0.dirname($);while(Z!==C0.dirname(Z)){let X;try{X=await iJ(Z)}catch{Z=C0.dirname(Z);continue}if(!X){Z=C0.dirname(Z);continue}if(X.isSymbolicLink()){let Y=C0.resolve(C0.dirname(Z),await mJ(Z));await cJ(Y,w,W,"symlink")}else{let Y;try{Y=await t8(Z)}catch{Z=C0.dirname(Z);continue}if(!Y)continue;if(r8(Y,w))return;throw new y("permission","workspace.symlink_escape",`Parent escapes workspace: ${W}`)}Z=C0.dirname(Z)}}async function vH($){let w=$;while(!0)try{return await t8(w)}catch{let W=C0.dirname(w);if(W===w)return;w=W}}var s8={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:W,oldText:Z,newText:X}=$,Y=await X$(w.workspace,W),G=await uH(Y,dJ.O_RDWR|dJ.O_NOFOLLOW);try{let J=await G.readFile("utf8"),T=J.indexOf(Z);if(T<0)return{content:"edit.no_match: oldText was not found",isError:!0};if(J.indexOf(Z,T+1)>=0)return{content:"edit.multiple_matches: oldText is not unique",isError:!0};let Q=`${J.slice(0,T)}${X}${J.slice(T+Z.length)}`;await G.truncate(0),await G.write(Q,0,"utf8")}finally{await G.close()}return{content:`Edited ${W}`}}};import{constants as nJ}from"node:fs";import{open as hH}from"node:fs/promises";class pJ{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 a8={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:W,offset:Z=1,limit:X=500}=$,Y=await X$(w.workspace,W),G=new pJ(50000),J=1,T=0,Q=!1,M=()=>J>=Z&&J<Z+X,z=(P)=>{if(!M())return;if(!Q){if(T>0)G.add(`
57
+ `);T++,Q=!0}G.add(P)},N=await hH(Y,nJ.O_RDONLY|nJ.O_NOFOLLOW);try{let P=N.createReadStream({encoding:"utf8",autoClose:!1,highWaterMark:65536,signal:w.signal});for await(let q of P){let f=String(q),H=0;for(let E=f.indexOf(`
58
58
  `,H);E>=0;E=f.indexOf(`
59
59
  `,H))z(f.slice(H,E)),J++,Q=!1,H=E+1;z(f.slice(H))}}finally{await N.close()}z("");let B=J,K=Math.max(0,B-(Z-1+T));return{content:G.value()+(K>0?`
60
- ... [${K} lines omitted]`:""),metadata:{totalLines:B,offset:Z,limit:X}}}};import{constants as a8}from"node:fs";import{mkdir as iH,open as mH}from"node:fs/promises";import lH from"node:path";var o8={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:W,content:Z}=$,X=await X$(w.workspace,W);await iH(lH.dirname(X),{recursive:!0}),X=await X$(w.workspace,W);let Y=await mH(X,a8.O_WRONLY|a8.O_CREAT|a8.O_TRUNC|a8.O_NOFOLLOW,384);try{await Y.writeFile(Z,"utf8")}finally{await Y.close()}return{content:`Wrote ${Buffer.byteLength(Z)} bytes to ${W}`}}};function pJ(){return[s8,o8,r8,n8]}var tJ="0.1.3";import MW from"node:path";import{stdin as kL,stdout as $$}from"node:process";import{createInterface as AL}from"node:readline/promises";var rJ=m1(OW(),1),{program:cS,createCommand:dS,createArgument:nS,createOption:pS,CommanderError:tS,InvalidArgumentError:v5,InvalidOptionArgumentError:rS,Command:sS,Argument:aS,Option:oS,Help:eS}=rJ.default;import{mkdir as cH,readFile as dH,realpath as sJ,writeFile as nH}from"node:fs/promises";import pH from"node:path";class h5{file;constructor($){this.file=$}async isTrusted($){return(await this.read()).includes($)}async isWorkspaceTrusted($){return this.isTrusted(await sJ($))}async trustWorkspace($){return this.trust(await sJ($))}async trust($){let w=await this.read();if(!w.includes($))w.push($);await cH(pH.dirname(this.file),{recursive:!0}),await nH(this.file,`${JSON.stringify(w,null,2)}
61
- `,{encoding:"utf8",mode:384})}async read(){try{let $=JSON.parse(await dH(this.file,"utf8"));return Array.isArray($)?$.filter((w)=>typeof w==="string"):[]}catch($){if($.code==="ENOENT")return[];throw $}}}class eJ{estimateText($){return Math.ceil($.length/3.5)}estimateMessages($){return $.reduce((w,W)=>w+6+this.estimateText(JSON.stringify(W)),0)}estimateTools($){return this.estimateText(JSON.stringify($.map(({execute:w,...W})=>W)))}}class u5{budget;threshold;estimator=new eJ;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 W=$[0]??{role:"system",content:"You are CodeN."},Z=aJ($.slice(1)),X=this.estimator.estimateTools(w),Y=this.inputBudget(),G=this.summary?Z.filter((z)=>z.end>this.compactedThrough):[...Z],J=Math.min(3,G.length),T=this.project(W,G),Q=this.estimator.estimateMessages(T)+X,M=!1;if(Q>Y*this.threshold&&G.length>J){let z=G.slice(0,-J);G=G.slice(-J);let N=[...this.summary?[this.summary]:[],...z.flatMap((B)=>B.messages)];this.compactionRange={start:z[0]?.start??1,end:z.at(-1)?.end??1},this.compactedThrough=this.compactionRange.end,this.summary={role:"system",content:`Compacted conversation summary:
62
- ${oJ(N)}`},T=this.project(W,G),Q=this.estimator.estimateMessages(T)+X,M=!0}while(Q>Y&&G.length>1)G=G.slice(1),T=this.project(W,G),Q=this.estimator.estimateMessages(T)+X,M=!0;return{messages:T,estimatedTokens:Q,compacted:M}}forceCompact($,w){let W=$[0]??{role:"system",content:"You are CodeN."},Z=aJ($.slice(1)),X=this.summary?Z.filter((M)=>M.end>this.compactedThrough):Z,Y=X.slice(-1),G=X.slice(0,-1),J=[...this.summary?[this.summary]:[],...G.flatMap((M)=>M.messages)];if(G.length)this.compactionRange={start:G[0]?.start??1,end:G.at(-1)?.end??1},this.compactedThrough=this.compactionRange.end;this.summary={role:"system",content:`Emergency compacted summary:
63
- ${oJ(J)}`};let T=this.project(W,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((W)=>W.messages)]}}function aJ($){let w=[],W;for(let Z=0;Z<$.length;Z++){let X=$[Z];if(!X)continue;let Y=Z+1;if(X.role==="user"||!W){if(W)w.push(W);W={messages:[X],start:Y,end:Y}}else W.messages.push(X),W.end=Y}if(W)w.push(W);return w}function oJ($){return $.map((W)=>{if(W.role==="tool")return`Tool ${W.name} (${W.isError?"error":"ok"}): ${W.content.slice(0,300)}`;return`${W.role}: ${W.content.slice(0,500)}`}).join(`
64
- `).slice(0,6000)}function i5($,w,W,Z,X){let Y={model:$,messages:w.messages,tools:W,maxOutputTokens:Z.reservedOutputTokens};if(X)Y.signal=X;return Y}class m5{#$=new Set;on($){return this.#$.add($),()=>this.#$.delete($)}async emit($,w,W){let Z={type:$,timestamp:new Date().toISOString()};if(W!==void 0)Z.turnId=W;if(w!==void 0)Z.data=w;return await Promise.all([...this.#$].map((X)=>X(Z))),Z}}import{randomUUID as tH}from"node:crypto";class l5{provider;registry;executor;context;sessions;events;options;messages;maxSteps;retries;retryBaseMs;systemPersisted;constructor($,w,W,Z,X,Y,G,J){this.provider=$;this.registry=w;this.executor=W;this.context=Z;this.sessions=X;this.events=Y;this.options=G;this.maxSteps=G.maxSteps??20,this.retries=G.retries??3,this.retryBaseMs=G.retryBaseMs??250,this.systemPersisted=Boolean(J?.length),this.messages=J?.length?[...J]:[{role:"system",content:G.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 W=tH(),Z=Date.now(),X=0,Y={inputTokens:0,outputTokens:0};await this.sessions.create(),await this.events.emit("turn.started",{input:$},W);try{if(!this.systemPersisted){let T=this.messages[0];if(T?.role==="system")await this.sessions.appendMessage(T);this.systemPersisted=!0}let G=this.messages.some((T)=>T.role==="user"),J={role:"user",content:$};if(this.messages.push(J),await this.sessions.appendMessage(J),!G)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 N=this.context.getSummary();if(N){let B=await this.refineSummary(N,w,W);if(B){let K=N;N=B,this.context.setSummary(B,this.context.getCompactionRange()?.end??0),Q.messages=Q.messages.map((P)=>P.role==="system"&&P.content===K?{role:"system",content:B}:P)}await this.sessions.appendCompaction(N,this.context.getCompactionRange())}await this.events.emit("context.compacted",{estimatedTokens:Q.estimatedTokens},W)}await this.events.emit("context.prepared",{estimatedTokens:Q.estimatedTokens,budget:this.context.inputBudget()},W);let M=await this.requestWithRetry(i5(this.options.model,Q,this.registry.list(),this.context.budget,w),W,async()=>{Q=this.context.forceCompact(this.messages,this.registry.list());let N=this.context.getSummary();if(N)await this.sessions.appendCompaction(N,this.context.getCompactionRange());return i5(this.options.model,Q,this.registry.list(),this.context.budget,w)});Y.inputTokens+=M.usage.inputTokens,Y.outputTokens+=M.usage.outputTokens;let z={role:"assistant",content:M.text,toolCalls:M.toolCalls,model:this.options.model,usage:M.usage};if(this.messages.push(z),await this.sessions.appendMessage(z),z.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},W),{answer:z.content,messages:this.messages,toolsExecuted:X,usage:Y};for(let N of z.toolCalls){let B=await this.executor.execute(N,w,W);X++;let K={role:"tool",callId:N.callId,name:N.name,content:B.content,isError:B.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(G){throw await this.events.emit("turn.failed",{code:G instanceof y?G.code:"runtime.unknown",message:G instanceof Error?G.message:String(G)},W),G}}async refineSummary($,w,W){try{await this.events.emit("context.compaction_started",{model:this.options.model},W);let Z=await $T(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:
65
- ${Z.text.trim()}`}catch(Z){await this.events.emit("context.compaction_failed",{message:Z instanceof Error?Z.message:String(Z),fallback:"deterministic"},W);return}}async requestWithRetry($,w,W){let Z=$,X=!1;for(let Y=0;;Y++)try{await this.events.emit("provider.started",{attempt:Y},w);let G=await $T(this.provider.stream(Z),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:G.usage},w),G}catch(G){if(Z.signal?.aborted)throw G;if(aH(G)){if(!X){X=!0,Z=await W(),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:G})}if(Y>=this.retries||!rH(G))throw G;await this.events.emit("provider.retry",{attempt:Y+1,message:G instanceof Error?G.message:String(G)},w);let J=sH(G),T=this.retryBaseMs*2**Y*(0.8+Math.random()*0.4);await oH(J??Math.min(30000,T),Z.signal)}}}async function $T($,w,W,Z){let X="",Y={inputTokens:0,outputTokens:0},G=new Map;for await(let T of $)if(T.type==="reasoning_delta")await W?.(T.text);else if(T.type==="text_delta")X+=T.text,await w?.(T.text);else if(T.type==="tool_call_start")G.set(T.index,{callId:T.callId,name:T.name,json:"",ended:!1}),await Z?.(T);else if(T.type==="tool_call_delta"){let Q=G.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=G.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 J=[...G.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:J,usage:Y}}function rH($){if($ instanceof y)return $.retryable;let w=$?.status;return typeof w!=="number"||w===429||w>=500}function sH($){let W=$?.headers?.get?.("retry-after");if(!W)return;let Z=Number(W);if(Number.isFinite(Z))return Math.max(0,Z*1000);let X=Date.parse(W);return Number.isNaN(X)?void 0:Math.max(0,X-Date.now())}function aH($){let w=$?.status,W=$ instanceof Error?$.message:String($);return w===413||/context.{0,20}(?:length|window|limit|too long)/i.test(W)}function oH($,w){return new Promise((W,Z)=>{if(w?.aborted){Z(w.reason);return}let X=setTimeout(W,$);w?.addEventListener("abort",()=>{clearTimeout(X),Z(w.reason)},{once:!0})})}var G$=m1(w6(),1);import*as Gw from"node:readline";function n5(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var P1=n5();function MT($){P1=$}var K1={exec:()=>null};function Zw($){let w=[];return(W)=>{let Z=Math.max(0,Math.min(3,W-1)),X=w[Z];return X||(X=$(Z),w[Z]=X),X}}function m($,w=""){let W=typeof $=="string"?$:$.source,Z={replace:(X,Y)=>{let G=typeof Y=="string"?Y:Y.source;return G=G.replace(f0.caret,"$1"),W=W.replace(X,G),Z},getRegex:()=>new RegExp(W,w)};return Z}var WF=(($="")=>{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: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,${$}}>`))},ZF=/^(?:[ \t]*(?:\n|$))+/,XF=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,YF=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,q9=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,GF=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,p5=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,zT=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,NT=m(zT).replace(/bull/g,p5).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(),JF=m(zT).replace(/bull/g,p5).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(),t5=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,TF=/^[^\n]+/,r5=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,QF=m(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",r5).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),MF=m(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,p5).getRegex(),G6="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",s5=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,zF=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",s5).replace("tag",G6).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),KT=($)=>m(t5).replace("hr",q9).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",G6).getRegex(),NF=KT(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),KF=KT(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),BF=m(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",KF).getRegex(),a5={blockquote:BF,code:XF,def:QF,fences:YF,heading:GF,hr:q9,html:zF,lheading:NT,list:MF,newline:ZF,paragraph:NF,table:K1,text:TF},ZT=m("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",q9).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",G6).getRegex(),PF={...a5,lheading:JF,table:ZT,paragraph:m(t5).replace("hr",q9).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",ZT).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",G6).getRegex()},VF={...a5,html:m(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",s5).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:K1,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:m(t5).replace("hr",q9).replace("heading",` *#{1,6} *[^
66
- ]`).replace("lheading",NT).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},fF=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,qF=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,BT=/^( {2,}|\\)\n(?!\s*$)/,UF=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,q$=/[\p{P}\p{S}]/u,Xw=/[\s\p{P}\p{S}]/u,U9=/[^\s\p{P}\p{S}]/u,HF=m(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Xw).getRegex(),FF=/[\p{Pi}\p{Ps}"']/u,PT=/(?!~)[\p{P}\p{S}]/u,OF=/(?!~)[\s\p{P}\p{S}]/u,EF=/(?:[^\s\p{P}\p{S}]|~)/u,LF=m(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",WF?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),VT=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,DF=m(VT,"u").replace(/punct/g,q$).getRegex(),kF=m(VT,"u").replace(/punct/g,PT).getRegex(),AF=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,SF=m(AF,"u").replace(/openQuote/g,FF).replace(/punct/g,q$).getRegex(),fT="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",RF=m(fT,"gu").replace(/notPunctSpace/g,U9).replace(/punctSpace/g,Xw).replace(/punct/g,q$).getRegex(),CF=m(fT,"gu").replace(/notPunctSpace/g,EF).replace(/punctSpace/g,OF).replace(/punct/g,PT).getRegex(),jF="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",yF=m(jF,"gu").replace(/notPunctSpace/g,U9).replace(/punctSpace/g,Xw).replace(/punct/g,q$).getRegex(),IF=m("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,U9).replace(/punctSpace/g,Xw).replace(/punct/g,q$).getRegex(),bF="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",xF=m(bF,"gu").replace(/notPunctSpace/g,U9).replace(/punctSpace/g,Xw).replace(/punct/g,q$).getRegex(),_F=m(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,q$).getRegex(),gF="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",vF=m(gF,"gu").replace(/notPunctSpace/g,U9).replace(/punctSpace/g,Xw).replace(/punct/g,q$).getRegex(),hF=m(/\\(punct)/,"gu").replace(/punct/g,q$).getRegex(),uF=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(),iF=m(s5).replace("(?:-->|$)","-->").getRegex(),mF=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",iF).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Z6=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,lF=m(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",Z6).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),qT=m(/^!?\[(label)\]\[(ref)\]/).replace("label",Z6).replace("ref",r5).getRegex(),UT=m(/^!?\[(ref)\](?:\[\])?/).replace("ref",r5).getRegex(),cF=m("reflink|nolink(?!\\()","g").replace("reflink",qT).replace("nolink",UT).getRegex(),XT=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,o5={_backpedal:K1,anyPunctuation:hF,autolink:uF,blockSkip:LF,br:BT,code:qF,del:K1,delLDelim:K1,delRDelim:K1,emStrongLDelim:DF,emStrongRDelimAst:RF,emStrongRDelimUnd:IF,escape:fF,link:lF,nolink:UT,punctuation:HF,reflink:qT,reflinkSearch:cF,tag:mF,text:UF,url:K1},dF={...o5,emStrongLDelim:SF,emStrongRDelimAst:yF,emStrongRDelimUnd:xF,link:m(/^!?\[(label)\]\((.*?)\)/).replace("label",Z6).getRegex(),reflink:m(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Z6).getRegex()},d5={...o5,emStrongRDelimAst:CF,emStrongLDelim:kF,delLDelim:_F,delRDelim:vF,url:m(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",XT).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",XT).getRegex()},nF={...d5,br:m(BT).replace("{2,}","*").getRegex(),text:m(d5.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},W6={normal:a5,gfm:PF,pedantic:VF},V9={normal:o5,gfm:d5,breaks:nF,pedantic:dF},pF={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},YT=($)=>pF[$];function Y$($,w){if(w){if(f0.escapeTest.test($))return $.replace(f0.escapeReplace,YT)}else if(f0.escapeTestNoEncode.test($))return $.replace(f0.escapeReplaceNoEncode,YT);return $}function GT($){try{$=encodeURI($).replace(f0.percentDecode,"%")}catch{return null}return $}function JT($,w){let W=$.replace(f0.findPipe,(Y,G,J)=>{let T=!1,Q=G;for(;--Q>=0&&J[Q]==="\\";)T=!T;return T?"|":" |"}),Z=W.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 m$($,w,W){let Z=$.length;if(Z===0)return"";let X=0;for(;X<Z;){let Y=$.charAt(Z-X-1);if(Y===w&&!W)X++;else if(Y!==w&&W)X++;else break}return $.slice(0,Z-X)}function TT($){let w=$.split(`
60
+ ... [${K} lines omitted]`:""),metadata:{totalLines:B,offset:Z,limit:X}}}};import{constants as o8}from"node:fs";import{mkdir as iH,open as mH}from"node:fs/promises";import lH from"node:path";var e8={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:W,content:Z}=$,X=await X$(w.workspace,W);await iH(lH.dirname(X),{recursive:!0}),X=await X$(w.workspace,W);let Y=await mH(X,o8.O_WRONLY|o8.O_CREAT|o8.O_TRUNC|o8.O_NOFOLLOW,384);try{await Y.writeFile(Z,"utf8")}finally{await Y.close()}return{content:`Wrote ${Buffer.byteLength(Z)} bytes to ${W}`}}};function tJ(){return[a8,e8,s8,p8]}var rJ="0.1.4";import zW from"node:path";import{stdin as yL,stdout as c0}from"node:process";import{createInterface as IL}from"node:readline/promises";var sJ=m1(EW(),1),{program:sS,createCommand:aS,createArgument:oS,createOption:eS,CommanderError:$R,InvalidArgumentError:u5,InvalidOptionArgumentError:wR,Command:WR,Argument:ZR,Option:XR,Help:YR}=sJ.default;import{mkdir as cH,readFile as dH,realpath as aJ,writeFile as nH}from"node:fs/promises";import pH from"node:path";class h5{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 cH(pH.dirname(this.file),{recursive:!0}),await nH(this.file,`${JSON.stringify(w,null,2)}
61
+ `,{encoding:"utf8",mode:384})}async read(){try{let $=JSON.parse(await dH(this.file,"utf8"));return Array.isArray($)?$.filter((w)=>typeof w==="string"):[]}catch($){if($.code==="ENOENT")return[];throw $}}}class $T{estimateText($){return Math.ceil($.length/3.5)}estimateMessages($){return $.reduce((w,W)=>w+6+this.estimateText(JSON.stringify(W)),0)}estimateTools($){return this.estimateText(JSON.stringify($.map(({execute:w,...W})=>W)))}}class i5{budget;threshold;estimator=new $T;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 W=$[0]??{role:"system",content:"You are CodeN."},Z=oJ($.slice(1)),X=this.estimator.estimateTools(w),Y=this.inputBudget(),G=this.summary?Z.filter((z)=>z.end>this.compactedThrough):[...Z],J=Math.min(3,G.length),T=this.project(W,G),Q=this.estimator.estimateMessages(T)+X,M=!1;if(Q>Y*this.threshold&&G.length>J){let z=G.slice(0,-J);G=G.slice(-J);let N=[...this.summary?[this.summary]:[],...z.flatMap((B)=>B.messages)];this.compactionRange={start:z[0]?.start??1,end:z.at(-1)?.end??1},this.compactedThrough=this.compactionRange.end,this.summary={role:"system",content:`Compacted conversation summary:
62
+ ${eJ(N)}`},T=this.project(W,G),Q=this.estimator.estimateMessages(T)+X,M=!0}while(Q>Y&&G.length>1)G=G.slice(1),T=this.project(W,G),Q=this.estimator.estimateMessages(T)+X,M=!0;return{messages:T,estimatedTokens:Q,compacted:M}}forceCompact($,w){let W=$[0]??{role:"system",content:"You are CodeN."},Z=oJ($.slice(1)),X=this.summary?Z.filter((M)=>M.end>this.compactedThrough):Z,Y=X.slice(-1),G=X.slice(0,-1),J=[...this.summary?[this.summary]:[],...G.flatMap((M)=>M.messages)];if(G.length)this.compactionRange={start:G[0]?.start??1,end:G.at(-1)?.end??1},this.compactedThrough=this.compactionRange.end;this.summary={role:"system",content:`Emergency compacted summary:
63
+ ${eJ(J)}`};let T=this.project(W,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((W)=>W.messages)]}}function oJ($){let w=[],W;for(let Z=0;Z<$.length;Z++){let X=$[Z];if(!X)continue;let Y=Z+1;if(X.role==="user"||!W){if(W)w.push(W);W={messages:[X],start:Y,end:Y}}else W.messages.push(X),W.end=Y}if(W)w.push(W);return w}function eJ($){return $.map((W)=>{if(W.role==="tool")return`Tool ${W.name} (${W.isError?"error":"ok"}): ${W.content.slice(0,300)}`;return`${W.role}: ${W.content.slice(0,500)}`}).join(`
64
+ `).slice(0,6000)}function m5($,w,W,Z,X){let Y={model:$,messages:w.messages,tools:W,maxOutputTokens:Z.reservedOutputTokens};if(X)Y.signal=X;return Y}class l5{#$=new Set;on($){return this.#$.add($),()=>this.#$.delete($)}async emit($,w,W){let Z={type:$,timestamp:new Date().toISOString()};if(W!==void 0)Z.turnId=W;if(w!==void 0)Z.data=w;return await Promise.all([...this.#$].map((X)=>X(Z))),Z}}import{randomUUID as tH}from"node:crypto";class c5{provider;registry;executor;context;sessions;events;options;messages;maxSteps;retries;retryBaseMs;systemPersisted;constructor($,w,W,Z,X,Y,G,J){this.provider=$;this.registry=w;this.executor=W;this.context=Z;this.sessions=X;this.events=Y;this.options=G;this.maxSteps=G.maxSteps??20,this.retries=G.retries??3,this.retryBaseMs=G.retryBaseMs??250,this.systemPersisted=Boolean(J?.length),this.messages=J?.length?[...J]:[{role:"system",content:G.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 W=tH(),Z=Date.now(),X=0,Y={inputTokens:0,outputTokens:0};await this.sessions.create(),await this.events.emit("turn.started",{input:$},W);try{if(!this.systemPersisted){let T=this.messages[0];if(T?.role==="system")await this.sessions.appendMessage(T);this.systemPersisted=!0}let G=this.messages.some((T)=>T.role==="user"),J={role:"user",content:$};if(this.messages.push(J),await this.sessions.appendMessage(J),!G)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 N=this.context.getSummary();if(N){let B=await this.refineSummary(N,w,W);if(B){let K=N;N=B,this.context.setSummary(B,this.context.getCompactionRange()?.end??0),Q.messages=Q.messages.map((P)=>P.role==="system"&&P.content===K?{role:"system",content:B}:P)}await this.sessions.appendCompaction(N,this.context.getCompactionRange())}await this.events.emit("context.compacted",{estimatedTokens:Q.estimatedTokens},W)}await this.events.emit("context.prepared",{estimatedTokens:Q.estimatedTokens,budget:this.context.inputBudget()},W);let M=await this.requestWithRetry(m5(this.options.model,Q,this.registry.list(),this.context.budget,w),W,async()=>{Q=this.context.forceCompact(this.messages,this.registry.list());let N=this.context.getSummary();if(N)await this.sessions.appendCompaction(N,this.context.getCompactionRange());return m5(this.options.model,Q,this.registry.list(),this.context.budget,w)});Y.inputTokens+=M.usage.inputTokens,Y.outputTokens+=M.usage.outputTokens;let z={role:"assistant",content:M.text,toolCalls:M.toolCalls,model:this.options.model,usage:M.usage};if(this.messages.push(z),await this.sessions.appendMessage(z),z.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},W),{answer:z.content,messages:this.messages,toolsExecuted:X,usage:Y};for(let N of z.toolCalls){let B=await this.executor.execute(N,w,W);X++;let K={role:"tool",callId:N.callId,name:N.name,content:B.content,isError:B.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(G){throw await this.events.emit("turn.failed",{code:G instanceof y?G.code:"runtime.unknown",message:G instanceof Error?G.message:String(G)},W),G}}async refineSummary($,w,W){try{await this.events.emit("context.compaction_started",{model:this.options.model},W);let Z=await wT(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:
65
+ ${Z.text.trim()}`}catch(Z){await this.events.emit("context.compaction_failed",{message:Z instanceof Error?Z.message:String(Z),fallback:"deterministic"},W);return}}async requestWithRetry($,w,W){let Z=$,X=!1;for(let Y=0;;Y++)try{await this.events.emit("provider.started",{attempt:Y},w);let G=await wT(this.provider.stream(Z),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:G.usage},w),G}catch(G){if(Z.signal?.aborted)throw G;if(aH(G)){if(!X){X=!0,Z=await W(),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:G})}if(Y>=this.retries||!rH(G))throw G;await this.events.emit("provider.retry",{attempt:Y+1,message:G instanceof Error?G.message:String(G)},w);let J=sH(G),T=this.retryBaseMs*2**Y*(0.8+Math.random()*0.4);await oH(J??Math.min(30000,T),Z.signal)}}}async function wT($,w,W,Z){let X="",Y={inputTokens:0,outputTokens:0},G=new Map;for await(let T of $)if(T.type==="reasoning_delta")await W?.(T.text);else if(T.type==="text_delta")X+=T.text,await w?.(T.text);else if(T.type==="tool_call_start")G.set(T.index,{callId:T.callId,name:T.name,json:"",ended:!1}),await Z?.(T);else if(T.type==="tool_call_delta"){let Q=G.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=G.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 J=[...G.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:J,usage:Y}}function rH($){if($ instanceof y)return $.retryable;let w=$?.status;return typeof w!=="number"||w===429||w>=500}function sH($){let W=$?.headers?.get?.("retry-after");if(!W)return;let Z=Number(W);if(Number.isFinite(Z))return Math.max(0,Z*1000);let X=Date.parse(W);return Number.isNaN(X)?void 0:Math.max(0,X-Date.now())}function aH($){let w=$?.status,W=$ instanceof Error?$.message:String($);return w===413||/context.{0,20}(?:length|window|limit|too long)/i.test(W)}function oH($,w){return new Promise((W,Z)=>{if(w?.aborted){Z(w.reason);return}let X=setTimeout(W,$);w?.addEventListener("abort",()=>{clearTimeout(X),Z(w.reason)},{once:!0})})}var G$=m1(W6(),1);import*as Gw from"node:readline";function p5(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var P1=p5();function zT($){P1=$}var K1={exec:()=>null};function Zw($){let w=[];return(W)=>{let Z=Math.max(0,Math.min(3,W-1)),X=w[Z];return X||(X=$(Z),w[Z]=X),X}}function m($,w=""){let W=typeof $=="string"?$:$.source,Z={replace:(X,Y)=>{let G=typeof Y=="string"?Y:Y.source;return G=G.replace(f0.caret,"$1"),W=W.replace(X,G),Z},getRegex:()=>new RegExp(W,w)};return Z}var WF=(($="")=>{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: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,${$}}>`))},ZF=/^(?:[ \t]*(?:\n|$))+/,XF=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,YF=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,q4=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,GF=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,t5=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,NT=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,KT=m(NT).replace(/bull/g,t5).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(),JF=m(NT).replace(/bull/g,t5).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(),r5=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,TF=/^[^\n]+/,s5=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,QF=m(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",s5).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),MF=m(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,t5).getRegex(),J6="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",a5=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,zF=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",a5).replace("tag",J6).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),BT=($)=>m(r5).replace("hr",q4).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",J6).getRegex(),NF=BT(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),KF=BT(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),BF=m(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",KF).getRegex(),o5={blockquote:BF,code:XF,def:QF,fences:YF,heading:GF,hr:q4,html:zF,lheading:KT,list:MF,newline:ZF,paragraph:NF,table:K1,text:TF},XT=m("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",q4).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",J6).getRegex(),PF={...o5,lheading:JF,table:XT,paragraph:m(r5).replace("hr",q4).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",XT).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",J6).getRegex()},VF={...o5,html:m(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",a5).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:K1,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:m(r5).replace("hr",q4).replace("heading",` *#{1,6} *[^
66
+ ]`).replace("lheading",KT).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},fF=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,qF=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,PT=/^( {2,}|\\)\n(?!\s*$)/,UF=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,q$=/[\p{P}\p{S}]/u,Xw=/[\s\p{P}\p{S}]/u,U4=/[^\s\p{P}\p{S}]/u,HF=m(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Xw).getRegex(),FF=/[\p{Pi}\p{Ps}"']/u,VT=/(?!~)[\p{P}\p{S}]/u,OF=/(?!~)[\s\p{P}\p{S}]/u,EF=/(?:[^\s\p{P}\p{S}]|~)/u,LF=m(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",WF?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),fT=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,DF=m(fT,"u").replace(/punct/g,q$).getRegex(),kF=m(fT,"u").replace(/punct/g,VT).getRegex(),AF=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,SF=m(AF,"u").replace(/openQuote/g,FF).replace(/punct/g,q$).getRegex(),qT="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",RF=m(qT,"gu").replace(/notPunctSpace/g,U4).replace(/punctSpace/g,Xw).replace(/punct/g,q$).getRegex(),CF=m(qT,"gu").replace(/notPunctSpace/g,EF).replace(/punctSpace/g,OF).replace(/punct/g,VT).getRegex(),jF="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",yF=m(jF,"gu").replace(/notPunctSpace/g,U4).replace(/punctSpace/g,Xw).replace(/punct/g,q$).getRegex(),IF=m("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,U4).replace(/punctSpace/g,Xw).replace(/punct/g,q$).getRegex(),bF="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",xF=m(bF,"gu").replace(/notPunctSpace/g,U4).replace(/punctSpace/g,Xw).replace(/punct/g,q$).getRegex(),_F=m(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,q$).getRegex(),gF="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",vF=m(gF,"gu").replace(/notPunctSpace/g,U4).replace(/punctSpace/g,Xw).replace(/punct/g,q$).getRegex(),uF=m(/\\(punct)/,"gu").replace(/punct/g,q$).getRegex(),hF=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(),iF=m(a5).replace("(?:-->|$)","-->").getRegex(),mF=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",iF).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),X6=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,lF=m(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",X6).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),UT=m(/^!?\[(label)\]\[(ref)\]/).replace("label",X6).replace("ref",s5).getRegex(),HT=m(/^!?\[(ref)\](?:\[\])?/).replace("ref",s5).getRegex(),cF=m("reflink|nolink(?!\\()","g").replace("reflink",UT).replace("nolink",HT).getRegex(),YT=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,e5={_backpedal:K1,anyPunctuation:uF,autolink:hF,blockSkip:LF,br:PT,code:qF,del:K1,delLDelim:K1,delRDelim:K1,emStrongLDelim:DF,emStrongRDelimAst:RF,emStrongRDelimUnd:IF,escape:fF,link:lF,nolink:HT,punctuation:HF,reflink:UT,reflinkSearch:cF,tag:mF,text:UF,url:K1},dF={...e5,emStrongLDelim:SF,emStrongRDelimAst:yF,emStrongRDelimUnd:xF,link:m(/^!?\[(label)\]\((.*?)\)/).replace("label",X6).getRegex(),reflink:m(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",X6).getRegex()},n5={...e5,emStrongRDelimAst:CF,emStrongLDelim:kF,delLDelim:_F,delRDelim:vF,url:m(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",YT).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",YT).getRegex()},nF={...n5,br:m(PT).replace("{2,}","*").getRegex(),text:m(n5.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Z6={normal:o5,gfm:PF,pedantic:VF},V4={normal:e5,gfm:n5,breaks:nF,pedantic:dF},pF={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},GT=($)=>pF[$];function Y$($,w){if(w){if(f0.escapeTest.test($))return $.replace(f0.escapeReplace,GT)}else if(f0.escapeTestNoEncode.test($))return $.replace(f0.escapeReplaceNoEncode,GT);return $}function JT($){try{$=encodeURI($).replace(f0.percentDecode,"%")}catch{return null}return $}function TT($,w){let W=$.replace(f0.findPipe,(Y,G,J)=>{let T=!1,Q=G;for(;--Q>=0&&J[Q]==="\\";)T=!T;return T?"|":" |"}),Z=W.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 m$($,w,W){let Z=$.length;if(Z===0)return"";let X=0;for(;X<Z;){let Y=$.charAt(Z-X-1);if(Y===w&&!W)X++;else if(Y!==w&&W)X++;else break}return $.slice(0,Z-X)}function QT($){let w=$.split(`
67
67
  `),W=w.length-1;for(;W>=0&&f0.blankLine.test(w[W]);)W--;return w.length-W<=2?$:w.slice(0,W+1).join(`
68
- `)}function tF($,w){if($.indexOf(w[1])===-1)return-1;let W=0;for(let Z=0;Z<$.length;Z++)if($[Z]==="\\")Z++;else if($[Z]===w[0])W++;else if($[Z]===w[1]&&(W--,W<0))return Z;return W>0?-2:-1}function rF($,w=0){let W=w,Z="";for(let X of $)if(X==="\t"){let Y=4-W%4;Z+=" ".repeat(Y),W+=Y}else Z+=X,W++;return Z}function QT($,w,W,Z,X){let Y=w.href,G=w.title||null,J=$[1].replace(X.other.outputLinkReplace,"$1"),T=$[0].charAt(0)==="!";Z.state.inLink=!0;let Q=Z.state.linkEmitted,M=Z.state.inRawBlock;Z.state.linkEmitted=!1;let z=Z.inlineTokens(J),N=Z.state.linkEmitted;if(Z.state.linkEmitted=Q,Z.state.inLink=!1,!T){if(N){Z.state.inRawBlock=M;return}Z.state.linkEmitted=!0}return{type:T?"image":"link",raw:W,href:Y,title:G,text:J,tokens:z}}function sF($,w,W){let Z=$.match(W.other.indentCodeCompensation);if(Z===null)return w;let X=Z[1];return w.split(`
68
+ `)}function tF($,w){if($.indexOf(w[1])===-1)return-1;let W=0;for(let Z=0;Z<$.length;Z++)if($[Z]==="\\")Z++;else if($[Z]===w[0])W++;else if($[Z]===w[1]&&(W--,W<0))return Z;return W>0?-2:-1}function rF($,w=0){let W=w,Z="";for(let X of $)if(X==="\t"){let Y=4-W%4;Z+=" ".repeat(Y),W+=Y}else Z+=X,W++;return Z}function MT($,w,W,Z,X){let Y=w.href,G=w.title||null,J=$[1].replace(X.other.outputLinkReplace,"$1"),T=$[0].charAt(0)==="!";Z.state.inLink=!0;let Q=Z.state.linkEmitted,M=Z.state.inRawBlock;Z.state.linkEmitted=!1;let z=Z.inlineTokens(J),N=Z.state.linkEmitted;if(Z.state.linkEmitted=Q,Z.state.inLink=!1,!T){if(N){Z.state.inRawBlock=M;return}Z.state.linkEmitted=!0}return{type:T?"image":"link",raw:W,href:Y,title:G,text:J,tokens:z}}function sF($,w,W){let Z=$.match(W.other.indentCodeCompensation);if(Z===null)return w;let X=Z[1];return w.split(`
69
69
  `).map((Y)=>{let G=Y.match(W.other.beginningSpace);if(G===null)return Y;let[J]=G;return J.length>=X.length?Y.slice(X.length):Y}).join(`
70
- `)}var X6=class{options;rules;lexer;constructor($){this.options=$||P1}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 W=this.options.pedantic?w[0]:TT(w[0]),Z=W.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:W,codeBlockStyle:"indented",text:Z}}}fences($){let w=this.rules.block.fences.exec($);if(w){let W=w[0],Z=sF(W,w[3]||"",this.rules);return{type:"code",raw:W,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 W=w[2].trim();if(this.rules.other.endingHash.test(W)){let Z=m$(W,"#");(this.options.pedantic||!Z||this.rules.other.endingSpaceChar.test(Z))&&(W=Z.trim())}return{type:"heading",raw:m$(w[0],`
70
+ `)}var Y6=class{options;rules;lexer;constructor($){this.options=$||P1}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 W=this.options.pedantic?w[0]:QT(w[0]),Z=W.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:W,codeBlockStyle:"indented",text:Z}}}fences($){let w=this.rules.block.fences.exec($);if(w){let W=w[0],Z=sF(W,w[3]||"",this.rules);return{type:"code",raw:W,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 W=w[2].trim();if(this.rules.other.endingHash.test(W)){let Z=m$(W,"#");(this.options.pedantic||!Z||this.rules.other.endingSpaceChar.test(Z))&&(W=Z.trim())}return{type:"heading",raw:m$(w[0],`
71
71
  `),depth:w[1].length,text:W,tokens:this.lexer.inline(W)}}}hr($){let w=this.rules.block.hr.exec($);if(w)return{type:"hr",raw:m$(w[0],`
72
72
  `)}}blockquote($){let w=this.rules.block.blockquote.exec($);if(w){let W=m$(w[0],`
73
73
  `).split(`
@@ -88,12 +88,12 @@ ${K}`,X=X.substring(0,X.length-B.text.length)+q.text;break}else if(N?.type==="li
88
88
  `,1)[0],j;if(N=A,this.options.pedantic?(N=N.replace(this.rules.other.listReplaceNesting," "),j=N):j=N.replace(this.rules.other.tabCharGlobal," "),f.test(N)||H.test(N)||E.test(N)||S.test(N)||P.test(N)||q.test(N))break;if(j.search(this.rules.other.nonSpaceChar)>=K||!N.trim())M+=`
89
89
  `+j.slice(K);else{if(B||z.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||f.test(z)||H.test(z)||q.test(z))break;M+=`
90
90
  `+N}B=!N.trim(),Q+=A+`
91
- `,$=$.substring(A.length+1),z=j.slice(K)}}X.loose||(G?X.loose=!0:this.rules.other.doubleBlankLine.test(Q)&&(G=!0)),X.items.push({type:"list_item",raw:Q,task:!!this.options.gfm&&this.rules.other.listIsTask.test(M),loose:!1,text:M,tokens:[]}),X.raw+=Q}let J=X.items.at(-1);if(J)J.raw=J.raw.trimEnd(),J.text=J.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((z)=>z.type==="space"),M=Q.length>0&&Q.some((z)=>this.rules.other.anyLine.test(z.raw));X.loose=M}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 z=this.lexer.inlineQueue.length-1;z>=0;z--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[z].src)){this.lexer.inlineQueue[z].src=this.lexer.inlineQueue[z].src.replace(this.rules.other.listReplaceTask,"");break}let M=this.rules.other.listTaskCheckbox.exec(T.raw);if(M){let z={type:"checkbox",raw:M[0]+" ",checked:M[0]!=="[ ]"};T.checked=z.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=z.raw+T.tokens[0].raw,T.tokens[0].text=z.raw+T.tokens[0].text,T.tokens[0].tokens.unshift(z)):T.tokens.unshift({type:"paragraph",raw:z.raw,text:z.raw,tokens:[z]}):T.tokens.unshift(z)}}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 W=TT(w[0]);return{type:"html",block:!0,raw:W,pre:w[1]==="pre"||w[1]==="script"||w[1]==="style",text:W}}}def($){let w=this.rules.block.def.exec($);if(w){let W=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:W,raw:m$(w[0],`
92
- `),href:Z,title:X}}}table($){let w=this.rules.block.table.exec($);if(!w||!this.rules.other.tableDelimiter.test(w[2]))return;let W=JT(w[1]),Z=w[2].replace(this.rules.other.tableAlignChars,"").split("|"),X=w[3]?.trim()?w[3].replace(this.rules.other.tableRowBlankLine,"").split(`
91
+ `,$=$.substring(A.length+1),z=j.slice(K)}}X.loose||(G?X.loose=!0:this.rules.other.doubleBlankLine.test(Q)&&(G=!0)),X.items.push({type:"list_item",raw:Q,task:!!this.options.gfm&&this.rules.other.listIsTask.test(M),loose:!1,text:M,tokens:[]}),X.raw+=Q}let J=X.items.at(-1);if(J)J.raw=J.raw.trimEnd(),J.text=J.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((z)=>z.type==="space"),M=Q.length>0&&Q.some((z)=>this.rules.other.anyLine.test(z.raw));X.loose=M}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 z=this.lexer.inlineQueue.length-1;z>=0;z--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[z].src)){this.lexer.inlineQueue[z].src=this.lexer.inlineQueue[z].src.replace(this.rules.other.listReplaceTask,"");break}let M=this.rules.other.listTaskCheckbox.exec(T.raw);if(M){let z={type:"checkbox",raw:M[0]+" ",checked:M[0]!=="[ ]"};T.checked=z.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=z.raw+T.tokens[0].raw,T.tokens[0].text=z.raw+T.tokens[0].text,T.tokens[0].tokens.unshift(z)):T.tokens.unshift({type:"paragraph",raw:z.raw,text:z.raw,tokens:[z]}):T.tokens.unshift(z)}}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 W=QT(w[0]);return{type:"html",block:!0,raw:W,pre:w[1]==="pre"||w[1]==="script"||w[1]==="style",text:W}}}def($){let w=this.rules.block.def.exec($);if(w){let W=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:W,raw:m$(w[0],`
92
+ `),href:Z,title:X}}}table($){let w=this.rules.block.table.exec($);if(!w||!this.rules.other.tableDelimiter.test(w[2]))return;let W=TT(w[1]),Z=w[2].replace(this.rules.other.tableAlignChars,"").split("|"),X=w[3]?.trim()?w[3].replace(this.rules.other.tableRowBlankLine,"").split(`
93
93
  `):[],Y={type:"table",raw:m$(w[0],`
94
- `),header:[],align:[],rows:[]};if(W.length===Z.length){for(let G of Z)this.rules.other.tableAlignRight.test(G)?Y.align.push("right"):this.rules.other.tableAlignCenter.test(G)?Y.align.push("center"):this.rules.other.tableAlignLeft.test(G)?Y.align.push("left"):Y.align.push(null);for(let G=0;G<W.length;G++)Y.header.push({text:W[G],tokens:this.lexer.inline(W[G]),header:!0,align:Y.align[G]});for(let G of X)Y.rows.push(JT(G,Y.header.length).map((J,T)=>({text:J,tokens:this.lexer.inline(J),header:!1,align:Y.align[T]})));return Y}}lheading($){let w=this.rules.block.lheading.exec($);if(w){let W=w[1].trim();return{type:"heading",raw:m$(w[0],`
94
+ `),header:[],align:[],rows:[]};if(W.length===Z.length){for(let G of Z)this.rules.other.tableAlignRight.test(G)?Y.align.push("right"):this.rules.other.tableAlignCenter.test(G)?Y.align.push("center"):this.rules.other.tableAlignLeft.test(G)?Y.align.push("left"):Y.align.push(null);for(let G=0;G<W.length;G++)Y.header.push({text:W[G],tokens:this.lexer.inline(W[G]),header:!0,align:Y.align[G]});for(let G of X)Y.rows.push(TT(G,Y.header.length).map((J,T)=>({text:J,tokens:this.lexer.inline(J),header:!1,align:Y.align[T]})));return Y}}lheading($){let w=this.rules.block.lheading.exec($);if(w){let W=w[1].trim();return{type:"heading",raw:m$(w[0],`
95
95
  `),depth:w[2].charAt(0)==="="?1:2,text:W,tokens:this.lexer.inline(W)}}}paragraph($){let w=this.rules.block.paragraph.exec($);if(w){let W=w[1].charAt(w[1].length-1)===`
96
- `?w[1].slice(0,-1):w[1];return{type:"paragraph",raw:w[0],text:W,tokens:this.lexer.inline(W)}}}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 W=w[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(W)){if(!this.rules.other.endAngleBracket.test(W))return;let Y=m$(W.slice(0,-1),"\\");if((W.length-Y.length)%2===0)return}else{let Y=tF(w[2],"()");if(Y===-2)return;if(Y>-1){let G=(w[0].indexOf("!")===0?5:4)+w[1].length+Y;w[2]=w[2].substring(0,Y),w[0]=w[0].substring(0,G).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(W)?Z=Z.slice(1):Z=Z.slice(1,-1)),QT(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 W;if((W=this.rules.inline.reflink.exec($))||(W=this.rules.inline.nolink.exec($))){let Z=(W[2]||W[1]).replace(this.rules.other.multipleSpaceGlobal," "),X=w[Z.toLowerCase()];if(!X){let Y=W[0].charAt(0);return{type:"text",raw:Y,text:Y}}return QT(W,X,W[0],this.lexer,this.rules)}}emStrong($,w,W=""){let Z=this.rules.inline.emStrongLDelim.exec($);if(!Z||!Z[1]&&!Z[2]&&!Z[3]&&!Z[4]||Z[4]&&W.match(this.rules.other.unicodeAlphaNumeric))return;if(!(Z[1]||Z[3])||!W||this.rules.inline.punctuation.exec(W)){let X=[...Z[0]].length-1,Y,G,J=X,T=0,Q=Z[0][0],M=W===Q,z=Q==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(z.lastIndex=0,w=w.slice(-1*$.length+X);(Z=z.exec(w))!==null;){if(Y=Z[1]||Z[2]||Z[3]||Z[4]||Z[5]||Z[6],!Y)continue;if(G=[...Y].length,Z[3]||Z[4]){J+=G;continue}else if(Z[5]||Z[6]){if(X%3&&!((X+G)%3)){T+=G;continue}if(M)break}if(J-=G,J>0)continue;G=Math.min(G,G+J+T);let N=[...Z[0]][0].length,B=$.slice(0,X+Z.index+N+G);if(Math.min(X,G)%2){let P=B.slice(1,-1);return{type:"em",raw:B,text:P,tokens:this.lexer.inlineTokens(P)}}let K=B.slice(2,-2);return{type:"strong",raw:B,text:K,tokens:this.lexer.inlineTokens(K)}}}}codespan($){let w=this.rules.inline.code.exec($);if(w){let W=w[2].replace(this.rules.other.newLineCharGlobal," "),Z=this.rules.other.nonSpaceChar.test(W),X=this.rules.other.startingSpaceChar.test(W)&&this.rules.other.endingSpaceChar.test(W);return Z&&X&&(W=W.substring(1,W.length-1)),{type:"codespan",raw:w[0],text:W}}}br($){let w=this.rules.inline.br.exec($);if(w)return{type:"br",raw:w[0]}}del($,w,W=""){let Z=this.rules.inline.delLDelim.exec($);if(!Z)return;if(!Z[1]||!W||this.rules.inline.punctuation.exec(W)){let X=[...Z[0]].length-1,Y,G,J=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||(G=[...Y].length,G!==X))continue;if(Z[3]||Z[4]){J+=G;continue}if(J-=G,J>0)continue;G=Math.min(G,G+J);let Q=[...Z[0]][0].length,M=$.slice(0,X+Z.index+Q+G),z=M.slice(X,-X);return{type:"del",raw:M,text:z,tokens:this.lexer.inlineTokens(z)}}}}autolink($){let w=this.rules.inline.autolink.exec($);if(w){let W,Z;return w[2]==="@"?(W=w[1],Z="mailto:"+W):(W=w[1],Z=W),{type:"link",raw:w[0],text:W,href:Z,tokens:[{type:"text",raw:W,text:W}]}}}url($){let w;if(w=this.rules.inline.url.exec($)){let W,Z;if(w[2]==="@")W=w[0],Z="mailto:"+W;else{let X;do X=w[0],w[0]=this.rules.inline._backpedal.exec(w[0])?.[0]??"";while(X!==w[0]);W=w[0],w[1]==="www."?Z="http://"+w[0]:Z=w[0]}return{type:"link",raw:w[0],text:W,href:Z,tokens:[{type:"text",raw:W,text:W}]}}}inlineText($){let w=this.rules.inline.text.exec($);if(w){let W=this.lexer.state.inRawBlock;return{type:"text",raw:w[0],text:w[0],escaped:W}}}},r0=class ${tokens;options;state;inlineQueue;tokenizer;constructor(w){this.tokens=[],this.tokens.links=Object.create(null),this.options=w||P1,this.options.tokenizer=this.options.tokenizer||new X6,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 W={other:f0,block:W6.normal,inline:V9.normal};this.options.pedantic?(W.block=W6.pedantic,W.inline=V9.pedantic):this.options.gfm&&(W.block=W6.gfm,this.options.breaks?W.inline=V9.breaks:W.inline=V9.gfm),this.tokenizer.rules=W}static get rules(){return{block:W6,inline:V9}}static lex(w,W){return new $(W).lex(w)}static lexInline(w,W){return new $(W).inlineTokens(w)}lex(w){w=w.replace(f0.carriageReturn,`
96
+ `?w[1].slice(0,-1):w[1];return{type:"paragraph",raw:w[0],text:W,tokens:this.lexer.inline(W)}}}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 W=w[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(W)){if(!this.rules.other.endAngleBracket.test(W))return;let Y=m$(W.slice(0,-1),"\\");if((W.length-Y.length)%2===0)return}else{let Y=tF(w[2],"()");if(Y===-2)return;if(Y>-1){let G=(w[0].indexOf("!")===0?5:4)+w[1].length+Y;w[2]=w[2].substring(0,Y),w[0]=w[0].substring(0,G).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(W)?Z=Z.slice(1):Z=Z.slice(1,-1)),MT(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 W;if((W=this.rules.inline.reflink.exec($))||(W=this.rules.inline.nolink.exec($))){let Z=(W[2]||W[1]).replace(this.rules.other.multipleSpaceGlobal," "),X=w[Z.toLowerCase()];if(!X){let Y=W[0].charAt(0);return{type:"text",raw:Y,text:Y}}return MT(W,X,W[0],this.lexer,this.rules)}}emStrong($,w,W=""){let Z=this.rules.inline.emStrongLDelim.exec($);if(!Z||!Z[1]&&!Z[2]&&!Z[3]&&!Z[4]||Z[4]&&W.match(this.rules.other.unicodeAlphaNumeric))return;if(!(Z[1]||Z[3])||!W||this.rules.inline.punctuation.exec(W)){let X=[...Z[0]].length-1,Y,G,J=X,T=0,Q=Z[0][0],M=W===Q,z=Q==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(z.lastIndex=0,w=w.slice(-1*$.length+X);(Z=z.exec(w))!==null;){if(Y=Z[1]||Z[2]||Z[3]||Z[4]||Z[5]||Z[6],!Y)continue;if(G=[...Y].length,Z[3]||Z[4]){J+=G;continue}else if(Z[5]||Z[6]){if(X%3&&!((X+G)%3)){T+=G;continue}if(M)break}if(J-=G,J>0)continue;G=Math.min(G,G+J+T);let N=[...Z[0]][0].length,B=$.slice(0,X+Z.index+N+G);if(Math.min(X,G)%2){let P=B.slice(1,-1);return{type:"em",raw:B,text:P,tokens:this.lexer.inlineTokens(P)}}let K=B.slice(2,-2);return{type:"strong",raw:B,text:K,tokens:this.lexer.inlineTokens(K)}}}}codespan($){let w=this.rules.inline.code.exec($);if(w){let W=w[2].replace(this.rules.other.newLineCharGlobal," "),Z=this.rules.other.nonSpaceChar.test(W),X=this.rules.other.startingSpaceChar.test(W)&&this.rules.other.endingSpaceChar.test(W);return Z&&X&&(W=W.substring(1,W.length-1)),{type:"codespan",raw:w[0],text:W}}}br($){let w=this.rules.inline.br.exec($);if(w)return{type:"br",raw:w[0]}}del($,w,W=""){let Z=this.rules.inline.delLDelim.exec($);if(!Z)return;if(!Z[1]||!W||this.rules.inline.punctuation.exec(W)){let X=[...Z[0]].length-1,Y,G,J=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||(G=[...Y].length,G!==X))continue;if(Z[3]||Z[4]){J+=G;continue}if(J-=G,J>0)continue;G=Math.min(G,G+J);let Q=[...Z[0]][0].length,M=$.slice(0,X+Z.index+Q+G),z=M.slice(X,-X);return{type:"del",raw:M,text:z,tokens:this.lexer.inlineTokens(z)}}}}autolink($){let w=this.rules.inline.autolink.exec($);if(w){let W,Z;return w[2]==="@"?(W=w[1],Z="mailto:"+W):(W=w[1],Z=W),{type:"link",raw:w[0],text:W,href:Z,tokens:[{type:"text",raw:W,text:W}]}}}url($){let w;if(w=this.rules.inline.url.exec($)){let W,Z;if(w[2]==="@")W=w[0],Z="mailto:"+W;else{let X;do X=w[0],w[0]=this.rules.inline._backpedal.exec(w[0])?.[0]??"";while(X!==w[0]);W=w[0],w[1]==="www."?Z="http://"+w[0]:Z=w[0]}return{type:"link",raw:w[0],text:W,href:Z,tokens:[{type:"text",raw:W,text:W}]}}}inlineText($){let w=this.rules.inline.text.exec($);if(w){let W=this.lexer.state.inRawBlock;return{type:"text",raw:w[0],text:w[0],escaped:W}}}},s0=class ${tokens;options;state;inlineQueue;tokenizer;constructor(w){this.tokens=[],this.tokens.links=Object.create(null),this.options=w||P1,this.options.tokenizer=this.options.tokenizer||new Y6,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 W={other:f0,block:Z6.normal,inline:V4.normal};this.options.pedantic?(W.block=Z6.pedantic,W.inline=V4.pedantic):this.options.gfm&&(W.block=Z6.gfm,this.options.breaks?W.inline=V4.breaks:W.inline=V4.gfm),this.tokenizer.rules=W}static get rules(){return{block:Z6,inline:V4}}static lex(w,W){return new $(W).lex(w)}static lexInline(w,W){return new $(W).inlineTokens(w)}lex(w){w=w.replace(f0.carriageReturn,`
97
97
  `),this.blockTokens(w,this.tokens);for(let W=0;W<this.inlineQueue.length;W++){let Z=this.inlineQueue[W];this.inlineTokens(Z.src,Z.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(w,W=[],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((J)=>(Y=J.call({lexer:this},w,W))?(w=w.substring(Y.raw.length),W.push(Y),!0):!1))continue;if(Y=this.tokenizer.space(w)){w=w.substring(Y.raw.length);let J=W.at(-1);Y.raw.length===1&&J!==void 0?J.raw+=`
98
98
  `:W.push(Y);continue}if(Y=this.tokenizer.code(w)){w=w.substring(Y.raw.length);let J=W.at(-1);J?.type==="paragraph"||J?.type==="text"?(J.raw+=(J.raw.endsWith(`
99
99
  `)?"":`
@@ -107,7 +107,7 @@ ${K}`,X=X.substring(0,X.length-B.text.length)+q.text;break}else if(N?.type==="li
107
107
  `+Y.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=J.text):W.push(Y),Z=G.length!==w.length,w=w.substring(Y.raw.length);continue}if(Y=this.tokenizer.text(w)){w=w.substring(Y.raw.length);let J=W.at(-1);J?.type==="text"?(J.raw+=(J.raw.endsWith(`
108
108
  `)?"":`
109
109
  `)+Y.raw,J.text+=`
110
- `+Y.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=J.text):W.push(Y);continue}if(w){this.infiniteLoopError(w.charCodeAt(0));break}}return this.state.top=!0,W}inline(w,W=[]){return this.inlineQueue.push({src:w,tokens:W}),W}linkInText(w){if(!w.includes("["))return!1;let W=this.tokenizer.rules.inline.link;for(let Z of w.matchAll(this.tokenizer.rules.inline.blockSkip))if(W.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,W=[]){this.tokenizer.lexer=this;let Z=w;if(this.tokens.links&&w.includes("[")){let J=this.tokenizer.rules.inline.reflinkSearch,T=(Q)=>{let M=Q.lastIndexOf("[");if(!Object.hasOwn(this.tokens.links,Q.slice(M+1,-1)))return Q;if(M>1&&Q.charAt(0)!=="!"){let z=Q.slice(1,M-1);if(this.linkInText(z))return"["+z.replace(J,T)+"]["+"a".repeat(Q.length-M-2)+"]"}return"["+"a".repeat(Q.length-2)+"]"};Z=Z.replace(J,T)}Z=Z.replace(this.tokenizer.rules.inline.anyPunctuation,(J)=>"+".repeat(J.length)),Z=Z.replace(this.tokenizer.rules.inline.blockSkip,(J,T,Q)=>{let M=Q?Q.length:0;return J.slice(0,M)+"["+"a".repeat(J.length-M-2)+"]"}),Z=this.options.hooks?.emStrongMask?.call({lexer:this},Z)??Z;let X=!1,Y="",G=1/0;for(;w;){if(w.length<G)G=w.length;else{this.infiniteLoopError(w.charCodeAt(0));break}X||(Y=""),X=!1;let J;if(this.options.extensions?.inline?.some((Q)=>(J=Q.call({lexer:this},w,W))?(w=w.substring(J.raw.length),W.push(J),!0):!1))continue;if(J=this.tokenizer.escape(w)){w=w.substring(J.raw.length),W.push(J);continue}if(J=this.tokenizer.tag(w)){w=w.substring(J.raw.length),W.push(J);continue}if(J=this.tokenizer.link(w)){w=w.substring(J.raw.length),W.push(J);continue}if(J=this.tokenizer.reflink(w,this.tokens.links)){w=w.substring(J.raw.length);let Q=W.at(-1);J.type==="text"&&Q?.type==="text"?(Q.raw+=J.raw,Q.text+=J.text):W.push(J);continue}if(J=this.tokenizer.emStrong(w,Z,Y)){w=w.substring(J.raw.length),W.push(J);continue}if(J=this.tokenizer.codespan(w)){w=w.substring(J.raw.length),W.push(J);continue}if(J=this.tokenizer.br(w)){w=w.substring(J.raw.length),W.push(J);continue}if(J=this.tokenizer.del(w,Z,Y)){w=w.substring(J.raw.length),W.push(J);continue}if(J=this.tokenizer.autolink(w)){w=w.substring(J.raw.length),W.push(J);continue}if(!this.state.inLink&&(J=this.tokenizer.url(w))){w=w.substring(J.raw.length),W.push(J);continue}let T=w;if(this.options.extensions?.startInline){let Q=1/0,M=w.slice(1),z;this.options.extensions.startInline.forEach((N)=>{z=N.call({lexer:this},M),typeof z=="number"&&z>=0&&(Q=Math.min(Q,z))}),Q<1/0&&Q>=0&&(T=w.substring(0,Q+1))}if(J=this.tokenizer.inlineText(T)){w=w.substring(J.raw.length),J.raw.slice(-1)!=="_"&&(Y=J.raw.slice(-1)),X=!0;let Q=W.at(-1);Q?.type==="text"?(Q.raw+=J.raw,Q.text+=J.text):W.push(J);continue}if(w){this.infiniteLoopError(w.charCodeAt(0));break}}return W}infiniteLoopError(w){let W="Infinite loop on byte: "+w;if(this.options.silent)console.error(W);else throw Error(W)}},Y6=class{options;parser;constructor($){this.options=$||P1}space($){return""}code({text:$,lang:w,escaped:W}){let Z=(w||"").match(f0.notSpaceStart)?.[0],X=$.replace(f0.endingNewline,"")+`
110
+ `+Y.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=J.text):W.push(Y);continue}if(w){this.infiniteLoopError(w.charCodeAt(0));break}}return this.state.top=!0,W}inline(w,W=[]){return this.inlineQueue.push({src:w,tokens:W}),W}linkInText(w){if(!w.includes("["))return!1;let W=this.tokenizer.rules.inline.link;for(let Z of w.matchAll(this.tokenizer.rules.inline.blockSkip))if(W.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,W=[]){this.tokenizer.lexer=this;let Z=w;if(this.tokens.links&&w.includes("[")){let J=this.tokenizer.rules.inline.reflinkSearch,T=(Q)=>{let M=Q.lastIndexOf("[");if(!Object.hasOwn(this.tokens.links,Q.slice(M+1,-1)))return Q;if(M>1&&Q.charAt(0)!=="!"){let z=Q.slice(1,M-1);if(this.linkInText(z))return"["+z.replace(J,T)+"]["+"a".repeat(Q.length-M-2)+"]"}return"["+"a".repeat(Q.length-2)+"]"};Z=Z.replace(J,T)}Z=Z.replace(this.tokenizer.rules.inline.anyPunctuation,(J)=>"+".repeat(J.length)),Z=Z.replace(this.tokenizer.rules.inline.blockSkip,(J,T,Q)=>{let M=Q?Q.length:0;return J.slice(0,M)+"["+"a".repeat(J.length-M-2)+"]"}),Z=this.options.hooks?.emStrongMask?.call({lexer:this},Z)??Z;let X=!1,Y="",G=1/0;for(;w;){if(w.length<G)G=w.length;else{this.infiniteLoopError(w.charCodeAt(0));break}X||(Y=""),X=!1;let J;if(this.options.extensions?.inline?.some((Q)=>(J=Q.call({lexer:this},w,W))?(w=w.substring(J.raw.length),W.push(J),!0):!1))continue;if(J=this.tokenizer.escape(w)){w=w.substring(J.raw.length),W.push(J);continue}if(J=this.tokenizer.tag(w)){w=w.substring(J.raw.length),W.push(J);continue}if(J=this.tokenizer.link(w)){w=w.substring(J.raw.length),W.push(J);continue}if(J=this.tokenizer.reflink(w,this.tokens.links)){w=w.substring(J.raw.length);let Q=W.at(-1);J.type==="text"&&Q?.type==="text"?(Q.raw+=J.raw,Q.text+=J.text):W.push(J);continue}if(J=this.tokenizer.emStrong(w,Z,Y)){w=w.substring(J.raw.length),W.push(J);continue}if(J=this.tokenizer.codespan(w)){w=w.substring(J.raw.length),W.push(J);continue}if(J=this.tokenizer.br(w)){w=w.substring(J.raw.length),W.push(J);continue}if(J=this.tokenizer.del(w,Z,Y)){w=w.substring(J.raw.length),W.push(J);continue}if(J=this.tokenizer.autolink(w)){w=w.substring(J.raw.length),W.push(J);continue}if(!this.state.inLink&&(J=this.tokenizer.url(w))){w=w.substring(J.raw.length),W.push(J);continue}let T=w;if(this.options.extensions?.startInline){let Q=1/0,M=w.slice(1),z;this.options.extensions.startInline.forEach((N)=>{z=N.call({lexer:this},M),typeof z=="number"&&z>=0&&(Q=Math.min(Q,z))}),Q<1/0&&Q>=0&&(T=w.substring(0,Q+1))}if(J=this.tokenizer.inlineText(T)){w=w.substring(J.raw.length),J.raw.slice(-1)!=="_"&&(Y=J.raw.slice(-1)),X=!0;let Q=W.at(-1);Q?.type==="text"?(Q.raw+=J.raw,Q.text+=J.text):W.push(J);continue}if(w){this.infiniteLoopError(w.charCodeAt(0));break}}return W}infiniteLoopError(w){let W="Infinite loop on byte: "+w;if(this.options.silent)console.error(W);else throw Error(W)}},G6=class{options;parser;constructor($){this.options=$||P1}space($){return""}code({text:$,lang:w,escaped:W}){let Z=(w||"").match(f0.notSpaceStart)?.[0],X=$.replace(f0.endingNewline,"")+`
111
111
  `;return Z?'<pre><code class="language-'+Y$(Z)+'">'+(W?X:Y$(X,!0))+`</code></pre>
112
112
  `:"<pre><code>"+(W?X:Y$(X,!0))+`</code></pre>
113
113
  `}blockquote({tokens:$}){return`<blockquote>
@@ -125,11 +125,11 @@ ${this.parser.parse($)}</blockquote>
125
125
  `}tablerow({text:$}){return`<tr>
126
126
  ${$}</tr>
127
127
  `}tablecell($){let w=this.parser.parseInline($.tokens),W=$.header?"th":"td";return($.align?`<${W} align="${$.align}">`:`<${W}>`)+w+`</${W}>
128
- `}strong({tokens:$}){return`<strong>${this.parser.parseInline($)}</strong>`}em({tokens:$}){return`<em>${this.parser.parseInline($)}</em>`}codespan({text:$}){return`<code>${Y$($,!0)}</code>`}br($){return"<br>"}del({tokens:$}){return`<del>${this.parser.parseInline($)}</del>`}link({href:$,title:w,tokens:W}){let Z=this.parser.parseInline(W),X=GT($);if(X===null)return Z;$=X;let Y='<a href="'+$+'"';return w&&(Y+=' title="'+Y$(w)+'"'),Y+=">"+Z+"</a>",Y}image({href:$,title:w,text:W,tokens:Z}){Z&&(W=this.parser.parseInline(Z,this.parser.textRenderer));let X=GT($);if(X===null)return Y$(W);$=X;let Y=`<img src="${$}" alt="${Y$(W)}"`;return w&&(Y+=` title="${Y$(w)}"`),Y+=">",Y}text($){return"tokens"in $&&$.tokens?this.parser.parseInline($.tokens):("escaped"in $)&&$.escaped?$.text:Y$($.text)}},e5=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 $}},s0=class ${options;renderer;textRenderer;constructor(w){this.options=w||P1,this.options.renderer=this.options.renderer||new Y6,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new e5}static parse(w,W){return new $(W).parse(w)}static parseInline(w,W){return new $(W).parseInline(w)}parse(w){this.renderer.parser=this;let W="";for(let Z=0;Z<w.length;Z++){let X=w[Z];if(this.options.extensions?.renderers?.[X.type]){let G=X,J=this.options.extensions.renderers[G.type].call({parser:this},G);if(J!==!1||!["space","hr","heading","code","table","blockquote","list","checkbox","html","def","paragraph","text"].includes(G.type)){W+=J||"";continue}}let Y=X;switch(Y.type){case"space":{W+=this.renderer.space(Y);break}case"hr":{W+=this.renderer.hr(Y);break}case"heading":{W+=this.renderer.heading(Y);break}case"code":{W+=this.renderer.code(Y);break}case"table":{W+=this.renderer.table(Y);break}case"blockquote":{W+=this.renderer.blockquote(Y);break}case"list":{W+=this.renderer.list(Y);break}case"checkbox":{W+=this.renderer.checkbox(Y);break}case"html":{W+=this.renderer.html(Y);break}case"def":{W+=this.renderer.def(Y);break}case"paragraph":{W+=this.renderer.paragraph(Y);break}case"text":{W+=this.renderer.text(Y);break}default:{let G='Token with "'+Y.type+'" type was not found.';if(this.options.silent)return console.error(G),"";throw Error(G)}}}return W}parseInline(w,W=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 J=this.options.extensions.renderers[Y.type].call({parser:this},Y);if(J!==!1||!["escape","html","link","image","checkbox","strong","em","codespan","br","del","text"].includes(Y.type)){Z+=J||"";continue}}let G=Y;switch(G.type){case"escape":{Z+=W.text(G);break}case"html":{Z+=W.html(G);break}case"link":{Z+=W.link(G);break}case"image":{Z+=W.image(G);break}case"checkbox":{Z+=W.checkbox(G);break}case"strong":{Z+=W.strong(G);break}case"em":{Z+=W.em(G);break}case"codespan":{Z+=W.codespan(G);break}case"br":{Z+=W.br(G);break}case"del":{Z+=W.del(G);break}case"text":{Z+=W.text(G);break}default:{let J='Token with "'+G.type+'" type was not found.';if(this.options.silent)return console.error(J),"";throw Error(J)}}}return Z}},f9=class{options;block;constructor($){this.options=$||P1}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 $?r0.lex:r0.lexInline}provideParser($=this.block){return $?s0.parse:s0.parseInline}},aF=class{defaults=n5();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=s0;Renderer=Y6;TextRenderer=e5;Lexer=r0;Tokenizer=X6;Hooks=f9;constructor(...$){this.use(...$)}walkTokens($,w){let W=[];for(let Z of $)switch(W=W.concat(w.call(this,Z)),Z.type){case"table":{let X=Z;for(let Y of X.header)W=W.concat(this.walkTokens(Y.tokens,w));for(let Y of X.rows)for(let G of Y)W=W.concat(this.walkTokens(G.tokens,w));break}case"list":{let X=Z;W=W.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 G=X[Y].flat(1/0);W=W.concat(this.walkTokens(G,w))}):X.tokens&&(W=W.concat(this.walkTokens(X.tokens,w)))}}return W}use(...$){let w=this.defaults.extensions||{renderers:{},childTokens:{}};return $.forEach((W)=>{let Z={...W};if(Z.async=this.defaults.async||Z.async||!1,W.extensions&&(W.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(...G){let J=X.renderer.apply(this,G);return J===!1&&(J=Y.apply(this,G)),J}: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),W.renderer){let X=this.defaults.renderer||new Y6(this.defaults);for(let Y in W.renderer){if(!(Y in X))throw Error(`renderer '${Y}' does not exist`);if(["options","parser"].includes(Y))continue;let G=Y,J=W.renderer[G],T=X[G];X[G]=(...Q)=>{let M=J.apply(X,Q);return M===!1&&(M=T.apply(X,Q)),M||""}}Z.renderer=X}if(W.tokenizer){let X=this.defaults.tokenizer||new X6(this.defaults);for(let Y in W.tokenizer){if(!(Y in X))throw Error(`tokenizer '${Y}' does not exist`);if(["options","rules","lexer"].includes(Y))continue;let G=Y,J=W.tokenizer[G],T=X[G];X[G]=(...Q)=>{let M=J.apply(X,Q);return M===!1&&(M=T.apply(X,Q)),M}}Z.tokenizer=X}if(W.hooks){let X=this.defaults.hooks||new f9;for(let Y in W.hooks){if(!(Y in X))throw Error(`hook '${Y}' does not exist`);if(["options","block"].includes(Y))continue;let G=Y,J=W.hooks[G],T=X[G];f9.passThroughHooks.has(Y)?X[G]=(Q)=>{if(this.defaults.async&&f9.passThroughHooksRespectAsync.has(Y))return(async()=>{let z=await J.call(X,Q);return T.call(X,z)})();let M=J.call(X,Q);return T.call(X,M)}:X[G]=(...Q)=>{if(this.defaults.async)return(async()=>{let z=await J.apply(X,Q);return z===!1&&(z=await T.apply(X,Q)),z})();let M=J.apply(X,Q);return M===!1&&(M=T.apply(X,Q)),M}}Z.hooks=X}if(W.walkTokens){let X=this.defaults.walkTokens,Y=W.walkTokens;Z.walkTokens=function(G){let J=[];return J.push(Y.call(this,G)),X&&(J=J.concat(X.call(this,G))),J}}this.defaults={...this.defaults,...Z}}),this}setOptions($){return this.defaults={...this.defaults,...$},this}lexer($,w){return r0.lex($,w??this.defaults)}parser($,w){return s0.parse($,w??this.defaults)}parseMarkdown($){return(w,W)=>{let Z={...W},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 G=X.hooks?await X.hooks.preprocess(w):w,J=await(X.hooks?await X.hooks.provideLexer($):$?r0.lex:r0.lexInline)(G,X),T=X.hooks?await X.hooks.processAllTokens(J):J;X.walkTokens&&await Promise.all(this.walkTokens(T,X.walkTokens));let Q=await(X.hooks?await X.hooks.provideParser($):$?s0.parse:s0.parseInline)(T,X);return X.hooks?await X.hooks.postprocess(Q):Q})().catch(Y);try{X.hooks&&(w=X.hooks.preprocess(w));let G=(X.hooks?X.hooks.provideLexer($):$?r0.lex:r0.lexInline)(w,X);X.hooks&&(G=X.hooks.processAllTokens(G)),X.walkTokens&&this.walkTokens(G,X.walkTokens);let J=(X.hooks?X.hooks.provideParser($):$?s0.parse:s0.parseInline)(G,X);return X.hooks&&(J=X.hooks.postprocess(J)),J}catch(G){return Y(G)}}}onError($,w){return(W)=>{if(W.message+=`
129
- Please report this to https://github.com/markedjs/marked.`,$){let Z="<p>An error occurred:</p><pre>"+Y$(W.message+"",!0)+"</pre>";return w?Promise.resolve(Z):Z}if(w)return Promise.reject(W);throw W}}},B1=new aF;function t($,w){return B1.parse($,w)}t.options=t.setOptions=function($){return B1.setOptions($),t.defaults=B1.defaults,MT(t.defaults),t};t.getDefaults=n5;t.defaults=P1;function oF(...$){return B1.use(...$),t.defaults=B1.defaults,MT(t.defaults),t}t.use=oF;t.walkTokens=function($,w){return B1.walkTokens($,w)};t.parseInline=B1.parseInline;t.Parser=s0;t.parser=s0.parse;t.Renderer=Y6;t.TextRenderer=e5;t.Lexer=r0;t.lexer=r0.lex;t.Tokenizer=X6;t.Hooks=f9;t.parse=t;var{options:zR,setOptions:NR,walkTokens:KR,parseInline:BR}=t;var PR=s0.parse,VR=r0.lex;var a0=m1(w6(),1);var O9=m1(w6(),1);import{stripVTControlCharacters as $O}from"node:util";import{stripVTControlCharacters as eF}from"node:util";function X0($){return Array.from(eF($)).filter((w)=>{let W=w.codePointAt(0)??0;return W===9||W===10||W>159||W>31&&W<127}).join("")}function H9($){let w=$.codePointAt(0)??0;if(w>=9472&&w<=9599)return 1;return w<=255?1:2}function F9($){return Array.from($).reduce((w,W)=>w+H9(W),0)}function Yw($,w,W="head"){if(w<=0)return"";if(F9($)<=w)return $;if(w===1)return"…";let Z=Array.from($),X=[],Y=1,G=W==="head"?Z.map((J,T)=>T):Z.map((J,T)=>Z.length-T-1);for(let J of G){let T=Z[J];if(T===void 0||Y+H9(T)>w)break;if(W==="head")X.push(T);else X.unshift(T);Y+=H9(T)}return W==="head"?`${X.join("")}…`:`…${X.join("")}`}var WZ="\x1B",FT=`${WZ}[0m`,wO=new RegExp(`^${WZ}\\[[0-?]*[ -/]*[@-~]`);function OT($){return F9($O($))}function ET($){let w=[],W=0,Z="";while(W<$.length){let X=$.slice(W).match(wO)?.[0];if(X){if(X.endsWith("m"))Z=X===`${WZ}[m`||X===FT?"":`${Z}${X}`;W+=X.length;continue}let Y=$.codePointAt(W);if(Y===void 0)break;let G=String.fromCodePoint(Y);w.push({value:G,width:H9(G),state:Z}),W+=G.length}return w}function $Z($){return $.map((w)=>w.state?`${w.state}${w.value}${FT}`:w.value).join("")}function WO($,w){if($.length===0)return[""];let W=[],Z=$;while(Z.length>0){if(W.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,G=-1;while(Y<Z.length){let J=Z[Y];if(!J||Y>0&&X+J.width>w)break;if(X+=J.width,/\s/u.test(J.value))G=Y;if(Y+=1,X>=w)break}if(Y>=Z.length){W.push($Z(Z));break}if(G>=0){W.push($Z(Z.slice(0,G))),Z=Z.slice(G+1);while(Z[0]&&/\s/u.test(Z[0].value))Z=Z.slice(1);continue}W.push($Z(Z.slice(0,Math.max(1,Y)))),Z=Z.slice(Math.max(1,Y))}return W.length>0?W:[""]}function ZO($,w){let W=Math.max(1,w);return $.split(`
130
- `).flatMap((Z)=>WO(ET(Z),W))}function XO($){return $.some((w)=>ET(w).some((W)=>W.width>1))?2:1}function YO($){return Math.max(1,...$.flatMap((w)=>w.split(`
131
- `).map(OT)))}function GO($,w){let W=$.header.length,Z=$.header.map((J,T)=>[J,...$.rows.map((Q)=>Q[T]??"")]),X=Z.map(XO),Y=Z.map(YO),G=Math.max(X.reduce((J,T)=>J+T,0),w-(3*W+1));while(Y.reduce((J,T)=>J+T,0)>G){let J=-1;for(let T=0;T<Y.length;T+=1){let Q=Y[T]??0,M=X[T]??1;if(Q>M&&(J<0||Q>(Y[J]??0)))J=T}if(J<0)break;Y[J]=(Y[J]??1)-1}return Y}function JO($,w,W){let Z=Math.max(0,w-OT($)),X=W==="right"?Z:W==="center"?Math.floor(Z/2):0;return`${" ".repeat(X)}${$}${" ".repeat(Z-X)}`}function wZ($,w,W,Z){return O9.default.dim(`${$}${Z.map((X)=>"─".repeat(X+2)).join(w)}${W}`)}function HT($,w,W){let Z=W.map((Y,G)=>ZO($[G]??"",Y)),X=Math.max(1,...Z.map((Y)=>Y.length));return Array.from({length:X},(Y,G)=>{let J=W.map((T,Q)=>JO(Z[Q]?.[G]??"",T,w[Q]??"left"));return`${O9.default.dim("│")} ${J.join(` ${O9.default.dim("│")} `)} ${O9.default.dim("│")}`})}function LT($,w){if($.header.length===0)return"";let W=GO($,Math.max(1,w)),Z=W.map((Y,G)=>$.align[G]??"left");return[wZ("┌","┬","┐",W),...HT($.header,Z,W),wZ("├","┼","┤",W),...$.rows.flatMap((Y)=>HT(Y,Z,W)),wZ("└","┴","┘",W)].join(`
132
- `)}class ZZ{write;columns;pending="";fence;table;constructor($,w=()=>80){this.write=$;this.columns=w}push($){this.pending+=X0($);let w=this.pending.indexOf(`
128
+ `}strong({tokens:$}){return`<strong>${this.parser.parseInline($)}</strong>`}em({tokens:$}){return`<em>${this.parser.parseInline($)}</em>`}codespan({text:$}){return`<code>${Y$($,!0)}</code>`}br($){return"<br>"}del({tokens:$}){return`<del>${this.parser.parseInline($)}</del>`}link({href:$,title:w,tokens:W}){let Z=this.parser.parseInline(W),X=JT($);if(X===null)return Z;$=X;let Y='<a href="'+$+'"';return w&&(Y+=' title="'+Y$(w)+'"'),Y+=">"+Z+"</a>",Y}image({href:$,title:w,text:W,tokens:Z}){Z&&(W=this.parser.parseInline(Z,this.parser.textRenderer));let X=JT($);if(X===null)return Y$(W);$=X;let Y=`<img src="${$}" alt="${Y$(W)}"`;return w&&(Y+=` title="${Y$(w)}"`),Y+=">",Y}text($){return"tokens"in $&&$.tokens?this.parser.parseInline($.tokens):("escaped"in $)&&$.escaped?$.text:Y$($.text)}},$Z=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 $}},a0=class ${options;renderer;textRenderer;constructor(w){this.options=w||P1,this.options.renderer=this.options.renderer||new G6,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new $Z}static parse(w,W){return new $(W).parse(w)}static parseInline(w,W){return new $(W).parseInline(w)}parse(w){this.renderer.parser=this;let W="";for(let Z=0;Z<w.length;Z++){let X=w[Z];if(this.options.extensions?.renderers?.[X.type]){let G=X,J=this.options.extensions.renderers[G.type].call({parser:this},G);if(J!==!1||!["space","hr","heading","code","table","blockquote","list","checkbox","html","def","paragraph","text"].includes(G.type)){W+=J||"";continue}}let Y=X;switch(Y.type){case"space":{W+=this.renderer.space(Y);break}case"hr":{W+=this.renderer.hr(Y);break}case"heading":{W+=this.renderer.heading(Y);break}case"code":{W+=this.renderer.code(Y);break}case"table":{W+=this.renderer.table(Y);break}case"blockquote":{W+=this.renderer.blockquote(Y);break}case"list":{W+=this.renderer.list(Y);break}case"checkbox":{W+=this.renderer.checkbox(Y);break}case"html":{W+=this.renderer.html(Y);break}case"def":{W+=this.renderer.def(Y);break}case"paragraph":{W+=this.renderer.paragraph(Y);break}case"text":{W+=this.renderer.text(Y);break}default:{let G='Token with "'+Y.type+'" type was not found.';if(this.options.silent)return console.error(G),"";throw Error(G)}}}return W}parseInline(w,W=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 J=this.options.extensions.renderers[Y.type].call({parser:this},Y);if(J!==!1||!["escape","html","link","image","checkbox","strong","em","codespan","br","del","text"].includes(Y.type)){Z+=J||"";continue}}let G=Y;switch(G.type){case"escape":{Z+=W.text(G);break}case"html":{Z+=W.html(G);break}case"link":{Z+=W.link(G);break}case"image":{Z+=W.image(G);break}case"checkbox":{Z+=W.checkbox(G);break}case"strong":{Z+=W.strong(G);break}case"em":{Z+=W.em(G);break}case"codespan":{Z+=W.codespan(G);break}case"br":{Z+=W.br(G);break}case"del":{Z+=W.del(G);break}case"text":{Z+=W.text(G);break}default:{let J='Token with "'+G.type+'" type was not found.';if(this.options.silent)return console.error(J),"";throw Error(J)}}}return Z}},f4=class{options;block;constructor($){this.options=$||P1}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 $?s0.lex:s0.lexInline}provideParser($=this.block){return $?a0.parse:a0.parseInline}},aF=class{defaults=p5();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=a0;Renderer=G6;TextRenderer=$Z;Lexer=s0;Tokenizer=Y6;Hooks=f4;constructor(...$){this.use(...$)}walkTokens($,w){let W=[];for(let Z of $)switch(W=W.concat(w.call(this,Z)),Z.type){case"table":{let X=Z;for(let Y of X.header)W=W.concat(this.walkTokens(Y.tokens,w));for(let Y of X.rows)for(let G of Y)W=W.concat(this.walkTokens(G.tokens,w));break}case"list":{let X=Z;W=W.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 G=X[Y].flat(1/0);W=W.concat(this.walkTokens(G,w))}):X.tokens&&(W=W.concat(this.walkTokens(X.tokens,w)))}}return W}use(...$){let w=this.defaults.extensions||{renderers:{},childTokens:{}};return $.forEach((W)=>{let Z={...W};if(Z.async=this.defaults.async||Z.async||!1,W.extensions&&(W.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(...G){let J=X.renderer.apply(this,G);return J===!1&&(J=Y.apply(this,G)),J}: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),W.renderer){let X=this.defaults.renderer||new G6(this.defaults);for(let Y in W.renderer){if(!(Y in X))throw Error(`renderer '${Y}' does not exist`);if(["options","parser"].includes(Y))continue;let G=Y,J=W.renderer[G],T=X[G];X[G]=(...Q)=>{let M=J.apply(X,Q);return M===!1&&(M=T.apply(X,Q)),M||""}}Z.renderer=X}if(W.tokenizer){let X=this.defaults.tokenizer||new Y6(this.defaults);for(let Y in W.tokenizer){if(!(Y in X))throw Error(`tokenizer '${Y}' does not exist`);if(["options","rules","lexer"].includes(Y))continue;let G=Y,J=W.tokenizer[G],T=X[G];X[G]=(...Q)=>{let M=J.apply(X,Q);return M===!1&&(M=T.apply(X,Q)),M}}Z.tokenizer=X}if(W.hooks){let X=this.defaults.hooks||new f4;for(let Y in W.hooks){if(!(Y in X))throw Error(`hook '${Y}' does not exist`);if(["options","block"].includes(Y))continue;let G=Y,J=W.hooks[G],T=X[G];f4.passThroughHooks.has(Y)?X[G]=(Q)=>{if(this.defaults.async&&f4.passThroughHooksRespectAsync.has(Y))return(async()=>{let z=await J.call(X,Q);return T.call(X,z)})();let M=J.call(X,Q);return T.call(X,M)}:X[G]=(...Q)=>{if(this.defaults.async)return(async()=>{let z=await J.apply(X,Q);return z===!1&&(z=await T.apply(X,Q)),z})();let M=J.apply(X,Q);return M===!1&&(M=T.apply(X,Q)),M}}Z.hooks=X}if(W.walkTokens){let X=this.defaults.walkTokens,Y=W.walkTokens;Z.walkTokens=function(G){let J=[];return J.push(Y.call(this,G)),X&&(J=J.concat(X.call(this,G))),J}}this.defaults={...this.defaults,...Z}}),this}setOptions($){return this.defaults={...this.defaults,...$},this}lexer($,w){return s0.lex($,w??this.defaults)}parser($,w){return a0.parse($,w??this.defaults)}parseMarkdown($){return(w,W)=>{let Z={...W},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 G=X.hooks?await X.hooks.preprocess(w):w,J=await(X.hooks?await X.hooks.provideLexer($):$?s0.lex:s0.lexInline)(G,X),T=X.hooks?await X.hooks.processAllTokens(J):J;X.walkTokens&&await Promise.all(this.walkTokens(T,X.walkTokens));let Q=await(X.hooks?await X.hooks.provideParser($):$?a0.parse:a0.parseInline)(T,X);return X.hooks?await X.hooks.postprocess(Q):Q})().catch(Y);try{X.hooks&&(w=X.hooks.preprocess(w));let G=(X.hooks?X.hooks.provideLexer($):$?s0.lex:s0.lexInline)(w,X);X.hooks&&(G=X.hooks.processAllTokens(G)),X.walkTokens&&this.walkTokens(G,X.walkTokens);let J=(X.hooks?X.hooks.provideParser($):$?a0.parse:a0.parseInline)(G,X);return X.hooks&&(J=X.hooks.postprocess(J)),J}catch(G){return Y(G)}}}onError($,w){return(W)=>{if(W.message+=`
129
+ Please report this to https://github.com/markedjs/marked.`,$){let Z="<p>An error occurred:</p><pre>"+Y$(W.message+"",!0)+"</pre>";return w?Promise.resolve(Z):Z}if(w)return Promise.reject(W);throw W}}},B1=new aF;function t($,w){return B1.parse($,w)}t.options=t.setOptions=function($){return B1.setOptions($),t.defaults=B1.defaults,zT(t.defaults),t};t.getDefaults=p5;t.defaults=P1;function oF(...$){return B1.use(...$),t.defaults=B1.defaults,zT(t.defaults),t}t.use=oF;t.walkTokens=function($,w){return B1.walkTokens($,w)};t.parseInline=B1.parseInline;t.Parser=a0;t.parser=a0.parse;t.Renderer=G6;t.TextRenderer=$Z;t.Lexer=s0;t.lexer=s0.lex;t.Tokenizer=Y6;t.Hooks=f4;t.parse=t;var{options:fR,setOptions:qR,walkTokens:UR,parseInline:HR}=t;var FR=a0.parse,OR=s0.lex;var o0=m1(W6(),1);var O4=m1(W6(),1);import{stripVTControlCharacters as $O}from"node:util";import{stripVTControlCharacters as eF}from"node:util";function X0($){return Array.from(eF($)).filter((w)=>{let W=w.codePointAt(0)??0;return W===9||W===10||W>159||W>31&&W<127}).join("")}function H4($){let w=$.codePointAt(0)??0;if(w>=9472&&w<=9599)return 1;return w<=255?1:2}function F4($){return Array.from($).reduce((w,W)=>w+H4(W),0)}function Yw($,w,W="head"){if(w<=0)return"";if(F4($)<=w)return $;if(w===1)return"…";let Z=Array.from($),X=[],Y=1,G=W==="head"?Z.map((J,T)=>T):Z.map((J,T)=>Z.length-T-1);for(let J of G){let T=Z[J];if(T===void 0||Y+H4(T)>w)break;if(W==="head")X.push(T);else X.unshift(T);Y+=H4(T)}return W==="head"?`${X.join("")}…`:`…${X.join("")}`}var ZZ="\x1B",OT=`${ZZ}[0m`,wO=new RegExp(`^${ZZ}\\[[0-?]*[ -/]*[@-~]`);function ET($){return F4($O($))}function LT($){let w=[],W=0,Z="";while(W<$.length){let X=$.slice(W).match(wO)?.[0];if(X){if(X.endsWith("m"))Z=X===`${ZZ}[m`||X===OT?"":`${Z}${X}`;W+=X.length;continue}let Y=$.codePointAt(W);if(Y===void 0)break;let G=String.fromCodePoint(Y);w.push({value:G,width:H4(G),state:Z}),W+=G.length}return w}function wZ($){return $.map((w)=>w.state?`${w.state}${w.value}${OT}`:w.value).join("")}function WO($,w){if($.length===0)return[""];let W=[],Z=$;while(Z.length>0){if(W.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,G=-1;while(Y<Z.length){let J=Z[Y];if(!J||Y>0&&X+J.width>w)break;if(X+=J.width,/\s/u.test(J.value))G=Y;if(Y+=1,X>=w)break}if(Y>=Z.length){W.push(wZ(Z));break}if(G>=0){W.push(wZ(Z.slice(0,G))),Z=Z.slice(G+1);while(Z[0]&&/\s/u.test(Z[0].value))Z=Z.slice(1);continue}W.push(wZ(Z.slice(0,Math.max(1,Y)))),Z=Z.slice(Math.max(1,Y))}return W.length>0?W:[""]}function ZO($,w){let W=Math.max(1,w);return $.split(`
130
+ `).flatMap((Z)=>WO(LT(Z),W))}function XO($){return $.some((w)=>LT(w).some((W)=>W.width>1))?2:1}function YO($){return Math.max(1,...$.flatMap((w)=>w.split(`
131
+ `).map(ET)))}function GO($,w){let W=$.header.length,Z=$.header.map((J,T)=>[J,...$.rows.map((Q)=>Q[T]??"")]),X=Z.map(XO),Y=Z.map(YO),G=Math.max(X.reduce((J,T)=>J+T,0),w-(3*W+1));while(Y.reduce((J,T)=>J+T,0)>G){let J=-1;for(let T=0;T<Y.length;T+=1){let Q=Y[T]??0,M=X[T]??1;if(Q>M&&(J<0||Q>(Y[J]??0)))J=T}if(J<0)break;Y[J]=(Y[J]??1)-1}return Y}function JO($,w,W){let Z=Math.max(0,w-ET($)),X=W==="right"?Z:W==="center"?Math.floor(Z/2):0;return`${" ".repeat(X)}${$}${" ".repeat(Z-X)}`}function WZ($,w,W,Z){return O4.default.dim(`${$}${Z.map((X)=>"─".repeat(X+2)).join(w)}${W}`)}function FT($,w,W){let Z=W.map((Y,G)=>ZO($[G]??"",Y)),X=Math.max(1,...Z.map((Y)=>Y.length));return Array.from({length:X},(Y,G)=>{let J=W.map((T,Q)=>JO(Z[Q]?.[G]??"",T,w[Q]??"left"));return`${O4.default.dim("│")} ${J.join(` ${O4.default.dim("│")} `)} ${O4.default.dim("│")}`})}function DT($,w){if($.header.length===0)return"";let W=GO($,Math.max(1,w)),Z=W.map((Y,G)=>$.align[G]??"left");return[WZ("┌","┬","┐",W),...FT($.header,Z,W),WZ("├","┼","┤",W),...$.rows.flatMap((Y)=>FT(Y,Z,W)),WZ("└","┴","┘",W)].join(`
132
+ `)}class E4{write;columns;pending="";fence;table;constructor($,w=()=>80){this.write=$;this.columns=w}push($){this.pending+=X0($);let w=this.pending.indexOf(`
133
133
  `);while(w>=0){let W=this.pending.slice(0,w+1);this.pending=this.pending.slice(w+1),this.consumeLine(W),w=this.pending.indexOf(`
134
134
  `)}}preview(){if(this.pending)return this.pending;let $=this.table?.lines.at(-1);if($!==void 0)return $.endsWith(`
135
135
  `)?$.slice(0,-1):$;let w=this.fence?.lines.at(-1);if(w===void 0)return;return w.endsWith(`
@@ -138,53 +138,53 @@ Please report this to https://github.com/markedjs/marked.`,$){let Z="<p>An error
138
138
  `)?$.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
139
  `)&&!w.endsWith(`
140
140
  `))w+=`
141
- `;this.write(w)}catch{this.write(X0($))}}renderTokens($){return($??[]).map((w)=>this.renderToken(w)).join("")}renderToken($){let w=()=>this.renderTokens("tokens"in $?$.tokens:void 0),W=()=>X0("text"in $?$.text:"");switch($.type){case"heading":return a0.default.bold(w()||W());case"strong":return a0.default.bold(w()||W());case"em":return a0.default.italic(w()||W());case"codespan":return a0.default.cyan(W());case"link":{let Z=w()||W(),X=X0($.href??"");return`${a0.default.underline(Z)}${X?a0.default.dim(` (${X})`):""}`}case"list":{let Z=$,X=typeof Z.start==="number"?Z.start:1;return Z.items.map((Y,G)=>{let J=this.renderTokens(Y.tokens)||X0(Y.text??""),T=Z.ordered?`${X+G}. `:"• ";return J.trimEnd().split(`
141
+ `;this.write(w)}catch{this.write(X0($))}}renderTokens($){return($??[]).map((w)=>this.renderToken(w)).join("")}renderToken($){let w=()=>this.renderTokens("tokens"in $?$.tokens:void 0),W=()=>X0("text"in $?$.text:"");switch($.type){case"heading":return o0.default.bold(w()||W());case"strong":return o0.default.bold(w()||W());case"em":return o0.default.italic(w()||W());case"codespan":return o0.default.cyan(W());case"link":{let Z=w()||W(),X=X0($.href??"");return`${o0.default.underline(Z)}${X?o0.default.dim(` (${X})`):""}`}case"list":{let Z=$,X=typeof Z.start==="number"?Z.start:1;return Z.items.map((Y,G)=>{let J=this.renderTokens(Y.tokens)||X0(Y.text??""),T=Z.ordered?`${X+G}. `:"• ";return J.trimEnd().split(`
142
142
  `).map((M,z)=>`${z===0?T:" "}${M}`).join(`
143
143
  `)}).join(`
144
144
  `)}case"list_item":return w()||W();case"blockquote":return(w()||W()).trimEnd().split(`
145
- `).map((X)=>`${a0.default.dim("│ ")}${X}`).join(`
146
- `);case"code":{let Z=X0(($.lang??"").trim()),X=a0.default.cyan(W());return Z?`${a0.default.dim(Z)}
147
- ${X}`:X}case"table":{let Z=$;return LT({header:Z.header.map((X)=>a0.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()||W();case"space":case"br":return`
148
- `;default:{let Z=w();if(Z)return Z;let X=W();if(X)return X;return X0($.raw??"")}}}}var DT=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];class YZ{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 ZZ((W)=>this.stdout.write(W),()=>{let W=this.stdout.columns,Z=this.stderr.columns;return W??Z??80}),$.on((W)=>this.render(W))}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),W=String($.data?.name??"tool");if(Number.isInteger(w))this.startToolCallPreview(w,W)}if($.type==="provider.tool_call_delta"&&this.tty){let w=Number($.data?.index),W=String($.data?.argumentsDelta??"");if(Number.isInteger(w)&&W)this.appendToolCallPreview(w,W)}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=X0(String($.data?.name??"tool"));if(this.tty){let W=X0(String($.data?.summary??""));this.toolStatus(`◇ ${w}${W?` ${W}`:""}`)}else this.status(`tool ${w} started`)}if($.type==="tool.completed"){let w=X0(String($.data?.name??"tool")),W=String($.data?.durationMs??"?");if(this.tty){let Z=Boolean($.data?.isError);this.toolStatus(`${Z?"✗":"✓"} ${w} ${W}ms`,Z)}else this.status(`tool ${w} ${$.data?.isError?"failed":"completed"} (${W}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(G$.default.red(`failed: ${String($.data?.message)}`));if($.type==="plugin.loaded"&&this.options.verbose)this.status(`plugin loaded: ${J6($)}`);if($.type==="plugin.failed")this.status(G$.default.red(`plugin failed: ${J6($)}${XZ($)}`));if($.type==="plugin.unavailable")this.status(G$.default.yellow(`plugin unavailable: ${J6($)}${XZ($)}`));if($.type==="plugin.restart_required")this.status(G$.default.yellow(`plugin restart required: ${J6($)}${XZ($)}`))}status($){this.stderr.write(this.tty?`${G$.default.dim($)}
145
+ `).map((X)=>`${o0.default.dim("│ ")}${X}`).join(`
146
+ `);case"code":{let Z=X0(($.lang??"").trim()),X=o0.default.cyan(W());return Z?`${o0.default.dim(Z)}
147
+ ${X}`:X}case"table":{let Z=$;return DT({header:Z.header.map((X)=>o0.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()||W();case"space":case"br":return`
148
+ `;default:{let Z=w();if(Z)return Z;let X=W();if(X)return X;return X0($.raw??"")}}}}var kT=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];class YZ{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 E4((W)=>this.stdout.write(W),()=>{let W=this.stdout.columns,Z=this.stderr.columns;return W??Z??80}),$.on((W)=>this.render(W))}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),W=String($.data?.name??"tool");if(Number.isInteger(w))this.startToolCallPreview(w,W)}if($.type==="provider.tool_call_delta"&&this.tty){let w=Number($.data?.index),W=String($.data?.argumentsDelta??"");if(Number.isInteger(w)&&W)this.appendToolCallPreview(w,W)}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=X0(String($.data?.name??"tool"));if(this.tty){let W=X0(String($.data?.summary??""));this.toolStatus(`◇ ${w}${W?` ${W}`:""}`)}else this.status(`tool ${w} started`)}if($.type==="tool.completed"){let w=X0(String($.data?.name??"tool")),W=String($.data?.durationMs??"?");if(this.tty){let Z=Boolean($.data?.isError);this.toolStatus(`${Z?"✗":"✓"} ${w} ${W}ms`,Z)}else this.status(`tool ${w} ${$.data?.isError?"failed":"completed"} (${W}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(G$.default.red(`failed: ${String($.data?.message)}`));if($.type==="plugin.loaded"&&this.options.verbose)this.status(`plugin loaded: ${T6($)}`);if($.type==="plugin.failed")this.status(G$.default.red(`plugin failed: ${T6($)}${XZ($)}`));if($.type==="plugin.unavailable")this.status(G$.default.yellow(`plugin unavailable: ${T6($)}${XZ($)}`));if($.type==="plugin.restart_required")this.status(G$.default.yellow(`plugin restart required: ${T6($)}${XZ($)}`))}status($){this.stderr.write(this.tty?`${G$.default.dim($)}
150
150
  `:`[coden] ${$}
151
151
  `)}toolStatus($,w=!1){let W=this.stderr.columns??80,Z=Yw(X0($),W);this.stderr.write(`${w?G$.default.red(Z):G$.default.dim(Z)}
152
152
  `)}startProviderAttempt(){this.endProviderAttempt(),this.providerStartedAt=Date.now(),this.startSpinner()}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 W=((Date.now()-$)/1000).toFixed(1);this.stderr.write(`${G$.default.dim(`thought for ${W}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 W=this.toolCallPreviews.get($);if(!W)return;W.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),W=DT[this.frame++%DT.length]??"",Z=this.currentActivityText(w);Gw.clearLine(this.stderr,0),Gw.cursorTo(this.stderr,0),this.stderr.write(G$.default.dim(`${W} ${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,$-F9(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 W=this.normalizedReasoning();return W?this.truncateTail(W,$):"thinking"}truncateTail($,w){return Yw($,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;Gw.clearLine(this.stderr,0),Gw.cursorTo(this.stderr,0)}stopSpinner(){if(!this.spinner)return;clearInterval(this.spinner),this.spinner=void 0,this.clearActivityLine()}dispose(){this.endProviderAttempt()}}function J6($){let w=$.data??{},W=V1(w.scope),Z=V1(w.packageName),X=V1(w.version??w.diskVersion),Y=V1(w.name),G=V1(w.path),J=V1(w.source);if(Z)return`${W?`${W} `:""}${Z}${X?`@${X}`:""}`;if(Y)return Y;if(G)return`${W?`${W} `:""}${G}`;if(J)return J;return"plugin"}function XZ($){let w=V1($.data?.message??$.data?.reason);return w?` — ${w}`:""}function V1($){return typeof $==="string"&&$.length>0?$:void 0}import{appendFile as TO,chmod as kT,mkdir as QO}from"node:fs/promises";import MO from"node:path";class GZ{file;shouldPersist;#$=Promise.resolve();#w=[];constructor($,w,W=()=>!0){this.file=$;this.shouldPersist=W;w.on((Z)=>this.write(Z))}write($){if(!this.shouldPersist())return this.#w.push($),Promise.resolve();let w=[...this.#w.splice(0),$],W=this.#$.then(async()=>{let Z=MO.dirname(this.file);await QO(Z,{recursive:!0,mode:448}),await kT(Z,448),await TO(this.file,`${w.map((X)=>JSON.stringify(X)).join(`
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 W=this.toolCallPreviews.get($);if(!W)return;W.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),W=kT[this.frame++%kT.length]??"",Z=this.currentActivityText(w);Gw.clearLine(this.stderr,0),Gw.cursorTo(this.stderr,0),this.stderr.write(G$.default.dim(`${W} ${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,$-F4(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 W=this.normalizedReasoning();return W?this.truncateTail(W,$):"thinking"}truncateTail($,w){return Yw($,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;Gw.clearLine(this.stderr,0),Gw.cursorTo(this.stderr,0)}stopSpinner(){if(!this.spinner)return;clearInterval(this.spinner),this.spinner=void 0,this.clearActivityLine()}dispose(){this.endProviderAttempt()}}function T6($){let w=$.data??{},W=V1(w.scope),Z=V1(w.packageName),X=V1(w.version??w.diskVersion),Y=V1(w.name),G=V1(w.path),J=V1(w.source);if(Z)return`${W?`${W} `:""}${Z}${X?`@${X}`:""}`;if(Y)return Y;if(G)return`${W?`${W} `:""}${G}`;if(J)return J;return"plugin"}function XZ($){let w=V1($.data?.message??$.data?.reason);return w?` — ${w}`:""}function V1($){return typeof $==="string"&&$.length>0?$:void 0}import{appendFile as TO,chmod as AT,mkdir as QO}from"node:fs/promises";import MO from"node:path";class GZ{file;shouldPersist;#$=Promise.resolve();#w=[];constructor($,w,W=()=>!0){this.file=$;this.shouldPersist=W;w.on((Z)=>this.write(Z))}write($){if(!this.shouldPersist())return this.#w.push($),Promise.resolve();let w=[...this.#w.splice(0),$],W=this.#$.then(async()=>{let Z=MO.dirname(this.file);await QO(Z,{recursive:!0,mode:448}),await AT(Z,448),await TO(this.file,`${w.map((X)=>JSON.stringify(X)).join(`
154
154
  `)}
155
- `,{encoding:"utf8",mode:384}),await kT(this.file,384)});return this.#$=W.catch(()=>{}),W}async flush(){await this.#$}}var zO=[/\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 NO($){return zO.some((w)=>w.test($))?"dangerous":"modify"}class JZ{auto;prompt;#$=new Set;constructor($,w){this.auto=$;this.prompt=w}async authorize($,w,W){let Z=$.risk;if($.name==="bash"&&typeof w.input?.command==="string"){if(NO(w.input.command)==="dangerous")Z="dangerous"}if(this.auto||Z==="read"||Z==="modify"&&this.#$.has($.name))return{allowed:!0,risk:Z};if(!this.prompt)return{allowed:!1,risk:Z};let X=await this.prompt($,w,Z,W);if(X==="allow_session"&&Z!=="dangerous")this.#$.add($.name);return{allowed:X!=="deny",risk:Z}}}function I($,w,W,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($,W):X?X.value=W:w.set($,W),W}function F($,w,W,Z){if(W==="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 W==="m"?Z:W==="a"?Z.call($):Z?Z.value:w.get($)}var TZ=function(){let{crypto:$}=globalThis;if($?.randomUUID)return TZ=$.randomUUID.bind($),$.randomUUID();let w=new Uint8Array(1),W=$?()=>$.getRandomValues(w)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(Z)=>(+Z^W()&15>>+Z/4).toString(16))};function U$($){return typeof $==="object"&&$!==null&&(("name"in $)&&$.name==="AbortError"||("message"in $)&&String($.message).includes("FetchRequestCanceledException"))}var E9=($)=>{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 G0 extends b{constructor($,w,W,Z){super(`${G0.makeMessage($,w,W)}`);this.status=$,this.headers=Z,this.requestID=Z?.get("request-id"),this.error=w}static makeMessage($,w,W){let Z=w?.message?typeof w.message==="string"?w.message:JSON.stringify(w.message):w?JSON.stringify(w):W;if($&&Z)return`${$} ${Z}`;if($)return`${$} status code (no body)`;if(Z)return Z;return"(no status code or body)"}static generate($,w,W,Z){if(!$||!Z)return new f1({message:W,cause:E9(w)});let X=w;if($===400)return new D9($,X,W,Z);if($===401)return new k9($,X,W,Z);if($===403)return new A9($,X,W,Z);if($===404)return new S9($,X,W,Z);if($===409)return new R9($,X,W,Z);if($===422)return new C9($,X,W,Z);if($===429)return new j9($,X,W,Z);if($>=500)return new y9($,X,W,Z);return new G0($,X,W,Z)}}class q0 extends G0{constructor({message:$}={}){super(void 0,void 0,$||"Request was aborted.",void 0)}}class f1 extends G0{constructor({message:$,cause:w}){super(void 0,void 0,$||"Connection error.",void 0);if(w)this.cause=w}}class L9 extends f1{constructor({message:$}={}){super({message:$??"Request timed out."})}}class D9 extends G0{}class k9 extends G0{}class A9 extends G0{}class S9 extends G0{}class R9 extends G0{}class C9 extends G0{}class j9 extends G0{}class y9 extends G0{}var BO=/^[a-z][a-z0-9+.-]*:/i,AT=($)=>{return BO.test($)},QZ=($)=>(QZ=Array.isArray,QZ($)),MZ=QZ;function zZ($){if(typeof $!=="object")return{};return $??{}}function ST($){if(!$)return!0;for(let w in $)return!1;return!0}function RT($,w){return Object.prototype.hasOwnProperty.call($,w)}var CT=($,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 T6=($)=>{try{return JSON.parse($)}catch(w){return}};var jT=($)=>new Promise((w)=>setTimeout(w,$));var l$="0.61.0";var xT=()=>{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 VO=()=>{let $=PO();if($==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":l$,"X-Stainless-OS":IT(Deno.build.os),"X-Stainless-Arch":yT(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":l$,"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":l$,"X-Stainless-OS":IT(globalThis.process.platform??"unknown"),"X-Stainless-Arch":yT(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let w=fO();if(w)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":l$,"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":l$,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function fO(){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:W}of $){let Z=W.exec(navigator.userAgent);if(Z){let X=Z[1]||0,Y=Z[2]||0,G=Z[3]||0;return{browser:w,version:`${X}.${Y}.${G}`}}}return null}var yT=($)=>{if($==="x32")return"x32";if($==="x86_64"||$==="x64")return"x64";if($==="arm")return"arm";if($==="aarch64"||$==="arm64")return"arm64";if($)return`other:${$}`;return"unknown"},IT=($)=>{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"},bT,_T=()=>{return bT??(bT=VO())};function gT(){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 NZ(...$){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 Q6($){let w=Symbol.asyncIterator in $?$[Symbol.asyncIterator]():$[Symbol.iterator]();return NZ({start(){},async pull(W){let{done:Z,value:X}=await w.next();if(Z)W.close();else W.enqueue(X)},async cancel(){await w.return?.()}})}function I9($){if($[Symbol.asyncIterator])return $;let w=$.getReader();return{async next(){try{let W=await w.read();if(W?.done)w.releaseLock();return W}catch(W){throw w.releaseLock(),W}},async return(){let W=w.cancel();return w.releaseLock(),await W,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function vT($){if($===null||typeof $!=="object")return;if($[Symbol.asyncIterator]){await $[Symbol.asyncIterator]().return?.();return}let w=$.getReader(),W=w.cancel();w.releaseLock(),await W}var hT=({headers:$,body:w})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(w)}};function mT($){let w=0;for(let X of $)w+=X.length;let W=new Uint8Array(w),Z=0;for(let X of $)W.set(X,Z),Z+=X.length;return W}var uT;function b9($){let w;return(uT??(w=new globalThis.TextEncoder,uT=w.encode.bind(w)))($)}var iT;function KZ($){let w;return(iT??(w=new globalThis.TextDecoder,iT=w.decode.bind(w)))($)}var y0,I0;class c${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"?b9($):$;I(this,y0,mT([F(this,y0,"f"),w]),"f");let W=[],Z;while((Z=HO(F(this,y0,"f"),F(this,I0,"f")))!=null){if(Z.carriage&&F(this,I0,"f")==null){I(this,I0,Z.index,"f");continue}if(F(this,I0,"f")!=null&&(Z.index!==F(this,I0,"f")+1||Z.carriage)){W.push(KZ(F(this,y0,"f").subarray(0,F(this,I0,"f")-1))),I(this,y0,F(this,y0,"f").subarray(F(this,I0,"f")),"f"),I(this,I0,null,"f");continue}let X=F(this,I0,"f")!==null?Z.preceding-1:Z.preceding,Y=KZ(F(this,y0,"f").subarray(0,X));W.push(Y),I(this,y0,F(this,y0,"f").subarray(Z.index),"f"),I(this,I0,null,"f")}return W}flush(){if(!F(this,y0,"f").length)return[];return this.decode(`
155
+ `,{encoding:"utf8",mode:384}),await AT(this.file,384)});return this.#$=W.catch(()=>{}),W}async flush(){await this.#$}}var zO=[/\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 NO($){return zO.some((w)=>w.test($))?"dangerous":"modify"}class JZ{auto;prompt;#$=new Set;constructor($,w){this.auto=$;this.prompt=w}async authorize($,w,W){let Z=$.risk;if($.name==="bash"&&typeof w.input?.command==="string"){if(NO(w.input.command)==="dangerous")Z="dangerous"}if(this.auto||Z==="read"||Z==="modify"&&this.#$.has($.name))return{allowed:!0,risk:Z};if(!this.prompt)return{allowed:!1,risk:Z};let X=await this.prompt($,w,Z,W);if(X==="allow_session"&&Z!=="dangerous")this.#$.add($.name);return{allowed:X!=="deny",risk:Z}}}function I($,w,W,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($,W):X?X.value=W:w.set($,W),W}function F($,w,W,Z){if(W==="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 W==="m"?Z:W==="a"?Z.call($):Z?Z.value:w.get($)}var TZ=function(){let{crypto:$}=globalThis;if($?.randomUUID)return TZ=$.randomUUID.bind($),$.randomUUID();let w=new Uint8Array(1),W=$?()=>$.getRandomValues(w)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(Z)=>(+Z^W()&15>>+Z/4).toString(16))};function U$($){return typeof $==="object"&&$!==null&&(("name"in $)&&$.name==="AbortError"||("message"in $)&&String($.message).includes("FetchRequestCanceledException"))}var L4=($)=>{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 G0 extends b{constructor($,w,W,Z){super(`${G0.makeMessage($,w,W)}`);this.status=$,this.headers=Z,this.requestID=Z?.get("request-id"),this.error=w}static makeMessage($,w,W){let Z=w?.message?typeof w.message==="string"?w.message:JSON.stringify(w.message):w?JSON.stringify(w):W;if($&&Z)return`${$} ${Z}`;if($)return`${$} status code (no body)`;if(Z)return Z;return"(no status code or body)"}static generate($,w,W,Z){if(!$||!Z)return new f1({message:W,cause:L4(w)});let X=w;if($===400)return new k4($,X,W,Z);if($===401)return new A4($,X,W,Z);if($===403)return new S4($,X,W,Z);if($===404)return new R4($,X,W,Z);if($===409)return new C4($,X,W,Z);if($===422)return new j4($,X,W,Z);if($===429)return new y4($,X,W,Z);if($>=500)return new I4($,X,W,Z);return new G0($,X,W,Z)}}class q0 extends G0{constructor({message:$}={}){super(void 0,void 0,$||"Request was aborted.",void 0)}}class f1 extends G0{constructor({message:$,cause:w}){super(void 0,void 0,$||"Connection error.",void 0);if(w)this.cause=w}}class D4 extends f1{constructor({message:$}={}){super({message:$??"Request timed out."})}}class k4 extends G0{}class A4 extends G0{}class S4 extends G0{}class R4 extends G0{}class C4 extends G0{}class j4 extends G0{}class y4 extends G0{}class I4 extends G0{}var BO=/^[a-z][a-z0-9+.-]*:/i,ST=($)=>{return BO.test($)},QZ=($)=>(QZ=Array.isArray,QZ($)),MZ=QZ;function zZ($){if(typeof $!=="object")return{};return $??{}}function RT($){if(!$)return!0;for(let w in $)return!1;return!0}function CT($,w){return Object.prototype.hasOwnProperty.call($,w)}var jT=($,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 Q6=($)=>{try{return JSON.parse($)}catch(w){return}};var yT=($)=>new Promise((w)=>setTimeout(w,$));var l$="0.61.0";var _T=()=>{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 VO=()=>{let $=PO();if($==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":l$,"X-Stainless-OS":bT(Deno.build.os),"X-Stainless-Arch":IT(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":l$,"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":l$,"X-Stainless-OS":bT(globalThis.process.platform??"unknown"),"X-Stainless-Arch":IT(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let w=fO();if(w)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":l$,"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":l$,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function fO(){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:W}of $){let Z=W.exec(navigator.userAgent);if(Z){let X=Z[1]||0,Y=Z[2]||0,G=Z[3]||0;return{browser:w,version:`${X}.${Y}.${G}`}}}return null}var IT=($)=>{if($==="x32")return"x32";if($==="x86_64"||$==="x64")return"x64";if($==="arm")return"arm";if($==="aarch64"||$==="arm64")return"arm64";if($)return`other:${$}`;return"unknown"},bT=($)=>{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"},xT,gT=()=>{return xT??(xT=VO())};function vT(){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 NZ(...$){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 M6($){let w=Symbol.asyncIterator in $?$[Symbol.asyncIterator]():$[Symbol.iterator]();return NZ({start(){},async pull(W){let{done:Z,value:X}=await w.next();if(Z)W.close();else W.enqueue(X)},async cancel(){await w.return?.()}})}function b4($){if($[Symbol.asyncIterator])return $;let w=$.getReader();return{async next(){try{let W=await w.read();if(W?.done)w.releaseLock();return W}catch(W){throw w.releaseLock(),W}},async return(){let W=w.cancel();return w.releaseLock(),await W,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function uT($){if($===null||typeof $!=="object")return;if($[Symbol.asyncIterator]){await $[Symbol.asyncIterator]().return?.();return}let w=$.getReader(),W=w.cancel();w.releaseLock(),await W}var hT=({headers:$,body:w})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(w)}};function lT($){let w=0;for(let X of $)w+=X.length;let W=new Uint8Array(w),Z=0;for(let X of $)W.set(X,Z),Z+=X.length;return W}var iT;function x4($){let w;return(iT??(w=new globalThis.TextEncoder,iT=w.encode.bind(w)))($)}var mT;function KZ($){let w;return(mT??(w=new globalThis.TextDecoder,mT=w.decode.bind(w)))($)}var y0,I0;class c${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"?x4($):$;I(this,y0,lT([F(this,y0,"f"),w]),"f");let W=[],Z;while((Z=HO(F(this,y0,"f"),F(this,I0,"f")))!=null){if(Z.carriage&&F(this,I0,"f")==null){I(this,I0,Z.index,"f");continue}if(F(this,I0,"f")!=null&&(Z.index!==F(this,I0,"f")+1||Z.carriage)){W.push(KZ(F(this,y0,"f").subarray(0,F(this,I0,"f")-1))),I(this,y0,F(this,y0,"f").subarray(F(this,I0,"f")),"f"),I(this,I0,null,"f");continue}let X=F(this,I0,"f")!==null?Z.preceding-1:Z.preceding,Y=KZ(F(this,y0,"f").subarray(0,X));W.push(Y),I(this,y0,F(this,y0,"f").subarray(Z.index),"f"),I(this,I0,null,"f")}return W}flush(){if(!F(this,y0,"f").length)return[];return this.decode(`
156
156
  `)}}y0=new WeakMap,I0=new WeakMap;c$.NEWLINE_CHARS=new Set([`
157
- `,"\r"]);c$.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function HO($,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 lT($){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 z6={off:0,error:200,warn:300,info:400,debug:500},BZ=($,w,W)=>{if(!$)return;if(RT(z6,$))return $;z0(W).warn(`${w} was set to ${JSON.stringify($)}, expected one of ${JSON.stringify(Object.keys(z6))}`);return};function x9(){}function M6($,w,W){if(!w||z6[$]>z6[W])return x9;else return w[$].bind(w)}var FO={error:x9,warn:x9,info:x9,debug:x9},cT=new WeakMap;function z0($){let w=$.logger,W=$.logLevel??"off";if(!w)return FO;let Z=cT.get(w);if(Z&&Z[0]===W)return Z[1];let X={error:M6("error",w,W),warn:M6("warn",w,W),info:M6("info",w,W),debug:M6("debug",w,W)};return cT.set(w,[W,X]),X}var H$=($)=>{if($.options)$.options={...$.options},delete $.options.headers;if($.headers)$.headers=Object.fromEntries(($.headers instanceof Headers?[...$.headers]:Object.entries($.headers)).map(([w,W])=>[w,w.toLowerCase()==="x-api-key"||w.toLowerCase()==="authorization"||w.toLowerCase()==="cookie"||w.toLowerCase()==="set-cookie"?"***":W]));if("retryOfRequestLogID"in $){if($.retryOfRequestLogID)$.retryOf=$.retryOfRequestLogID;delete $.retryOfRequestLogID}return $};var _9;class b0{constructor($,w,W){this.iterator=$,_9.set(this,void 0),this.controller=w,I(this,_9,W,"f")}static fromSSEResponse($,w,W){let Z=!1,X=W?z0(W):console;async function*Y(){if(Z)throw new b("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");Z=!0;let G=!1;try{for await(let J of OO($,w)){if(J.event==="completion")try{yield JSON.parse(J.data)}catch(T){throw X.error("Could not parse message into JSON:",J.data),X.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 X.error("Could not parse message into JSON:",J.data),X.error("From chunk:",J.raw),T}if(J.event==="ping")continue;if(J.event==="error")throw new G0(void 0,T6(J.data)??J.data,void 0,$.headers)}G=!0}catch(J){if(U$(J))return;throw J}finally{if(!G)w.abort()}}return new b0(Y,w,W)}static fromReadableStream($,w,W){let Z=!1;async function*X(){let G=new c$,J=I9($);for await(let T of J)for(let Q of G.decode(T))yield Q;for(let T of G.flush())yield T}async function*Y(){if(Z)throw new b("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");Z=!0;let G=!1;try{for await(let J of X()){if(G)continue;if(J)yield JSON.parse(J)}G=!0}catch(J){if(U$(J))return;throw J}finally{if(!G)w.abort()}}return new b0(Y,w,W)}[(_9=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let $=[],w=[],W=this.iterator(),Z=(X)=>{return{next:()=>{if(X.length===0){let Y=W.next();$.push(Y),w.push(Y)}return X.shift()}}};return[new b0(()=>Z($),this.controller,F(this,_9,"f")),new b0(()=>Z(w),this.controller,F(this,_9,"f"))]}toReadableStream(){let $=this,w;return NZ({async start(){w=$[Symbol.asyncIterator]()},async pull(W){try{let{value:Z,done:X}=await w.next();if(X)return W.close();let Y=b9(JSON.stringify(Z)+`
158
- `);W.enqueue(Y)}catch(Z){W.error(Z)}},async cancel(){await w.return?.()}})}}async function*OO($,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 W=new dT,Z=new c$,X=I9($.body);for await(let Y of EO(X))for(let G of Z.decode(Y)){let J=W.decode(G);if(J)yield J}for(let Y of Z.flush()){let G=W.decode(Y);if(G)yield G}}async function*EO($){let w=new Uint8Array;for await(let W of $){if(W==null)continue;let Z=W instanceof ArrayBuffer?new Uint8Array(W):typeof W==="string"?b9(W):W,X=new Uint8Array(w.length+Z.length);X.set(w),X.set(Z,w.length),w=X;let Y;while((Y=lT(w))!==-1)yield w.slice(0,Y),w=w.slice(Y)}if(w.length>0)yield w}class dT{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(`
159
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],X}if(this.chunks.push($),$.startsWith(":"))return null;let[w,W,Z]=LO($,":");if(Z.startsWith(" "))Z=Z.substring(1);if(w==="event")this.event=Z;else if(w==="data")this.data.push(Z);return null}}function LO($,w){let W=$.indexOf(w);if(W!==-1)return[$.substring(0,W),w,$.substring(W+w.length)];return[$,"",""]}async function N6($,w){let{response:W,requestLogID:Z,retryOfRequestLogID:X,startTime:Y}=w,G=await(async()=>{if(w.options.stream){if(z0($).debug("response",W.status,W.url,W.headers,W.body),w.options.__streamClass)return w.options.__streamClass.fromSSEResponse(W,w.controller);return b0.fromSSEResponse(W,w.controller)}if(W.status===204)return null;if(w.options.__binaryResponse)return W;let T=W.headers.get("content-type")?.split(";")[0]?.trim();if(T?.includes("application/json")||T?.endsWith("+json")){let z=await W.json();return PZ(z,W)}return await W.text()})();return z0($).debug(`[${Z}] response parsed`,H$({retryOfRequestLogID:X,url:W.url,status:W.status,body:G,durationMs:Date.now()-Y})),G}function PZ($,w){if(!$||typeof $!=="object"||Array.isArray($))return $;return Object.defineProperty($,"_request_id",{value:w.headers.get("request-id"),enumerable:!1})}var g9;class q1 extends Promise{constructor($,w,W=N6){super((Z)=>{Z(null)});this.responsePromise=w,this.parseResponse=W,g9.set(this,void 0),I(this,g9,$,"f")}_thenUnwrap($){return new q1(F(this,g9,"f"),this.responsePromise,async(w,W)=>PZ($(await this.parseResponse(w,W),W),W.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(F(this,g9,"f"),$));return this.parsedPromise}then($,w){return this.parse().then($,w)}catch($){return this.parse().catch($)}finally($){return this.parse().finally($)}}g9=new WeakMap;var K6;class nT{constructor($,w,W,Z){K6.set(this,void 0),I(this,K6,$,"f"),this.options=Z,this.response=w,this.body=W}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 F(this,K6,"f").requestAPIList(this.constructor,$)}async*iterPages(){let $=this;yield $;while($.hasNextPage())$=await $.getNextPage(),yield $}async*[(K6=new WeakMap,Symbol.asyncIterator)](){for await(let $ of this.iterPages())for(let w of $.getPaginatedItems())yield w}}class B6 extends q1{constructor($,w,W){super($,w,async(Z,X)=>new W(Z,X.response,await N6(Z,X),X.options))}async*[Symbol.asyncIterator](){let $=await this;for await(let w of $)yield w}}class o0 extends nT{constructor($,w,W,Z){super($,w,W,Z);this.data=W.data||[],this.has_more=W.has_more||!1,this.first_id=W.first_id||null,this.last_id=W.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:{...zZ(this.options.query),before_id:w}}}let $=this.last_id;if(!$)return null;return{...this.options,query:{...zZ(this.options.query),after_id:$}}}}var fZ=()=>{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 U1($,w,W){return fZ(),new File($,w??"unknown_file",W)}function v9($){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 qZ=($)=>$!=null&&typeof $==="object"&&typeof $[Symbol.asyncIterator]==="function";var tT=async($,w)=>{return{...$,body:await AO($.body,w)}},pT=new WeakMap;function kO($){let w=typeof $==="function"?$:$.fetch,W=pT.get(w);if(W)return W;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 pT.set(w,Z),Z}var AO=async($,w)=>{if(!await kO(w))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let W=new FormData;return await Promise.all(Object.entries($||{}).map(([Z,X])=>VZ(W,Z,X))),W},SO=($)=>$ instanceof Blob&&("name"in $);var VZ=async($,w,W)=>{if(W===void 0)return;if(W==null)throw TypeError(`Received null for "${w}"; to pass null in FormData, you must use the string 'null'`);if(typeof W==="string"||typeof W==="number"||typeof W==="boolean")$.append(w,String(W));else if(W instanceof Response){let Z={},X=W.headers.get("Content-Type");if(X)Z={type:X};$.append(w,U1([await W.blob()],v9(W),Z))}else if(qZ(W))$.append(w,U1([await new Response(Q6(W)).blob()],v9(W)));else if(SO(W))$.append(w,U1([W],v9(W),{type:W.type}));else if(Array.isArray(W))await Promise.all(W.map((Z)=>VZ($,w+"[]",Z)));else if(typeof W==="object")await Promise.all(Object.entries(W).map(([Z,X])=>VZ($,`${w}[${Z}]`,X)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${W} instead`)};var rT=($)=>$!=null&&typeof $==="object"&&typeof $.size==="number"&&typeof $.type==="string"&&typeof $.text==="function"&&typeof $.slice==="function"&&typeof $.arrayBuffer==="function",RO=($)=>$!=null&&typeof $==="object"&&typeof $.name==="string"&&typeof $.lastModified==="number"&&rT($),CO=($)=>$!=null&&typeof $==="object"&&typeof $.url==="string"&&typeof $.blob==="function";async function P6($,w,W){if(fZ(),$=await $,w||(w=v9($)),RO($)){if($ instanceof File&&w==null&&W==null)return $;return U1([await $.arrayBuffer()],w??$.name,{type:$.type,lastModified:$.lastModified,...W})}if(CO($)){let X=await $.blob();return w||(w=new URL($.url).pathname.split(/[\\/]/).pop()),U1(await UZ(X),w,W)}let Z=await UZ($);if(!W?.type){let X=Z.find((Y)=>typeof Y==="object"&&("type"in Y)&&Y.type);if(typeof X==="string")W={...W,type:X}}return U1(Z,w,W)}async function UZ($){let w=[];if(typeof $==="string"||ArrayBuffer.isView($)||$ instanceof ArrayBuffer)w.push($);else if(rT($))w.push($ instanceof Blob?$:await $.arrayBuffer());else if(qZ($))for await(let W of $)w.push(...await UZ(W));else{let W=$?.constructor?.name;throw Error(`Unexpected data type: ${typeof $}${W?`; constructor: ${W}`:""}${jO($)}`)}return w}function jO($){if(typeof $!=="object"||$===null)return"";return`; props: [${Object.getOwnPropertyNames($).map((W)=>`"${W}"`).join(", ")}]`}class J0{constructor($){this._client=$}}var sT=Symbol.for("brand.privateNullableHeaders");function*IO($){if(!$)return;if(sT in $){let{values:Z,nulls:X}=$;yield*Z.entries();for(let Y of X)yield[Y,null];return}let w=!1,W;if($ instanceof Headers)W=$.entries();else if(MZ($))W=$;else w=!0,W=Object.entries($??{});for(let Z of W){let X=Z[0];if(typeof X!=="string")throw TypeError("expected header name to be a string");let Y=MZ(Z[1])?Z[1]:[Z[1]],G=!1;for(let J of Y){if(J===void 0)continue;if(w&&!G)G=!0,yield[X,null];yield[X,J]}}}var n=($)=>{let w=new Headers,W=new Set;for(let Z of $){let X=new Set;for(let[Y,G]of IO(Z)){let J=Y.toLowerCase();if(!X.has(J))w.delete(Y),X.add(J);if(G===null)w.delete(Y),W.add(J);else w.append(Y,G),W.delete(J)}}return{[sT]:!0,values:w,nulls:W}};function oT($){return $.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var aT=Object.freeze(Object.create(null)),bO=($=oT)=>function(W,...Z){if(W.length===1)return W[0];let X=!1,Y=[],G=W.reduce((M,z,N)=>{if(/[?#]/.test(z))X=!0;let B=Z[N],K=(X?encodeURIComponent:$)(""+B);if(N!==Z.length&&(B==null||typeof B==="object"&&B.toString===Object.getPrototypeOf(Object.getPrototypeOf(B.hasOwnProperty??aT)??aT)?.toString))K=B+"",Y.push({start:M.length+z.length,length:K.length,error:`Value of type ${Object.prototype.toString.call(B).slice(8,-1)} is not a valid path parameter`});return M+z+(N===Z.length?"":K)},""),J=G.split(/[?#]/,1)[0],T=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,Q;while((Q=T.exec(J))!==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((M,z)=>M.start-z.start),Y.length>0){let M=0,z=Y.reduce((N,B)=>{let K=" ".repeat(B.start-M),P="^".repeat(B.length);return M=B.start+B.length,N+K+P},"");throw new b(`Path parameters result in path with invalid segments:
157
+ `,"\r"]);c$.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function HO($,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 cT($){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 N6={off:0,error:200,warn:300,info:400,debug:500},BZ=($,w,W)=>{if(!$)return;if(CT(N6,$))return $;z0(W).warn(`${w} was set to ${JSON.stringify($)}, expected one of ${JSON.stringify(Object.keys(N6))}`);return};function _4(){}function z6($,w,W){if(!w||N6[$]>N6[W])return _4;else return w[$].bind(w)}var FO={error:_4,warn:_4,info:_4,debug:_4},dT=new WeakMap;function z0($){let w=$.logger,W=$.logLevel??"off";if(!w)return FO;let Z=dT.get(w);if(Z&&Z[0]===W)return Z[1];let X={error:z6("error",w,W),warn:z6("warn",w,W),info:z6("info",w,W),debug:z6("debug",w,W)};return dT.set(w,[W,X]),X}var H$=($)=>{if($.options)$.options={...$.options},delete $.options.headers;if($.headers)$.headers=Object.fromEntries(($.headers instanceof Headers?[...$.headers]:Object.entries($.headers)).map(([w,W])=>[w,w.toLowerCase()==="x-api-key"||w.toLowerCase()==="authorization"||w.toLowerCase()==="cookie"||w.toLowerCase()==="set-cookie"?"***":W]));if("retryOfRequestLogID"in $){if($.retryOfRequestLogID)$.retryOf=$.retryOfRequestLogID;delete $.retryOfRequestLogID}return $};var g4;class b0{constructor($,w,W){this.iterator=$,g4.set(this,void 0),this.controller=w,I(this,g4,W,"f")}static fromSSEResponse($,w,W){let Z=!1,X=W?z0(W):console;async function*Y(){if(Z)throw new b("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");Z=!0;let G=!1;try{for await(let J of OO($,w)){if(J.event==="completion")try{yield JSON.parse(J.data)}catch(T){throw X.error("Could not parse message into JSON:",J.data),X.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 X.error("Could not parse message into JSON:",J.data),X.error("From chunk:",J.raw),T}if(J.event==="ping")continue;if(J.event==="error")throw new G0(void 0,Q6(J.data)??J.data,void 0,$.headers)}G=!0}catch(J){if(U$(J))return;throw J}finally{if(!G)w.abort()}}return new b0(Y,w,W)}static fromReadableStream($,w,W){let Z=!1;async function*X(){let G=new c$,J=b4($);for await(let T of J)for(let Q of G.decode(T))yield Q;for(let T of G.flush())yield T}async function*Y(){if(Z)throw new b("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");Z=!0;let G=!1;try{for await(let J of X()){if(G)continue;if(J)yield JSON.parse(J)}G=!0}catch(J){if(U$(J))return;throw J}finally{if(!G)w.abort()}}return new b0(Y,w,W)}[(g4=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let $=[],w=[],W=this.iterator(),Z=(X)=>{return{next:()=>{if(X.length===0){let Y=W.next();$.push(Y),w.push(Y)}return X.shift()}}};return[new b0(()=>Z($),this.controller,F(this,g4,"f")),new b0(()=>Z(w),this.controller,F(this,g4,"f"))]}toReadableStream(){let $=this,w;return NZ({async start(){w=$[Symbol.asyncIterator]()},async pull(W){try{let{value:Z,done:X}=await w.next();if(X)return W.close();let Y=x4(JSON.stringify(Z)+`
158
+ `);W.enqueue(Y)}catch(Z){W.error(Z)}},async cancel(){await w.return?.()}})}}async function*OO($,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 W=new nT,Z=new c$,X=b4($.body);for await(let Y of EO(X))for(let G of Z.decode(Y)){let J=W.decode(G);if(J)yield J}for(let Y of Z.flush()){let G=W.decode(Y);if(G)yield G}}async function*EO($){let w=new Uint8Array;for await(let W of $){if(W==null)continue;let Z=W instanceof ArrayBuffer?new Uint8Array(W):typeof W==="string"?x4(W):W,X=new Uint8Array(w.length+Z.length);X.set(w),X.set(Z,w.length),w=X;let Y;while((Y=cT(w))!==-1)yield w.slice(0,Y),w=w.slice(Y)}if(w.length>0)yield w}class nT{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(`
159
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],X}if(this.chunks.push($),$.startsWith(":"))return null;let[w,W,Z]=LO($,":");if(Z.startsWith(" "))Z=Z.substring(1);if(w==="event")this.event=Z;else if(w==="data")this.data.push(Z);return null}}function LO($,w){let W=$.indexOf(w);if(W!==-1)return[$.substring(0,W),w,$.substring(W+w.length)];return[$,"",""]}async function K6($,w){let{response:W,requestLogID:Z,retryOfRequestLogID:X,startTime:Y}=w,G=await(async()=>{if(w.options.stream){if(z0($).debug("response",W.status,W.url,W.headers,W.body),w.options.__streamClass)return w.options.__streamClass.fromSSEResponse(W,w.controller);return b0.fromSSEResponse(W,w.controller)}if(W.status===204)return null;if(w.options.__binaryResponse)return W;let T=W.headers.get("content-type")?.split(";")[0]?.trim();if(T?.includes("application/json")||T?.endsWith("+json")){let z=await W.json();return PZ(z,W)}return await W.text()})();return z0($).debug(`[${Z}] response parsed`,H$({retryOfRequestLogID:X,url:W.url,status:W.status,body:G,durationMs:Date.now()-Y})),G}function PZ($,w){if(!$||typeof $!=="object"||Array.isArray($))return $;return Object.defineProperty($,"_request_id",{value:w.headers.get("request-id"),enumerable:!1})}var v4;class q1 extends Promise{constructor($,w,W=K6){super((Z)=>{Z(null)});this.responsePromise=w,this.parseResponse=W,v4.set(this,void 0),I(this,v4,$,"f")}_thenUnwrap($){return new q1(F(this,v4,"f"),this.responsePromise,async(w,W)=>PZ($(await this.parseResponse(w,W),W),W.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(F(this,v4,"f"),$));return this.parsedPromise}then($,w){return this.parse().then($,w)}catch($){return this.parse().catch($)}finally($){return this.parse().finally($)}}v4=new WeakMap;var B6;class pT{constructor($,w,W,Z){B6.set(this,void 0),I(this,B6,$,"f"),this.options=Z,this.response=w,this.body=W}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 F(this,B6,"f").requestAPIList(this.constructor,$)}async*iterPages(){let $=this;yield $;while($.hasNextPage())$=await $.getNextPage(),yield $}async*[(B6=new WeakMap,Symbol.asyncIterator)](){for await(let $ of this.iterPages())for(let w of $.getPaginatedItems())yield w}}class P6 extends q1{constructor($,w,W){super($,w,async(Z,X)=>new W(Z,X.response,await K6(Z,X),X.options))}async*[Symbol.asyncIterator](){let $=await this;for await(let w of $)yield w}}class e0 extends pT{constructor($,w,W,Z){super($,w,W,Z);this.data=W.data||[],this.has_more=W.has_more||!1,this.first_id=W.first_id||null,this.last_id=W.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:{...zZ(this.options.query),before_id:w}}}let $=this.last_id;if(!$)return null;return{...this.options,query:{...zZ(this.options.query),after_id:$}}}}var fZ=()=>{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 U1($,w,W){return fZ(),new File($,w??"unknown_file",W)}function u4($){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 qZ=($)=>$!=null&&typeof $==="object"&&typeof $[Symbol.asyncIterator]==="function";var rT=async($,w)=>{return{...$,body:await AO($.body,w)}},tT=new WeakMap;function kO($){let w=typeof $==="function"?$:$.fetch,W=tT.get(w);if(W)return W;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 tT.set(w,Z),Z}var AO=async($,w)=>{if(!await kO(w))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let W=new FormData;return await Promise.all(Object.entries($||{}).map(([Z,X])=>VZ(W,Z,X))),W},SO=($)=>$ instanceof Blob&&("name"in $);var VZ=async($,w,W)=>{if(W===void 0)return;if(W==null)throw TypeError(`Received null for "${w}"; to pass null in FormData, you must use the string 'null'`);if(typeof W==="string"||typeof W==="number"||typeof W==="boolean")$.append(w,String(W));else if(W instanceof Response){let Z={},X=W.headers.get("Content-Type");if(X)Z={type:X};$.append(w,U1([await W.blob()],u4(W),Z))}else if(qZ(W))$.append(w,U1([await new Response(M6(W)).blob()],u4(W)));else if(SO(W))$.append(w,U1([W],u4(W),{type:W.type}));else if(Array.isArray(W))await Promise.all(W.map((Z)=>VZ($,w+"[]",Z)));else if(typeof W==="object")await Promise.all(Object.entries(W).map(([Z,X])=>VZ($,`${w}[${Z}]`,X)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${W} instead`)};var sT=($)=>$!=null&&typeof $==="object"&&typeof $.size==="number"&&typeof $.type==="string"&&typeof $.text==="function"&&typeof $.slice==="function"&&typeof $.arrayBuffer==="function",RO=($)=>$!=null&&typeof $==="object"&&typeof $.name==="string"&&typeof $.lastModified==="number"&&sT($),CO=($)=>$!=null&&typeof $==="object"&&typeof $.url==="string"&&typeof $.blob==="function";async function V6($,w,W){if(fZ(),$=await $,w||(w=u4($)),RO($)){if($ instanceof File&&w==null&&W==null)return $;return U1([await $.arrayBuffer()],w??$.name,{type:$.type,lastModified:$.lastModified,...W})}if(CO($)){let X=await $.blob();return w||(w=new URL($.url).pathname.split(/[\\/]/).pop()),U1(await UZ(X),w,W)}let Z=await UZ($);if(!W?.type){let X=Z.find((Y)=>typeof Y==="object"&&("type"in Y)&&Y.type);if(typeof X==="string")W={...W,type:X}}return U1(Z,w,W)}async function UZ($){let w=[];if(typeof $==="string"||ArrayBuffer.isView($)||$ instanceof ArrayBuffer)w.push($);else if(sT($))w.push($ instanceof Blob?$:await $.arrayBuffer());else if(qZ($))for await(let W of $)w.push(...await UZ(W));else{let W=$?.constructor?.name;throw Error(`Unexpected data type: ${typeof $}${W?`; constructor: ${W}`:""}${jO($)}`)}return w}function jO($){if(typeof $!=="object"||$===null)return"";return`; props: [${Object.getOwnPropertyNames($).map((W)=>`"${W}"`).join(", ")}]`}class J0{constructor($){this._client=$}}var aT=Symbol.for("brand.privateNullableHeaders");function*IO($){if(!$)return;if(aT in $){let{values:Z,nulls:X}=$;yield*Z.entries();for(let Y of X)yield[Y,null];return}let w=!1,W;if($ instanceof Headers)W=$.entries();else if(MZ($))W=$;else w=!0,W=Object.entries($??{});for(let Z of W){let X=Z[0];if(typeof X!=="string")throw TypeError("expected header name to be a string");let Y=MZ(Z[1])?Z[1]:[Z[1]],G=!1;for(let J of Y){if(J===void 0)continue;if(w&&!G)G=!0,yield[X,null];yield[X,J]}}}var n=($)=>{let w=new Headers,W=new Set;for(let Z of $){let X=new Set;for(let[Y,G]of IO(Z)){let J=Y.toLowerCase();if(!X.has(J))w.delete(Y),X.add(J);if(G===null)w.delete(Y),W.add(J);else w.append(Y,G),W.delete(J)}}return{[aT]:!0,values:w,nulls:W}};function eT($){return $.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var oT=Object.freeze(Object.create(null)),bO=($=eT)=>function(W,...Z){if(W.length===1)return W[0];let X=!1,Y=[],G=W.reduce((M,z,N)=>{if(/[?#]/.test(z))X=!0;let B=Z[N],K=(X?encodeURIComponent:$)(""+B);if(N!==Z.length&&(B==null||typeof B==="object"&&B.toString===Object.getPrototypeOf(Object.getPrototypeOf(B.hasOwnProperty??oT)??oT)?.toString))K=B+"",Y.push({start:M.length+z.length,length:K.length,error:`Value of type ${Object.prototype.toString.call(B).slice(8,-1)} is not a valid path parameter`});return M+z+(N===Z.length?"":K)},""),J=G.split(/[?#]/,1)[0],T=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,Q;while((Q=T.exec(J))!==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((M,z)=>M.start-z.start),Y.length>0){let M=0,z=Y.reduce((N,B)=>{let K=" ".repeat(B.start-M),P="^".repeat(B.length);return M=B.start+B.length,N+K+P},"");throw new b(`Path parameters result in path with invalid segments:
160
160
  ${Y.map((N)=>N.error).join(`
161
161
  `)}
162
162
  ${G}
163
- ${z}`)}return G},U0=bO(oT);class h9 extends J0{list($={},w){let{betas:W,...Z}=$??{};return this._client.getAPIList("/v1/files",o0,{query:Z,...w,headers:n([{"anthropic-beta":[...W??[],"files-api-2025-04-14"].toString()},w?.headers])})}delete($,w={},W){let{betas:Z}=w??{};return this._client.delete(U0`/v1/files/${$}`,{...W,headers:n([{"anthropic-beta":[...Z??[],"files-api-2025-04-14"].toString()},W?.headers])})}download($,w={},W){let{betas:Z}=w??{};return this._client.get(U0`/v1/files/${$}/content`,{...W,headers:n([{"anthropic-beta":[...Z??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},W?.headers]),__binaryResponse:!0})}retrieveMetadata($,w={},W){let{betas:Z}=w??{};return this._client.get(U0`/v1/files/${$}`,{...W,headers:n([{"anthropic-beta":[...Z??[],"files-api-2025-04-14"].toString()},W?.headers])})}upload($,w){let{betas:W,...Z}=$;return this._client.post("/v1/files",tT({body:Z,...w,headers:n([{"anthropic-beta":[...W??[],"files-api-2025-04-14"].toString()},w?.headers])},this._client))}}class u9 extends J0{retrieve($,w={},W){let{betas:Z}=w??{};return this._client.get(U0`/v1/models/${$}?beta=true`,{...W,headers:n([{...Z?.toString()!=null?{"anthropic-beta":Z?.toString()}:void 0},W?.headers])})}list($={},w){let{betas:W,...Z}=$??{};return this._client.getAPIList("/v1/models?beta=true",o0,{query:Z,...w,headers:n([{...W?.toString()!=null?{"anthropic-beta":W?.toString()}:void 0},w?.headers])})}}class Jw{constructor($,w){this.iterator=$,this.controller=w}async*decoder(){let $=new c$;for await(let w of this.iterator)for(let W of $.decode(w))yield JSON.parse(W);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 Jw(I9($.body),w)}}class i9 extends J0{create($,w){let{betas:W,...Z}=$;return this._client.post("/v1/messages/batches?beta=true",{body:Z,...w,headers:n([{"anthropic-beta":[...W??[],"message-batches-2024-09-24"].toString()},w?.headers])})}retrieve($,w={},W){let{betas:Z}=w??{};return this._client.get(U0`/v1/messages/batches/${$}?beta=true`,{...W,headers:n([{"anthropic-beta":[...Z??[],"message-batches-2024-09-24"].toString()},W?.headers])})}list($={},w){let{betas:W,...Z}=$??{};return this._client.getAPIList("/v1/messages/batches?beta=true",o0,{query:Z,...w,headers:n([{"anthropic-beta":[...W??[],"message-batches-2024-09-24"].toString()},w?.headers])})}delete($,w={},W){let{betas:Z}=w??{};return this._client.delete(U0`/v1/messages/batches/${$}?beta=true`,{...W,headers:n([{"anthropic-beta":[...Z??[],"message-batches-2024-09-24"].toString()},W?.headers])})}cancel($,w={},W){let{betas:Z}=w??{};return this._client.post(U0`/v1/messages/batches/${$}/cancel?beta=true`,{...W,headers:n([{"anthropic-beta":[...Z??[],"message-batches-2024-09-24"].toString()},W?.headers])})}async results($,w={},W){let Z=await this.retrieve($);if(!Z.results_url)throw new b(`No batch \`results_url\`; Has it finished processing? ${Z.processing_status} - ${Z.id}`);let{betas:X}=w??{};return this._client.get(Z.results_url,{...W,headers:n([{"anthropic-beta":[...X??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},W?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((Y,G)=>Jw.fromResponse(G.response,G.controller))}}var vO=($)=>{let w=0,W=[];while(w<$.length){let Z=$[w];if(Z==="\\"){w++;continue}if(Z==="{"){W.push({type:"brace",value:"{"}),w++;continue}if(Z==="}"){W.push({type:"brace",value:"}"}),w++;continue}if(Z==="["){W.push({type:"paren",value:"["}),w++;continue}if(Z==="]"){W.push({type:"paren",value:"]"}),w++;continue}if(Z===":"){W.push({type:"separator",value:":"}),w++;continue}if(Z===","){W.push({type:"delimiter",value:","}),w++;continue}if(Z==='"'){let J="",T=!1;Z=$[++w];while(Z!=='"'){if(w===$.length){T=!0;break}if(Z==="\\"){if(w++,w===$.length){T=!0;break}J+=Z+$[w],Z=$[++w]}else J+=Z,Z=$[++w]}if(Z=$[++w],!T)W.push({type:"string",value:J});continue}if(Z&&/\s/.test(Z)){w++;continue}let Y=/[0-9]/;if(Z&&Y.test(Z)||Z==="-"||Z==="."){let J="";if(Z==="-")J+=Z,Z=$[++w];while(Z&&Y.test(Z)||Z===".")J+=Z,Z=$[++w];W.push({type:"number",value:J});continue}let G=/[a-z]/i;if(Z&&G.test(Z)){let J="";while(Z&&G.test(Z)){if(w===$.length)break;J+=Z,Z=$[++w]}if(J=="true"||J=="false"||J==="null")W.push({type:"name",value:J});else{w++;continue}continue}w++}return W},Tw=($)=>{if($.length===0)return $;let w=$[$.length-1];switch(w.type){case"separator":return $=$.slice(0,$.length-1),Tw($);break;case"number":let W=w.value[w.value.length-1];if(W==="."||W==="-")return $=$.slice(0,$.length-1),Tw($);case"string":let Z=$[$.length-2];if(Z?.type==="delimiter")return $=$.slice(0,$.length-1),Tw($);else if(Z?.type==="brace"&&Z.value==="{")return $=$.slice(0,$.length-1),Tw($);break;case"delimiter":return $=$.slice(0,$.length-1),Tw($);break}return $},hO=($)=>{let w=[];if($.map((W)=>{if(W.type==="brace")if(W.value==="{")w.push("}");else w.splice(w.lastIndexOf("}"),1);if(W.type==="paren")if(W.value==="[")w.push("]");else w.splice(w.lastIndexOf("]"),1)}),w.length>0)w.reverse().map((W)=>{if(W==="}")$.push({type:"brace",value:"}"});else if(W==="]")$.push({type:"paren",value:"]"})});return $},uO=($)=>{let w="";return $.map((W)=>{switch(W.type){case"string":w+='"'+W.value+'"';break;default:w+=W.value;break}}),w},V6=($)=>JSON.parse(uO(hO(Tw(vO($)))));var m0,d$,m9,f6,l9,c9,q6,d9,F$,n9,U6,H6,Qw,F6,O6,HZ,eT,E6,FZ,OZ,EZ,$Q,wQ="__json_buf";function WQ($){return $.type==="tool_use"||$.type==="server_tool_use"||$.type==="mcp_tool_use"}class p9{constructor(){m0.add(this),this.messages=[],this.receivedMessages=[],d$.set(this,void 0),this.controller=new AbortController,m9.set(this,void 0),f6.set(this,()=>{}),l9.set(this,()=>{}),c9.set(this,void 0),q6.set(this,()=>{}),d9.set(this,()=>{}),F$.set(this,{}),n9.set(this,!1),U6.set(this,!1),H6.set(this,!1),Qw.set(this,!1),F6.set(this,void 0),O6.set(this,void 0),E6.set(this,($)=>{if(I(this,U6,!0,"f"),U$($))$=new q0;if($ instanceof q0)return I(this,H6,!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,m9,new Promise(($,w)=>{I(this,f6,$,"f"),I(this,l9,w,"f")}),"f"),I(this,c9,new Promise(($,w)=>{I(this,q6,$,"f"),I(this,d9,w,"f")}),"f"),F(this,m9,"f").catch(()=>{}),F(this,c9,"f").catch(()=>{})}get response(){return F(this,F6,"f")}get request_id(){return F(this,O6,"f")}async withResponse(){let $=await F(this,m9,"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 p9;return w._run(()=>w._fromReadableStream($)),w}static createMessage($,w,W){let Z=new p9;for(let X of w.messages)Z._addMessageParam(X);return Z._run(()=>Z._createMessage($,{...w,stream:!0},{...W,headers:{...W?.headers,"X-Stainless-Helper-Method":"stream"}})),Z}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},F(this,E6,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,w=!0){if(this.receivedMessages.push($),w)this._emit("message",$)}async _createMessage($,w,W){let Z=W?.signal,X;if(Z){if(Z.aborted)this.controller.abort();X=this.controller.abort.bind(this.controller),Z.addEventListener("abort",X)}try{F(this,m0,"m",FZ).call(this);let{response:Y,data:G}=await $.create({...w,stream:!0},{...W,signal:this.controller.signal}).withResponse();this._connected(Y);for await(let J of G)F(this,m0,"m",OZ).call(this,J);if(G.controller.signal?.aborted)throw new q0;F(this,m0,"m",EZ).call(this)}finally{if(Z&&X)Z.removeEventListener("abort",X)}}_connected($){if(this.ended)return;I(this,F6,$,"f"),I(this,O6,$?.headers.get("request-id"),"f"),F(this,f6,"f").call(this,$),this._emit("connect")}get ended(){return F(this,n9,"f")}get errored(){return F(this,U6,"f")}get aborted(){return F(this,H6,"f")}abort(){this.controller.abort()}on($,w){return(F(this,F$,"f")[$]||(F(this,F$,"f")[$]=[])).push({listener:w}),this}off($,w){let W=F(this,F$,"f")[$];if(!W)return this;let Z=W.findIndex((X)=>X.listener===w);if(Z>=0)W.splice(Z,1);return this}once($,w){return(F(this,F$,"f")[$]||(F(this,F$,"f")[$]=[])).push({listener:w,once:!0}),this}emitted($){return new Promise((w,W)=>{if(I(this,Qw,!0,"f"),$!=="error")this.once("error",W);this.once($,w)})}async done(){I(this,Qw,!0,"f"),await F(this,c9,"f")}get currentMessage(){return F(this,d$,"f")}async finalMessage(){return await this.done(),F(this,m0,"m",HZ).call(this)}async finalText(){return await this.done(),F(this,m0,"m",eT).call(this)}_emit($,...w){if(F(this,n9,"f"))return;if($==="end")I(this,n9,!0,"f"),F(this,q6,"f").call(this);let W=F(this,F$,"f")[$];if(W)F(this,F$,"f")[$]=W.filter((Z)=>!Z.once),W.forEach(({listener:Z})=>Z(...w));if($==="abort"){let Z=w[0];if(!F(this,Qw,"f")&&!W?.length)Promise.reject(Z);F(this,l9,"f").call(this,Z),F(this,d9,"f").call(this,Z),this._emit("end");return}if($==="error"){let Z=w[0];if(!F(this,Qw,"f")&&!W?.length)Promise.reject(Z);F(this,l9,"f").call(this,Z),F(this,d9,"f").call(this,Z),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",F(this,m0,"m",HZ).call(this))}async _fromReadableStream($,w){let W=w?.signal,Z;if(W){if(W.aborted)this.controller.abort();Z=this.controller.abort.bind(this.controller),W.addEventListener("abort",Z)}try{F(this,m0,"m",FZ).call(this),this._connected(null);let X=b0.fromReadableStream($,this.controller);for await(let Y of X)F(this,m0,"m",OZ).call(this,Y);if(X.controller.signal?.aborted)throw new q0;F(this,m0,"m",EZ).call(this)}finally{if(W&&Z)W.removeEventListener("abort",Z)}}[(d$=new WeakMap,m9=new WeakMap,f6=new WeakMap,l9=new WeakMap,c9=new WeakMap,q6=new WeakMap,d9=new WeakMap,F$=new WeakMap,n9=new WeakMap,U6=new WeakMap,H6=new WeakMap,Qw=new WeakMap,F6=new WeakMap,O6=new WeakMap,E6=new WeakMap,m0=new WeakSet,HZ=function(){if(this.receivedMessages.length===0)throw new b("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},eT=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((W)=>W.type==="text").map((W)=>W.text);if(w.length===0)throw new b("stream ended without producing a content block with type=text");return w.join(" ")},FZ=function(){if(this.ended)return;I(this,d$,void 0,"f")},OZ=function(w){if(this.ended)return;let W=F(this,m0,"m",$Q).call(this,w);switch(this._emit("streamEvent",w,W),w.type){case"content_block_delta":{let Z=W.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(WQ(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:ZQ(w.delta)}break}case"message_stop":{this._addMessageParam(W),this._addMessage(W,!0);break}case"content_block_stop":{this._emit("contentBlock",W.content.at(-1));break}case"message_start":{I(this,d$,W,"f");break}case"content_block_start":case"message_delta":break}},EZ=function(){if(this.ended)throw new b("stream has ended, this shouldn't happen");let w=F(this,d$,"f");if(!w)throw new b("request ended without sending any chunks");return I(this,d$,void 0,"f"),w},$Q=function(w){let W=F(this,d$,"f");if(w.type==="message_start"){if(W)throw new b(`Unexpected event order, got ${w.type} before receiving "message_stop"`);return w.message}if(!W)throw new b(`Unexpected event order, got ${w.type} before "message_start"`);switch(w.type){case"message_stop":return W;case"message_delta":if(W.container=w.delta.container,W.stop_reason=w.delta.stop_reason,W.stop_sequence=w.delta.stop_sequence,W.usage.output_tokens=w.usage.output_tokens,w.usage.input_tokens!=null)W.usage.input_tokens=w.usage.input_tokens;if(w.usage.cache_creation_input_tokens!=null)W.usage.cache_creation_input_tokens=w.usage.cache_creation_input_tokens;if(w.usage.cache_read_input_tokens!=null)W.usage.cache_read_input_tokens=w.usage.cache_read_input_tokens;if(w.usage.server_tool_use!=null)W.usage.server_tool_use=w.usage.server_tool_use;return W;case"content_block_start":return W.content.push(w.content_block),W;case"content_block_delta":{let Z=W.content.at(w.index);switch(w.delta.type){case"text_delta":{if(Z?.type==="text")W.content[w.index]={...Z,text:(Z.text||"")+w.delta.text};break}case"citations_delta":{if(Z?.type==="text")W.content[w.index]={...Z,citations:[...Z.citations??[],w.delta.citation]};break}case"input_json_delta":{if(Z&&WQ(Z)){let X=Z[wQ]||"";X+=w.delta.partial_json;let Y={...Z};if(Object.defineProperty(Y,wQ,{value:X,enumerable:!1,writable:!0}),X)try{Y.input=V6(X)}catch(G){let J=new b(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${G}. JSON: ${X}`);F(this,E6,"f").call(this,J)}W.content[w.index]=Y}break}case"thinking_delta":{if(Z?.type==="thinking")W.content[w.index]={...Z,thinking:Z.thinking+w.delta.thinking};break}case"signature_delta":{if(Z?.type==="thinking")W.content[w.index]={...Z,signature:w.delta.signature};break}default:ZQ(w.delta)}return W}case"content_block_stop":return W}},Symbol.asyncIterator)](){let $=[],w=[],W=!1;return this.on("streamEvent",(Z)=>{let X=w.shift();if(X)X.resolve(Z);else $.push(Z)}),this.on("end",()=>{W=!0;for(let Z of w)Z.resolve(void 0);w.length=0}),this.on("abort",(Z)=>{W=!0;for(let X of w)X.reject(Z);w.length=0}),this.on("error",(Z)=>{W=!0;for(let X of w)X.reject(Z);w.length=0}),{next:async()=>{if(!$.length){if(W)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 b0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function ZQ($){}var L6={"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 XQ={"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 Mw extends J0{constructor(){super(...arguments);this.batches=new i9(this._client)}create($,w){let{betas:W,...Z}=$;if(Z.model in XQ)console.warn(`The model '${Z.model}' is deprecated and will reach end-of-life on ${XQ[Z.model]}
164
- 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=L6[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:n([{...W?.toString()!=null?{"anthropic-beta":W?.toString()}:void 0},w?.headers]),stream:$.stream??!1})}stream($,w){return p9.createMessage(this,$,w)}countTokens($,w){let{betas:W,...Z}=$;return this._client.post("/v1/messages/count_tokens?beta=true",{body:Z,...w,headers:n([{"anthropic-beta":[...W??[],"token-counting-2024-11-01"].toString()},w?.headers])})}}Mw.Batches=i9;class O$ extends J0{constructor(){super(...arguments);this.models=new u9(this._client),this.messages=new Mw(this._client),this.files=new h9(this._client)}}O$.Models=u9;O$.Messages=Mw;O$.Files=h9;class zw extends J0{create($,w){let{betas:W,...Z}=$;return this._client.post("/v1/complete",{body:Z,timeout:this._client._options.timeout??600000,...w,headers:n([{...W?.toString()!=null?{"anthropic-beta":W?.toString()}:void 0},w?.headers]),stream:$.stream??!1})}}var l0,n$,t9,D6,r9,s9,k6,a9,E$,o9,A6,S6,Nw,R6,C6,LZ,YQ,DZ,kZ,AZ,SZ,GQ,JQ="__json_buf";function TQ($){return $.type==="tool_use"||$.type==="server_tool_use"}class e9{constructor(){l0.add(this),this.messages=[],this.receivedMessages=[],n$.set(this,void 0),this.controller=new AbortController,t9.set(this,void 0),D6.set(this,()=>{}),r9.set(this,()=>{}),s9.set(this,void 0),k6.set(this,()=>{}),a9.set(this,()=>{}),E$.set(this,{}),o9.set(this,!1),A6.set(this,!1),S6.set(this,!1),Nw.set(this,!1),R6.set(this,void 0),C6.set(this,void 0),DZ.set(this,($)=>{if(I(this,A6,!0,"f"),U$($))$=new q0;if($ instanceof q0)return I(this,S6,!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,t9,new Promise(($,w)=>{I(this,D6,$,"f"),I(this,r9,w,"f")}),"f"),I(this,s9,new Promise(($,w)=>{I(this,k6,$,"f"),I(this,a9,w,"f")}),"f"),F(this,t9,"f").catch(()=>{}),F(this,s9,"f").catch(()=>{})}get response(){return F(this,R6,"f")}get request_id(){return F(this,C6,"f")}async withResponse(){let $=await F(this,t9,"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 e9;return w._run(()=>w._fromReadableStream($)),w}static createMessage($,w,W){let Z=new e9;for(let X of w.messages)Z._addMessageParam(X);return Z._run(()=>Z._createMessage($,{...w,stream:!0},{...W,headers:{...W?.headers,"X-Stainless-Helper-Method":"stream"}})),Z}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},F(this,DZ,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,w=!0){if(this.receivedMessages.push($),w)this._emit("message",$)}async _createMessage($,w,W){let Z=W?.signal,X;if(Z){if(Z.aborted)this.controller.abort();X=this.controller.abort.bind(this.controller),Z.addEventListener("abort",X)}try{F(this,l0,"m",kZ).call(this);let{response:Y,data:G}=await $.create({...w,stream:!0},{...W,signal:this.controller.signal}).withResponse();this._connected(Y);for await(let J of G)F(this,l0,"m",AZ).call(this,J);if(G.controller.signal?.aborted)throw new q0;F(this,l0,"m",SZ).call(this)}finally{if(Z&&X)Z.removeEventListener("abort",X)}}_connected($){if(this.ended)return;I(this,R6,$,"f"),I(this,C6,$?.headers.get("request-id"),"f"),F(this,D6,"f").call(this,$),this._emit("connect")}get ended(){return F(this,o9,"f")}get errored(){return F(this,A6,"f")}get aborted(){return F(this,S6,"f")}abort(){this.controller.abort()}on($,w){return(F(this,E$,"f")[$]||(F(this,E$,"f")[$]=[])).push({listener:w}),this}off($,w){let W=F(this,E$,"f")[$];if(!W)return this;let Z=W.findIndex((X)=>X.listener===w);if(Z>=0)W.splice(Z,1);return this}once($,w){return(F(this,E$,"f")[$]||(F(this,E$,"f")[$]=[])).push({listener:w,once:!0}),this}emitted($){return new Promise((w,W)=>{if(I(this,Nw,!0,"f"),$!=="error")this.once("error",W);this.once($,w)})}async done(){I(this,Nw,!0,"f"),await F(this,s9,"f")}get currentMessage(){return F(this,n$,"f")}async finalMessage(){return await this.done(),F(this,l0,"m",LZ).call(this)}async finalText(){return await this.done(),F(this,l0,"m",YQ).call(this)}_emit($,...w){if(F(this,o9,"f"))return;if($==="end")I(this,o9,!0,"f"),F(this,k6,"f").call(this);let W=F(this,E$,"f")[$];if(W)F(this,E$,"f")[$]=W.filter((Z)=>!Z.once),W.forEach(({listener:Z})=>Z(...w));if($==="abort"){let Z=w[0];if(!F(this,Nw,"f")&&!W?.length)Promise.reject(Z);F(this,r9,"f").call(this,Z),F(this,a9,"f").call(this,Z),this._emit("end");return}if($==="error"){let Z=w[0];if(!F(this,Nw,"f")&&!W?.length)Promise.reject(Z);F(this,r9,"f").call(this,Z),F(this,a9,"f").call(this,Z),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",F(this,l0,"m",LZ).call(this))}async _fromReadableStream($,w){let W=w?.signal,Z;if(W){if(W.aborted)this.controller.abort();Z=this.controller.abort.bind(this.controller),W.addEventListener("abort",Z)}try{F(this,l0,"m",kZ).call(this),this._connected(null);let X=b0.fromReadableStream($,this.controller);for await(let Y of X)F(this,l0,"m",AZ).call(this,Y);if(X.controller.signal?.aborted)throw new q0;F(this,l0,"m",SZ).call(this)}finally{if(W&&Z)W.removeEventListener("abort",Z)}}[(n$=new WeakMap,t9=new WeakMap,D6=new WeakMap,r9=new WeakMap,s9=new WeakMap,k6=new WeakMap,a9=new WeakMap,E$=new WeakMap,o9=new WeakMap,A6=new WeakMap,S6=new WeakMap,Nw=new WeakMap,R6=new WeakMap,C6=new WeakMap,DZ=new WeakMap,l0=new WeakSet,LZ=function(){if(this.receivedMessages.length===0)throw new b("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},YQ=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((W)=>W.type==="text").map((W)=>W.text);if(w.length===0)throw new b("stream ended without producing a content block with type=text");return w.join(" ")},kZ=function(){if(this.ended)return;I(this,n$,void 0,"f")},AZ=function(w){if(this.ended)return;let W=F(this,l0,"m",GQ).call(this,w);switch(this._emit("streamEvent",w,W),w.type){case"content_block_delta":{let Z=W.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(TQ(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:QQ(w.delta)}break}case"message_stop":{this._addMessageParam(W),this._addMessage(W,!0);break}case"content_block_stop":{this._emit("contentBlock",W.content.at(-1));break}case"message_start":{I(this,n$,W,"f");break}case"content_block_start":case"message_delta":break}},SZ=function(){if(this.ended)throw new b("stream has ended, this shouldn't happen");let w=F(this,n$,"f");if(!w)throw new b("request ended without sending any chunks");return I(this,n$,void 0,"f"),w},GQ=function(w){let W=F(this,n$,"f");if(w.type==="message_start"){if(W)throw new b(`Unexpected event order, got ${w.type} before receiving "message_stop"`);return w.message}if(!W)throw new b(`Unexpected event order, got ${w.type} before "message_start"`);switch(w.type){case"message_stop":return W;case"message_delta":if(W.stop_reason=w.delta.stop_reason,W.stop_sequence=w.delta.stop_sequence,W.usage.output_tokens=w.usage.output_tokens,w.usage.input_tokens!=null)W.usage.input_tokens=w.usage.input_tokens;if(w.usage.cache_creation_input_tokens!=null)W.usage.cache_creation_input_tokens=w.usage.cache_creation_input_tokens;if(w.usage.cache_read_input_tokens!=null)W.usage.cache_read_input_tokens=w.usage.cache_read_input_tokens;if(w.usage.server_tool_use!=null)W.usage.server_tool_use=w.usage.server_tool_use;return W;case"content_block_start":return W.content.push({...w.content_block}),W;case"content_block_delta":{let Z=W.content.at(w.index);switch(w.delta.type){case"text_delta":{if(Z?.type==="text")W.content[w.index]={...Z,text:(Z.text||"")+w.delta.text};break}case"citations_delta":{if(Z?.type==="text")W.content[w.index]={...Z,citations:[...Z.citations??[],w.delta.citation]};break}case"input_json_delta":{if(Z&&TQ(Z)){let X=Z[JQ]||"";X+=w.delta.partial_json;let Y={...Z};if(Object.defineProperty(Y,JQ,{value:X,enumerable:!1,writable:!0}),X)Y.input=V6(X);W.content[w.index]=Y}break}case"thinking_delta":{if(Z?.type==="thinking")W.content[w.index]={...Z,thinking:Z.thinking+w.delta.thinking};break}case"signature_delta":{if(Z?.type==="thinking")W.content[w.index]={...Z,signature:w.delta.signature};break}default:QQ(w.delta)}return W}case"content_block_stop":return W}},Symbol.asyncIterator)](){let $=[],w=[],W=!1;return this.on("streamEvent",(Z)=>{let X=w.shift();if(X)X.resolve(Z);else $.push(Z)}),this.on("end",()=>{W=!0;for(let Z of w)Z.resolve(void 0);w.length=0}),this.on("abort",(Z)=>{W=!0;for(let X of w)X.reject(Z);w.length=0}),this.on("error",(Z)=>{W=!0;for(let X of w)X.reject(Z);w.length=0}),{next:async()=>{if(!$.length){if(W)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 b0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function QQ($){}class $4 extends J0{create($,w){return this._client.post("/v1/messages/batches",{body:$,...w})}retrieve($,w){return this._client.get(U0`/v1/messages/batches/${$}`,w)}list($={},w){return this._client.getAPIList("/v1/messages/batches",o0,{query:$,...w})}delete($,w){return this._client.delete(U0`/v1/messages/batches/${$}`,w)}cancel($,w){return this._client.post(U0`/v1/messages/batches/${$}/cancel`,w)}async results($,w){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}`);return this._client.get(W.results_url,{...w,headers:n([{Accept:"application/binary"},w?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((Z,X)=>Jw.fromResponse(X.response,X.controller))}}class H1 extends J0{constructor(){super(...arguments);this.batches=new $4(this._client)}create($,w){if($.model in MQ)console.warn(`The model '${$.model}' is deprecated and will reach end-of-life on ${MQ[$.model]}
165
- Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let W=this._client._options.timeout;if(!$.stream&&W==null){let Z=L6[$.model]??void 0;W=this._client.calculateNonstreamingTimeout($.max_tokens,Z)}return this._client.post("/v1/messages",{body:$,timeout:W??600000,...w,stream:$.stream??!1})}stream($,w){return e9.createMessage(this,$,w)}countTokens($,w){return this._client.post("/v1/messages/count_tokens",{body:$,...w})}}var MQ={"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"};H1.Batches=$4;class Kw extends J0{retrieve($,w={},W){let{betas:Z}=w??{};return this._client.get(U0`/v1/models/${$}`,{...W,headers:n([{...Z?.toString()!=null?{"anthropic-beta":Z?.toString()}:void 0},W?.headers])})}list($={},w){let{betas:W,...Z}=$??{};return this._client.getAPIList("/v1/models",o0,{query:Z,...w,headers:n([{...W?.toString()!=null?{"anthropic-beta":W?.toString()}:void 0},w?.headers])})}}var w4=($)=>{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 RZ,CZ,j6,zQ,NQ="\\n\\nHuman:",KQ="\\n\\nAssistant:";class o{constructor({baseURL:$=w4("ANTHROPIC_BASE_URL"),apiKey:w=w4("ANTHROPIC_API_KEY")??null,authToken:W=w4("ANTHROPIC_AUTH_TOKEN")??null,...Z}={}){RZ.add(this),j6.set(this,void 0);let X={apiKey:w,authToken:W,...Z,baseURL:$||"https://api.anthropic.com"};if(!X.dangerouslyAllowBrowser&&xT())throw new b(`It looks like you're running in a browser-like environment.
163
+ ${z}`)}return G},U0=bO(eT);class h4 extends J0{list($={},w){let{betas:W,...Z}=$??{};return this._client.getAPIList("/v1/files",e0,{query:Z,...w,headers:n([{"anthropic-beta":[...W??[],"files-api-2025-04-14"].toString()},w?.headers])})}delete($,w={},W){let{betas:Z}=w??{};return this._client.delete(U0`/v1/files/${$}`,{...W,headers:n([{"anthropic-beta":[...Z??[],"files-api-2025-04-14"].toString()},W?.headers])})}download($,w={},W){let{betas:Z}=w??{};return this._client.get(U0`/v1/files/${$}/content`,{...W,headers:n([{"anthropic-beta":[...Z??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},W?.headers]),__binaryResponse:!0})}retrieveMetadata($,w={},W){let{betas:Z}=w??{};return this._client.get(U0`/v1/files/${$}`,{...W,headers:n([{"anthropic-beta":[...Z??[],"files-api-2025-04-14"].toString()},W?.headers])})}upload($,w){let{betas:W,...Z}=$;return this._client.post("/v1/files",rT({body:Z,...w,headers:n([{"anthropic-beta":[...W??[],"files-api-2025-04-14"].toString()},w?.headers])},this._client))}}class i4 extends J0{retrieve($,w={},W){let{betas:Z}=w??{};return this._client.get(U0`/v1/models/${$}?beta=true`,{...W,headers:n([{...Z?.toString()!=null?{"anthropic-beta":Z?.toString()}:void 0},W?.headers])})}list($={},w){let{betas:W,...Z}=$??{};return this._client.getAPIList("/v1/models?beta=true",e0,{query:Z,...w,headers:n([{...W?.toString()!=null?{"anthropic-beta":W?.toString()}:void 0},w?.headers])})}}class Jw{constructor($,w){this.iterator=$,this.controller=w}async*decoder(){let $=new c$;for await(let w of this.iterator)for(let W of $.decode(w))yield JSON.parse(W);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 Jw(b4($.body),w)}}class m4 extends J0{create($,w){let{betas:W,...Z}=$;return this._client.post("/v1/messages/batches?beta=true",{body:Z,...w,headers:n([{"anthropic-beta":[...W??[],"message-batches-2024-09-24"].toString()},w?.headers])})}retrieve($,w={},W){let{betas:Z}=w??{};return this._client.get(U0`/v1/messages/batches/${$}?beta=true`,{...W,headers:n([{"anthropic-beta":[...Z??[],"message-batches-2024-09-24"].toString()},W?.headers])})}list($={},w){let{betas:W,...Z}=$??{};return this._client.getAPIList("/v1/messages/batches?beta=true",e0,{query:Z,...w,headers:n([{"anthropic-beta":[...W??[],"message-batches-2024-09-24"].toString()},w?.headers])})}delete($,w={},W){let{betas:Z}=w??{};return this._client.delete(U0`/v1/messages/batches/${$}?beta=true`,{...W,headers:n([{"anthropic-beta":[...Z??[],"message-batches-2024-09-24"].toString()},W?.headers])})}cancel($,w={},W){let{betas:Z}=w??{};return this._client.post(U0`/v1/messages/batches/${$}/cancel?beta=true`,{...W,headers:n([{"anthropic-beta":[...Z??[],"message-batches-2024-09-24"].toString()},W?.headers])})}async results($,w={},W){let Z=await this.retrieve($);if(!Z.results_url)throw new b(`No batch \`results_url\`; Has it finished processing? ${Z.processing_status} - ${Z.id}`);let{betas:X}=w??{};return this._client.get(Z.results_url,{...W,headers:n([{"anthropic-beta":[...X??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},W?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((Y,G)=>Jw.fromResponse(G.response,G.controller))}}var vO=($)=>{let w=0,W=[];while(w<$.length){let Z=$[w];if(Z==="\\"){w++;continue}if(Z==="{"){W.push({type:"brace",value:"{"}),w++;continue}if(Z==="}"){W.push({type:"brace",value:"}"}),w++;continue}if(Z==="["){W.push({type:"paren",value:"["}),w++;continue}if(Z==="]"){W.push({type:"paren",value:"]"}),w++;continue}if(Z===":"){W.push({type:"separator",value:":"}),w++;continue}if(Z===","){W.push({type:"delimiter",value:","}),w++;continue}if(Z==='"'){let J="",T=!1;Z=$[++w];while(Z!=='"'){if(w===$.length){T=!0;break}if(Z==="\\"){if(w++,w===$.length){T=!0;break}J+=Z+$[w],Z=$[++w]}else J+=Z,Z=$[++w]}if(Z=$[++w],!T)W.push({type:"string",value:J});continue}if(Z&&/\s/.test(Z)){w++;continue}let Y=/[0-9]/;if(Z&&Y.test(Z)||Z==="-"||Z==="."){let J="";if(Z==="-")J+=Z,Z=$[++w];while(Z&&Y.test(Z)||Z===".")J+=Z,Z=$[++w];W.push({type:"number",value:J});continue}let G=/[a-z]/i;if(Z&&G.test(Z)){let J="";while(Z&&G.test(Z)){if(w===$.length)break;J+=Z,Z=$[++w]}if(J=="true"||J=="false"||J==="null")W.push({type:"name",value:J});else{w++;continue}continue}w++}return W},Tw=($)=>{if($.length===0)return $;let w=$[$.length-1];switch(w.type){case"separator":return $=$.slice(0,$.length-1),Tw($);break;case"number":let W=w.value[w.value.length-1];if(W==="."||W==="-")return $=$.slice(0,$.length-1),Tw($);case"string":let Z=$[$.length-2];if(Z?.type==="delimiter")return $=$.slice(0,$.length-1),Tw($);else if(Z?.type==="brace"&&Z.value==="{")return $=$.slice(0,$.length-1),Tw($);break;case"delimiter":return $=$.slice(0,$.length-1),Tw($);break}return $},uO=($)=>{let w=[];if($.map((W)=>{if(W.type==="brace")if(W.value==="{")w.push("}");else w.splice(w.lastIndexOf("}"),1);if(W.type==="paren")if(W.value==="[")w.push("]");else w.splice(w.lastIndexOf("]"),1)}),w.length>0)w.reverse().map((W)=>{if(W==="}")$.push({type:"brace",value:"}"});else if(W==="]")$.push({type:"paren",value:"]"})});return $},hO=($)=>{let w="";return $.map((W)=>{switch(W.type){case"string":w+='"'+W.value+'"';break;default:w+=W.value;break}}),w},f6=($)=>JSON.parse(hO(uO(Tw(vO($)))));var m0,d$,l4,q6,c4,d4,U6,n4,F$,p4,H6,F6,Qw,O6,E6,HZ,$Q,L6,FZ,OZ,EZ,wQ,WQ="__json_buf";function ZQ($){return $.type==="tool_use"||$.type==="server_tool_use"||$.type==="mcp_tool_use"}class t4{constructor(){m0.add(this),this.messages=[],this.receivedMessages=[],d$.set(this,void 0),this.controller=new AbortController,l4.set(this,void 0),q6.set(this,()=>{}),c4.set(this,()=>{}),d4.set(this,void 0),U6.set(this,()=>{}),n4.set(this,()=>{}),F$.set(this,{}),p4.set(this,!1),H6.set(this,!1),F6.set(this,!1),Qw.set(this,!1),O6.set(this,void 0),E6.set(this,void 0),L6.set(this,($)=>{if(I(this,H6,!0,"f"),U$($))$=new q0;if($ instanceof q0)return I(this,F6,!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,l4,new Promise(($,w)=>{I(this,q6,$,"f"),I(this,c4,w,"f")}),"f"),I(this,d4,new Promise(($,w)=>{I(this,U6,$,"f"),I(this,n4,w,"f")}),"f"),F(this,l4,"f").catch(()=>{}),F(this,d4,"f").catch(()=>{})}get response(){return F(this,O6,"f")}get request_id(){return F(this,E6,"f")}async withResponse(){let $=await F(this,l4,"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 t4;return w._run(()=>w._fromReadableStream($)),w}static createMessage($,w,W){let Z=new t4;for(let X of w.messages)Z._addMessageParam(X);return Z._run(()=>Z._createMessage($,{...w,stream:!0},{...W,headers:{...W?.headers,"X-Stainless-Helper-Method":"stream"}})),Z}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},F(this,L6,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,w=!0){if(this.receivedMessages.push($),w)this._emit("message",$)}async _createMessage($,w,W){let Z=W?.signal,X;if(Z){if(Z.aborted)this.controller.abort();X=this.controller.abort.bind(this.controller),Z.addEventListener("abort",X)}try{F(this,m0,"m",FZ).call(this);let{response:Y,data:G}=await $.create({...w,stream:!0},{...W,signal:this.controller.signal}).withResponse();this._connected(Y);for await(let J of G)F(this,m0,"m",OZ).call(this,J);if(G.controller.signal?.aborted)throw new q0;F(this,m0,"m",EZ).call(this)}finally{if(Z&&X)Z.removeEventListener("abort",X)}}_connected($){if(this.ended)return;I(this,O6,$,"f"),I(this,E6,$?.headers.get("request-id"),"f"),F(this,q6,"f").call(this,$),this._emit("connect")}get ended(){return F(this,p4,"f")}get errored(){return F(this,H6,"f")}get aborted(){return F(this,F6,"f")}abort(){this.controller.abort()}on($,w){return(F(this,F$,"f")[$]||(F(this,F$,"f")[$]=[])).push({listener:w}),this}off($,w){let W=F(this,F$,"f")[$];if(!W)return this;let Z=W.findIndex((X)=>X.listener===w);if(Z>=0)W.splice(Z,1);return this}once($,w){return(F(this,F$,"f")[$]||(F(this,F$,"f")[$]=[])).push({listener:w,once:!0}),this}emitted($){return new Promise((w,W)=>{if(I(this,Qw,!0,"f"),$!=="error")this.once("error",W);this.once($,w)})}async done(){I(this,Qw,!0,"f"),await F(this,d4,"f")}get currentMessage(){return F(this,d$,"f")}async finalMessage(){return await this.done(),F(this,m0,"m",HZ).call(this)}async finalText(){return await this.done(),F(this,m0,"m",$Q).call(this)}_emit($,...w){if(F(this,p4,"f"))return;if($==="end")I(this,p4,!0,"f"),F(this,U6,"f").call(this);let W=F(this,F$,"f")[$];if(W)F(this,F$,"f")[$]=W.filter((Z)=>!Z.once),W.forEach(({listener:Z})=>Z(...w));if($==="abort"){let Z=w[0];if(!F(this,Qw,"f")&&!W?.length)Promise.reject(Z);F(this,c4,"f").call(this,Z),F(this,n4,"f").call(this,Z),this._emit("end");return}if($==="error"){let Z=w[0];if(!F(this,Qw,"f")&&!W?.length)Promise.reject(Z);F(this,c4,"f").call(this,Z),F(this,n4,"f").call(this,Z),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",F(this,m0,"m",HZ).call(this))}async _fromReadableStream($,w){let W=w?.signal,Z;if(W){if(W.aborted)this.controller.abort();Z=this.controller.abort.bind(this.controller),W.addEventListener("abort",Z)}try{F(this,m0,"m",FZ).call(this),this._connected(null);let X=b0.fromReadableStream($,this.controller);for await(let Y of X)F(this,m0,"m",OZ).call(this,Y);if(X.controller.signal?.aborted)throw new q0;F(this,m0,"m",EZ).call(this)}finally{if(W&&Z)W.removeEventListener("abort",Z)}}[(d$=new WeakMap,l4=new WeakMap,q6=new WeakMap,c4=new WeakMap,d4=new WeakMap,U6=new WeakMap,n4=new WeakMap,F$=new WeakMap,p4=new WeakMap,H6=new WeakMap,F6=new WeakMap,Qw=new WeakMap,O6=new WeakMap,E6=new WeakMap,L6=new WeakMap,m0=new WeakSet,HZ=function(){if(this.receivedMessages.length===0)throw new b("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},$Q=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((W)=>W.type==="text").map((W)=>W.text);if(w.length===0)throw new b("stream ended without producing a content block with type=text");return w.join(" ")},FZ=function(){if(this.ended)return;I(this,d$,void 0,"f")},OZ=function(w){if(this.ended)return;let W=F(this,m0,"m",wQ).call(this,w);switch(this._emit("streamEvent",w,W),w.type){case"content_block_delta":{let Z=W.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(ZQ(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:XQ(w.delta)}break}case"message_stop":{this._addMessageParam(W),this._addMessage(W,!0);break}case"content_block_stop":{this._emit("contentBlock",W.content.at(-1));break}case"message_start":{I(this,d$,W,"f");break}case"content_block_start":case"message_delta":break}},EZ=function(){if(this.ended)throw new b("stream has ended, this shouldn't happen");let w=F(this,d$,"f");if(!w)throw new b("request ended without sending any chunks");return I(this,d$,void 0,"f"),w},wQ=function(w){let W=F(this,d$,"f");if(w.type==="message_start"){if(W)throw new b(`Unexpected event order, got ${w.type} before receiving "message_stop"`);return w.message}if(!W)throw new b(`Unexpected event order, got ${w.type} before "message_start"`);switch(w.type){case"message_stop":return W;case"message_delta":if(W.container=w.delta.container,W.stop_reason=w.delta.stop_reason,W.stop_sequence=w.delta.stop_sequence,W.usage.output_tokens=w.usage.output_tokens,w.usage.input_tokens!=null)W.usage.input_tokens=w.usage.input_tokens;if(w.usage.cache_creation_input_tokens!=null)W.usage.cache_creation_input_tokens=w.usage.cache_creation_input_tokens;if(w.usage.cache_read_input_tokens!=null)W.usage.cache_read_input_tokens=w.usage.cache_read_input_tokens;if(w.usage.server_tool_use!=null)W.usage.server_tool_use=w.usage.server_tool_use;return W;case"content_block_start":return W.content.push(w.content_block),W;case"content_block_delta":{let Z=W.content.at(w.index);switch(w.delta.type){case"text_delta":{if(Z?.type==="text")W.content[w.index]={...Z,text:(Z.text||"")+w.delta.text};break}case"citations_delta":{if(Z?.type==="text")W.content[w.index]={...Z,citations:[...Z.citations??[],w.delta.citation]};break}case"input_json_delta":{if(Z&&ZQ(Z)){let X=Z[WQ]||"";X+=w.delta.partial_json;let Y={...Z};if(Object.defineProperty(Y,WQ,{value:X,enumerable:!1,writable:!0}),X)try{Y.input=f6(X)}catch(G){let J=new b(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${G}. JSON: ${X}`);F(this,L6,"f").call(this,J)}W.content[w.index]=Y}break}case"thinking_delta":{if(Z?.type==="thinking")W.content[w.index]={...Z,thinking:Z.thinking+w.delta.thinking};break}case"signature_delta":{if(Z?.type==="thinking")W.content[w.index]={...Z,signature:w.delta.signature};break}default:XQ(w.delta)}return W}case"content_block_stop":return W}},Symbol.asyncIterator)](){let $=[],w=[],W=!1;return this.on("streamEvent",(Z)=>{let X=w.shift();if(X)X.resolve(Z);else $.push(Z)}),this.on("end",()=>{W=!0;for(let Z of w)Z.resolve(void 0);w.length=0}),this.on("abort",(Z)=>{W=!0;for(let X of w)X.reject(Z);w.length=0}),this.on("error",(Z)=>{W=!0;for(let X of w)X.reject(Z);w.length=0}),{next:async()=>{if(!$.length){if(W)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 b0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function XQ($){}var D6={"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 YQ={"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 Mw extends J0{constructor(){super(...arguments);this.batches=new m4(this._client)}create($,w){let{betas:W,...Z}=$;if(Z.model in YQ)console.warn(`The model '${Z.model}' is deprecated and will reach end-of-life on ${YQ[Z.model]}
164
+ 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=D6[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:n([{...W?.toString()!=null?{"anthropic-beta":W?.toString()}:void 0},w?.headers]),stream:$.stream??!1})}stream($,w){return t4.createMessage(this,$,w)}countTokens($,w){let{betas:W,...Z}=$;return this._client.post("/v1/messages/count_tokens?beta=true",{body:Z,...w,headers:n([{"anthropic-beta":[...W??[],"token-counting-2024-11-01"].toString()},w?.headers])})}}Mw.Batches=m4;class O$ extends J0{constructor(){super(...arguments);this.models=new i4(this._client),this.messages=new Mw(this._client),this.files=new h4(this._client)}}O$.Models=i4;O$.Messages=Mw;O$.Files=h4;class zw extends J0{create($,w){let{betas:W,...Z}=$;return this._client.post("/v1/complete",{body:Z,timeout:this._client._options.timeout??600000,...w,headers:n([{...W?.toString()!=null?{"anthropic-beta":W?.toString()}:void 0},w?.headers]),stream:$.stream??!1})}}var l0,n$,r4,k6,s4,a4,A6,o4,E$,e4,S6,R6,Nw,C6,j6,LZ,GQ,DZ,kZ,AZ,SZ,JQ,TQ="__json_buf";function QQ($){return $.type==="tool_use"||$.type==="server_tool_use"}class $9{constructor(){l0.add(this),this.messages=[],this.receivedMessages=[],n$.set(this,void 0),this.controller=new AbortController,r4.set(this,void 0),k6.set(this,()=>{}),s4.set(this,()=>{}),a4.set(this,void 0),A6.set(this,()=>{}),o4.set(this,()=>{}),E$.set(this,{}),e4.set(this,!1),S6.set(this,!1),R6.set(this,!1),Nw.set(this,!1),C6.set(this,void 0),j6.set(this,void 0),DZ.set(this,($)=>{if(I(this,S6,!0,"f"),U$($))$=new q0;if($ instanceof q0)return I(this,R6,!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,r4,new Promise(($,w)=>{I(this,k6,$,"f"),I(this,s4,w,"f")}),"f"),I(this,a4,new Promise(($,w)=>{I(this,A6,$,"f"),I(this,o4,w,"f")}),"f"),F(this,r4,"f").catch(()=>{}),F(this,a4,"f").catch(()=>{})}get response(){return F(this,C6,"f")}get request_id(){return F(this,j6,"f")}async withResponse(){let $=await F(this,r4,"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 $9;return w._run(()=>w._fromReadableStream($)),w}static createMessage($,w,W){let Z=new $9;for(let X of w.messages)Z._addMessageParam(X);return Z._run(()=>Z._createMessage($,{...w,stream:!0},{...W,headers:{...W?.headers,"X-Stainless-Helper-Method":"stream"}})),Z}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},F(this,DZ,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,w=!0){if(this.receivedMessages.push($),w)this._emit("message",$)}async _createMessage($,w,W){let Z=W?.signal,X;if(Z){if(Z.aborted)this.controller.abort();X=this.controller.abort.bind(this.controller),Z.addEventListener("abort",X)}try{F(this,l0,"m",kZ).call(this);let{response:Y,data:G}=await $.create({...w,stream:!0},{...W,signal:this.controller.signal}).withResponse();this._connected(Y);for await(let J of G)F(this,l0,"m",AZ).call(this,J);if(G.controller.signal?.aborted)throw new q0;F(this,l0,"m",SZ).call(this)}finally{if(Z&&X)Z.removeEventListener("abort",X)}}_connected($){if(this.ended)return;I(this,C6,$,"f"),I(this,j6,$?.headers.get("request-id"),"f"),F(this,k6,"f").call(this,$),this._emit("connect")}get ended(){return F(this,e4,"f")}get errored(){return F(this,S6,"f")}get aborted(){return F(this,R6,"f")}abort(){this.controller.abort()}on($,w){return(F(this,E$,"f")[$]||(F(this,E$,"f")[$]=[])).push({listener:w}),this}off($,w){let W=F(this,E$,"f")[$];if(!W)return this;let Z=W.findIndex((X)=>X.listener===w);if(Z>=0)W.splice(Z,1);return this}once($,w){return(F(this,E$,"f")[$]||(F(this,E$,"f")[$]=[])).push({listener:w,once:!0}),this}emitted($){return new Promise((w,W)=>{if(I(this,Nw,!0,"f"),$!=="error")this.once("error",W);this.once($,w)})}async done(){I(this,Nw,!0,"f"),await F(this,a4,"f")}get currentMessage(){return F(this,n$,"f")}async finalMessage(){return await this.done(),F(this,l0,"m",LZ).call(this)}async finalText(){return await this.done(),F(this,l0,"m",GQ).call(this)}_emit($,...w){if(F(this,e4,"f"))return;if($==="end")I(this,e4,!0,"f"),F(this,A6,"f").call(this);let W=F(this,E$,"f")[$];if(W)F(this,E$,"f")[$]=W.filter((Z)=>!Z.once),W.forEach(({listener:Z})=>Z(...w));if($==="abort"){let Z=w[0];if(!F(this,Nw,"f")&&!W?.length)Promise.reject(Z);F(this,s4,"f").call(this,Z),F(this,o4,"f").call(this,Z),this._emit("end");return}if($==="error"){let Z=w[0];if(!F(this,Nw,"f")&&!W?.length)Promise.reject(Z);F(this,s4,"f").call(this,Z),F(this,o4,"f").call(this,Z),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",F(this,l0,"m",LZ).call(this))}async _fromReadableStream($,w){let W=w?.signal,Z;if(W){if(W.aborted)this.controller.abort();Z=this.controller.abort.bind(this.controller),W.addEventListener("abort",Z)}try{F(this,l0,"m",kZ).call(this),this._connected(null);let X=b0.fromReadableStream($,this.controller);for await(let Y of X)F(this,l0,"m",AZ).call(this,Y);if(X.controller.signal?.aborted)throw new q0;F(this,l0,"m",SZ).call(this)}finally{if(W&&Z)W.removeEventListener("abort",Z)}}[(n$=new WeakMap,r4=new WeakMap,k6=new WeakMap,s4=new WeakMap,a4=new WeakMap,A6=new WeakMap,o4=new WeakMap,E$=new WeakMap,e4=new WeakMap,S6=new WeakMap,R6=new WeakMap,Nw=new WeakMap,C6=new WeakMap,j6=new WeakMap,DZ=new WeakMap,l0=new WeakSet,LZ=function(){if(this.receivedMessages.length===0)throw new b("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},GQ=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((W)=>W.type==="text").map((W)=>W.text);if(w.length===0)throw new b("stream ended without producing a content block with type=text");return w.join(" ")},kZ=function(){if(this.ended)return;I(this,n$,void 0,"f")},AZ=function(w){if(this.ended)return;let W=F(this,l0,"m",JQ).call(this,w);switch(this._emit("streamEvent",w,W),w.type){case"content_block_delta":{let Z=W.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(QQ(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:MQ(w.delta)}break}case"message_stop":{this._addMessageParam(W),this._addMessage(W,!0);break}case"content_block_stop":{this._emit("contentBlock",W.content.at(-1));break}case"message_start":{I(this,n$,W,"f");break}case"content_block_start":case"message_delta":break}},SZ=function(){if(this.ended)throw new b("stream has ended, this shouldn't happen");let w=F(this,n$,"f");if(!w)throw new b("request ended without sending any chunks");return I(this,n$,void 0,"f"),w},JQ=function(w){let W=F(this,n$,"f");if(w.type==="message_start"){if(W)throw new b(`Unexpected event order, got ${w.type} before receiving "message_stop"`);return w.message}if(!W)throw new b(`Unexpected event order, got ${w.type} before "message_start"`);switch(w.type){case"message_stop":return W;case"message_delta":if(W.stop_reason=w.delta.stop_reason,W.stop_sequence=w.delta.stop_sequence,W.usage.output_tokens=w.usage.output_tokens,w.usage.input_tokens!=null)W.usage.input_tokens=w.usage.input_tokens;if(w.usage.cache_creation_input_tokens!=null)W.usage.cache_creation_input_tokens=w.usage.cache_creation_input_tokens;if(w.usage.cache_read_input_tokens!=null)W.usage.cache_read_input_tokens=w.usage.cache_read_input_tokens;if(w.usage.server_tool_use!=null)W.usage.server_tool_use=w.usage.server_tool_use;return W;case"content_block_start":return W.content.push({...w.content_block}),W;case"content_block_delta":{let Z=W.content.at(w.index);switch(w.delta.type){case"text_delta":{if(Z?.type==="text")W.content[w.index]={...Z,text:(Z.text||"")+w.delta.text};break}case"citations_delta":{if(Z?.type==="text")W.content[w.index]={...Z,citations:[...Z.citations??[],w.delta.citation]};break}case"input_json_delta":{if(Z&&QQ(Z)){let X=Z[TQ]||"";X+=w.delta.partial_json;let Y={...Z};if(Object.defineProperty(Y,TQ,{value:X,enumerable:!1,writable:!0}),X)Y.input=f6(X);W.content[w.index]=Y}break}case"thinking_delta":{if(Z?.type==="thinking")W.content[w.index]={...Z,thinking:Z.thinking+w.delta.thinking};break}case"signature_delta":{if(Z?.type==="thinking")W.content[w.index]={...Z,signature:w.delta.signature};break}default:MQ(w.delta)}return W}case"content_block_stop":return W}},Symbol.asyncIterator)](){let $=[],w=[],W=!1;return this.on("streamEvent",(Z)=>{let X=w.shift();if(X)X.resolve(Z);else $.push(Z)}),this.on("end",()=>{W=!0;for(let Z of w)Z.resolve(void 0);w.length=0}),this.on("abort",(Z)=>{W=!0;for(let X of w)X.reject(Z);w.length=0}),this.on("error",(Z)=>{W=!0;for(let X of w)X.reject(Z);w.length=0}),{next:async()=>{if(!$.length){if(W)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 b0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function MQ($){}class w9 extends J0{create($,w){return this._client.post("/v1/messages/batches",{body:$,...w})}retrieve($,w){return this._client.get(U0`/v1/messages/batches/${$}`,w)}list($={},w){return this._client.getAPIList("/v1/messages/batches",e0,{query:$,...w})}delete($,w){return this._client.delete(U0`/v1/messages/batches/${$}`,w)}cancel($,w){return this._client.post(U0`/v1/messages/batches/${$}/cancel`,w)}async results($,w){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}`);return this._client.get(W.results_url,{...w,headers:n([{Accept:"application/binary"},w?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((Z,X)=>Jw.fromResponse(X.response,X.controller))}}class H1 extends J0{constructor(){super(...arguments);this.batches=new w9(this._client)}create($,w){if($.model in zQ)console.warn(`The model '${$.model}' is deprecated and will reach end-of-life on ${zQ[$.model]}
165
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let W=this._client._options.timeout;if(!$.stream&&W==null){let Z=D6[$.model]??void 0;W=this._client.calculateNonstreamingTimeout($.max_tokens,Z)}return this._client.post("/v1/messages",{body:$,timeout:W??600000,...w,stream:$.stream??!1})}stream($,w){return $9.createMessage(this,$,w)}countTokens($,w){return this._client.post("/v1/messages/count_tokens",{body:$,...w})}}var zQ={"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"};H1.Batches=w9;class Kw extends J0{retrieve($,w={},W){let{betas:Z}=w??{};return this._client.get(U0`/v1/models/${$}`,{...W,headers:n([{...Z?.toString()!=null?{"anthropic-beta":Z?.toString()}:void 0},W?.headers])})}list($={},w){let{betas:W,...Z}=$??{};return this._client.getAPIList("/v1/models",e0,{query:Z,...w,headers:n([{...W?.toString()!=null?{"anthropic-beta":W?.toString()}:void 0},w?.headers])})}}var W9=($)=>{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 RZ,CZ,y6,NQ,KQ="\\n\\nHuman:",BQ="\\n\\nAssistant:";class o{constructor({baseURL:$=W9("ANTHROPIC_BASE_URL"),apiKey:w=W9("ANTHROPIC_API_KEY")??null,authToken:W=W9("ANTHROPIC_AUTH_TOKEN")??null,...Z}={}){RZ.add(this),y6.set(this,void 0);let X={apiKey:w,authToken:W,...Z,baseURL:$||"https://api.anthropic.com"};if(!X.dangerouslyAllowBrowser&&_T())throw new b(`It looks like you're running in a browser-like environment.
166
166
 
167
167
  This is disabled by default, as it risks exposing your secret API credentials to attackers.
168
168
  If you understand the risks and have appropriate mitigations in place,
169
169
  you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
170
170
 
171
171
  new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
172
- `);this.baseURL=X.baseURL,this.timeout=X.timeout??CZ.DEFAULT_TIMEOUT,this.logger=X.logger??console;let Y="warn";this.logLevel=Y,this.logLevel=BZ(X.logLevel,"ClientOptions.logLevel",this)??BZ(w4("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??Y,this.fetchOptions=X.fetchOptions,this.maxRetries=X.maxRetries??2,this.fetch=X.fetch??gT(),I(this,j6,hT,"f"),this._options=X,this.apiKey=w,this.authToken=W}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,W])=>typeof W<"u").map(([w,W])=>{if(typeof W==="string"||typeof W==="number"||typeof W==="boolean")return`${encodeURIComponent(w)}=${encodeURIComponent(W)}`;if(W===null)return`${encodeURIComponent(w)}=`;throw new b(`Cannot stringify type ${typeof W}; 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 ${l$}`}defaultIdempotencyKey(){return`stainless-node-retry-${TZ()}`}makeStatusError($,w,W,Z){return G0.generate($,w,W,Z)}buildURL($,w,W){let Z=!F(this,RZ,"m",zQ).call(this)&&W||this.baseURL,X=AT($)?new URL($):new URL(Z+(Z.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),Y=this.defaultQuery();if(!ST(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 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:W}){}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,W){return this.request(Promise.resolve(W).then((Z)=>{return{method:$,path:w,...Z}}))}request($,w=null){return new q1(this,this.makeRequest($,w,void 0))}async makeRequest($,w,W){let Z=await $,X=Z.maxRetries??this.maxRetries;if(w==null)w=X;await this.prepareOptions(Z);let{req:Y,url:G,timeout:J}=await this.buildRequest(Z,{retryCount:X-w});await this.prepareRequest(Y,{url:G,options:Z});let T="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),Q=W===void 0?"":`, retryOf: ${W}`,M=Date.now();if(z0(this).debug(`[${T}] sending request`,H$({retryOfRequestLogID:W,method:Z.method,url:G,options:Z,headers:Y.headers})),Z.signal?.aborted)throw new q0;let z=new AbortController,N=await this.fetchWithTimeout(G,Y,J,z).catch(E9),B=Date.now();if(N instanceof globalThis.Error){let q=`retrying, ${w} attempts remaining`;if(Z.signal?.aborted)throw new q0;let f=U$(N)||/timed? ?out/i.test(String(N)+("cause"in N?String(N.cause):""));if(w)return z0(this).info(`[${T}] connection ${f?"timed out":"failed"} - ${q}`),z0(this).debug(`[${T}] connection ${f?"timed out":"failed"} (${q})`,H$({retryOfRequestLogID:W,url:G,durationMs:B-M,message:N.message})),this.retryRequest(Z,w,W??T);if(z0(this).info(`[${T}] connection ${f?"timed out":"failed"} - error; no more retries left`),z0(this).debug(`[${T}] connection ${f?"timed out":"failed"} (error; no more retries left)`,H$({retryOfRequestLogID:W,url:G,durationMs:B-M,message:N.message})),f)throw new L9;throw new f1({cause:N})}let K=[...N.headers.entries()].filter(([q])=>q==="request-id").map(([q,f])=>", "+q+": "+JSON.stringify(f)).join(""),P=`[${T}${Q}${K}] ${Y.method} ${G} ${N.ok?"succeeded":"failed"} with status ${N.status} in ${B-M}ms`;if(!N.ok){let q=await this.shouldRetry(N);if(w&&q){let j=`retrying, ${w} attempts remaining`;return await vT(N.body),z0(this).info(`${P} - ${j}`),z0(this).debug(`[${T}] response error (${j})`,H$({retryOfRequestLogID:W,url:N.url,status:N.status,headers:N.headers,durationMs:B-M})),this.retryRequest(Z,w,W??T,N.headers)}let f=q?"error; no more retries left":"error; not retryable";z0(this).info(`${P} - ${f}`);let H=await N.text().catch((j)=>E9(j).message),E=T6(H),S=E?void 0:H;throw z0(this).debug(`[${T}] response error (${f})`,H$({retryOfRequestLogID:W,url:N.url,status:N.status,headers:N.headers,message:S,durationMs:Date.now()-M})),this.makeStatusError(N.status,E,S,N.headers)}return z0(this).info(P),z0(this).debug(`[${T}] response start`,H$({retryOfRequestLogID:W,url:N.url,status:N.status,headers:N.headers,durationMs:B-M})),{response:N,options:Z,controller:z,requestLogID:T,retryOfRequestLogID:W,startTime:M}}getAPIList($,w,W){return this.requestAPIList(w,{method:"get",path:$,...W})}requestAPIList($,w){let W=this.makeRequest(w,null,void 0);return new B6(this,W,$)}async fetchWithTimeout($,w,W,Z){let{signal:X,method:Y,...G}=w||{};if(X)X.addEventListener("abort",()=>Z.abort());let J=setTimeout(()=>Z.abort(),W),T=globalThis.ReadableStream&&G.body instanceof globalThis.ReadableStream||typeof G.body==="object"&&G.body!==null&&Symbol.asyncIterator in G.body,Q={signal:Z.signal,...T?{duplex:"half"}:{},method:"GET",...G};if(Y)Q.method=Y.toUpperCase();try{return await this.fetch.call(void 0,$,Q)}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,W,Z){let X,Y=Z?.get("retry-after-ms");if(Y){let J=parseFloat(Y);if(!Number.isNaN(J))X=J}let G=Z?.get("retry-after");if(G&&!X){let J=parseFloat(G);if(!Number.isNaN(J))X=J*1000;else X=Date.parse(G)-Date.now()}if(!(X&&0<=X&&X<60000)){let J=$.maxRetries??this.maxRetries;X=this.calculateDefaultRetryTimeoutMillis(w,J)}return await jT(X),this.makeRequest($,w-1,W)}calculateDefaultRetryTimeoutMillis($,w){let X=w-$,Y=Math.min(0.5*Math.pow(2,X),8),G=1-Math.random()*0.25;return Y*G*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 W={...$},{method:Z,path:X,query:Y,defaultBaseURL:G}=W,J=this.buildURL(X,Y,G);if("timeout"in W)CT("timeout",W.timeout);W.timeout=W.timeout??this.timeout;let{bodyHeaders:T,body:Q}=this.buildBody({options:W}),M=await this.buildHeaders({options:$,method:Z,bodyHeaders:T,retryCount:w});return{req:{method:Z,headers:M,...W.signal&&{signal:W.signal},...globalThis.ReadableStream&&Q instanceof globalThis.ReadableStream&&{duplex:"half"},...Q&&{body:Q},...this.fetchOptions??{},...W.fetchOptions??{}},url:J,timeout:W.timeout}}async buildHeaders({options:$,method:w,bodyHeaders:W,retryCount:Z}){let X={};if(this.idempotencyHeader&&w!=="get"){if(!$.idempotencyKey)$.idempotencyKey=this.defaultIdempotencyKey();X[this.idempotencyHeader]=$.idempotencyKey}let Y=n([X,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(Z),...$.timeout?{"X-Stainless-Timeout":String(Math.trunc($.timeout/1000))}:{},..._T(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders($),this._options.defaultHeaders,W,$.headers]);return this.validateHeaders(Y),Y.values}buildBody({options:{body:$,headers:w}}){if(!$)return{bodyHeaders:void 0,body:void 0};let W=n([w]);if(ArrayBuffer.isView($)||$ instanceof ArrayBuffer||$ instanceof DataView||typeof $==="string"&&W.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:Q6($)};else return F(this,j6,"f").call(this,{body:$,headers:W})}}CZ=o,j6=new WeakMap,RZ=new WeakSet,zQ=function(){return this.baseURL!=="https://api.anthropic.com"};o.Anthropic=CZ;o.HUMAN_PROMPT=NQ;o.AI_PROMPT=KQ;o.DEFAULT_TIMEOUT=600000;o.AnthropicError=b;o.APIError=G0;o.APIConnectionError=f1;o.APIConnectionTimeoutError=L9;o.APIUserAbortError=q0;o.NotFoundError=S9;o.ConflictError=R9;o.RateLimitError=j9;o.BadRequestError=D9;o.AuthenticationError=k9;o.InternalServerError=y9;o.PermissionDeniedError=A9;o.UnprocessableEntityError=C9;o.toFile=P6;class L$ extends o{constructor(){super(...arguments);this.completions=new zw(this),this.messages=new H1(this),this.models=new Kw(this),this.beta=new O$(this)}}L$.Completions=zw;L$.Messages=H1;L$.Models=Kw;L$.Beta=O$;class jZ{client;constructor($){this.client=new L$({...$,maxRetries:0})}async*stream($){let{system:w,messages:W}=cO($.messages),Z=this.client.messages.stream({model:$.model,system:w,messages:W,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 cO($){let w=$.filter((Z)=>Z.role==="system").map((Z)=>Z.content).join(`
172
+ `);this.baseURL=X.baseURL,this.timeout=X.timeout??CZ.DEFAULT_TIMEOUT,this.logger=X.logger??console;let Y="warn";this.logLevel=Y,this.logLevel=BZ(X.logLevel,"ClientOptions.logLevel",this)??BZ(W9("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??Y,this.fetchOptions=X.fetchOptions,this.maxRetries=X.maxRetries??2,this.fetch=X.fetch??vT(),I(this,y6,hT,"f"),this._options=X,this.apiKey=w,this.authToken=W}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,W])=>typeof W<"u").map(([w,W])=>{if(typeof W==="string"||typeof W==="number"||typeof W==="boolean")return`${encodeURIComponent(w)}=${encodeURIComponent(W)}`;if(W===null)return`${encodeURIComponent(w)}=`;throw new b(`Cannot stringify type ${typeof W}; 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 ${l$}`}defaultIdempotencyKey(){return`stainless-node-retry-${TZ()}`}makeStatusError($,w,W,Z){return G0.generate($,w,W,Z)}buildURL($,w,W){let Z=!F(this,RZ,"m",NQ).call(this)&&W||this.baseURL,X=ST($)?new URL($):new URL(Z+(Z.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),Y=this.defaultQuery();if(!RT(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 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:W}){}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,W){return this.request(Promise.resolve(W).then((Z)=>{return{method:$,path:w,...Z}}))}request($,w=null){return new q1(this,this.makeRequest($,w,void 0))}async makeRequest($,w,W){let Z=await $,X=Z.maxRetries??this.maxRetries;if(w==null)w=X;await this.prepareOptions(Z);let{req:Y,url:G,timeout:J}=await this.buildRequest(Z,{retryCount:X-w});await this.prepareRequest(Y,{url:G,options:Z});let T="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),Q=W===void 0?"":`, retryOf: ${W}`,M=Date.now();if(z0(this).debug(`[${T}] sending request`,H$({retryOfRequestLogID:W,method:Z.method,url:G,options:Z,headers:Y.headers})),Z.signal?.aborted)throw new q0;let z=new AbortController,N=await this.fetchWithTimeout(G,Y,J,z).catch(L4),B=Date.now();if(N instanceof globalThis.Error){let q=`retrying, ${w} attempts remaining`;if(Z.signal?.aborted)throw new q0;let f=U$(N)||/timed? ?out/i.test(String(N)+("cause"in N?String(N.cause):""));if(w)return z0(this).info(`[${T}] connection ${f?"timed out":"failed"} - ${q}`),z0(this).debug(`[${T}] connection ${f?"timed out":"failed"} (${q})`,H$({retryOfRequestLogID:W,url:G,durationMs:B-M,message:N.message})),this.retryRequest(Z,w,W??T);if(z0(this).info(`[${T}] connection ${f?"timed out":"failed"} - error; no more retries left`),z0(this).debug(`[${T}] connection ${f?"timed out":"failed"} (error; no more retries left)`,H$({retryOfRequestLogID:W,url:G,durationMs:B-M,message:N.message})),f)throw new D4;throw new f1({cause:N})}let K=[...N.headers.entries()].filter(([q])=>q==="request-id").map(([q,f])=>", "+q+": "+JSON.stringify(f)).join(""),P=`[${T}${Q}${K}] ${Y.method} ${G} ${N.ok?"succeeded":"failed"} with status ${N.status} in ${B-M}ms`;if(!N.ok){let q=await this.shouldRetry(N);if(w&&q){let j=`retrying, ${w} attempts remaining`;return await uT(N.body),z0(this).info(`${P} - ${j}`),z0(this).debug(`[${T}] response error (${j})`,H$({retryOfRequestLogID:W,url:N.url,status:N.status,headers:N.headers,durationMs:B-M})),this.retryRequest(Z,w,W??T,N.headers)}let f=q?"error; no more retries left":"error; not retryable";z0(this).info(`${P} - ${f}`);let H=await N.text().catch((j)=>L4(j).message),E=Q6(H),S=E?void 0:H;throw z0(this).debug(`[${T}] response error (${f})`,H$({retryOfRequestLogID:W,url:N.url,status:N.status,headers:N.headers,message:S,durationMs:Date.now()-M})),this.makeStatusError(N.status,E,S,N.headers)}return z0(this).info(P),z0(this).debug(`[${T}] response start`,H$({retryOfRequestLogID:W,url:N.url,status:N.status,headers:N.headers,durationMs:B-M})),{response:N,options:Z,controller:z,requestLogID:T,retryOfRequestLogID:W,startTime:M}}getAPIList($,w,W){return this.requestAPIList(w,{method:"get",path:$,...W})}requestAPIList($,w){let W=this.makeRequest(w,null,void 0);return new P6(this,W,$)}async fetchWithTimeout($,w,W,Z){let{signal:X,method:Y,...G}=w||{};if(X)X.addEventListener("abort",()=>Z.abort());let J=setTimeout(()=>Z.abort(),W),T=globalThis.ReadableStream&&G.body instanceof globalThis.ReadableStream||typeof G.body==="object"&&G.body!==null&&Symbol.asyncIterator in G.body,Q={signal:Z.signal,...T?{duplex:"half"}:{},method:"GET",...G};if(Y)Q.method=Y.toUpperCase();try{return await this.fetch.call(void 0,$,Q)}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,W,Z){let X,Y=Z?.get("retry-after-ms");if(Y){let J=parseFloat(Y);if(!Number.isNaN(J))X=J}let G=Z?.get("retry-after");if(G&&!X){let J=parseFloat(G);if(!Number.isNaN(J))X=J*1000;else X=Date.parse(G)-Date.now()}if(!(X&&0<=X&&X<60000)){let J=$.maxRetries??this.maxRetries;X=this.calculateDefaultRetryTimeoutMillis(w,J)}return await yT(X),this.makeRequest($,w-1,W)}calculateDefaultRetryTimeoutMillis($,w){let X=w-$,Y=Math.min(0.5*Math.pow(2,X),8),G=1-Math.random()*0.25;return Y*G*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 W={...$},{method:Z,path:X,query:Y,defaultBaseURL:G}=W,J=this.buildURL(X,Y,G);if("timeout"in W)jT("timeout",W.timeout);W.timeout=W.timeout??this.timeout;let{bodyHeaders:T,body:Q}=this.buildBody({options:W}),M=await this.buildHeaders({options:$,method:Z,bodyHeaders:T,retryCount:w});return{req:{method:Z,headers:M,...W.signal&&{signal:W.signal},...globalThis.ReadableStream&&Q instanceof globalThis.ReadableStream&&{duplex:"half"},...Q&&{body:Q},...this.fetchOptions??{},...W.fetchOptions??{}},url:J,timeout:W.timeout}}async buildHeaders({options:$,method:w,bodyHeaders:W,retryCount:Z}){let X={};if(this.idempotencyHeader&&w!=="get"){if(!$.idempotencyKey)$.idempotencyKey=this.defaultIdempotencyKey();X[this.idempotencyHeader]=$.idempotencyKey}let Y=n([X,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(Z),...$.timeout?{"X-Stainless-Timeout":String(Math.trunc($.timeout/1000))}:{},...gT(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders($),this._options.defaultHeaders,W,$.headers]);return this.validateHeaders(Y),Y.values}buildBody({options:{body:$,headers:w}}){if(!$)return{bodyHeaders:void 0,body:void 0};let W=n([w]);if(ArrayBuffer.isView($)||$ instanceof ArrayBuffer||$ instanceof DataView||typeof $==="string"&&W.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:M6($)};else return F(this,y6,"f").call(this,{body:$,headers:W})}}CZ=o,y6=new WeakMap,RZ=new WeakSet,NQ=function(){return this.baseURL!=="https://api.anthropic.com"};o.Anthropic=CZ;o.HUMAN_PROMPT=KQ;o.AI_PROMPT=BQ;o.DEFAULT_TIMEOUT=600000;o.AnthropicError=b;o.APIError=G0;o.APIConnectionError=f1;o.APIConnectionTimeoutError=D4;o.APIUserAbortError=q0;o.NotFoundError=R4;o.ConflictError=C4;o.RateLimitError=y4;o.BadRequestError=k4;o.AuthenticationError=A4;o.InternalServerError=I4;o.PermissionDeniedError=S4;o.UnprocessableEntityError=j4;o.toFile=V6;class L$ extends o{constructor(){super(...arguments);this.completions=new zw(this),this.messages=new H1(this),this.models=new Kw(this),this.beta=new O$(this)}}L$.Completions=zw;L$.Messages=H1;L$.Models=Kw;L$.Beta=O$;class jZ{client;constructor($){this.client=new L$({...$,maxRetries:0})}async*stream($){let{system:w,messages:W}=cO($.messages),Z=this.client.messages.stream({model:$.model,system:w,messages:W,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 cO($){let w=$.filter((Z)=>Z.role==="system").map((Z)=>Z.content).join(`
173
173
 
174
- `),W=[];for(let Z of $){if(Z.role==="system")continue;if(Z.role==="user")W.push({role:"user",content:Z.content});else if(Z.role==="assistant")W.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=W.at(-1);if(Y?.role==="user"&&Array.isArray(Y.content))Y.content=[...Y.content,X];else W.push({role:"user",content:[X]})}}return{system:w,messages:W}}function C($,w,W,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($,W):X?X.value=W:w.set($,W),W}function V($,w,W,Z){if(W==="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 W==="m"?Z:W==="a"?Z.call($):Z?Z.value:w.get($)}var yZ=function(){let{crypto:$}=globalThis;if($?.randomUUID)return yZ=$.randomUUID.bind($),$.randomUUID();let w=new Uint8Array(1),W=$?()=>$.getRandomValues(w)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(Z)=>(+Z^W()&15>>+Z/4).toString(16))};function W4($){return typeof $==="object"&&$!==null&&(("name"in $)&&$.name==="AbortError"||("message"in $)&&String($.message).includes("FetchRequestCanceledException"))}var Z4=($)=>{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 Y0 extends k{constructor($,w,W,Z){super(`${Y0.makeMessage($,w,W)}`);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,W){let Z=w?.message?typeof w.message==="string"?w.message:JSON.stringify(w.message):w?JSON.stringify(w):W;if($&&Z)return`${$} ${Z}`;if($)return`${$} status code (no body)`;if(Z)return Z;return"(no status code or body)"}static generate($,w,W,Z){if(!$||!Z)return new F1({message:W,cause:Z4(w)});let X=w?.error;if($===400)return new X4($,X,W,Z);if($===401)return new Y4($,X,W,Z);if($===403)return new G4($,X,W,Z);if($===404)return new J4($,X,W,Z);if($===409)return new T4($,X,W,Z);if($===422)return new Q4($,X,W,Z);if($===429)return new M4($,X,W,Z);if($>=500)return new z4($,X,W,Z);return new Y0($,X,W,Z)}}class T0 extends Y0{constructor({message:$}={}){super(void 0,void 0,$||"Request was aborted.",void 0)}}class F1 extends Y0{constructor({message:$,cause:w}){super(void 0,void 0,$||"Connection error.",void 0);if(w)this.cause=w}}class O1 extends F1{constructor({message:$}={}){super({message:$??"Request timed out."})}}class X4 extends Y0{}class Y4 extends Y0{}class G4 extends Y0{}class J4 extends Y0{}class T4 extends Y0{}class Q4 extends Y0{}class M4 extends Y0{}class z4 extends Y0{}class N4 extends k{constructor(){super("Could not parse response content as the length limit was reached")}}class K4 extends k{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class D$ extends Error{constructor($){super($)}}var nO=/^[a-z][a-z0-9+.-]*:/i,BQ=($)=>{return nO.test($)},H0=($)=>(H0=Array.isArray,H0($)),IZ=H0;function bZ($){if(typeof $!=="object")return{};return $??{}}function PQ($){if(!$)return!0;for(let w in $)return!1;return!0}function VQ($,w){return Object.prototype.hasOwnProperty.call($,w)}function B4($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var fQ=($,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 qQ=($)=>{try{return JSON.parse($)}catch(w){return}};var J$=($)=>new Promise((w)=>setTimeout(w,$));var p$="5.23.2";var OQ=()=>{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 tO=()=>{let $=pO();if($==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":p$,"X-Stainless-OS":HQ(Deno.build.os),"X-Stainless-Arch":UQ(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":p$,"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":p$,"X-Stainless-OS":HQ(globalThis.process.platform??"unknown"),"X-Stainless-Arch":UQ(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let w=rO();if(w)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":p$,"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":p$,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function rO(){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:W}of $){let Z=W.exec(navigator.userAgent);if(Z){let X=Z[1]||0,Y=Z[2]||0,G=Z[3]||0;return{browser:w,version:`${X}.${Y}.${G}`}}}return null}var UQ=($)=>{if($==="x32")return"x32";if($==="x86_64"||$==="x64")return"x64";if($==="arm")return"arm";if($==="aarch64"||$==="arm64")return"arm64";if($)return`other:${$}`;return"unknown"},HQ=($)=>{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"},FQ,EQ=()=>{return FQ??(FQ=tO())};function LQ(){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 xZ(...$){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 y6($){let w=Symbol.asyncIterator in $?$[Symbol.asyncIterator]():$[Symbol.iterator]();return xZ({start(){},async pull(W){let{done:Z,value:X}=await w.next();if(Z)W.close();else W.enqueue(X)},async cancel(){await w.return?.()}})}function _Z($){if($[Symbol.asyncIterator])return $;let w=$.getReader();return{async next(){try{let W=await w.read();if(W?.done)w.releaseLock();return W}catch(W){throw w.releaseLock(),W}},async return(){let W=w.cancel();return w.releaseLock(),await W,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function DQ($){if($===null||typeof $!=="object")return;if($[Symbol.asyncIterator]){await $[Symbol.asyncIterator]().return?.();return}let w=$.getReader(),W=w.cancel();w.releaseLock(),await W}var kQ=({headers:$,body:w})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(w)}};var I6="RFC3986",gZ=($)=>String($),b6={RFC1738:($)=>String($).replace(/%20/g,"+"),RFC3986:gZ},vZ="RFC1738";var x6=($,w)=>(x6=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),x6($,w)),T$=(()=>{let $=[];for(let w=0;w<256;++w)$.push("%"+((w<16?"0":"")+w.toString(16)).toUpperCase());return $})();var hZ=1024,AQ=($,w,W,Z,X)=>{if($.length===0)return $;let Y=$;if(typeof $==="symbol")Y=Symbol.prototype.toString.call($);else if(typeof $!=="string")Y=String($);if(W==="iso-8859-1")return escape(Y).replace(/%u[0-9a-f]{4}/gi,function(J){return"%26%23"+parseInt(J.slice(2),16)+"%3B"});let G="";for(let J=0;J<Y.length;J+=hZ){let T=Y.length>=hZ?Y.slice(J,J+hZ):Y,Q=[];for(let M=0;M<T.length;++M){let z=T.charCodeAt(M);if(z===45||z===46||z===95||z===126||z>=48&&z<=57||z>=65&&z<=90||z>=97&&z<=122||X===vZ&&(z===40||z===41)){Q[Q.length]=T.charAt(M);continue}if(z<128){Q[Q.length]=T$[z];continue}if(z<2048){Q[Q.length]=T$[192|z>>6]+T$[128|z&63];continue}if(z<55296||z>=57344){Q[Q.length]=T$[224|z>>12]+T$[128|z>>6&63]+T$[128|z&63];continue}M+=1,z=65536+((z&1023)<<10|T.charCodeAt(M)&1023),Q[Q.length]=T$[240|z>>18]+T$[128|z>>12&63]+T$[128|z>>6&63]+T$[128|z&63]}G+=Q.join("")}return G};function SQ($){if(!$||typeof $!=="object")return!1;return!!($.constructor&&$.constructor.isBuffer&&$.constructor.isBuffer($))}function uZ($,w){if(H0($)){let W=[];for(let Z=0;Z<$.length;Z+=1)W.push(w($[Z]));return W}return w($)}var CQ={brackets($){return String($)+"[]"},comma:"comma",indices($,w){return String($)+"["+w+"]"},repeat($){return String($)}},jQ=function($,w){Array.prototype.push.apply($,H0(w)?w:[w])},RQ,Q0={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:AQ,encodeValuesOnly:!1,format:I6,formatter:gZ,indices:!1,serializeDate($){return(RQ??(RQ=Function.prototype.call.bind(Date.prototype.toISOString)))($)},skipNulls:!1,strictNullHandling:!1};function oO($){return typeof $==="string"||typeof $==="number"||typeof $==="boolean"||typeof $==="symbol"||typeof $==="bigint"}var iZ={};function yQ($,w,W,Z,X,Y,G,J,T,Q,M,z,N,B,K,P,q,f){let H=$,E=f,S=0,A=!1;while((E=E.get(iZ))!==void 0&&!A){let i=E.get($);if(S+=1,typeof i<"u")if(i===S)throw RangeError("Cyclic object value");else A=!0;if(typeof E.get(iZ)>"u")S=0}if(typeof Q==="function")H=Q(w,H);else if(H instanceof Date)H=N?.(H);else if(W==="comma"&&H0(H))H=uZ(H,function(i){if(i instanceof Date)return N?.(i);return i});if(H===null){if(Y)return T&&!P?T(w,Q0.encoder,q,"key",B):w;H=""}if(oO(H)||SQ(H)){if(T){let i=P?w:T(w,Q0.encoder,q,"key",B);return[K?.(i)+"="+K?.(T(H,Q0.encoder,q,"value",B))]}return[K?.(w)+"="+K?.(String(H))]}let j=[];if(typeof H>"u")return j;let g;if(W==="comma"&&H0(H)){if(P&&T)H=uZ(H,T);g=[{value:H.length>0?H.join(",")||null:void 0}]}else if(H0(Q))g=Q;else{let i=Object.keys(H);g=M?i.sort(M):i}let s=J?String(w).replace(/\./g,"%2E"):String(w),e=Z&&H0(H)&&H.length===1?s+"[]":s;if(X&&H0(H)&&H.length===0)return e+"[]";for(let i=0;i<g.length;++i){let F0=g[i],w1=typeof F0==="object"&&typeof F0.value<"u"?F0.value:H[F0];if(G&&w1===null)continue;let z$=z&&J?F0.replace(/\./g,"%2E"):F0,i1=H0(H)?typeof W==="function"?W(e,z$):e:e+(z?"."+z$:"["+z$+"]");f.set($,S);let uw=new WeakMap;uw.set(iZ,f),jQ(j,yQ(w1,i1,W,Z,X,Y,G,J,W==="comma"&&P&&H0(H)?null:T,Q,M,z,N,B,K,P,q,uw))}return j}function eO($=Q0){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||Q0.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 W=I6;if(typeof $.format<"u"){if(!x6(b6,$.format))throw TypeError("Unknown format option provided.");W=$.format}let Z=b6[W],X=Q0.filter;if(typeof $.filter==="function"||H0($.filter))X=$.filter;let Y;if($.arrayFormat&&$.arrayFormat in CQ)Y=$.arrayFormat;else if("indices"in $)Y=$.indices?"indices":"repeat";else Y=Q0.arrayFormat;if("commaRoundTrip"in $&&typeof $.commaRoundTrip!=="boolean")throw TypeError("`commaRoundTrip` must be a boolean, or absent");let G=typeof $.allowDots>"u"?!!$.encodeDotInKeys===!0?!0:Q0.allowDots:!!$.allowDots;return{addQueryPrefix:typeof $.addQueryPrefix==="boolean"?$.addQueryPrefix:Q0.addQueryPrefix,allowDots:G,allowEmptyArrays:typeof $.allowEmptyArrays==="boolean"?!!$.allowEmptyArrays:Q0.allowEmptyArrays,arrayFormat:Y,charset:w,charsetSentinel:typeof $.charsetSentinel==="boolean"?$.charsetSentinel:Q0.charsetSentinel,commaRoundTrip:!!$.commaRoundTrip,delimiter:typeof $.delimiter>"u"?Q0.delimiter:$.delimiter,encode:typeof $.encode==="boolean"?$.encode:Q0.encode,encodeDotInKeys:typeof $.encodeDotInKeys==="boolean"?$.encodeDotInKeys:Q0.encodeDotInKeys,encoder:typeof $.encoder==="function"?$.encoder:Q0.encoder,encodeValuesOnly:typeof $.encodeValuesOnly==="boolean"?$.encodeValuesOnly:Q0.encodeValuesOnly,filter:X,format:W,formatter:Z,serializeDate:typeof $.serializeDate==="function"?$.serializeDate:Q0.serializeDate,skipNulls:typeof $.skipNulls==="boolean"?$.skipNulls:Q0.skipNulls,sort:typeof $.sort==="function"?$.sort:null,strictNullHandling:typeof $.strictNullHandling==="boolean"?$.strictNullHandling:Q0.strictNullHandling}}function mZ($,w={}){let W=$,Z=eO(w),X,Y;if(typeof Z.filter==="function")Y=Z.filter,W=Y("",W);else if(H0(Z.filter))Y=Z.filter,X=Y;let G=[];if(typeof W!=="object"||W===null)return"";let J=CQ[Z.arrayFormat],T=J==="comma"&&Z.commaRoundTrip;if(!X)X=Object.keys(W);if(Z.sort)X.sort(Z.sort);let Q=new WeakMap;for(let N=0;N<X.length;++N){let B=X[N];if(Z.skipNulls&&W[B]===null)continue;jQ(G,yQ(W[B],B,J,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 M=G.join(Z.delimiter),z=Z.addQueryPrefix===!0?"?":"";if(Z.charsetSentinel)if(Z.charset==="iso-8859-1")z+="utf8=%26%2310003%3B&";else z+="utf8=%E2%9C%93&";return M.length>0?z+M:""}function xQ($){let w=0;for(let X of $)w+=X.length;let W=new Uint8Array(w),Z=0;for(let X of $)W.set(X,Z),Z+=X.length;return W}var IQ;function Bw($){let w;return(IQ??(w=new globalThis.TextEncoder,IQ=w.encode.bind(w)))($)}var bQ;function lZ($){let w;return(bQ??(w=new globalThis.TextDecoder,bQ=w.decode.bind(w)))($)}var x0,_0;class Pw{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"?Bw($):$;C(this,x0,xQ([V(this,x0,"f"),w]),"f");let W=[],Z;while((Z=wE(V(this,x0,"f"),V(this,_0,"f")))!=null){if(Z.carriage&&V(this,_0,"f")==null){C(this,_0,Z.index,"f");continue}if(V(this,_0,"f")!=null&&(Z.index!==V(this,_0,"f")+1||Z.carriage)){W.push(lZ(V(this,x0,"f").subarray(0,V(this,_0,"f")-1))),C(this,x0,V(this,x0,"f").subarray(V(this,_0,"f")),"f"),C(this,_0,null,"f");continue}let X=V(this,_0,"f")!==null?Z.preceding-1:Z.preceding,Y=lZ(V(this,x0,"f").subarray(0,X));W.push(Y),C(this,x0,V(this,x0,"f").subarray(Z.index),"f"),C(this,_0,null,"f")}return W}flush(){if(!V(this,x0,"f").length)return[];return this.decode(`
174
+ `),W=[];for(let Z of $){if(Z.role==="system")continue;if(Z.role==="user")W.push({role:"user",content:Z.content});else if(Z.role==="assistant")W.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=W.at(-1);if(Y?.role==="user"&&Array.isArray(Y.content))Y.content=[...Y.content,X];else W.push({role:"user",content:[X]})}}return{system:w,messages:W}}function C($,w,W,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($,W):X?X.value=W:w.set($,W),W}function V($,w,W,Z){if(W==="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 W==="m"?Z:W==="a"?Z.call($):Z?Z.value:w.get($)}var yZ=function(){let{crypto:$}=globalThis;if($?.randomUUID)return yZ=$.randomUUID.bind($),$.randomUUID();let w=new Uint8Array(1),W=$?()=>$.getRandomValues(w)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(Z)=>(+Z^W()&15>>+Z/4).toString(16))};function Z9($){return typeof $==="object"&&$!==null&&(("name"in $)&&$.name==="AbortError"||("message"in $)&&String($.message).includes("FetchRequestCanceledException"))}var X9=($)=>{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 Y0 extends k{constructor($,w,W,Z){super(`${Y0.makeMessage($,w,W)}`);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,W){let Z=w?.message?typeof w.message==="string"?w.message:JSON.stringify(w.message):w?JSON.stringify(w):W;if($&&Z)return`${$} ${Z}`;if($)return`${$} status code (no body)`;if(Z)return Z;return"(no status code or body)"}static generate($,w,W,Z){if(!$||!Z)return new F1({message:W,cause:X9(w)});let X=w?.error;if($===400)return new Y9($,X,W,Z);if($===401)return new G9($,X,W,Z);if($===403)return new J9($,X,W,Z);if($===404)return new T9($,X,W,Z);if($===409)return new Q9($,X,W,Z);if($===422)return new M9($,X,W,Z);if($===429)return new z9($,X,W,Z);if($>=500)return new N9($,X,W,Z);return new Y0($,X,W,Z)}}class T0 extends Y0{constructor({message:$}={}){super(void 0,void 0,$||"Request was aborted.",void 0)}}class F1 extends Y0{constructor({message:$,cause:w}){super(void 0,void 0,$||"Connection error.",void 0);if(w)this.cause=w}}class O1 extends F1{constructor({message:$}={}){super({message:$??"Request timed out."})}}class Y9 extends Y0{}class G9 extends Y0{}class J9 extends Y0{}class T9 extends Y0{}class Q9 extends Y0{}class M9 extends Y0{}class z9 extends Y0{}class N9 extends Y0{}class K9 extends k{constructor(){super("Could not parse response content as the length limit was reached")}}class B9 extends k{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class D$ extends Error{constructor($){super($)}}var nO=/^[a-z][a-z0-9+.-]*:/i,PQ=($)=>{return nO.test($)},H0=($)=>(H0=Array.isArray,H0($)),IZ=H0;function bZ($){if(typeof $!=="object")return{};return $??{}}function VQ($){if(!$)return!0;for(let w in $)return!1;return!0}function fQ($,w){return Object.prototype.hasOwnProperty.call($,w)}function P9($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var qQ=($,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 UQ=($)=>{try{return JSON.parse($)}catch(w){return}};var J$=($)=>new Promise((w)=>setTimeout(w,$));var p$="5.23.2";var EQ=()=>{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 tO=()=>{let $=pO();if($==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":p$,"X-Stainless-OS":FQ(Deno.build.os),"X-Stainless-Arch":HQ(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":p$,"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":p$,"X-Stainless-OS":FQ(globalThis.process.platform??"unknown"),"X-Stainless-Arch":HQ(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let w=rO();if(w)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":p$,"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":p$,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function rO(){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:W}of $){let Z=W.exec(navigator.userAgent);if(Z){let X=Z[1]||0,Y=Z[2]||0,G=Z[3]||0;return{browser:w,version:`${X}.${Y}.${G}`}}}return null}var HQ=($)=>{if($==="x32")return"x32";if($==="x86_64"||$==="x64")return"x64";if($==="arm")return"arm";if($==="aarch64"||$==="arm64")return"arm64";if($)return`other:${$}`;return"unknown"},FQ=($)=>{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"},OQ,LQ=()=>{return OQ??(OQ=tO())};function DQ(){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 xZ(...$){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 I6($){let w=Symbol.asyncIterator in $?$[Symbol.asyncIterator]():$[Symbol.iterator]();return xZ({start(){},async pull(W){let{done:Z,value:X}=await w.next();if(Z)W.close();else W.enqueue(X)},async cancel(){await w.return?.()}})}function _Z($){if($[Symbol.asyncIterator])return $;let w=$.getReader();return{async next(){try{let W=await w.read();if(W?.done)w.releaseLock();return W}catch(W){throw w.releaseLock(),W}},async return(){let W=w.cancel();return w.releaseLock(),await W,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function kQ($){if($===null||typeof $!=="object")return;if($[Symbol.asyncIterator]){await $[Symbol.asyncIterator]().return?.();return}let w=$.getReader(),W=w.cancel();w.releaseLock(),await W}var AQ=({headers:$,body:w})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(w)}};var b6="RFC3986",gZ=($)=>String($),x6={RFC1738:($)=>String($).replace(/%20/g,"+"),RFC3986:gZ},vZ="RFC1738";var _6=($,w)=>(_6=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),_6($,w)),T$=(()=>{let $=[];for(let w=0;w<256;++w)$.push("%"+((w<16?"0":"")+w.toString(16)).toUpperCase());return $})();var uZ=1024,SQ=($,w,W,Z,X)=>{if($.length===0)return $;let Y=$;if(typeof $==="symbol")Y=Symbol.prototype.toString.call($);else if(typeof $!=="string")Y=String($);if(W==="iso-8859-1")return escape(Y).replace(/%u[0-9a-f]{4}/gi,function(J){return"%26%23"+parseInt(J.slice(2),16)+"%3B"});let G="";for(let J=0;J<Y.length;J+=uZ){let T=Y.length>=uZ?Y.slice(J,J+uZ):Y,Q=[];for(let M=0;M<T.length;++M){let z=T.charCodeAt(M);if(z===45||z===46||z===95||z===126||z>=48&&z<=57||z>=65&&z<=90||z>=97&&z<=122||X===vZ&&(z===40||z===41)){Q[Q.length]=T.charAt(M);continue}if(z<128){Q[Q.length]=T$[z];continue}if(z<2048){Q[Q.length]=T$[192|z>>6]+T$[128|z&63];continue}if(z<55296||z>=57344){Q[Q.length]=T$[224|z>>12]+T$[128|z>>6&63]+T$[128|z&63];continue}M+=1,z=65536+((z&1023)<<10|T.charCodeAt(M)&1023),Q[Q.length]=T$[240|z>>18]+T$[128|z>>12&63]+T$[128|z>>6&63]+T$[128|z&63]}G+=Q.join("")}return G};function RQ($){if(!$||typeof $!=="object")return!1;return!!($.constructor&&$.constructor.isBuffer&&$.constructor.isBuffer($))}function hZ($,w){if(H0($)){let W=[];for(let Z=0;Z<$.length;Z+=1)W.push(w($[Z]));return W}return w($)}var jQ={brackets($){return String($)+"[]"},comma:"comma",indices($,w){return String($)+"["+w+"]"},repeat($){return String($)}},yQ=function($,w){Array.prototype.push.apply($,H0(w)?w:[w])},CQ,Q0={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:SQ,encodeValuesOnly:!1,format:b6,formatter:gZ,indices:!1,serializeDate($){return(CQ??(CQ=Function.prototype.call.bind(Date.prototype.toISOString)))($)},skipNulls:!1,strictNullHandling:!1};function oO($){return typeof $==="string"||typeof $==="number"||typeof $==="boolean"||typeof $==="symbol"||typeof $==="bigint"}var iZ={};function IQ($,w,W,Z,X,Y,G,J,T,Q,M,z,N,B,K,P,q,f){let H=$,E=f,S=0,A=!1;while((E=E.get(iZ))!==void 0&&!A){let i=E.get($);if(S+=1,typeof i<"u")if(i===S)throw RangeError("Cyclic object value");else A=!0;if(typeof E.get(iZ)>"u")S=0}if(typeof Q==="function")H=Q(w,H);else if(H instanceof Date)H=N?.(H);else if(W==="comma"&&H0(H))H=hZ(H,function(i){if(i instanceof Date)return N?.(i);return i});if(H===null){if(Y)return T&&!P?T(w,Q0.encoder,q,"key",B):w;H=""}if(oO(H)||RQ(H)){if(T){let i=P?w:T(w,Q0.encoder,q,"key",B);return[K?.(i)+"="+K?.(T(H,Q0.encoder,q,"value",B))]}return[K?.(w)+"="+K?.(String(H))]}let j=[];if(typeof H>"u")return j;let g;if(W==="comma"&&H0(H)){if(P&&T)H=hZ(H,T);g=[{value:H.length>0?H.join(",")||null:void 0}]}else if(H0(Q))g=Q;else{let i=Object.keys(H);g=M?i.sort(M):i}let s=J?String(w).replace(/\./g,"%2E"):String(w),e=Z&&H0(H)&&H.length===1?s+"[]":s;if(X&&H0(H)&&H.length===0)return e+"[]";for(let i=0;i<g.length;++i){let F0=g[i],w1=typeof F0==="object"&&typeof F0.value<"u"?F0.value:H[F0];if(G&&w1===null)continue;let z$=z&&J?F0.replace(/\./g,"%2E"):F0,i1=H0(H)?typeof W==="function"?W(e,z$):e:e+(z?"."+z$:"["+z$+"]");f.set($,S);let hw=new WeakMap;hw.set(iZ,f),yQ(j,IQ(w1,i1,W,Z,X,Y,G,J,W==="comma"&&P&&H0(H)?null:T,Q,M,z,N,B,K,P,q,hw))}return j}function eO($=Q0){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||Q0.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 W=b6;if(typeof $.format<"u"){if(!_6(x6,$.format))throw TypeError("Unknown format option provided.");W=$.format}let Z=x6[W],X=Q0.filter;if(typeof $.filter==="function"||H0($.filter))X=$.filter;let Y;if($.arrayFormat&&$.arrayFormat in jQ)Y=$.arrayFormat;else if("indices"in $)Y=$.indices?"indices":"repeat";else Y=Q0.arrayFormat;if("commaRoundTrip"in $&&typeof $.commaRoundTrip!=="boolean")throw TypeError("`commaRoundTrip` must be a boolean, or absent");let G=typeof $.allowDots>"u"?!!$.encodeDotInKeys===!0?!0:Q0.allowDots:!!$.allowDots;return{addQueryPrefix:typeof $.addQueryPrefix==="boolean"?$.addQueryPrefix:Q0.addQueryPrefix,allowDots:G,allowEmptyArrays:typeof $.allowEmptyArrays==="boolean"?!!$.allowEmptyArrays:Q0.allowEmptyArrays,arrayFormat:Y,charset:w,charsetSentinel:typeof $.charsetSentinel==="boolean"?$.charsetSentinel:Q0.charsetSentinel,commaRoundTrip:!!$.commaRoundTrip,delimiter:typeof $.delimiter>"u"?Q0.delimiter:$.delimiter,encode:typeof $.encode==="boolean"?$.encode:Q0.encode,encodeDotInKeys:typeof $.encodeDotInKeys==="boolean"?$.encodeDotInKeys:Q0.encodeDotInKeys,encoder:typeof $.encoder==="function"?$.encoder:Q0.encoder,encodeValuesOnly:typeof $.encodeValuesOnly==="boolean"?$.encodeValuesOnly:Q0.encodeValuesOnly,filter:X,format:W,formatter:Z,serializeDate:typeof $.serializeDate==="function"?$.serializeDate:Q0.serializeDate,skipNulls:typeof $.skipNulls==="boolean"?$.skipNulls:Q0.skipNulls,sort:typeof $.sort==="function"?$.sort:null,strictNullHandling:typeof $.strictNullHandling==="boolean"?$.strictNullHandling:Q0.strictNullHandling}}function mZ($,w={}){let W=$,Z=eO(w),X,Y;if(typeof Z.filter==="function")Y=Z.filter,W=Y("",W);else if(H0(Z.filter))Y=Z.filter,X=Y;let G=[];if(typeof W!=="object"||W===null)return"";let J=jQ[Z.arrayFormat],T=J==="comma"&&Z.commaRoundTrip;if(!X)X=Object.keys(W);if(Z.sort)X.sort(Z.sort);let Q=new WeakMap;for(let N=0;N<X.length;++N){let B=X[N];if(Z.skipNulls&&W[B]===null)continue;yQ(G,IQ(W[B],B,J,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 M=G.join(Z.delimiter),z=Z.addQueryPrefix===!0?"?":"";if(Z.charsetSentinel)if(Z.charset==="iso-8859-1")z+="utf8=%26%2310003%3B&";else z+="utf8=%E2%9C%93&";return M.length>0?z+M:""}function _Q($){let w=0;for(let X of $)w+=X.length;let W=new Uint8Array(w),Z=0;for(let X of $)W.set(X,Z),Z+=X.length;return W}var bQ;function Bw($){let w;return(bQ??(w=new globalThis.TextEncoder,bQ=w.encode.bind(w)))($)}var xQ;function lZ($){let w;return(xQ??(w=new globalThis.TextDecoder,xQ=w.decode.bind(w)))($)}var x0,_0;class Pw{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"?Bw($):$;C(this,x0,_Q([V(this,x0,"f"),w]),"f");let W=[],Z;while((Z=wE(V(this,x0,"f"),V(this,_0,"f")))!=null){if(Z.carriage&&V(this,_0,"f")==null){C(this,_0,Z.index,"f");continue}if(V(this,_0,"f")!=null&&(Z.index!==V(this,_0,"f")+1||Z.carriage)){W.push(lZ(V(this,x0,"f").subarray(0,V(this,_0,"f")-1))),C(this,x0,V(this,x0,"f").subarray(V(this,_0,"f")),"f"),C(this,_0,null,"f");continue}let X=V(this,_0,"f")!==null?Z.preceding-1:Z.preceding,Y=lZ(V(this,x0,"f").subarray(0,X));W.push(Y),C(this,x0,V(this,x0,"f").subarray(Z.index),"f"),C(this,_0,null,"f")}return W}flush(){if(!V(this,x0,"f").length)return[];return this.decode(`
175
175
  `)}}x0=new WeakMap,_0=new WeakMap;Pw.NEWLINE_CHARS=new Set([`
176
- `,"\r"]);Pw.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function wE($,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 _Q($){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 g6={off:0,error:200,warn:300,info:400,debug:500},cZ=($,w,W)=>{if(!$)return;if(VQ(g6,$))return $;Z0(W).warn(`${w} was set to ${JSON.stringify($)}, expected one of ${JSON.stringify(Object.keys(g6))}`);return};function P4(){}function _6($,w,W){if(!w||g6[$]>g6[W])return P4;else return w[$].bind(w)}var WE={error:P4,warn:P4,info:P4,debug:P4},gQ=new WeakMap;function Z0($){let w=$.logger,W=$.logLevel??"off";if(!w)return WE;let Z=gQ.get(w);if(Z&&Z[0]===W)return Z[1];let X={error:_6("error",w,W),warn:_6("warn",w,W),info:_6("info",w,W),debug:_6("debug",w,W)};return gQ.set(w,[W,X]),X}var k$=($)=>{if($.options)$.options={...$.options},delete $.options.headers;if($.headers)$.headers=Object.fromEntries(($.headers instanceof Headers?[...$.headers]:Object.entries($.headers)).map(([w,W])=>[w,w.toLowerCase()==="authorization"||w.toLowerCase()==="cookie"||w.toLowerCase()==="set-cookie"?"***":W]));if("retryOfRequestLogID"in $){if($.retryOfRequestLogID)$.retryOf=$.retryOfRequestLogID;delete $.retryOfRequestLogID}return $};var V4;class g0{constructor($,w,W){this.iterator=$,V4.set(this,void 0),this.controller=w,C(this,V4,W,"f")}static fromSSEResponse($,w,W){let Z=!1,X=W?Z0(W):console;async function*Y(){if(Z)throw new k("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");Z=!0;let G=!1;try{for await(let J of ZE($,w)){if(G)continue;if(J.data.startsWith("[DONE]")){G=!0;continue}if(J.event===null||!J.event.startsWith("thread.")){let T;try{T=JSON.parse(J.data)}catch(Q){throw X.error("Could not parse message into JSON:",J.data),X.error("From chunk:",J.raw),Q}if(T&&T.error)throw new Y0(void 0,T.error,void 0,$.headers);yield T}else{let T;try{T=JSON.parse(J.data)}catch(Q){throw console.error("Could not parse message into JSON:",J.data),console.error("From chunk:",J.raw),Q}if(J.event=="error")throw new Y0(void 0,T.error,T.message,void 0);yield{event:J.event,data:T}}}G=!0}catch(J){if(W4(J))return;throw J}finally{if(!G)w.abort()}}return new g0(Y,w,W)}static fromReadableStream($,w,W){let Z=!1;async function*X(){let G=new Pw,J=_Z($);for await(let T of J)for(let Q of G.decode(T))yield Q;for(let T of G.flush())yield T}async function*Y(){if(Z)throw new k("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");Z=!0;let G=!1;try{for await(let J of X()){if(G)continue;if(J)yield JSON.parse(J)}G=!0}catch(J){if(W4(J))return;throw J}finally{if(!G)w.abort()}}return new g0(Y,w,W)}[(V4=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let $=[],w=[],W=this.iterator(),Z=(X)=>{return{next:()=>{if(X.length===0){let Y=W.next();$.push(Y),w.push(Y)}return X.shift()}}};return[new g0(()=>Z($),this.controller,V(this,V4,"f")),new g0(()=>Z(w),this.controller,V(this,V4,"f"))]}toReadableStream(){let $=this,w;return xZ({async start(){w=$[Symbol.asyncIterator]()},async pull(W){try{let{value:Z,done:X}=await w.next();if(X)return W.close();let Y=Bw(JSON.stringify(Z)+`
177
- `);W.enqueue(Y)}catch(Z){W.error(Z)}},async cancel(){await w.return?.()}})}}async function*ZE($,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 W=new vQ,Z=new Pw,X=_Z($.body);for await(let Y of XE(X))for(let G of Z.decode(Y)){let J=W.decode(G);if(J)yield J}for(let Y of Z.flush()){let G=W.decode(Y);if(G)yield G}}async function*XE($){let w=new Uint8Array;for await(let W of $){if(W==null)continue;let Z=W instanceof ArrayBuffer?new Uint8Array(W):typeof W==="string"?Bw(W):W,X=new Uint8Array(w.length+Z.length);X.set(w),X.set(Z,w.length),w=X;let Y;while((Y=_Q(w))!==-1)yield w.slice(0,Y),w=w.slice(Y)}if(w.length>0)yield w}class vQ{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(`
178
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],X}if(this.chunks.push($),$.startsWith(":"))return null;let[w,W,Z]=YE($,":");if(Z.startsWith(" "))Z=Z.substring(1);if(w==="event")this.event=Z;else if(w==="data")this.data.push(Z);return null}}function YE($,w){let W=$.indexOf(w);if(W!==-1)return[$.substring(0,W),w,$.substring(W+w.length)];return[$,"",""]}async function v6($,w){let{response:W,requestLogID:Z,retryOfRequestLogID:X,startTime:Y}=w,G=await(async()=>{if(w.options.stream){if(Z0($).debug("response",W.status,W.url,W.headers,W.body),w.options.__streamClass)return w.options.__streamClass.fromSSEResponse(W,w.controller,$);return g0.fromSSEResponse(W,w.controller,$)}if(W.status===204)return null;if(w.options.__binaryResponse)return W;let T=W.headers.get("content-type")?.split(";")[0]?.trim();if(T?.includes("application/json")||T?.endsWith("+json")){let z=await W.json();return dZ(z,W)}return await W.text()})();return Z0($).debug(`[${Z}] response parsed`,k$({retryOfRequestLogID:X,url:W.url,status:W.status,body:G,durationMs:Date.now()-Y})),G}function dZ($,w){if(!$||typeof $!=="object"||Array.isArray($))return $;return Object.defineProperty($,"_request_id",{value:w.headers.get("x-request-id"),enumerable:!1})}var f4;class E1 extends Promise{constructor($,w,W=v6){super((Z)=>{Z(null)});this.responsePromise=w,this.parseResponse=W,f4.set(this,void 0),C(this,f4,$,"f")}_thenUnwrap($){return new E1(V(this,f4,"f"),this.responsePromise,async(w,W)=>dZ($(await this.parseResponse(w,W),W),W.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(V(this,f4,"f"),$));return this.parsedPromise}then($,w){return this.parse().then($,w)}catch($){return this.parse().catch($)}finally($){return this.parse().finally($)}}f4=new WeakMap;var h6;class u6{constructor($,w,W,Z){h6.set(this,void 0),C(this,h6,$,"f"),this.options=Z,this.response=w,this.body=W}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 V(this,h6,"f").requestAPIList(this.constructor,$)}async*iterPages(){let $=this;yield $;while($.hasNextPage())$=await $.getNextPage(),yield $}async*[(h6=new WeakMap,Symbol.asyncIterator)](){for await(let $ of this.iterPages())for(let w of $.getPaginatedItems())yield w}}class i6 extends E1{constructor($,w,W){super($,w,async(Z,X)=>new W(Z,X.response,await v6(Z,X),X.options))}async*[Symbol.asyncIterator](){let $=await this;for await(let w of $)yield w}}class A$ extends u6{constructor($,w,W,Z){super($,w,W,Z);this.data=W.data||[],this.object=W.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class h extends u6{constructor($,w,W,Z){super($,w,W,Z);this.data=W.data||[],this.has_more=W.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:{...bZ(this.options.query),after:w}}}}class nZ extends u6{constructor($,w,W,Z){super($,w,W,Z);this.data=W.data||[],this.has_more=W.has_more||!1,this.last_id=W.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:{...bZ(this.options.query),after:$}}}}var tZ=()=>{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 Vw($,w,W){return tZ(),new File($,w??"unknown_file",W)}function q4($){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 rZ=($)=>$!=null&&typeof $==="object"&&typeof $[Symbol.asyncIterator]==="function";var v0=async($,w)=>{return{...$,body:await TE($.body,w)}},hQ=new WeakMap;function JE($){let w=typeof $==="function"?$:$.fetch,W=hQ.get(w);if(W)return W;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 hQ.set(w,Z),Z}var TE=async($,w)=>{if(!await JE(w))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let W=new FormData;return await Promise.all(Object.entries($||{}).map(([Z,X])=>pZ(W,Z,X))),W},QE=($)=>$ instanceof Blob&&("name"in $);var pZ=async($,w,W)=>{if(W===void 0)return;if(W==null)throw TypeError(`Received null for "${w}"; to pass null in FormData, you must use the string 'null'`);if(typeof W==="string"||typeof W==="number"||typeof W==="boolean")$.append(w,String(W));else if(W instanceof Response)$.append(w,Vw([await W.blob()],q4(W)));else if(rZ(W))$.append(w,Vw([await new Response(y6(W)).blob()],q4(W)));else if(QE(W))$.append(w,W,q4(W));else if(Array.isArray(W))await Promise.all(W.map((Z)=>pZ($,w+"[]",Z)));else if(typeof W==="object")await Promise.all(Object.entries(W).map(([Z,X])=>pZ($,`${w}[${Z}]`,X)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${W} instead`)};var uQ=($)=>$!=null&&typeof $==="object"&&typeof $.size==="number"&&typeof $.type==="string"&&typeof $.text==="function"&&typeof $.slice==="function"&&typeof $.arrayBuffer==="function",ME=($)=>$!=null&&typeof $==="object"&&typeof $.name==="string"&&typeof $.lastModified==="number"&&uQ($),zE=($)=>$!=null&&typeof $==="object"&&typeof $.url==="string"&&typeof $.blob==="function";async function m6($,w,W){if(tZ(),$=await $,ME($)){if($ instanceof File)return $;return Vw([await $.arrayBuffer()],$.name)}if(zE($)){let X=await $.blob();return w||(w=new URL($.url).pathname.split(/[\\/]/).pop()),Vw(await sZ(X),w,W)}let Z=await sZ($);if(w||(w=q4($)),!W?.type){let X=Z.find((Y)=>typeof Y==="object"&&("type"in Y)&&Y.type);if(typeof X==="string")W={...W,type:X}}return Vw(Z,w,W)}async function sZ($){let w=[];if(typeof $==="string"||ArrayBuffer.isView($)||$ instanceof ArrayBuffer)w.push($);else if(uQ($))w.push($ instanceof Blob?$:await $.arrayBuffer());else if(rZ($))for await(let W of $)w.push(...await sZ(W));else{let W=$?.constructor?.name;throw Error(`Unexpected data type: ${typeof $}${W?`; constructor: ${W}`:""}${NE($)}`)}return w}function NE($){if(typeof $!=="object"||$===null)return"";return`; props: [${Object.getOwnPropertyNames($).map((W)=>`"${W}"`).join(", ")}]`}class O{constructor($){this._client=$}}function mQ($){return $.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var iQ=Object.freeze(Object.create(null)),BE=($=mQ)=>function(W,...Z){if(W.length===1)return W[0];let X=!1,Y=[],G=W.reduce((M,z,N)=>{if(/[?#]/.test(z))X=!0;let B=Z[N],K=(X?encodeURIComponent:$)(""+B);if(N!==Z.length&&(B==null||typeof B==="object"&&B.toString===Object.getPrototypeOf(Object.getPrototypeOf(B.hasOwnProperty??iQ)??iQ)?.toString))K=B+"",Y.push({start:M.length+z.length,length:K.length,error:`Value of type ${Object.prototype.toString.call(B).slice(8,-1)} is not a valid path parameter`});return M+z+(N===Z.length?"":K)},""),J=G.split(/[?#]/,1)[0],T=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,Q;while((Q=T.exec(J))!==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((M,z)=>M.start-z.start),Y.length>0){let M=0,z=Y.reduce((N,B)=>{let K=" ".repeat(B.start-M),P="^".repeat(B.length);return M=B.start+B.length,N+K+P},"");throw new k(`Path parameters result in path with invalid segments:
176
+ `,"\r"]);Pw.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function wE($,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 gQ($){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 v6={off:0,error:200,warn:300,info:400,debug:500},cZ=($,w,W)=>{if(!$)return;if(fQ(v6,$))return $;Z0(W).warn(`${w} was set to ${JSON.stringify($)}, expected one of ${JSON.stringify(Object.keys(v6))}`);return};function V9(){}function g6($,w,W){if(!w||v6[$]>v6[W])return V9;else return w[$].bind(w)}var WE={error:V9,warn:V9,info:V9,debug:V9},vQ=new WeakMap;function Z0($){let w=$.logger,W=$.logLevel??"off";if(!w)return WE;let Z=vQ.get(w);if(Z&&Z[0]===W)return Z[1];let X={error:g6("error",w,W),warn:g6("warn",w,W),info:g6("info",w,W),debug:g6("debug",w,W)};return vQ.set(w,[W,X]),X}var k$=($)=>{if($.options)$.options={...$.options},delete $.options.headers;if($.headers)$.headers=Object.fromEntries(($.headers instanceof Headers?[...$.headers]:Object.entries($.headers)).map(([w,W])=>[w,w.toLowerCase()==="authorization"||w.toLowerCase()==="cookie"||w.toLowerCase()==="set-cookie"?"***":W]));if("retryOfRequestLogID"in $){if($.retryOfRequestLogID)$.retryOf=$.retryOfRequestLogID;delete $.retryOfRequestLogID}return $};var f9;class g0{constructor($,w,W){this.iterator=$,f9.set(this,void 0),this.controller=w,C(this,f9,W,"f")}static fromSSEResponse($,w,W){let Z=!1,X=W?Z0(W):console;async function*Y(){if(Z)throw new k("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");Z=!0;let G=!1;try{for await(let J of ZE($,w)){if(G)continue;if(J.data.startsWith("[DONE]")){G=!0;continue}if(J.event===null||!J.event.startsWith("thread.")){let T;try{T=JSON.parse(J.data)}catch(Q){throw X.error("Could not parse message into JSON:",J.data),X.error("From chunk:",J.raw),Q}if(T&&T.error)throw new Y0(void 0,T.error,void 0,$.headers);yield T}else{let T;try{T=JSON.parse(J.data)}catch(Q){throw console.error("Could not parse message into JSON:",J.data),console.error("From chunk:",J.raw),Q}if(J.event=="error")throw new Y0(void 0,T.error,T.message,void 0);yield{event:J.event,data:T}}}G=!0}catch(J){if(Z9(J))return;throw J}finally{if(!G)w.abort()}}return new g0(Y,w,W)}static fromReadableStream($,w,W){let Z=!1;async function*X(){let G=new Pw,J=_Z($);for await(let T of J)for(let Q of G.decode(T))yield Q;for(let T of G.flush())yield T}async function*Y(){if(Z)throw new k("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");Z=!0;let G=!1;try{for await(let J of X()){if(G)continue;if(J)yield JSON.parse(J)}G=!0}catch(J){if(Z9(J))return;throw J}finally{if(!G)w.abort()}}return new g0(Y,w,W)}[(f9=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let $=[],w=[],W=this.iterator(),Z=(X)=>{return{next:()=>{if(X.length===0){let Y=W.next();$.push(Y),w.push(Y)}return X.shift()}}};return[new g0(()=>Z($),this.controller,V(this,f9,"f")),new g0(()=>Z(w),this.controller,V(this,f9,"f"))]}toReadableStream(){let $=this,w;return xZ({async start(){w=$[Symbol.asyncIterator]()},async pull(W){try{let{value:Z,done:X}=await w.next();if(X)return W.close();let Y=Bw(JSON.stringify(Z)+`
177
+ `);W.enqueue(Y)}catch(Z){W.error(Z)}},async cancel(){await w.return?.()}})}}async function*ZE($,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 W=new uQ,Z=new Pw,X=_Z($.body);for await(let Y of XE(X))for(let G of Z.decode(Y)){let J=W.decode(G);if(J)yield J}for(let Y of Z.flush()){let G=W.decode(Y);if(G)yield G}}async function*XE($){let w=new Uint8Array;for await(let W of $){if(W==null)continue;let Z=W instanceof ArrayBuffer?new Uint8Array(W):typeof W==="string"?Bw(W):W,X=new Uint8Array(w.length+Z.length);X.set(w),X.set(Z,w.length),w=X;let Y;while((Y=gQ(w))!==-1)yield w.slice(0,Y),w=w.slice(Y)}if(w.length>0)yield w}class uQ{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(`
178
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],X}if(this.chunks.push($),$.startsWith(":"))return null;let[w,W,Z]=YE($,":");if(Z.startsWith(" "))Z=Z.substring(1);if(w==="event")this.event=Z;else if(w==="data")this.data.push(Z);return null}}function YE($,w){let W=$.indexOf(w);if(W!==-1)return[$.substring(0,W),w,$.substring(W+w.length)];return[$,"",""]}async function u6($,w){let{response:W,requestLogID:Z,retryOfRequestLogID:X,startTime:Y}=w,G=await(async()=>{if(w.options.stream){if(Z0($).debug("response",W.status,W.url,W.headers,W.body),w.options.__streamClass)return w.options.__streamClass.fromSSEResponse(W,w.controller,$);return g0.fromSSEResponse(W,w.controller,$)}if(W.status===204)return null;if(w.options.__binaryResponse)return W;let T=W.headers.get("content-type")?.split(";")[0]?.trim();if(T?.includes("application/json")||T?.endsWith("+json")){let z=await W.json();return dZ(z,W)}return await W.text()})();return Z0($).debug(`[${Z}] response parsed`,k$({retryOfRequestLogID:X,url:W.url,status:W.status,body:G,durationMs:Date.now()-Y})),G}function dZ($,w){if(!$||typeof $!=="object"||Array.isArray($))return $;return Object.defineProperty($,"_request_id",{value:w.headers.get("x-request-id"),enumerable:!1})}var q9;class E1 extends Promise{constructor($,w,W=u6){super((Z)=>{Z(null)});this.responsePromise=w,this.parseResponse=W,q9.set(this,void 0),C(this,q9,$,"f")}_thenUnwrap($){return new E1(V(this,q9,"f"),this.responsePromise,async(w,W)=>dZ($(await this.parseResponse(w,W),W),W.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(V(this,q9,"f"),$));return this.parsedPromise}then($,w){return this.parse().then($,w)}catch($){return this.parse().catch($)}finally($){return this.parse().finally($)}}q9=new WeakMap;var h6;class i6{constructor($,w,W,Z){h6.set(this,void 0),C(this,h6,$,"f"),this.options=Z,this.response=w,this.body=W}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 V(this,h6,"f").requestAPIList(this.constructor,$)}async*iterPages(){let $=this;yield $;while($.hasNextPage())$=await $.getNextPage(),yield $}async*[(h6=new WeakMap,Symbol.asyncIterator)](){for await(let $ of this.iterPages())for(let w of $.getPaginatedItems())yield w}}class m6 extends E1{constructor($,w,W){super($,w,async(Z,X)=>new W(Z,X.response,await u6(Z,X),X.options))}async*[Symbol.asyncIterator](){let $=await this;for await(let w of $)yield w}}class A$ extends i6{constructor($,w,W,Z){super($,w,W,Z);this.data=W.data||[],this.object=W.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class u extends i6{constructor($,w,W,Z){super($,w,W,Z);this.data=W.data||[],this.has_more=W.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:{...bZ(this.options.query),after:w}}}}class nZ extends i6{constructor($,w,W,Z){super($,w,W,Z);this.data=W.data||[],this.has_more=W.has_more||!1,this.last_id=W.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:{...bZ(this.options.query),after:$}}}}var tZ=()=>{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 Vw($,w,W){return tZ(),new File($,w??"unknown_file",W)}function U9($){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 rZ=($)=>$!=null&&typeof $==="object"&&typeof $[Symbol.asyncIterator]==="function";var v0=async($,w)=>{return{...$,body:await TE($.body,w)}},hQ=new WeakMap;function JE($){let w=typeof $==="function"?$:$.fetch,W=hQ.get(w);if(W)return W;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 hQ.set(w,Z),Z}var TE=async($,w)=>{if(!await JE(w))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let W=new FormData;return await Promise.all(Object.entries($||{}).map(([Z,X])=>pZ(W,Z,X))),W},QE=($)=>$ instanceof Blob&&("name"in $);var pZ=async($,w,W)=>{if(W===void 0)return;if(W==null)throw TypeError(`Received null for "${w}"; to pass null in FormData, you must use the string 'null'`);if(typeof W==="string"||typeof W==="number"||typeof W==="boolean")$.append(w,String(W));else if(W instanceof Response)$.append(w,Vw([await W.blob()],U9(W)));else if(rZ(W))$.append(w,Vw([await new Response(I6(W)).blob()],U9(W)));else if(QE(W))$.append(w,W,U9(W));else if(Array.isArray(W))await Promise.all(W.map((Z)=>pZ($,w+"[]",Z)));else if(typeof W==="object")await Promise.all(Object.entries(W).map(([Z,X])=>pZ($,`${w}[${Z}]`,X)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${W} instead`)};var iQ=($)=>$!=null&&typeof $==="object"&&typeof $.size==="number"&&typeof $.type==="string"&&typeof $.text==="function"&&typeof $.slice==="function"&&typeof $.arrayBuffer==="function",ME=($)=>$!=null&&typeof $==="object"&&typeof $.name==="string"&&typeof $.lastModified==="number"&&iQ($),zE=($)=>$!=null&&typeof $==="object"&&typeof $.url==="string"&&typeof $.blob==="function";async function l6($,w,W){if(tZ(),$=await $,ME($)){if($ instanceof File)return $;return Vw([await $.arrayBuffer()],$.name)}if(zE($)){let X=await $.blob();return w||(w=new URL($.url).pathname.split(/[\\/]/).pop()),Vw(await sZ(X),w,W)}let Z=await sZ($);if(w||(w=U9($)),!W?.type){let X=Z.find((Y)=>typeof Y==="object"&&("type"in Y)&&Y.type);if(typeof X==="string")W={...W,type:X}}return Vw(Z,w,W)}async function sZ($){let w=[];if(typeof $==="string"||ArrayBuffer.isView($)||$ instanceof ArrayBuffer)w.push($);else if(iQ($))w.push($ instanceof Blob?$:await $.arrayBuffer());else if(rZ($))for await(let W of $)w.push(...await sZ(W));else{let W=$?.constructor?.name;throw Error(`Unexpected data type: ${typeof $}${W?`; constructor: ${W}`:""}${NE($)}`)}return w}function NE($){if(typeof $!=="object"||$===null)return"";return`; props: [${Object.getOwnPropertyNames($).map((W)=>`"${W}"`).join(", ")}]`}class O{constructor($){this._client=$}}function lQ($){return $.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var mQ=Object.freeze(Object.create(null)),BE=($=lQ)=>function(W,...Z){if(W.length===1)return W[0];let X=!1,Y=[],G=W.reduce((M,z,N)=>{if(/[?#]/.test(z))X=!0;let B=Z[N],K=(X?encodeURIComponent:$)(""+B);if(N!==Z.length&&(B==null||typeof B==="object"&&B.toString===Object.getPrototypeOf(Object.getPrototypeOf(B.hasOwnProperty??mQ)??mQ)?.toString))K=B+"",Y.push({start:M.length+z.length,length:K.length,error:`Value of type ${Object.prototype.toString.call(B).slice(8,-1)} is not a valid path parameter`});return M+z+(N===Z.length?"":K)},""),J=G.split(/[?#]/,1)[0],T=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,Q;while((Q=T.exec(J))!==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((M,z)=>M.start-z.start),Y.length>0){let M=0,z=Y.reduce((N,B)=>{let K=" ".repeat(B.start-M),P="^".repeat(B.length);return M=B.start+B.length,N+K+P},"");throw new k(`Path parameters result in path with invalid segments:
179
179
  ${Y.map((N)=>N.error).join(`
180
180
  `)}
181
181
  ${G}
182
- ${z}`)}return G},U=BE(mQ);class fw extends O{list($,w={},W){return this._client.getAPIList(U`/chat/completions/${$}/messages`,h,{query:w,...W})}}function U4($){return $!==void 0&&"function"in $&&$.function!==void 0}function H4($){return $?.$brand==="auto-parseable-response-format"}function L1($){return $?.$brand==="auto-parseable-tool"}function lQ($,w){if(!w||!aZ(w))return{...$,choices:$.choices.map((W)=>{return dQ(W.message.tool_calls),{...W,message:{...W.message,parsed:null,...W.message.tool_calls?{tool_calls:W.message.tool_calls}:void 0}}})};return F4($,w)}function F4($,w){let W=$.choices.map((Z)=>{if(Z.finish_reason==="length")throw new N4;if(Z.finish_reason==="content_filter")throw new K4;return dQ(Z.message.tool_calls),{...Z,message:{...Z.message,...Z.message.tool_calls?{tool_calls:Z.message.tool_calls?.map((X)=>qE(w,X))??void 0}:void 0,parsed:Z.message.content&&!Z.message.refusal?fE(w,Z.message.content):null}}});return{...$,choices:W}}function fE($,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 qE($,w){let W=$.tools?.find((Z)=>U4(Z)&&Z.function?.name===w.function.name);return{...w,function:{...w.function,parsed_arguments:L1(W)?W.$parseRaw(w.function.arguments):W?.function.strict?JSON.parse(w.function.arguments):null}}}function cQ($,w){if(!$||!("tools"in $)||!$.tools)return!1;let W=$.tools?.find((Z)=>U4(Z)&&Z.function?.name===w.function.name);return U4(W)&&(L1(W)||W?.function.strict||!1)}function aZ($){if(H4($.response_format))return!0;return $.tools?.some((w)=>L1(w)||w.type==="function"&&w.function.strict===!0)??!1}function dQ($){for(let w of $||[])if(w.type!=="function")throw new k(`Currently only \`function\` tool calls are supported; Received \`${w.type}\``)}function nQ($){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 qw=($)=>{return $?.role==="assistant"},oZ=($)=>{return $?.role==="tool"};var eZ,l6,c6,O4,E4,d6,L4,S$,D4,n6,p6,Uw,pQ;class D1{constructor(){eZ.add(this),this.controller=new AbortController,l6.set(this,void 0),c6.set(this,()=>{}),O4.set(this,()=>{}),E4.set(this,void 0),d6.set(this,()=>{}),L4.set(this,()=>{}),S$.set(this,{}),D4.set(this,!1),n6.set(this,!1),p6.set(this,!1),Uw.set(this,!1),C(this,l6,new Promise(($,w)=>{C(this,c6,$,"f"),C(this,O4,w,"f")}),"f"),C(this,E4,new Promise(($,w)=>{C(this,d6,$,"f"),C(this,L4,w,"f")}),"f"),V(this,l6,"f").catch(()=>{}),V(this,E4,"f").catch(()=>{})}_run($){setTimeout(()=>{$().then(()=>{this._emitFinal(),this._emit("end")},V(this,eZ,"m",pQ).bind(this))},0)}_connected(){if(this.ended)return;V(this,c6,"f").call(this),this._emit("connect")}get ended(){return V(this,D4,"f")}get errored(){return V(this,n6,"f")}get aborted(){return V(this,p6,"f")}abort(){this.controller.abort()}on($,w){return(V(this,S$,"f")[$]||(V(this,S$,"f")[$]=[])).push({listener:w}),this}off($,w){let W=V(this,S$,"f")[$];if(!W)return this;let Z=W.findIndex((X)=>X.listener===w);if(Z>=0)W.splice(Z,1);return this}once($,w){return(V(this,S$,"f")[$]||(V(this,S$,"f")[$]=[])).push({listener:w,once:!0}),this}emitted($){return new Promise((w,W)=>{if(C(this,Uw,!0,"f"),$!=="error")this.once("error",W);this.once($,w)})}async done(){C(this,Uw,!0,"f"),await V(this,E4,"f")}_emit($,...w){if(V(this,D4,"f"))return;if($==="end")C(this,D4,!0,"f"),V(this,d6,"f").call(this);let W=V(this,S$,"f")[$];if(W)V(this,S$,"f")[$]=W.filter((Z)=>!Z.once),W.forEach(({listener:Z})=>Z(...w));if($==="abort"){let Z=w[0];if(!V(this,Uw,"f")&&!W?.length)Promise.reject(Z);V(this,O4,"f").call(this,Z),V(this,L4,"f").call(this,Z),this._emit("end");return}if($==="error"){let Z=w[0];if(!V(this,Uw,"f")&&!W?.length)Promise.reject(Z);V(this,O4,"f").call(this,Z),V(this,L4,"f").call(this,Z),this._emit("end")}}_emitFinal(){}}l6=new WeakMap,c6=new WeakMap,O4=new WeakMap,E4=new WeakMap,d6=new WeakMap,L4=new WeakMap,S$=new WeakMap,D4=new WeakMap,n6=new WeakMap,p6=new WeakMap,Uw=new WeakMap,eZ=new WeakSet,pQ=function(w){if(C(this,n6,!0,"f"),w instanceof Error&&w.name==="AbortError")w=new T0;if(w instanceof T0)return C(this,p6,!0,"f"),this._emit("abort",w);if(w instanceof k)return this._emit("error",w);if(w instanceof Error){let W=new k(w.message);return W.cause=w,this._emit("error",W)}return this._emit("error",new k(String(w)))};function tQ($){return typeof $.parse==="function"}var L0,$3,t6,w3,W3,Z3,rQ,sQ,UE=10;class k4 extends D1{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",$),oZ($)&&$.content)this._emit("functionToolCallResult",$.content);else if(qw($)&&$.tool_calls){for(let W of $.tool_calls)if(W.type==="function")this._emit("functionToolCall",W.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(),V(this,L0,"m",$3).call(this)}async finalMessage(){return await this.done(),V(this,L0,"m",t6).call(this)}async finalFunctionToolCall(){return await this.done(),V(this,L0,"m",w3).call(this)}async finalFunctionToolCallResult(){return await this.done(),V(this,L0,"m",W3).call(this)}async totalUsage(){return await this.done(),V(this,L0,"m",Z3).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let $=this._chatCompletions[this._chatCompletions.length-1];if($)this._emit("finalChatCompletion",$);let w=V(this,L0,"m",t6).call(this);if(w)this._emit("finalMessage",w);let W=V(this,L0,"m",$3).call(this);if(W)this._emit("finalContent",W);let Z=V(this,L0,"m",w3).call(this);if(Z)this._emit("finalFunctionToolCall",Z);let X=V(this,L0,"m",W3).call(this);if(X!=null)this._emit("finalFunctionToolCallResult",X);if(this._chatCompletions.some((Y)=>Y.usage))this._emit("totalUsage",V(this,L0,"m",Z3).call(this))}async _createChatCompletion($,w,W){let Z=W?.signal;if(Z){if(Z.aborted)this.controller.abort();Z.addEventListener("abort",()=>this.controller.abort())}V(this,L0,"m",rQ).call(this,w);let X=await $.chat.completions.create({...w,stream:!1},{...W,signal:this.controller.signal});return this._connected(),this._addChatCompletion(F4(X,w))}async _runChatCompletion($,w,W){for(let Z of w.messages)this._addMessage(Z,!1);return await this._createChatCompletion($,w,W)}async _runTools($,w,W){let{tool_choice:X="auto",stream:Y,...G}=w,J=typeof X!=="string"&&X.type==="function"&&X?.function?.name,{maxChatCompletions:T=UE}=W||{},Q=w.tools.map((N)=>{if(L1(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}),M={};for(let N of Q)if(N.type==="function")M[N.function.name||N.function.function.name]=N.function;let z="tools"in w?Q.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($,{...G,tool_choice:X,tools:z,messages:[...this.messages]},W)).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:f,arguments:H}=P.function,E=M[f];if(!E){let g=`Invalid tool_call: ${JSON.stringify(f)}. Available options are: ${Object.keys(M).map((s)=>JSON.stringify(s)).join(", ")}. Please try again`;this._addMessage({role:"tool",tool_call_id:q,content:g});continue}else if(J&&J!==f){let g=`Invalid tool_call: ${JSON.stringify(f)}. ${JSON.stringify(J)} requested. Please try again`;this._addMessage({role:"tool",tool_call_id:q,content:g});continue}let S;try{S=tQ(E)?await E.parse(H):H}catch(g){let s=g instanceof Error?g.message:String(g);this._addMessage({role:"tool",tool_call_id:q,content:s});continue}let A=await E.function(S,this),j=V(this,L0,"m",sQ).call(this,A);if(this._addMessage({role:"tool",tool_call_id:q,content:j}),J)return}}return}}L0=new WeakSet,$3=function(){return V(this,L0,"m",t6).call(this).content??null},t6=function(){let w=this.messages.length;while(w-- >0){let W=this.messages[w];if(qw(W))return{...W,content:W.content??null,refusal:W.refusal??null}}throw new k("stream ended without producing a ChatCompletionMessage with role=assistant")},w3=function(){for(let w=this.messages.length-1;w>=0;w--){let W=this.messages[w];if(qw(W)&&W?.tool_calls?.length)return W.tool_calls.filter((Z)=>Z.type==="function").at(-1)?.function}return},W3=function(){for(let w=this.messages.length-1;w>=0;w--){let W=this.messages[w];if(oZ(W)&&W.content!=null&&typeof W.content==="string"&&this.messages.some((Z)=>Z.role==="assistant"&&Z.tool_calls?.some((X)=>X.type==="function"&&X.id===W.tool_call_id)))return W.content}return},Z3=function(){let w={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:W}of this._chatCompletions)if(W)w.completion_tokens+=W.completion_tokens,w.prompt_tokens+=W.prompt_tokens,w.total_tokens+=W.total_tokens;return w},rQ=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.")},sQ=function(w){return typeof w==="string"?w:w===void 0?"undefined":JSON.stringify(w)};class A4 extends k4{static runTools($,w,W){let Z=new A4,X={...W,headers:{...W?.headers,"X-Stainless-Helper-Method":"runTools"}};return Z._run(()=>Z._runTools($,w,X)),Z}_addMessage($,w=!0){if(super._addMessage($,w),qw($)&&$.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 aQ extends Error{}class oQ extends Error{}function HE($,w=N0.ALL){if(typeof $!=="string")throw TypeError(`expecting str, got ${typeof $}`);if(!$.trim())throw Error(`${$} is empty`);return FE($.trim(),w)}var FE=($,w)=>{let W=$.length,Z=0,X=(N)=>{throw new aQ(`${N} at position ${Z}`)},Y=(N)=>{throw new oQ(`${N} at position ${Z}`)},G=()=>{if(z(),Z>=W)X("Unexpected end of input");if($[Z]==='"')return J();if($[Z]==="{")return T();if($[Z]==="[")return Q();if($.substring(Z,Z+4)==="null"||N0.NULL&w&&W-Z<4&&"null".startsWith($.substring(Z)))return Z+=4,null;if($.substring(Z,Z+4)==="true"||N0.BOOL&w&&W-Z<4&&"true".startsWith($.substring(Z)))return Z+=4,!0;if($.substring(Z,Z+5)==="false"||N0.BOOL&w&&W-Z<5&&"false".startsWith($.substring(Z)))return Z+=5,!1;if($.substring(Z,Z+8)==="Infinity"||N0.INFINITY&w&&W-Z<8&&"Infinity".startsWith($.substring(Z)))return Z+=8,1/0;if($.substring(Z,Z+9)==="-Infinity"||N0.MINUS_INFINITY&w&&1<W-Z&&W-Z<9&&"-Infinity".startsWith($.substring(Z)))return Z+=9,-1/0;if($.substring(Z,Z+3)==="NaN"||N0.NAN&w&&W-Z<3&&"NaN".startsWith($.substring(Z)))return Z+=3,NaN;return M()},J=()=>{let N=Z,B=!1;Z++;while(Z<W&&($[Z]!=='"'||B&&$[Z-1]==="\\"))B=$[Z]==="\\"?!B:!1,Z++;if($.charAt(Z)=='"')try{return JSON.parse($.substring(N,++Z-Number(B)))}catch(K){Y(String(K))}else if(N0.STR&w)try{return JSON.parse($.substring(N,Z-Number(B))+'"')}catch(K){return JSON.parse($.substring(N,$.lastIndexOf("\\"))+'"')}X("Unterminated string literal")},T=()=>{Z++,z();let N={};try{while($[Z]!=="}"){if(z(),Z>=W&&N0.OBJ&w)return N;let B=J();z(),Z++;try{let K=G();Object.defineProperty(N,B,{value:K,writable:!0,enumerable:!0,configurable:!0})}catch(K){if(N0.OBJ&w)return N;else throw K}if(z(),$[Z]===",")Z++}}catch(B){if(N0.OBJ&w)return N;else X("Expected '}' at end of object")}return Z++,N},Q=()=>{Z++;let N=[];try{while($[Z]!=="]")if(N.push(G()),z(),$[Z]===",")Z++}catch(B){if(N0.ARR&w)return N;X("Expected ']' at end of array")}return Z++,N},M=()=>{if(Z===0){if($==="-"&&N0.NUM&w)X("Not sure what '-' is");try{return JSON.parse($)}catch(B){if(N0.NUM&w)try{if($[$.length-1]===".")return JSON.parse($.substring(0,$.lastIndexOf(".")));return JSON.parse($.substring(0,$.lastIndexOf("e")))}catch(K){}Y(String(B))}}let N=Z;if($[Z]==="-")Z++;while($[Z]&&!",]}".includes($[Z]))Z++;if(Z==W&&!(N0.NUM&w))X("Unterminated number literal");try{return JSON.parse($.substring(N,Z))}catch(B){if($.substring(N,Z)==="-"&&N0.NUM&w)X("Not sure what '-' is");try{return JSON.parse($.substring(N,$.lastIndexOf("e")))}catch(K){Y(String(K))}}},z=()=>{while(Z<W&&`
183
- \r `.includes($[Z]))Z++};return G()},X3=($)=>HE($,N0.ALL^N0.NUM);var M0,R$,Hw,t$,Y3,r6,G3,J3,T3,s6,Q3,eQ;class r$ extends k4{constructor($){super();M0.add(this),R$.set(this,void 0),Hw.set(this,void 0),t$.set(this,void 0),C(this,R$,$,"f"),C(this,Hw,[],"f")}get currentChatCompletionSnapshot(){return V(this,t$,"f")}static fromReadableStream($){let w=new r$(null);return w._run(()=>w._fromReadableStream($)),w}static createChatCompletion($,w,W){let Z=new r$(w);return Z._run(()=>Z._runChatCompletion($,{...w,stream:!0},{...W,headers:{...W?.headers,"X-Stainless-Helper-Method":"stream"}})),Z}async _createChatCompletion($,w,W){super._createChatCompletion;let Z=W?.signal;if(Z){if(Z.aborted)this.controller.abort();Z.addEventListener("abort",()=>this.controller.abort())}V(this,M0,"m",Y3).call(this);let X=await $.chat.completions.create({...w,stream:!0},{...W,signal:this.controller.signal});this._connected();for await(let Y of X)V(this,M0,"m",G3).call(this,Y);if(X.controller.signal?.aborted)throw new T0;return this._addChatCompletion(V(this,M0,"m",s6).call(this))}async _fromReadableStream($,w){let W=w?.signal;if(W){if(W.aborted)this.controller.abort();W.addEventListener("abort",()=>this.controller.abort())}V(this,M0,"m",Y3).call(this),this._connected();let Z=g0.fromReadableStream($,this.controller),X;for await(let Y of Z){if(X&&X!==Y.id)this._addChatCompletion(V(this,M0,"m",s6).call(this));V(this,M0,"m",G3).call(this,Y),X=Y.id}if(Z.controller.signal?.aborted)throw new T0;return this._addChatCompletion(V(this,M0,"m",s6).call(this))}[(R$=new WeakMap,Hw=new WeakMap,t$=new WeakMap,M0=new WeakSet,Y3=function(){if(this.ended)return;C(this,t$,void 0,"f")},r6=function(w){let W=V(this,Hw,"f")[w.index];if(W)return W;return W={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},V(this,Hw,"f")[w.index]=W,W},G3=function(w){if(this.ended)return;let W=V(this,M0,"m",eQ).call(this,w);this._emit("chunk",w,W);for(let Z of w.choices){let X=W.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=V(this,M0,"m",r6).call(this,X);if(X.finish_reason){if(V(this,M0,"m",T3).call(this,X),Y.current_tool_call_index!=null)V(this,M0,"m",J3).call(this,X,Y.current_tool_call_index)}for(let G of Z.delta.tool_calls??[]){if(Y.current_tool_call_index!==G.index){if(V(this,M0,"m",T3).call(this,X),Y.current_tool_call_index!=null)V(this,M0,"m",J3).call(this,X,Y.current_tool_call_index)}Y.current_tool_call_index=G.index}for(let G of Z.delta.tool_calls??[]){let J=X.message.tool_calls?.[G.index];if(!J?.type)continue;if(J?.type==="function")this._emit("tool_calls.function.arguments.delta",{name:J.function?.name,index:G.index,arguments:J.function.arguments,parsed_arguments:J.function.parsed_arguments,arguments_delta:G.function?.arguments??""});else wM(J?.type)}}},J3=function(w,W){if(V(this,M0,"m",r6).call(this,w).done_tool_calls.has(W))return;let X=w.message.tool_calls?.[W];if(!X)throw Error("no tool call snapshot");if(!X.type)throw Error("tool call snapshot missing `type`");if(X.type==="function"){let Y=V(this,R$,"f")?.tools?.find((G)=>U4(G)&&G.function.name===X.function.name);this._emit("tool_calls.function.arguments.done",{name:X.function.name,index:W,arguments:X.function.arguments,parsed_arguments:L1(Y)?Y.$parseRaw(X.function.arguments):Y?.function.strict?JSON.parse(X.function.arguments):null})}else wM(X.type)},T3=function(w){let W=V(this,M0,"m",r6).call(this,w);if(w.message.content&&!W.content_done){W.content_done=!0;let Z=V(this,M0,"m",Q3).call(this);this._emit("content.done",{content:w.message.content,parsed:Z?Z.$parseRaw(w.message.content):null})}if(w.message.refusal&&!W.refusal_done)W.refusal_done=!0,this._emit("refusal.done",{refusal:w.message.refusal});if(w.logprobs?.content&&!W.logprobs_content_done)W.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:w.logprobs.content});if(w.logprobs?.refusal&&!W.logprobs_refusal_done)W.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:w.logprobs.refusal})},s6=function(){if(this.ended)throw new k("stream has ended, this shouldn't happen");let w=V(this,t$,"f");if(!w)throw new k("request ended without sending any chunks");return C(this,t$,void 0,"f"),C(this,Hw,[],"f"),OE(w,V(this,R$,"f"))},Q3=function(){let w=V(this,R$,"f")?.response_format;if(H4(w))return w;return null},eQ=function(w){var W,Z,X,Y;let G=V(this,t$,"f"),{choices:J,...T}=w;if(!G)G=C(this,t$,{...T,choices:[]},"f");else Object.assign(G,T);for(let{delta:Q,finish_reason:M,index:z,logprobs:N=null,...B}of w.choices){let K=G.choices[z];if(!K)K=G.choices[z]={finish_reason:M,index:z,message:{},logprobs:N,...B};if(N)if(!K.logprobs)K.logprobs=Object.assign({},N);else{let{content:A,refusal:j,...g}=N;if($M(g),Object.assign(K.logprobs,g),A)(W=K.logprobs).content??(W.content=[]),K.logprobs.content.push(...A);if(j)(Z=K.logprobs).refusal??(Z.refusal=[]),K.logprobs.refusal.push(...j)}if(M){if(K.finish_reason=M,V(this,R$,"f")&&aZ(V(this,R$,"f"))){if(M==="length")throw new N4;if(M==="content_filter")throw new K4}}if(Object.assign(K,B),!Q)continue;let{content:P,refusal:q,function_call:f,role:H,tool_calls:E,...S}=Q;if($M(S),Object.assign(K.message,S),q)K.message.refusal=(K.message.refusal||"")+q;if(H)K.message.role=H;if(f)if(!K.message.function_call)K.message.function_call=f;else{if(f.name)K.message.function_call.name=f.name;if(f.arguments)(X=K.message.function_call).arguments??(X.arguments=""),K.message.function_call.arguments+=f.arguments}if(P){if(K.message.content=(K.message.content||"")+P,!K.message.refusal&&V(this,M0,"m",Q3).call(this))K.message.parsed=X3(K.message.content)}if(E){if(!K.message.tool_calls)K.message.tool_calls=[];for(let{index:A,id:j,type:g,function:s,...e}of E){let i=(Y=K.message.tool_calls)[A]??(Y[A]={});if(Object.assign(i,e),j)i.id=j;if(g)i.type=g;if(s)i.function??(i.function={name:s.name??"",arguments:""});if(s?.name)i.function.name=s.name;if(s?.arguments){if(i.function.arguments+=s.arguments,cQ(V(this,R$,"f"),i))i.function.parsed_arguments=X3(i.function.arguments)}}}}return G},Symbol.asyncIterator)](){let $=[],w=[],W=!1;return this.on("chunk",(Z)=>{let X=w.shift();if(X)X.resolve(Z);else $.push(Z)}),this.on("end",()=>{W=!0;for(let Z of w)Z.resolve(void 0);w.length=0}),this.on("abort",(Z)=>{W=!0;for(let X of w)X.reject(Z);w.length=0}),this.on("error",(Z)=>{W=!0;for(let X of w)X.reject(Z);w.length=0}),{next:async()=>{if(!$.length){if(W)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 g0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function OE($,w){let{id:W,choices:Z,created:X,model:Y,system_fingerprint:G,...J}=$,T={...J,id:W,choices:Z.map(({message:Q,finish_reason:M,index:z,logprobs:N,...B})=>{if(!M)throw new k(`missing finish_reason for choice ${z}`);let{content:K=null,function_call:P,tool_calls:q,...f}=Q,H=Q.role;if(!H)throw new k(`missing role for choice ${z}`);if(P){let{arguments:E,name:S}=P;if(E==null)throw new k(`missing function_call.arguments for choice ${z}`);if(!S)throw new k(`missing function_call.name for choice ${z}`);return{...B,message:{content:K,function_call:{arguments:E,name:S},role:H,refusal:Q.refusal??null},finish_reason:M,index:z,logprobs:N}}if(q)return{...B,index:z,finish_reason:M,logprobs:N,message:{...f,role:H,content:K,refusal:Q.refusal??null,tool_calls:q.map((E,S)=>{let{function:A,type:j,id:g,...s}=E,{arguments:e,name:i,...F0}=A||{};if(g==null)throw new k(`missing choices[${z}].tool_calls[${S}].id
184
- ${a6($)}`);if(j==null)throw new k(`missing choices[${z}].tool_calls[${S}].type
185
- ${a6($)}`);if(i==null)throw new k(`missing choices[${z}].tool_calls[${S}].function.name
186
- ${a6($)}`);if(e==null)throw new k(`missing choices[${z}].tool_calls[${S}].function.arguments
187
- ${a6($)}`);return{...s,id:g,type:j,function:{...F0,name:i,arguments:e}}})}};return{...B,message:{...f,content:K,role:H,refusal:Q.refusal??null},finish_reason:M,index:z,logprobs:N}}),created:X,model:Y,object:"chat.completion",...G?{system_fingerprint:G}:{}};return lQ(T,w)}function a6($){return JSON.stringify($)}function $M($){return}function wM($){}class Fw extends r${static fromReadableStream($){let w=new Fw(null);return w._run(()=>w._fromReadableStream($)),w}static runTools($,w,W){let Z=new Fw(w),X={...W,headers:{...W?.headers,"X-Stainless-Helper-Method":"runTools"}};return Z._run(()=>Z._runTools($,w,X)),Z}}class s$ extends O{constructor(){super(...arguments);this.messages=new fw(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,W){return this._client.post(U`/chat/completions/${$}`,{body:w,...W})}list($={},w){return this._client.getAPIList("/chat/completions",h,{query:$,...w})}delete($,w){return this._client.delete(U`/chat/completions/${$}`,w)}parse($,w){return nQ($.tools),this._client.chat.completions.create($,{...w,headers:{...w?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap((W)=>F4(W,$))}runTools($,w){if($.stream)return Fw.runTools(this._client,$,w);return A4.runTools(this._client,$,w)}stream($,w){return r$.createChatCompletion(this._client,$,w)}}s$.Messages=fw;class k1 extends O{constructor(){super(...arguments);this.completions=new s$(this._client)}}k1.Completions=s$;var WM=Symbol("brand.privateNullableHeaders");function*LE($){if(!$)return;if(WM in $){let{values:Z,nulls:X}=$;yield*Z.entries();for(let Y of X)yield[Y,null];return}let w=!1,W;if($ instanceof Headers)W=$.entries();else if(IZ($))W=$;else w=!0,W=Object.entries($??{});for(let Z of W){let X=Z[0];if(typeof X!=="string")throw TypeError("expected header name to be a string");let Y=IZ(Z[1])?Z[1]:[Z[1]],G=!1;for(let J of Y){if(J===void 0)continue;if(w&&!G)G=!0,yield[X,null];yield[X,J]}}}var D=($)=>{let w=new Headers,W=new Set;for(let Z of $){let X=new Set;for(let[Y,G]of LE(Z)){let J=Y.toLowerCase();if(!X.has(J))w.delete(Y),X.add(J);if(G===null)w.delete(Y),W.add(J);else w.append(Y,G),W.delete(J)}}return{[WM]:!0,values:w,nulls:W}};class S4 extends O{create($,w){return this._client.post("/audio/speech",{body:$,...w,headers:D([{Accept:"application/octet-stream"},w?.headers]),__binaryResponse:!0})}}class R4 extends O{create($,w){return this._client.post("/audio/transcriptions",v0({body:$,...w,stream:$.stream??!1,__metadata:{model:$.model}},this._client))}}class C4 extends O{create($,w){return this._client.post("/audio/translations",v0({body:$,...w,__metadata:{model:$.model}},this._client))}}class C$ extends O{constructor(){super(...arguments);this.transcriptions=new R4(this._client),this.translations=new C4(this._client),this.speech=new S4(this._client)}}C$.Transcriptions=R4;C$.Translations=C4;C$.Speech=S4;class Ow extends O{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 j4 extends O{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,W){return this._client.post(U`/assistants/${$}`,{body:w,...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.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 y4 extends O{create($,w){return this._client.post("/realtime/sessions",{body:$,...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}}class I4 extends O{create($,w){return this._client.post("/realtime/transcription_sessions",{body:$,...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}}class A1 extends O{constructor(){super(...arguments);this.sessions=new y4(this._client),this.transcriptionSessions=new I4(this._client)}}A1.Sessions=y4;A1.TranscriptionSessions=I4;class b4 extends O{create($,w,W){return this._client.post(U`/threads/${$}/messages`,{body:w,...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}retrieve($,w,W){let{thread_id:Z}=w;return this._client.get(U`/threads/${Z}/messages/${$}`,{...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}update($,w,W){let{thread_id:Z,...X}=w;return this._client.post(U`/threads/${Z}/messages/${$}`,{body:X,...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}list($,w={},W){return this._client.getAPIList(U`/threads/${$}/messages`,h,{query:w,...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}delete($,w,W){let{thread_id:Z}=w;return this._client.delete(U`/threads/${Z}/messages/${$}`,{...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}}class x4 extends O{retrieve($,w,W){let{thread_id:Z,run_id:X,...Y}=w;return this._client.get(U`/threads/${Z}/runs/${X}/steps/${$}`,{query:Y,...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}list($,w,W){let{thread_id:Z,...X}=w;return this._client.getAPIList(U`/threads/${Z}/runs/${$}/steps`,h,{query:X,...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}}var ZM=($)=>{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($),W=w.length,Z=new Uint8Array(W);for(let X=0;X<W;X++)Z[X]=w.charCodeAt(X);return Array.from(new Float32Array(Z.buffer))}};var a$=($)=>{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 B0,R1,M3,Q$,o6,e0,C1,Ew,S1,wW,h0,e6,$W,v4,_4,g4,XM,YM,GM,JM,TM,QM,MM;class o$ extends D1{constructor(){super(...arguments);B0.add(this),M3.set(this,[]),Q$.set(this,{}),o6.set(this,{}),e0.set(this,void 0),C1.set(this,void 0),Ew.set(this,void 0),S1.set(this,void 0),wW.set(this,void 0),h0.set(this,void 0),e6.set(this,void 0),$W.set(this,void 0),v4.set(this,void 0)}[(M3=new WeakMap,Q$=new WeakMap,o6=new WeakMap,e0=new WeakMap,C1=new WeakMap,Ew=new WeakMap,S1=new WeakMap,wW=new WeakMap,h0=new WeakMap,e6=new WeakMap,$W=new WeakMap,v4=new WeakMap,B0=new WeakSet,Symbol.asyncIterator)](){let $=[],w=[],W=!1;return this.on("event",(Z)=>{let X=w.shift();if(X)X.resolve(Z);else $.push(Z)}),this.on("end",()=>{W=!0;for(let Z of w)Z.resolve(void 0);w.length=0}),this.on("abort",(Z)=>{W=!0;for(let X of w)X.reject(Z);w.length=0}),this.on("error",(Z)=>{W=!0;for(let X of w)X.reject(Z);w.length=0}),{next:async()=>{if(!$.length){if(W)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 R1;return w._run(()=>w._fromReadableStream($)),w}async _fromReadableStream($,w){let W=w?.signal;if(W){if(W.aborted)this.controller.abort();W.addEventListener("abort",()=>this.controller.abort())}this._connected();let Z=g0.fromReadableStream($,this.controller);for await(let X of Z)V(this,B0,"m",_4).call(this,X);if(Z.controller.signal?.aborted)throw new T0;return this._addRun(V(this,B0,"m",g4).call(this))}toReadableStream(){return new g0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream($,w,W,Z){let X=new R1;return X._run(()=>X._runToolAssistantStream($,w,W,{...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"stream"}})),X}async _createToolAssistantStream($,w,W,Z){let X=Z?.signal;if(X){if(X.aborted)this.controller.abort();X.addEventListener("abort",()=>this.controller.abort())}let Y={...W,stream:!0},G=await $.submitToolOutputs(w,Y,{...Z,signal:this.controller.signal});this._connected();for await(let J of G)V(this,B0,"m",_4).call(this,J);if(G.controller.signal?.aborted)throw new T0;return this._addRun(V(this,B0,"m",g4).call(this))}static createThreadAssistantStream($,w,W){let Z=new R1;return Z._run(()=>Z._threadAssistantStream($,w,{...W,headers:{...W?.headers,"X-Stainless-Helper-Method":"stream"}})),Z}static createAssistantStream($,w,W,Z){let X=new R1;return X._run(()=>X._runAssistantStream($,w,W,{...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"stream"}})),X}currentEvent(){return V(this,e6,"f")}currentRun(){return V(this,$W,"f")}currentMessageSnapshot(){return V(this,e0,"f")}currentRunStepSnapshot(){return V(this,v4,"f")}async finalRunSteps(){return await this.done(),Object.values(V(this,Q$,"f"))}async finalMessages(){return await this.done(),Object.values(V(this,o6,"f"))}async finalRun(){if(await this.done(),!V(this,C1,"f"))throw Error("Final run was not received.");return V(this,C1,"f")}async _createThreadAssistantStream($,w,W){let Z=W?.signal;if(Z){if(Z.aborted)this.controller.abort();Z.addEventListener("abort",()=>this.controller.abort())}let X={...w,stream:!0},Y=await $.createAndRun(X,{...W,signal:this.controller.signal});this._connected();for await(let G of Y)V(this,B0,"m",_4).call(this,G);if(Y.controller.signal?.aborted)throw new T0;return this._addRun(V(this,B0,"m",g4).call(this))}async _createAssistantStream($,w,W,Z){let X=Z?.signal;if(X){if(X.aborted)this.controller.abort();X.addEventListener("abort",()=>this.controller.abort())}let Y={...W,stream:!0},G=await $.create(w,Y,{...Z,signal:this.controller.signal});this._connected();for await(let J of G)V(this,B0,"m",_4).call(this,J);if(G.controller.signal?.aborted)throw new T0;return this._addRun(V(this,B0,"m",g4).call(this))}static accumulateDelta($,w){for(let[W,Z]of Object.entries(w)){if(!$.hasOwnProperty(W)){$[W]=Z;continue}let X=$[W];if(X===null||X===void 0){$[W]=Z;continue}if(W==="index"||W==="type"){$[W]=Z;continue}if(typeof X==="string"&&typeof Z==="string")X+=Z;else if(typeof X==="number"&&typeof Z==="number")X+=Z;else if(B4(X)&&B4(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(!B4(Y))throw Error(`Expected array delta entry to be an object but got: ${Y}`);let G=Y.index;if(G==null)throw console.error(Y),Error("Expected array delta entry to have an `index` property");if(typeof G!=="number")throw Error(`Expected array delta entry \`index\` property to be a number but got ${G}`);let J=X[G];if(J==null)X.push(Y);else X[G]=this.accumulateDelta(J,Y)}continue}else throw Error(`Unhandled record type: ${W}, deltaValue: ${Z}, accValue: ${X}`);$[W]=X}return $}_addRun($){return $}async _threadAssistantStream($,w,W){return await this._createThreadAssistantStream(w,$,W)}async _runAssistantStream($,w,W,Z){return await this._createAssistantStream(w,$,W,Z)}async _runToolAssistantStream($,w,W,Z){return await this._createToolAssistantStream(w,$,W,Z)}}R1=o$,_4=function(w){if(this.ended)return;switch(C(this,e6,w,"f"),V(this,B0,"m",GM).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":V(this,B0,"m",MM).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":V(this,B0,"m",YM).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":V(this,B0,"m",XM).call(this,w);break;case"error":throw Error("Encountered an error event in event processing - errors should be processed earlier");default:bE(w)}},g4=function(){if(this.ended)throw new k("stream has ended, this shouldn't happen");if(!V(this,C1,"f"))throw Error("Final run has not been received");return V(this,C1,"f")},XM=function(w){let[W,Z]=V(this,B0,"m",TM).call(this,w,V(this,e0,"f"));C(this,e0,W,"f"),V(this,o6,"f")[W.id]=W;for(let X of Z){let Y=W.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,W),w.data.delta.content)for(let X of w.data.delta.content){if(X.type=="text"&&X.text){let Y=X.text,G=W.content[X.index];if(G&&G.type=="text")this._emit("textDelta",Y,G.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(X.index!=V(this,Ew,"f")){if(V(this,S1,"f"))switch(V(this,S1,"f").type){case"text":this._emit("textDone",V(this,S1,"f").text,V(this,e0,"f"));break;case"image_file":this._emit("imageFileDone",V(this,S1,"f").image_file,V(this,e0,"f"));break}C(this,Ew,X.index,"f")}C(this,S1,W.content[X.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(V(this,Ew,"f")!==void 0){let X=w.data.content[V(this,Ew,"f")];if(X)switch(X.type){case"image_file":this._emit("imageFileDone",X.image_file,V(this,e0,"f"));break;case"text":this._emit("textDone",X.text,V(this,e0,"f"));break}}if(V(this,e0,"f"))this._emit("messageDone",w.data);C(this,e0,void 0,"f")}},YM=function(w){let W=V(this,B0,"m",JM).call(this,w);switch(C(this,v4,W,"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&&W.step_details.type=="tool_calls")for(let Y of Z.step_details.tool_calls)if(Y.index==V(this,wW,"f"))this._emit("toolCallDelta",Y,W.step_details.tool_calls[Y.index]);else{if(V(this,h0,"f"))this._emit("toolCallDone",V(this,h0,"f"));if(C(this,wW,Y.index,"f"),C(this,h0,W.step_details.tool_calls[Y.index],"f"),V(this,h0,"f"))this._emit("toolCallCreated",V(this,h0,"f"))}this._emit("runStepDelta",w.data.delta,W);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":if(C(this,v4,void 0,"f"),w.data.step_details.type=="tool_calls"){if(V(this,h0,"f"))this._emit("toolCallDone",V(this,h0,"f")),C(this,h0,void 0,"f")}this._emit("runStepDone",w.data,W);break;case"thread.run.step.in_progress":break}},GM=function(w){V(this,M3,"f").push(w),this._emit("event",w)},JM=function(w){switch(w.event){case"thread.run.step.created":return V(this,Q$,"f")[w.data.id]=w.data,w.data;case"thread.run.step.delta":let W=V(this,Q$,"f")[w.data.id];if(!W)throw Error("Received a RunStepDelta before creation of a snapshot");let Z=w.data;if(Z.delta){let X=R1.accumulateDelta(W,Z.delta);V(this,Q$,"f")[w.data.id]=X}return V(this,Q$,"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":V(this,Q$,"f")[w.data.id]=w.data;break}if(V(this,Q$,"f")[w.data.id])return V(this,Q$,"f")[w.data.id];throw Error("No snapshot available")},TM=function(w,W){let Z=[];switch(w.event){case"thread.message.created":return[w.data,Z];case"thread.message.delta":if(!W)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 W.content){let G=W.content[Y.index];W.content[Y.index]=V(this,B0,"m",QM).call(this,Y,G)}else W.content[Y.index]=Y,Z.push(Y);return[W,Z];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(W)return[W,Z];else throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},QM=function(w,W){return R1.accumulateDelta(W,w)},MM=function(w){switch(C(this,$W,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,C1,w.data,"f"),V(this,h0,"f"))this._emit("toolCallDone",V(this,h0,"f")),C(this,h0,void 0,"f");break;case"thread.run.cancelling":break}};function bE($){}class Lw extends O{constructor(){super(...arguments);this.steps=new x4(this._client)}create($,w,W){let{include:Z,...X}=w;return this._client.post(U`/threads/${$}/runs`,{query:{include:Z},body:X,...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers]),stream:w.stream??!1})}retrieve($,w,W){let{thread_id:Z}=w;return this._client.get(U`/threads/${Z}/runs/${$}`,{...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}update($,w,W){let{thread_id:Z,...X}=w;return this._client.post(U`/threads/${Z}/runs/${$}`,{body:X,...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}list($,w={},W){return this._client.getAPIList(U`/threads/${$}/runs`,h,{query:w,...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}cancel($,w,W){let{thread_id:Z}=w;return this._client.post(U`/threads/${Z}/runs/${$}/cancel`,{...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}async createAndPoll($,w,W){let Z=await this.create($,w,W);return await this.poll(Z.id,{thread_id:$},W)}createAndStream($,w,W){return o$.createAssistantStream($,this._client.beta.threads.runs,w,W)}async poll($,w,W){let Z=D([W?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":W?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:X,response:Y}=await this.retrieve($,w,{...W,headers:{...W?.headers,...Z}}).withResponse();switch(X.status){case"queued":case"in_progress":case"cancelling":let G=5000;if(W?.pollIntervalMs)G=W.pollIntervalMs;else{let J=Y.headers.get("openai-poll-after-ms");if(J){let T=parseInt(J);if(!isNaN(T))G=T}}await J$(G);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return X}}}stream($,w,W){return o$.createAssistantStream($,this._client.beta.threads.runs,w,W)}submitToolOutputs($,w,W){let{thread_id:Z,...X}=w;return this._client.post(U`/threads/${Z}/runs/${$}/submit_tool_outputs`,{body:X,...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers]),stream:w.stream??!1})}async submitToolOutputsAndPoll($,w,W){let Z=await this.submitToolOutputs($,w,W);return await this.poll(Z.id,w,W)}submitToolOutputsStream($,w,W){return o$.createToolAssistantStream($,this._client.beta.threads.runs,w,W)}}Lw.Steps=x4;class j1 extends O{constructor(){super(...arguments);this.runs=new Lw(this._client),this.messages=new b4(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,W){return this._client.post(U`/threads/${$}`,{body:w,...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.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 W=await this.createAndRun($,w);return await this.runs.poll(W.id,{thread_id:W.thread_id},w)}createAndRunStream($,w){return o$.createThreadAssistantStream($,this._client.beta.threads,w)}}j1.Runs=Lw;j1.Messages=b4;class j$ extends O{constructor(){super(...arguments);this.realtime=new A1(this._client),this.assistants=new j4(this._client),this.threads=new j1(this._client)}}j$.Realtime=A1;j$.Assistants=j4;j$.Threads=j1;class Dw extends O{create($,w){return this._client.post("/completions",{body:$,...w,stream:$.stream??!1})}}class h4 extends O{retrieve($,w,W){let{container_id:Z}=w;return this._client.get(U`/containers/${Z}/files/${$}/content`,{...W,headers:D([{Accept:"application/binary"},W?.headers]),__binaryResponse:!0})}}class kw extends O{constructor(){super(...arguments);this.content=new h4(this._client)}create($,w,W){return this._client.post(U`/containers/${$}/files`,v0({body:w,...W},this._client))}retrieve($,w,W){let{container_id:Z}=w;return this._client.get(U`/containers/${Z}/files/${$}`,W)}list($,w={},W){return this._client.getAPIList(U`/containers/${$}/files`,h,{query:w,...W})}delete($,w,W){let{container_id:Z}=w;return this._client.delete(U`/containers/${Z}/files/${$}`,{...W,headers:D([{Accept:"*/*"},W?.headers])})}}kw.Content=h4;class y1 extends O{constructor(){super(...arguments);this.files=new kw(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])})}}y1.Files=kw;class u4 extends O{create($,w,W){let{include:Z,...X}=w;return this._client.post(U`/conversations/${$}/items`,{query:{include:Z},body:X,...W})}retrieve($,w,W){let{conversation_id:Z,...X}=w;return this._client.get(U`/conversations/${Z}/items/${$}`,{query:X,...W})}list($,w={},W){return this._client.getAPIList(U`/conversations/${$}/items`,nZ,{query:w,...W})}delete($,w,W){let{conversation_id:Z}=w;return this._client.delete(U`/conversations/${Z}/items/${$}`,W)}}class I1 extends O{constructor(){super(...arguments);this.items=new u4(this._client)}create($={},w){return this._client.post("/conversations",{body:$,...w})}retrieve($,w){return this._client.get(U`/conversations/${$}`,w)}update($,w,W){return this._client.post(U`/conversations/${$}`,{body:w,...W})}delete($,w){return this._client.delete(U`/conversations/${$}`,w)}}I1.Items=u4;class Aw extends O{create($,w){let W=!!$.encoding_format,Z=W?$.encoding_format:"base64";if(W)Z0(this._client).debug("embeddings/user defined encoding_format:",$.encoding_format);let X=this._client.post("/embeddings",{body:{...$,encoding_format:Z},...w});if(W)return X;return Z0(this._client).debug("embeddings/decoding base64 embeddings from base64"),X._thenUnwrap((Y)=>{if(Y&&Y.data)Y.data.forEach((G)=>{let J=G.embedding;G.embedding=ZM(J)});return Y})}}class i4 extends O{retrieve($,w,W){let{eval_id:Z,run_id:X}=w;return this._client.get(U`/evals/${Z}/runs/${X}/output_items/${$}`,W)}list($,w,W){let{eval_id:Z,...X}=w;return this._client.getAPIList(U`/evals/${Z}/runs/${$}/output_items`,h,{query:X,...W})}}class Sw extends O{constructor(){super(...arguments);this.outputItems=new i4(this._client)}create($,w,W){return this._client.post(U`/evals/${$}/runs`,{body:w,...W})}retrieve($,w,W){let{eval_id:Z}=w;return this._client.get(U`/evals/${Z}/runs/${$}`,W)}list($,w={},W){return this._client.getAPIList(U`/evals/${$}/runs`,h,{query:w,...W})}delete($,w,W){let{eval_id:Z}=w;return this._client.delete(U`/evals/${Z}/runs/${$}`,W)}cancel($,w,W){let{eval_id:Z}=w;return this._client.post(U`/evals/${Z}/runs/${$}`,W)}}Sw.OutputItems=i4;class b1 extends O{constructor(){super(...arguments);this.runs=new Sw(this._client)}create($,w){return this._client.post("/evals",{body:$,...w})}retrieve($,w){return this._client.get(U`/evals/${$}`,w)}update($,w,W){return this._client.post(U`/evals/${$}`,{body:w,...W})}list($={},w){return this._client.getAPIList("/evals",h,{query:$,...w})}delete($,w){return this._client.delete(U`/evals/${$}`,w)}}b1.Runs=Sw;class Rw extends O{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:W=1800000}={}){let Z=new Set(["processed","error","deleted"]),X=Date.now(),Y=await this.retrieve($);while(!Y.status||!Z.has(Y.status))if(await J$(w),Y=await this.retrieve($),Date.now()-X>W)throw new O1({message:`Giving up on waiting for file ${$} to finish processing after ${W} milliseconds.`});return Y}}class m4 extends O{}class l4 extends O{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 Cw extends O{constructor(){super(...arguments);this.graders=new l4(this._client)}}Cw.Graders=l4;class c4 extends O{create($,w,W){return this._client.getAPIList(U`/fine_tuning/checkpoints/${$}/permissions`,A$,{body:w,method:"post",...W})}retrieve($,w={},W){return this._client.get(U`/fine_tuning/checkpoints/${$}/permissions`,{query:w,...W})}delete($,w,W){let{fine_tuned_model_checkpoint:Z}=w;return this._client.delete(U`/fine_tuning/checkpoints/${Z}/permissions/${$}`,W)}}class jw extends O{constructor(){super(...arguments);this.permissions=new c4(this._client)}}jw.Permissions=c4;class d4 extends O{list($,w={},W){return this._client.getAPIList(U`/fine_tuning/jobs/${$}/checkpoints`,h,{query:w,...W})}}class yw extends O{constructor(){super(...arguments);this.checkpoints=new d4(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={},W){return this._client.getAPIList(U`/fine_tuning/jobs/${$}/events`,h,{query:w,...W})}pause($,w){return this._client.post(U`/fine_tuning/jobs/${$}/pause`,w)}resume($,w){return this._client.post(U`/fine_tuning/jobs/${$}/resume`,w)}}yw.Checkpoints=d4;class M$ extends O{constructor(){super(...arguments);this.methods=new m4(this._client),this.jobs=new yw(this._client),this.checkpoints=new jw(this._client),this.alpha=new Cw(this._client)}}M$.Methods=m4;M$.Jobs=yw;M$.Checkpoints=jw;M$.Alpha=Cw;class n4 extends O{}class x1 extends O{constructor(){super(...arguments);this.graderModels=new n4(this._client)}}x1.GraderModels=n4;class Iw extends O{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 bw extends O{retrieve($,w){return this._client.get(U`/models/${$}`,w)}list($){return this._client.getAPIList("/models",A$,$)}delete($,w){return this._client.delete(U`/models/${$}`,w)}}class xw extends O{create($,w){return this._client.post("/moderations",{body:$,...w})}}class p4 extends O{create($,w){return this._client.post("/realtime/client_secrets",{body:$,...w})}}class _1 extends O{constructor(){super(...arguments);this.clientSecrets=new p4(this._client)}}_1.ClientSecrets=p4;function zM($,w){if(!w||!oE(w))return{...$,output_parsed:null,output:$.output.map((W)=>{if(W.type==="function_call")return{...W,parsed_arguments:null};if(W.type==="message")return{...W,content:W.content.map((Z)=>({...Z,parsed:null}))};else return W})};return z3($,w)}function z3($,w){let W=$.output.map((X)=>{if(X.type==="function_call")return{...X,parsed_arguments:wL(w,X)};if(X.type==="message"){let Y=X.content.map((G)=>{if(G.type==="output_text")return{...G,parsed:aE(w,G.text)};return G});return{...X,content:Y}}return X}),Z=Object.assign({},$,{output:W});if(!Object.getOwnPropertyDescriptor($,"output_text"))WW(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 aE($,w){if($.text?.format?.type!=="json_schema")return null;if("$parseRaw"in $.text?.format)return($.text?.format).$parseRaw(w);return JSON.parse(w)}function oE($){if(H4($.text?.format))return!0;return!1}function eE($){return $?.$brand==="auto-parseable-tool"}function $L($,w){return $.find((W)=>W.type==="function"&&W.name===w)}function wL($,w){let W=$L($.tools??[],w.name);return{...w,...w,parsed_arguments:eE(W)?W.$parseRaw(w.arguments):W?.strict?JSON.parse(w.arguments):null}}function WW($){let w=[];for(let W of $.output){if(W.type!=="message")continue;for(let Z of W.content)if(Z.type==="output_text")w.push(Z.text)}$.output_text=w.join("")}var _w,ZW,e$,XW,NM,KM,BM,PM;class YW extends D1{constructor($){super();_w.add(this),ZW.set(this,void 0),e$.set(this,void 0),XW.set(this,void 0),C(this,ZW,$,"f")}static createResponse($,w,W){let Z=new YW(w);return Z._run(()=>Z._createOrRetrieveResponse($,w,{...W,headers:{...W?.headers,"X-Stainless-Helper-Method":"stream"}})),Z}async _createOrRetrieveResponse($,w,W){let Z=W?.signal;if(Z){if(Z.aborted)this.controller.abort();Z.addEventListener("abort",()=>this.controller.abort())}V(this,_w,"m",NM).call(this);let X,Y=null;if("response_id"in w)X=await $.responses.retrieve(w.response_id,{stream:!0},{...W,signal:this.controller.signal,stream:!0}),Y=w.starting_after??null;else X=await $.responses.create({...w,stream:!0},{...W,signal:this.controller.signal});this._connected();for await(let G of X)V(this,_w,"m",KM).call(this,G,Y);if(X.controller.signal?.aborted)throw new T0;return V(this,_w,"m",BM).call(this)}[(ZW=new WeakMap,e$=new WeakMap,XW=new WeakMap,_w=new WeakSet,NM=function(){if(this.ended)return;C(this,e$,void 0,"f")},KM=function(w,W){if(this.ended)return;let Z=(Y,G)=>{if(W==null||G.sequence_number>W)this._emit(Y,G)},X=V(this,_w,"m",PM).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 k(`missing output at index ${w.output_index}`);if(Y.type==="message"){let G=Y.content[w.content_index];if(!G)throw new k(`missing content at index ${w.content_index}`);if(G.type!=="output_text")throw new k(`expected content to be 'output_text', got ${G.type}`);Z("response.output_text.delta",{...w,snapshot:G.text})}break}case"response.function_call_arguments.delta":{let Y=X.output[w.output_index];if(!Y)throw new k(`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}},BM=function(){if(this.ended)throw new k("stream has ended, this shouldn't happen");let w=V(this,e$,"f");if(!w)throw new k("request ended without sending any events");C(this,e$,void 0,"f");let W=WL(w,V(this,ZW,"f"));return C(this,XW,W,"f"),W},PM=function(w){let W=V(this,e$,"f");if(!W){if(w.type!=="response.created")throw new k(`When snapshot hasn't been set yet, expected 'response.created' event, got ${w.type}`);return W=C(this,e$,w.response,"f"),W}switch(w.type){case"response.output_item.added":{W.output.push(w.item);break}case"response.content_part.added":{let Z=W.output[w.output_index];if(!Z)throw new k(`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=W.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}`);X.text+=w.delta}break}case"response.function_call_arguments.delta":{let Z=W.output[w.output_index];if(!Z)throw new k(`missing output at index ${w.output_index}`);if(Z.type==="function_call")Z.arguments+=w.delta;break}case"response.reasoning_text.delta":{let Z=W.output[w.output_index];if(!Z)throw new k(`missing output at index ${w.output_index}`);if(Z.type==="reasoning"){let X=Z.content?.[w.content_index];if(!X)throw new k(`missing content at index ${w.content_index}`);if(X.type!=="reasoning_text")throw new k(`expected content to be 'reasoning_text', got ${X.type}`);X.text+=w.delta}break}case"response.completed":{C(this,e$,w.response,"f");break}}return W},Symbol.asyncIterator)](){let $=[],w=[],W=!1;return this.on("event",(Z)=>{let X=w.shift();if(X)X.resolve(Z);else $.push(Z)}),this.on("end",()=>{W=!0;for(let Z of w)Z.resolve(void 0);w.length=0}),this.on("abort",(Z)=>{W=!0;for(let X of w)X.reject(Z);w.length=0}),this.on("error",(Z)=>{W=!0;for(let X of w)X.reject(Z);w.length=0}),{next:async()=>{if(!$.length){if(W)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 $=V(this,XW,"f");if(!$)throw new k("stream ended without producing a ChatCompletion");return $}}function WL($,w){return zM($,w)}class t4 extends O{list($,w={},W){return this._client.getAPIList(U`/responses/${$}/input_items`,h,{query:w,...W})}}class g1 extends O{constructor(){super(...arguments);this.inputItems=new t4(this._client)}create($,w){return this._client.post("/responses",{body:$,...w,stream:$.stream??!1})._thenUnwrap((W)=>{if("object"in W&&W.object==="response")WW(W);return W})}retrieve($,w={},W){return this._client.get(U`/responses/${$}`,{query:w,...W,stream:w?.stream??!1})._thenUnwrap((Z)=>{if("object"in Z&&Z.object==="response")WW(Z);return Z})}delete($,w){return this._client.delete(U`/responses/${$}`,{...w,headers:D([{Accept:"*/*"},w?.headers])})}parse($,w){return this._client.responses.create($,w)._thenUnwrap((W)=>z3(W,$))}stream($,w){return YW.createResponse(this._client,$,w)}cancel($,w){return this._client.post(U`/responses/${$}/cancel`,w)}}g1.InputItems=t4;class r4 extends O{create($,w,W){return this._client.post(U`/uploads/${$}/parts`,v0({body:w,...W},this._client))}}class v1 extends O{constructor(){super(...arguments);this.parts=new r4(this._client)}create($,w){return this._client.post("/uploads",{body:$,...w})}cancel($,w){return this._client.post(U`/uploads/${$}/cancel`,w)}complete($,w,W){return this._client.post(U`/uploads/${$}/complete`,{body:w,...W})}}v1.Parts=r4;var VM=async($)=>{let w=await Promise.allSettled($),W=w.filter((X)=>X.status==="rejected");if(W.length){for(let X of W)console.error(X.reason);throw Error(`${W.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 s4 extends O{create($,w,W){return this._client.post(U`/vector_stores/${$}/file_batches`,{body:w,...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}retrieve($,w,W){let{vector_store_id:Z}=w;return this._client.get(U`/vector_stores/${Z}/file_batches/${$}`,{...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}cancel($,w,W){let{vector_store_id:Z}=w;return this._client.post(U`/vector_stores/${Z}/file_batches/${$}/cancel`,{...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}async createAndPoll($,w,W){let Z=await this.create($,w);return await this.poll($,Z.id,W)}listFiles($,w,W){let{vector_store_id:Z,...X}=w;return this._client.getAPIList(U`/vector_stores/${Z}/file_batches/${$}/files`,h,{query:X,...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}async poll($,w,W){let Z=D([W?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":W?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:X,response:Y}=await this.retrieve(w,{vector_store_id:$},{...W,headers:Z}).withResponse();switch(X.status){case"in_progress":let G=5000;if(W?.pollIntervalMs)G=W.pollIntervalMs;else{let J=Y.headers.get("openai-poll-after-ms");if(J){let T=parseInt(J);if(!isNaN(T))G=T}}await J$(G);break;case"failed":case"cancelled":case"completed":return X}}}async uploadAndPoll($,{files:w,fileIds:W=[]},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),G=this._client,J=w.values(),T=[...W];async function Q(z){for(let N of z){let B=await G.files.create({file:N,purpose:"assistants"},Z);T.push(B.id)}}let M=Array(Y).fill(J).map(Q);return await VM(M),await this.createAndPoll($,{file_ids:T})}}class a4 extends O{create($,w,W){return this._client.post(U`/vector_stores/${$}/files`,{body:w,...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}retrieve($,w,W){let{vector_store_id:Z}=w;return this._client.get(U`/vector_stores/${Z}/files/${$}`,{...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}update($,w,W){let{vector_store_id:Z,...X}=w;return this._client.post(U`/vector_stores/${Z}/files/${$}`,{body:X,...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}list($,w={},W){return this._client.getAPIList(U`/vector_stores/${$}/files`,h,{query:w,...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}delete($,w,W){let{vector_store_id:Z}=w;return this._client.delete(U`/vector_stores/${Z}/files/${$}`,{...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}async createAndPoll($,w,W){let Z=await this.create($,w,W);return await this.poll($,Z.id,W)}async poll($,w,W){let Z=D([W?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":W?.pollIntervalMs?.toString()??void 0}]);while(!0){let X=await this.retrieve(w,{vector_store_id:$},{...W,headers:Z}).withResponse(),Y=X.data;switch(Y.status){case"in_progress":let G=5000;if(W?.pollIntervalMs)G=W.pollIntervalMs;else{let J=X.response.headers.get("openai-poll-after-ms");if(J){let T=parseInt(J);if(!isNaN(T))G=T}}await J$(G);break;case"failed":case"completed":return Y}}}async upload($,w,W){let Z=await this._client.files.create({file:w,purpose:"assistants"},W);return this.create($,{file_id:Z.id},W)}async uploadAndPoll($,w,W){let Z=await this.upload($,w,W);return await this.poll($,Z.id,W)}content($,w,W){let{vector_store_id:Z}=w;return this._client.getAPIList(U`/vector_stores/${Z}/files/${$}/content`,A$,{...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}}class $1 extends O{constructor(){super(...arguments);this.files=new a4(this._client),this.fileBatches=new s4(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,W){return this._client.post(U`/vector_stores/${$}`,{body:w,...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.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,W){return this._client.getAPIList(U`/vector_stores/${$}/search`,A$,{body:w,method:"post",...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}}$1.Files=a4;$1.FileBatches=s4;var gw,fM,GW;class vw extends O{constructor(){super(...arguments);gw.add(this)}async unwrap($,w,W=this._client.webhookSecret,Z=300){return await this.verifySignature($,w,W,Z),JSON.parse($)}async verifySignature($,w,W=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");V(this,gw,"m",fM).call(this,W);let X=D([w]).values,Y=V(this,gw,"m",GW).call(this,X,"webhook-signature"),G=V(this,gw,"m",GW).call(this,X,"webhook-timestamp"),J=V(this,gw,"m",GW).call(this,X,"webhook-id"),T=parseInt(G,10);if(isNaN(T))throw new D$("Invalid webhook timestamp format");let Q=Math.floor(Date.now()/1000);if(Q-T>Z)throw new D$("Webhook timestamp is too old");if(T>Q+Z)throw new D$("Webhook timestamp is too new");let M=Y.split(" ").map((K)=>K.startsWith("v1,")?K.substring(3):K),z=W.startsWith("whsec_")?Buffer.from(W.replace("whsec_",""),"base64"):Buffer.from(W,"utf-8"),N=J?`${J}.${G}.${$}`:`${G}.${$}`,B=await crypto.subtle.importKey("raw",z,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let K of M)try{let P=Buffer.from(K,"base64");if(await crypto.subtle.verify("HMAC",B,P,new TextEncoder().encode(N)))return}catch{continue}throw new D$("The given webhook signature does not match the expected signature")}}gw=new WeakSet,fM=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")},GW=function(w,W){if(!w)throw Error("Headers are required");let Z=w.get(W);if(Z===null||Z===void 0)throw Error(`Missing required header: ${W}`);return Z};var N3,K3,JW,qM;class _{constructor({baseURL:$=a$("OPENAI_BASE_URL"),apiKey:w=a$("OPENAI_API_KEY"),organization:W=a$("OPENAI_ORG_ID")??null,project:Z=a$("OPENAI_PROJECT_ID")??null,webhookSecret:X=a$("OPENAI_WEBHOOK_SECRET")??null,...Y}={}){if(N3.add(this),JW.set(this,void 0),this.completions=new Dw(this),this.chat=new k1(this),this.embeddings=new Aw(this),this.files=new Rw(this),this.images=new Iw(this),this.audio=new C$(this),this.moderations=new xw(this),this.models=new bw(this),this.fineTuning=new M$(this),this.graders=new x1(this),this.vectorStores=new $1(this),this.webhooks=new vw(this),this.beta=new j$(this),this.batches=new Ow(this),this.uploads=new v1(this),this.responses=new g1(this),this.realtime=new _1(this),this.conversations=new I1(this),this.evals=new b1(this),this.containers=new y1(this),w===void 0)throw new k("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");let G={apiKey:w,organization:W,project:Z,webhookSecret:X,...Y,baseURL:$||"https://api.openai.com/v1"};if(!G.dangerouslyAllowBrowser&&OQ())throw new k(`It looks like you're running in a browser-like environment.
182
+ ${z}`)}return G},U=BE(lQ);class fw extends O{list($,w={},W){return this._client.getAPIList(U`/chat/completions/${$}/messages`,u,{query:w,...W})}}function H9($){return $!==void 0&&"function"in $&&$.function!==void 0}function F9($){return $?.$brand==="auto-parseable-response-format"}function L1($){return $?.$brand==="auto-parseable-tool"}function cQ($,w){if(!w||!aZ(w))return{...$,choices:$.choices.map((W)=>{return nQ(W.message.tool_calls),{...W,message:{...W.message,parsed:null,...W.message.tool_calls?{tool_calls:W.message.tool_calls}:void 0}}})};return O9($,w)}function O9($,w){let W=$.choices.map((Z)=>{if(Z.finish_reason==="length")throw new K9;if(Z.finish_reason==="content_filter")throw new B9;return nQ(Z.message.tool_calls),{...Z,message:{...Z.message,...Z.message.tool_calls?{tool_calls:Z.message.tool_calls?.map((X)=>qE(w,X))??void 0}:void 0,parsed:Z.message.content&&!Z.message.refusal?fE(w,Z.message.content):null}}});return{...$,choices:W}}function fE($,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 qE($,w){let W=$.tools?.find((Z)=>H9(Z)&&Z.function?.name===w.function.name);return{...w,function:{...w.function,parsed_arguments:L1(W)?W.$parseRaw(w.function.arguments):W?.function.strict?JSON.parse(w.function.arguments):null}}}function dQ($,w){if(!$||!("tools"in $)||!$.tools)return!1;let W=$.tools?.find((Z)=>H9(Z)&&Z.function?.name===w.function.name);return H9(W)&&(L1(W)||W?.function.strict||!1)}function aZ($){if(F9($.response_format))return!0;return $.tools?.some((w)=>L1(w)||w.type==="function"&&w.function.strict===!0)??!1}function nQ($){for(let w of $||[])if(w.type!=="function")throw new k(`Currently only \`function\` tool calls are supported; Received \`${w.type}\``)}function pQ($){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 qw=($)=>{return $?.role==="assistant"},oZ=($)=>{return $?.role==="tool"};var eZ,c6,d6,E9,L9,n6,D9,S$,k9,p6,t6,Uw,tQ;class D1{constructor(){eZ.add(this),this.controller=new AbortController,c6.set(this,void 0),d6.set(this,()=>{}),E9.set(this,()=>{}),L9.set(this,void 0),n6.set(this,()=>{}),D9.set(this,()=>{}),S$.set(this,{}),k9.set(this,!1),p6.set(this,!1),t6.set(this,!1),Uw.set(this,!1),C(this,c6,new Promise(($,w)=>{C(this,d6,$,"f"),C(this,E9,w,"f")}),"f"),C(this,L9,new Promise(($,w)=>{C(this,n6,$,"f"),C(this,D9,w,"f")}),"f"),V(this,c6,"f").catch(()=>{}),V(this,L9,"f").catch(()=>{})}_run($){setTimeout(()=>{$().then(()=>{this._emitFinal(),this._emit("end")},V(this,eZ,"m",tQ).bind(this))},0)}_connected(){if(this.ended)return;V(this,d6,"f").call(this),this._emit("connect")}get ended(){return V(this,k9,"f")}get errored(){return V(this,p6,"f")}get aborted(){return V(this,t6,"f")}abort(){this.controller.abort()}on($,w){return(V(this,S$,"f")[$]||(V(this,S$,"f")[$]=[])).push({listener:w}),this}off($,w){let W=V(this,S$,"f")[$];if(!W)return this;let Z=W.findIndex((X)=>X.listener===w);if(Z>=0)W.splice(Z,1);return this}once($,w){return(V(this,S$,"f")[$]||(V(this,S$,"f")[$]=[])).push({listener:w,once:!0}),this}emitted($){return new Promise((w,W)=>{if(C(this,Uw,!0,"f"),$!=="error")this.once("error",W);this.once($,w)})}async done(){C(this,Uw,!0,"f"),await V(this,L9,"f")}_emit($,...w){if(V(this,k9,"f"))return;if($==="end")C(this,k9,!0,"f"),V(this,n6,"f").call(this);let W=V(this,S$,"f")[$];if(W)V(this,S$,"f")[$]=W.filter((Z)=>!Z.once),W.forEach(({listener:Z})=>Z(...w));if($==="abort"){let Z=w[0];if(!V(this,Uw,"f")&&!W?.length)Promise.reject(Z);V(this,E9,"f").call(this,Z),V(this,D9,"f").call(this,Z),this._emit("end");return}if($==="error"){let Z=w[0];if(!V(this,Uw,"f")&&!W?.length)Promise.reject(Z);V(this,E9,"f").call(this,Z),V(this,D9,"f").call(this,Z),this._emit("end")}}_emitFinal(){}}c6=new WeakMap,d6=new WeakMap,E9=new WeakMap,L9=new WeakMap,n6=new WeakMap,D9=new WeakMap,S$=new WeakMap,k9=new WeakMap,p6=new WeakMap,t6=new WeakMap,Uw=new WeakMap,eZ=new WeakSet,tQ=function(w){if(C(this,p6,!0,"f"),w instanceof Error&&w.name==="AbortError")w=new T0;if(w instanceof T0)return C(this,t6,!0,"f"),this._emit("abort",w);if(w instanceof k)return this._emit("error",w);if(w instanceof Error){let W=new k(w.message);return W.cause=w,this._emit("error",W)}return this._emit("error",new k(String(w)))};function rQ($){return typeof $.parse==="function"}var L0,$X,r6,wX,WX,ZX,sQ,aQ,UE=10;class A9 extends D1{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",$),oZ($)&&$.content)this._emit("functionToolCallResult",$.content);else if(qw($)&&$.tool_calls){for(let W of $.tool_calls)if(W.type==="function")this._emit("functionToolCall",W.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(),V(this,L0,"m",$X).call(this)}async finalMessage(){return await this.done(),V(this,L0,"m",r6).call(this)}async finalFunctionToolCall(){return await this.done(),V(this,L0,"m",wX).call(this)}async finalFunctionToolCallResult(){return await this.done(),V(this,L0,"m",WX).call(this)}async totalUsage(){return await this.done(),V(this,L0,"m",ZX).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let $=this._chatCompletions[this._chatCompletions.length-1];if($)this._emit("finalChatCompletion",$);let w=V(this,L0,"m",r6).call(this);if(w)this._emit("finalMessage",w);let W=V(this,L0,"m",$X).call(this);if(W)this._emit("finalContent",W);let Z=V(this,L0,"m",wX).call(this);if(Z)this._emit("finalFunctionToolCall",Z);let X=V(this,L0,"m",WX).call(this);if(X!=null)this._emit("finalFunctionToolCallResult",X);if(this._chatCompletions.some((Y)=>Y.usage))this._emit("totalUsage",V(this,L0,"m",ZX).call(this))}async _createChatCompletion($,w,W){let Z=W?.signal;if(Z){if(Z.aborted)this.controller.abort();Z.addEventListener("abort",()=>this.controller.abort())}V(this,L0,"m",sQ).call(this,w);let X=await $.chat.completions.create({...w,stream:!1},{...W,signal:this.controller.signal});return this._connected(),this._addChatCompletion(O9(X,w))}async _runChatCompletion($,w,W){for(let Z of w.messages)this._addMessage(Z,!1);return await this._createChatCompletion($,w,W)}async _runTools($,w,W){let{tool_choice:X="auto",stream:Y,...G}=w,J=typeof X!=="string"&&X.type==="function"&&X?.function?.name,{maxChatCompletions:T=UE}=W||{},Q=w.tools.map((N)=>{if(L1(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}),M={};for(let N of Q)if(N.type==="function")M[N.function.name||N.function.function.name]=N.function;let z="tools"in w?Q.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($,{...G,tool_choice:X,tools:z,messages:[...this.messages]},W)).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:f,arguments:H}=P.function,E=M[f];if(!E){let g=`Invalid tool_call: ${JSON.stringify(f)}. Available options are: ${Object.keys(M).map((s)=>JSON.stringify(s)).join(", ")}. Please try again`;this._addMessage({role:"tool",tool_call_id:q,content:g});continue}else if(J&&J!==f){let g=`Invalid tool_call: ${JSON.stringify(f)}. ${JSON.stringify(J)} requested. Please try again`;this._addMessage({role:"tool",tool_call_id:q,content:g});continue}let S;try{S=rQ(E)?await E.parse(H):H}catch(g){let s=g instanceof Error?g.message:String(g);this._addMessage({role:"tool",tool_call_id:q,content:s});continue}let A=await E.function(S,this),j=V(this,L0,"m",aQ).call(this,A);if(this._addMessage({role:"tool",tool_call_id:q,content:j}),J)return}}return}}L0=new WeakSet,$X=function(){return V(this,L0,"m",r6).call(this).content??null},r6=function(){let w=this.messages.length;while(w-- >0){let W=this.messages[w];if(qw(W))return{...W,content:W.content??null,refusal:W.refusal??null}}throw new k("stream ended without producing a ChatCompletionMessage with role=assistant")},wX=function(){for(let w=this.messages.length-1;w>=0;w--){let W=this.messages[w];if(qw(W)&&W?.tool_calls?.length)return W.tool_calls.filter((Z)=>Z.type==="function").at(-1)?.function}return},WX=function(){for(let w=this.messages.length-1;w>=0;w--){let W=this.messages[w];if(oZ(W)&&W.content!=null&&typeof W.content==="string"&&this.messages.some((Z)=>Z.role==="assistant"&&Z.tool_calls?.some((X)=>X.type==="function"&&X.id===W.tool_call_id)))return W.content}return},ZX=function(){let w={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:W}of this._chatCompletions)if(W)w.completion_tokens+=W.completion_tokens,w.prompt_tokens+=W.prompt_tokens,w.total_tokens+=W.total_tokens;return w},sQ=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.")},aQ=function(w){return typeof w==="string"?w:w===void 0?"undefined":JSON.stringify(w)};class S9 extends A9{static runTools($,w,W){let Z=new S9,X={...W,headers:{...W?.headers,"X-Stainless-Helper-Method":"runTools"}};return Z._run(()=>Z._runTools($,w,X)),Z}_addMessage($,w=!0){if(super._addMessage($,w),qw($)&&$.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 oQ extends Error{}class eQ extends Error{}function HE($,w=N0.ALL){if(typeof $!=="string")throw TypeError(`expecting str, got ${typeof $}`);if(!$.trim())throw Error(`${$} is empty`);return FE($.trim(),w)}var FE=($,w)=>{let W=$.length,Z=0,X=(N)=>{throw new oQ(`${N} at position ${Z}`)},Y=(N)=>{throw new eQ(`${N} at position ${Z}`)},G=()=>{if(z(),Z>=W)X("Unexpected end of input");if($[Z]==='"')return J();if($[Z]==="{")return T();if($[Z]==="[")return Q();if($.substring(Z,Z+4)==="null"||N0.NULL&w&&W-Z<4&&"null".startsWith($.substring(Z)))return Z+=4,null;if($.substring(Z,Z+4)==="true"||N0.BOOL&w&&W-Z<4&&"true".startsWith($.substring(Z)))return Z+=4,!0;if($.substring(Z,Z+5)==="false"||N0.BOOL&w&&W-Z<5&&"false".startsWith($.substring(Z)))return Z+=5,!1;if($.substring(Z,Z+8)==="Infinity"||N0.INFINITY&w&&W-Z<8&&"Infinity".startsWith($.substring(Z)))return Z+=8,1/0;if($.substring(Z,Z+9)==="-Infinity"||N0.MINUS_INFINITY&w&&1<W-Z&&W-Z<9&&"-Infinity".startsWith($.substring(Z)))return Z+=9,-1/0;if($.substring(Z,Z+3)==="NaN"||N0.NAN&w&&W-Z<3&&"NaN".startsWith($.substring(Z)))return Z+=3,NaN;return M()},J=()=>{let N=Z,B=!1;Z++;while(Z<W&&($[Z]!=='"'||B&&$[Z-1]==="\\"))B=$[Z]==="\\"?!B:!1,Z++;if($.charAt(Z)=='"')try{return JSON.parse($.substring(N,++Z-Number(B)))}catch(K){Y(String(K))}else if(N0.STR&w)try{return JSON.parse($.substring(N,Z-Number(B))+'"')}catch(K){return JSON.parse($.substring(N,$.lastIndexOf("\\"))+'"')}X("Unterminated string literal")},T=()=>{Z++,z();let N={};try{while($[Z]!=="}"){if(z(),Z>=W&&N0.OBJ&w)return N;let B=J();z(),Z++;try{let K=G();Object.defineProperty(N,B,{value:K,writable:!0,enumerable:!0,configurable:!0})}catch(K){if(N0.OBJ&w)return N;else throw K}if(z(),$[Z]===",")Z++}}catch(B){if(N0.OBJ&w)return N;else X("Expected '}' at end of object")}return Z++,N},Q=()=>{Z++;let N=[];try{while($[Z]!=="]")if(N.push(G()),z(),$[Z]===",")Z++}catch(B){if(N0.ARR&w)return N;X("Expected ']' at end of array")}return Z++,N},M=()=>{if(Z===0){if($==="-"&&N0.NUM&w)X("Not sure what '-' is");try{return JSON.parse($)}catch(B){if(N0.NUM&w)try{if($[$.length-1]===".")return JSON.parse($.substring(0,$.lastIndexOf(".")));return JSON.parse($.substring(0,$.lastIndexOf("e")))}catch(K){}Y(String(B))}}let N=Z;if($[Z]==="-")Z++;while($[Z]&&!",]}".includes($[Z]))Z++;if(Z==W&&!(N0.NUM&w))X("Unterminated number literal");try{return JSON.parse($.substring(N,Z))}catch(B){if($.substring(N,Z)==="-"&&N0.NUM&w)X("Not sure what '-' is");try{return JSON.parse($.substring(N,$.lastIndexOf("e")))}catch(K){Y(String(K))}}},z=()=>{while(Z<W&&`
183
+ \r `.includes($[Z]))Z++};return G()},XX=($)=>HE($,N0.ALL^N0.NUM);var M0,R$,Hw,t$,YX,s6,GX,JX,TX,a6,QX,$M;class r$ extends A9{constructor($){super();M0.add(this),R$.set(this,void 0),Hw.set(this,void 0),t$.set(this,void 0),C(this,R$,$,"f"),C(this,Hw,[],"f")}get currentChatCompletionSnapshot(){return V(this,t$,"f")}static fromReadableStream($){let w=new r$(null);return w._run(()=>w._fromReadableStream($)),w}static createChatCompletion($,w,W){let Z=new r$(w);return Z._run(()=>Z._runChatCompletion($,{...w,stream:!0},{...W,headers:{...W?.headers,"X-Stainless-Helper-Method":"stream"}})),Z}async _createChatCompletion($,w,W){super._createChatCompletion;let Z=W?.signal;if(Z){if(Z.aborted)this.controller.abort();Z.addEventListener("abort",()=>this.controller.abort())}V(this,M0,"m",YX).call(this);let X=await $.chat.completions.create({...w,stream:!0},{...W,signal:this.controller.signal});this._connected();for await(let Y of X)V(this,M0,"m",GX).call(this,Y);if(X.controller.signal?.aborted)throw new T0;return this._addChatCompletion(V(this,M0,"m",a6).call(this))}async _fromReadableStream($,w){let W=w?.signal;if(W){if(W.aborted)this.controller.abort();W.addEventListener("abort",()=>this.controller.abort())}V(this,M0,"m",YX).call(this),this._connected();let Z=g0.fromReadableStream($,this.controller),X;for await(let Y of Z){if(X&&X!==Y.id)this._addChatCompletion(V(this,M0,"m",a6).call(this));V(this,M0,"m",GX).call(this,Y),X=Y.id}if(Z.controller.signal?.aborted)throw new T0;return this._addChatCompletion(V(this,M0,"m",a6).call(this))}[(R$=new WeakMap,Hw=new WeakMap,t$=new WeakMap,M0=new WeakSet,YX=function(){if(this.ended)return;C(this,t$,void 0,"f")},s6=function(w){let W=V(this,Hw,"f")[w.index];if(W)return W;return W={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},V(this,Hw,"f")[w.index]=W,W},GX=function(w){if(this.ended)return;let W=V(this,M0,"m",$M).call(this,w);this._emit("chunk",w,W);for(let Z of w.choices){let X=W.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=V(this,M0,"m",s6).call(this,X);if(X.finish_reason){if(V(this,M0,"m",TX).call(this,X),Y.current_tool_call_index!=null)V(this,M0,"m",JX).call(this,X,Y.current_tool_call_index)}for(let G of Z.delta.tool_calls??[]){if(Y.current_tool_call_index!==G.index){if(V(this,M0,"m",TX).call(this,X),Y.current_tool_call_index!=null)V(this,M0,"m",JX).call(this,X,Y.current_tool_call_index)}Y.current_tool_call_index=G.index}for(let G of Z.delta.tool_calls??[]){let J=X.message.tool_calls?.[G.index];if(!J?.type)continue;if(J?.type==="function")this._emit("tool_calls.function.arguments.delta",{name:J.function?.name,index:G.index,arguments:J.function.arguments,parsed_arguments:J.function.parsed_arguments,arguments_delta:G.function?.arguments??""});else WM(J?.type)}}},JX=function(w,W){if(V(this,M0,"m",s6).call(this,w).done_tool_calls.has(W))return;let X=w.message.tool_calls?.[W];if(!X)throw Error("no tool call snapshot");if(!X.type)throw Error("tool call snapshot missing `type`");if(X.type==="function"){let Y=V(this,R$,"f")?.tools?.find((G)=>H9(G)&&G.function.name===X.function.name);this._emit("tool_calls.function.arguments.done",{name:X.function.name,index:W,arguments:X.function.arguments,parsed_arguments:L1(Y)?Y.$parseRaw(X.function.arguments):Y?.function.strict?JSON.parse(X.function.arguments):null})}else WM(X.type)},TX=function(w){let W=V(this,M0,"m",s6).call(this,w);if(w.message.content&&!W.content_done){W.content_done=!0;let Z=V(this,M0,"m",QX).call(this);this._emit("content.done",{content:w.message.content,parsed:Z?Z.$parseRaw(w.message.content):null})}if(w.message.refusal&&!W.refusal_done)W.refusal_done=!0,this._emit("refusal.done",{refusal:w.message.refusal});if(w.logprobs?.content&&!W.logprobs_content_done)W.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:w.logprobs.content});if(w.logprobs?.refusal&&!W.logprobs_refusal_done)W.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:w.logprobs.refusal})},a6=function(){if(this.ended)throw new k("stream has ended, this shouldn't happen");let w=V(this,t$,"f");if(!w)throw new k("request ended without sending any chunks");return C(this,t$,void 0,"f"),C(this,Hw,[],"f"),OE(w,V(this,R$,"f"))},QX=function(){let w=V(this,R$,"f")?.response_format;if(F9(w))return w;return null},$M=function(w){var W,Z,X,Y;let G=V(this,t$,"f"),{choices:J,...T}=w;if(!G)G=C(this,t$,{...T,choices:[]},"f");else Object.assign(G,T);for(let{delta:Q,finish_reason:M,index:z,logprobs:N=null,...B}of w.choices){let K=G.choices[z];if(!K)K=G.choices[z]={finish_reason:M,index:z,message:{},logprobs:N,...B};if(N)if(!K.logprobs)K.logprobs=Object.assign({},N);else{let{content:A,refusal:j,...g}=N;if(wM(g),Object.assign(K.logprobs,g),A)(W=K.logprobs).content??(W.content=[]),K.logprobs.content.push(...A);if(j)(Z=K.logprobs).refusal??(Z.refusal=[]),K.logprobs.refusal.push(...j)}if(M){if(K.finish_reason=M,V(this,R$,"f")&&aZ(V(this,R$,"f"))){if(M==="length")throw new K9;if(M==="content_filter")throw new B9}}if(Object.assign(K,B),!Q)continue;let{content:P,refusal:q,function_call:f,role:H,tool_calls:E,...S}=Q;if(wM(S),Object.assign(K.message,S),q)K.message.refusal=(K.message.refusal||"")+q;if(H)K.message.role=H;if(f)if(!K.message.function_call)K.message.function_call=f;else{if(f.name)K.message.function_call.name=f.name;if(f.arguments)(X=K.message.function_call).arguments??(X.arguments=""),K.message.function_call.arguments+=f.arguments}if(P){if(K.message.content=(K.message.content||"")+P,!K.message.refusal&&V(this,M0,"m",QX).call(this))K.message.parsed=XX(K.message.content)}if(E){if(!K.message.tool_calls)K.message.tool_calls=[];for(let{index:A,id:j,type:g,function:s,...e}of E){let i=(Y=K.message.tool_calls)[A]??(Y[A]={});if(Object.assign(i,e),j)i.id=j;if(g)i.type=g;if(s)i.function??(i.function={name:s.name??"",arguments:""});if(s?.name)i.function.name=s.name;if(s?.arguments){if(i.function.arguments+=s.arguments,dQ(V(this,R$,"f"),i))i.function.parsed_arguments=XX(i.function.arguments)}}}}return G},Symbol.asyncIterator)](){let $=[],w=[],W=!1;return this.on("chunk",(Z)=>{let X=w.shift();if(X)X.resolve(Z);else $.push(Z)}),this.on("end",()=>{W=!0;for(let Z of w)Z.resolve(void 0);w.length=0}),this.on("abort",(Z)=>{W=!0;for(let X of w)X.reject(Z);w.length=0}),this.on("error",(Z)=>{W=!0;for(let X of w)X.reject(Z);w.length=0}),{next:async()=>{if(!$.length){if(W)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 g0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function OE($,w){let{id:W,choices:Z,created:X,model:Y,system_fingerprint:G,...J}=$,T={...J,id:W,choices:Z.map(({message:Q,finish_reason:M,index:z,logprobs:N,...B})=>{if(!M)throw new k(`missing finish_reason for choice ${z}`);let{content:K=null,function_call:P,tool_calls:q,...f}=Q,H=Q.role;if(!H)throw new k(`missing role for choice ${z}`);if(P){let{arguments:E,name:S}=P;if(E==null)throw new k(`missing function_call.arguments for choice ${z}`);if(!S)throw new k(`missing function_call.name for choice ${z}`);return{...B,message:{content:K,function_call:{arguments:E,name:S},role:H,refusal:Q.refusal??null},finish_reason:M,index:z,logprobs:N}}if(q)return{...B,index:z,finish_reason:M,logprobs:N,message:{...f,role:H,content:K,refusal:Q.refusal??null,tool_calls:q.map((E,S)=>{let{function:A,type:j,id:g,...s}=E,{arguments:e,name:i,...F0}=A||{};if(g==null)throw new k(`missing choices[${z}].tool_calls[${S}].id
184
+ ${o6($)}`);if(j==null)throw new k(`missing choices[${z}].tool_calls[${S}].type
185
+ ${o6($)}`);if(i==null)throw new k(`missing choices[${z}].tool_calls[${S}].function.name
186
+ ${o6($)}`);if(e==null)throw new k(`missing choices[${z}].tool_calls[${S}].function.arguments
187
+ ${o6($)}`);return{...s,id:g,type:j,function:{...F0,name:i,arguments:e}}})}};return{...B,message:{...f,content:K,role:H,refusal:Q.refusal??null},finish_reason:M,index:z,logprobs:N}}),created:X,model:Y,object:"chat.completion",...G?{system_fingerprint:G}:{}};return cQ(T,w)}function o6($){return JSON.stringify($)}function wM($){return}function WM($){}class Fw extends r${static fromReadableStream($){let w=new Fw(null);return w._run(()=>w._fromReadableStream($)),w}static runTools($,w,W){let Z=new Fw(w),X={...W,headers:{...W?.headers,"X-Stainless-Helper-Method":"runTools"}};return Z._run(()=>Z._runTools($,w,X)),Z}}class s$ extends O{constructor(){super(...arguments);this.messages=new fw(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,W){return this._client.post(U`/chat/completions/${$}`,{body:w,...W})}list($={},w){return this._client.getAPIList("/chat/completions",u,{query:$,...w})}delete($,w){return this._client.delete(U`/chat/completions/${$}`,w)}parse($,w){return pQ($.tools),this._client.chat.completions.create($,{...w,headers:{...w?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap((W)=>O9(W,$))}runTools($,w){if($.stream)return Fw.runTools(this._client,$,w);return S9.runTools(this._client,$,w)}stream($,w){return r$.createChatCompletion(this._client,$,w)}}s$.Messages=fw;class k1 extends O{constructor(){super(...arguments);this.completions=new s$(this._client)}}k1.Completions=s$;var ZM=Symbol("brand.privateNullableHeaders");function*LE($){if(!$)return;if(ZM in $){let{values:Z,nulls:X}=$;yield*Z.entries();for(let Y of X)yield[Y,null];return}let w=!1,W;if($ instanceof Headers)W=$.entries();else if(IZ($))W=$;else w=!0,W=Object.entries($??{});for(let Z of W){let X=Z[0];if(typeof X!=="string")throw TypeError("expected header name to be a string");let Y=IZ(Z[1])?Z[1]:[Z[1]],G=!1;for(let J of Y){if(J===void 0)continue;if(w&&!G)G=!0,yield[X,null];yield[X,J]}}}var D=($)=>{let w=new Headers,W=new Set;for(let Z of $){let X=new Set;for(let[Y,G]of LE(Z)){let J=Y.toLowerCase();if(!X.has(J))w.delete(Y),X.add(J);if(G===null)w.delete(Y),W.add(J);else w.append(Y,G),W.delete(J)}}return{[ZM]:!0,values:w,nulls:W}};class R9 extends O{create($,w){return this._client.post("/audio/speech",{body:$,...w,headers:D([{Accept:"application/octet-stream"},w?.headers]),__binaryResponse:!0})}}class C9 extends O{create($,w){return this._client.post("/audio/transcriptions",v0({body:$,...w,stream:$.stream??!1,__metadata:{model:$.model}},this._client))}}class j9 extends O{create($,w){return this._client.post("/audio/translations",v0({body:$,...w,__metadata:{model:$.model}},this._client))}}class C$ extends O{constructor(){super(...arguments);this.transcriptions=new C9(this._client),this.translations=new j9(this._client),this.speech=new R9(this._client)}}C$.Transcriptions=C9;C$.Translations=j9;C$.Speech=R9;class Ow extends O{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",u,{query:$,...w})}cancel($,w){return this._client.post(U`/batches/${$}/cancel`,w)}}class y9 extends O{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,W){return this._client.post(U`/assistants/${$}`,{body:w,...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}list($={},w){return this._client.getAPIList("/assistants",u,{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 I9 extends O{create($,w){return this._client.post("/realtime/sessions",{body:$,...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}}class b9 extends O{create($,w){return this._client.post("/realtime/transcription_sessions",{body:$,...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}}class A1 extends O{constructor(){super(...arguments);this.sessions=new I9(this._client),this.transcriptionSessions=new b9(this._client)}}A1.Sessions=I9;A1.TranscriptionSessions=b9;class x9 extends O{create($,w,W){return this._client.post(U`/threads/${$}/messages`,{body:w,...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}retrieve($,w,W){let{thread_id:Z}=w;return this._client.get(U`/threads/${Z}/messages/${$}`,{...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}update($,w,W){let{thread_id:Z,...X}=w;return this._client.post(U`/threads/${Z}/messages/${$}`,{body:X,...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}list($,w={},W){return this._client.getAPIList(U`/threads/${$}/messages`,u,{query:w,...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}delete($,w,W){let{thread_id:Z}=w;return this._client.delete(U`/threads/${Z}/messages/${$}`,{...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}}class _9 extends O{retrieve($,w,W){let{thread_id:Z,run_id:X,...Y}=w;return this._client.get(U`/threads/${Z}/runs/${X}/steps/${$}`,{query:Y,...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}list($,w,W){let{thread_id:Z,...X}=w;return this._client.getAPIList(U`/threads/${Z}/runs/${$}/steps`,u,{query:X,...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}}var XM=($)=>{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($),W=w.length,Z=new Uint8Array(W);for(let X=0;X<W;X++)Z[X]=w.charCodeAt(X);return Array.from(new Float32Array(Z.buffer))}};var a$=($)=>{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 B0,R1,MX,Q$,e6,$$,C1,Ew,S1,WW,u0,$W,wW,u9,g9,v9,YM,GM,JM,TM,QM,MM,zM;class o$ extends D1{constructor(){super(...arguments);B0.add(this),MX.set(this,[]),Q$.set(this,{}),e6.set(this,{}),$$.set(this,void 0),C1.set(this,void 0),Ew.set(this,void 0),S1.set(this,void 0),WW.set(this,void 0),u0.set(this,void 0),$W.set(this,void 0),wW.set(this,void 0),u9.set(this,void 0)}[(MX=new WeakMap,Q$=new WeakMap,e6=new WeakMap,$$=new WeakMap,C1=new WeakMap,Ew=new WeakMap,S1=new WeakMap,WW=new WeakMap,u0=new WeakMap,$W=new WeakMap,wW=new WeakMap,u9=new WeakMap,B0=new WeakSet,Symbol.asyncIterator)](){let $=[],w=[],W=!1;return this.on("event",(Z)=>{let X=w.shift();if(X)X.resolve(Z);else $.push(Z)}),this.on("end",()=>{W=!0;for(let Z of w)Z.resolve(void 0);w.length=0}),this.on("abort",(Z)=>{W=!0;for(let X of w)X.reject(Z);w.length=0}),this.on("error",(Z)=>{W=!0;for(let X of w)X.reject(Z);w.length=0}),{next:async()=>{if(!$.length){if(W)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 R1;return w._run(()=>w._fromReadableStream($)),w}async _fromReadableStream($,w){let W=w?.signal;if(W){if(W.aborted)this.controller.abort();W.addEventListener("abort",()=>this.controller.abort())}this._connected();let Z=g0.fromReadableStream($,this.controller);for await(let X of Z)V(this,B0,"m",g9).call(this,X);if(Z.controller.signal?.aborted)throw new T0;return this._addRun(V(this,B0,"m",v9).call(this))}toReadableStream(){return new g0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream($,w,W,Z){let X=new R1;return X._run(()=>X._runToolAssistantStream($,w,W,{...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"stream"}})),X}async _createToolAssistantStream($,w,W,Z){let X=Z?.signal;if(X){if(X.aborted)this.controller.abort();X.addEventListener("abort",()=>this.controller.abort())}let Y={...W,stream:!0},G=await $.submitToolOutputs(w,Y,{...Z,signal:this.controller.signal});this._connected();for await(let J of G)V(this,B0,"m",g9).call(this,J);if(G.controller.signal?.aborted)throw new T0;return this._addRun(V(this,B0,"m",v9).call(this))}static createThreadAssistantStream($,w,W){let Z=new R1;return Z._run(()=>Z._threadAssistantStream($,w,{...W,headers:{...W?.headers,"X-Stainless-Helper-Method":"stream"}})),Z}static createAssistantStream($,w,W,Z){let X=new R1;return X._run(()=>X._runAssistantStream($,w,W,{...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"stream"}})),X}currentEvent(){return V(this,$W,"f")}currentRun(){return V(this,wW,"f")}currentMessageSnapshot(){return V(this,$$,"f")}currentRunStepSnapshot(){return V(this,u9,"f")}async finalRunSteps(){return await this.done(),Object.values(V(this,Q$,"f"))}async finalMessages(){return await this.done(),Object.values(V(this,e6,"f"))}async finalRun(){if(await this.done(),!V(this,C1,"f"))throw Error("Final run was not received.");return V(this,C1,"f")}async _createThreadAssistantStream($,w,W){let Z=W?.signal;if(Z){if(Z.aborted)this.controller.abort();Z.addEventListener("abort",()=>this.controller.abort())}let X={...w,stream:!0},Y=await $.createAndRun(X,{...W,signal:this.controller.signal});this._connected();for await(let G of Y)V(this,B0,"m",g9).call(this,G);if(Y.controller.signal?.aborted)throw new T0;return this._addRun(V(this,B0,"m",v9).call(this))}async _createAssistantStream($,w,W,Z){let X=Z?.signal;if(X){if(X.aborted)this.controller.abort();X.addEventListener("abort",()=>this.controller.abort())}let Y={...W,stream:!0},G=await $.create(w,Y,{...Z,signal:this.controller.signal});this._connected();for await(let J of G)V(this,B0,"m",g9).call(this,J);if(G.controller.signal?.aborted)throw new T0;return this._addRun(V(this,B0,"m",v9).call(this))}static accumulateDelta($,w){for(let[W,Z]of Object.entries(w)){if(!$.hasOwnProperty(W)){$[W]=Z;continue}let X=$[W];if(X===null||X===void 0){$[W]=Z;continue}if(W==="index"||W==="type"){$[W]=Z;continue}if(typeof X==="string"&&typeof Z==="string")X+=Z;else if(typeof X==="number"&&typeof Z==="number")X+=Z;else if(P9(X)&&P9(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(!P9(Y))throw Error(`Expected array delta entry to be an object but got: ${Y}`);let G=Y.index;if(G==null)throw console.error(Y),Error("Expected array delta entry to have an `index` property");if(typeof G!=="number")throw Error(`Expected array delta entry \`index\` property to be a number but got ${G}`);let J=X[G];if(J==null)X.push(Y);else X[G]=this.accumulateDelta(J,Y)}continue}else throw Error(`Unhandled record type: ${W}, deltaValue: ${Z}, accValue: ${X}`);$[W]=X}return $}_addRun($){return $}async _threadAssistantStream($,w,W){return await this._createThreadAssistantStream(w,$,W)}async _runAssistantStream($,w,W,Z){return await this._createAssistantStream(w,$,W,Z)}async _runToolAssistantStream($,w,W,Z){return await this._createToolAssistantStream(w,$,W,Z)}}R1=o$,g9=function(w){if(this.ended)return;switch(C(this,$W,w,"f"),V(this,B0,"m",JM).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":V(this,B0,"m",zM).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":V(this,B0,"m",GM).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":V(this,B0,"m",YM).call(this,w);break;case"error":throw Error("Encountered an error event in event processing - errors should be processed earlier");default:bE(w)}},v9=function(){if(this.ended)throw new k("stream has ended, this shouldn't happen");if(!V(this,C1,"f"))throw Error("Final run has not been received");return V(this,C1,"f")},YM=function(w){let[W,Z]=V(this,B0,"m",QM).call(this,w,V(this,$$,"f"));C(this,$$,W,"f"),V(this,e6,"f")[W.id]=W;for(let X of Z){let Y=W.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,W),w.data.delta.content)for(let X of w.data.delta.content){if(X.type=="text"&&X.text){let Y=X.text,G=W.content[X.index];if(G&&G.type=="text")this._emit("textDelta",Y,G.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(X.index!=V(this,Ew,"f")){if(V(this,S1,"f"))switch(V(this,S1,"f").type){case"text":this._emit("textDone",V(this,S1,"f").text,V(this,$$,"f"));break;case"image_file":this._emit("imageFileDone",V(this,S1,"f").image_file,V(this,$$,"f"));break}C(this,Ew,X.index,"f")}C(this,S1,W.content[X.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(V(this,Ew,"f")!==void 0){let X=w.data.content[V(this,Ew,"f")];if(X)switch(X.type){case"image_file":this._emit("imageFileDone",X.image_file,V(this,$$,"f"));break;case"text":this._emit("textDone",X.text,V(this,$$,"f"));break}}if(V(this,$$,"f"))this._emit("messageDone",w.data);C(this,$$,void 0,"f")}},GM=function(w){let W=V(this,B0,"m",TM).call(this,w);switch(C(this,u9,W,"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&&W.step_details.type=="tool_calls")for(let Y of Z.step_details.tool_calls)if(Y.index==V(this,WW,"f"))this._emit("toolCallDelta",Y,W.step_details.tool_calls[Y.index]);else{if(V(this,u0,"f"))this._emit("toolCallDone",V(this,u0,"f"));if(C(this,WW,Y.index,"f"),C(this,u0,W.step_details.tool_calls[Y.index],"f"),V(this,u0,"f"))this._emit("toolCallCreated",V(this,u0,"f"))}this._emit("runStepDelta",w.data.delta,W);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":if(C(this,u9,void 0,"f"),w.data.step_details.type=="tool_calls"){if(V(this,u0,"f"))this._emit("toolCallDone",V(this,u0,"f")),C(this,u0,void 0,"f")}this._emit("runStepDone",w.data,W);break;case"thread.run.step.in_progress":break}},JM=function(w){V(this,MX,"f").push(w),this._emit("event",w)},TM=function(w){switch(w.event){case"thread.run.step.created":return V(this,Q$,"f")[w.data.id]=w.data,w.data;case"thread.run.step.delta":let W=V(this,Q$,"f")[w.data.id];if(!W)throw Error("Received a RunStepDelta before creation of a snapshot");let Z=w.data;if(Z.delta){let X=R1.accumulateDelta(W,Z.delta);V(this,Q$,"f")[w.data.id]=X}return V(this,Q$,"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":V(this,Q$,"f")[w.data.id]=w.data;break}if(V(this,Q$,"f")[w.data.id])return V(this,Q$,"f")[w.data.id];throw Error("No snapshot available")},QM=function(w,W){let Z=[];switch(w.event){case"thread.message.created":return[w.data,Z];case"thread.message.delta":if(!W)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 W.content){let G=W.content[Y.index];W.content[Y.index]=V(this,B0,"m",MM).call(this,Y,G)}else W.content[Y.index]=Y,Z.push(Y);return[W,Z];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(W)return[W,Z];else throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},MM=function(w,W){return R1.accumulateDelta(W,w)},zM=function(w){switch(C(this,wW,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,C1,w.data,"f"),V(this,u0,"f"))this._emit("toolCallDone",V(this,u0,"f")),C(this,u0,void 0,"f");break;case"thread.run.cancelling":break}};function bE($){}class Lw extends O{constructor(){super(...arguments);this.steps=new _9(this._client)}create($,w,W){let{include:Z,...X}=w;return this._client.post(U`/threads/${$}/runs`,{query:{include:Z},body:X,...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers]),stream:w.stream??!1})}retrieve($,w,W){let{thread_id:Z}=w;return this._client.get(U`/threads/${Z}/runs/${$}`,{...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}update($,w,W){let{thread_id:Z,...X}=w;return this._client.post(U`/threads/${Z}/runs/${$}`,{body:X,...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}list($,w={},W){return this._client.getAPIList(U`/threads/${$}/runs`,u,{query:w,...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}cancel($,w,W){let{thread_id:Z}=w;return this._client.post(U`/threads/${Z}/runs/${$}/cancel`,{...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}async createAndPoll($,w,W){let Z=await this.create($,w,W);return await this.poll(Z.id,{thread_id:$},W)}createAndStream($,w,W){return o$.createAssistantStream($,this._client.beta.threads.runs,w,W)}async poll($,w,W){let Z=D([W?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":W?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:X,response:Y}=await this.retrieve($,w,{...W,headers:{...W?.headers,...Z}}).withResponse();switch(X.status){case"queued":case"in_progress":case"cancelling":let G=5000;if(W?.pollIntervalMs)G=W.pollIntervalMs;else{let J=Y.headers.get("openai-poll-after-ms");if(J){let T=parseInt(J);if(!isNaN(T))G=T}}await J$(G);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return X}}}stream($,w,W){return o$.createAssistantStream($,this._client.beta.threads.runs,w,W)}submitToolOutputs($,w,W){let{thread_id:Z,...X}=w;return this._client.post(U`/threads/${Z}/runs/${$}/submit_tool_outputs`,{body:X,...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers]),stream:w.stream??!1})}async submitToolOutputsAndPoll($,w,W){let Z=await this.submitToolOutputs($,w,W);return await this.poll(Z.id,w,W)}submitToolOutputsStream($,w,W){return o$.createToolAssistantStream($,this._client.beta.threads.runs,w,W)}}Lw.Steps=_9;class j1 extends O{constructor(){super(...arguments);this.runs=new Lw(this._client),this.messages=new x9(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,W){return this._client.post(U`/threads/${$}`,{body:w,...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.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 W=await this.createAndRun($,w);return await this.runs.poll(W.id,{thread_id:W.thread_id},w)}createAndRunStream($,w){return o$.createThreadAssistantStream($,this._client.beta.threads,w)}}j1.Runs=Lw;j1.Messages=x9;class j$ extends O{constructor(){super(...arguments);this.realtime=new A1(this._client),this.assistants=new y9(this._client),this.threads=new j1(this._client)}}j$.Realtime=A1;j$.Assistants=y9;j$.Threads=j1;class Dw extends O{create($,w){return this._client.post("/completions",{body:$,...w,stream:$.stream??!1})}}class h9 extends O{retrieve($,w,W){let{container_id:Z}=w;return this._client.get(U`/containers/${Z}/files/${$}/content`,{...W,headers:D([{Accept:"application/binary"},W?.headers]),__binaryResponse:!0})}}class kw extends O{constructor(){super(...arguments);this.content=new h9(this._client)}create($,w,W){return this._client.post(U`/containers/${$}/files`,v0({body:w,...W},this._client))}retrieve($,w,W){let{container_id:Z}=w;return this._client.get(U`/containers/${Z}/files/${$}`,W)}list($,w={},W){return this._client.getAPIList(U`/containers/${$}/files`,u,{query:w,...W})}delete($,w,W){let{container_id:Z}=w;return this._client.delete(U`/containers/${Z}/files/${$}`,{...W,headers:D([{Accept:"*/*"},W?.headers])})}}kw.Content=h9;class y1 extends O{constructor(){super(...arguments);this.files=new kw(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",u,{query:$,...w})}delete($,w){return this._client.delete(U`/containers/${$}`,{...w,headers:D([{Accept:"*/*"},w?.headers])})}}y1.Files=kw;class i9 extends O{create($,w,W){let{include:Z,...X}=w;return this._client.post(U`/conversations/${$}/items`,{query:{include:Z},body:X,...W})}retrieve($,w,W){let{conversation_id:Z,...X}=w;return this._client.get(U`/conversations/${Z}/items/${$}`,{query:X,...W})}list($,w={},W){return this._client.getAPIList(U`/conversations/${$}/items`,nZ,{query:w,...W})}delete($,w,W){let{conversation_id:Z}=w;return this._client.delete(U`/conversations/${Z}/items/${$}`,W)}}class I1 extends O{constructor(){super(...arguments);this.items=new i9(this._client)}create($={},w){return this._client.post("/conversations",{body:$,...w})}retrieve($,w){return this._client.get(U`/conversations/${$}`,w)}update($,w,W){return this._client.post(U`/conversations/${$}`,{body:w,...W})}delete($,w){return this._client.delete(U`/conversations/${$}`,w)}}I1.Items=i9;class Aw extends O{create($,w){let W=!!$.encoding_format,Z=W?$.encoding_format:"base64";if(W)Z0(this._client).debug("embeddings/user defined encoding_format:",$.encoding_format);let X=this._client.post("/embeddings",{body:{...$,encoding_format:Z},...w});if(W)return X;return Z0(this._client).debug("embeddings/decoding base64 embeddings from base64"),X._thenUnwrap((Y)=>{if(Y&&Y.data)Y.data.forEach((G)=>{let J=G.embedding;G.embedding=XM(J)});return Y})}}class m9 extends O{retrieve($,w,W){let{eval_id:Z,run_id:X}=w;return this._client.get(U`/evals/${Z}/runs/${X}/output_items/${$}`,W)}list($,w,W){let{eval_id:Z,...X}=w;return this._client.getAPIList(U`/evals/${Z}/runs/${$}/output_items`,u,{query:X,...W})}}class Sw extends O{constructor(){super(...arguments);this.outputItems=new m9(this._client)}create($,w,W){return this._client.post(U`/evals/${$}/runs`,{body:w,...W})}retrieve($,w,W){let{eval_id:Z}=w;return this._client.get(U`/evals/${Z}/runs/${$}`,W)}list($,w={},W){return this._client.getAPIList(U`/evals/${$}/runs`,u,{query:w,...W})}delete($,w,W){let{eval_id:Z}=w;return this._client.delete(U`/evals/${Z}/runs/${$}`,W)}cancel($,w,W){let{eval_id:Z}=w;return this._client.post(U`/evals/${Z}/runs/${$}`,W)}}Sw.OutputItems=m9;class b1 extends O{constructor(){super(...arguments);this.runs=new Sw(this._client)}create($,w){return this._client.post("/evals",{body:$,...w})}retrieve($,w){return this._client.get(U`/evals/${$}`,w)}update($,w,W){return this._client.post(U`/evals/${$}`,{body:w,...W})}list($={},w){return this._client.getAPIList("/evals",u,{query:$,...w})}delete($,w){return this._client.delete(U`/evals/${$}`,w)}}b1.Runs=Sw;class Rw extends O{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",u,{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:W=1800000}={}){let Z=new Set(["processed","error","deleted"]),X=Date.now(),Y=await this.retrieve($);while(!Y.status||!Z.has(Y.status))if(await J$(w),Y=await this.retrieve($),Date.now()-X>W)throw new O1({message:`Giving up on waiting for file ${$} to finish processing after ${W} milliseconds.`});return Y}}class l9 extends O{}class c9 extends O{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 Cw extends O{constructor(){super(...arguments);this.graders=new c9(this._client)}}Cw.Graders=c9;class d9 extends O{create($,w,W){return this._client.getAPIList(U`/fine_tuning/checkpoints/${$}/permissions`,A$,{body:w,method:"post",...W})}retrieve($,w={},W){return this._client.get(U`/fine_tuning/checkpoints/${$}/permissions`,{query:w,...W})}delete($,w,W){let{fine_tuned_model_checkpoint:Z}=w;return this._client.delete(U`/fine_tuning/checkpoints/${Z}/permissions/${$}`,W)}}class jw extends O{constructor(){super(...arguments);this.permissions=new d9(this._client)}}jw.Permissions=d9;class n9 extends O{list($,w={},W){return this._client.getAPIList(U`/fine_tuning/jobs/${$}/checkpoints`,u,{query:w,...W})}}class yw extends O{constructor(){super(...arguments);this.checkpoints=new n9(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",u,{query:$,...w})}cancel($,w){return this._client.post(U`/fine_tuning/jobs/${$}/cancel`,w)}listEvents($,w={},W){return this._client.getAPIList(U`/fine_tuning/jobs/${$}/events`,u,{query:w,...W})}pause($,w){return this._client.post(U`/fine_tuning/jobs/${$}/pause`,w)}resume($,w){return this._client.post(U`/fine_tuning/jobs/${$}/resume`,w)}}yw.Checkpoints=n9;class M$ extends O{constructor(){super(...arguments);this.methods=new l9(this._client),this.jobs=new yw(this._client),this.checkpoints=new jw(this._client),this.alpha=new Cw(this._client)}}M$.Methods=l9;M$.Jobs=yw;M$.Checkpoints=jw;M$.Alpha=Cw;class p9 extends O{}class x1 extends O{constructor(){super(...arguments);this.graderModels=new p9(this._client)}}x1.GraderModels=p9;class Iw extends O{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 bw extends O{retrieve($,w){return this._client.get(U`/models/${$}`,w)}list($){return this._client.getAPIList("/models",A$,$)}delete($,w){return this._client.delete(U`/models/${$}`,w)}}class xw extends O{create($,w){return this._client.post("/moderations",{body:$,...w})}}class t9 extends O{create($,w){return this._client.post("/realtime/client_secrets",{body:$,...w})}}class _1 extends O{constructor(){super(...arguments);this.clientSecrets=new t9(this._client)}}_1.ClientSecrets=t9;function NM($,w){if(!w||!oE(w))return{...$,output_parsed:null,output:$.output.map((W)=>{if(W.type==="function_call")return{...W,parsed_arguments:null};if(W.type==="message")return{...W,content:W.content.map((Z)=>({...Z,parsed:null}))};else return W})};return zX($,w)}function zX($,w){let W=$.output.map((X)=>{if(X.type==="function_call")return{...X,parsed_arguments:wL(w,X)};if(X.type==="message"){let Y=X.content.map((G)=>{if(G.type==="output_text")return{...G,parsed:aE(w,G.text)};return G});return{...X,content:Y}}return X}),Z=Object.assign({},$,{output:W});if(!Object.getOwnPropertyDescriptor($,"output_text"))ZW(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 aE($,w){if($.text?.format?.type!=="json_schema")return null;if("$parseRaw"in $.text?.format)return($.text?.format).$parseRaw(w);return JSON.parse(w)}function oE($){if(F9($.text?.format))return!0;return!1}function eE($){return $?.$brand==="auto-parseable-tool"}function $L($,w){return $.find((W)=>W.type==="function"&&W.name===w)}function wL($,w){let W=$L($.tools??[],w.name);return{...w,...w,parsed_arguments:eE(W)?W.$parseRaw(w.arguments):W?.strict?JSON.parse(w.arguments):null}}function ZW($){let w=[];for(let W of $.output){if(W.type!=="message")continue;for(let Z of W.content)if(Z.type==="output_text")w.push(Z.text)}$.output_text=w.join("")}var _w,XW,e$,YW,KM,BM,PM,VM;class GW extends D1{constructor($){super();_w.add(this),XW.set(this,void 0),e$.set(this,void 0),YW.set(this,void 0),C(this,XW,$,"f")}static createResponse($,w,W){let Z=new GW(w);return Z._run(()=>Z._createOrRetrieveResponse($,w,{...W,headers:{...W?.headers,"X-Stainless-Helper-Method":"stream"}})),Z}async _createOrRetrieveResponse($,w,W){let Z=W?.signal;if(Z){if(Z.aborted)this.controller.abort();Z.addEventListener("abort",()=>this.controller.abort())}V(this,_w,"m",KM).call(this);let X,Y=null;if("response_id"in w)X=await $.responses.retrieve(w.response_id,{stream:!0},{...W,signal:this.controller.signal,stream:!0}),Y=w.starting_after??null;else X=await $.responses.create({...w,stream:!0},{...W,signal:this.controller.signal});this._connected();for await(let G of X)V(this,_w,"m",BM).call(this,G,Y);if(X.controller.signal?.aborted)throw new T0;return V(this,_w,"m",PM).call(this)}[(XW=new WeakMap,e$=new WeakMap,YW=new WeakMap,_w=new WeakSet,KM=function(){if(this.ended)return;C(this,e$,void 0,"f")},BM=function(w,W){if(this.ended)return;let Z=(Y,G)=>{if(W==null||G.sequence_number>W)this._emit(Y,G)},X=V(this,_w,"m",VM).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 k(`missing output at index ${w.output_index}`);if(Y.type==="message"){let G=Y.content[w.content_index];if(!G)throw new k(`missing content at index ${w.content_index}`);if(G.type!=="output_text")throw new k(`expected content to be 'output_text', got ${G.type}`);Z("response.output_text.delta",{...w,snapshot:G.text})}break}case"response.function_call_arguments.delta":{let Y=X.output[w.output_index];if(!Y)throw new k(`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}},PM=function(){if(this.ended)throw new k("stream has ended, this shouldn't happen");let w=V(this,e$,"f");if(!w)throw new k("request ended without sending any events");C(this,e$,void 0,"f");let W=WL(w,V(this,XW,"f"));return C(this,YW,W,"f"),W},VM=function(w){let W=V(this,e$,"f");if(!W){if(w.type!=="response.created")throw new k(`When snapshot hasn't been set yet, expected 'response.created' event, got ${w.type}`);return W=C(this,e$,w.response,"f"),W}switch(w.type){case"response.output_item.added":{W.output.push(w.item);break}case"response.content_part.added":{let Z=W.output[w.output_index];if(!Z)throw new k(`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=W.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}`);X.text+=w.delta}break}case"response.function_call_arguments.delta":{let Z=W.output[w.output_index];if(!Z)throw new k(`missing output at index ${w.output_index}`);if(Z.type==="function_call")Z.arguments+=w.delta;break}case"response.reasoning_text.delta":{let Z=W.output[w.output_index];if(!Z)throw new k(`missing output at index ${w.output_index}`);if(Z.type==="reasoning"){let X=Z.content?.[w.content_index];if(!X)throw new k(`missing content at index ${w.content_index}`);if(X.type!=="reasoning_text")throw new k(`expected content to be 'reasoning_text', got ${X.type}`);X.text+=w.delta}break}case"response.completed":{C(this,e$,w.response,"f");break}}return W},Symbol.asyncIterator)](){let $=[],w=[],W=!1;return this.on("event",(Z)=>{let X=w.shift();if(X)X.resolve(Z);else $.push(Z)}),this.on("end",()=>{W=!0;for(let Z of w)Z.resolve(void 0);w.length=0}),this.on("abort",(Z)=>{W=!0;for(let X of w)X.reject(Z);w.length=0}),this.on("error",(Z)=>{W=!0;for(let X of w)X.reject(Z);w.length=0}),{next:async()=>{if(!$.length){if(W)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 $=V(this,YW,"f");if(!$)throw new k("stream ended without producing a ChatCompletion");return $}}function WL($,w){return NM($,w)}class r9 extends O{list($,w={},W){return this._client.getAPIList(U`/responses/${$}/input_items`,u,{query:w,...W})}}class g1 extends O{constructor(){super(...arguments);this.inputItems=new r9(this._client)}create($,w){return this._client.post("/responses",{body:$,...w,stream:$.stream??!1})._thenUnwrap((W)=>{if("object"in W&&W.object==="response")ZW(W);return W})}retrieve($,w={},W){return this._client.get(U`/responses/${$}`,{query:w,...W,stream:w?.stream??!1})._thenUnwrap((Z)=>{if("object"in Z&&Z.object==="response")ZW(Z);return Z})}delete($,w){return this._client.delete(U`/responses/${$}`,{...w,headers:D([{Accept:"*/*"},w?.headers])})}parse($,w){return this._client.responses.create($,w)._thenUnwrap((W)=>zX(W,$))}stream($,w){return GW.createResponse(this._client,$,w)}cancel($,w){return this._client.post(U`/responses/${$}/cancel`,w)}}g1.InputItems=r9;class s9 extends O{create($,w,W){return this._client.post(U`/uploads/${$}/parts`,v0({body:w,...W},this._client))}}class v1 extends O{constructor(){super(...arguments);this.parts=new s9(this._client)}create($,w){return this._client.post("/uploads",{body:$,...w})}cancel($,w){return this._client.post(U`/uploads/${$}/cancel`,w)}complete($,w,W){return this._client.post(U`/uploads/${$}/complete`,{body:w,...W})}}v1.Parts=s9;var fM=async($)=>{let w=await Promise.allSettled($),W=w.filter((X)=>X.status==="rejected");if(W.length){for(let X of W)console.error(X.reason);throw Error(`${W.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 a9 extends O{create($,w,W){return this._client.post(U`/vector_stores/${$}/file_batches`,{body:w,...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}retrieve($,w,W){let{vector_store_id:Z}=w;return this._client.get(U`/vector_stores/${Z}/file_batches/${$}`,{...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}cancel($,w,W){let{vector_store_id:Z}=w;return this._client.post(U`/vector_stores/${Z}/file_batches/${$}/cancel`,{...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}async createAndPoll($,w,W){let Z=await this.create($,w);return await this.poll($,Z.id,W)}listFiles($,w,W){let{vector_store_id:Z,...X}=w;return this._client.getAPIList(U`/vector_stores/${Z}/file_batches/${$}/files`,u,{query:X,...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}async poll($,w,W){let Z=D([W?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":W?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:X,response:Y}=await this.retrieve(w,{vector_store_id:$},{...W,headers:Z}).withResponse();switch(X.status){case"in_progress":let G=5000;if(W?.pollIntervalMs)G=W.pollIntervalMs;else{let J=Y.headers.get("openai-poll-after-ms");if(J){let T=parseInt(J);if(!isNaN(T))G=T}}await J$(G);break;case"failed":case"cancelled":case"completed":return X}}}async uploadAndPoll($,{files:w,fileIds:W=[]},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),G=this._client,J=w.values(),T=[...W];async function Q(z){for(let N of z){let B=await G.files.create({file:N,purpose:"assistants"},Z);T.push(B.id)}}let M=Array(Y).fill(J).map(Q);return await fM(M),await this.createAndPoll($,{file_ids:T})}}class o9 extends O{create($,w,W){return this._client.post(U`/vector_stores/${$}/files`,{body:w,...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}retrieve($,w,W){let{vector_store_id:Z}=w;return this._client.get(U`/vector_stores/${Z}/files/${$}`,{...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}update($,w,W){let{vector_store_id:Z,...X}=w;return this._client.post(U`/vector_stores/${Z}/files/${$}`,{body:X,...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}list($,w={},W){return this._client.getAPIList(U`/vector_stores/${$}/files`,u,{query:w,...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}delete($,w,W){let{vector_store_id:Z}=w;return this._client.delete(U`/vector_stores/${Z}/files/${$}`,{...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}async createAndPoll($,w,W){let Z=await this.create($,w,W);return await this.poll($,Z.id,W)}async poll($,w,W){let Z=D([W?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":W?.pollIntervalMs?.toString()??void 0}]);while(!0){let X=await this.retrieve(w,{vector_store_id:$},{...W,headers:Z}).withResponse(),Y=X.data;switch(Y.status){case"in_progress":let G=5000;if(W?.pollIntervalMs)G=W.pollIntervalMs;else{let J=X.response.headers.get("openai-poll-after-ms");if(J){let T=parseInt(J);if(!isNaN(T))G=T}}await J$(G);break;case"failed":case"completed":return Y}}}async upload($,w,W){let Z=await this._client.files.create({file:w,purpose:"assistants"},W);return this.create($,{file_id:Z.id},W)}async uploadAndPoll($,w,W){let Z=await this.upload($,w,W);return await this.poll($,Z.id,W)}content($,w,W){let{vector_store_id:Z}=w;return this._client.getAPIList(U`/vector_stores/${Z}/files/${$}/content`,A$,{...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}}class $1 extends O{constructor(){super(...arguments);this.files=new o9(this._client),this.fileBatches=new a9(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,W){return this._client.post(U`/vector_stores/${$}`,{body:w,...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}list($={},w){return this._client.getAPIList("/vector_stores",u,{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,W){return this._client.getAPIList(U`/vector_stores/${$}/search`,A$,{body:w,method:"post",...W,headers:D([{"OpenAI-Beta":"assistants=v2"},W?.headers])})}}$1.Files=o9;$1.FileBatches=a9;var gw,qM,JW;class vw extends O{constructor(){super(...arguments);gw.add(this)}async unwrap($,w,W=this._client.webhookSecret,Z=300){return await this.verifySignature($,w,W,Z),JSON.parse($)}async verifySignature($,w,W=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");V(this,gw,"m",qM).call(this,W);let X=D([w]).values,Y=V(this,gw,"m",JW).call(this,X,"webhook-signature"),G=V(this,gw,"m",JW).call(this,X,"webhook-timestamp"),J=V(this,gw,"m",JW).call(this,X,"webhook-id"),T=parseInt(G,10);if(isNaN(T))throw new D$("Invalid webhook timestamp format");let Q=Math.floor(Date.now()/1000);if(Q-T>Z)throw new D$("Webhook timestamp is too old");if(T>Q+Z)throw new D$("Webhook timestamp is too new");let M=Y.split(" ").map((K)=>K.startsWith("v1,")?K.substring(3):K),z=W.startsWith("whsec_")?Buffer.from(W.replace("whsec_",""),"base64"):Buffer.from(W,"utf-8"),N=J?`${J}.${G}.${$}`:`${G}.${$}`,B=await crypto.subtle.importKey("raw",z,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let K of M)try{let P=Buffer.from(K,"base64");if(await crypto.subtle.verify("HMAC",B,P,new TextEncoder().encode(N)))return}catch{continue}throw new D$("The given webhook signature does not match the expected signature")}}gw=new WeakSet,qM=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")},JW=function(w,W){if(!w)throw Error("Headers are required");let Z=w.get(W);if(Z===null||Z===void 0)throw Error(`Missing required header: ${W}`);return Z};var NX,KX,TW,UM;class _{constructor({baseURL:$=a$("OPENAI_BASE_URL"),apiKey:w=a$("OPENAI_API_KEY"),organization:W=a$("OPENAI_ORG_ID")??null,project:Z=a$("OPENAI_PROJECT_ID")??null,webhookSecret:X=a$("OPENAI_WEBHOOK_SECRET")??null,...Y}={}){if(NX.add(this),TW.set(this,void 0),this.completions=new Dw(this),this.chat=new k1(this),this.embeddings=new Aw(this),this.files=new Rw(this),this.images=new Iw(this),this.audio=new C$(this),this.moderations=new xw(this),this.models=new bw(this),this.fineTuning=new M$(this),this.graders=new x1(this),this.vectorStores=new $1(this),this.webhooks=new vw(this),this.beta=new j$(this),this.batches=new Ow(this),this.uploads=new v1(this),this.responses=new g1(this),this.realtime=new _1(this),this.conversations=new I1(this),this.evals=new b1(this),this.containers=new y1(this),w===void 0)throw new k("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");let G={apiKey:w,organization:W,project:Z,webhookSecret:X,...Y,baseURL:$||"https://api.openai.com/v1"};if(!G.dangerouslyAllowBrowser&&EQ())throw new k(`It looks like you're running in a browser-like environment.
188
188
 
189
189
  This is disabled by default, as it risks exposing your secret API credentials to attackers.
190
190
  If you understand the risks and have appropriate mitigations in place,
@@ -193,60 +193,67 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
193
193
  new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
194
194
 
195
195
  https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
196
- `);this.baseURL=G.baseURL,this.timeout=G.timeout??K3.DEFAULT_TIMEOUT,this.logger=G.logger??console;let J="warn";this.logLevel=J,this.logLevel=cZ(G.logLevel,"ClientOptions.logLevel",this)??cZ(a$("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??J,this.fetchOptions=G.fetchOptions,this.maxRetries=G.maxRetries??2,this.fetch=G.fetch??LQ(),C(this,JW,kQ,"f"),this._options=G,this.apiKey=typeof w==="string"?w:"Missing Key",this.organization=W,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 D([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery($){return mZ($,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${p$}`}defaultIdempotencyKey(){return`stainless-node-retry-${yZ()}`}makeStatusError($,w,W,Z){return Y0.generate($,w,W,Z)}async _callApiKey(){let $=this._options.apiKey;if(typeof $!=="function")return!1;let w;try{w=await $()}catch(W){if(W instanceof k)throw W;throw new k(`Failed to get token from 'apiKey' function: ${W.message}`,{cause:W})}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,W){let Z=!V(this,N3,"m",qM).call(this)&&W||this.baseURL,X=BQ($)?new URL($):new URL(Z+(Z.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),Y=this.defaultQuery();if(!PQ(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:W}){}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,W){return this.request(Promise.resolve(W).then((Z)=>{return{method:$,path:w,...Z}}))}request($,w=null){return new E1(this,this.makeRequest($,w,void 0))}async makeRequest($,w,W){let Z=await $,X=Z.maxRetries??this.maxRetries;if(w==null)w=X;await this.prepareOptions(Z);let{req:Y,url:G,timeout:J}=await this.buildRequest(Z,{retryCount:X-w});await this.prepareRequest(Y,{url:G,options:Z});let T="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),Q=W===void 0?"":`, retryOf: ${W}`,M=Date.now();if(Z0(this).debug(`[${T}] sending request`,k$({retryOfRequestLogID:W,method:Z.method,url:G,options:Z,headers:Y.headers})),Z.signal?.aborted)throw new T0;let z=new AbortController,N=await this.fetchWithTimeout(G,Y,J,z).catch(Z4),B=Date.now();if(N instanceof globalThis.Error){let q=`retrying, ${w} attempts remaining`;if(Z.signal?.aborted)throw new T0;let f=W4(N)||/timed? ?out/i.test(String(N)+("cause"in N?String(N.cause):""));if(w)return Z0(this).info(`[${T}] connection ${f?"timed out":"failed"} - ${q}`),Z0(this).debug(`[${T}] connection ${f?"timed out":"failed"} (${q})`,k$({retryOfRequestLogID:W,url:G,durationMs:B-M,message:N.message})),this.retryRequest(Z,w,W??T);if(Z0(this).info(`[${T}] connection ${f?"timed out":"failed"} - error; no more retries left`),Z0(this).debug(`[${T}] connection ${f?"timed out":"failed"} (error; no more retries left)`,k$({retryOfRequestLogID:W,url:G,durationMs:B-M,message:N.message})),f)throw new O1;throw new F1({cause:N})}let K=[...N.headers.entries()].filter(([q])=>q==="x-request-id").map(([q,f])=>", "+q+": "+JSON.stringify(f)).join(""),P=`[${T}${Q}${K}] ${Y.method} ${G} ${N.ok?"succeeded":"failed"} with status ${N.status} in ${B-M}ms`;if(!N.ok){let q=await this.shouldRetry(N);if(w&&q){let j=`retrying, ${w} attempts remaining`;return await DQ(N.body),Z0(this).info(`${P} - ${j}`),Z0(this).debug(`[${T}] response error (${j})`,k$({retryOfRequestLogID:W,url:N.url,status:N.status,headers:N.headers,durationMs:B-M})),this.retryRequest(Z,w,W??T,N.headers)}let f=q?"error; no more retries left":"error; not retryable";Z0(this).info(`${P} - ${f}`);let H=await N.text().catch((j)=>Z4(j).message),E=qQ(H),S=E?void 0:H;throw Z0(this).debug(`[${T}] response error (${f})`,k$({retryOfRequestLogID:W,url:N.url,status:N.status,headers:N.headers,message:S,durationMs:Date.now()-M})),this.makeStatusError(N.status,E,S,N.headers)}return Z0(this).info(P),Z0(this).debug(`[${T}] response start`,k$({retryOfRequestLogID:W,url:N.url,status:N.status,headers:N.headers,durationMs:B-M})),{response:N,options:Z,controller:z,requestLogID:T,retryOfRequestLogID:W,startTime:M}}getAPIList($,w,W){return this.requestAPIList(w,{method:"get",path:$,...W})}requestAPIList($,w){let W=this.makeRequest(w,null,void 0);return new i6(this,W,$)}async fetchWithTimeout($,w,W,Z){let{signal:X,method:Y,...G}=w||{};if(X)X.addEventListener("abort",()=>Z.abort());let J=setTimeout(()=>Z.abort(),W),T=globalThis.ReadableStream&&G.body instanceof globalThis.ReadableStream||typeof G.body==="object"&&G.body!==null&&Symbol.asyncIterator in G.body,Q={signal:Z.signal,...T?{duplex:"half"}:{},method:"GET",...G};if(Y)Q.method=Y.toUpperCase();try{return await this.fetch.call(void 0,$,Q)}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,W,Z){let X,Y=Z?.get("retry-after-ms");if(Y){let J=parseFloat(Y);if(!Number.isNaN(J))X=J}let G=Z?.get("retry-after");if(G&&!X){let J=parseFloat(G);if(!Number.isNaN(J))X=J*1000;else X=Date.parse(G)-Date.now()}if(!(X&&0<=X&&X<60000)){let J=$.maxRetries??this.maxRetries;X=this.calculateDefaultRetryTimeoutMillis(w,J)}return await J$(X),this.makeRequest($,w-1,W)}calculateDefaultRetryTimeoutMillis($,w){let X=w-$,Y=Math.min(0.5*Math.pow(2,X),8),G=1-Math.random()*0.25;return Y*G*1000}async buildRequest($,{retryCount:w=0}={}){let W={...$},{method:Z,path:X,query:Y,defaultBaseURL:G}=W,J=this.buildURL(X,Y,G);if("timeout"in W)fQ("timeout",W.timeout);W.timeout=W.timeout??this.timeout;let{bodyHeaders:T,body:Q}=this.buildBody({options:W}),M=await this.buildHeaders({options:$,method:Z,bodyHeaders:T,retryCount:w});return{req:{method:Z,headers:M,...W.signal&&{signal:W.signal},...globalThis.ReadableStream&&Q instanceof globalThis.ReadableStream&&{duplex:"half"},...Q&&{body:Q},...this.fetchOptions??{},...W.fetchOptions??{}},url:J,timeout:W.timeout}}async buildHeaders({options:$,method:w,bodyHeaders:W,retryCount:Z}){let X={};if(this.idempotencyHeader&&w!=="get"){if(!$.idempotencyKey)$.idempotencyKey=this.defaultIdempotencyKey();X[this.idempotencyHeader]=$.idempotencyKey}let Y=D([X,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(Z),...$.timeout?{"X-Stainless-Timeout":String(Math.trunc($.timeout/1000))}:{},...EQ(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders($),this._options.defaultHeaders,W,$.headers]);return this.validateHeaders(Y),Y.values}buildBody({options:{body:$,headers:w}}){if(!$)return{bodyHeaders:void 0,body:void 0};let W=D([w]);if(ArrayBuffer.isView($)||$ instanceof ArrayBuffer||$ instanceof DataView||typeof $==="string"&&W.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:y6($)};else return V(this,JW,"f").call(this,{body:$,headers:W})}}K3=_,JW=new WeakMap,N3=new WeakSet,qM=function(){return this.baseURL!=="https://api.openai.com/v1"};_.OpenAI=K3;_.DEFAULT_TIMEOUT=600000;_.OpenAIError=k;_.APIError=Y0;_.APIConnectionError=F1;_.APIConnectionTimeoutError=O1;_.APIUserAbortError=T0;_.NotFoundError=J4;_.ConflictError=T4;_.RateLimitError=M4;_.BadRequestError=X4;_.AuthenticationError=Y4;_.InternalServerError=z4;_.PermissionDeniedError=G4;_.UnprocessableEntityError=Q4;_.InvalidWebhookSignatureError=D$;_.toFile=m6;_.Completions=Dw;_.Chat=k1;_.Embeddings=Aw;_.Files=Rw;_.Images=Iw;_.Audio=C$;_.Moderations=xw;_.Models=bw;_.FineTuning=M$;_.Graders=x1;_.VectorStores=$1;_.Webhooks=vw;_.Beta=j$;_.Batches=Ow;_.Uploads=v1;_.Responses=g1;_.Realtime=_1;_.Conversations=I1;_.Evals=b1;_.Containers=y1;class B3{client;constructor($){this.client=new _({...$,maxRetries:0})}async*stream($){let w=await this.client.chat.completions.create({model:$.model,messages:TL($.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),W=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 G of X?.tool_calls??[]){let J=G.index;if(!W.has(J))W.add(J),yield{type:"tool_call_start",index:J,callId:G.id??`call_${J}`,name:G.function?.name??""};if(G.function?.arguments)yield{type:"tool_call_delta",index:J,argumentsDelta:G.function.arguments}}if(Z.usage)yield{type:"usage",usage:{inputTokens:Z.usage.prompt_tokens,outputTokens:Z.usage.completion_tokens}}}for(let Z of W)yield{type:"tool_call_end",index:Z};yield{type:"done"}}}function TL($){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 W={role:"assistant",content:w.content||null};if(w.toolCalls.length)W.tool_calls=w.toolCalls.map((Z)=>({id:Z.callId,type:"function",function:{name:Z.name,arguments:JSON.stringify(Z.input)}}));return W})}import{createHash as QL,randomUUID as UM}from"node:crypto";import{appendFile as ML,chmod as HM,mkdir as zL,readdir as NL,readFile as FM}from"node:fs/promises";import h1 from"node:path";var KL=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;function OM($){return KL.test($)}function P3($){return QL("sha256").update(h1.resolve($)).digest("hex").slice(0,16)}class V3{workspace;sessionId;sessionPath;tracePath;#$=Promise.resolve();#w=!1;constructor($,w,W=UM()){this.workspace=w;this.sessionId=W;if(!OM(W))throw Error("Invalid session ID");let Z=h1.join($,"sessions",P3(w));this.sessionPath=h1.join(Z,`${W}.jsonl`),this.tracePath=h1.join(Z,`${W}.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 W={version:1,id:UM(),timestamp:new Date().toISOString(),type:$,data:w},Z=this.#$.then(async()=>{let X=h1.dirname(this.sessionPath);await zL(X,{recursive:!0,mode:448}),await HM(X,448),await ML(this.sessionPath,`${JSON.stringify(W)}
197
- `,{encoding:"utf8",mode:384}),await HM(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 $=h1.dirname(this.sessionPath),w;try{w=await NL($)}catch(Z){if(Z.code==="ENOENT")return[];throw Z}let W=[];for(let Z of w){if(!Z.endsWith(".jsonl")||Z.endsWith(".trace.jsonl"))continue;let X=Z.slice(0,-6);if(!OM(X))continue;try{W.push(await this.#W(h1.join($,Z),X))}catch{}}return W.sort((Z,X)=>X.lastActivity.localeCompare(Z.lastActivity)),W}async#W($,w){let W=await FM($,"utf8"),Z=0,X,Y,G="";for(let Q of W.split(`
198
- `)){if(!Q)continue;let M;try{M=JSON.parse(Q)}catch{continue}if(M.version!==1)continue;if(M.timestamp)G=M.timestamp;switch(M.type){case"session.reset":Z=0,Y=void 0,X=void 0;break;case"session.title":{let z=M.data;if(typeof z?.title==="string")X=z.title;break}case"message":if(Z++,Y===void 0){let z=M.data;if(z?.role==="user"&&typeof z.content==="string")Y=z.content}break}}let J=X??Y,T={id:w,messageCount:Z,lastActivity:G};if(J!==void 0)T.title=J;return T}async recover(){let $=[],w=[],W,Z,X=await FM(this.sessionPath,"utf8");this.#w=!0;let Y=X.split(`
199
- `),G=-1;for(let Q=Y.length-1;Q>=0;Q--)if(Y[Q]){G=Q;break}for(let Q=0;Q<Y.length;Q++){let M=Y[Q];if(!M)continue;let z;try{z=JSON.parse(M)}catch(N){if(Q===G){w.push("Ignored incomplete final JSONL record");break}throw EM(Q,N)}try{if(z.version!==1)throw Error("unsupported schema version");if(z.type==="session.reset")$.length=0,W=void 0,Z=void 0;if(z.type==="message"){if(!BL(z.data))throw Error("invalid message structure");$.push(z.data)}if(z.type==="context.compacted"){let N=z.data;if(typeof N?.summary!=="string")throw Error("invalid compaction record");W=N.summary,Z=typeof N.sourceRange?.start==="number"&&typeof N.sourceRange.end==="number"?{start:N.sourceRange.start,end:N.sourceRange.end}:void 0}}catch(N){throw EM(Q,N)}}let J=PL($,w);for(let Q of J)await this.appendMessage(Q);let T={messages:$,warnings:w};if(W!==void 0)T.summary=W;if(Z!==void 0)T.compactionRange=Z;return T}}function BL($){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((W)=>!!W&&typeof W==="object"&&typeof W.callId==="string"&&typeof W.name==="string"&&("input"in W));return w.role==="tool"&&typeof w.callId==="string"&&typeof w.name==="string"&&typeof w.content==="string"&&typeof w.isError==="boolean"}function EM($,w){return Error(`Invalid session record at line ${$+1}: ${w instanceof Error?w.message:String(w)}`)}function PL($,w){let W=new Map,Z=new Set;for(let Y of $)if(Y.role==="assistant"){if(W.size>0)throw Error("Assistant message appeared before pending tool results");for(let G of Y.toolCalls){if(Z.has(G.callId))throw Error(`Duplicate tool call ID: ${G.callId}`);Z.add(G.callId),W.set(G.callId,G.name)}}else if(Y.role==="tool"){if(!W.delete(Y.callId))throw Error(`Orphan tool result: ${Y.callId}`)}else if(W.size>0)throw Error(`${Y.role} message appeared before pending tool results`);if(W.size===0)return[];let X=[];for(let[Y,G]of W){let J={role:"tool",callId:Y,name:G,content:"runtime.interrupted: tool execution did not complete before the previous process exited",isError:!0};$.push(J),X.push(J)}return w.push(`Recovered ${W.size} interrupted tool call(s)`),X}function LM(){return[s8,o8,r8,n8]}var VL={maxLines:20,maxValueChars:2000,maxDepth:4,maxSummaryColumns:120};function u1($){return typeof $==="object"&&$!==null&&!Array.isArray($)?$:void 0}function DM($,w){let W=u1(w?.properties),Z=W?Object.keys(W).filter((X)=>(X in $)):[];return[...Z,...Object.keys($).filter((X)=>!Z.includes(X))]}function fL($,w){return u1(u1($?.properties)?.[w])}function qL($,w){let W=X0($),Z=Array.from(W);if(Z.length<=w)return W;let X=Z.length-w;return`${Z.slice(0,w).join("")}… [${X} characters omitted]`}function TW($,w){if(typeof $==="string")return qL($,w.maxValueChars);if($===null)return"null";if(typeof $==="number"||typeof $==="boolean"||typeof $==="bigint")return String($);if($===void 0)return"undefined";return}function QW($,w={}){let W={...VL,...w},Z=X0($.name);try{let X=[],Y=new WeakSet,G=Math.max(0,W.maxLines),J=(N)=>{if(X.length<=G)X.push(N)},T=(N,B,K,P,q)=>{if(X.length>G)return;let f=q===void 0?void 0:X0(q),H=TW(N,W);if(H!==void 0){let j=H.split(`
200
- `);if(f!==void 0&&j.length===1)J(`${P}${f}: ${H}`);else if(f!==void 0){J(`${P}${f}:`);for(let g of j)J(`${P} ${g}`)}else for(let g of j)J(`${P}${g}`);return}if(K>=W.maxDepth){J(`${P}${f===void 0?"":`${f}: `}[max depth]`);return}if(typeof N!=="object"||N===null){J(`${P}${f===void 0?"":`${f}: `}${X0(String(N))}`);return}if(Y.has(N)){J(`${P}${f===void 0?"":`${f}: `}[circular]`);return}if(Y.add(N),Array.isArray(N)){if(N.length===0){J(`${P}${f===void 0?"":`${f}: `}[]`);return}if(f!==void 0)J(`${P}${f}:`);let j=f===void 0?P:`${P} `,g=u1(B?.items);for(let s of N){if(X.length>G)break;let e=TW(s,W);if(e!==void 0&&!e.includes(`
201
- `))J(`${j}- ${e}`);else J(`${j}-`),T(s,g,K+1,`${j} `)}return}let E=N,S=DM(E,B);if(S.length===0){J(`${P}${f===void 0?"":`${f}: `}{}`);return}if(f!==void 0)J(`${P}${f}:`);let A=f===void 0?P:`${P} `;for(let j of S){if(X.length>G)break;T(E[j],fL(B,j),K+1,A,j)}};T($.input,u1($.inputSchema),0,"");let Q=X;if(Q.length>G)Q=G===0?[]:[...Q.slice(0,G-1),"... [1 or more lines omitted]"];let M=Z,z=u1($.input);if(z)for(let N of DM(z,u1($.inputSchema))){let B=TW(z[N],W);if(B!==void 0){M=`${X0(N)}: ${B.split(`
202
- `)[0]??""}`;break}}else{let N=TW($.input,W);if(N!==void 0)M=N.split(`
203
- `)[0]??Z}return{lines:Q,summary:Yw(X0(M),W.maxSummaryColumns)}}catch{return{lines:["[unavailable]"],summary:Yw(Z,W.maxSummaryColumns)}}}class f3{registry;permissions;events;workspace;timeoutMs;constructor($,w,W,Z,X=60000){this.registry=$;this.permissions=w;this.events=W;this.workspace=Z;this.timeoutMs=X}setRegistry($){this.registry=$}async execute($,w,W){await this.events.emit("tool.requested",{name:$.name,callId:$.callId},W);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};if(["read","write","edit"].includes($.name))try{await X$(this.workspace,$.input.path)}catch(N){return{content:`permission.workspace_denied: ${N instanceof Error?N.message:String(N)}`,isError:!0}}let Y=await this.permissions.authorize(Z,$,w);if(await this.events.emit("permission.requested",{name:$.name,callId:$.callId,risk:Y.risk,allowed:Y.allowed},W),!Y.allowed)return{content:`permission.denied: ${$.name} was not authorized`,isError:!0};let G=QW({name:Z.name,risk:Y.risk,inputSchema:Z.inputSchema,input:$.input});await this.events.emit("tool.started",{name:$.name,callId:$.callId,summary:G.summary},W);let J=Date.now(),T,Q=new AbortController,M=()=>Q.abort(w.reason);if(w.aborted)M();else w.addEventListener("abort",M,{once:!0});let z=setTimeout(()=>Q.abort(Error(`Tool timed out after ${this.timeoutMs}ms`)),this.timeoutMs);try{let N=Q.signal.aborted?Promise.reject(Q.signal.reason):new Promise((B,K)=>{Q.signal.addEventListener("abort",()=>K(Q.signal.reason),{once:!0})});T=await Promise.race([Z.execute($.input,{workspace:this.workspace,signal:Q.signal}),N]),T={...T,content:l1(T.content,50000)}}catch(N){T={content:`${!w.aborted&&Q.signal.aborted?"tool.timeout (abort requested; tools must cooperate)":"tool.internal_error"}: ${N instanceof Error?N.message:String(N)}`,isError:!0}}finally{clearTimeout(z),w.removeEventListener("abort",M)}return await this.events.emit("tool.completed",{name:$.name,callId:$.callId,isError:T.isError??!1,durationMs:Date.now()-J},W),T}}import{createHash as UL,randomUUID as HL}from"node:crypto";import{readdir as FL,readFile as OL,realpath as EL,stat as kM}from"node:fs/promises";import AM from"node:path";import{pathToFileURL as q3}from"node:url";class o4{builtins;events;auto;trust;importer;static defaultImporter=($)=>import($);#$=new Map;constructor($,w,W,Z,X=o4.defaultImporter){this.builtins=$;this.events=w;this.auto=W;this.trust=Z;this.importer=X}async load($,w){let W=w?.clone()??new W$(this.builtins),Z=[],X=[];for(let Y of $)try{let G=await EL(Y.path),J=await kM(G),T=J.isDirectory()?G:AM.dirname(G);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=J.isDirectory()?(await FL(G)).filter((M)=>M.endsWith(".ts")).sort().map((M)=>AM.join(G,M)):G.endsWith(".ts")?[G]:[];for(let M of Q)try{let z=await this.importPlugin(M);if(!LL(z.default))throw Error("default export is not a ToolDefinition");W.register(z.default,{kind:"local",path:M}),Z.push(z.default.name),await this.events.emit("plugin.loaded",{path:M,name:z.default.name})}catch(z){X.push(M),await this.events.emit("plugin.failed",{path:M,message:z instanceof Error?z.message:String(z)})}}catch(G){if(G.code!=="ENOENT")X.push(Y.path),await this.events.emit("plugin.failed",{path:Y.path,message:G instanceof Error?G.message:String(G)})}return{registry:W,loaded:Z,failed:X}}async importPlugin($){if(this.importer!==o4.defaultImporter){let G=(await kM($)).mtimeMs;return this.importer(`${q3($).href}?mtime=${G}`)}let w=await OL($,"utf8"),W=UL("sha256").update(w).digest("hex"),Z=this.#$.get($);if(Z?.hash===W)return Z.module;let X=`// coden-source: ${q3($).href}
196
+ `);this.baseURL=G.baseURL,this.timeout=G.timeout??KX.DEFAULT_TIMEOUT,this.logger=G.logger??console;let J="warn";this.logLevel=J,this.logLevel=cZ(G.logLevel,"ClientOptions.logLevel",this)??cZ(a$("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??J,this.fetchOptions=G.fetchOptions,this.maxRetries=G.maxRetries??2,this.fetch=G.fetch??DQ(),C(this,TW,AQ,"f"),this._options=G,this.apiKey=typeof w==="string"?w:"Missing Key",this.organization=W,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 D([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery($){return mZ($,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${p$}`}defaultIdempotencyKey(){return`stainless-node-retry-${yZ()}`}makeStatusError($,w,W,Z){return Y0.generate($,w,W,Z)}async _callApiKey(){let $=this._options.apiKey;if(typeof $!=="function")return!1;let w;try{w=await $()}catch(W){if(W instanceof k)throw W;throw new k(`Failed to get token from 'apiKey' function: ${W.message}`,{cause:W})}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,W){let Z=!V(this,NX,"m",UM).call(this)&&W||this.baseURL,X=PQ($)?new URL($):new URL(Z+(Z.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),Y=this.defaultQuery();if(!VQ(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:W}){}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,W){return this.request(Promise.resolve(W).then((Z)=>{return{method:$,path:w,...Z}}))}request($,w=null){return new E1(this,this.makeRequest($,w,void 0))}async makeRequest($,w,W){let Z=await $,X=Z.maxRetries??this.maxRetries;if(w==null)w=X;await this.prepareOptions(Z);let{req:Y,url:G,timeout:J}=await this.buildRequest(Z,{retryCount:X-w});await this.prepareRequest(Y,{url:G,options:Z});let T="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),Q=W===void 0?"":`, retryOf: ${W}`,M=Date.now();if(Z0(this).debug(`[${T}] sending request`,k$({retryOfRequestLogID:W,method:Z.method,url:G,options:Z,headers:Y.headers})),Z.signal?.aborted)throw new T0;let z=new AbortController,N=await this.fetchWithTimeout(G,Y,J,z).catch(X9),B=Date.now();if(N instanceof globalThis.Error){let q=`retrying, ${w} attempts remaining`;if(Z.signal?.aborted)throw new T0;let f=Z9(N)||/timed? ?out/i.test(String(N)+("cause"in N?String(N.cause):""));if(w)return Z0(this).info(`[${T}] connection ${f?"timed out":"failed"} - ${q}`),Z0(this).debug(`[${T}] connection ${f?"timed out":"failed"} (${q})`,k$({retryOfRequestLogID:W,url:G,durationMs:B-M,message:N.message})),this.retryRequest(Z,w,W??T);if(Z0(this).info(`[${T}] connection ${f?"timed out":"failed"} - error; no more retries left`),Z0(this).debug(`[${T}] connection ${f?"timed out":"failed"} (error; no more retries left)`,k$({retryOfRequestLogID:W,url:G,durationMs:B-M,message:N.message})),f)throw new O1;throw new F1({cause:N})}let K=[...N.headers.entries()].filter(([q])=>q==="x-request-id").map(([q,f])=>", "+q+": "+JSON.stringify(f)).join(""),P=`[${T}${Q}${K}] ${Y.method} ${G} ${N.ok?"succeeded":"failed"} with status ${N.status} in ${B-M}ms`;if(!N.ok){let q=await this.shouldRetry(N);if(w&&q){let j=`retrying, ${w} attempts remaining`;return await kQ(N.body),Z0(this).info(`${P} - ${j}`),Z0(this).debug(`[${T}] response error (${j})`,k$({retryOfRequestLogID:W,url:N.url,status:N.status,headers:N.headers,durationMs:B-M})),this.retryRequest(Z,w,W??T,N.headers)}let f=q?"error; no more retries left":"error; not retryable";Z0(this).info(`${P} - ${f}`);let H=await N.text().catch((j)=>X9(j).message),E=UQ(H),S=E?void 0:H;throw Z0(this).debug(`[${T}] response error (${f})`,k$({retryOfRequestLogID:W,url:N.url,status:N.status,headers:N.headers,message:S,durationMs:Date.now()-M})),this.makeStatusError(N.status,E,S,N.headers)}return Z0(this).info(P),Z0(this).debug(`[${T}] response start`,k$({retryOfRequestLogID:W,url:N.url,status:N.status,headers:N.headers,durationMs:B-M})),{response:N,options:Z,controller:z,requestLogID:T,retryOfRequestLogID:W,startTime:M}}getAPIList($,w,W){return this.requestAPIList(w,{method:"get",path:$,...W})}requestAPIList($,w){let W=this.makeRequest(w,null,void 0);return new m6(this,W,$)}async fetchWithTimeout($,w,W,Z){let{signal:X,method:Y,...G}=w||{};if(X)X.addEventListener("abort",()=>Z.abort());let J=setTimeout(()=>Z.abort(),W),T=globalThis.ReadableStream&&G.body instanceof globalThis.ReadableStream||typeof G.body==="object"&&G.body!==null&&Symbol.asyncIterator in G.body,Q={signal:Z.signal,...T?{duplex:"half"}:{},method:"GET",...G};if(Y)Q.method=Y.toUpperCase();try{return await this.fetch.call(void 0,$,Q)}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,W,Z){let X,Y=Z?.get("retry-after-ms");if(Y){let J=parseFloat(Y);if(!Number.isNaN(J))X=J}let G=Z?.get("retry-after");if(G&&!X){let J=parseFloat(G);if(!Number.isNaN(J))X=J*1000;else X=Date.parse(G)-Date.now()}if(!(X&&0<=X&&X<60000)){let J=$.maxRetries??this.maxRetries;X=this.calculateDefaultRetryTimeoutMillis(w,J)}return await J$(X),this.makeRequest($,w-1,W)}calculateDefaultRetryTimeoutMillis($,w){let X=w-$,Y=Math.min(0.5*Math.pow(2,X),8),G=1-Math.random()*0.25;return Y*G*1000}async buildRequest($,{retryCount:w=0}={}){let W={...$},{method:Z,path:X,query:Y,defaultBaseURL:G}=W,J=this.buildURL(X,Y,G);if("timeout"in W)qQ("timeout",W.timeout);W.timeout=W.timeout??this.timeout;let{bodyHeaders:T,body:Q}=this.buildBody({options:W}),M=await this.buildHeaders({options:$,method:Z,bodyHeaders:T,retryCount:w});return{req:{method:Z,headers:M,...W.signal&&{signal:W.signal},...globalThis.ReadableStream&&Q instanceof globalThis.ReadableStream&&{duplex:"half"},...Q&&{body:Q},...this.fetchOptions??{},...W.fetchOptions??{}},url:J,timeout:W.timeout}}async buildHeaders({options:$,method:w,bodyHeaders:W,retryCount:Z}){let X={};if(this.idempotencyHeader&&w!=="get"){if(!$.idempotencyKey)$.idempotencyKey=this.defaultIdempotencyKey();X[this.idempotencyHeader]=$.idempotencyKey}let Y=D([X,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(Z),...$.timeout?{"X-Stainless-Timeout":String(Math.trunc($.timeout/1000))}:{},...LQ(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders($),this._options.defaultHeaders,W,$.headers]);return this.validateHeaders(Y),Y.values}buildBody({options:{body:$,headers:w}}){if(!$)return{bodyHeaders:void 0,body:void 0};let W=D([w]);if(ArrayBuffer.isView($)||$ instanceof ArrayBuffer||$ instanceof DataView||typeof $==="string"&&W.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:I6($)};else return V(this,TW,"f").call(this,{body:$,headers:W})}}KX=_,TW=new WeakMap,NX=new WeakSet,UM=function(){return this.baseURL!=="https://api.openai.com/v1"};_.OpenAI=KX;_.DEFAULT_TIMEOUT=600000;_.OpenAIError=k;_.APIError=Y0;_.APIConnectionError=F1;_.APIConnectionTimeoutError=O1;_.APIUserAbortError=T0;_.NotFoundError=T9;_.ConflictError=Q9;_.RateLimitError=z9;_.BadRequestError=Y9;_.AuthenticationError=G9;_.InternalServerError=N9;_.PermissionDeniedError=J9;_.UnprocessableEntityError=M9;_.InvalidWebhookSignatureError=D$;_.toFile=l6;_.Completions=Dw;_.Chat=k1;_.Embeddings=Aw;_.Files=Rw;_.Images=Iw;_.Audio=C$;_.Moderations=xw;_.Models=bw;_.FineTuning=M$;_.Graders=x1;_.VectorStores=$1;_.Webhooks=vw;_.Beta=j$;_.Batches=Ow;_.Uploads=v1;_.Responses=g1;_.Realtime=_1;_.Conversations=I1;_.Evals=b1;_.Containers=y1;class BX{client;constructor($){this.client=new _({...$,maxRetries:0})}async*stream($){let w=await this.client.chat.completions.create({model:$.model,messages:TL($.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),W=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 G of X?.tool_calls??[]){let J=G.index;if(!W.has(J))W.add(J),yield{type:"tool_call_start",index:J,callId:G.id??`call_${J}`,name:G.function?.name??""};if(G.function?.arguments)yield{type:"tool_call_delta",index:J,argumentsDelta:G.function.arguments}}if(Z.usage)yield{type:"usage",usage:{inputTokens:Z.usage.prompt_tokens,outputTokens:Z.usage.completion_tokens}}}for(let Z of W)yield{type:"tool_call_end",index:Z};yield{type:"done"}}}function TL($){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 W={role:"assistant",content:w.content||null};if(w.toolCalls.length)W.tool_calls=w.toolCalls.map((Z)=>({id:Z.callId,type:"function",function:{name:Z.name,arguments:JSON.stringify(Z.input)}}));return W})}import{createHash as QL,randomUUID as HM}from"node:crypto";import{appendFile as ML,chmod as FM,mkdir as zL,readdir as NL,readFile as OM}from"node:fs/promises";import u1 from"node:path";var KL=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;function EM($){return KL.test($)}function PX($){return QL("sha256").update(u1.resolve($)).digest("hex").slice(0,16)}class VX{workspace;sessionId;sessionPath;tracePath;#$=Promise.resolve();#w=!1;constructor($,w,W=HM()){this.workspace=w;this.sessionId=W;if(!EM(W))throw Error("Invalid session ID");let Z=u1.join($,"sessions",PX(w));this.sessionPath=u1.join(Z,`${W}.jsonl`),this.tracePath=u1.join(Z,`${W}.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 W={version:1,id:HM(),timestamp:new Date().toISOString(),type:$,data:w},Z=this.#$.then(async()=>{let X=u1.dirname(this.sessionPath);await zL(X,{recursive:!0,mode:448}),await FM(X,448),await ML(this.sessionPath,`${JSON.stringify(W)}
197
+ `,{encoding:"utf8",mode:384}),await FM(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 $=u1.dirname(this.sessionPath),w;try{w=await NL($)}catch(Z){if(Z.code==="ENOENT")return[];throw Z}let W=[];for(let Z of w){if(!Z.endsWith(".jsonl")||Z.endsWith(".trace.jsonl"))continue;let X=Z.slice(0,-6);if(!EM(X))continue;try{W.push(await this.#W(u1.join($,Z),X))}catch{}}return W.sort((Z,X)=>X.lastActivity.localeCompare(Z.lastActivity)),W}async#W($,w){let W=await OM($,"utf8"),Z=0,X,Y,G="";for(let Q of W.split(`
198
+ `)){if(!Q)continue;let M;try{M=JSON.parse(Q)}catch{continue}if(M.version!==1)continue;if(M.timestamp)G=M.timestamp;switch(M.type){case"session.reset":Z=0,Y=void 0,X=void 0;break;case"session.title":{let z=M.data;if(typeof z?.title==="string")X=z.title;break}case"message":if(Z++,Y===void 0){let z=M.data;if(z?.role==="user"&&typeof z.content==="string")Y=z.content}break}}let J=X??Y,T={id:w,messageCount:Z,lastActivity:G};if(J!==void 0)T.title=J;return T}async recover(){let $=[],w=[],W,Z,X=await OM(this.sessionPath,"utf8");this.#w=!0;let Y=X.split(`
199
+ `),G=-1;for(let Q=Y.length-1;Q>=0;Q--)if(Y[Q]){G=Q;break}for(let Q=0;Q<Y.length;Q++){let M=Y[Q];if(!M)continue;let z;try{z=JSON.parse(M)}catch(N){if(Q===G){w.push("Ignored incomplete final JSONL record");break}throw LM(Q,N)}try{if(z.version!==1)throw Error("unsupported schema version");if(z.type==="session.reset")$.length=0,W=void 0,Z=void 0;if(z.type==="message"){if(!BL(z.data))throw Error("invalid message structure");$.push(z.data)}if(z.type==="context.compacted"){let N=z.data;if(typeof N?.summary!=="string")throw Error("invalid compaction record");W=N.summary,Z=typeof N.sourceRange?.start==="number"&&typeof N.sourceRange.end==="number"?{start:N.sourceRange.start,end:N.sourceRange.end}:void 0}}catch(N){throw LM(Q,N)}}let J=PL($,w);for(let Q of J)await this.appendMessage(Q);let T={messages:$,warnings:w};if(W!==void 0)T.summary=W;if(Z!==void 0)T.compactionRange=Z;return T}}function BL($){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((W)=>!!W&&typeof W==="object"&&typeof W.callId==="string"&&typeof W.name==="string"&&("input"in W));return w.role==="tool"&&typeof w.callId==="string"&&typeof w.name==="string"&&typeof w.content==="string"&&typeof w.isError==="boolean"}function LM($,w){return Error(`Invalid session record at line ${$+1}: ${w instanceof Error?w.message:String(w)}`)}function PL($,w){let W=new Map,Z=new Set;for(let Y of $)if(Y.role==="assistant"){if(W.size>0)throw Error("Assistant message appeared before pending tool results");for(let G of Y.toolCalls){if(Z.has(G.callId))throw Error(`Duplicate tool call ID: ${G.callId}`);Z.add(G.callId),W.set(G.callId,G.name)}}else if(Y.role==="tool"){if(!W.delete(Y.callId))throw Error(`Orphan tool result: ${Y.callId}`)}else if(W.size>0)throw Error(`${Y.role} message appeared before pending tool results`);if(W.size===0)return[];let X=[];for(let[Y,G]of W){let J={role:"tool",callId:Y,name:G,content:"runtime.interrupted: tool execution did not complete before the previous process exited",isError:!0};$.push(J),X.push(J)}return w.push(`Recovered ${W.size} interrupted tool call(s)`),X}function DM(){return[a8,e8,s8,p8]}var VL={maxLines:20,maxValueChars:2000,maxDepth:4,maxSummaryColumns:120};function h1($){return typeof $==="object"&&$!==null&&!Array.isArray($)?$:void 0}function kM($,w){let W=h1(w?.properties),Z=W?Object.keys(W).filter((X)=>(X in $)):[];return[...Z,...Object.keys($).filter((X)=>!Z.includes(X))]}function fL($,w){return h1(h1($?.properties)?.[w])}function qL($,w){let W=X0($),Z=Array.from(W);if(Z.length<=w)return W;let X=Z.length-w;return`${Z.slice(0,w).join("")}… [${X} characters omitted]`}function QW($,w){if(typeof $==="string")return qL($,w.maxValueChars);if($===null)return"null";if(typeof $==="number"||typeof $==="boolean"||typeof $==="bigint")return String($);if($===void 0)return"undefined";return}function MW($,w={}){let W={...VL,...w},Z=X0($.name);try{let X=[],Y=new WeakSet,G=Math.max(0,W.maxLines),J=(N)=>{if(X.length<=G)X.push(N)},T=(N,B,K,P,q)=>{if(X.length>G)return;let f=q===void 0?void 0:X0(q),H=QW(N,W);if(H!==void 0){let j=H.split(`
200
+ `);if(f!==void 0&&j.length===1)J(`${P}${f}: ${H}`);else if(f!==void 0){J(`${P}${f}:`);for(let g of j)J(`${P} ${g}`)}else for(let g of j)J(`${P}${g}`);return}if(K>=W.maxDepth){J(`${P}${f===void 0?"":`${f}: `}[max depth]`);return}if(typeof N!=="object"||N===null){J(`${P}${f===void 0?"":`${f}: `}${X0(String(N))}`);return}if(Y.has(N)){J(`${P}${f===void 0?"":`${f}: `}[circular]`);return}if(Y.add(N),Array.isArray(N)){if(N.length===0){J(`${P}${f===void 0?"":`${f}: `}[]`);return}if(f!==void 0)J(`${P}${f}:`);let j=f===void 0?P:`${P} `,g=h1(B?.items);for(let s of N){if(X.length>G)break;let e=QW(s,W);if(e!==void 0&&!e.includes(`
201
+ `))J(`${j}- ${e}`);else J(`${j}-`),T(s,g,K+1,`${j} `)}return}let E=N,S=kM(E,B);if(S.length===0){J(`${P}${f===void 0?"":`${f}: `}{}`);return}if(f!==void 0)J(`${P}${f}:`);let A=f===void 0?P:`${P} `;for(let j of S){if(X.length>G)break;T(E[j],fL(B,j),K+1,A,j)}};T($.input,h1($.inputSchema),0,"");let Q=X;if(Q.length>G)Q=G===0?[]:[...Q.slice(0,G-1),"... [1 or more lines omitted]"];let M=Z,z=h1($.input);if(z)for(let N of kM(z,h1($.inputSchema))){let B=QW(z[N],W);if(B!==void 0){M=`${X0(N)}: ${B.split(`
202
+ `)[0]??""}`;break}}else{let N=QW($.input,W);if(N!==void 0)M=N.split(`
203
+ `)[0]??Z}return{lines:Q,summary:Yw(X0(M),W.maxSummaryColumns)}}catch{return{lines:["[unavailable]"],summary:Yw(Z,W.maxSummaryColumns)}}}class fX{registry;permissions;events;workspace;timeoutMs;constructor($,w,W,Z,X=60000){this.registry=$;this.permissions=w;this.events=W;this.workspace=Z;this.timeoutMs=X}setRegistry($){this.registry=$}async execute($,w,W){await this.events.emit("tool.requested",{name:$.name,callId:$.callId},W);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};if(["read","write","edit"].includes($.name))try{await X$(this.workspace,$.input.path)}catch(N){return{content:`permission.workspace_denied: ${N instanceof Error?N.message:String(N)}`,isError:!0}}let Y=await this.permissions.authorize(Z,$,w);if(await this.events.emit("permission.requested",{name:$.name,callId:$.callId,risk:Y.risk,allowed:Y.allowed},W),!Y.allowed)return{content:`permission.denied: ${$.name} was not authorized`,isError:!0};let G=MW({name:Z.name,risk:Y.risk,inputSchema:Z.inputSchema,input:$.input});await this.events.emit("tool.started",{name:$.name,callId:$.callId,summary:G.summary},W);let J=Date.now(),T,Q=new AbortController,M=()=>Q.abort(w.reason);if(w.aborted)M();else w.addEventListener("abort",M,{once:!0});let z=setTimeout(()=>Q.abort(Error(`Tool timed out after ${this.timeoutMs}ms`)),this.timeoutMs);try{let N=Q.signal.aborted?Promise.reject(Q.signal.reason):new Promise((B,K)=>{Q.signal.addEventListener("abort",()=>K(Q.signal.reason),{once:!0})});T=await Promise.race([Z.execute($.input,{workspace:this.workspace,signal:Q.signal}),N]),T={...T,content:l1(T.content,50000)}}catch(N){T={content:`${!w.aborted&&Q.signal.aborted?"tool.timeout (abort requested; tools must cooperate)":"tool.internal_error"}: ${N instanceof Error?N.message:String(N)}`,isError:!0}}finally{clearTimeout(z),w.removeEventListener("abort",M)}return await this.events.emit("tool.completed",{name:$.name,callId:$.callId,isError:T.isError??!1,durationMs:Date.now()-J},W),T}}import{createHash as UL,randomUUID as HL}from"node:crypto";import{readdir as FL,readFile as OL,realpath as EL,stat as AM}from"node:fs/promises";import SM from"node:path";import{pathToFileURL as qX}from"node:url";class e9{builtins;events;auto;trust;importer;static defaultImporter=($)=>import($);#$=new Map;constructor($,w,W,Z,X=e9.defaultImporter){this.builtins=$;this.events=w;this.auto=W;this.trust=Z;this.importer=X}async load($,w){let W=w?.clone()??new W$(this.builtins),Z=[],X=[];for(let Y of $)try{let G=await EL(Y.path),J=await AM(G),T=J.isDirectory()?G:SM.dirname(G);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=J.isDirectory()?(await FL(G)).filter((M)=>M.endsWith(".ts")).sort().map((M)=>SM.join(G,M)):G.endsWith(".ts")?[G]:[];for(let M of Q)try{let z=await this.importPlugin(M);if(!LL(z.default))throw Error("default export is not a ToolDefinition");W.register(z.default,{kind:"local",path:M}),Z.push(z.default.name),await this.events.emit("plugin.loaded",{path:M,name:z.default.name})}catch(z){X.push(M),await this.events.emit("plugin.failed",{path:M,message:z instanceof Error?z.message:String(z)})}}catch(G){if(G.code!=="ENOENT")X.push(Y.path),await this.events.emit("plugin.failed",{path:Y.path,message:G instanceof Error?G.message:String(G)})}return{registry:W,loaded:Z,failed:X}}async importPlugin($){if(this.importer!==e9.defaultImporter){let G=(await AM($)).mtimeMs;return this.importer(`${qX($).href}?mtime=${G}`)}let w=await OL($,"utf8"),W=UL("sha256").update(w).digest("hex"),Z=this.#$.get($);if(Z?.hash===W)return Z.module;let X=`// coden-source: ${qX($).href}
204
204
  // coden-load: ${HL()}
205
205
  ${w}
206
- //# sourceURL=${q3($).href}
207
- `,Y=await this.importer(`data:text/typescript;base64,${Buffer.from(X).toString("base64")}`);return this.#$.set($,{hash:W,module:Y}),Y}}function LL($){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 SM="0.1.3";function RM($,w){let W=$.replace(/\s+/g," ").trim();return W.length<=w?W:`${W.slice(0,w-1)}…`}function DL($){let w=new Date($);if(Number.isNaN(w.getTime()))return $;let W=(Z)=>String(Z).padStart(2,"0");return`${w.getFullYear()}-${W(w.getMonth()+1)}-${W(w.getDate())} ${W(w.getHours())}:${W(w.getMinutes())}`}function U3($,w){if($.length===0)return`No sessions found.
208
- `;let W=$.map((X)=>{let Y=X.title?RM(X.title,40):"(no title)",G=X.messageCount===0?"new session":`${X.messageCount} messages`,J=X.id===w?" *":"";return`${X.id}${J} ${Y} (${G}, ${DL(X.lastActivity)})`}),Z=w?`Current session: ${w}
206
+ //# sourceURL=${qX($).href}
207
+ `,Y=await this.importer(`data:text/typescript;base64,${Buffer.from(X).toString("base64")}`);return this.#$.set($,{hash:W,module:Y}),Y}}function LL($){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 RM="0.1.4";var UX=2000;function DL($,w){let W=$.replace(/\s+/g," ").trim();return W.length<=w?W:`${W.slice(0,w-1)}…`}function kL($){let w=new Date($);if(Number.isNaN(w.getTime()))return $;let W=(Z)=>String(Z).padStart(2,"0");return`${w.getFullYear()}-${W(w.getMonth()+1)}-${W(w.getDate())} ${W(w.getHours())}:${W(w.getMinutes())}`}function HX($,w){if($.length===0)return`No sessions found.
208
+ `;let W=$.map((X)=>{let Y=X.title?DL(X.title,40):"(no title)",G=X.messageCount===0?"new session":`${X.messageCount} messages`,J=X.id===w?" *":"";return`${X.id}${J} ${Y} (${G}, ${kL(X.lastActivity)})`}),Z=w?`Current session: ${w}
209
209
  `:"";return`${W.join(`
210
210
  `)}
211
- ${Z}`}function CM($,w,W){let X=QW({name:$.name,risk:W,inputSchema:$.inputSchema,input:w.input}).lines.map((G)=>` ${G}`).join(`
212
- `),Y=W==="dangerous"?"[y]es / [N]o":"[y]es / [s]ession / [N]o";return`${W.toUpperCase()} ${$.name}
211
+ ${Z}`}function CM($,w,W,Z=80){let X=MW({name:$.name,risk:W,inputSchema:$.inputSchema,input:w.input},{maxLines:1/0,maxValueChars:1/0,maxDepth:1/0}),Y=`${W.toUpperCase()} ${$.name}`,G=X.lines.map((Q)=>` ${Q}`).join(`
212
+ `),J=W==="dangerous"?"[y]es / [N]o":"[y]es / [s]ession / [N]o",T=AL(Z);return`${T}
213
+ ${Y}
213
214
 
214
- ${X}
215
+ ${G}
216
+ ${T}
217
+ Allow? ${J}: `}function AL($){return"─".repeat(Math.max(1,$))}function jM($,w){let W=(Y)=>Y.role==="user"||Y.role==="assistant",Z=[`Resumed session ${$} (${w.length} messages).`];for(let Y of w.filter(W))Z.push(Y.role==="user"?SL(Y.content):RL(Y.content));let X=jL(w);if(X)Z.push(X);return Z.join(`
215
218
 
216
- Allow? ${Y}: `}function jM($,w){let W=w.length,Z=w.filter((Y)=>Y.role==="user"||Y.role==="assistant").slice(-3),X=[`Resumed session ${$} (${W} messages).`,`Showing last ${Z.length} of ${W} messages.`];for(let Y of Z){let G=Y.role==="user"?"user":"assistant";X.push(`┌ ${G.padEnd(9)} ${RM(Y.content,120)}`)}return X.join(`
217
- `)}class hw extends Error{}async function SL($,w){try{return await bJ($,w)}catch(W){throw new hw(`configuration: ${W instanceof Error?W.message:String(W)}`,{cause:W})}}async function IM($,w){let W=process.cwd(),Z=await SL(W,{...w.provider?{provider:w.provider}:{},...w.model?{model:w.model}:{},...w.maxSteps?{maxSteps:w.maxSteps}:{},plugins:w.plugin}),X=new m5,G=!w.auto||!$&&!w.print?AL({input:kL,output:process.stderr}):void 0,J=typeof w.resume==="string"?w.resume:void 0,T=new V3(Z.dataDir,W,J);if(w.resume===!0){G?.close(),$$.write(U3(await T.list()));return}let Q,M,z=0,N;if(typeof w.resume==="string"){let $0=await T.recover();Q=$0.messages,M=$0.summary,z=$0.compactionRange?.end??0;for(let y$ of $0.warnings)process.stderr.write(`coden: ${y$}
218
- `);if(!w.print)N=jM(T.sessionId,$0.messages)}let B=new GZ(T.tracePath,X,()=>T.isCreated),K=new YZ(X,{verbose:w.verbose,printMode:w.print}),P;try{P=jL(Z.provider)}catch($0){throw new hw(`provider: ${$0 instanceof Error?$0.message:String($0)}`,{cause:$0})}let q=LM(),f=w.auto?void 0:IL(H3(G)),H=new JZ(w.auto,f),E=new W$(q),S=new f3(E,H,X,W),A=new h5(MW.join(l8(),"trusted-workspaces.json")),j=new o4(q,X,w.auto,async($0)=>{if(await A.isTrusted($0))return!0;let y$=await bL(H3(G),`Project plugins at ${$0} run with full process permissions. Trust? [y/N] `);if(y$)await A.trust($0);return y$}),g=new C5,s=B9(W,"global",Z.dataDir),e=B9(W,"project",Z.dataDir),i=[{path:MW.join(l8(),"plugins"),project:!1},{path:MW.join(W,".coden","plugins"),project:!0},...Z.plugins.map(($0)=>({path:MW.resolve(W,$0),project:!0}))],F0=new Map,w1=async()=>{await new j0(s).recover(),await new j0(e).recover();let $0=await yM(g,s,X,"global"),NW=w.auto||await A.isWorkspaceTrusted(W)?await yM(g,e,X,"project"):{loaded:[],failed:[],unavailable:!0};if(NW.unavailable)await X.emit("plugin.unavailable",{source:"npm",scope:"project",path:e.root,reason:"workspace is not trusted; run coden plugin install or sync after trusting"});let D3=await RL(q,$0.loaded,NW.loaded,X);for(let{scope:lM,plugin:iw}of D3.effective){let KW=`${lM}:${iw.version}`,e4=F0.get(iw.packageName);if(e4&&e4!==KW)await X.emit("plugin.restart_required",{source:"npm",packageName:iw.packageName,loadedIdentity:e4,diskIdentity:KW,loadedVersion:e4.split(":").slice(1).join(":"),diskVersion:iw.version,reason:"npm plugin metadata changed; restart CodeN to load it"});F0.set(iw.packageName,KW)}return{composed:D3,global:$0,project:NW}},z$=async()=>{let $0=await w1(),y$=await j.load(i,$0.composed.registry);return E.replaceWith(y$.registry),y$};await z$();let i1=await CL(W),uw=new u5({contextWindow:Z.contextWindow,reservedOutputTokens:Z.reservedOutputTokens,safetyMargin:Z.safetyMargin});if(M)uw.setSummary(M,z);let L3=new l5(P,E,S,uw,T,X,{model:Z.model,maxSteps:Z.maxSteps,systemPrompt:"You are CodeN, a concise coding agent. Inspect before editing, use tools carefully, and verify changes."+(i1?`
219
+ `)}function SL($){return $.split(`
220
+ `).map((w,W)=>W===0?`> ${w}`:` ${w}`).join(`
221
+ `)}function RL($){let{text:w,omitted:W}=CL($),Z="",X=new E4((G)=>{Z+=G});if(X.push(w),X.complete(),!W)return Z;return`${Z.endsWith(`
222
+ `)?Z:`${Z}
223
+ `}…(已省略 ${W} 个字符)`}function CL($){let w=[...$];return w.length<=UX?{text:$,omitted:0}:{text:w.slice(0,UX).join(""),omitted:w.length-UX}}function jL($){let w=new Map;for(let G of $)if(G.role==="assistant")for(let J of G.toolCalls)w.set(J.name,(w.get(J.name)??0)+1);if(w.size===0)return;let W=[...w.values()].reduce((G,J)=>G+J,0),Z=0;for(let G of $)if(G.role==="tool"&&G.isError)Z++;let X=[...w.entries()].sort((G,J)=>J[1]-G[1]||G[0].localeCompare(J[0])).map(([G,J])=>`${G} ×${J}`).join(", "),Y=`Tools: ${W} calls — ${X}`;return Z>0?`${Y}; ${Z} failed`:Y}class uw extends Error{}async function bL($,w){try{return await xJ($,w)}catch(W){throw new uw(`configuration: ${W instanceof Error?W.message:String(W)}`,{cause:W})}}async function IM($,w){let W=process.cwd(),Z=await bL(W,{...w.provider?{provider:w.provider}:{},...w.model?{model:w.model}:{},...w.maxSteps?{maxSteps:w.maxSteps}:{},plugins:w.plugin}),X=new l5,G=!w.auto||!$&&!w.print?IL({input:yL,output:process.stderr}):void 0,J=typeof w.resume==="string"?w.resume:void 0,T=new VX(Z.dataDir,W,J);if(w.resume===!0){G?.close(),c0.write(HX(await T.list()));return}let Q,M,z=0,N;if(typeof w.resume==="string"){let $0=await T.recover();Q=$0.messages,M=$0.summary,z=$0.compactionRange?.end??0;for(let y$ of $0.warnings)process.stderr.write(`coden: ${y$}
224
+ `);if(!w.print)N=jM(T.sessionId,$0.messages)}let B=new GZ(T.tracePath,X,()=>T.isCreated),K=new YZ(X,{verbose:w.verbose,printMode:w.print}),P;try{P=gL(Z.provider)}catch($0){throw new uw(`provider: ${$0 instanceof Error?$0.message:String($0)}`,{cause:$0})}let q=DM(),f=w.auto?void 0:uL(FX(G)),H=new JZ(w.auto,f),E=new W$(q),S=new fX(E,H,X,W),A=new h5(zW.join(c8(),"trusted-workspaces.json")),j=new e9(q,X,w.auto,async($0)=>{if(await A.isTrusted($0))return!0;let y$=await hL(FX(G),`Project plugins at ${$0} run with full process permissions. Trust? [y/N] `);if(y$)await A.trust($0);return y$}),g=new j5,s=B4(W,"global",Z.dataDir),e=B4(W,"project",Z.dataDir),i=[{path:zW.join(c8(),"plugins"),project:!1},{path:zW.join(W,".coden","plugins"),project:!0},...Z.plugins.map(($0)=>({path:zW.resolve(W,$0),project:!0}))],F0=new Map,w1=async()=>{await new j0(s).recover(),await new j0(e).recover();let $0=await yM(g,s,X,"global"),KW=w.auto||await A.isWorkspaceTrusted(W)?await yM(g,e,X,"project"):{loaded:[],failed:[],unavailable:!0};if(KW.unavailable)await X.emit("plugin.unavailable",{source:"npm",scope:"project",path:e.root,reason:"workspace is not trusted; run coden plugin install or sync after trusting"});let kX=await xL(q,$0.loaded,KW.loaded,X);for(let{scope:lM,plugin:iw}of kX.effective){let BW=`${lM}:${iw.version}`,$8=F0.get(iw.packageName);if($8&&$8!==BW)await X.emit("plugin.restart_required",{source:"npm",packageName:iw.packageName,loadedIdentity:$8,diskIdentity:BW,loadedVersion:$8.split(":").slice(1).join(":"),diskVersion:iw.version,reason:"npm plugin metadata changed; restart CodeN to load it"});F0.set(iw.packageName,BW)}return{composed:kX,global:$0,project:KW}},z$=async()=>{let $0=await w1(),y$=await j.load(i,$0.composed.registry);return E.replaceWith(y$.registry),y$};await z$();let i1=await _L(W),hw=new i5({contextWindow:Z.contextWindow,reservedOutputTokens:Z.reservedOutputTokens,safetyMargin:Z.safetyMargin});if(M)hw.setSummary(M,z);let DX=new c5(P,E,S,hw,T,X,{model:Z.model,maxSteps:Z.maxSteps,systemPrompt:"You are CodeN, a concise coding agent. Inspect before editing, use tools carefully, and verify changes."+(i1?`
219
225
 
220
226
  Project instructions:
221
- ${i1}`:"")},Q);try{if($){await xM(L3,$,G);return}if(w.print)throw Error("print mode requires a prompt");await yL(L3,T,z$,E,H3(G),P3(W),N)}finally{G?.close(),K.dispose(),await B.flush()}}async function RL($,w,W,Z){let X=new W$($),Y=new Set(W.map((T)=>T.packageName)),G=[...w.map((T)=>({scope:"global",plugin:T})),...W.map((T)=>({scope:"project",plugin:T}))],J=[];for(let T of G){if(T.scope==="global"&&Y.has(T.plugin.packageName))continue;let Q=X.clone(),M={kind:"npm",pluginName:T.plugin.packageName,pluginVersion:T.plugin.version,path:T.plugin.entryPath};try{for(let z of T.plugin.tools)Q.register(z,M);X.replaceWith(Q),J.push(T)}catch(z){await Z.emit("plugin.failed",{source:"npm",scope:T.scope,packageName:T.plugin.packageName,version:T.plugin.version,path:T.plugin.entryPath,message:`${z instanceof Error?z.message:String(z)}; package skipped to preserve earlier tools`})}}return{registry:X,effective:J}}async function yM($,w,W,Z){try{let X=await $.loadScope(w);for(let Y of X.loaded)await W.emit("plugin.loaded",{source:"npm",scope:Z,packageName:Y.packageName,version:Y.version,path:Y.entryPath,tools:Y.tools.map((G)=>G.name)});for(let Y of X.failed)await W.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 W.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 CL($){try{return await mJ($,"AGENTS.md")}catch(w){if(w.code==="ENOENT")return"";if(w.category==="permission")return process.stderr.write(`coden: ignoring AGENTS.md: ${w.message}
222
- `),"";throw new hw(`project instructions: ${w instanceof Error?w.message:String(w)}`,{cause:w})}}function jL($){if($==="anthropic"){let W=process.env.CODEN_ANTHROPIC_API_KEY;if(!W)throw Error("CODEN_ANTHROPIC_API_KEY is required");return new jZ({apiKey:W})}let w=process.env.CODEN_OPENAI_API_KEY;if(!w)throw Error("CODEN_OPENAI_API_KEY is required");return new B3({apiKey:w,...process.env.CODEN_OPENAI_BASE_URL?{baseURL:process.env.CODEN_OPENAI_BASE_URL}:{}})}async function yL($,w,W,Z,X,Y,G){$$.write(xL),$$.write(`Version: ${SM}
223
- `),$$.write(`Workspace hash: ${Y}
224
- `),$$.write(G?`${G}
227
+ ${i1}`:"")},Q);try{if($){await xM(DX,$,G);return}if(w.print)throw Error("print mode requires a prompt");await vL(DX,T,z$,E,FX(G),PX(W),N)}finally{G?.close(),K.dispose(),await B.flush()}}async function xL($,w,W,Z){let X=new W$($),Y=new Set(W.map((T)=>T.packageName)),G=[...w.map((T)=>({scope:"global",plugin:T})),...W.map((T)=>({scope:"project",plugin:T}))],J=[];for(let T of G){if(T.scope==="global"&&Y.has(T.plugin.packageName))continue;let Q=X.clone(),M={kind:"npm",pluginName:T.plugin.packageName,pluginVersion:T.plugin.version,path:T.plugin.entryPath};try{for(let z of T.plugin.tools)Q.register(z,M);X.replaceWith(Q),J.push(T)}catch(z){await Z.emit("plugin.failed",{source:"npm",scope:T.scope,packageName:T.plugin.packageName,version:T.plugin.version,path:T.plugin.entryPath,message:`${z instanceof Error?z.message:String(z)}; package skipped to preserve earlier tools`})}}return{registry:X,effective:J}}async function yM($,w,W,Z){try{let X=await $.loadScope(w);for(let Y of X.loaded)await W.emit("plugin.loaded",{source:"npm",scope:Z,packageName:Y.packageName,version:Y.version,path:Y.entryPath,tools:Y.tools.map((G)=>G.name)});for(let Y of X.failed)await W.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 W.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 _L($){try{return await lJ($,"AGENTS.md")}catch(w){if(w.code==="ENOENT")return"";if(w.category==="permission")return process.stderr.write(`coden: ignoring AGENTS.md: ${w.message}
228
+ `),"";throw new uw(`project instructions: ${w instanceof Error?w.message:String(w)}`,{cause:w})}}function gL($){if($==="anthropic"){let W=process.env.CODEN_ANTHROPIC_API_KEY;if(!W)throw Error("CODEN_ANTHROPIC_API_KEY is required");return new jZ({apiKey:W})}let w=process.env.CODEN_OPENAI_API_KEY;if(!w)throw Error("CODEN_OPENAI_API_KEY is required");return new BX({apiKey:w,...process.env.CODEN_OPENAI_BASE_URL?{baseURL:process.env.CODEN_OPENAI_BASE_URL}:{}})}async function vL($,w,W,Z,X,Y,G){c0.write(iL),c0.write(`Version: ${RM}
229
+ `),c0.write(`Workspace hash: ${Y}
230
+ `),c0.write(G?`${G}
231
+
225
232
  Type /help for commands.
226
233
  `:`CodeN session ${w.sessionId}. Type /help for commands.
227
- `);while(!0){let J=(await F3(X,"> ")).trim();if(J===bM)break;if(!J)continue;if(J==="/quit")break;if(J==="/help"){$$.write(`/help /session /sessions /compact /reload /new /quit
228
- `);continue}if(J==="/sessions"){$$.write(U3(await w.list(),w.sessionId));continue}if(J==="/session"){$$.write(`${w.sessionId}
229
- `);continue}if(J==="/compact"){await $.compact(),$$.write(`Context compacted.
230
- `);continue}if(J==="/new"){await $.reset(),$$.write(`Started a new conversation in this session.
231
- `);continue}if(J==="/reload"){let T=await W();$$.write(`Loaded: ${T.loaded.join(", ")||"none"}; failed: ${T.failed.length}; tools: ${Z.list().map((Q)=>Q.name).join(", ")}
232
- `);continue}await xM($,J,X)}}function IL($){return async(w,W,Z,X)=>{let Y=await F3($,CM(w,W,Z),X);return Y.toLowerCase()==="y"?"allow_once":Y.toLowerCase()==="s"&&Z!=="dangerous"?"allow_session":"deny"}}var bM="\x04";async function F3($,w,W){let Z=W?void 0:new AbortController,X=W??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(G){if(X?.aborted)return"";if(G.code==="ERR_USE_AFTER_CLOSE"||/readline was closed/.test(G.message))return bM;throw G}finally{if(Z)process.removeListener("SIGINT",Y),$.removeListener("SIGINT",Y)}}async function bL($,w){return/^y(?:es)?$/i.test(await F3($,w))}function H3($){if(!$)throw Error("Interactive input is unavailable");return $}async function xM($,w,W){let Z=new AbortController,X=()=>Z.abort(Error("Cancelled by user"));process.once("SIGINT",X),W?.once("SIGINT",X);try{await $.run(w,Z.signal)}catch(Y){if(!Z.signal.aborted)throw Y}finally{process.removeListener("SIGINT",X),W?.removeListener("SIGINT",X)}}function _M($){if($!=="openai"&&$!=="anthropic")throw new v5("must be openai or anthropic");return $}function gM($){let w=Number($);if(!Number.isInteger(w)||w<1)throw new v5("must be a positive integer");return w}function vM($,w){return[...w,$]}var xL=`
234
+ `);while(!0){let J=(await OX(X,"> ")).trim();if(J===bM)break;if(!J)continue;if(J==="/quit")break;if(J==="/help"){c0.write(`/help /session /sessions /compact /reload /new /quit
235
+ `);continue}if(J==="/sessions"){c0.write(HX(await w.list(),w.sessionId));continue}if(J==="/session"){c0.write(`${w.sessionId}
236
+ `);continue}if(J==="/compact"){await $.compact(),c0.write(`Context compacted.
237
+ `);continue}if(J==="/new"){await $.reset(),c0.write(`Started a new conversation in this session.
238
+ `);continue}if(J==="/reload"){let T=await W();c0.write(`Loaded: ${T.loaded.join(", ")||"none"}; failed: ${T.failed.length}; tools: ${Z.list().map((Q)=>Q.name).join(", ")}
239
+ `);continue}await xM($,J,X)}}function uL($){return async(w,W,Z,X)=>{let Y=c0.columns??80,G=await OX($,CM(w,W,Z,Y),X);return G.toLowerCase()==="y"?"allow_once":G.toLowerCase()==="s"&&Z!=="dangerous"?"allow_session":"deny"}}var bM="\x04";async function OX($,w,W){let Z=W?void 0:new AbortController,X=W??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(G){if(X?.aborted)return"";if(G.code==="ERR_USE_AFTER_CLOSE"||/readline was closed/.test(G.message))return bM;throw G}finally{if(Z)process.removeListener("SIGINT",Y),$.removeListener("SIGINT",Y)}}async function hL($,w){return/^y(?:es)?$/i.test(await OX($,w))}function FX($){if(!$)throw Error("Interactive input is unavailable");return $}async function xM($,w,W){let Z=new AbortController,X=()=>Z.abort(Error("Cancelled by user"));process.once("SIGINT",X),W?.once("SIGINT",X);try{await $.run(w,Z.signal)}catch(Y){if(!Z.signal.aborted)throw Y}finally{process.removeListener("SIGINT",X),W?.removeListener("SIGINT",X)}}function _M($){if($!=="openai"&&$!=="anthropic")throw new u5("must be openai or anthropic");return $}function gM($){let w=Number($);if(!Number.isInteger(w)||w<1)throw new u5("must be a positive integer");return w}function vM($,w){return[...w,$]}var iL=`
233
240
  ██████╗ ██████╗ ██████╗ ███████╗███╗ ██╗
234
241
  ██╔════╝██╔═══██╗██╔══██╗██╔════╝████╗ ██║
235
242
  ██║ ██║ ██║██║ ██║█████╗ ██╔██╗ ██║
236
243
  ██║ ██║ ██║██║ ██║██╔══╝ ██║╚██╗██║
237
244
  ╚██████╗╚██████╔╝██████╔╝███████╗██║ ╚████║
238
245
  ╚═════╝ ╚═════╝ ╚═════╝ ╚══════╝╚═╝ ╚═══╝
239
- `;function uM($,w){let W=$.command("plugin").description("manage installed npm plugins");W.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)=>zW(w,async()=>{let Y=O3(X);if(!await E3(w,"Install",Z,X))return;let G=await w.service.install(Z,Y);w.stdout.write(_L(G,Y.allowScripts))})),W.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)=>zW(w,async()=>{let Y=O3(X);if(!await E3(w,"Remove",Z,X))return;await w.service.remove(Z,Y),w.stdout.write(`Removed ${Z} from ${Y.scope} plugins.
246
+ `;function hM($,w){let W=$.command("plugin").description("manage installed npm plugins");W.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)=>NW(w,async()=>{let Y=EX(X);if(!await LX(w,"Install",Z,X))return;let G=await w.service.install(Z,Y);w.stdout.write(mL(G,Y.allowScripts))})),W.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)=>NW(w,async()=>{let Y=EX(X);if(!await LX(w,"Remove",Z,X))return;await w.service.remove(Z,Y),w.stdout.write(`Removed ${Z} from ${Y.scope} plugins.
240
247
  Restart CodeN to use npm plugin changes.
241
- `)})),W.command("list").option("--project","show only project plugins").option("--global","show only user-global plugins").action((Z)=>zW(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(vL(X,Z))})),W.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)=>zW(w,async()=>{let X=O3(Z);if(!await E3(w,"Sync",`${X.scope} plugins`,Z))return;let Y=await w.service.sync(X);w.stdout.write(gL(X.scope,Y,X.allowScripts))}))}function O3($){return{scope:$.global?"global":"project",allowScripts:$.allowScripts===!0}}async function E3($,w,W,Z){if(!Z.yes){if(!await $.confirm(`${w} ${W}? 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.
242
- `),!Z.yes){if(!await $.confirm("Allow npm lifecycle scripts to run with full user permissions?"))return!1}}return!0}async function zW($,w){try{await w()}catch(W){$.stderr.write(`coden: ${hL(W)}
243
- `),process.exitCode=2}}function _L($,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(`
244
- `)}function gL($,w,W){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: ${W?"enabled":"disabled"}`,"Restart CodeN to use npm plugin changes.",""].join(`
245
- `)}function vL($,w){let W=[];if(!w.global)W.push(hM("Project plugins",$.project));if(!w.project)W.push(hM("Global plugins",$.global));return`${W.join(`
248
+ `)})),W.command("list").option("--project","show only project plugins").option("--global","show only user-global plugins").action((Z)=>NW(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(cL(X,Z))})),W.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)=>NW(w,async()=>{let X=EX(Z);if(!await LX(w,"Sync",`${X.scope} plugins`,Z))return;let Y=await w.service.sync(X);w.stdout.write(lL(X.scope,Y,X.allowScripts))}))}function EX($){return{scope:$.global?"global":"project",allowScripts:$.allowScripts===!0}}async function LX($,w,W,Z){if(!Z.yes){if(!await $.confirm(`${w} ${W}? 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.
249
+ `),!Z.yes){if(!await $.confirm("Allow npm lifecycle scripts to run with full user permissions?"))return!1}}return!0}async function NW($,w){try{await w()}catch(W){$.stderr.write(`coden: ${dL(W)}
250
+ `),process.exitCode=2}}function mL($,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(`
251
+ `)}function lL($,w,W){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: ${W?"enabled":"disabled"}`,"Restart CodeN to use npm plugin changes.",""].join(`
252
+ `)}function cL($,w){let W=[];if(!w.global)W.push(uM("Project plugins",$.project));if(!w.project)W.push(uM("Global plugins",$.global));return`${W.join(`
246
253
  `)}
247
- `}function hM($,w){let W=w.slice().sort((X,Y)=>X.packageName.localeCompare(Y.packageName));if(W.length===0)return`${$}: none
254
+ `}function uM($,w){let W=w.slice().sort((X,Y)=>X.packageName.localeCompare(Y.packageName));if(W.length===0)return`${$}: none
248
255
  `;let Z=W.map((X)=>{let Y=X.shadowedByProject?" (shadowed by project)":"";return` ${X.packageName}@${X.version} requested ${X.requested}; ${X.tools.length} tool(s)${Y}`});return`${$}:
249
256
  ${Z.join(`
250
257
  `)}
251
- `}function hL($){let w=$ instanceof Error?$.message:String($);for(let W of Object.values(process.env)){if(!W||W.length<8)continue;w=w.split(W).join("[redacted]")}return w}function cL($={}){let w=$.confirm??nL,W=$.pluginService??dL(w),Z=new l3().name("coden").description("CodeN \u2014 a minimal coding agent").version(tJ).argument("[prompt]","task to execute").option("-p, --print","non-interactive print mode",!1).option("--provider <provider>","openai or anthropic",_M).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",gM).option("--plugin <path>","additional local TypeScript plugin or directory",vM,[]).action((X,Y)=>IM(X,Y));return uM(Z,{service:W,confirm:w,stdout:process.stdout,stderr:process.stderr}),Z}function dL($){let w=process.cwd(),W=new g5(w,n3(),new DW,new R5,pJ()),Z=new EW(iL.join(d3(),"trusted-workspaces.json"));return new mM(W,w,Z,$)}class mM{service;workspace;trustStore;confirm;constructor($,w,W,Z){this.service=$;this.workspace=w;this.trustStore=W;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 uL(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 nL($){let w=mL({input:process.stdin,output:process.stderr});try{let W=await w.question(`${$} [y/N] `);return/^y(?:es)?$/i.test(W)}finally{w.close()}}function pL(){let $=process.argv[1];if(!$)return!1;try{return iM(lL(import.meta.url))===iM($)}catch{return!1}}if(pL())cL().parseAsync().catch(($)=>{process.stderr.write(`coden: ${$ instanceof Error?$.message:String($)}
252
- `),process.exitCode=$ instanceof hw?2:1});export{cL as createCliProgram};
258
+ `}function dL($){let w=$ instanceof Error?$.message:String($);for(let W of Object.values(process.env)){if(!W||W.length<8)continue;w=w.split(W).join("[redacted]")}return w}function sL($={}){let w=$.confirm??oL,W=$.pluginService??aL(w),Z=new cX().name("coden").description("CodeN \u2014 a minimal coding agent").version(rJ).argument("[prompt]","task to execute").option("-p, --print","non-interactive print mode",!1).option("--provider <provider>","openai or anthropic",_M).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",gM).option("--plugin <path>","additional local TypeScript plugin or directory",vM,[]).action((X,Y)=>IM(X,Y));return hM(Z,{service:W,confirm:w,stdout:process.stdout,stderr:process.stderr}),Z}function aL($){let w=process.cwd(),W=new v5(w,pX(),new kW,new C5,tJ()),Z=new LW(pL.join(nX(),"trusted-workspaces.json"));return new mM(W,w,Z,$)}class mM{service;workspace;trustStore;confirm;constructor($,w,W,Z){this.service=$;this.workspace=w;this.trustStore=W;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 nL(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 oL($){let w=tL({input:process.stdin,output:process.stderr});try{let W=await w.question(`${$} [y/N] `);return/^y(?:es)?$/i.test(W)}finally{w.close()}}function eL(){let $=process.argv[1];if(!$)return!1;try{return iM(rL(import.meta.url))===iM($)}catch{return!1}}if(eL())sL().parseAsync().catch(($)=>{process.stderr.write(`coden: ${$ instanceof Error?$.message:String($)}
259
+ `),process.exitCode=$ instanceof uw?2:1});export{sL as createCliProgram};