botparty 0.0.51 → 0.0.53

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 (2) hide show
  1. package/dist/index.js +63 -63
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __createRequire } from "module";
3
3
  const require = __createRequire(import.meta.url);
4
- var bn=Object.create;var Kt=Object.defineProperty;var wn=Object.getOwnPropertyDescriptor;var xn=Object.getOwnPropertyNames;var kn=Object.getPrototypeOf,Sn=Object.prototype.hasOwnProperty;var ut=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var V=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ce=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),kt=(t,e)=>{for(var r in e)Kt(t,r,{get:e[r],enumerable:!0})},An=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of xn(e))!Sn.call(t,n)&&n!==r&&Kt(t,n,{get:()=>e[n],enumerable:!(s=wn(e,n))||s.enumerable});return t};var En=(t,e,r)=>(r=t!=null?bn(kn(t)):{},An(e||!t||!t.__esModule?Kt(r,"default",{value:t,enumerable:!0}):r,t));var yt=Ce(lr=>{var Ct=class extends Error{constructor(e,r,s){super(s),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=r,this.exitCode=e,this.nestedError=void 0}},cr=class extends Ct{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};lr.CommanderError=Ct;lr.InvalidArgumentError=cr});var Ot=Ce(dr=>{var{InvalidArgumentError:Li}=yt(),ur=class{constructor(e,r){switch(this.description=r||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.endsWith("...")&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(e,r){return r===this.defaultValue||!Array.isArray(r)?[e]:(r.push(e),r)}default(e,r){return this.defaultValue=e,this.defaultValueDescription=r,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(r,s)=>{if(!this.argChoices.includes(r))throw new Li(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(r,s):r},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Hi(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}dr.Argument=ur;dr.humanReadableArgName=Hi});var fr=Ce(pr=>{var{humanReadableArgName:Mi}=Ot(),hr=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let r=e.commands.filter(n=>!n._hidden),s=e._getHelpCommand();return s&&!s._hidden&&r.push(s),this.sortSubcommands&&r.sort((n,i)=>n.name().localeCompare(i.name())),r}compareOptions(e,r){let s=n=>n.short?n.short.replace(/^-/,""):n.long.replace(/^--/,"");return s(e).localeCompare(s(r))}visibleOptions(e){let r=e.options.filter(n=>!n.hidden),s=e._getHelpOption();if(s&&!s.hidden){let n=s.short&&e._findOption(s.short),i=s.long&&e._findOption(s.long);!n&&!i?r.push(s):s.long&&!i?r.push(e.createOption(s.long,s.description)):s.short&&!n&&r.push(e.createOption(s.short,s.description))}return this.sortOptions&&r.sort(this.compareOptions),r}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let r=[];for(let s=e.parent;s;s=s.parent){let n=s.options.filter(i=>!i.hidden);r.push(...n)}return this.sortOptions&&r.sort(this.compareOptions),r}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(r=>{r.description=r.description||e._argsDescription[r.name()]||""}),e.registeredArguments.find(r=>r.description)?e.registeredArguments:[]}subcommandTerm(e){let r=e.registeredArguments.map(s=>Mi(s)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(r?" "+r:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,r){return r.visibleCommands(e).reduce((s,n)=>Math.max(s,this.displayWidth(r.styleSubcommandTerm(r.subcommandTerm(n)))),0)}longestOptionTermLength(e,r){return r.visibleOptions(e).reduce((s,n)=>Math.max(s,this.displayWidth(r.styleOptionTerm(r.optionTerm(n)))),0)}longestGlobalOptionTermLength(e,r){return r.visibleGlobalOptions(e).reduce((s,n)=>Math.max(s,this.displayWidth(r.styleOptionTerm(r.optionTerm(n)))),0)}longestArgumentTermLength(e,r){return r.visibleArguments(e).reduce((s,n)=>Math.max(s,this.displayWidth(r.styleArgumentTerm(r.argumentTerm(n)))),0)}commandUsage(e){let r=e._name;e._aliases[0]&&(r=r+"|"+e._aliases[0]);let s="";for(let n=e.parent;n;n=n.parent)s=n.name()+" "+s;return s+r+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let r=[];if(e.argChoices&&r.push(`choices: ${e.argChoices.map(s=>JSON.stringify(s)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&r.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&r.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&r.push(`env: ${e.envVar}`),r.length>0){let s=`(${r.join(", ")})`;return e.description?`${e.description} ${s}`:s}return e.description}argumentDescription(e){let r=[];if(e.argChoices&&r.push(`choices: ${e.argChoices.map(s=>JSON.stringify(s)).join(", ")}`),e.defaultValue!==void 0&&r.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),r.length>0){let s=`(${r.join(", ")})`;return e.description?`${e.description} ${s}`:s}return e.description}formatItemList(e,r,s){return r.length===0?[]:[s.styleTitle(e),...r,""]}groupItems(e,r,s){let n=new Map;return e.forEach(i=>{let o=s(i);n.has(o)||n.set(o,[])}),r.forEach(i=>{let o=s(i);n.has(o)||n.set(o,[]),n.get(o).push(i)}),n}formatHelp(e,r){let s=r.padWidth(e,r),n=r.helpWidth??80;function i(d,m){return r.formatItem(d,s,m,r)}let o=[`${r.styleTitle("Usage:")} ${r.styleUsage(r.commandUsage(e))}`,""],a=r.commandDescription(e);a.length>0&&(o=o.concat([r.boxWrap(r.styleCommandDescription(a),n),""]));let c=r.visibleArguments(e).map(d=>i(r.styleArgumentTerm(r.argumentTerm(d)),r.styleArgumentDescription(r.argumentDescription(d))));if(o=o.concat(this.formatItemList("Arguments:",c,r)),this.groupItems(e.options,r.visibleOptions(e),d=>d.helpGroupHeading??"Options:").forEach((d,m)=>{let x=d.map(R=>i(r.styleOptionTerm(r.optionTerm(R)),r.styleOptionDescription(r.optionDescription(R))));o=o.concat(this.formatItemList(m,x,r))}),r.showGlobalOptions){let d=r.visibleGlobalOptions(e).map(m=>i(r.styleOptionTerm(r.optionTerm(m)),r.styleOptionDescription(r.optionDescription(m))));o=o.concat(this.formatItemList("Global Options:",d,r))}return this.groupItems(e.commands,r.visibleCommands(e),d=>d.helpGroup()||"Commands:").forEach((d,m)=>{let x=d.map(R=>i(r.styleSubcommandTerm(r.subcommandTerm(R)),r.styleSubcommandDescription(r.subcommandDescription(R))));o=o.concat(this.formatItemList(m,x,r))}),o.join(`
4
+ var bn=Object.create;var Kt=Object.defineProperty;var wn=Object.getOwnPropertyDescriptor;var xn=Object.getOwnPropertyNames;var kn=Object.getPrototypeOf,An=Object.prototype.hasOwnProperty;var ut=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var W=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ce=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),kt=(t,e)=>{for(var r in e)Kt(t,r,{get:e[r],enumerable:!0})},Sn=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of xn(e))!An.call(t,n)&&n!==r&&Kt(t,n,{get:()=>e[n],enumerable:!(s=wn(e,n))||s.enumerable});return t};var En=(t,e,r)=>(r=t!=null?bn(kn(t)):{},Sn(e||!t||!t.__esModule?Kt(r,"default",{value:t,enumerable:!0}):r,t));var yt=Ce(lr=>{var Ct=class extends Error{constructor(e,r,s){super(s),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=r,this.exitCode=e,this.nestedError=void 0}},cr=class extends Ct{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};lr.CommanderError=Ct;lr.InvalidArgumentError=cr});var Ot=Ce(dr=>{var{InvalidArgumentError:Li}=yt(),ur=class{constructor(e,r){switch(this.description=r||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.endsWith("...")&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(e,r){return r===this.defaultValue||!Array.isArray(r)?[e]:(r.push(e),r)}default(e,r){return this.defaultValue=e,this.defaultValueDescription=r,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(r,s)=>{if(!this.argChoices.includes(r))throw new Li(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(r,s):r},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Hi(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}dr.Argument=ur;dr.humanReadableArgName=Hi});var fr=Ce(pr=>{var{humanReadableArgName:Mi}=Ot(),hr=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let r=e.commands.filter(n=>!n._hidden),s=e._getHelpCommand();return s&&!s._hidden&&r.push(s),this.sortSubcommands&&r.sort((n,i)=>n.name().localeCompare(i.name())),r}compareOptions(e,r){let s=n=>n.short?n.short.replace(/^-/,""):n.long.replace(/^--/,"");return s(e).localeCompare(s(r))}visibleOptions(e){let r=e.options.filter(n=>!n.hidden),s=e._getHelpOption();if(s&&!s.hidden){let n=s.short&&e._findOption(s.short),i=s.long&&e._findOption(s.long);!n&&!i?r.push(s):s.long&&!i?r.push(e.createOption(s.long,s.description)):s.short&&!n&&r.push(e.createOption(s.short,s.description))}return this.sortOptions&&r.sort(this.compareOptions),r}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let r=[];for(let s=e.parent;s;s=s.parent){let n=s.options.filter(i=>!i.hidden);r.push(...n)}return this.sortOptions&&r.sort(this.compareOptions),r}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(r=>{r.description=r.description||e._argsDescription[r.name()]||""}),e.registeredArguments.find(r=>r.description)?e.registeredArguments:[]}subcommandTerm(e){let r=e.registeredArguments.map(s=>Mi(s)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(r?" "+r:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,r){return r.visibleCommands(e).reduce((s,n)=>Math.max(s,this.displayWidth(r.styleSubcommandTerm(r.subcommandTerm(n)))),0)}longestOptionTermLength(e,r){return r.visibleOptions(e).reduce((s,n)=>Math.max(s,this.displayWidth(r.styleOptionTerm(r.optionTerm(n)))),0)}longestGlobalOptionTermLength(e,r){return r.visibleGlobalOptions(e).reduce((s,n)=>Math.max(s,this.displayWidth(r.styleOptionTerm(r.optionTerm(n)))),0)}longestArgumentTermLength(e,r){return r.visibleArguments(e).reduce((s,n)=>Math.max(s,this.displayWidth(r.styleArgumentTerm(r.argumentTerm(n)))),0)}commandUsage(e){let r=e._name;e._aliases[0]&&(r=r+"|"+e._aliases[0]);let s="";for(let n=e.parent;n;n=n.parent)s=n.name()+" "+s;return s+r+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let r=[];if(e.argChoices&&r.push(`choices: ${e.argChoices.map(s=>JSON.stringify(s)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&r.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&r.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&r.push(`env: ${e.envVar}`),r.length>0){let s=`(${r.join(", ")})`;return e.description?`${e.description} ${s}`:s}return e.description}argumentDescription(e){let r=[];if(e.argChoices&&r.push(`choices: ${e.argChoices.map(s=>JSON.stringify(s)).join(", ")}`),e.defaultValue!==void 0&&r.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),r.length>0){let s=`(${r.join(", ")})`;return e.description?`${e.description} ${s}`:s}return e.description}formatItemList(e,r,s){return r.length===0?[]:[s.styleTitle(e),...r,""]}groupItems(e,r,s){let n=new Map;return e.forEach(i=>{let o=s(i);n.has(o)||n.set(o,[])}),r.forEach(i=>{let o=s(i);n.has(o)||n.set(o,[]),n.get(o).push(i)}),n}formatHelp(e,r){let s=r.padWidth(e,r),n=r.helpWidth??80;function i(d,m){return r.formatItem(d,s,m,r)}let o=[`${r.styleTitle("Usage:")} ${r.styleUsage(r.commandUsage(e))}`,""],a=r.commandDescription(e);a.length>0&&(o=o.concat([r.boxWrap(r.styleCommandDescription(a),n),""]));let c=r.visibleArguments(e).map(d=>i(r.styleArgumentTerm(r.argumentTerm(d)),r.styleArgumentDescription(r.argumentDescription(d))));if(o=o.concat(this.formatItemList("Arguments:",c,r)),this.groupItems(e.options,r.visibleOptions(e),d=>d.helpGroupHeading??"Options:").forEach((d,m)=>{let w=d.map(I=>i(r.styleOptionTerm(r.optionTerm(I)),r.styleOptionDescription(r.optionDescription(I))));o=o.concat(this.formatItemList(m,w,r))}),r.showGlobalOptions){let d=r.visibleGlobalOptions(e).map(m=>i(r.styleOptionTerm(r.optionTerm(m)),r.styleOptionDescription(r.optionDescription(m))));o=o.concat(this.formatItemList("Global Options:",d,r))}return this.groupItems(e.commands,r.visibleCommands(e),d=>d.helpGroup()||"Commands:").forEach((d,m)=>{let w=d.map(I=>i(r.styleSubcommandTerm(r.subcommandTerm(I)),r.styleSubcommandDescription(r.subcommandDescription(I))));o=o.concat(this.formatItemList(m,w,r))}),o.join(`
5
5
  `)}displayWidth(e){return _s(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map(r=>r==="[options]"?this.styleOptionText(r):r==="[command]"?this.styleSubcommandText(r):r[0]==="["||r[0]==="<"?this.styleArgumentText(r):this.styleCommandText(r)).join(" ")}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(" ").map(r=>r==="[options]"?this.styleOptionText(r):r[0]==="["||r[0]==="<"?this.styleArgumentText(r):this.styleSubcommandText(r)).join(" ")}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,r){return Math.max(r.longestOptionTermLength(e,r),r.longestGlobalOptionTermLength(e,r),r.longestSubcommandTermLength(e,r),r.longestArgumentTermLength(e,r))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,r,s,n){let o=" ".repeat(2);if(!s)return o+e;let a=e.padEnd(r+e.length-n.displayWidth(e)),c=2,u=(this.helpWidth??80)-r-c-2,d;return u<this.minWidthToWrap||n.preformatted(s)?d=s:d=n.boxWrap(s,u).replace(/\n/g,`
6
6
  `+" ".repeat(r+c)),o+a+" ".repeat(c)+d.replace(/\n/g,`
7
7
  ${o}`)}boxWrap(e,r){if(r<this.minWidthToWrap)return e;let s=e.split(/\r\n|\n/),n=/[\s]*[^\s]+/g,i=[];return s.forEach(o=>{let a=o.match(n);if(a===null){i.push("");return}let c=[a.shift()],l=this.displayWidth(c[0]);a.forEach(u=>{let d=this.displayWidth(u);if(l+d<=r){c.push(u),l+=d;return}i.push(c.join(""));let m=u.trimStart();c=[m],l=this.displayWidth(m)}),i.push(c.join(""))}),i.join(`
@@ -13,36 +13,36 @@ ${o}`)}boxWrap(e,r){if(r<this.minWidthToWrap)return e;let s=e.split(/\r\n|\n/),n
13
13
  - too many long flags`):new Error(`${a}
14
14
  - unrecognised flag format`)}if(e===void 0&&r===void 0)throw new Error(`option creation failed due to no flags found in '${t}'.`);return{shortFlag:e,longFlag:r}}yr.Option=mr;yr.DualOptions=gr});var xs=Ce(ws=>{function Fi(t,e){if(Math.abs(t.length-e.length)>3)return Math.max(t.length,e.length);let r=[];for(let s=0;s<=t.length;s++)r[s]=[s];for(let s=0;s<=e.length;s++)r[0][s]=s;for(let s=1;s<=e.length;s++)for(let n=1;n<=t.length;n++){let i=1;t[n-1]===e[s-1]?i=0:i=1,r[n][s]=Math.min(r[n-1][s]+1,r[n][s-1]+1,r[n-1][s-1]+i),n>1&&s>1&&t[n-1]===e[s-2]&&t[n-2]===e[s-1]&&(r[n][s]=Math.min(r[n][s],r[n-2][s-2]+1))}return r[t.length][e.length]}function Ki(t,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let r=t.startsWith("--");r&&(t=t.slice(2),e=e.map(o=>o.slice(2)));let s=[],n=3,i=.4;return e.forEach(o=>{if(o.length<=1)return;let a=Fi(t,o),c=Math.max(t.length,o.length);(c-a)/c>i&&(a<n?(n=a,s=[o]):a===n&&s.push(o))}),s.sort((o,a)=>o.localeCompare(a)),r&&(s=s.map(o=>`--${o}`)),s.length>1?`
15
15
  (Did you mean one of ${s.join(", ")}?)`:s.length===1?`
16
- (Did you mean ${s[0]}?)`:""}ws.suggestSimilar=Ki});var Es=Ce(kr=>{var qi=ut("node:events").EventEmitter,_r=ut("node:child_process"),he=ut("node:path"),Rt=ut("node:fs"),$=ut("node:process"),{Argument:Bi,humanReadableArgName:Gi}=Ot(),{CommanderError:br}=yt(),{Help:zi,stripColor:Zi}=fr(),{Option:ks,DualOptions:Ji}=vr(),{suggestSimilar:Ss}=xs(),wr=class t extends qi{constructor(e){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=e||"",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:r=>$.stdout.write(r),writeErr:r=>$.stderr.write(r),outputError:(r,s)=>s(r),getOutHelpWidth:()=>$.stdout.isTTY?$.stdout.columns:void 0,getErrHelpWidth:()=>$.stderr.isTTY?$.stderr.columns:void 0,getOutHasColors:()=>xr()??($.stdout.isTTY&&$.stdout.hasColors?.()),getErrHasColors:()=>xr()??($.stderr.isTTY&&$.stderr.hasColors?.()),stripColor:r=>Zi(r)},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(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let r=this;r;r=r.parent)e.push(r);return e}command(e,r,s){let n=r,i=s;typeof n=="object"&&n!==null&&(i=n,n=null),i=i||{};let[,o,a]=e.match(/([^ ]+) *(.*)/),c=this.createCommand(o);return n&&(c.description(n),c._executableHandler=!0),i.isDefault&&(this._defaultCommandName=c._name),c._hidden=!!(i.noHelp||i.hidden),c._executableFile=i.executableFile||null,a&&c.arguments(a),this._registerCommand(c),c.parent=this,c.copyInheritedSettings(this),n?this:c}createCommand(e){return new t(e)}createHelp(){return Object.assign(new zi,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...e},this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,r){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
16
+ (Did you mean ${s[0]}?)`:""}ws.suggestSimilar=Ki});var Es=Ce(kr=>{var qi=ut("node:events").EventEmitter,_r=ut("node:child_process"),he=ut("node:path"),Rt=ut("node:fs"),$=ut("node:process"),{Argument:Bi,humanReadableArgName:Gi}=Ot(),{CommanderError:br}=yt(),{Help:zi,stripColor:Zi}=fr(),{Option:ks,DualOptions:Ji}=vr(),{suggestSimilar:As}=xs(),wr=class t extends qi{constructor(e){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=e||"",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:r=>$.stdout.write(r),writeErr:r=>$.stderr.write(r),outputError:(r,s)=>s(r),getOutHelpWidth:()=>$.stdout.isTTY?$.stdout.columns:void 0,getErrHelpWidth:()=>$.stderr.isTTY?$.stderr.columns:void 0,getOutHasColors:()=>xr()??($.stdout.isTTY&&$.stdout.hasColors?.()),getErrHasColors:()=>xr()??($.stderr.isTTY&&$.stderr.hasColors?.()),stripColor:r=>Zi(r)},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(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let r=this;r;r=r.parent)e.push(r);return e}command(e,r,s){let n=r,i=s;typeof n=="object"&&n!==null&&(i=n,n=null),i=i||{};let[,o,a]=e.match(/([^ ]+) *(.*)/),c=this.createCommand(o);return n&&(c.description(n),c._executableHandler=!0),i.isDefault&&(this._defaultCommandName=c._name),c._hidden=!!(i.noHelp||i.hidden),c._executableFile=i.executableFile||null,a&&c.arguments(a),this._registerCommand(c),c.parent=this,c.copyInheritedSettings(this),n?this:c}createCommand(e){return new t(e)}createHelp(){return Object.assign(new zi,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...e},this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,r){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
17
17
  - specify the name in Command constructor or using .name()`);return r=r||{},r.isDefault&&(this._defaultCommandName=e._name),(r.noHelp||r.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,r){return new Bi(e,r)}argument(e,r,s,n){let i=this.createArgument(e,r);return typeof s=="function"?i.default(n).argParser(s):i.default(s),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(r=>{this.argument(r)}),this}addArgument(e){let r=this.registeredArguments.slice(-1)[0];if(r?.variadic)throw new Error(`only the last argument can be variadic '${r.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,r){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,e&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;let s=e??"help [command]",[,n,i]=s.match(/([^ ]+) *(.*)/),o=r??"display help for command",a=this.createCommand(n);return a.helpOption(!1),i&&a.arguments(i),o&&a.description(o),this._addImplicitHelpCommand=!0,this._helpCommand=a,(e||r)&&this._initCommandGroup(a),this}addHelpCommand(e,r){return typeof e!="object"?(this.helpCommand(e,r),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this._initCommandGroup(e),this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,r){let s=["preSubcommand","preAction","postAction"];if(!s.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
18
18
  Expecting one of '${s.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(r):this._lifeCycleHooks[e]=[r],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=r=>{if(r.code!=="commander.executeSubCommandAsync")throw r},this}_exit(e,r,s){this._exitCallback&&this._exitCallback(new br(e,r,s)),$.exit(e)}action(e){let r=s=>{let n=this.registeredArguments.length,i=s.slice(0,n);return this._storeOptionsAsProperties?i[n]=this:i[n]=this.opts(),i.push(this),e.apply(this,i)};return this._actionHandler=r,this}createOption(e,r){return new ks(e,r)}_callParseArg(e,r,s,n){try{return e.parseArg(r,s)}catch(i){if(i.code==="commander.invalidArgument"){let o=`${n} ${i.message}`;this.error(o,{exitCode:i.exitCode,code:i.code})}throw i}}_registerOption(e){let r=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(r){let s=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${s}'
19
19
  - already used by option '${r.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let r=n=>[n.name()].concat(n.aliases()),s=r(e).find(n=>this._findCommand(n));if(s){let n=r(this._findCommand(s)).join("|"),i=r(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${n}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let r=e.name(),s=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(s,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(s,e.defaultValue,"default");let n=(i,o,a)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let c=this.getOptionValue(s);i!==null&&e.parseArg?i=this._callParseArg(e,i,c,o):i!==null&&e.variadic&&(i=e._collectValue(i,c)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(s,i,a)};return this.on("option:"+r,i=>{let o=`error: option '${e.flags}' argument '${i}' is invalid.`;n(i,o,"cli")}),e.envVar&&this.on("optionEnv:"+r,i=>{let o=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;n(i,o,"env")}),this}_optionEx(e,r,s,n,i){if(typeof r=="object"&&r instanceof ks)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(r,s);if(o.makeOptionMandatory(!!e.mandatory),typeof n=="function")o.default(i).argParser(n);else if(n instanceof RegExp){let a=n;n=(c,l)=>{let u=a.exec(c);return u?u[0]:l},o.default(i).argParser(n)}else o.default(n);return this.addOption(o)}option(e,r,s,n){return this._optionEx({},e,r,s,n)}requiredOption(e,r,s,n){return this._optionEx({mandatory:!0},e,r,s,n)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,r){return this.setOptionValueWithSource(e,r,void 0)}setOptionValueWithSource(e,r,s){return this._storeOptionsAsProperties?this[e]=r:this._optionValues[e]=r,this._optionValueSources[e]=s,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let r;return this._getCommandAndAncestors().forEach(s=>{s.getOptionValueSource(e)!==void 0&&(r=s.getOptionValueSource(e))}),r}_prepareUserArgs(e,r){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(r=r||{},e===void 0&&r.from===void 0){$.versions?.electron&&(r.from="electron");let n=$.execArgv??[];(n.includes("-e")||n.includes("--eval")||n.includes("-p")||n.includes("--print"))&&(r.from="eval")}e===void 0&&(e=$.argv),this.rawArgs=e.slice();let s;switch(r.from){case void 0:case"node":this._scriptPath=e[1],s=e.slice(2);break;case"electron":$.defaultApp?(this._scriptPath=e[1],s=e.slice(2)):s=e.slice(1);break;case"user":s=e.slice(0);break;case"eval":s=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${r.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",s}parse(e,r){this._prepareForParse();let s=this._prepareUserArgs(e,r);return this._parseCommand([],s),this}async parseAsync(e,r){this._prepareForParse();let s=this._prepareUserArgs(e,r);return await this._parseCommand([],s),this}_prepareForParse(){this._savedState===null?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
20
20
  - 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(e,r,s){if(Rt.existsSync(e))return;let n=r?`searched for local subcommand relative to directory '${r}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",i=`'${e}' does not exist
21
21
  - if '${s}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
22
22
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
23
- - ${n}`;throw new Error(i)}_executeSubCommand(e,r){r=r.slice();let s=!1,n=[".js",".ts",".tsx",".mjs",".cjs"];function i(u,d){let m=he.resolve(u,d);if(Rt.existsSync(m))return m;if(n.includes(he.extname(d)))return;let x=n.find(R=>Rt.existsSync(`${m}${R}`));if(x)return`${m}${x}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let u;try{u=Rt.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=he.resolve(he.dirname(u),a)}if(a){let u=i(a,o);if(!u&&!e._executableFile&&this._scriptPath){let d=he.basename(this._scriptPath,he.extname(this._scriptPath));d!==this._name&&(u=i(a,`${d}-${e._name}`))}o=u||o}s=n.includes(he.extname(o));let c;$.platform!=="win32"?s?(r.unshift(o),r=As($.execArgv).concat(r),c=_r.spawn($.argv[0],r,{stdio:"inherit"})):c=_r.spawn(o,r,{stdio:"inherit"}):(this._checkForMissingExecutable(o,a,e._name),r.unshift(o),r=As($.execArgv).concat(r),c=_r.spawn($.execPath,r,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(d=>{$.on(d,()=>{c.killed===!1&&c.exitCode===null&&c.kill(d)})});let l=this._exitCallback;c.on("close",u=>{u=u??1,l?l(new br(u,"commander.executeSubCommandAsync","(close)")):$.exit(u)}),c.on("error",u=>{if(u.code==="ENOENT")this._checkForMissingExecutable(o,a,e._name);else if(u.code==="EACCES")throw new Error(`'${o}' not executable`);if(!l)$.exit(1);else{let d=new br(1,"commander.executeSubCommandAsync","(error)");d.nestedError=u,l(d)}}),this.runningCommand=c}_dispatchSubcommand(e,r,s){let n=this._findCommand(e);n||this.help({error:!0}),n._prepareForParse();let i;return i=this._chainOrCallSubCommandHook(i,n,"preSubcommand"),i=this._chainOrCall(i,()=>{if(n._executableHandler)this._executeSubCommand(n,r.concat(s));else return n._parseCommand(r,s)}),i}_dispatchHelpCommand(e){e||this.help();let r=this._findCommand(e);return r&&!r._executableHandler&&r.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,r)=>{e.required&&this.args[r]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(s,n,i)=>{let o=n;if(n!==null&&s.parseArg){let a=`error: command-argument value '${n}' is invalid for argument '${s.name()}'.`;o=this._callParseArg(s,n,i,a)}return o};this._checkNumberOfArguments();let r=[];this.registeredArguments.forEach((s,n)=>{let i=s.defaultValue;s.variadic?n<this.args.length?(i=this.args.slice(n),s.parseArg&&(i=i.reduce((o,a)=>e(s,a,o),s.defaultValue))):i===void 0&&(i=[]):n<this.args.length&&(i=this.args[n],s.parseArg&&(i=e(s,i,s.defaultValue))),r[n]=i}),this.processedArgs=r}_chainOrCall(e,r){return e?.then&&typeof e.then=="function"?e.then(()=>r()):r()}_chainOrCallHooks(e,r){let s=e,n=[];return this._getCommandAndAncestors().reverse().filter(i=>i._lifeCycleHooks[r]!==void 0).forEach(i=>{i._lifeCycleHooks[r].forEach(o=>{n.push({hookedCommand:i,callback:o})})}),r==="postAction"&&n.reverse(),n.forEach(i=>{s=this._chainOrCall(s,()=>i.callback(i.hookedCommand,this))}),s}_chainOrCallSubCommandHook(e,r,s){let n=e;return this._lifeCycleHooks[s]!==void 0&&this._lifeCycleHooks[s].forEach(i=>{n=this._chainOrCall(n,()=>i(this,r))}),n}_parseCommand(e,r){let s=this.parseOptions(r);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(s.operands),r=s.unknown,this.args=e.concat(r),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),r);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(r),this._dispatchSubcommand(this._defaultCommandName,e,r);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(s.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let n=()=>{s.unknown.length>0&&this.unknownOption(s.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){n(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(i,e,r)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent?.listenerCount(i))n(),this._processArguments(),this.parent.emit(i,e,r);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,r);this.listenerCount("command:*")?this.emit("command:*",e,r):this.commands.length?this.unknownCommand():(n(),this._processArguments())}else this.commands.length?(n(),this.help({error:!0})):(n(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(r=>r._name===e||r._aliases.includes(e))}_findOption(e){return this.options.find(r=>r.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(r=>{r.mandatory&&e.getOptionValue(r.attributeName())===void 0&&e.missingMandatoryOptionValue(r)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(s=>{let n=s.attributeName();return this.getOptionValue(n)===void 0?!1:this.getOptionValueSource(n)!=="default"});e.filter(s=>s.conflictsWith.length>0).forEach(s=>{let n=e.find(i=>s.conflictsWith.includes(i.attributeName()));n&&this._conflictingOption(s,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let r=[],s=[],n=r;function i(u){return u.length>1&&u[0]==="-"}let o=u=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(u)?!this._getCommandAndAncestors().some(d=>d.options.map(m=>m.short).some(m=>/^-\d$/.test(m))):!1,a=null,c=null,l=0;for(;l<e.length||c;){let u=c??e[l++];if(c=null,u==="--"){n===s&&n.push(u),n.push(...e.slice(l));break}if(a&&(!i(u)||o(u))){this.emit(`option:${a.name()}`,u);continue}if(a=null,i(u)){let d=this._findOption(u);if(d){if(d.required){let m=e[l++];m===void 0&&this.optionMissingArgument(d),this.emit(`option:${d.name()}`,m)}else if(d.optional){let m=null;l<e.length&&(!i(e[l])||o(e[l]))&&(m=e[l++]),this.emit(`option:${d.name()}`,m)}else this.emit(`option:${d.name()}`);a=d.variadic?d:null;continue}}if(u.length>2&&u[0]==="-"&&u[1]!=="-"){let d=this._findOption(`-${u[1]}`);if(d){d.required||d.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${d.name()}`,u.slice(2)):(this.emit(`option:${d.name()}`),c=`-${u.slice(2)}`);continue}}if(/^--[^=]+=/.test(u)){let d=u.indexOf("="),m=this._findOption(u.slice(0,d));if(m&&(m.required||m.optional)){this.emit(`option:${m.name()}`,u.slice(d+1));continue}}if(n===r&&i(u)&&!(this.commands.length===0&&o(u))&&(n=s),(this._enablePositionalOptions||this._passThroughOptions)&&r.length===0&&s.length===0){if(this._findCommand(u)){r.push(u),s.push(...e.slice(l));break}else if(this._getHelpCommand()&&u===this._getHelpCommand().name()){r.push(u,...e.slice(l));break}else if(this._defaultCommandName){s.push(u,...e.slice(l));break}}if(this._passThroughOptions){n.push(u,...e.slice(l));break}n.push(u)}return{operands:r,unknown:s}}opts(){if(this._storeOptionsAsProperties){let e={},r=this.options.length;for(let s=0;s<r;s++){let n=this.options[s].attributeName();e[n]=n===this._versionOptionName?this._version:this[n]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,r)=>Object.assign(e,r.opts()),{})}error(e,r){this._outputConfiguration.outputError(`${e}
23
+ - ${n}`;throw new Error(i)}_executeSubCommand(e,r){r=r.slice();let s=!1,n=[".js",".ts",".tsx",".mjs",".cjs"];function i(u,d){let m=he.resolve(u,d);if(Rt.existsSync(m))return m;if(n.includes(he.extname(d)))return;let w=n.find(I=>Rt.existsSync(`${m}${I}`));if(w)return`${m}${w}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let u;try{u=Rt.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=he.resolve(he.dirname(u),a)}if(a){let u=i(a,o);if(!u&&!e._executableFile&&this._scriptPath){let d=he.basename(this._scriptPath,he.extname(this._scriptPath));d!==this._name&&(u=i(a,`${d}-${e._name}`))}o=u||o}s=n.includes(he.extname(o));let c;$.platform!=="win32"?s?(r.unshift(o),r=Ss($.execArgv).concat(r),c=_r.spawn($.argv[0],r,{stdio:"inherit"})):c=_r.spawn(o,r,{stdio:"inherit"}):(this._checkForMissingExecutable(o,a,e._name),r.unshift(o),r=Ss($.execArgv).concat(r),c=_r.spawn($.execPath,r,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(d=>{$.on(d,()=>{c.killed===!1&&c.exitCode===null&&c.kill(d)})});let l=this._exitCallback;c.on("close",u=>{u=u??1,l?l(new br(u,"commander.executeSubCommandAsync","(close)")):$.exit(u)}),c.on("error",u=>{if(u.code==="ENOENT")this._checkForMissingExecutable(o,a,e._name);else if(u.code==="EACCES")throw new Error(`'${o}' not executable`);if(!l)$.exit(1);else{let d=new br(1,"commander.executeSubCommandAsync","(error)");d.nestedError=u,l(d)}}),this.runningCommand=c}_dispatchSubcommand(e,r,s){let n=this._findCommand(e);n||this.help({error:!0}),n._prepareForParse();let i;return i=this._chainOrCallSubCommandHook(i,n,"preSubcommand"),i=this._chainOrCall(i,()=>{if(n._executableHandler)this._executeSubCommand(n,r.concat(s));else return n._parseCommand(r,s)}),i}_dispatchHelpCommand(e){e||this.help();let r=this._findCommand(e);return r&&!r._executableHandler&&r.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,r)=>{e.required&&this.args[r]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(s,n,i)=>{let o=n;if(n!==null&&s.parseArg){let a=`error: command-argument value '${n}' is invalid for argument '${s.name()}'.`;o=this._callParseArg(s,n,i,a)}return o};this._checkNumberOfArguments();let r=[];this.registeredArguments.forEach((s,n)=>{let i=s.defaultValue;s.variadic?n<this.args.length?(i=this.args.slice(n),s.parseArg&&(i=i.reduce((o,a)=>e(s,a,o),s.defaultValue))):i===void 0&&(i=[]):n<this.args.length&&(i=this.args[n],s.parseArg&&(i=e(s,i,s.defaultValue))),r[n]=i}),this.processedArgs=r}_chainOrCall(e,r){return e?.then&&typeof e.then=="function"?e.then(()=>r()):r()}_chainOrCallHooks(e,r){let s=e,n=[];return this._getCommandAndAncestors().reverse().filter(i=>i._lifeCycleHooks[r]!==void 0).forEach(i=>{i._lifeCycleHooks[r].forEach(o=>{n.push({hookedCommand:i,callback:o})})}),r==="postAction"&&n.reverse(),n.forEach(i=>{s=this._chainOrCall(s,()=>i.callback(i.hookedCommand,this))}),s}_chainOrCallSubCommandHook(e,r,s){let n=e;return this._lifeCycleHooks[s]!==void 0&&this._lifeCycleHooks[s].forEach(i=>{n=this._chainOrCall(n,()=>i(this,r))}),n}_parseCommand(e,r){let s=this.parseOptions(r);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(s.operands),r=s.unknown,this.args=e.concat(r),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),r);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(r),this._dispatchSubcommand(this._defaultCommandName,e,r);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(s.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let n=()=>{s.unknown.length>0&&this.unknownOption(s.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){n(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(i,e,r)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent?.listenerCount(i))n(),this._processArguments(),this.parent.emit(i,e,r);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,r);this.listenerCount("command:*")?this.emit("command:*",e,r):this.commands.length?this.unknownCommand():(n(),this._processArguments())}else this.commands.length?(n(),this.help({error:!0})):(n(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(r=>r._name===e||r._aliases.includes(e))}_findOption(e){return this.options.find(r=>r.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(r=>{r.mandatory&&e.getOptionValue(r.attributeName())===void 0&&e.missingMandatoryOptionValue(r)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(s=>{let n=s.attributeName();return this.getOptionValue(n)===void 0?!1:this.getOptionValueSource(n)!=="default"});e.filter(s=>s.conflictsWith.length>0).forEach(s=>{let n=e.find(i=>s.conflictsWith.includes(i.attributeName()));n&&this._conflictingOption(s,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let r=[],s=[],n=r;function i(u){return u.length>1&&u[0]==="-"}let o=u=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(u)?!this._getCommandAndAncestors().some(d=>d.options.map(m=>m.short).some(m=>/^-\d$/.test(m))):!1,a=null,c=null,l=0;for(;l<e.length||c;){let u=c??e[l++];if(c=null,u==="--"){n===s&&n.push(u),n.push(...e.slice(l));break}if(a&&(!i(u)||o(u))){this.emit(`option:${a.name()}`,u);continue}if(a=null,i(u)){let d=this._findOption(u);if(d){if(d.required){let m=e[l++];m===void 0&&this.optionMissingArgument(d),this.emit(`option:${d.name()}`,m)}else if(d.optional){let m=null;l<e.length&&(!i(e[l])||o(e[l]))&&(m=e[l++]),this.emit(`option:${d.name()}`,m)}else this.emit(`option:${d.name()}`);a=d.variadic?d:null;continue}}if(u.length>2&&u[0]==="-"&&u[1]!=="-"){let d=this._findOption(`-${u[1]}`);if(d){d.required||d.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${d.name()}`,u.slice(2)):(this.emit(`option:${d.name()}`),c=`-${u.slice(2)}`);continue}}if(/^--[^=]+=/.test(u)){let d=u.indexOf("="),m=this._findOption(u.slice(0,d));if(m&&(m.required||m.optional)){this.emit(`option:${m.name()}`,u.slice(d+1));continue}}if(n===r&&i(u)&&!(this.commands.length===0&&o(u))&&(n=s),(this._enablePositionalOptions||this._passThroughOptions)&&r.length===0&&s.length===0){if(this._findCommand(u)){r.push(u),s.push(...e.slice(l));break}else if(this._getHelpCommand()&&u===this._getHelpCommand().name()){r.push(u,...e.slice(l));break}else if(this._defaultCommandName){s.push(u,...e.slice(l));break}}if(this._passThroughOptions){n.push(u,...e.slice(l));break}n.push(u)}return{operands:r,unknown:s}}opts(){if(this._storeOptionsAsProperties){let e={},r=this.options.length;for(let s=0;s<r;s++){let n=this.options[s].attributeName();e[n]=n===this._versionOptionName?this._version:this[n]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,r)=>Object.assign(e,r.opts()),{})}error(e,r){this._outputConfiguration.outputError(`${e}
24
24
  `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
25
25
  `):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
26
- `),this.outputHelp({error:!0}));let s=r||{},n=s.exitCode||1,i=s.code||"commander.error";this._exit(n,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in $.env){let r=e.attributeName();(this.getOptionValue(r)===void 0||["default","config","env"].includes(this.getOptionValueSource(r)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,$.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Ji(this.options),r=s=>this.getOptionValue(s)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(s));this.options.filter(s=>s.implied!==void 0&&r(s.attributeName())&&e.valueFromOption(this.getOptionValue(s.attributeName()),s)).forEach(s=>{Object.keys(s.implied).filter(n=>!r(n)).forEach(n=>{this.setOptionValueWithSource(n,s.implied[n],"implied")})})}missingArgument(e){let r=`error: missing required argument '${e}'`;this.error(r,{code:"commander.missingArgument"})}optionMissingArgument(e){let r=`error: option '${e.flags}' argument missing`;this.error(r,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let r=`error: required option '${e.flags}' not specified`;this.error(r,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,r){let s=o=>{let a=o.attributeName(),c=this.getOptionValue(a),l=this.options.find(d=>d.negate&&a===d.attributeName()),u=this.options.find(d=>!d.negate&&a===d.attributeName());return l&&(l.presetArg===void 0&&c===!1||l.presetArg!==void 0&&c===l.presetArg)?l:u||o},n=o=>{let a=s(o),c=a.attributeName();return this.getOptionValueSource(c)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},i=`error: ${n(e)} cannot be used with ${n(r)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let r="";if(e.startsWith("--")&&this._showSuggestionAfterError){let n=[],i=this;do{let o=i.createHelp().visibleOptions(i).filter(a=>a.long).map(a=>a.long);n=n.concat(o),i=i.parent}while(i&&!i._enablePositionalOptions);r=Ss(e,n)}let s=`error: unknown option '${e}'${r}`;this.error(s,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let r=this.registeredArguments.length,s=r===1?"":"s",i=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${r} argument${s} but got ${e.length}.`;this.error(i,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],r="";if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(i=>{n.push(i.name()),i.alias()&&n.push(i.alias())}),r=Ss(e,n)}let s=`error: unknown command '${e}'${r}`;this.error(s,{code:"commander.unknownCommand"})}version(e,r,s){if(e===void 0)return this._version;this._version=e,r=r||"-V, --version",s=s||"output the version number";let n=this.createOption(r,s);return this._versionOptionName=n.attributeName(),this._registerOption(n),this.on("option:"+n.name(),()=>{this._outputConfiguration.writeOut(`${e}
26
+ `),this.outputHelp({error:!0}));let s=r||{},n=s.exitCode||1,i=s.code||"commander.error";this._exit(n,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in $.env){let r=e.attributeName();(this.getOptionValue(r)===void 0||["default","config","env"].includes(this.getOptionValueSource(r)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,$.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Ji(this.options),r=s=>this.getOptionValue(s)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(s));this.options.filter(s=>s.implied!==void 0&&r(s.attributeName())&&e.valueFromOption(this.getOptionValue(s.attributeName()),s)).forEach(s=>{Object.keys(s.implied).filter(n=>!r(n)).forEach(n=>{this.setOptionValueWithSource(n,s.implied[n],"implied")})})}missingArgument(e){let r=`error: missing required argument '${e}'`;this.error(r,{code:"commander.missingArgument"})}optionMissingArgument(e){let r=`error: option '${e.flags}' argument missing`;this.error(r,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let r=`error: required option '${e.flags}' not specified`;this.error(r,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,r){let s=o=>{let a=o.attributeName(),c=this.getOptionValue(a),l=this.options.find(d=>d.negate&&a===d.attributeName()),u=this.options.find(d=>!d.negate&&a===d.attributeName());return l&&(l.presetArg===void 0&&c===!1||l.presetArg!==void 0&&c===l.presetArg)?l:u||o},n=o=>{let a=s(o),c=a.attributeName();return this.getOptionValueSource(c)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},i=`error: ${n(e)} cannot be used with ${n(r)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let r="";if(e.startsWith("--")&&this._showSuggestionAfterError){let n=[],i=this;do{let o=i.createHelp().visibleOptions(i).filter(a=>a.long).map(a=>a.long);n=n.concat(o),i=i.parent}while(i&&!i._enablePositionalOptions);r=As(e,n)}let s=`error: unknown option '${e}'${r}`;this.error(s,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let r=this.registeredArguments.length,s=r===1?"":"s",i=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${r} argument${s} but got ${e.length}.`;this.error(i,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],r="";if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(i=>{n.push(i.name()),i.alias()&&n.push(i.alias())}),r=As(e,n)}let s=`error: unknown command '${e}'${r}`;this.error(s,{code:"commander.unknownCommand"})}version(e,r,s){if(e===void 0)return this._version;this._version=e,r=r||"-V, --version",s=s||"output the version number";let n=this.createOption(r,s);return this._versionOptionName=n.attributeName(),this._registerOption(n),this.on("option:"+n.name(),()=>{this._outputConfiguration.writeOut(`${e}
27
27
  `),this._exit(0,"commander.version",e)}),this}description(e,r){return e===void 0&&r===void 0?this._description:(this._description=e,r&&(this._argsDescription=r),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let r=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(r=this.commands[this.commands.length-1]),e===r._name)throw new Error("Command alias can't be the same as its name");let s=this.parent?._findCommand(e);if(s){let n=[s.name()].concat(s.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${n}'`)}return r._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(r=>this.alias(r)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let r=this.registeredArguments.map(s=>Gi(s));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?r:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}helpGroup(e){return e===void 0?this._helpGroupHeading??"":(this._helpGroupHeading=e,this)}commandsGroup(e){return e===void 0?this._defaultCommandGroup??"":(this._defaultCommandGroup=e,this)}optionsGroup(e){return e===void 0?this._defaultOptionGroup??"":(this._defaultOptionGroup=e,this)}_initOptionGroup(e){this._defaultOptionGroup&&!e.helpGroupHeading&&e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){this._defaultCommandGroup&&!e.helpGroup()&&e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=he.basename(e,he.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let r=this.createHelp(),s=this._getOutputContext(e);r.prepareContext({error:s.error,helpWidth:s.helpWidth,outputHasColors:s.hasColors});let n=r.formatHelp(this,r);return s.hasColors?n:this._outputConfiguration.stripColor(n)}_getOutputContext(e){e=e||{};let r=!!e.error,s,n,i;return r?(s=a=>this._outputConfiguration.writeErr(a),n=this._outputConfiguration.getErrHasColors(),i=this._outputConfiguration.getErrHelpWidth()):(s=a=>this._outputConfiguration.writeOut(a),n=this._outputConfiguration.getOutHasColors(),i=this._outputConfiguration.getOutHelpWidth()),{error:r,write:a=>(n||(a=this._outputConfiguration.stripColor(a)),s(a)),hasColors:n,helpWidth:i}}outputHelp(e){let r;typeof e=="function"&&(r=e,e=void 0);let s=this._getOutputContext(e),n={error:s.error,write:s.write,command:this};this._getCommandAndAncestors().reverse().forEach(o=>o.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let i=this.helpInformation({error:s.error});if(r&&(i=r(i),typeof i!="string"&&!Buffer.isBuffer(i)))throw new Error("outputHelp callback must return a string or a Buffer");s.write(i),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(o=>o.emit("afterAllHelp",n))}helpOption(e,r){return typeof e=="boolean"?(e?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(e??"-h, --help",r??"display help for command"),(e||r)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(e){this.outputHelp(e);let r=Number($.exitCode??0);r===0&&e&&typeof e!="function"&&e.error&&(r=1),this._exit(r,"commander.help","(outputHelp)")}addHelpText(e,r){let s=["beforeAll","before","after","afterAll"];if(!s.includes(e))throw new Error(`Unexpected value for position to addHelpText.
28
28
  Expecting one of '${s.join("', '")}'`);let n=`${e}Help`;return this.on(n,i=>{let o;typeof r=="function"?o=r({error:i.error,command:i.command}):o=r,o&&i.write(`${o}
29
- `)}),this}_outputHelpIfRequested(e){let r=this._getHelpOption();r&&e.find(n=>r.is(n))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function As(t){return t.map(e=>{if(!e.startsWith("--inspect"))return e;let r,s="127.0.0.1",n="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?r=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(r=i[1],/^\d+$/.test(i[3])?n=i[3]:s=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(r=i[1],s=i[3],n=i[4]),r&&n!=="0"?`${r}=${s}:${parseInt(n)+1}`:e})}function xr(){if($.env.NO_COLOR||$.env.FORCE_COLOR==="0"||$.env.FORCE_COLOR==="false")return!1;if($.env.FORCE_COLOR||$.env.CLICOLOR_FORCE!==void 0)return!0}kr.Command=wr;kr.useColor=xr});var Os=Ce(z=>{var{Argument:Ts}=Ot(),{Command:Sr}=Es(),{CommanderError:Yi,InvalidArgumentError:$s}=yt(),{Help:Xi}=fr(),{Option:Cs}=vr();z.program=new Sr;z.createCommand=t=>new Sr(t);z.createOption=(t,e)=>new Cs(t,e);z.createArgument=(t,e)=>new Ts(t,e);z.Command=Sr;z.Option=Cs;z.Argument=Ts;z.Help=Xi;z.CommanderError=Yi;z.InvalidArgumentError=$s;z.InvalidOptionArgumentError=$s});var Rs,Lc,Hc,Mc,Vc,Wc,Fc,Kc,Pt,qc,Bc,Gc,Ar=V(()=>{Rs=En(Os(),1),{program:Lc,createCommand:Hc,createArgument:Mc,createOption:Vc,CommanderError:Wc,InvalidArgumentError:Fc,InvalidOptionArgumentError:Kc,Command:Pt,Argument:qc,Option:Bc,Help:Gc}=Rs.default});var Ws={};kt(Ws,{checkServiceExists:()=>Nt,fetchActionDetail:()=>$r,fetchServicesIndex:()=>we});function Tr(t){return(t.includes("://")?t:`https://${t}`).replace(/\/$/,"")}async function we(t){let e=`${Tr(t)}/.well-known/botparty/services.json`,r=await fetch(e);if(!r.ok)throw new Error(`Failed to fetch services index from ${e} (${r.status} ${r.statusText})`);return r.json()}async function $r(t,e){let r=`${Tr(t)}/.well-known/botparty/services/${e}.json`,s=await fetch(r);if(!s.ok)throw new Error(`Failed to fetch action "${e}" from ${r} (${s.status} ${s.statusText})`);return s.json()}async function Nt(t){try{let e=`${Tr(t)}/.well-known/botparty/services.json`,r=new AbortController,s=setTimeout(()=>r.abort(),3e3),n=await fetch(e,{method:"HEAD",signal:r.signal});return clearTimeout(s),n.ok}catch{return!1}}var Qe=V(()=>{"use strict"});var Ks={};kt(Ks,{discover:()=>Cr,listSubActions:()=>Or});function _o(t){let e={label:"",children:new Map};for(let r of t){let s=r.slug.split("."),n=e;for(let i=0;i<s.length;i++){let o=s[i];n.children.has(o)||n.children.set(o,{label:o,children:new Map}),n=n.children.get(o)}n.description=r.description,n.method=r.method,n.payment=r.payment}return e}function Fs(t,e="",r=!0,s=!0){if(!s){let o=`${e}${r?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 "}\x1B[36m${t.label}\x1B[0m`;if(t.method&&t.description){let a=t.payment&&t.payment!=="free"?` \x1B[33m[$${t.payment}]\x1B[0m`:"";o+=` \x1B[90m(${t.method})\x1B[0m \u2014 ${t.description}${a}`}console.log(o)}let n=[...t.children.entries()];n.forEach(([,i],o)=>{let a=o===n.length-1,c=s?"":e+(r?" ":"\u2502 ");Fs(i,c,a,!1)})}async function Cr(t){let e=await we(t);console.log(`
29
+ `)}),this}_outputHelpIfRequested(e){let r=this._getHelpOption();r&&e.find(n=>r.is(n))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Ss(t){return t.map(e=>{if(!e.startsWith("--inspect"))return e;let r,s="127.0.0.1",n="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?r=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(r=i[1],/^\d+$/.test(i[3])?n=i[3]:s=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(r=i[1],s=i[3],n=i[4]),r&&n!=="0"?`${r}=${s}:${parseInt(n)+1}`:e})}function xr(){if($.env.NO_COLOR||$.env.FORCE_COLOR==="0"||$.env.FORCE_COLOR==="false")return!1;if($.env.FORCE_COLOR||$.env.CLICOLOR_FORCE!==void 0)return!0}kr.Command=wr;kr.useColor=xr});var Os=Ce(J=>{var{Argument:Ts}=Ot(),{Command:Ar}=Es(),{CommanderError:Yi,InvalidArgumentError:$s}=yt(),{Help:Xi}=fr(),{Option:Cs}=vr();J.program=new Ar;J.createCommand=t=>new Ar(t);J.createOption=(t,e)=>new Cs(t,e);J.createArgument=(t,e)=>new Ts(t,e);J.Command=Ar;J.Option=Cs;J.Argument=Ts;J.Help=Xi;J.CommanderError=Yi;J.InvalidArgumentError=$s;J.InvalidOptionArgumentError=$s});var Rs,Lc,Hc,Mc,Vc,Wc,Fc,Kc,Pt,qc,Bc,Gc,Sr=W(()=>{Rs=En(Os(),1),{program:Lc,createCommand:Hc,createArgument:Mc,createOption:Vc,CommanderError:Wc,InvalidArgumentError:Fc,InvalidOptionArgumentError:Kc,Command:Pt,Argument:qc,Option:Bc,Help:Gc}=Rs.default});var Ws={};kt(Ws,{checkServiceExists:()=>Nt,fetchActionDetail:()=>$r,fetchServicesIndex:()=>xe});function Tr(t){return(t.includes("://")?t:`https://${t}`).replace(/\/$/,"")}async function xe(t){let e=`${Tr(t)}/.well-known/botparty/services.json`,r=await fetch(e);if(!r.ok)throw new Error(`Failed to fetch services index from ${e} (${r.status} ${r.statusText})`);return r.json()}async function $r(t,e){let r=`${Tr(t)}/.well-known/botparty/services/${e}.json`,s=await fetch(r);if(!s.ok)throw new Error(`Failed to fetch action "${e}" from ${r} (${s.status} ${s.statusText})`);return s.json()}async function Nt(t){try{let e=`${Tr(t)}/.well-known/botparty/services.json`,r=new AbortController,s=setTimeout(()=>r.abort(),3e3),n=await fetch(e,{method:"HEAD",signal:r.signal});return clearTimeout(s),n.ok}catch{return!1}}var Qe=W(()=>{"use strict"});var Ks={};kt(Ks,{discover:()=>Cr,listSubActions:()=>Or});function _o(t){let e={label:"",children:new Map};for(let r of t){let s=r.slug.split("."),n=e;for(let i=0;i<s.length;i++){let o=s[i];n.children.has(o)||n.children.set(o,{label:o,children:new Map}),n=n.children.get(o)}n.description=r.description,n.method=r.method,n.payment=r.payment}return e}function Fs(t,e="",r=!0,s=!0){if(!s){let o=`${e}${r?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 "}\x1B[36m${t.label}\x1B[0m`;if(t.method&&t.description){let a=t.payment&&t.payment!=="free"?` \x1B[33m[$${t.payment}]\x1B[0m`:"";o+=` \x1B[90m(${t.method})\x1B[0m \u2014 ${t.description}${a}`}console.log(o)}let n=[...t.children.entries()];n.forEach(([,i],o)=>{let a=o===n.length-1,c=s?"":e+(r?" ":"\u2502 ");Fs(i,c,a,!1)})}async function Cr(t){let e=await xe(t);console.log(`
30
30
  \x1B[1m${e.name}\x1B[0m`),console.log(`\x1B[90m${e.description}\x1B[0m`),console.log(`\x1B[90mAuth: ${e.auth} \xB7 Base: ${e.baseUrl}\x1B[0m`),console.log(`\x1B[90m${e.actions.length} actions\x1B[0m
31
- `);let r=_o(e.actions);Fs(r),console.log()}async function Or(t,e){let r=await we(t),s=e+".",n=r.actions.filter(i=>i.slug.startsWith(s)||i.slug===e);n.length===0&&(console.error(`\x1B[31mNo actions matching "${e}" found.\x1B[0m`),console.log(`
31
+ `);let r=_o(e.actions);Fs(r),console.log()}async function Or(t,e){let r=await xe(t),s=e+".",n=r.actions.filter(i=>i.slug.startsWith(s)||i.slug===e);n.length===0&&(console.error(`\x1B[31mNo actions matching "${e}" found.\x1B[0m`),console.log(`
32
32
  Available top-level categories:`,[...new Set(r.actions.map(i=>i.slug.split(".")[0]))].join(", ")),process.exit(1)),console.log(`
33
33
  \x1B[1mActions under "${e}" on ${r.name}:\x1B[0m
34
- `);for(let i of n){let o=i.payment!=="free"?` \x1B[33m[$${i.payment}]\x1B[0m`:"";console.log(` \x1B[36m${i.slug}\x1B[0m \x1B[90m(${i.method})\x1B[0m \u2014 ${i.description}${o}`)}console.log()}var Dt=V(()=>{"use strict";Qe()});var E,Rr,f,oe,vt=V(()=>{(function(t){t.assertEqual=n=>{};function e(n){}t.assertIs=e;function r(n){throw new Error}t.assertNever=r,t.arrayToEnum=n=>{let i={};for(let o of n)i[o]=o;return i},t.getValidEnumValues=n=>{let i=t.objectKeys(n).filter(a=>typeof n[n[a]]!="number"),o={};for(let a of i)o[a]=n[a];return t.objectValues(o)},t.objectValues=n=>t.objectKeys(n).map(function(i){return n[i]}),t.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{let i=[];for(let o in n)Object.prototype.hasOwnProperty.call(n,o)&&i.push(o);return i},t.find=(n,i)=>{for(let o of n)if(i(o))return o},t.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&Number.isFinite(n)&&Math.floor(n)===n;function s(n,i=" | "){return n.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}t.joinValues=s,t.jsonStringifyReplacer=(n,i)=>typeof i=="bigint"?i.toString():i})(E||(E={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Rr||(Rr={}));f=E.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),oe=t=>{switch(typeof t){case"undefined":return f.undefined;case"string":return f.string;case"number":return Number.isNaN(t)?f.nan:f.number;case"boolean":return f.boolean;case"function":return f.function;case"bigint":return f.bigint;case"symbol":return f.symbol;case"object":return Array.isArray(t)?f.array:t===null?f.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?f.promise:typeof Map<"u"&&t instanceof Map?f.map:typeof Set<"u"&&t instanceof Set?f.set:typeof Date<"u"&&t instanceof Date?f.date:f.object;default:return f.unknown}}});var h,bo,K,Ut=V(()=>{vt();h=E.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),bo=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),K=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(i){return i.message},s={_errors:[]},n=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(n);else if(o.code==="invalid_return_type")n(o.returnTypeError);else if(o.code==="invalid_arguments")n(o.argumentsError);else if(o.path.length===0)s._errors.push(r(o));else{let a=s,c=0;for(;c<o.path.length;){let l=o.path[c];c===o.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(r(o))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return n(this),s}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,E.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},s=[];for(let n of this.issues)if(n.path.length>0){let i=n.path[0];r[i]=r[i]||[],r[i].push(e(n))}else s.push(e(n));return{formErrors:s,fieldErrors:r}}get formErrors(){return this.flatten()}};K.create=t=>new K(t)});var wo,pe,Pr=V(()=>{Ut();vt();wo=(t,e)=>{let r;switch(t.code){case h.invalid_type:t.received===f.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case h.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,E.jsonStringifyReplacer)}`;break;case h.unrecognized_keys:r=`Unrecognized key(s) in object: ${E.joinValues(t.keys,", ")}`;break;case h.invalid_union:r="Invalid input";break;case h.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${E.joinValues(t.options)}`;break;case h.invalid_enum_value:r=`Invalid enum value. Expected ${E.joinValues(t.options)}, received '${t.received}'`;break;case h.invalid_arguments:r="Invalid function arguments";break;case h.invalid_return_type:r="Invalid function return type";break;case h.invalid_date:r="Invalid date";break;case h.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:E.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case h.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case h.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case h.custom:r="Invalid input";break;case h.invalid_intersection_types:r="Intersection results could not be merged";break;case h.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case h.not_finite:r="Number must be finite";break;default:r=e.defaultError,E.assertNever(t)}return{message:r}},pe=wo});function xo(t){qs=t}function et(){return qs}var qs,jt=V(()=>{Pr();qs=pe});function p(t,e){let r=et(),s=_t({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===pe?void 0:pe].filter(n=>!!n)});t.common.issues.push(s)}var _t,ko,M,v,Pe,W,Lt,Ht,xe,tt,Ir=V(()=>{jt();Pr();_t=t=>{let{data:e,path:r,errorMaps:s,issueData:n}=t,i=[...r,...n.path||[]],o={...n,path:i};if(n.message!==void 0)return{...n,path:i,message:n.message};let a="",c=s.filter(l=>!!l).slice().reverse();for(let l of c)a=l(o,{data:e,defaultError:a}).message;return{...n,path:i,message:a}},ko=[];M=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let s=[];for(let n of r){if(n.status==="aborted")return v;n.status==="dirty"&&e.dirty(),s.push(n.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,r){let s=[];for(let n of r){let i=await n.key,o=await n.value;s.push({key:i,value:o})}return t.mergeObjectSync(e,s)}static mergeObjectSync(e,r){let s={};for(let n of r){let{key:i,value:o}=n;if(i.status==="aborted"||o.status==="aborted")return v;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||n.alwaysSet)&&(s[i.value]=o.value)}return{status:e.value,value:s}}},v=Object.freeze({status:"aborted"}),Pe=t=>({status:"dirty",value:t}),W=t=>({status:"valid",value:t}),Lt=t=>t.status==="aborted",Ht=t=>t.status==="dirty",xe=t=>t.status==="valid",tt=t=>typeof Promise<"u"&&t instanceof Promise});var Bs=V(()=>{});var g,Gs=V(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(g||(g={}))});function w(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:s,description:n}=t;if(e&&(r||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(o,a)=>{let{message:c}=t;return o.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??s??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:n}}function Ys(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function Mo(t){return new RegExp(`^${Ys(t)}$`)}function Xs(t){let e=`${Js}T${Ys(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function Vo(t,e){return!!((e==="v4"||!e)&&Io.test(t)||(e==="v6"||!e)&&Do.test(t))}function Wo(t,e){if(!Co.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let s=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),n=JSON.parse(atob(s));return!(typeof n!="object"||n===null||"typ"in n&&n?.typ!=="JWT"||!n.alg||e&&n.alg!==e)}catch{return!1}}function Fo(t,e){return!!((e==="v4"||!e)&&No.test(t)||(e==="v6"||!e)&&Uo.test(t))}function Ko(t,e){let r=(t.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,n=r>s?r:s,i=Number.parseInt(t.toFixed(n).replace(".","")),o=Number.parseInt(e.toFixed(n).replace(".",""));return i%o/10**n}function rt(t){if(t instanceof q){let e={};for(let r in t.shape){let s=t.shape[r];e[r]=Z.create(rt(s))}return new q({...t._def,shape:()=>e})}else return t instanceof ge?new ge({...t._def,type:rt(t.element)}):t instanceof Z?Z.create(rt(t.unwrap())):t instanceof ce?ce.create(rt(t.unwrap())):t instanceof ae?ae.create(t.items.map(e=>rt(e))):t}function Dr(t,e){let r=oe(t),s=oe(e);if(t===e)return{valid:!0,data:t};if(r===f.object&&s===f.object){let n=E.objectKeys(e),i=E.objectKeys(t).filter(a=>n.indexOf(a)!==-1),o={...t,...e};for(let a of i){let c=Dr(t[a],e[a]);if(!c.valid)return{valid:!1};o[a]=c.data}return{valid:!0,data:o}}else if(r===f.array&&s===f.array){if(t.length!==e.length)return{valid:!1};let n=[];for(let i=0;i<t.length;i++){let o=t[i],a=e[i],c=Dr(o,a);if(!c.valid)return{valid:!1};n.push(c.data)}return{valid:!0,data:n}}else return r===f.date&&s===f.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function Qs(t,e){return new Fe({values:t,typeName:_.ZodEnum,...w(e)})}function Zs(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function en(t,e={},r){return t?Se.create().superRefine((s,n)=>{let i=t(s);if(i instanceof Promise)return i.then(o=>{if(!o){let a=Zs(e,s),c=a.fatal??r??!0;n.addIssue({code:"custom",...a,fatal:c})}});if(!i){let o=Zs(e,s),a=o.fatal??r??!0;n.addIssue({code:"custom",...o,fatal:a})}}):Se.create()}var J,zs,k,So,Ao,Eo,To,$o,Co,Oo,Ro,Po,Nr,Io,No,Do,Uo,jo,Lo,Js,Ho,ke,Ie,Ne,De,Ue,st,je,Le,Se,me,Q,nt,ge,q,He,fe,Mt,Me,ae,Vt,it,ot,Wt,Ve,We,Fe,Ke,Ae,Y,Z,ce,qe,Be,at,qo,bt,wt,Ge,Bo,_,Go,tn,rn,zo,Zo,sn,Jo,Yo,Xo,Qo,ea,ta,ra,sa,na,ia,oa,aa,ca,la,ua,da,ha,pa,fa,ma,ga,ya,va,_a,ba,wa,xa,ka,Sa,Aa,Ea,Ta,$a,Ca,nn=V(()=>{Ut();jt();Gs();Ir();vt();J=class{constructor(e,r,s,n){this._cachedPath=[],this.parent=e,this.data=r,this._path=s,this._key=n}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},zs=(t,e)=>{if(xe(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new K(t.common.issues);return this._error=r,this._error}}};k=class{get description(){return this._def.description}_getType(e){return oe(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:oe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new M,ctx:{common:e.parent.common,data:e.data,parsedType:oe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(tt(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let s=this.safeParse(e,r);if(s.success)return s.data;throw s.error}safeParse(e,r){let s={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:oe(e)},n=this._parseSync({data:e,path:s.path,parent:s});return zs(s,n)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:oe(e)};if(!this["~standard"].async)try{let s=this._parseSync({data:e,path:[],parent:r});return xe(s)?{value:s.value}:{issues:r.common.issues}}catch(s){s?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(s=>xe(s)?{value:s.value}:{issues:r.common.issues})}async parseAsync(e,r){let s=await this.safeParseAsync(e,r);if(s.success)return s.data;throw s.error}async safeParseAsync(e,r){let s={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:oe(e)},n=this._parse({data:e,path:s.path,parent:s}),i=await(tt(n)?n:Promise.resolve(n));return zs(s,i)}refine(e,r){let s=n=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(n):r;return this._refinement((n,i)=>{let o=e(n),a=()=>i.addIssue({code:h.custom,...s(n)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,r){return this._refinement((s,n)=>e(s)?!0:(n.addIssue(typeof r=="function"?r(s,n):r),!1))}_refinement(e){return new Y({schema:this,typeName:_.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Z.create(this,this._def)}nullable(){return ce.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ge.create(this)}promise(){return Ae.create(this,this._def)}or(e){return He.create([this,e],this._def)}and(e){return Me.create(this,e,this._def)}transform(e){return new Y({...w(this._def),schema:this,typeName:_.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new qe({...w(this._def),innerType:this,defaultValue:r,typeName:_.ZodDefault})}brand(){return new bt({typeName:_.ZodBranded,type:this,...w(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Be({...w(this._def),innerType:this,catchValue:r,typeName:_.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return wt.create(this,e)}readonly(){return Ge.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},So=/^c[^\s-]{8,}$/i,Ao=/^[0-9a-z]+$/,Eo=/^[0-9A-HJKMNP-TV-Z]{26}$/i,To=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,$o=/^[a-z0-9_-]{21}$/i,Co=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Oo=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Ro=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Po="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Io=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,No=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Do=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Uo=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,jo=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Lo=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Js="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Ho=new RegExp(`^${Js}$`);ke=class t extends k{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==f.string){let i=this._getOrReturnCtx(e);return p(i,{code:h.invalid_type,expected:f.string,received:i.parsedType}),v}let s=new M,n;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(n=this._getOrReturnCtx(e,n),p(n,{code:h.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),s.dirty());else if(i.kind==="max")e.data.length>i.value&&(n=this._getOrReturnCtx(e,n),p(n,{code:h.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),s.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,a=e.data.length<i.value;(o||a)&&(n=this._getOrReturnCtx(e,n),o?p(n,{code:h.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&p(n,{code:h.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),s.dirty())}else if(i.kind==="email")Ro.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"email",code:h.invalid_string,message:i.message}),s.dirty());else if(i.kind==="emoji")Nr||(Nr=new RegExp(Po,"u")),Nr.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"emoji",code:h.invalid_string,message:i.message}),s.dirty());else if(i.kind==="uuid")To.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"uuid",code:h.invalid_string,message:i.message}),s.dirty());else if(i.kind==="nanoid")$o.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"nanoid",code:h.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid")So.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"cuid",code:h.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid2")Ao.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"cuid2",code:h.invalid_string,message:i.message}),s.dirty());else if(i.kind==="ulid")Eo.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"ulid",code:h.invalid_string,message:i.message}),s.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),p(n,{validation:"url",code:h.invalid_string,message:i.message}),s.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"regex",code:h.invalid_string,message:i.message}),s.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(n=this._getOrReturnCtx(e,n),p(n,{code:h.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),s.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(n=this._getOrReturnCtx(e,n),p(n,{code:h.invalid_string,validation:{startsWith:i.value},message:i.message}),s.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(n=this._getOrReturnCtx(e,n),p(n,{code:h.invalid_string,validation:{endsWith:i.value},message:i.message}),s.dirty()):i.kind==="datetime"?Xs(i).test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:h.invalid_string,validation:"datetime",message:i.message}),s.dirty()):i.kind==="date"?Ho.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:h.invalid_string,validation:"date",message:i.message}),s.dirty()):i.kind==="time"?Mo(i).test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:h.invalid_string,validation:"time",message:i.message}),s.dirty()):i.kind==="duration"?Oo.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"duration",code:h.invalid_string,message:i.message}),s.dirty()):i.kind==="ip"?Vo(e.data,i.version)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"ip",code:h.invalid_string,message:i.message}),s.dirty()):i.kind==="jwt"?Wo(e.data,i.alg)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"jwt",code:h.invalid_string,message:i.message}),s.dirty()):i.kind==="cidr"?Fo(e.data,i.version)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"cidr",code:h.invalid_string,message:i.message}),s.dirty()):i.kind==="base64"?jo.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"base64",code:h.invalid_string,message:i.message}),s.dirty()):i.kind==="base64url"?Lo.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"base64url",code:h.invalid_string,message:i.message}),s.dirty()):E.assertNever(i);return{status:s.value,value:e.data}}_regex(e,r,s){return this.refinement(n=>e.test(n),{validation:r,code:h.invalid_string,...g.errToObj(s)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...g.errToObj(e)})}url(e){return this._addCheck({kind:"url",...g.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...g.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...g.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...g.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...g.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...g.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...g.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...g.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...g.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...g.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...g.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...g.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...g.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...g.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...g.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...g.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...g.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...g.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...g.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...g.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...g.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...g.errToObj(r)})}nonempty(e){return this.min(1,g.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};ke.create=t=>new ke({checks:[],typeName:_.ZodString,coerce:t?.coerce??!1,...w(t)});Ie=class t extends k{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==f.number){let i=this._getOrReturnCtx(e);return p(i,{code:h.invalid_type,expected:f.number,received:i.parsedType}),v}let s,n=new M;for(let i of this._def.checks)i.kind==="int"?E.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{code:h.invalid_type,expected:"integer",received:"float",message:i.message}),n.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(s=this._getOrReturnCtx(e,s),p(s,{code:h.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(s=this._getOrReturnCtx(e,s),p(s,{code:h.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty()):i.kind==="multipleOf"?Ko(e.data,i.value)!==0&&(s=this._getOrReturnCtx(e,s),p(s,{code:h.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{code:h.not_finite,message:i.message}),n.dirty()):E.assertNever(i);return{status:n.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,g.toString(r))}gt(e,r){return this.setLimit("min",e,!1,g.toString(r))}lte(e,r){return this.setLimit("max",e,!0,g.toString(r))}lt(e,r){return this.setLimit("max",e,!1,g.toString(r))}setLimit(e,r,s,n){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:s,message:g.toString(n)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:g.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:g.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:g.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:g.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:g.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:g.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:g.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:g.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:g.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&E.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(r===null||s.value>r)&&(r=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value)}return Number.isFinite(r)&&Number.isFinite(e)}};Ie.create=t=>new Ie({checks:[],typeName:_.ZodNumber,coerce:t?.coerce||!1,...w(t)});Ne=class t extends k{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==f.bigint)return this._getInvalidInput(e);let s,n=new M;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(s=this._getOrReturnCtx(e,s),p(s,{code:h.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(s=this._getOrReturnCtx(e,s),p(s,{code:h.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(s=this._getOrReturnCtx(e,s),p(s,{code:h.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):E.assertNever(i);return{status:n.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return p(r,{code:h.invalid_type,expected:f.bigint,received:r.parsedType}),v}gte(e,r){return this.setLimit("min",e,!0,g.toString(r))}gt(e,r){return this.setLimit("min",e,!1,g.toString(r))}lte(e,r){return this.setLimit("max",e,!0,g.toString(r))}lt(e,r){return this.setLimit("max",e,!1,g.toString(r))}setLimit(e,r,s,n){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:s,message:g.toString(n)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:g.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:g.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:g.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:g.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:g.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Ne.create=t=>new Ne({checks:[],typeName:_.ZodBigInt,coerce:t?.coerce??!1,...w(t)});De=class extends k{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==f.boolean){let s=this._getOrReturnCtx(e);return p(s,{code:h.invalid_type,expected:f.boolean,received:s.parsedType}),v}return W(e.data)}};De.create=t=>new De({typeName:_.ZodBoolean,coerce:t?.coerce||!1,...w(t)});Ue=class t extends k{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==f.date){let i=this._getOrReturnCtx(e);return p(i,{code:h.invalid_type,expected:f.date,received:i.parsedType}),v}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return p(i,{code:h.invalid_date}),v}let s=new M,n;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(n=this._getOrReturnCtx(e,n),p(n,{code:h.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),s.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(n=this._getOrReturnCtx(e,n),p(n,{code:h.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),s.dirty()):E.assertNever(i);return{status:s.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:g.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:g.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};Ue.create=t=>new Ue({checks:[],coerce:t?.coerce||!1,typeName:_.ZodDate,...w(t)});st=class extends k{_parse(e){if(this._getType(e)!==f.symbol){let s=this._getOrReturnCtx(e);return p(s,{code:h.invalid_type,expected:f.symbol,received:s.parsedType}),v}return W(e.data)}};st.create=t=>new st({typeName:_.ZodSymbol,...w(t)});je=class extends k{_parse(e){if(this._getType(e)!==f.undefined){let s=this._getOrReturnCtx(e);return p(s,{code:h.invalid_type,expected:f.undefined,received:s.parsedType}),v}return W(e.data)}};je.create=t=>new je({typeName:_.ZodUndefined,...w(t)});Le=class extends k{_parse(e){if(this._getType(e)!==f.null){let s=this._getOrReturnCtx(e);return p(s,{code:h.invalid_type,expected:f.null,received:s.parsedType}),v}return W(e.data)}};Le.create=t=>new Le({typeName:_.ZodNull,...w(t)});Se=class extends k{constructor(){super(...arguments),this._any=!0}_parse(e){return W(e.data)}};Se.create=t=>new Se({typeName:_.ZodAny,...w(t)});me=class extends k{constructor(){super(...arguments),this._unknown=!0}_parse(e){return W(e.data)}};me.create=t=>new me({typeName:_.ZodUnknown,...w(t)});Q=class extends k{_parse(e){let r=this._getOrReturnCtx(e);return p(r,{code:h.invalid_type,expected:f.never,received:r.parsedType}),v}};Q.create=t=>new Q({typeName:_.ZodNever,...w(t)});nt=class extends k{_parse(e){if(this._getType(e)!==f.undefined){let s=this._getOrReturnCtx(e);return p(s,{code:h.invalid_type,expected:f.void,received:s.parsedType}),v}return W(e.data)}};nt.create=t=>new nt({typeName:_.ZodVoid,...w(t)});ge=class t extends k{_parse(e){let{ctx:r,status:s}=this._processInputParams(e),n=this._def;if(r.parsedType!==f.array)return p(r,{code:h.invalid_type,expected:f.array,received:r.parsedType}),v;if(n.exactLength!==null){let o=r.data.length>n.exactLength.value,a=r.data.length<n.exactLength.value;(o||a)&&(p(r,{code:o?h.too_big:h.too_small,minimum:a?n.exactLength.value:void 0,maximum:o?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),s.dirty())}if(n.minLength!==null&&r.data.length<n.minLength.value&&(p(r,{code:h.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),s.dirty()),n.maxLength!==null&&r.data.length>n.maxLength.value&&(p(r,{code:h.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),s.dirty()),r.common.async)return Promise.all([...r.data].map((o,a)=>n.type._parseAsync(new J(r,o,r.path,a)))).then(o=>M.mergeArray(s,o));let i=[...r.data].map((o,a)=>n.type._parseSync(new J(r,o,r.path,a)));return M.mergeArray(s,i)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:g.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:g.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:g.toString(r)}})}nonempty(e){return this.min(1,e)}};ge.create=(t,e)=>new ge({type:t,minLength:null,maxLength:null,exactLength:null,typeName:_.ZodArray,...w(e)});q=class t extends k{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=E.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==f.object){let l=this._getOrReturnCtx(e);return p(l,{code:h.invalid_type,expected:f.object,received:l.parsedType}),v}let{status:s,ctx:n}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof Q&&this._def.unknownKeys==="strip"))for(let l in n.data)o.includes(l)||a.push(l);let c=[];for(let l of o){let u=i[l],d=n.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new J(n,d,n.path,l)),alwaysSet:l in n.data})}if(this._def.catchall instanceof Q){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of a)c.push({key:{status:"valid",value:u},value:{status:"valid",value:n.data[u]}});else if(l==="strict")a.length>0&&(p(n,{code:h.unrecognized_keys,keys:a}),s.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let u of a){let d=n.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new J(n,d,n.path,u)),alwaysSet:u in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let d=await u.key,m=await u.value;l.push({key:d,value:m,alwaysSet:u.alwaysSet})}return l}).then(l=>M.mergeObjectSync(s,l)):M.mergeObjectSync(s,c)}get shape(){return this._def.shape()}strict(e){return g.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,s)=>{let n=this._def.errorMap?.(r,s).message??s.defaultError;return r.code==="unrecognized_keys"?{message:g.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:_.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let s of E.objectKeys(e))e[s]&&this.shape[s]&&(r[s]=this.shape[s]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let s of E.objectKeys(this.shape))e[s]||(r[s]=this.shape[s]);return new t({...this._def,shape:()=>r})}deepPartial(){return rt(this)}partial(e){let r={};for(let s of E.objectKeys(this.shape)){let n=this.shape[s];e&&!e[s]?r[s]=n:r[s]=n.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let s of E.objectKeys(this.shape))if(e&&!e[s])r[s]=this.shape[s];else{let i=this.shape[s];for(;i instanceof Z;)i=i._def.innerType;r[s]=i}return new t({...this._def,shape:()=>r})}keyof(){return Qs(E.objectKeys(this.shape))}};q.create=(t,e)=>new q({shape:()=>t,unknownKeys:"strip",catchall:Q.create(),typeName:_.ZodObject,...w(e)});q.strictCreate=(t,e)=>new q({shape:()=>t,unknownKeys:"strict",catchall:Q.create(),typeName:_.ZodObject,...w(e)});q.lazycreate=(t,e)=>new q({shape:t,unknownKeys:"strip",catchall:Q.create(),typeName:_.ZodObject,...w(e)});He=class extends k{_parse(e){let{ctx:r}=this._processInputParams(e),s=this._def.options;function n(i){for(let a of i)if(a.result.status==="valid")return a.result;for(let a of i)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(a=>new K(a.ctx.common.issues));return p(r,{code:h.invalid_union,unionErrors:o}),v}if(r.common.async)return Promise.all(s.map(async i=>{let o={...r,common:{...r.common,issues:[]},parent:null};return{result:await i._parseAsync({data:r.data,path:r.path,parent:o}),ctx:o}})).then(n);{let i,o=[];for(let c of s){let l={...r,common:{...r.common,issues:[]},parent:null},u=c._parseSync({data:r.data,path:r.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!i&&(i={result:u,ctx:l}),l.common.issues.length&&o.push(l.common.issues)}if(i)return r.common.issues.push(...i.ctx.common.issues),i.result;let a=o.map(c=>new K(c));return p(r,{code:h.invalid_union,unionErrors:a}),v}}get options(){return this._def.options}};He.create=(t,e)=>new He({options:t,typeName:_.ZodUnion,...w(e)});fe=t=>t instanceof Ve?fe(t.schema):t instanceof Y?fe(t.innerType()):t instanceof We?[t.value]:t instanceof Fe?t.options:t instanceof Ke?E.objectValues(t.enum):t instanceof qe?fe(t._def.innerType):t instanceof je?[void 0]:t instanceof Le?[null]:t instanceof Z?[void 0,...fe(t.unwrap())]:t instanceof ce?[null,...fe(t.unwrap())]:t instanceof bt||t instanceof Ge?fe(t.unwrap()):t instanceof Be?fe(t._def.innerType):[],Mt=class t extends k{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==f.object)return p(r,{code:h.invalid_type,expected:f.object,received:r.parsedType}),v;let s=this.discriminator,n=r.data[s],i=this.optionsMap.get(n);return i?r.common.async?i._parseAsync({data:r.data,path:r.path,parent:r}):i._parseSync({data:r.data,path:r.path,parent:r}):(p(r,{code:h.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),v)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,s){let n=new Map;for(let i of r){let o=fe(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of o){if(n.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);n.set(a,i)}}return new t({typeName:_.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:n,...w(s)})}};Me=class extends k{_parse(e){let{status:r,ctx:s}=this._processInputParams(e),n=(i,o)=>{if(Lt(i)||Lt(o))return v;let a=Dr(i.value,o.value);return a.valid?((Ht(i)||Ht(o))&&r.dirty(),{status:r.value,value:a.data}):(p(s,{code:h.invalid_intersection_types}),v)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([i,o])=>n(i,o)):n(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}};Me.create=(t,e,r)=>new Me({left:t,right:e,typeName:_.ZodIntersection,...w(r)});ae=class t extends k{_parse(e){let{status:r,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.array)return p(s,{code:h.invalid_type,expected:f.array,received:s.parsedType}),v;if(s.data.length<this._def.items.length)return p(s,{code:h.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),v;!this._def.rest&&s.data.length>this._def.items.length&&(p(s,{code:h.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let i=[...s.data].map((o,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new J(s,o,s.path,a)):null}).filter(o=>!!o);return s.common.async?Promise.all(i).then(o=>M.mergeArray(r,o)):M.mergeArray(r,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};ae.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ae({items:t,typeName:_.ZodTuple,rest:null,...w(e)})};Vt=class t extends k{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.object)return p(s,{code:h.invalid_type,expected:f.object,received:s.parsedType}),v;let n=[],i=this._def.keyType,o=this._def.valueType;for(let a in s.data)n.push({key:i._parse(new J(s,a,s.path,a)),value:o._parse(new J(s,s.data[a],s.path,a)),alwaysSet:a in s.data});return s.common.async?M.mergeObjectAsync(r,n):M.mergeObjectSync(r,n)}get element(){return this._def.valueType}static create(e,r,s){return r instanceof k?new t({keyType:e,valueType:r,typeName:_.ZodRecord,...w(s)}):new t({keyType:ke.create(),valueType:e,typeName:_.ZodRecord,...w(r)})}},it=class extends k{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.map)return p(s,{code:h.invalid_type,expected:f.map,received:s.parsedType}),v;let n=this._def.keyType,i=this._def.valueType,o=[...s.data.entries()].map(([a,c],l)=>({key:n._parse(new J(s,a,s.path,[l,"key"])),value:i._parse(new J(s,c,s.path,[l,"value"]))}));if(s.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of o){let l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return v;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(l.value,u.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of o){let l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return v;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(l.value,u.value)}return{status:r.value,value:a}}}};it.create=(t,e,r)=>new it({valueType:e,keyType:t,typeName:_.ZodMap,...w(r)});ot=class t extends k{_parse(e){let{status:r,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.set)return p(s,{code:h.invalid_type,expected:f.set,received:s.parsedType}),v;let n=this._def;n.minSize!==null&&s.data.size<n.minSize.value&&(p(s,{code:h.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),r.dirty()),n.maxSize!==null&&s.data.size>n.maxSize.value&&(p(s,{code:h.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),r.dirty());let i=this._def.valueType;function o(c){let l=new Set;for(let u of c){if(u.status==="aborted")return v;u.status==="dirty"&&r.dirty(),l.add(u.value)}return{status:r.value,value:l}}let a=[...s.data.values()].map((c,l)=>i._parse(new J(s,c,s.path,l)));return s.common.async?Promise.all(a).then(c=>o(c)):o(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:g.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:g.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};ot.create=(t,e)=>new ot({valueType:t,minSize:null,maxSize:null,typeName:_.ZodSet,...w(e)});Wt=class t extends k{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==f.function)return p(r,{code:h.invalid_type,expected:f.function,received:r.parsedType}),v;function s(a,c){return _t({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,et(),pe].filter(l=>!!l),issueData:{code:h.invalid_arguments,argumentsError:c}})}function n(a,c){return _t({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,et(),pe].filter(l=>!!l),issueData:{code:h.invalid_return_type,returnTypeError:c}})}let i={errorMap:r.common.contextualErrorMap},o=r.data;if(this._def.returns instanceof Ae){let a=this;return W(async function(...c){let l=new K([]),u=await a._def.args.parseAsync(c,i).catch(x=>{throw l.addIssue(s(c,x)),l}),d=await Reflect.apply(o,this,u);return await a._def.returns._def.type.parseAsync(d,i).catch(x=>{throw l.addIssue(n(d,x)),l})})}else{let a=this;return W(function(...c){let l=a._def.args.safeParse(c,i);if(!l.success)throw new K([s(c,l.error)]);let u=Reflect.apply(o,this,l.data),d=a._def.returns.safeParse(u,i);if(!d.success)throw new K([n(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:ae.create(e).rest(me.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,s){return new t({args:e||ae.create([]).rest(me.create()),returns:r||me.create(),typeName:_.ZodFunction,...w(s)})}},Ve=class extends k{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Ve.create=(t,e)=>new Ve({getter:t,typeName:_.ZodLazy,...w(e)});We=class extends k{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return p(r,{received:r.data,code:h.invalid_literal,expected:this._def.value}),v}return{status:"valid",value:e.data}}get value(){return this._def.value}};We.create=(t,e)=>new We({value:t,typeName:_.ZodLiteral,...w(e)});Fe=class t extends k{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),s=this._def.values;return p(r,{expected:E.joinValues(s),received:r.parsedType,code:h.invalid_type}),v}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),s=this._def.values;return p(r,{received:r.data,code:h.invalid_enum_value,options:s}),v}return W(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(s=>!e.includes(s)),{...this._def,...r})}};Fe.create=Qs;Ke=class extends k{_parse(e){let r=E.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==f.string&&s.parsedType!==f.number){let n=E.objectValues(r);return p(s,{expected:E.joinValues(n),received:s.parsedType,code:h.invalid_type}),v}if(this._cache||(this._cache=new Set(E.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let n=E.objectValues(r);return p(s,{received:s.data,code:h.invalid_enum_value,options:n}),v}return W(e.data)}get enum(){return this._def.values}};Ke.create=(t,e)=>new Ke({values:t,typeName:_.ZodNativeEnum,...w(e)});Ae=class extends k{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==f.promise&&r.common.async===!1)return p(r,{code:h.invalid_type,expected:f.promise,received:r.parsedType}),v;let s=r.parsedType===f.promise?r.data:Promise.resolve(r.data);return W(s.then(n=>this._def.type.parseAsync(n,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Ae.create=(t,e)=>new Ae({type:t,typeName:_.ZodPromise,...w(e)});Y=class extends k{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===_.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:s}=this._processInputParams(e),n=this._def.effect||null,i={addIssue:o=>{p(s,o),o.fatal?r.abort():r.dirty()},get path(){return s.path}};if(i.addIssue=i.addIssue.bind(i),n.type==="preprocess"){let o=n.transform(s.data,i);if(s.common.async)return Promise.resolve(o).then(async a=>{if(r.value==="aborted")return v;let c=await this._def.schema._parseAsync({data:a,path:s.path,parent:s});return c.status==="aborted"?v:c.status==="dirty"?Pe(c.value):r.value==="dirty"?Pe(c.value):c});{if(r.value==="aborted")return v;let a=this._def.schema._parseSync({data:o,path:s.path,parent:s});return a.status==="aborted"?v:a.status==="dirty"?Pe(a.value):r.value==="dirty"?Pe(a.value):a}}if(n.type==="refinement"){let o=a=>{let c=n.refinement(a,i);if(s.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(s.common.async===!1){let a=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return a.status==="aborted"?v:(a.status==="dirty"&&r.dirty(),o(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(a=>a.status==="aborted"?v:(a.status==="dirty"&&r.dirty(),o(a.value).then(()=>({status:r.value,value:a.value}))))}if(n.type==="transform")if(s.common.async===!1){let o=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!xe(o))return v;let a=n.transform(o.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(o=>xe(o)?Promise.resolve(n.transform(o.value,i)).then(a=>({status:r.value,value:a})):v);E.assertNever(n)}};Y.create=(t,e,r)=>new Y({schema:t,typeName:_.ZodEffects,effect:e,...w(r)});Y.createWithPreprocess=(t,e,r)=>new Y({schema:e,effect:{type:"preprocess",transform:t},typeName:_.ZodEffects,...w(r)});Z=class extends k{_parse(e){return this._getType(e)===f.undefined?W(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Z.create=(t,e)=>new Z({innerType:t,typeName:_.ZodOptional,...w(e)});ce=class extends k{_parse(e){return this._getType(e)===f.null?W(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ce.create=(t,e)=>new ce({innerType:t,typeName:_.ZodNullable,...w(e)});qe=class extends k{_parse(e){let{ctx:r}=this._processInputParams(e),s=r.data;return r.parsedType===f.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};qe.create=(t,e)=>new qe({innerType:t,typeName:_.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...w(e)});Be=class extends k{_parse(e){let{ctx:r}=this._processInputParams(e),s={...r,common:{...r.common,issues:[]}},n=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return tt(n)?n.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new K(s.common.issues)},input:s.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new K(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};Be.create=(t,e)=>new Be({innerType:t,typeName:_.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...w(e)});at=class extends k{_parse(e){if(this._getType(e)!==f.nan){let s=this._getOrReturnCtx(e);return p(s,{code:h.invalid_type,expected:f.nan,received:s.parsedType}),v}return{status:"valid",value:e.data}}};at.create=t=>new at({typeName:_.ZodNaN,...w(t)});qo=Symbol("zod_brand"),bt=class extends k{_parse(e){let{ctx:r}=this._processInputParams(e),s=r.data;return this._def.type._parse({data:s,path:r.path,parent:r})}unwrap(){return this._def.type}},wt=class t extends k{_parse(e){let{status:r,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return i.status==="aborted"?v:i.status==="dirty"?(r.dirty(),Pe(i.value)):this._def.out._parseAsync({data:i.value,path:s.path,parent:s})})();{let n=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return n.status==="aborted"?v:n.status==="dirty"?(r.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:s.path,parent:s})}}static create(e,r){return new t({in:e,out:r,typeName:_.ZodPipeline})}},Ge=class extends k{_parse(e){let r=this._def.innerType._parse(e),s=n=>(xe(n)&&(n.value=Object.freeze(n.value)),n);return tt(r)?r.then(n=>s(n)):s(r)}unwrap(){return this._def.innerType}};Ge.create=(t,e)=>new Ge({innerType:t,typeName:_.ZodReadonly,...w(e)});Bo={object:q.lazycreate};(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(_||(_={}));Go=(t,e={message:`Input not instance of ${t.name}`})=>en(r=>r instanceof t,e),tn=ke.create,rn=Ie.create,zo=at.create,Zo=Ne.create,sn=De.create,Jo=Ue.create,Yo=st.create,Xo=je.create,Qo=Le.create,ea=Se.create,ta=me.create,ra=Q.create,sa=nt.create,na=ge.create,ia=q.create,oa=q.strictCreate,aa=He.create,ca=Mt.create,la=Me.create,ua=ae.create,da=Vt.create,ha=it.create,pa=ot.create,fa=Wt.create,ma=Ve.create,ga=We.create,ya=Fe.create,va=Ke.create,_a=Ae.create,ba=Y.create,wa=Z.create,xa=ce.create,ka=Y.createWithPreprocess,Sa=wt.create,Aa=()=>tn().optional(),Ea=()=>rn().optional(),Ta=()=>sn().optional(),$a={string:(t=>ke.create({...t,coerce:!0})),number:(t=>Ie.create({...t,coerce:!0})),boolean:(t=>De.create({...t,coerce:!0})),bigint:(t=>Ne.create({...t,coerce:!0})),date:(t=>Ue.create({...t,coerce:!0}))},Ca=v});var B={};kt(B,{BRAND:()=>qo,DIRTY:()=>Pe,EMPTY_PATH:()=>ko,INVALID:()=>v,NEVER:()=>Ca,OK:()=>W,ParseStatus:()=>M,Schema:()=>k,ZodAny:()=>Se,ZodArray:()=>ge,ZodBigInt:()=>Ne,ZodBoolean:()=>De,ZodBranded:()=>bt,ZodCatch:()=>Be,ZodDate:()=>Ue,ZodDefault:()=>qe,ZodDiscriminatedUnion:()=>Mt,ZodEffects:()=>Y,ZodEnum:()=>Fe,ZodError:()=>K,ZodFirstPartyTypeKind:()=>_,ZodFunction:()=>Wt,ZodIntersection:()=>Me,ZodIssueCode:()=>h,ZodLazy:()=>Ve,ZodLiteral:()=>We,ZodMap:()=>it,ZodNaN:()=>at,ZodNativeEnum:()=>Ke,ZodNever:()=>Q,ZodNull:()=>Le,ZodNullable:()=>ce,ZodNumber:()=>Ie,ZodObject:()=>q,ZodOptional:()=>Z,ZodParsedType:()=>f,ZodPipeline:()=>wt,ZodPromise:()=>Ae,ZodReadonly:()=>Ge,ZodRecord:()=>Vt,ZodSchema:()=>k,ZodSet:()=>ot,ZodString:()=>ke,ZodSymbol:()=>st,ZodTransformer:()=>Y,ZodTuple:()=>ae,ZodType:()=>k,ZodUndefined:()=>je,ZodUnion:()=>He,ZodUnknown:()=>me,ZodVoid:()=>nt,addIssueToContext:()=>p,any:()=>ea,array:()=>na,bigint:()=>Zo,boolean:()=>sn,coerce:()=>$a,custom:()=>en,date:()=>Jo,datetimeRegex:()=>Xs,defaultErrorMap:()=>pe,discriminatedUnion:()=>ca,effect:()=>ba,enum:()=>ya,function:()=>fa,getErrorMap:()=>et,getParsedType:()=>oe,instanceof:()=>Go,intersection:()=>la,isAborted:()=>Lt,isAsync:()=>tt,isDirty:()=>Ht,isValid:()=>xe,late:()=>Bo,lazy:()=>ma,literal:()=>ga,makeIssue:()=>_t,map:()=>ha,nan:()=>zo,nativeEnum:()=>va,never:()=>ra,null:()=>Qo,nullable:()=>xa,number:()=>rn,object:()=>ia,objectUtil:()=>Rr,oboolean:()=>Ta,onumber:()=>Ea,optional:()=>wa,ostring:()=>Aa,pipeline:()=>Sa,preprocess:()=>ka,promise:()=>_a,quotelessJson:()=>bo,record:()=>da,set:()=>pa,setErrorMap:()=>xo,strictObject:()=>oa,string:()=>tn,symbol:()=>Yo,transformer:()=>ba,tuple:()=>ua,undefined:()=>Xo,union:()=>aa,unknown:()=>ta,util:()=>E,void:()=>sa});var Ur=V(()=>{jt();Ir();Bs();vt();nn();Ut()});var on=V(()=>{Ur();Ur()});function an(t){switch(t.type){case"string":{let e=B.string();return t.pattern&&(e=e.regex(new RegExp(t.pattern))),t.minLength&&(e=e.min(t.minLength)),t.maxLength&&(e=e.max(t.maxLength)),t.enum?B.enum(t.enum):e}case"integer":case"number":{let e=t.type==="integer"?B.coerce.number().int():B.coerce.number();return t.minimum!==void 0&&(e=e.min(t.minimum)),t.maximum!==void 0&&(e=e.max(t.maximum)),e}case"boolean":return B.preprocess(e=>e==="true"||e===!0?!0:e==="false"||e===!1?!1:e,B.boolean());case"array":return B.array(t.items?an(t.items):B.any());case"object":return B.record(B.any());default:return B.any()}}function jr(t,e){let r=an(e),s=r.safeParse(t);if(s.success)return s.data;if(e.type==="object"||e.type==="array")try{let n=JSON.parse(t);return r.parse(n)}catch{}return t}var cn=V(()=>{"use strict";on()});import*as Ee from"node:fs";import*as ee from"node:path";function Ra(t){let e=ee.extname(t).toLowerCase();return!!(Oa.has(e)||e==="")}function ln(t){let e=ee.resolve(t),r=Ee.readFileSync(e),s=ee.relative(process.cwd(),e);if(Ra(t))return{path:s,contents:r.toString("utf-8")};let n=ee.extname(t).toLowerCase().slice(1)||"bin",o={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",ico:"image/x-icon",pdf:"application/pdf",zip:"application/zip",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf"}[n]||"application/octet-stream",a=r.toString("base64");return{path:s,contents:`data:${o};base64,${a}`}}function un(t){let e=[];for(let r of t){let s=ee.resolve(r);if(Ee.statSync(s).isDirectory()){let i=dn(s);for(let o of i)e.push(ln(o))}else e.push(ln(s))}return e}function dn(t){let e=[],r=Ee.readdirSync(t,{withFileTypes:!0});for(let s of r){let n=ee.join(t,s.name);s.isDirectory()?e.push(...dn(n)):e.push(n)}return e}function hn(t){if(t.startsWith("-"))return!1;try{let e=ee.resolve(t);return Ee.existsSync(e)}catch{return!1}}var Oa,pn=V(()=>{"use strict";Oa=new Set([".txt",".md",".html",".htm",".css",".js",".ts",".jsx",".tsx",".json",".xml",".yaml",".yml",".toml",".ini",".cfg",".conf",".sh",".bash",".zsh",".fish",".bat",".ps1",".py",".rb",".go",".rs",".java",".c",".cpp",".h",".hpp",".cs",".php",".swift",".kt",".scala",".r",".sql",".graphql",".proto",".env",".gitignore",".dockerignore",".editorconfig",".prettierrc",".eslintrc",".svg",".csv",".tsv",".log"])});var gn={};kt(gn,{execute:()=>Lr});import*as fn from"node:fs";import*as mn from"node:path";function Pa(t){try{let e=mn.join(process.cwd(),t),r=fn.readFileSync(e,"utf-8"),s=JSON.parse(r);if(s&&typeof s=="object"&&!Array.isArray(s))return s}catch{}return{}}function Ia(t){return t.args?t.args:[...t.params.path.filter(e=>e.required),...t.params.query.filter(e=>e.required),...t.params.body.filter(e=>e.required)].map(e=>e.name)}async function Lr(t,e,r,s){let n=await we(t),i=n.actions.find(y=>y.slug===e),o=n.actions.some(y=>y.slug.startsWith(e+"."));if(!i&&o)return Or(t,e);if(!i){console.error(`\x1B[31mAction "${e}" not found.\x1B[0m`);let y=n.actions.filter(A=>A.slug.includes(e)).map(A=>A.slug);if(y.length>0){console.log(`
35
- Did you mean:`);for(let A of y)console.log(` \x1B[36m${A}\x1B[0m`)}process.exit(1)}let a=await $r(t,e),c=[...a.params.path,...a.params.query,...a.params.body],l=new Map(c.map(y=>[y.name,y])),u=Ia(a),d=new Pt().exitOverride().name(e).description(a.description).allowUnknownOption(!1).configureOutput({writeOut:y=>process.stdout.write(y),writeErr:y=>process.stderr.write(y)});if(a.payment.mode!=="free"){let y=a.payment.description?`${a.payment.mode} \u2014 ${a.payment.description}`:a.payment.mode;d.addHelpText("after",`
34
+ `);for(let i of n){let o=i.payment!=="free"?` \x1B[33m[$${i.payment}]\x1B[0m`:"";console.log(` \x1B[36m${i.slug}\x1B[0m \x1B[90m(${i.method})\x1B[0m \u2014 ${i.description}${o}`)}console.log()}var Dt=W(()=>{"use strict";Qe()});var E,Rr,f,ae,vt=W(()=>{(function(t){t.assertEqual=n=>{};function e(n){}t.assertIs=e;function r(n){throw new Error}t.assertNever=r,t.arrayToEnum=n=>{let i={};for(let o of n)i[o]=o;return i},t.getValidEnumValues=n=>{let i=t.objectKeys(n).filter(a=>typeof n[n[a]]!="number"),o={};for(let a of i)o[a]=n[a];return t.objectValues(o)},t.objectValues=n=>t.objectKeys(n).map(function(i){return n[i]}),t.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{let i=[];for(let o in n)Object.prototype.hasOwnProperty.call(n,o)&&i.push(o);return i},t.find=(n,i)=>{for(let o of n)if(i(o))return o},t.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&Number.isFinite(n)&&Math.floor(n)===n;function s(n,i=" | "){return n.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}t.joinValues=s,t.jsonStringifyReplacer=(n,i)=>typeof i=="bigint"?i.toString():i})(E||(E={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Rr||(Rr={}));f=E.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ae=t=>{switch(typeof t){case"undefined":return f.undefined;case"string":return f.string;case"number":return Number.isNaN(t)?f.nan:f.number;case"boolean":return f.boolean;case"function":return f.function;case"bigint":return f.bigint;case"symbol":return f.symbol;case"object":return Array.isArray(t)?f.array:t===null?f.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?f.promise:typeof Map<"u"&&t instanceof Map?f.map:typeof Set<"u"&&t instanceof Set?f.set:typeof Date<"u"&&t instanceof Date?f.date:f.object;default:return f.unknown}}});var h,bo,q,Ut=W(()=>{vt();h=E.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),bo=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),q=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(i){return i.message},s={_errors:[]},n=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(n);else if(o.code==="invalid_return_type")n(o.returnTypeError);else if(o.code==="invalid_arguments")n(o.argumentsError);else if(o.path.length===0)s._errors.push(r(o));else{let a=s,c=0;for(;c<o.path.length;){let l=o.path[c];c===o.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(r(o))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return n(this),s}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,E.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},s=[];for(let n of this.issues)if(n.path.length>0){let i=n.path[0];r[i]=r[i]||[],r[i].push(e(n))}else s.push(e(n));return{formErrors:s,fieldErrors:r}}get formErrors(){return this.flatten()}};q.create=t=>new q(t)});var wo,pe,Pr=W(()=>{Ut();vt();wo=(t,e)=>{let r;switch(t.code){case h.invalid_type:t.received===f.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case h.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,E.jsonStringifyReplacer)}`;break;case h.unrecognized_keys:r=`Unrecognized key(s) in object: ${E.joinValues(t.keys,", ")}`;break;case h.invalid_union:r="Invalid input";break;case h.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${E.joinValues(t.options)}`;break;case h.invalid_enum_value:r=`Invalid enum value. Expected ${E.joinValues(t.options)}, received '${t.received}'`;break;case h.invalid_arguments:r="Invalid function arguments";break;case h.invalid_return_type:r="Invalid function return type";break;case h.invalid_date:r="Invalid date";break;case h.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:E.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case h.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case h.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case h.custom:r="Invalid input";break;case h.invalid_intersection_types:r="Intersection results could not be merged";break;case h.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case h.not_finite:r="Number must be finite";break;default:r=e.defaultError,E.assertNever(t)}return{message:r}},pe=wo});function xo(t){qs=t}function et(){return qs}var qs,jt=W(()=>{Pr();qs=pe});function p(t,e){let r=et(),s=_t({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===pe?void 0:pe].filter(n=>!!n)});t.common.issues.push(s)}var _t,ko,V,v,Pe,F,Lt,Ht,ke,tt,Ir=W(()=>{jt();Pr();_t=t=>{let{data:e,path:r,errorMaps:s,issueData:n}=t,i=[...r,...n.path||[]],o={...n,path:i};if(n.message!==void 0)return{...n,path:i,message:n.message};let a="",c=s.filter(l=>!!l).slice().reverse();for(let l of c)a=l(o,{data:e,defaultError:a}).message;return{...n,path:i,message:a}},ko=[];V=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let s=[];for(let n of r){if(n.status==="aborted")return v;n.status==="dirty"&&e.dirty(),s.push(n.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,r){let s=[];for(let n of r){let i=await n.key,o=await n.value;s.push({key:i,value:o})}return t.mergeObjectSync(e,s)}static mergeObjectSync(e,r){let s={};for(let n of r){let{key:i,value:o}=n;if(i.status==="aborted"||o.status==="aborted")return v;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||n.alwaysSet)&&(s[i.value]=o.value)}return{status:e.value,value:s}}},v=Object.freeze({status:"aborted"}),Pe=t=>({status:"dirty",value:t}),F=t=>({status:"valid",value:t}),Lt=t=>t.status==="aborted",Ht=t=>t.status==="dirty",ke=t=>t.status==="valid",tt=t=>typeof Promise<"u"&&t instanceof Promise});var Bs=W(()=>{});var g,Gs=W(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(g||(g={}))});function x(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:s,description:n}=t;if(e&&(r||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(o,a)=>{let{message:c}=t;return o.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??s??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:n}}function Ys(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function Mo(t){return new RegExp(`^${Ys(t)}$`)}function Xs(t){let e=`${Js}T${Ys(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function Vo(t,e){return!!((e==="v4"||!e)&&Io.test(t)||(e==="v6"||!e)&&Do.test(t))}function Wo(t,e){if(!Co.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let s=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),n=JSON.parse(atob(s));return!(typeof n!="object"||n===null||"typ"in n&&n?.typ!=="JWT"||!n.alg||e&&n.alg!==e)}catch{return!1}}function Fo(t,e){return!!((e==="v4"||!e)&&No.test(t)||(e==="v6"||!e)&&Uo.test(t))}function Ko(t,e){let r=(t.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,n=r>s?r:s,i=Number.parseInt(t.toFixed(n).replace(".","")),o=Number.parseInt(e.toFixed(n).replace(".",""));return i%o/10**n}function rt(t){if(t instanceof B){let e={};for(let r in t.shape){let s=t.shape[r];e[r]=Y.create(rt(s))}return new B({...t._def,shape:()=>e})}else return t instanceof ge?new ge({...t._def,type:rt(t.element)}):t instanceof Y?Y.create(rt(t.unwrap())):t instanceof le?le.create(rt(t.unwrap())):t instanceof ce?ce.create(t.items.map(e=>rt(e))):t}function Dr(t,e){let r=ae(t),s=ae(e);if(t===e)return{valid:!0,data:t};if(r===f.object&&s===f.object){let n=E.objectKeys(e),i=E.objectKeys(t).filter(a=>n.indexOf(a)!==-1),o={...t,...e};for(let a of i){let c=Dr(t[a],e[a]);if(!c.valid)return{valid:!1};o[a]=c.data}return{valid:!0,data:o}}else if(r===f.array&&s===f.array){if(t.length!==e.length)return{valid:!1};let n=[];for(let i=0;i<t.length;i++){let o=t[i],a=e[i],c=Dr(o,a);if(!c.valid)return{valid:!1};n.push(c.data)}return{valid:!0,data:n}}else return r===f.date&&s===f.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function Qs(t,e){return new Fe({values:t,typeName:_.ZodEnum,...x(e)})}function Zs(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function en(t,e={},r){return t?Se.create().superRefine((s,n)=>{let i=t(s);if(i instanceof Promise)return i.then(o=>{if(!o){let a=Zs(e,s),c=a.fatal??r??!0;n.addIssue({code:"custom",...a,fatal:c})}});if(!i){let o=Zs(e,s),a=o.fatal??r??!0;n.addIssue({code:"custom",...o,fatal:a})}}):Se.create()}var X,zs,k,Ao,So,Eo,To,$o,Co,Oo,Ro,Po,Nr,Io,No,Do,Uo,jo,Lo,Js,Ho,Ae,Ie,Ne,De,Ue,st,je,Le,Se,me,te,nt,ge,B,He,fe,Mt,Me,ce,Vt,it,ot,Wt,Ve,We,Fe,Ke,Ee,Q,Y,le,qe,Be,at,qo,bt,wt,Ge,Bo,_,Go,tn,rn,zo,Zo,sn,Jo,Yo,Xo,Qo,ea,ta,ra,sa,na,ia,oa,aa,ca,la,ua,da,ha,pa,fa,ma,ga,ya,va,_a,ba,wa,xa,ka,Aa,Sa,Ea,Ta,$a,Ca,nn=W(()=>{Ut();jt();Gs();Ir();vt();X=class{constructor(e,r,s,n){this._cachedPath=[],this.parent=e,this.data=r,this._path=s,this._key=n}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},zs=(t,e)=>{if(ke(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new q(t.common.issues);return this._error=r,this._error}}};k=class{get description(){return this._def.description}_getType(e){return ae(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:ae(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new V,ctx:{common:e.parent.common,data:e.data,parsedType:ae(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(tt(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let s=this.safeParse(e,r);if(s.success)return s.data;throw s.error}safeParse(e,r){let s={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ae(e)},n=this._parseSync({data:e,path:s.path,parent:s});return zs(s,n)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ae(e)};if(!this["~standard"].async)try{let s=this._parseSync({data:e,path:[],parent:r});return ke(s)?{value:s.value}:{issues:r.common.issues}}catch(s){s?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(s=>ke(s)?{value:s.value}:{issues:r.common.issues})}async parseAsync(e,r){let s=await this.safeParseAsync(e,r);if(s.success)return s.data;throw s.error}async safeParseAsync(e,r){let s={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ae(e)},n=this._parse({data:e,path:s.path,parent:s}),i=await(tt(n)?n:Promise.resolve(n));return zs(s,i)}refine(e,r){let s=n=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(n):r;return this._refinement((n,i)=>{let o=e(n),a=()=>i.addIssue({code:h.custom,...s(n)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,r){return this._refinement((s,n)=>e(s)?!0:(n.addIssue(typeof r=="function"?r(s,n):r),!1))}_refinement(e){return new Q({schema:this,typeName:_.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Y.create(this,this._def)}nullable(){return le.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ge.create(this)}promise(){return Ee.create(this,this._def)}or(e){return He.create([this,e],this._def)}and(e){return Me.create(this,e,this._def)}transform(e){return new Q({...x(this._def),schema:this,typeName:_.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new qe({...x(this._def),innerType:this,defaultValue:r,typeName:_.ZodDefault})}brand(){return new bt({typeName:_.ZodBranded,type:this,...x(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Be({...x(this._def),innerType:this,catchValue:r,typeName:_.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return wt.create(this,e)}readonly(){return Ge.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Ao=/^c[^\s-]{8,}$/i,So=/^[0-9a-z]+$/,Eo=/^[0-9A-HJKMNP-TV-Z]{26}$/i,To=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,$o=/^[a-z0-9_-]{21}$/i,Co=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Oo=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Ro=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Po="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Io=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,No=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Do=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Uo=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,jo=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Lo=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Js="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Ho=new RegExp(`^${Js}$`);Ae=class t extends k{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==f.string){let i=this._getOrReturnCtx(e);return p(i,{code:h.invalid_type,expected:f.string,received:i.parsedType}),v}let s=new V,n;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(n=this._getOrReturnCtx(e,n),p(n,{code:h.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),s.dirty());else if(i.kind==="max")e.data.length>i.value&&(n=this._getOrReturnCtx(e,n),p(n,{code:h.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),s.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,a=e.data.length<i.value;(o||a)&&(n=this._getOrReturnCtx(e,n),o?p(n,{code:h.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&p(n,{code:h.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),s.dirty())}else if(i.kind==="email")Ro.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"email",code:h.invalid_string,message:i.message}),s.dirty());else if(i.kind==="emoji")Nr||(Nr=new RegExp(Po,"u")),Nr.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"emoji",code:h.invalid_string,message:i.message}),s.dirty());else if(i.kind==="uuid")To.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"uuid",code:h.invalid_string,message:i.message}),s.dirty());else if(i.kind==="nanoid")$o.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"nanoid",code:h.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid")Ao.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"cuid",code:h.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid2")So.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"cuid2",code:h.invalid_string,message:i.message}),s.dirty());else if(i.kind==="ulid")Eo.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"ulid",code:h.invalid_string,message:i.message}),s.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),p(n,{validation:"url",code:h.invalid_string,message:i.message}),s.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"regex",code:h.invalid_string,message:i.message}),s.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(n=this._getOrReturnCtx(e,n),p(n,{code:h.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),s.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(n=this._getOrReturnCtx(e,n),p(n,{code:h.invalid_string,validation:{startsWith:i.value},message:i.message}),s.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(n=this._getOrReturnCtx(e,n),p(n,{code:h.invalid_string,validation:{endsWith:i.value},message:i.message}),s.dirty()):i.kind==="datetime"?Xs(i).test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:h.invalid_string,validation:"datetime",message:i.message}),s.dirty()):i.kind==="date"?Ho.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:h.invalid_string,validation:"date",message:i.message}),s.dirty()):i.kind==="time"?Mo(i).test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:h.invalid_string,validation:"time",message:i.message}),s.dirty()):i.kind==="duration"?Oo.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"duration",code:h.invalid_string,message:i.message}),s.dirty()):i.kind==="ip"?Vo(e.data,i.version)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"ip",code:h.invalid_string,message:i.message}),s.dirty()):i.kind==="jwt"?Wo(e.data,i.alg)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"jwt",code:h.invalid_string,message:i.message}),s.dirty()):i.kind==="cidr"?Fo(e.data,i.version)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"cidr",code:h.invalid_string,message:i.message}),s.dirty()):i.kind==="base64"?jo.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"base64",code:h.invalid_string,message:i.message}),s.dirty()):i.kind==="base64url"?Lo.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"base64url",code:h.invalid_string,message:i.message}),s.dirty()):E.assertNever(i);return{status:s.value,value:e.data}}_regex(e,r,s){return this.refinement(n=>e.test(n),{validation:r,code:h.invalid_string,...g.errToObj(s)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...g.errToObj(e)})}url(e){return this._addCheck({kind:"url",...g.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...g.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...g.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...g.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...g.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...g.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...g.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...g.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...g.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...g.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...g.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...g.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...g.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...g.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...g.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...g.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...g.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...g.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...g.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...g.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...g.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...g.errToObj(r)})}nonempty(e){return this.min(1,g.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Ae.create=t=>new Ae({checks:[],typeName:_.ZodString,coerce:t?.coerce??!1,...x(t)});Ie=class t extends k{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==f.number){let i=this._getOrReturnCtx(e);return p(i,{code:h.invalid_type,expected:f.number,received:i.parsedType}),v}let s,n=new V;for(let i of this._def.checks)i.kind==="int"?E.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{code:h.invalid_type,expected:"integer",received:"float",message:i.message}),n.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(s=this._getOrReturnCtx(e,s),p(s,{code:h.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(s=this._getOrReturnCtx(e,s),p(s,{code:h.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty()):i.kind==="multipleOf"?Ko(e.data,i.value)!==0&&(s=this._getOrReturnCtx(e,s),p(s,{code:h.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{code:h.not_finite,message:i.message}),n.dirty()):E.assertNever(i);return{status:n.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,g.toString(r))}gt(e,r){return this.setLimit("min",e,!1,g.toString(r))}lte(e,r){return this.setLimit("max",e,!0,g.toString(r))}lt(e,r){return this.setLimit("max",e,!1,g.toString(r))}setLimit(e,r,s,n){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:s,message:g.toString(n)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:g.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:g.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:g.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:g.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:g.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:g.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:g.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:g.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:g.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&E.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(r===null||s.value>r)&&(r=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value)}return Number.isFinite(r)&&Number.isFinite(e)}};Ie.create=t=>new Ie({checks:[],typeName:_.ZodNumber,coerce:t?.coerce||!1,...x(t)});Ne=class t extends k{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==f.bigint)return this._getInvalidInput(e);let s,n=new V;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(s=this._getOrReturnCtx(e,s),p(s,{code:h.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(s=this._getOrReturnCtx(e,s),p(s,{code:h.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(s=this._getOrReturnCtx(e,s),p(s,{code:h.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):E.assertNever(i);return{status:n.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return p(r,{code:h.invalid_type,expected:f.bigint,received:r.parsedType}),v}gte(e,r){return this.setLimit("min",e,!0,g.toString(r))}gt(e,r){return this.setLimit("min",e,!1,g.toString(r))}lte(e,r){return this.setLimit("max",e,!0,g.toString(r))}lt(e,r){return this.setLimit("max",e,!1,g.toString(r))}setLimit(e,r,s,n){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:s,message:g.toString(n)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:g.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:g.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:g.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:g.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:g.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Ne.create=t=>new Ne({checks:[],typeName:_.ZodBigInt,coerce:t?.coerce??!1,...x(t)});De=class extends k{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==f.boolean){let s=this._getOrReturnCtx(e);return p(s,{code:h.invalid_type,expected:f.boolean,received:s.parsedType}),v}return F(e.data)}};De.create=t=>new De({typeName:_.ZodBoolean,coerce:t?.coerce||!1,...x(t)});Ue=class t extends k{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==f.date){let i=this._getOrReturnCtx(e);return p(i,{code:h.invalid_type,expected:f.date,received:i.parsedType}),v}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return p(i,{code:h.invalid_date}),v}let s=new V,n;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(n=this._getOrReturnCtx(e,n),p(n,{code:h.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),s.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(n=this._getOrReturnCtx(e,n),p(n,{code:h.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),s.dirty()):E.assertNever(i);return{status:s.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:g.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:g.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};Ue.create=t=>new Ue({checks:[],coerce:t?.coerce||!1,typeName:_.ZodDate,...x(t)});st=class extends k{_parse(e){if(this._getType(e)!==f.symbol){let s=this._getOrReturnCtx(e);return p(s,{code:h.invalid_type,expected:f.symbol,received:s.parsedType}),v}return F(e.data)}};st.create=t=>new st({typeName:_.ZodSymbol,...x(t)});je=class extends k{_parse(e){if(this._getType(e)!==f.undefined){let s=this._getOrReturnCtx(e);return p(s,{code:h.invalid_type,expected:f.undefined,received:s.parsedType}),v}return F(e.data)}};je.create=t=>new je({typeName:_.ZodUndefined,...x(t)});Le=class extends k{_parse(e){if(this._getType(e)!==f.null){let s=this._getOrReturnCtx(e);return p(s,{code:h.invalid_type,expected:f.null,received:s.parsedType}),v}return F(e.data)}};Le.create=t=>new Le({typeName:_.ZodNull,...x(t)});Se=class extends k{constructor(){super(...arguments),this._any=!0}_parse(e){return F(e.data)}};Se.create=t=>new Se({typeName:_.ZodAny,...x(t)});me=class extends k{constructor(){super(...arguments),this._unknown=!0}_parse(e){return F(e.data)}};me.create=t=>new me({typeName:_.ZodUnknown,...x(t)});te=class extends k{_parse(e){let r=this._getOrReturnCtx(e);return p(r,{code:h.invalid_type,expected:f.never,received:r.parsedType}),v}};te.create=t=>new te({typeName:_.ZodNever,...x(t)});nt=class extends k{_parse(e){if(this._getType(e)!==f.undefined){let s=this._getOrReturnCtx(e);return p(s,{code:h.invalid_type,expected:f.void,received:s.parsedType}),v}return F(e.data)}};nt.create=t=>new nt({typeName:_.ZodVoid,...x(t)});ge=class t extends k{_parse(e){let{ctx:r,status:s}=this._processInputParams(e),n=this._def;if(r.parsedType!==f.array)return p(r,{code:h.invalid_type,expected:f.array,received:r.parsedType}),v;if(n.exactLength!==null){let o=r.data.length>n.exactLength.value,a=r.data.length<n.exactLength.value;(o||a)&&(p(r,{code:o?h.too_big:h.too_small,minimum:a?n.exactLength.value:void 0,maximum:o?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),s.dirty())}if(n.minLength!==null&&r.data.length<n.minLength.value&&(p(r,{code:h.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),s.dirty()),n.maxLength!==null&&r.data.length>n.maxLength.value&&(p(r,{code:h.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),s.dirty()),r.common.async)return Promise.all([...r.data].map((o,a)=>n.type._parseAsync(new X(r,o,r.path,a)))).then(o=>V.mergeArray(s,o));let i=[...r.data].map((o,a)=>n.type._parseSync(new X(r,o,r.path,a)));return V.mergeArray(s,i)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:g.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:g.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:g.toString(r)}})}nonempty(e){return this.min(1,e)}};ge.create=(t,e)=>new ge({type:t,minLength:null,maxLength:null,exactLength:null,typeName:_.ZodArray,...x(e)});B=class t extends k{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=E.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==f.object){let l=this._getOrReturnCtx(e);return p(l,{code:h.invalid_type,expected:f.object,received:l.parsedType}),v}let{status:s,ctx:n}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof te&&this._def.unknownKeys==="strip"))for(let l in n.data)o.includes(l)||a.push(l);let c=[];for(let l of o){let u=i[l],d=n.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new X(n,d,n.path,l)),alwaysSet:l in n.data})}if(this._def.catchall instanceof te){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of a)c.push({key:{status:"valid",value:u},value:{status:"valid",value:n.data[u]}});else if(l==="strict")a.length>0&&(p(n,{code:h.unrecognized_keys,keys:a}),s.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let u of a){let d=n.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new X(n,d,n.path,u)),alwaysSet:u in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let d=await u.key,m=await u.value;l.push({key:d,value:m,alwaysSet:u.alwaysSet})}return l}).then(l=>V.mergeObjectSync(s,l)):V.mergeObjectSync(s,c)}get shape(){return this._def.shape()}strict(e){return g.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,s)=>{let n=this._def.errorMap?.(r,s).message??s.defaultError;return r.code==="unrecognized_keys"?{message:g.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:_.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let s of E.objectKeys(e))e[s]&&this.shape[s]&&(r[s]=this.shape[s]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let s of E.objectKeys(this.shape))e[s]||(r[s]=this.shape[s]);return new t({...this._def,shape:()=>r})}deepPartial(){return rt(this)}partial(e){let r={};for(let s of E.objectKeys(this.shape)){let n=this.shape[s];e&&!e[s]?r[s]=n:r[s]=n.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let s of E.objectKeys(this.shape))if(e&&!e[s])r[s]=this.shape[s];else{let i=this.shape[s];for(;i instanceof Y;)i=i._def.innerType;r[s]=i}return new t({...this._def,shape:()=>r})}keyof(){return Qs(E.objectKeys(this.shape))}};B.create=(t,e)=>new B({shape:()=>t,unknownKeys:"strip",catchall:te.create(),typeName:_.ZodObject,...x(e)});B.strictCreate=(t,e)=>new B({shape:()=>t,unknownKeys:"strict",catchall:te.create(),typeName:_.ZodObject,...x(e)});B.lazycreate=(t,e)=>new B({shape:t,unknownKeys:"strip",catchall:te.create(),typeName:_.ZodObject,...x(e)});He=class extends k{_parse(e){let{ctx:r}=this._processInputParams(e),s=this._def.options;function n(i){for(let a of i)if(a.result.status==="valid")return a.result;for(let a of i)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(a=>new q(a.ctx.common.issues));return p(r,{code:h.invalid_union,unionErrors:o}),v}if(r.common.async)return Promise.all(s.map(async i=>{let o={...r,common:{...r.common,issues:[]},parent:null};return{result:await i._parseAsync({data:r.data,path:r.path,parent:o}),ctx:o}})).then(n);{let i,o=[];for(let c of s){let l={...r,common:{...r.common,issues:[]},parent:null},u=c._parseSync({data:r.data,path:r.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!i&&(i={result:u,ctx:l}),l.common.issues.length&&o.push(l.common.issues)}if(i)return r.common.issues.push(...i.ctx.common.issues),i.result;let a=o.map(c=>new q(c));return p(r,{code:h.invalid_union,unionErrors:a}),v}}get options(){return this._def.options}};He.create=(t,e)=>new He({options:t,typeName:_.ZodUnion,...x(e)});fe=t=>t instanceof Ve?fe(t.schema):t instanceof Q?fe(t.innerType()):t instanceof We?[t.value]:t instanceof Fe?t.options:t instanceof Ke?E.objectValues(t.enum):t instanceof qe?fe(t._def.innerType):t instanceof je?[void 0]:t instanceof Le?[null]:t instanceof Y?[void 0,...fe(t.unwrap())]:t instanceof le?[null,...fe(t.unwrap())]:t instanceof bt||t instanceof Ge?fe(t.unwrap()):t instanceof Be?fe(t._def.innerType):[],Mt=class t extends k{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==f.object)return p(r,{code:h.invalid_type,expected:f.object,received:r.parsedType}),v;let s=this.discriminator,n=r.data[s],i=this.optionsMap.get(n);return i?r.common.async?i._parseAsync({data:r.data,path:r.path,parent:r}):i._parseSync({data:r.data,path:r.path,parent:r}):(p(r,{code:h.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),v)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,s){let n=new Map;for(let i of r){let o=fe(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of o){if(n.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);n.set(a,i)}}return new t({typeName:_.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:n,...x(s)})}};Me=class extends k{_parse(e){let{status:r,ctx:s}=this._processInputParams(e),n=(i,o)=>{if(Lt(i)||Lt(o))return v;let a=Dr(i.value,o.value);return a.valid?((Ht(i)||Ht(o))&&r.dirty(),{status:r.value,value:a.data}):(p(s,{code:h.invalid_intersection_types}),v)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([i,o])=>n(i,o)):n(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}};Me.create=(t,e,r)=>new Me({left:t,right:e,typeName:_.ZodIntersection,...x(r)});ce=class t extends k{_parse(e){let{status:r,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.array)return p(s,{code:h.invalid_type,expected:f.array,received:s.parsedType}),v;if(s.data.length<this._def.items.length)return p(s,{code:h.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),v;!this._def.rest&&s.data.length>this._def.items.length&&(p(s,{code:h.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let i=[...s.data].map((o,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new X(s,o,s.path,a)):null}).filter(o=>!!o);return s.common.async?Promise.all(i).then(o=>V.mergeArray(r,o)):V.mergeArray(r,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};ce.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ce({items:t,typeName:_.ZodTuple,rest:null,...x(e)})};Vt=class t extends k{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.object)return p(s,{code:h.invalid_type,expected:f.object,received:s.parsedType}),v;let n=[],i=this._def.keyType,o=this._def.valueType;for(let a in s.data)n.push({key:i._parse(new X(s,a,s.path,a)),value:o._parse(new X(s,s.data[a],s.path,a)),alwaysSet:a in s.data});return s.common.async?V.mergeObjectAsync(r,n):V.mergeObjectSync(r,n)}get element(){return this._def.valueType}static create(e,r,s){return r instanceof k?new t({keyType:e,valueType:r,typeName:_.ZodRecord,...x(s)}):new t({keyType:Ae.create(),valueType:e,typeName:_.ZodRecord,...x(r)})}},it=class extends k{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.map)return p(s,{code:h.invalid_type,expected:f.map,received:s.parsedType}),v;let n=this._def.keyType,i=this._def.valueType,o=[...s.data.entries()].map(([a,c],l)=>({key:n._parse(new X(s,a,s.path,[l,"key"])),value:i._parse(new X(s,c,s.path,[l,"value"]))}));if(s.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of o){let l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return v;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(l.value,u.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of o){let l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return v;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(l.value,u.value)}return{status:r.value,value:a}}}};it.create=(t,e,r)=>new it({valueType:e,keyType:t,typeName:_.ZodMap,...x(r)});ot=class t extends k{_parse(e){let{status:r,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.set)return p(s,{code:h.invalid_type,expected:f.set,received:s.parsedType}),v;let n=this._def;n.minSize!==null&&s.data.size<n.minSize.value&&(p(s,{code:h.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),r.dirty()),n.maxSize!==null&&s.data.size>n.maxSize.value&&(p(s,{code:h.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),r.dirty());let i=this._def.valueType;function o(c){let l=new Set;for(let u of c){if(u.status==="aborted")return v;u.status==="dirty"&&r.dirty(),l.add(u.value)}return{status:r.value,value:l}}let a=[...s.data.values()].map((c,l)=>i._parse(new X(s,c,s.path,l)));return s.common.async?Promise.all(a).then(c=>o(c)):o(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:g.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:g.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};ot.create=(t,e)=>new ot({valueType:t,minSize:null,maxSize:null,typeName:_.ZodSet,...x(e)});Wt=class t extends k{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==f.function)return p(r,{code:h.invalid_type,expected:f.function,received:r.parsedType}),v;function s(a,c){return _t({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,et(),pe].filter(l=>!!l),issueData:{code:h.invalid_arguments,argumentsError:c}})}function n(a,c){return _t({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,et(),pe].filter(l=>!!l),issueData:{code:h.invalid_return_type,returnTypeError:c}})}let i={errorMap:r.common.contextualErrorMap},o=r.data;if(this._def.returns instanceof Ee){let a=this;return F(async function(...c){let l=new q([]),u=await a._def.args.parseAsync(c,i).catch(w=>{throw l.addIssue(s(c,w)),l}),d=await Reflect.apply(o,this,u);return await a._def.returns._def.type.parseAsync(d,i).catch(w=>{throw l.addIssue(n(d,w)),l})})}else{let a=this;return F(function(...c){let l=a._def.args.safeParse(c,i);if(!l.success)throw new q([s(c,l.error)]);let u=Reflect.apply(o,this,l.data),d=a._def.returns.safeParse(u,i);if(!d.success)throw new q([n(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:ce.create(e).rest(me.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,s){return new t({args:e||ce.create([]).rest(me.create()),returns:r||me.create(),typeName:_.ZodFunction,...x(s)})}},Ve=class extends k{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Ve.create=(t,e)=>new Ve({getter:t,typeName:_.ZodLazy,...x(e)});We=class extends k{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return p(r,{received:r.data,code:h.invalid_literal,expected:this._def.value}),v}return{status:"valid",value:e.data}}get value(){return this._def.value}};We.create=(t,e)=>new We({value:t,typeName:_.ZodLiteral,...x(e)});Fe=class t extends k{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),s=this._def.values;return p(r,{expected:E.joinValues(s),received:r.parsedType,code:h.invalid_type}),v}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),s=this._def.values;return p(r,{received:r.data,code:h.invalid_enum_value,options:s}),v}return F(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(s=>!e.includes(s)),{...this._def,...r})}};Fe.create=Qs;Ke=class extends k{_parse(e){let r=E.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==f.string&&s.parsedType!==f.number){let n=E.objectValues(r);return p(s,{expected:E.joinValues(n),received:s.parsedType,code:h.invalid_type}),v}if(this._cache||(this._cache=new Set(E.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let n=E.objectValues(r);return p(s,{received:s.data,code:h.invalid_enum_value,options:n}),v}return F(e.data)}get enum(){return this._def.values}};Ke.create=(t,e)=>new Ke({values:t,typeName:_.ZodNativeEnum,...x(e)});Ee=class extends k{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==f.promise&&r.common.async===!1)return p(r,{code:h.invalid_type,expected:f.promise,received:r.parsedType}),v;let s=r.parsedType===f.promise?r.data:Promise.resolve(r.data);return F(s.then(n=>this._def.type.parseAsync(n,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Ee.create=(t,e)=>new Ee({type:t,typeName:_.ZodPromise,...x(e)});Q=class extends k{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===_.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:s}=this._processInputParams(e),n=this._def.effect||null,i={addIssue:o=>{p(s,o),o.fatal?r.abort():r.dirty()},get path(){return s.path}};if(i.addIssue=i.addIssue.bind(i),n.type==="preprocess"){let o=n.transform(s.data,i);if(s.common.async)return Promise.resolve(o).then(async a=>{if(r.value==="aborted")return v;let c=await this._def.schema._parseAsync({data:a,path:s.path,parent:s});return c.status==="aborted"?v:c.status==="dirty"?Pe(c.value):r.value==="dirty"?Pe(c.value):c});{if(r.value==="aborted")return v;let a=this._def.schema._parseSync({data:o,path:s.path,parent:s});return a.status==="aborted"?v:a.status==="dirty"?Pe(a.value):r.value==="dirty"?Pe(a.value):a}}if(n.type==="refinement"){let o=a=>{let c=n.refinement(a,i);if(s.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(s.common.async===!1){let a=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return a.status==="aborted"?v:(a.status==="dirty"&&r.dirty(),o(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(a=>a.status==="aborted"?v:(a.status==="dirty"&&r.dirty(),o(a.value).then(()=>({status:r.value,value:a.value}))))}if(n.type==="transform")if(s.common.async===!1){let o=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!ke(o))return v;let a=n.transform(o.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(o=>ke(o)?Promise.resolve(n.transform(o.value,i)).then(a=>({status:r.value,value:a})):v);E.assertNever(n)}};Q.create=(t,e,r)=>new Q({schema:t,typeName:_.ZodEffects,effect:e,...x(r)});Q.createWithPreprocess=(t,e,r)=>new Q({schema:e,effect:{type:"preprocess",transform:t},typeName:_.ZodEffects,...x(r)});Y=class extends k{_parse(e){return this._getType(e)===f.undefined?F(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Y.create=(t,e)=>new Y({innerType:t,typeName:_.ZodOptional,...x(e)});le=class extends k{_parse(e){return this._getType(e)===f.null?F(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};le.create=(t,e)=>new le({innerType:t,typeName:_.ZodNullable,...x(e)});qe=class extends k{_parse(e){let{ctx:r}=this._processInputParams(e),s=r.data;return r.parsedType===f.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};qe.create=(t,e)=>new qe({innerType:t,typeName:_.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...x(e)});Be=class extends k{_parse(e){let{ctx:r}=this._processInputParams(e),s={...r,common:{...r.common,issues:[]}},n=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return tt(n)?n.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new q(s.common.issues)},input:s.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new q(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};Be.create=(t,e)=>new Be({innerType:t,typeName:_.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...x(e)});at=class extends k{_parse(e){if(this._getType(e)!==f.nan){let s=this._getOrReturnCtx(e);return p(s,{code:h.invalid_type,expected:f.nan,received:s.parsedType}),v}return{status:"valid",value:e.data}}};at.create=t=>new at({typeName:_.ZodNaN,...x(t)});qo=Symbol("zod_brand"),bt=class extends k{_parse(e){let{ctx:r}=this._processInputParams(e),s=r.data;return this._def.type._parse({data:s,path:r.path,parent:r})}unwrap(){return this._def.type}},wt=class t extends k{_parse(e){let{status:r,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return i.status==="aborted"?v:i.status==="dirty"?(r.dirty(),Pe(i.value)):this._def.out._parseAsync({data:i.value,path:s.path,parent:s})})();{let n=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return n.status==="aborted"?v:n.status==="dirty"?(r.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:s.path,parent:s})}}static create(e,r){return new t({in:e,out:r,typeName:_.ZodPipeline})}},Ge=class extends k{_parse(e){let r=this._def.innerType._parse(e),s=n=>(ke(n)&&(n.value=Object.freeze(n.value)),n);return tt(r)?r.then(n=>s(n)):s(r)}unwrap(){return this._def.innerType}};Ge.create=(t,e)=>new Ge({innerType:t,typeName:_.ZodReadonly,...x(e)});Bo={object:B.lazycreate};(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(_||(_={}));Go=(t,e={message:`Input not instance of ${t.name}`})=>en(r=>r instanceof t,e),tn=Ae.create,rn=Ie.create,zo=at.create,Zo=Ne.create,sn=De.create,Jo=Ue.create,Yo=st.create,Xo=je.create,Qo=Le.create,ea=Se.create,ta=me.create,ra=te.create,sa=nt.create,na=ge.create,ia=B.create,oa=B.strictCreate,aa=He.create,ca=Mt.create,la=Me.create,ua=ce.create,da=Vt.create,ha=it.create,pa=ot.create,fa=Wt.create,ma=Ve.create,ga=We.create,ya=Fe.create,va=Ke.create,_a=Ee.create,ba=Q.create,wa=Y.create,xa=le.create,ka=Q.createWithPreprocess,Aa=wt.create,Sa=()=>tn().optional(),Ea=()=>rn().optional(),Ta=()=>sn().optional(),$a={string:(t=>Ae.create({...t,coerce:!0})),number:(t=>Ie.create({...t,coerce:!0})),boolean:(t=>De.create({...t,coerce:!0})),bigint:(t=>Ne.create({...t,coerce:!0})),date:(t=>Ue.create({...t,coerce:!0}))},Ca=v});var G={};kt(G,{BRAND:()=>qo,DIRTY:()=>Pe,EMPTY_PATH:()=>ko,INVALID:()=>v,NEVER:()=>Ca,OK:()=>F,ParseStatus:()=>V,Schema:()=>k,ZodAny:()=>Se,ZodArray:()=>ge,ZodBigInt:()=>Ne,ZodBoolean:()=>De,ZodBranded:()=>bt,ZodCatch:()=>Be,ZodDate:()=>Ue,ZodDefault:()=>qe,ZodDiscriminatedUnion:()=>Mt,ZodEffects:()=>Q,ZodEnum:()=>Fe,ZodError:()=>q,ZodFirstPartyTypeKind:()=>_,ZodFunction:()=>Wt,ZodIntersection:()=>Me,ZodIssueCode:()=>h,ZodLazy:()=>Ve,ZodLiteral:()=>We,ZodMap:()=>it,ZodNaN:()=>at,ZodNativeEnum:()=>Ke,ZodNever:()=>te,ZodNull:()=>Le,ZodNullable:()=>le,ZodNumber:()=>Ie,ZodObject:()=>B,ZodOptional:()=>Y,ZodParsedType:()=>f,ZodPipeline:()=>wt,ZodPromise:()=>Ee,ZodReadonly:()=>Ge,ZodRecord:()=>Vt,ZodSchema:()=>k,ZodSet:()=>ot,ZodString:()=>Ae,ZodSymbol:()=>st,ZodTransformer:()=>Q,ZodTuple:()=>ce,ZodType:()=>k,ZodUndefined:()=>je,ZodUnion:()=>He,ZodUnknown:()=>me,ZodVoid:()=>nt,addIssueToContext:()=>p,any:()=>ea,array:()=>na,bigint:()=>Zo,boolean:()=>sn,coerce:()=>$a,custom:()=>en,date:()=>Jo,datetimeRegex:()=>Xs,defaultErrorMap:()=>pe,discriminatedUnion:()=>ca,effect:()=>ba,enum:()=>ya,function:()=>fa,getErrorMap:()=>et,getParsedType:()=>ae,instanceof:()=>Go,intersection:()=>la,isAborted:()=>Lt,isAsync:()=>tt,isDirty:()=>Ht,isValid:()=>ke,late:()=>Bo,lazy:()=>ma,literal:()=>ga,makeIssue:()=>_t,map:()=>ha,nan:()=>zo,nativeEnum:()=>va,never:()=>ra,null:()=>Qo,nullable:()=>xa,number:()=>rn,object:()=>ia,objectUtil:()=>Rr,oboolean:()=>Ta,onumber:()=>Ea,optional:()=>wa,ostring:()=>Sa,pipeline:()=>Aa,preprocess:()=>ka,promise:()=>_a,quotelessJson:()=>bo,record:()=>da,set:()=>pa,setErrorMap:()=>xo,strictObject:()=>oa,string:()=>tn,symbol:()=>Yo,transformer:()=>ba,tuple:()=>ua,undefined:()=>Xo,union:()=>aa,unknown:()=>ta,util:()=>E,void:()=>sa});var Ur=W(()=>{jt();Ir();Bs();vt();nn();Ut()});var on=W(()=>{Ur();Ur()});function an(t){switch(t.type){case"string":{let e=G.string();return t.pattern&&(e=e.regex(new RegExp(t.pattern))),t.minLength&&(e=e.min(t.minLength)),t.maxLength&&(e=e.max(t.maxLength)),t.enum?G.enum(t.enum):e}case"integer":case"number":{let e=t.type==="integer"?G.coerce.number().int():G.coerce.number();return t.minimum!==void 0&&(e=e.min(t.minimum)),t.maximum!==void 0&&(e=e.max(t.maximum)),e}case"boolean":return G.preprocess(e=>e==="true"||e===!0?!0:e==="false"||e===!1?!1:e,G.boolean());case"array":return G.array(t.items?an(t.items):G.any());case"object":return G.record(G.any());default:return G.any()}}function jr(t,e){let r=an(e),s=r.safeParse(t);if(s.success)return s.data;if(e.type==="object"||e.type==="array")try{let n=JSON.parse(t);return r.parse(n)}catch{}return t}var cn=W(()=>{"use strict";on()});import*as Te from"node:fs";import*as re from"node:path";function Ra(t){let e=re.extname(t).toLowerCase();return!!(Oa.has(e)||e==="")}function ln(t){let e=re.resolve(t),r=Te.readFileSync(e),s=re.relative(process.cwd(),e);if(Ra(t))return{path:s,contents:r.toString("utf-8")};let n=re.extname(t).toLowerCase().slice(1)||"bin",o={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",ico:"image/x-icon",pdf:"application/pdf",zip:"application/zip",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf"}[n]||"application/octet-stream",a=r.toString("base64");return{path:s,contents:`data:${o};base64,${a}`}}function un(t){let e=[];for(let r of t){let s=re.resolve(r);if(Te.statSync(s).isDirectory()){let i=dn(s);for(let o of i)e.push(ln(o))}else e.push(ln(s))}return e}function dn(t){let e=[],r=Te.readdirSync(t,{withFileTypes:!0});for(let s of r){let n=re.join(t,s.name);s.isDirectory()?e.push(...dn(n)):e.push(n)}return e}function hn(t){if(t.startsWith("-"))return!1;try{let e=re.resolve(t);return Te.existsSync(e)}catch{return!1}}var Oa,pn=W(()=>{"use strict";Oa=new Set([".txt",".md",".html",".htm",".css",".js",".ts",".jsx",".tsx",".json",".xml",".yaml",".yml",".toml",".ini",".cfg",".conf",".sh",".bash",".zsh",".fish",".bat",".ps1",".py",".rb",".go",".rs",".java",".c",".cpp",".h",".hpp",".cs",".php",".swift",".kt",".scala",".r",".sql",".graphql",".proto",".env",".gitignore",".dockerignore",".editorconfig",".prettierrc",".eslintrc",".svg",".csv",".tsv",".log"])});var gn={};kt(gn,{execute:()=>Lr});import*as fn from"node:fs";import*as mn from"node:path";function Pa(t){try{let e=mn.join(process.cwd(),t),r=fn.readFileSync(e,"utf-8"),s=JSON.parse(r);if(s&&typeof s=="object"&&!Array.isArray(s))return s}catch{}return{}}function Ia(t){return t.args?t.args:[...t.params.path.filter(e=>e.required),...t.params.query.filter(e=>e.required),...t.params.body.filter(e=>e.required)].map(e=>e.name)}async function Lr(t,e,r,s){let n=await xe(t),i=n.actions.find(y=>y.slug===e),o=n.actions.some(y=>y.slug.startsWith(e+"."));if(!i&&o)return Or(t,e);if(!i){console.error(`\x1B[31mAction "${e}" not found.\x1B[0m`);let y=n.actions.filter(S=>S.slug.includes(e)).map(S=>S.slug);if(y.length>0){console.log(`
35
+ Did you mean:`);for(let S of y)console.log(` \x1B[36m${S}\x1B[0m`)}process.exit(1)}let a=await $r(t,e),c=[...a.params.path,...a.params.query,...a.params.body],l=new Map(c.map(y=>[y.name,y])),u=Ia(a),d=new Pt().exitOverride().name(e).description(a.description).allowUnknownOption(!1).configureOutput({writeOut:y=>process.stdout.write(y),writeErr:y=>process.stderr.write(y)});if(a.payment.mode!=="free"){let y=a.payment.description?`${a.payment.mode} \u2014 ${a.payment.description}`:a.payment.mode;d.addHelpText("after",`
36
36
  \x1B[33mPayment: ${y}\x1B[0m`)}d.addHelpText("after",`
37
37
  \x1B[90m${a.method} ${a.endpoint}\x1B[0m`),a.example&&d.addHelpText("after",`
38
38
  Example:
39
39
  Input: ${JSON.stringify(a.example.input)}
40
- Output: ${JSON.stringify(a.example.output)}`);let m=u.map(y=>l.get(y)?.required?`<${y}>`:`[${y}]`);m.push("[options]"),d.usage(m.join(" ")),d.allowExcessArguments(!0);for(let y of c)y.type?.type==="boolean"?d.option(`--${y.name}`,y.description):d.option(`--${y.name} <value>`,y.description);a.params.files&&(d.option("--file <paths...>","File(s) to upload"),d.option("--files <paths...>","File(s) to upload"));let x={},R=[];d.action(()=>{let y=d.opts(),A=d.args,$e={};for(let[de,ve]of Object.entries(y)){if(de==="file"||de==="files"){R.push(...ve);continue}let lt=l.get(de);lt&&typeof ve=="string"?$e[de]=jr(ve,lt.type):$e[de]=ve}u.forEach((de,ve)=>{if(A[ve]!==void 0&&$e[de]===void 0){let lt=l.get(de);$e[de]=lt?jr(String(A[ve]),lt.type):A[ve]}});let Wr=A.slice(u.length);Wr.length>0&&a.params.files&&R.push(...Wr.filter(hn)),x=$e});try{await d.parseAsync(r,{from:"user"})}catch(y){throw y?.exitCode!==void 0&&process.exit(y.exitCode),y}if(r.length===0&&c.some(A=>A.required)&&d.help(),n.configFile){let y=Pa(n.configFile);for(let[A,$e]of Object.entries(y))x[A]===void 0&&(x[A]=$e)}let Te=s(),le=Te.getIdentity();le||(console.error("\x1B[31mNot registered. Run: botparty init\x1B[0m"),process.exit(1));let re=x,se=le.namespace,I=n.baseUrl.replace("{namespace}",se),L=a.endpoint;for(let y of a.params.path){let A=re[y.name];A!==void 0?(L=L.replace(`{${y.name}}`,String(A)),delete re[y.name]):y.required&&(console.error(`\x1B[31mMissing required path parameter: --${y.name}\x1B[0m`),process.exit(1))}let U=new URLSearchParams;for(let y of a.params.query){let A=re[y.name];A!==void 0?(U.set(y.name,String(A)),delete re[y.name]):y.required&&(console.error(`\x1B[31mMissing required query parameter: --${y.name}\x1B[0m`),process.exit(1))}let ye=t.includes("://")?t:`https://${t}`,ue=U.toString(),ct=`${ye.replace(/\/$/,"")}${I}${L}${ue?"?"+ue:""}`,X={method:a.method};if(["POST","PUT","PATCH"].includes(a.method)){let y={};for(let A of a.params.body)re[A.name]!==void 0?y[A.name]=re[A.name]:A.required&&(console.error(`\x1B[31mMissing required body parameter: --${A.name}\x1B[0m`),process.exit(1));if(a.params.files&&R.length>0){let A=un(R);y[a.params.files.bodyKey]=A}X.body=JSON.stringify(y),X.headers={"Content-Type":"application/json"}}console.log(`\x1B[90m${a.method} ${ct}\x1B[0m`);let Ft=await Te.generateToken({role:"admin"}),xt=new Headers(X.headers);xt.set("Authorization",`Bearer ${Ft}`),X.headers=xt;let ne=await fetch(ct,X),_n=ne.headers.get("content-type")||"";if(!ne.ok){let y=await ne.text();try{let A=JSON.parse(y);A?.error?.code&&A?.error?.message?(console.error(`\x1B[31m${A.error.code}\x1B[0m \x1B[90m(${ne.status})\x1B[0m`),console.error(`
41
- ${A.error.message}`),A.error.details&&console.error(`
42
- \x1B[90m${JSON.stringify(A.error.details,null,2)}\x1B[0m`)):(console.error(`\x1B[31m${ne.status} ${ne.statusText}\x1B[0m`),console.error(JSON.stringify(A,null,2)))}catch{console.error(`\x1B[31m${ne.status} ${ne.statusText}\x1B[0m`),y&&console.error(y)}process.exit(1)}if(_n.includes("application/json")){let y=await ne.json();console.log(JSON.stringify(y,null,2))}else{let y=await ne.text();console.log(y)}}var Hr=V(()=>{"use strict";Ar();Qe();Dt();cn();pn()});import{readFileSync as hs,writeFileSync as nr,mkdirSync as gi,existsSync as Et,unlinkSync as ir,statSync as yi,renameSync as ps}from"node:fs";import{join as be}from"node:path";import{homedir as vi}from"node:os";import{randomBytes as fs}from"node:crypto";var Xr=new TextEncoder,Fr=new TextDecoder,cc=2**32;function Tn(...t){let e=t.reduce((n,{length:i})=>n+i,0),r=new Uint8Array(e),s=0;for(let n of t)r.set(n,s),s+=n.length;return r}function qt(t){let e=new Uint8Array(t.length);for(let r=0;r<t.length;r++){let s=t.charCodeAt(r);if(s>127)throw new TypeError("non-ASCII string encountered in encode()");e[r]=s}return e}function Qr(t){if(Uint8Array.prototype.toBase64)return t.toBase64();let e=32768,r=[];for(let s=0;s<t.length;s+=e)r.push(String.fromCharCode.apply(null,t.subarray(s,s+e)));return btoa(r.join(""))}function es(t){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(t);let e=atob(t),r=new Uint8Array(e.length);for(let s=0;s<e.length;s++)r[s]=e.charCodeAt(s);return r}function $n(t){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof t=="string"?t:Fr.decode(t),{alphabet:"base64url"});let e=t;e instanceof Uint8Array&&(e=Fr.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/");try{return es(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}function Bt(t){let e=t;return typeof e=="string"&&(e=Xr.encode(e)),Uint8Array.prototype.toBase64?e.toBase64({alphabet:"base64url",omitPadding:!0}):Qr(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}var _e=(t,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`),ze=(t,e)=>t.name===e;function Cn(t){return parseInt(t.name.slice(4),10)}function Gt(t,e){if(Cn(t.hash)!==e)throw _e(`SHA-${e}`,"algorithm.hash")}function On(t){switch(t){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Rn(t,e){if(e&&!t.usages.includes(e))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${e}.`)}function Pn(t,e,r){switch(e){case"HS256":case"HS384":case"HS512":{if(!ze(t.algorithm,"HMAC"))throw _e("HMAC");Gt(t.algorithm,parseInt(e.slice(2),10));break}case"RS256":case"RS384":case"RS512":{if(!ze(t.algorithm,"RSASSA-PKCS1-v1_5"))throw _e("RSASSA-PKCS1-v1_5");Gt(t.algorithm,parseInt(e.slice(2),10));break}case"PS256":case"PS384":case"PS512":{if(!ze(t.algorithm,"RSA-PSS"))throw _e("RSA-PSS");Gt(t.algorithm,parseInt(e.slice(2),10));break}case"Ed25519":case"EdDSA":{if(!ze(t.algorithm,"Ed25519"))throw _e("Ed25519");break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{if(!ze(t.algorithm,e))throw _e(e);break}case"ES256":case"ES384":case"ES512":{if(!ze(t.algorithm,"ECDSA"))throw _e("ECDSA");let s=On(e);if(t.algorithm.namedCurve!==s)throw _e(s,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Rn(t,r)}function ts(t,e,...r){if(r=r.filter(Boolean),r.length>2){let s=r.pop();t+=`one of type ${r.join(", ")}, or ${s}.`}else r.length===2?t+=`one of type ${r[0]} or ${r[1]}.`:t+=`of type ${r[0]}.`;return e==null?t+=` Received ${e}`:typeof e=="function"&&e.name?t+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&e.constructor?.name&&(t+=` Received an instance of ${e.constructor.name}`),t}var rs=(t,...e)=>ts("Key must be ",t,...e),ss=(t,e,...r)=>ts(`Key for the ${t} algorithm must be `,e,...r),Qt=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(t,e){super(t,e),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},G=class extends Qt{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},dt=class extends Qt{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},In=class extends Qt{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"},er=t=>{if(t?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return t instanceof CryptoKey}catch{return!1}},tr=t=>t?.[Symbol.toStringTag]==="KeyObject",ns=t=>er(t)||tr(t),lc=Symbol();function Kr(t,e){if(t)throw new TypeError(`${e} can only be called once`)}var Nn=t=>typeof t=="object"&&t!==null;function is(t){if(!Nn(t)||Object.prototype.toString.call(t)!=="[object Object]")return!1;if(Object.getPrototypeOf(t)===null)return!0;let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function Dn(...t){let e=t.filter(Boolean);if(e.length===0||e.length===1)return!0;let r;for(let s of e){let n=Object.keys(s);if(!r||r.size===0){r=new Set(n);continue}for(let i of n){if(r.has(i))return!1;r.add(i)}}return!0}var rr=t=>is(t)&&typeof t.kty=="string",Un=t=>t.kty!=="oct"&&(t.kty==="AKP"&&typeof t.priv=="string"||typeof t.d=="string"),jn=t=>t.kty!=="oct"&&t.d===void 0&&t.priv===void 0,Ln=t=>t.kty==="oct"&&typeof t.k=="string";function Hn(t,e){if(t.startsWith("RS")||t.startsWith("PS")){let{modulusLength:r}=e.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)}}function Mn(t,e){let r=`SHA-${t.slice(-3)}`;switch(t){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:parseInt(t.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:e.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:t};default:throw new G(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}async function Vn(t,e,r){if(e instanceof Uint8Array){if(!t.startsWith("HS"))throw new TypeError(rs(e,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",e,{hash:`SHA-${t.slice(-3)}`,name:"HMAC"},!1,[r])}return Pn(e,t,r),e}async function Wn(t,e,r){let s=await Vn(t,e,"sign");Hn(t,s);let n=await crypto.subtle.sign(Mn(t,s.algorithm),s,r);return new Uint8Array(n)}var St='Invalid or unsupported JWK "alg" (Algorithm) Parameter value';function Fn(t){let e,r;switch(t.kty){case"AKP":{switch(t.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":e={name:t.alg},r=t.priv?["sign"]:["verify"];break;default:throw new G(St)}break}case"RSA":{switch(t.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(t.alg.slice(-3),10)||1}`},r=t.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new G(St)}break}case"EC":{switch(t.alg){case"ES256":case"ES384":case"ES512":e={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[t.alg]},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new G(St)}break}case"OKP":{switch(t.alg){case"Ed25519":case"EdDSA":e={name:"Ed25519"},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new G(St)}break}default:throw new G('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:r}}async function Kn(t){if(!t.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:e,keyUsages:r}=Fn(t),s={...t};return s.kty!=="AKP"&&delete s.alg,delete s.use,crypto.subtle.importKey("jwk",s,e,t.ext??!(t.d||t.priv),t.key_ops??r)}var Ze="given KeyObject instance cannot be used for this algorithm",Ye,qr=async(t,e,r,s=!1)=>{Ye||=new WeakMap;let n=Ye.get(t);if(n?.[r])return n[r];let i=await Kn({...e,alg:r});return s&&Object.freeze(t),n?n[r]=i:Ye.set(t,{[r]:i}),i},qn=(t,e)=>{Ye||=new WeakMap;let r=Ye.get(t);if(r?.[e])return r[e];let s=t.type==="public",n=!!s,i;if(t.asymmetricKeyType==="x25519"){switch(e){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw new TypeError(Ze)}i=t.toCryptoKey(t.asymmetricKeyType,n,s?[]:["deriveBits"])}if(t.asymmetricKeyType==="ed25519"){if(e!=="EdDSA"&&e!=="Ed25519")throw new TypeError(Ze);i=t.toCryptoKey(t.asymmetricKeyType,n,[s?"verify":"sign"])}switch(t.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":{if(e!==t.asymmetricKeyType.toUpperCase())throw new TypeError(Ze);i=t.toCryptoKey(t.asymmetricKeyType,n,[s?"verify":"sign"])}}if(t.asymmetricKeyType==="rsa"){let o;switch(e){case"RSA-OAEP":o="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":o="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":o="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":o="SHA-512";break;default:throw new TypeError(Ze)}if(e.startsWith("RSA-OAEP"))return t.toCryptoKey({name:"RSA-OAEP",hash:o},n,s?["encrypt"]:["decrypt"]);i=t.toCryptoKey({name:e.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:o},n,[s?"verify":"sign"])}if(t.asymmetricKeyType==="ec"){let o=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(t.asymmetricKeyDetails?.namedCurve);if(!o)throw new TypeError(Ze);let a={ES256:"P-256",ES384:"P-384",ES512:"P-521"};a[e]&&o===a[e]&&(i=t.toCryptoKey({name:"ECDSA",namedCurve:o},n,[s?"verify":"sign"])),e.startsWith("ECDH-ES")&&(i=t.toCryptoKey({name:"ECDH",namedCurve:o},n,s?[]:["deriveBits"]))}if(!i)throw new TypeError(Ze);return r?r[e]=i:Ye.set(t,{[e]:i}),i};async function Bn(t,e){if(t instanceof Uint8Array||er(t))return t;if(tr(t)){if(t.type==="secret")return t.export();if("toCryptoKey"in t&&typeof t.toCryptoKey=="function")try{return qn(t,e)}catch(s){if(s instanceof TypeError)throw s}let r=t.export({format:"jwk"});return qr(t,r,e)}if(rr(t))return t.k?$n(t.k):qr(t,t,e,!0);throw new Error("unreachable")}var Gn=(t,e)=>{let r=(t.match(/.{1,64}/g)||[]).join(`
40
+ Output: ${JSON.stringify(a.example.output)}`);let m=u.map(y=>l.get(y)?.required?`<${y}>`:`[${y}]`);m.push("[options]"),d.usage(m.join(" ")),d.allowExcessArguments(!0);for(let y of c)y.type?.type==="boolean"?d.option(`--${y.name}`,y.description):d.option(`--${y.name} <value>`,y.description);a.params.files&&(d.option("--file <paths...>","File(s) to upload"),d.option("--files <paths...>","File(s) to upload"));let w={},I=[];d.action(()=>{let y=d.opts(),S=d.args,$e={};for(let[de,_e]of Object.entries(y)){if(de==="file"||de==="files"){I.push(..._e);continue}let lt=l.get(de);lt&&typeof _e=="string"?$e[de]=jr(_e,lt.type):$e[de]=_e}u.forEach((de,_e)=>{if(S[_e]!==void 0&&$e[de]===void 0){let lt=l.get(de);$e[de]=lt?jr(String(S[_e]),lt.type):S[_e]}});let Wr=S.slice(u.length);Wr.length>0&&a.params.files&&I.push(...Wr.filter(hn)),w=$e});try{await d.parseAsync(r,{from:"user"})}catch(y){throw y?.exitCode!==void 0&&process.exit(y.exitCode),y}if(r.length===0&&c.some(S=>S.required)&&d.help(),n.configFile){let y=Pa(n.configFile);for(let[S,$e]of Object.entries(y))w[S]===void 0&&(w[S]=$e)}let ne=s(),ye=ne.getIdentity();ye||(console.error("\x1B[31mNot registered. Run: botparty init\x1B[0m"),process.exit(1));let U=w,z=ye.namespace,P=n.baseUrl.replace("{namespace}",z),j=a.endpoint;for(let y of a.params.path){let S=U[y.name];S!==void 0?(j=j.replace(`{${y.name}}`,String(S)),delete U[y.name]):y.required&&(console.error(`\x1B[31mMissing required path parameter: --${y.name}\x1B[0m`),process.exit(1))}let N=new URLSearchParams;for(let y of a.params.query){let S=U[y.name];S!==void 0?(N.set(y.name,String(S)),delete U[y.name]):y.required&&(console.error(`\x1B[31mMissing required query parameter: --${y.name}\x1B[0m`),process.exit(1))}let ve=t.includes("://")?t:`https://${t}`,ue=N.toString(),ct=`${ve.replace(/\/$/,"")}${P}${j}${ue?"?"+ue:""}`,ee={method:a.method};if(["POST","PUT","PATCH"].includes(a.method)){let y={};for(let S of a.params.body)U[S.name]!==void 0?y[S.name]=U[S.name]:S.required&&(console.error(`\x1B[31mMissing required body parameter: --${S.name}\x1B[0m`),process.exit(1));if(a.params.files&&I.length>0){let S=un(I);y[a.params.files.bodyKey]=S}ee.body=JSON.stringify(y),ee.headers={"Content-Type":"application/json"}}console.log(`\x1B[90m${a.method} ${ct}\x1B[0m`);let Ft=await ne.generateToken({role:"admin"}),xt=new Headers(ee.headers);xt.set("Authorization",`Bearer ${Ft}`),ee.headers=xt;let ie=await fetch(ct,ee),_n=ie.headers.get("content-type")||"";if(!ie.ok){let y=await ie.text();try{let S=JSON.parse(y);S?.error?.code&&S?.error?.message?(console.error(`\x1B[31m${S.error.code}\x1B[0m \x1B[90m(${ie.status})\x1B[0m`),console.error(`
41
+ ${S.error.message}`),S.error.details&&console.error(`
42
+ \x1B[90m${JSON.stringify(S.error.details,null,2)}\x1B[0m`)):(console.error(`\x1B[31m${ie.status} ${ie.statusText}\x1B[0m`),console.error(JSON.stringify(S,null,2)))}catch{console.error(`\x1B[31m${ie.status} ${ie.statusText}\x1B[0m`),y&&console.error(y)}process.exit(1)}if(_n.includes("application/json")){let y=await ie.json();console.log(JSON.stringify(y,null,2))}else{let y=await ie.text();console.log(y)}}var Hr=W(()=>{"use strict";Sr();Qe();Dt();cn();pn()});import{readFileSync as hs,writeFileSync as nr,mkdirSync as gi,existsSync as Et,unlinkSync as ir,statSync as yi,renameSync as ps}from"node:fs";import{join as we}from"node:path";import{homedir as vi}from"node:os";import{randomBytes as fs}from"node:crypto";var Xr=new TextEncoder,Fr=new TextDecoder,cc=2**32;function Tn(...t){let e=t.reduce((n,{length:i})=>n+i,0),r=new Uint8Array(e),s=0;for(let n of t)r.set(n,s),s+=n.length;return r}function qt(t){let e=new Uint8Array(t.length);for(let r=0;r<t.length;r++){let s=t.charCodeAt(r);if(s>127)throw new TypeError("non-ASCII string encountered in encode()");e[r]=s}return e}function Qr(t){if(Uint8Array.prototype.toBase64)return t.toBase64();let e=32768,r=[];for(let s=0;s<t.length;s+=e)r.push(String.fromCharCode.apply(null,t.subarray(s,s+e)));return btoa(r.join(""))}function es(t){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(t);let e=atob(t),r=new Uint8Array(e.length);for(let s=0;s<e.length;s++)r[s]=e.charCodeAt(s);return r}function $n(t){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof t=="string"?t:Fr.decode(t),{alphabet:"base64url"});let e=t;e instanceof Uint8Array&&(e=Fr.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/");try{return es(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}function Bt(t){let e=t;return typeof e=="string"&&(e=Xr.encode(e)),Uint8Array.prototype.toBase64?e.toBase64({alphabet:"base64url",omitPadding:!0}):Qr(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}var be=(t,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`),ze=(t,e)=>t.name===e;function Cn(t){return parseInt(t.name.slice(4),10)}function Gt(t,e){if(Cn(t.hash)!==e)throw be(`SHA-${e}`,"algorithm.hash")}function On(t){switch(t){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Rn(t,e){if(e&&!t.usages.includes(e))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${e}.`)}function Pn(t,e,r){switch(e){case"HS256":case"HS384":case"HS512":{if(!ze(t.algorithm,"HMAC"))throw be("HMAC");Gt(t.algorithm,parseInt(e.slice(2),10));break}case"RS256":case"RS384":case"RS512":{if(!ze(t.algorithm,"RSASSA-PKCS1-v1_5"))throw be("RSASSA-PKCS1-v1_5");Gt(t.algorithm,parseInt(e.slice(2),10));break}case"PS256":case"PS384":case"PS512":{if(!ze(t.algorithm,"RSA-PSS"))throw be("RSA-PSS");Gt(t.algorithm,parseInt(e.slice(2),10));break}case"Ed25519":case"EdDSA":{if(!ze(t.algorithm,"Ed25519"))throw be("Ed25519");break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{if(!ze(t.algorithm,e))throw be(e);break}case"ES256":case"ES384":case"ES512":{if(!ze(t.algorithm,"ECDSA"))throw be("ECDSA");let s=On(e);if(t.algorithm.namedCurve!==s)throw be(s,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Rn(t,r)}function ts(t,e,...r){if(r=r.filter(Boolean),r.length>2){let s=r.pop();t+=`one of type ${r.join(", ")}, or ${s}.`}else r.length===2?t+=`one of type ${r[0]} or ${r[1]}.`:t+=`of type ${r[0]}.`;return e==null?t+=` Received ${e}`:typeof e=="function"&&e.name?t+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&e.constructor?.name&&(t+=` Received an instance of ${e.constructor.name}`),t}var rs=(t,...e)=>ts("Key must be ",t,...e),ss=(t,e,...r)=>ts(`Key for the ${t} algorithm must be `,e,...r),Qt=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(t,e){super(t,e),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},Z=class extends Qt{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},dt=class extends Qt{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},In=class extends Qt{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"},er=t=>{if(t?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return t instanceof CryptoKey}catch{return!1}},tr=t=>t?.[Symbol.toStringTag]==="KeyObject",ns=t=>er(t)||tr(t),lc=Symbol();function Kr(t,e){if(t)throw new TypeError(`${e} can only be called once`)}var Nn=t=>typeof t=="object"&&t!==null;function is(t){if(!Nn(t)||Object.prototype.toString.call(t)!=="[object Object]")return!1;if(Object.getPrototypeOf(t)===null)return!0;let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function Dn(...t){let e=t.filter(Boolean);if(e.length===0||e.length===1)return!0;let r;for(let s of e){let n=Object.keys(s);if(!r||r.size===0){r=new Set(n);continue}for(let i of n){if(r.has(i))return!1;r.add(i)}}return!0}var rr=t=>is(t)&&typeof t.kty=="string",Un=t=>t.kty!=="oct"&&(t.kty==="AKP"&&typeof t.priv=="string"||typeof t.d=="string"),jn=t=>t.kty!=="oct"&&t.d===void 0&&t.priv===void 0,Ln=t=>t.kty==="oct"&&typeof t.k=="string";function Hn(t,e){if(t.startsWith("RS")||t.startsWith("PS")){let{modulusLength:r}=e.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)}}function Mn(t,e){let r=`SHA-${t.slice(-3)}`;switch(t){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:parseInt(t.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:e.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:t};default:throw new Z(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}async function Vn(t,e,r){if(e instanceof Uint8Array){if(!t.startsWith("HS"))throw new TypeError(rs(e,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",e,{hash:`SHA-${t.slice(-3)}`,name:"HMAC"},!1,[r])}return Pn(e,t,r),e}async function Wn(t,e,r){let s=await Vn(t,e,"sign");Hn(t,s);let n=await crypto.subtle.sign(Mn(t,s.algorithm),s,r);return new Uint8Array(n)}var At='Invalid or unsupported JWK "alg" (Algorithm) Parameter value';function Fn(t){let e,r;switch(t.kty){case"AKP":{switch(t.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":e={name:t.alg},r=t.priv?["sign"]:["verify"];break;default:throw new Z(At)}break}case"RSA":{switch(t.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(t.alg.slice(-3),10)||1}`},r=t.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new Z(At)}break}case"EC":{switch(t.alg){case"ES256":case"ES384":case"ES512":e={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[t.alg]},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new Z(At)}break}case"OKP":{switch(t.alg){case"Ed25519":case"EdDSA":e={name:"Ed25519"},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new Z(At)}break}default:throw new Z('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:r}}async function Kn(t){if(!t.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:e,keyUsages:r}=Fn(t),s={...t};return s.kty!=="AKP"&&delete s.alg,delete s.use,crypto.subtle.importKey("jwk",s,e,t.ext??!(t.d||t.priv),t.key_ops??r)}var Ze="given KeyObject instance cannot be used for this algorithm",Ye,qr=async(t,e,r,s=!1)=>{Ye||=new WeakMap;let n=Ye.get(t);if(n?.[r])return n[r];let i=await Kn({...e,alg:r});return s&&Object.freeze(t),n?n[r]=i:Ye.set(t,{[r]:i}),i},qn=(t,e)=>{Ye||=new WeakMap;let r=Ye.get(t);if(r?.[e])return r[e];let s=t.type==="public",n=!!s,i;if(t.asymmetricKeyType==="x25519"){switch(e){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw new TypeError(Ze)}i=t.toCryptoKey(t.asymmetricKeyType,n,s?[]:["deriveBits"])}if(t.asymmetricKeyType==="ed25519"){if(e!=="EdDSA"&&e!=="Ed25519")throw new TypeError(Ze);i=t.toCryptoKey(t.asymmetricKeyType,n,[s?"verify":"sign"])}switch(t.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":{if(e!==t.asymmetricKeyType.toUpperCase())throw new TypeError(Ze);i=t.toCryptoKey(t.asymmetricKeyType,n,[s?"verify":"sign"])}}if(t.asymmetricKeyType==="rsa"){let o;switch(e){case"RSA-OAEP":o="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":o="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":o="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":o="SHA-512";break;default:throw new TypeError(Ze)}if(e.startsWith("RSA-OAEP"))return t.toCryptoKey({name:"RSA-OAEP",hash:o},n,s?["encrypt"]:["decrypt"]);i=t.toCryptoKey({name:e.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:o},n,[s?"verify":"sign"])}if(t.asymmetricKeyType==="ec"){let o=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(t.asymmetricKeyDetails?.namedCurve);if(!o)throw new TypeError(Ze);let a={ES256:"P-256",ES384:"P-384",ES512:"P-521"};a[e]&&o===a[e]&&(i=t.toCryptoKey({name:"ECDSA",namedCurve:o},n,[s?"verify":"sign"])),e.startsWith("ECDH-ES")&&(i=t.toCryptoKey({name:"ECDH",namedCurve:o},n,s?[]:["deriveBits"]))}if(!i)throw new TypeError(Ze);return r?r[e]=i:Ye.set(t,{[e]:i}),i};async function Bn(t,e){if(t instanceof Uint8Array||er(t))return t;if(tr(t)){if(t.type==="secret")return t.export();if("toCryptoKey"in t&&typeof t.toCryptoKey=="function")try{return qn(t,e)}catch(s){if(s instanceof TypeError)throw s}let r=t.export({format:"jwk"});return qr(t,r,e)}if(rr(t))return t.k?$n(t.k):qr(t,t,e,!0);throw new Error("unreachable")}var Gn=(t,e)=>{let r=(t.match(/.{1,64}/g)||[]).join(`
43
43
  `);return`-----BEGIN ${e}-----
44
44
  ${r}
45
- -----END ${e}-----`},os=async(t,e,r)=>{if(tr(r)){if(r.type!==t)throw new TypeError(`key is not a ${t} key`);return r.export({format:"pem",type:e})}if(!er(r))throw new TypeError(rs(r,"CryptoKey","KeyObject"));if(!r.extractable)throw new TypeError("CryptoKey is not extractable");if(r.type!==t)throw new TypeError(`key is not a ${t} key`);return Gn(Qr(new Uint8Array(await crypto.subtle.exportKey(e,r))),`${t.toUpperCase()} KEY`)},zn=t=>os("public","spki",t),Zn=t=>os("private","pkcs8",t),zt=(t,e)=>{if(t.byteLength!==e.length)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0},Jn=t=>({data:t,pos:0}),ft=t=>{let e=t.data[t.pos++];if(e&128){let r=e&127,s=0;for(let n=0;n<r;n++)s=s<<8|t.data[t.pos++];return s}return e},mt=(t,e,r)=>{if(t.data[t.pos++]!==e)throw new Error(r)},as=(t,e)=>{let r=t.data.subarray(t.pos,t.pos+e);return t.pos+=e,r},Yn=t=>{mt(t,6,"Expected algorithm OID");let e=ft(t);return as(t,e)};function Xn(t){mt(t,48,"Invalid PKCS#8 structure"),ft(t),mt(t,2,"Expected version field");let e=ft(t);t.pos+=e,mt(t,48,"Expected algorithm identifier");let r=ft(t);return{algIdStart:t.pos,algIdLength:r}}var Qn=t=>{let e=Yn(t);if(zt(e,[43,101,110]))return"X25519";if(!zt(e,[42,134,72,206,61,2,1]))throw new Error("Unsupported key algorithm");mt(t,6,"Expected curve OID");let r=ft(t),s=as(t,r);for(let{name:n,oid:i}of[{name:"P-256",oid:[42,134,72,206,61,3,1,7]},{name:"P-384",oid:[43,129,4,0,34]},{name:"P-521",oid:[43,129,4,0,35]}])if(zt(s,i))return n;throw new Error("Unsupported named curve")},ei=async(t,e,r,s)=>{let n,i,o=t==="spki",a=()=>o?["verify"]:["sign"],c=()=>o?["encrypt","wrapKey"]:["decrypt","unwrapKey"];switch(r){case"PS256":case"PS384":case"PS512":n={name:"RSA-PSS",hash:`SHA-${r.slice(-3)}`},i=a();break;case"RS256":case"RS384":case"RS512":n={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${r.slice(-3)}`},i=a();break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":n={name:"RSA-OAEP",hash:`SHA-${parseInt(r.slice(-3),10)||1}`},i=c();break;case"ES256":case"ES384":case"ES512":{n={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[r]},i=a();break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{try{let l=s.getNamedCurve(e);n=l==="X25519"?{name:"X25519"}:{name:"ECDH",namedCurve:l}}catch{throw new G("Invalid or unsupported key format")}i=o?[]:["deriveBits"];break}case"Ed25519":case"EdDSA":n={name:"Ed25519"},i=a();break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":n={name:r},i=a();break;default:throw new G('Invalid or unsupported "alg" (Algorithm) value')}return crypto.subtle.importKey(t,e,n,s?.extractable??!!o,i)},ti=(t,e)=>es(t.replace(e,"")),ri=(t,e,r)=>{let s=ti(t,/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g),n=r;return e?.startsWith?.("ECDH-ES")&&(n||={},n.getNamedCurve=i=>{let o=Jn(i);return Xn(o),Qn(o)}),ei("pkcs8",s,e,n)};async function cs(t,e,r){if(typeof t!="string"||t.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return ri(t,e,r)}async function si(t){return zn(t)}async function ni(t){return Zn(t)}function ii(t,e,r,s,n){if(n.crit!==void 0&&s?.crit===void 0)throw new t('"crit" (Critical) Header Parameter MUST be integrity protected');if(!s||s.crit===void 0)return new Set;if(!Array.isArray(s.crit)||s.crit.length===0||s.crit.some(o=>typeof o!="string"||o.length===0))throw new t('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;r!==void 0?i=new Map([...Object.entries(r),...e.entries()]):i=e;for(let o of s.crit){if(!i.has(o))throw new G(`Extension Header Parameter "${o}" is not recognized`);if(n[o]===void 0)throw new t(`Extension Header Parameter "${o}" is missing`);if(i.get(o)&&s[o]===void 0)throw new t(`Extension Header Parameter "${o}" MUST be integrity protected`)}return new Set(s.crit)}var Je=t=>t?.[Symbol.toStringTag],Yt=(t,e,r)=>{if(e.use!==void 0){let s;switch(r){case"sign":case"verify":s="sig";break;case"encrypt":case"decrypt":s="enc";break}if(e.use!==s)throw new TypeError(`Invalid key for this operation, its "use" must be "${s}" when present`)}if(e.alg!==void 0&&e.alg!==t)throw new TypeError(`Invalid key for this operation, its "alg" must be "${t}" when present`);if(Array.isArray(e.key_ops)){let s;switch(!0){case(r==="sign"||r==="verify"):case t==="dir":case t.includes("CBC-HS"):s=r;break;case t.startsWith("PBES2"):s="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(t):!t.includes("GCM")&&t.endsWith("KW")?s=r==="encrypt"?"wrapKey":"unwrapKey":s=r;break;case(r==="encrypt"&&t.startsWith("RSA")):s="wrapKey";break;case r==="decrypt":s=t.startsWith("RSA")?"unwrapKey":"deriveBits";break}if(s&&e.key_ops?.includes?.(s)===!1)throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${s}" when present`)}return!0},oi=(t,e,r)=>{if(!(e instanceof Uint8Array)){if(rr(e)){if(Ln(e)&&Yt(t,e,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!ns(e))throw new TypeError(ss(t,e,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(e.type!=="secret")throw new TypeError(`${Je(e)} instances for symmetric algorithms must be of type "secret"`)}},ai=(t,e,r)=>{if(rr(e))switch(r){case"decrypt":case"sign":if(Un(e)&&Yt(t,e,r))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if(jn(e)&&Yt(t,e,r))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!ns(e))throw new TypeError(ss(t,e,"CryptoKey","KeyObject","JSON Web Key"));if(e.type==="secret")throw new TypeError(`${Je(e)} instances for asymmetric algorithms must not be of type "secret"`);if(e.type==="public")switch(r){case"sign":throw new TypeError(`${Je(e)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${Je(e)} instances for asymmetric algorithm decryption must be of type "private"`)}if(e.type==="private")switch(r){case"verify":throw new TypeError(`${Je(e)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${Je(e)} instances for asymmetric algorithm encryption must be of type "public"`)}};function ci(t,e,r){switch(t.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":oi(t,e,r);break;default:ai(t,e,r)}}var Oe=t=>Math.floor(t.getTime()/1e3),ls=60,us=ls*60,sr=us*24,li=sr*7,ui=sr*365.25,di=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function Zt(t){let e=di.exec(t);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");let r=parseFloat(e[2]),s=e[3].toLowerCase(),n;switch(s){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(r*ls);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(r*us);break;case"day":case"days":case"d":n=Math.round(r*sr);break;case"week":case"weeks":case"w":n=Math.round(r*li);break;default:n=Math.round(r*ui);break}return e[1]==="-"||e[4]==="ago"?-n:n}function Re(t,e){if(!Number.isFinite(e))throw new TypeError(`Invalid ${t} input`);return e}var hi=class{#e;constructor(t){if(!is(t))throw new TypeError("JWT Claims Set MUST be an object");this.#e=structuredClone(t)}data(){return Xr.encode(JSON.stringify(this.#e))}get iss(){return this.#e.iss}set iss(t){this.#e.iss=t}get sub(){return this.#e.sub}set sub(t){this.#e.sub=t}get aud(){return this.#e.aud}set aud(t){this.#e.aud=t}set jti(t){this.#e.jti=t}set nbf(t){typeof t=="number"?this.#e.nbf=Re("setNotBefore",t):t instanceof Date?this.#e.nbf=Re("setNotBefore",Oe(t)):this.#e.nbf=Oe(new Date)+Zt(t)}set exp(t){typeof t=="number"?this.#e.exp=Re("setExpirationTime",t):t instanceof Date?this.#e.exp=Re("setExpirationTime",Oe(t)):this.#e.exp=Oe(new Date)+Zt(t)}set iat(t){t===void 0?this.#e.iat=Oe(new Date):t instanceof Date?this.#e.iat=Re("setIssuedAt",Oe(t)):typeof t=="string"?this.#e.iat=Re("setIssuedAt",Oe(new Date)+Zt(t)):this.#e.iat=Re("setIssuedAt",t)}},ds=class{#e;#t;#r;constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this.#e=t}setProtectedHeader(t){return Kr(this.#t,"setProtectedHeader"),this.#t=t,this}setUnprotectedHeader(t){return Kr(this.#r,"setUnprotectedHeader"),this.#r=t,this}async sign(t,e){if(!this.#t&&!this.#r)throw new dt("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Dn(this.#t,this.#r))throw new dt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let r={...this.#t,...this.#r},s=ii(dt,new Map([["b64",!0]]),e?.crit,this.#t,r),n=!0;if(s.has("b64")&&(n=this.#t.b64,typeof n!="boolean"))throw new dt('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:i}=r;if(typeof i!="string"||!i)throw new dt('JWS "alg" (Algorithm) Header Parameter missing or invalid');ci(i,t,"sign");let o,a;n?(o=Bt(this.#e),a=qt(o)):(a=this.#e,o="");let c,l;this.#t?(c=Bt(JSON.stringify(this.#t)),l=qt(c)):(c="",l=new Uint8Array);let u=Tn(l,qt("."),a),d=await Bn(t,i),m=await Wn(i,d,u),x={signature:Bt(m),payload:o};return this.#r&&(x.header=this.#r),this.#t&&(x.protected=c),x}},pi=class{#e;constructor(t){this.#e=new ds(t)}setProtectedHeader(t){return this.#e.setProtectedHeader(t),this}async sign(t,e){let r=await this.#e.sign(t,e);if(r.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}},fi=class{#e;#t;constructor(t={}){this.#t=new hi(t)}setIssuer(t){return this.#t.iss=t,this}setSubject(t){return this.#t.sub=t,this}setAudience(t){return this.#t.aud=t,this}setJti(t){return this.#t.jti=t,this}setNotBefore(t){return this.#t.nbf=t,this}setExpirationTime(t){return this.#t.exp=t,this}setIssuedAt(t){return this.#t.iat=t,this}setProtectedHeader(t){return this.#e=t,this}async sign(t,e){let r=new pi(this.#t.data());if(r.setProtectedHeader(this.#e),Array.isArray(this.#e?.crit)&&this.#e.crit.includes("b64")&&this.#e.b64===!1)throw new In("JWTs MUST NOT use unencoded payload");return r.sign(t,e)}};function Jt(t){let e=t?.modulusLength??2048;if(typeof e!="number"||e<2048)throw new G("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return e}async function mi(t,e){let r,s;switch(t){case"PS256":case"PS384":case"PS512":r={name:"RSA-PSS",hash:`SHA-${t.slice(-3)}`,publicExponent:Uint8Array.of(1,0,1),modulusLength:Jt(e)},s=["sign","verify"];break;case"RS256":case"RS384":case"RS512":r={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${t.slice(-3)}`,publicExponent:Uint8Array.of(1,0,1),modulusLength:Jt(e)},s=["sign","verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":r={name:"RSA-OAEP",hash:`SHA-${parseInt(t.slice(-3),10)||1}`,publicExponent:Uint8Array.of(1,0,1),modulusLength:Jt(e)},s=["decrypt","unwrapKey","encrypt","wrapKey"];break;case"ES256":r={name:"ECDSA",namedCurve:"P-256"},s=["sign","verify"];break;case"ES384":r={name:"ECDSA",namedCurve:"P-384"},s=["sign","verify"];break;case"ES512":r={name:"ECDSA",namedCurve:"P-521"},s=["sign","verify"];break;case"Ed25519":case"EdDSA":{s=["sign","verify"],r={name:"Ed25519"};break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{s=["sign","verify"],r={name:t};break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{s=["deriveBits"];let n=e?.crv??"P-256";switch(n){case"P-256":case"P-384":case"P-521":{r={name:"ECDH",namedCurve:n};break}case"X25519":r={name:"X25519"};break;default:throw new G("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519")}break}default:throw new G('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return crypto.subtle.generateKey(r,e?.extractable??!1,s)}var _i="https://id.botparty.club",bi="EdDSA",wi=15,Br=6e4,xi=3e4,ki="5m",Si=3,Ai=["brave","calm","cosmic","eager","fair","gentle","happy","keen","lively","noble","proud","quick","rare","sharp","swift","true","vivid","warm","wild","bold","cool","fast","grand","just","kind","lean","mild","neat","pale","rich","safe","tall","vast","wise","bright","dark","fierce","quiet","free","glad"],Ei=["lion","hawk","wolf","bear","fox","deer","owl","crane","whale","tiger","eagle","shark","raven","puma","lynx","orca","swan","viper","bison","cobra","finch","gecko","heron","ibex","jay","kite","lark","moth","newt","otter","perch","quail","robin","seal","toad","wren","yak","zebra","ant","bee"],H=class extends Error{code;statusCode;actionUrl;details;constructor(t){super(t.message),this.name="BotPartyError",this.code=t.code,this.statusCode=t.statusCode,this.actionUrl=t.actionUrl,this.details=t.details}},or=class extends H{constructor(t){super({code:"NAMESPACE_LOCKED",message:t.message,statusCode:423,actionUrl:t.actionUrl,details:{lockedAt:t.lockedAt,reason:t.reason}}),this.name="NamespaceLockedError"}},Tt=class extends H{amount;service;constructor(t){super({code:"PAYMENT_REQUIRED",message:t.message,statusCode:402,actionUrl:t.actionUrl}),this.name="PaymentRequiredError",this.amount=t.amount,this.service=t.service}},gt=class extends H{missingScopes;constructor(t){super({code:"INSUFFICIENT_PERMISSION",message:t.message,statusCode:403,actionUrl:t.actionUrl}),this.name="InsufficientPermissionError",this.missingScopes=t.missingScopes}},$t=class extends H{constructor(t){super({code:"LINK_REQUIRED",message:t.message,statusCode:403,actionUrl:t.actionUrl}),this.name="LinkRequiredError"}};function Gr(t){let e=fs(4);return t[e.readUInt32BE(0)%t.length]}function Ti(){return`${Gr(Ai)}-${Gr(Ei)}`}function $i(){let t=Ti(),e=fs(2).toString("hex");return`${t}-${e}`}function Ci(){return be(vi(),".botparty")}function ar(t){Et(t)||gi(t,{recursive:!0,mode:448})}function Oi(t){let e=be(t,"identity.json");if(!Et(e))return null;try{return JSON.parse(hs(e,"utf-8"))}catch{return null}}function ms(t,e){ar(t);let r=be(t,"identity.json"),s=r+".tmp";nr(s,JSON.stringify(e,null,2),{mode:384}),ps(s,r)}function Ri(t){let e=be(t,"private.pem");if(!Et(e))return null;try{return hs(e,"utf-8")}catch{return null}}function gs(t,e){ar(t);let r=be(t,"private.pem"),s=r+".tmp";nr(s,e,{mode:384}),ps(s,r)}function zr(t){for(let e of["identity.json","private.pem"]){let r=be(t,e);Et(r)&&ir(r)}}function Pi(t){let e=be(t,"rotation.lock");ar(t);for(let r=0;r<2;r++)try{nr(e,`${process.pid}:${Date.now()}`,{flag:"wx",mode:384});return}catch(s){if(s.code!=="EEXIST")throw s;try{let n=yi(e);if(Date.now()-n.mtimeMs>xi){ir(e);continue}}catch{continue}throw s}}function Ii(t){try{ir(be(t,"rotation.lock"))}catch{}}async function ys(t){let e={extractable:!0};t==="EdDSA"&&(e.crv="Ed25519");let{privateKey:r,publicKey:s}=await mi(t,e),n=await ni(r),i=await si(s);return{privateKey:r,publicKey:s,privatePem:n,publicPem:i}}async function Ni(t,e,r){let s=await cs(e,r);return(await new ds(new TextEncoder().encode(t)).setProtectedHeader({alg:r}).sign(s)).signature}async function Xt(t,e,r,s,n){let i=s,o=await cs(r,i);return new fi({...n}).setProtectedHeader({alg:i,kid:e}).setIssuer(t).setSubject(t).setIssuedAt().setExpirationTime(ki).sign(o)}async function ie(t,e,r={}){let{token:s,...n}=r,i=new Headers(n.headers);return i.set("Content-Type","application/json"),s&&i.set("Authorization",`Bearer ${s}`),fetch(`${t}${e}`,{...n,headers:i})}function Zr(t,e){try{let r=new URL(t),s=new URL(e);return r.hostname===s.hostname&&r.port===s.port&&r.protocol===s.protocol?t:`${e}/${r.hostname}${r.pathname}${r.search}`}catch{return`${e}/${t}`}}async function At(t){try{return await t.clone().json()}catch{return null}}function pt(t){let e=t.error,r,s,n,i={};if(typeof e=="object"&&e!==null){let o=e;r=o.code||"UNKNOWN",s=o.message||t.message||"Request failed",n=o.actionUrl||t.actionUrl||o.payTo||t.payTo,i=o}else r=(typeof e=="string"?e:t.code)||"UNKNOWN",s=t.message||(typeof e=="string"?e:"Request failed"),n=t.actionUrl||t.payTo,i=t;return{code:r.toUpperCase(),message:s,actionUrl:n,extra:i}}var Di=class{constructor(t,e){this.client=t,this.keyId=e}get id(){return this.keyId}async info(){return this.client.keys.get(this.keyId)}async update(t){return this.client.keys.update(this.keyId,t)}async delete(){return this.client.keys.delete(this.keyId)}async rotate(){return this.client.keys.rotate(this.keyId)}async invalidate(t){return this.client.keys.invalidate(this.keyId,t)}},Ui=class{constructor(t){this.client=t}async list(){let t=await this.client.generateToken(),e=await ie(this.client.serverUrl,"/api/v1/namespaces/keys",{token:t});if(!e.ok)throw await this.client._apiError(e);return(await e.json()).data}async get(t){let e=(await this.list()).find(r=>r.id===t);if(!e)throw new H({code:"KEY_NOT_FOUND",message:`Key ${t} not found`,statusCode:404});return e}async add(t){let e=await this.client.generateToken(),r=await ie(this.client.serverUrl,"/api/v1/namespaces/keys",{method:"POST",token:e,body:JSON.stringify(t)});if(!r.ok)throw await this.client._apiError(r);return r.json()}async update(t,e){let r=await this.client.generateToken(),s=await ie(this.client.serverUrl,`/api/v1/namespaces/keys/${t}`,{method:"PATCH",token:r,body:JSON.stringify(e)});if(!s.ok)throw await this.client._apiError(s);return s.json()}async delete(t){let e=await this.client.generateToken(),r=await ie(this.client.serverUrl,`/api/v1/namespaces/keys/${t}`,{method:"DELETE",token:e});if(!r.ok&&r.status!==204)throw await this.client._apiError(r)}async rotate(t){let e=this.client.getIdentity();if(!e)throw new Error("Not registered");let r=this.client.getPrivateKey();if(!r)throw new Error("Private key not found");let s=t||e.keyId;if(s!==e.keyId)throw new H({code:"CANNOT_ROTATE_OTHER_KEY",message:"Can only rotate the current machine key from this client. Use the server API directly for other keys.",statusCode:400});let n=await ys(e.algorithm),i=await Xt(e.namespace,e.keyId,r,e.algorithm),o=await ie(e.serverUrl,`/api/v1/namespaces/keys/${s}/rotate`,{method:"POST",token:i,body:JSON.stringify({newPublicKey:n.publicPem})});if(!o.ok)throw await this.client._apiError(o);let a=await o.json();return gs(this.client.stateDir,n.privatePem),ms(this.client.stateDir,{...e,rotatedAt:a.rotatedAt}),a}async rotateCurrent(){return this.rotate()}async invalidate(t,e){let r=await this.client.generateToken(),s=await ie(this.client.serverUrl,`/api/v1/namespaces/keys/${t}/invalidate`,{method:"POST",token:r,body:JSON.stringify({reason:e})});if(!s.ok)throw await this.client._apiError(s)}},vs=class{serverUrl;stateDir;proxyUrl;keys;algorithm;rotationTTL;inviteToken;_rotationPromise=null;constructor(t={}){this.serverUrl=(t.serverUrl||ht("BOTPARTY_SERVER_URL")||_i).replace(/\/$/,""),this.proxyUrl=(t.proxyUrl||ht("BOTPARTY_PROXY_URL")||ht("KEYCHAINS_PROXY_URL")||"https://keychains.dev").replace(/\/$/,""),this.stateDir=t.stateDir||ht("BOTPARTY_STATE_DIR")||Ci(),this.algorithm=t.algorithm||bi,this.rotationTTL=t.rotationTTL||wi,this.inviteToken=t.inviteToken||ht("BOTPARTY_INVITE_TOKEN"),this.keys=new Ui(this)}getIdentity(){return Oi(this.stateDir)}getPrivateKey(){return Ri(this.stateDir)}isRegistered(){return this.getIdentity()!==null&&this.getPrivateKey()!==null}async register(t,e,r){let s=t,n=0,i=r?.inviteToken||this.inviteToken;for(;n<Si;){s||(s=$i());let o=e||s,a=await ys(this.algorithm),c=await ie(this.serverUrl,"/api/v1/namespaces/register",{method:"POST",body:JSON.stringify({namespace:s,publicKey:a.publicPem,rotationTTL:this.rotationTTL,...i&&{inviteToken:i}})}),l=await c.json();if(l.status==="already_registered")throw new H({code:"ALREADY_REGISTERED",message:`Namespace "${s}" is already registered`,statusCode:409});if(c.status===409&&!t){s=void 0,n++;continue}if(!c.ok)throw new H({code:l.error||"REGISTRATION_FAILED",message:l.message||l.error||"Registration failed",statusCode:c.status});let u=l.challenge,d=await Ni(u,a.privatePem,this.algorithm),m=await ie(this.serverUrl,"/api/v1/namespaces/register/verify",{method:"POST",body:JSON.stringify({namespace:s,challenge:u,signature:d})});if(!m.ok)throw await this._apiError(m);let x=await m.json();return gs(this.stateDir,a.privatePem),ms(this.stateDir,{serverUrl:this.serverUrl,namespace:s,keyId:x.keyId,algorithm:this.algorithm,rotatedAt:x.rotatedAt,rotationTTL:x.rotationTTL,label:o,...x.parentNamespace&&{parentNamespace:x.parentNamespace},...x.inheritedScopes&&{inheritedScopes:x.inheritedScopes}}),x}throw new H({code:"REGISTRATION_FAILED",message:"Failed to find available namespace after retries",statusCode:409})}async ensureRegistered(){let t=this.getIdentity();if(t&&this.getPrivateKey())return t;await this.register(void 0,void 0,{inviteToken:this.inviteToken});let e=this.getIdentity();if(!e)throw new Error("Registration succeeded but identity could not be read");return e}async ensureFreshKey(){if(this._rotationPromise)return this._rotationPromise;let t=this.getIdentity();if(!t)throw new Error("Not registered");let e=new Date(t.rotatedAt).getTime()+t.rotationTTL*6e4;if(Date.now()>=e-Br)return this._rotationPromise=this._lockedRotate().finally(()=>{this._rotationPromise=null}),this._rotationPromise}async _lockedRotate(){Pi(this.stateDir);try{let t=this.getIdentity();if(!t)throw new Error("Not registered");let e=new Date(t.rotatedAt).getTime()+t.rotationTTL*6e4;if(Date.now()<e-Br)return;await this.keys.rotateCurrent()}finally{Ii(this.stateDir)}}async generateToken(t){await this.ensureRegistered(),await this.ensureFreshKey();let e=this.getIdentity(),r=this.getPrivateKey();return Xt(e.namespace,e.keyId,r,e.algorithm,t)}async fetch(t,e={}){let r=await this.generateToken(),s=Zr(t,this.proxyUrl),n=new Headers(e.headers);n.set("X-Proxy-Authorization",`Bearer ${r}`);let i=await fetch(s,{...e,headers:n});if(i.status===401){let o=await At(i);if(o){let{code:a}=pt(o);if(a==="KEY_STALE"){await this._lockedRotate();let c=await this.generateToken(),l=new Headers(e.headers);l.set("X-Proxy-Authorization",`Bearer ${c}`),i=await fetch(s,{...e,headers:l})}}}if(i.status===403){let o=await At(i);if(o){let a=typeof o.error=="string"?o.error:o.error?.code;if(a==="wrong_proxy"&&o.proxyUrl){let u=o.proxyUrl.replace(/\/$/,""),d=Zr(t,u),m=new Headers(e.headers);return m.set("X-Proxy-Authorization",`Bearer ${r}`),fetch(d,{...e,headers:m})}let c=o.approval_url||o.authorizationUrl;if(c){let u=a==="scope_refused",d=o.missing_scopes||o.missingScopes;throw u||a==="insufficient_scope"||a==="permission_denied"||a==="scope_not_approved"||a==="permission_needs_revalidation"?new gt({message:o.message||"Missing required credentials",actionUrl:c,missingScopes:d}):new $t({message:o.message||"Missing required credentials",actionUrl:c})}let{code:l}=pt(o);Jr(l)&&Yr(i.status,o,this.getIdentity(),this.serverUrl)}}if([401,402,423].includes(i.status)){let o=await At(i);if(o){let{code:a}=pt(o);(Jr(a)||i.status===402||i.status===423)&&Yr(i.status,o,this.getIdentity(),this.serverUrl)}}return i}async info(t){let e=t||this.getIdentity()?.namespace;if(!e)throw new Error("Not registered and no namespace provided");let r=await ie(this.serverUrl,`/api/v1/namespaces/${e}/info`);if(!r.ok)throw await this._apiError(r);return r.json()}async destroy(){let t=await this.generateToken(),e=await ie(this.serverUrl,"/api/v1/namespaces",{method:"DELETE",token:t});if(!e.ok&&e.status!==204)throw await this._apiError(e);zr(this.stateDir)}async link(){let t=this.getIdentity();if(!t)throw new Error("Not registered");let e=this.getPrivateKey();if(!e)throw new Error("Private key not found");let r=await Xt(t.namespace,t.keyId,e,t.algorithm,{act:"link"});return{url:`${t.serverUrl}/namespaces/${t.namespace}/link?jwt=${r}`}}whoami(){let t=this.getIdentity();if(!t)return null;let e=new Date(new Date(t.rotatedAt).getTime()+t.rotationTTL*6e4).toISOString();return{namespace:t.namespace,keyId:t.keyId,algorithm:t.algorithm,rotationTTL:t.rotationTTL,rotatedAt:t.rotatedAt,staleAt:e,label:t.label,serverUrl:t.serverUrl}}key(t){return new Di(this,t)}reset(){zr(this.stateDir)}async _apiError(t){let e=await At(t);if(!e)return new H({code:"UNKNOWN",message:`Request failed with status ${t.status}`,statusCode:t.status});let{code:r,message:s,actionUrl:n}=pt(e);return new H({code:r,message:s,statusCode:t.status,actionUrl:n})}},ji=new Set(["NAMESPACE_LOCKED","LOCKUP_TRIGGERED","PAYMENT_REQUIRED","LINK_REQUIRED","INSUFFICIENT_SCOPE","PERMISSION_DENIED","KEY_STALE","KEY_EXPIRED"]);function Jr(t){return ji.has(t.toUpperCase())}function Yr(t,e,r,s){let{code:n,message:i,actionUrl:o,extra:a}=pt(e),c=r?.namespace||"",l=r?.serverUrl||s;throw n==="NAMESPACE_LOCKED"||n==="LOCKUP_TRIGGERED"||t===423?new or({message:i||"Namespace is locked",actionUrl:o||`${l}/namespaces/${c}/unlock`,lockedAt:a.lockedAt,reason:a.reason}):n==="PAYMENT_REQUIRED"||t===402?new Tt({message:i,actionUrl:o,amount:a.amount||e.amount,service:a.service||e.service}):n==="LINK_REQUIRED"?new $t({message:i,actionUrl:o||`${l}/namespaces/${c}/link`}):n==="INSUFFICIENT_SCOPE"||n==="PERMISSION_DENIED"||t===403?new gt({message:i,actionUrl:o,missingScopes:a.missingScopes||a.missing_scopes}):new H({code:n,message:i,statusCode:t,actionUrl:o})}function ht(t){if(typeof process<"u"&&process.env)return process.env[t]}Ar();import{writeFileSync as Us}from"fs";import{readFileSync as It}from"fs";import{basename as ho}from"path";var Qi="\x1B[1m",eo="\x1B[2m",to="\x1B[31m",ro="\x1B[32m",so="\x1B[33m",no="\x1B[36m",Xe="\x1B[0m";function S(t){return`${Qi}${t}${Xe}`}function O(t){return`${eo}${t}${Xe}`}function P(t){return`${to}${t}${Xe}`}function j(t){return`${ro}${t}${Xe}`}function F(t){return`${so}${t}${Xe}`}function b(t){return`${no}${t}${Xe}`}import{readFileSync as io,writeFileSync as oo,existsSync as Ps,mkdirSync as ao}from"node:fs";import{join as Is}from"node:path";var Ns="auth-capability-cache.json",co=1440*60*1e3;function lo(t){let e=Is(t,Ns);if(!Ps(e))return{};try{return JSON.parse(io(e,"utf-8"))}catch{return{}}}function uo(t,e){Ps(t)||ao(t,{recursive:!0,mode:448}),oo(Is(t,Ns),JSON.stringify(e,null,2))}async function Ds(t,e){let r=lo(e),s=r[t];if(s&&Date.now()-s.checkedAt<co)return s.supportsBotparty;let n=!1;try{let i=new AbortController,o=setTimeout(()=>i.abort(),3e3),a=await fetch(`https://${t}/api/botparty/auth/me`,{method:"HEAD",signal:i.signal});clearTimeout(o),n=a.ok||a.status===401}catch{n=!1}r[t]={supportsBotparty:n,checkedAt:Date.now()};try{uo(e,r)}catch{}return n}function Er(t,e,r,s){let n=(Date.now()-s)/1e3,i=e.headers.get("content-type")||"",o={http_code:e.status,http_connect:0,http_version:"1.1",response_code:e.status,content_type:i,size_download:r,size_header:0,size_request:0,size_upload:0,speed_download:n>0?Math.round(r/n):0,speed_upload:0,time_appconnect:n,time_connect:n,time_namelookup:0,time_pretransfer:n,time_redirect:0,time_starttransfer:n,time_total:n,url_effective:"",num_connects:1,num_redirects:0,redirect_url:"",ssl_verify_result:0,stdout:"-",stderr:"-",exitcode:0,errormsg:"",method:"",scheme:"",filename_effective:"",onerror:"",urlnum:0},a=t;return a=a.replace(/\\n/g,`
45
+ -----END ${e}-----`},os=async(t,e,r)=>{if(tr(r)){if(r.type!==t)throw new TypeError(`key is not a ${t} key`);return r.export({format:"pem",type:e})}if(!er(r))throw new TypeError(rs(r,"CryptoKey","KeyObject"));if(!r.extractable)throw new TypeError("CryptoKey is not extractable");if(r.type!==t)throw new TypeError(`key is not a ${t} key`);return Gn(Qr(new Uint8Array(await crypto.subtle.exportKey(e,r))),`${t.toUpperCase()} KEY`)},zn=t=>os("public","spki",t),Zn=t=>os("private","pkcs8",t),zt=(t,e)=>{if(t.byteLength!==e.length)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0},Jn=t=>({data:t,pos:0}),ft=t=>{let e=t.data[t.pos++];if(e&128){let r=e&127,s=0;for(let n=0;n<r;n++)s=s<<8|t.data[t.pos++];return s}return e},mt=(t,e,r)=>{if(t.data[t.pos++]!==e)throw new Error(r)},as=(t,e)=>{let r=t.data.subarray(t.pos,t.pos+e);return t.pos+=e,r},Yn=t=>{mt(t,6,"Expected algorithm OID");let e=ft(t);return as(t,e)};function Xn(t){mt(t,48,"Invalid PKCS#8 structure"),ft(t),mt(t,2,"Expected version field");let e=ft(t);t.pos+=e,mt(t,48,"Expected algorithm identifier");let r=ft(t);return{algIdStart:t.pos,algIdLength:r}}var Qn=t=>{let e=Yn(t);if(zt(e,[43,101,110]))return"X25519";if(!zt(e,[42,134,72,206,61,2,1]))throw new Error("Unsupported key algorithm");mt(t,6,"Expected curve OID");let r=ft(t),s=as(t,r);for(let{name:n,oid:i}of[{name:"P-256",oid:[42,134,72,206,61,3,1,7]},{name:"P-384",oid:[43,129,4,0,34]},{name:"P-521",oid:[43,129,4,0,35]}])if(zt(s,i))return n;throw new Error("Unsupported named curve")},ei=async(t,e,r,s)=>{let n,i,o=t==="spki",a=()=>o?["verify"]:["sign"],c=()=>o?["encrypt","wrapKey"]:["decrypt","unwrapKey"];switch(r){case"PS256":case"PS384":case"PS512":n={name:"RSA-PSS",hash:`SHA-${r.slice(-3)}`},i=a();break;case"RS256":case"RS384":case"RS512":n={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${r.slice(-3)}`},i=a();break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":n={name:"RSA-OAEP",hash:`SHA-${parseInt(r.slice(-3),10)||1}`},i=c();break;case"ES256":case"ES384":case"ES512":{n={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[r]},i=a();break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{try{let l=s.getNamedCurve(e);n=l==="X25519"?{name:"X25519"}:{name:"ECDH",namedCurve:l}}catch{throw new Z("Invalid or unsupported key format")}i=o?[]:["deriveBits"];break}case"Ed25519":case"EdDSA":n={name:"Ed25519"},i=a();break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":n={name:r},i=a();break;default:throw new Z('Invalid or unsupported "alg" (Algorithm) value')}return crypto.subtle.importKey(t,e,n,s?.extractable??!!o,i)},ti=(t,e)=>es(t.replace(e,"")),ri=(t,e,r)=>{let s=ti(t,/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g),n=r;return e?.startsWith?.("ECDH-ES")&&(n||={},n.getNamedCurve=i=>{let o=Jn(i);return Xn(o),Qn(o)}),ei("pkcs8",s,e,n)};async function cs(t,e,r){if(typeof t!="string"||t.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return ri(t,e,r)}async function si(t){return zn(t)}async function ni(t){return Zn(t)}function ii(t,e,r,s,n){if(n.crit!==void 0&&s?.crit===void 0)throw new t('"crit" (Critical) Header Parameter MUST be integrity protected');if(!s||s.crit===void 0)return new Set;if(!Array.isArray(s.crit)||s.crit.length===0||s.crit.some(o=>typeof o!="string"||o.length===0))throw new t('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;r!==void 0?i=new Map([...Object.entries(r),...e.entries()]):i=e;for(let o of s.crit){if(!i.has(o))throw new Z(`Extension Header Parameter "${o}" is not recognized`);if(n[o]===void 0)throw new t(`Extension Header Parameter "${o}" is missing`);if(i.get(o)&&s[o]===void 0)throw new t(`Extension Header Parameter "${o}" MUST be integrity protected`)}return new Set(s.crit)}var Je=t=>t?.[Symbol.toStringTag],Yt=(t,e,r)=>{if(e.use!==void 0){let s;switch(r){case"sign":case"verify":s="sig";break;case"encrypt":case"decrypt":s="enc";break}if(e.use!==s)throw new TypeError(`Invalid key for this operation, its "use" must be "${s}" when present`)}if(e.alg!==void 0&&e.alg!==t)throw new TypeError(`Invalid key for this operation, its "alg" must be "${t}" when present`);if(Array.isArray(e.key_ops)){let s;switch(!0){case(r==="sign"||r==="verify"):case t==="dir":case t.includes("CBC-HS"):s=r;break;case t.startsWith("PBES2"):s="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(t):!t.includes("GCM")&&t.endsWith("KW")?s=r==="encrypt"?"wrapKey":"unwrapKey":s=r;break;case(r==="encrypt"&&t.startsWith("RSA")):s="wrapKey";break;case r==="decrypt":s=t.startsWith("RSA")?"unwrapKey":"deriveBits";break}if(s&&e.key_ops?.includes?.(s)===!1)throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${s}" when present`)}return!0},oi=(t,e,r)=>{if(!(e instanceof Uint8Array)){if(rr(e)){if(Ln(e)&&Yt(t,e,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!ns(e))throw new TypeError(ss(t,e,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(e.type!=="secret")throw new TypeError(`${Je(e)} instances for symmetric algorithms must be of type "secret"`)}},ai=(t,e,r)=>{if(rr(e))switch(r){case"decrypt":case"sign":if(Un(e)&&Yt(t,e,r))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if(jn(e)&&Yt(t,e,r))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!ns(e))throw new TypeError(ss(t,e,"CryptoKey","KeyObject","JSON Web Key"));if(e.type==="secret")throw new TypeError(`${Je(e)} instances for asymmetric algorithms must not be of type "secret"`);if(e.type==="public")switch(r){case"sign":throw new TypeError(`${Je(e)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${Je(e)} instances for asymmetric algorithm decryption must be of type "private"`)}if(e.type==="private")switch(r){case"verify":throw new TypeError(`${Je(e)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${Je(e)} instances for asymmetric algorithm encryption must be of type "public"`)}};function ci(t,e,r){switch(t.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":oi(t,e,r);break;default:ai(t,e,r)}}var Oe=t=>Math.floor(t.getTime()/1e3),ls=60,us=ls*60,sr=us*24,li=sr*7,ui=sr*365.25,di=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function Zt(t){let e=di.exec(t);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");let r=parseFloat(e[2]),s=e[3].toLowerCase(),n;switch(s){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(r*ls);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(r*us);break;case"day":case"days":case"d":n=Math.round(r*sr);break;case"week":case"weeks":case"w":n=Math.round(r*li);break;default:n=Math.round(r*ui);break}return e[1]==="-"||e[4]==="ago"?-n:n}function Re(t,e){if(!Number.isFinite(e))throw new TypeError(`Invalid ${t} input`);return e}var hi=class{#e;constructor(t){if(!is(t))throw new TypeError("JWT Claims Set MUST be an object");this.#e=structuredClone(t)}data(){return Xr.encode(JSON.stringify(this.#e))}get iss(){return this.#e.iss}set iss(t){this.#e.iss=t}get sub(){return this.#e.sub}set sub(t){this.#e.sub=t}get aud(){return this.#e.aud}set aud(t){this.#e.aud=t}set jti(t){this.#e.jti=t}set nbf(t){typeof t=="number"?this.#e.nbf=Re("setNotBefore",t):t instanceof Date?this.#e.nbf=Re("setNotBefore",Oe(t)):this.#e.nbf=Oe(new Date)+Zt(t)}set exp(t){typeof t=="number"?this.#e.exp=Re("setExpirationTime",t):t instanceof Date?this.#e.exp=Re("setExpirationTime",Oe(t)):this.#e.exp=Oe(new Date)+Zt(t)}set iat(t){t===void 0?this.#e.iat=Oe(new Date):t instanceof Date?this.#e.iat=Re("setIssuedAt",Oe(t)):typeof t=="string"?this.#e.iat=Re("setIssuedAt",Oe(new Date)+Zt(t)):this.#e.iat=Re("setIssuedAt",t)}},ds=class{#e;#t;#r;constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this.#e=t}setProtectedHeader(t){return Kr(this.#t,"setProtectedHeader"),this.#t=t,this}setUnprotectedHeader(t){return Kr(this.#r,"setUnprotectedHeader"),this.#r=t,this}async sign(t,e){if(!this.#t&&!this.#r)throw new dt("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Dn(this.#t,this.#r))throw new dt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let r={...this.#t,...this.#r},s=ii(dt,new Map([["b64",!0]]),e?.crit,this.#t,r),n=!0;if(s.has("b64")&&(n=this.#t.b64,typeof n!="boolean"))throw new dt('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:i}=r;if(typeof i!="string"||!i)throw new dt('JWS "alg" (Algorithm) Header Parameter missing or invalid');ci(i,t,"sign");let o,a;n?(o=Bt(this.#e),a=qt(o)):(a=this.#e,o="");let c,l;this.#t?(c=Bt(JSON.stringify(this.#t)),l=qt(c)):(c="",l=new Uint8Array);let u=Tn(l,qt("."),a),d=await Bn(t,i),m=await Wn(i,d,u),w={signature:Bt(m),payload:o};return this.#r&&(w.header=this.#r),this.#t&&(w.protected=c),w}},pi=class{#e;constructor(t){this.#e=new ds(t)}setProtectedHeader(t){return this.#e.setProtectedHeader(t),this}async sign(t,e){let r=await this.#e.sign(t,e);if(r.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}},fi=class{#e;#t;constructor(t={}){this.#t=new hi(t)}setIssuer(t){return this.#t.iss=t,this}setSubject(t){return this.#t.sub=t,this}setAudience(t){return this.#t.aud=t,this}setJti(t){return this.#t.jti=t,this}setNotBefore(t){return this.#t.nbf=t,this}setExpirationTime(t){return this.#t.exp=t,this}setIssuedAt(t){return this.#t.iat=t,this}setProtectedHeader(t){return this.#e=t,this}async sign(t,e){let r=new pi(this.#t.data());if(r.setProtectedHeader(this.#e),Array.isArray(this.#e?.crit)&&this.#e.crit.includes("b64")&&this.#e.b64===!1)throw new In("JWTs MUST NOT use unencoded payload");return r.sign(t,e)}};function Jt(t){let e=t?.modulusLength??2048;if(typeof e!="number"||e<2048)throw new Z("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return e}async function mi(t,e){let r,s;switch(t){case"PS256":case"PS384":case"PS512":r={name:"RSA-PSS",hash:`SHA-${t.slice(-3)}`,publicExponent:Uint8Array.of(1,0,1),modulusLength:Jt(e)},s=["sign","verify"];break;case"RS256":case"RS384":case"RS512":r={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${t.slice(-3)}`,publicExponent:Uint8Array.of(1,0,1),modulusLength:Jt(e)},s=["sign","verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":r={name:"RSA-OAEP",hash:`SHA-${parseInt(t.slice(-3),10)||1}`,publicExponent:Uint8Array.of(1,0,1),modulusLength:Jt(e)},s=["decrypt","unwrapKey","encrypt","wrapKey"];break;case"ES256":r={name:"ECDSA",namedCurve:"P-256"},s=["sign","verify"];break;case"ES384":r={name:"ECDSA",namedCurve:"P-384"},s=["sign","verify"];break;case"ES512":r={name:"ECDSA",namedCurve:"P-521"},s=["sign","verify"];break;case"Ed25519":case"EdDSA":{s=["sign","verify"],r={name:"Ed25519"};break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{s=["sign","verify"],r={name:t};break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{s=["deriveBits"];let n=e?.crv??"P-256";switch(n){case"P-256":case"P-384":case"P-521":{r={name:"ECDH",namedCurve:n};break}case"X25519":r={name:"X25519"};break;default:throw new Z("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519")}break}default:throw new Z('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return crypto.subtle.generateKey(r,e?.extractable??!1,s)}var _i="https://id.botparty.club",bi="EdDSA",wi=15,Br=6e4,xi=3e4,ki="5m",Ai=3,Si=["brave","calm","cosmic","eager","fair","gentle","happy","keen","lively","noble","proud","quick","rare","sharp","swift","true","vivid","warm","wild","bold","cool","fast","grand","just","kind","lean","mild","neat","pale","rich","safe","tall","vast","wise","bright","dark","fierce","quiet","free","glad"],Ei=["lion","hawk","wolf","bear","fox","deer","owl","crane","whale","tiger","eagle","shark","raven","puma","lynx","orca","swan","viper","bison","cobra","finch","gecko","heron","ibex","jay","kite","lark","moth","newt","otter","perch","quail","robin","seal","toad","wren","yak","zebra","ant","bee"],M=class extends Error{code;statusCode;actionUrl;details;constructor(t){super(t.message),this.name="BotPartyError",this.code=t.code,this.statusCode=t.statusCode,this.actionUrl=t.actionUrl,this.details=t.details}},or=class extends M{constructor(t){super({code:"NAMESPACE_LOCKED",message:t.message,statusCode:423,actionUrl:t.actionUrl,details:{lockedAt:t.lockedAt,reason:t.reason}}),this.name="NamespaceLockedError"}},Tt=class extends M{amount;service;constructor(t){super({code:"PAYMENT_REQUIRED",message:t.message,statusCode:402,actionUrl:t.actionUrl}),this.name="PaymentRequiredError",this.amount=t.amount,this.service=t.service}},gt=class extends M{missingScopes;constructor(t){super({code:"INSUFFICIENT_PERMISSION",message:t.message,statusCode:403,actionUrl:t.actionUrl}),this.name="InsufficientPermissionError",this.missingScopes=t.missingScopes}},$t=class extends M{constructor(t){super({code:"LINK_REQUIRED",message:t.message,statusCode:403,actionUrl:t.actionUrl}),this.name="LinkRequiredError"}};function Gr(t){let e=fs(4);return t[e.readUInt32BE(0)%t.length]}function Ti(){return`${Gr(Si)}-${Gr(Ei)}`}function $i(){let t=Ti(),e=fs(2).toString("hex");return`${t}-${e}`}function Ci(){return we(vi(),".botparty")}function ar(t){Et(t)||gi(t,{recursive:!0,mode:448})}function Oi(t){let e=we(t,"identity.json");if(!Et(e))return null;try{return JSON.parse(hs(e,"utf-8"))}catch{return null}}function ms(t,e){ar(t);let r=we(t,"identity.json"),s=r+".tmp";nr(s,JSON.stringify(e,null,2),{mode:384}),ps(s,r)}function Ri(t){let e=we(t,"private.pem");if(!Et(e))return null;try{return hs(e,"utf-8")}catch{return null}}function gs(t,e){ar(t);let r=we(t,"private.pem"),s=r+".tmp";nr(s,e,{mode:384}),ps(s,r)}function zr(t){for(let e of["identity.json","private.pem"]){let r=we(t,e);Et(r)&&ir(r)}}function Pi(t){let e=we(t,"rotation.lock");ar(t);for(let r=0;r<2;r++)try{nr(e,`${process.pid}:${Date.now()}`,{flag:"wx",mode:384});return}catch(s){if(s.code!=="EEXIST")throw s;try{let n=yi(e);if(Date.now()-n.mtimeMs>xi){ir(e);continue}}catch{continue}throw s}}function Ii(t){try{ir(we(t,"rotation.lock"))}catch{}}async function ys(t){let e={extractable:!0};t==="EdDSA"&&(e.crv="Ed25519");let{privateKey:r,publicKey:s}=await mi(t,e),n=await ni(r),i=await si(s);return{privateKey:r,publicKey:s,privatePem:n,publicPem:i}}async function Ni(t,e,r){let s=await cs(e,r);return(await new ds(new TextEncoder().encode(t)).setProtectedHeader({alg:r}).sign(s)).signature}async function Xt(t,e,r,s,n){let i=s,o=await cs(r,i);return new fi({...n}).setProtectedHeader({alg:i,kid:e}).setIssuer(t).setSubject(t).setIssuedAt().setExpirationTime(ki).sign(o)}async function oe(t,e,r={}){let{token:s,...n}=r,i=new Headers(n.headers);return i.set("Content-Type","application/json"),s&&i.set("Authorization",`Bearer ${s}`),fetch(`${t}${e}`,{...n,headers:i})}function Zr(t,e){try{let r=new URL(t),s=new URL(e);return r.hostname===s.hostname&&r.port===s.port&&r.protocol===s.protocol?t:`${e}/${r.hostname}${r.pathname}${r.search}`}catch{return`${e}/${t}`}}async function St(t){try{return await t.clone().json()}catch{return null}}function pt(t){let e=t.error,r,s,n,i={};if(typeof e=="object"&&e!==null){let o=e;r=o.code||"UNKNOWN",s=o.message||t.message||"Request failed",n=o.actionUrl||t.actionUrl||o.payTo||t.payTo,i=o}else r=(typeof e=="string"?e:t.code)||"UNKNOWN",s=t.message||(typeof e=="string"?e:"Request failed"),n=t.actionUrl||t.payTo,i=t;return{code:r.toUpperCase(),message:s,actionUrl:n,extra:i}}var Di=class{constructor(t,e){this.client=t,this.keyId=e}get id(){return this.keyId}async info(){return this.client.keys.get(this.keyId)}async update(t){return this.client.keys.update(this.keyId,t)}async delete(){return this.client.keys.delete(this.keyId)}async rotate(){return this.client.keys.rotate(this.keyId)}async invalidate(t){return this.client.keys.invalidate(this.keyId,t)}},Ui=class{constructor(t){this.client=t}async list(){let t=await this.client.generateToken(),e=await oe(this.client.serverUrl,"/api/v1/namespaces/keys",{token:t});if(!e.ok)throw await this.client._apiError(e);return(await e.json()).data}async get(t){let e=(await this.list()).find(r=>r.id===t);if(!e)throw new M({code:"KEY_NOT_FOUND",message:`Key ${t} not found`,statusCode:404});return e}async add(t){let e=await this.client.generateToken(),r=await oe(this.client.serverUrl,"/api/v1/namespaces/keys",{method:"POST",token:e,body:JSON.stringify(t)});if(!r.ok)throw await this.client._apiError(r);return r.json()}async update(t,e){let r=await this.client.generateToken(),s=await oe(this.client.serverUrl,`/api/v1/namespaces/keys/${t}`,{method:"PATCH",token:r,body:JSON.stringify(e)});if(!s.ok)throw await this.client._apiError(s);return s.json()}async delete(t){let e=await this.client.generateToken(),r=await oe(this.client.serverUrl,`/api/v1/namespaces/keys/${t}`,{method:"DELETE",token:e});if(!r.ok&&r.status!==204)throw await this.client._apiError(r)}async rotate(t){let e=this.client.getIdentity();if(!e)throw new Error("Not registered");let r=this.client.getPrivateKey();if(!r)throw new Error("Private key not found");let s=t||e.keyId;if(s!==e.keyId)throw new M({code:"CANNOT_ROTATE_OTHER_KEY",message:"Can only rotate the current machine key from this client. Use the server API directly for other keys.",statusCode:400});let n=await ys(e.algorithm),i=await Xt(e.namespace,e.keyId,r,e.algorithm),o=await oe(e.serverUrl,`/api/v1/namespaces/keys/${s}/rotate`,{method:"POST",token:i,body:JSON.stringify({newPublicKey:n.publicPem})});if(!o.ok)throw await this.client._apiError(o);let a=await o.json();return gs(this.client.stateDir,n.privatePem),ms(this.client.stateDir,{...e,rotatedAt:a.rotatedAt}),a}async rotateCurrent(){return this.rotate()}async invalidate(t,e){let r=await this.client.generateToken(),s=await oe(this.client.serverUrl,`/api/v1/namespaces/keys/${t}/invalidate`,{method:"POST",token:r,body:JSON.stringify({reason:e})});if(!s.ok)throw await this.client._apiError(s)}},vs=class{serverUrl;stateDir;proxyUrl;keys;algorithm;rotationTTL;inviteToken;_rotationPromise=null;constructor(t={}){this.serverUrl=(t.serverUrl||ht("BOTPARTY_SERVER_URL")||_i).replace(/\/$/,""),this.proxyUrl=(t.proxyUrl||ht("BOTPARTY_PROXY_URL")||ht("KEYCHAINS_PROXY_URL")||"https://keychains.dev").replace(/\/$/,""),this.stateDir=t.stateDir||ht("BOTPARTY_STATE_DIR")||Ci(),this.algorithm=t.algorithm||bi,this.rotationTTL=t.rotationTTL||wi,this.inviteToken=t.inviteToken||ht("BOTPARTY_INVITE_TOKEN"),this.keys=new Ui(this)}getIdentity(){return Oi(this.stateDir)}getPrivateKey(){return Ri(this.stateDir)}isRegistered(){return this.getIdentity()!==null&&this.getPrivateKey()!==null}async register(t,e,r){let s=t,n=0,i=r?.inviteToken||this.inviteToken;for(;n<Ai;){s||(s=$i());let o=e||s,a=await ys(this.algorithm),c=await oe(this.serverUrl,"/api/v1/namespaces/register",{method:"POST",body:JSON.stringify({namespace:s,publicKey:a.publicPem,rotationTTL:this.rotationTTL,...i&&{inviteToken:i}})}),l=await c.json();if(l.status==="already_registered")throw new M({code:"ALREADY_REGISTERED",message:`Namespace "${s}" is already registered`,statusCode:409});if(c.status===409&&!t){s=void 0,n++;continue}if(!c.ok)throw new M({code:l.error||"REGISTRATION_FAILED",message:l.message||l.error||"Registration failed",statusCode:c.status});let u=l.challenge,d=await Ni(u,a.privatePem,this.algorithm),m=await oe(this.serverUrl,"/api/v1/namespaces/register/verify",{method:"POST",body:JSON.stringify({namespace:s,challenge:u,signature:d})});if(!m.ok)throw await this._apiError(m);let w=await m.json();return gs(this.stateDir,a.privatePem),ms(this.stateDir,{serverUrl:this.serverUrl,namespace:s,keyId:w.keyId,algorithm:this.algorithm,rotatedAt:w.rotatedAt,rotationTTL:w.rotationTTL,label:o,...w.parentNamespace&&{parentNamespace:w.parentNamespace},...w.inheritedScopes&&{inheritedScopes:w.inheritedScopes}}),w}throw new M({code:"REGISTRATION_FAILED",message:"Failed to find available namespace after retries",statusCode:409})}async ensureRegistered(){let t=this.getIdentity();if(t&&this.getPrivateKey())return t;await this.register(void 0,void 0,{inviteToken:this.inviteToken});let e=this.getIdentity();if(!e)throw new Error("Registration succeeded but identity could not be read");return e}async ensureFreshKey(){if(this._rotationPromise)return this._rotationPromise;let t=this.getIdentity();if(!t)throw new Error("Not registered");let e=new Date(t.rotatedAt).getTime()+t.rotationTTL*6e4;if(Date.now()>=e-Br)return this._rotationPromise=this._lockedRotate().finally(()=>{this._rotationPromise=null}),this._rotationPromise}async _lockedRotate(){Pi(this.stateDir);try{let t=this.getIdentity();if(!t)throw new Error("Not registered");let e=new Date(t.rotatedAt).getTime()+t.rotationTTL*6e4;if(Date.now()<e-Br)return;await this.keys.rotateCurrent()}finally{Ii(this.stateDir)}}async generateToken(t){await this.ensureRegistered(),await this.ensureFreshKey();let e=this.getIdentity(),r=this.getPrivateKey();return Xt(e.namespace,e.keyId,r,e.algorithm,t)}async fetch(t,e={}){let r=await this.generateToken(),s=Zr(t,this.proxyUrl),n=new Headers(e.headers);n.set("X-Proxy-Authorization",`Bearer ${r}`);let i=await fetch(s,{...e,headers:n});if(i.status===401){let o=await St(i);if(o){let{code:a}=pt(o);if(a==="KEY_STALE"){await this._lockedRotate();let c=await this.generateToken(),l=new Headers(e.headers);l.set("X-Proxy-Authorization",`Bearer ${c}`),i=await fetch(s,{...e,headers:l})}}}if(i.status===403){let o=await St(i);if(o){let a=typeof o.error=="string"?o.error:o.error?.code;if(a==="wrong_proxy"&&o.proxyUrl){let u=o.proxyUrl.replace(/\/$/,""),d=Zr(t,u),m=new Headers(e.headers);return m.set("X-Proxy-Authorization",`Bearer ${r}`),fetch(d,{...e,headers:m})}let c=o.approval_url||o.authorizationUrl;if(c){let u=a==="scope_refused",d=o.missing_scopes||o.missingScopes;throw u||a==="insufficient_scope"||a==="permission_denied"||a==="scope_not_approved"||a==="permission_needs_revalidation"?new gt({message:o.message||"Missing required credentials",actionUrl:c,missingScopes:d}):new $t({message:o.message||"Missing required credentials",actionUrl:c})}let{code:l}=pt(o);Jr(l)&&Yr(i.status,o,this.getIdentity(),this.serverUrl)}}if([401,402,423].includes(i.status)){let o=await St(i);if(o){let{code:a}=pt(o);(Jr(a)||i.status===402||i.status===423)&&Yr(i.status,o,this.getIdentity(),this.serverUrl)}}return i}async info(t){let e=t||this.getIdentity()?.namespace;if(!e)throw new Error("Not registered and no namespace provided");let r=await oe(this.serverUrl,`/api/v1/namespaces/${e}/info`);if(!r.ok)throw await this._apiError(r);return r.json()}async destroy(){let t=await this.generateToken(),e=await oe(this.serverUrl,"/api/v1/namespaces",{method:"DELETE",token:t});if(!e.ok&&e.status!==204)throw await this._apiError(e);zr(this.stateDir)}async link(){let t=this.getIdentity();if(!t)throw new Error("Not registered");let e=this.getPrivateKey();if(!e)throw new Error("Private key not found");let r=await Xt(t.namespace,t.keyId,e,t.algorithm,{act:"link"});return{url:`${t.serverUrl}/namespaces/${t.namespace}/link?jwt=${r}`}}whoami(){let t=this.getIdentity();if(!t)return null;let e=new Date(new Date(t.rotatedAt).getTime()+t.rotationTTL*6e4).toISOString();return{namespace:t.namespace,keyId:t.keyId,algorithm:t.algorithm,rotationTTL:t.rotationTTL,rotatedAt:t.rotatedAt,staleAt:e,label:t.label,serverUrl:t.serverUrl}}key(t){return new Di(this,t)}reset(){zr(this.stateDir)}async _apiError(t){let e=await St(t);if(!e)return new M({code:"UNKNOWN",message:`Request failed with status ${t.status}`,statusCode:t.status});let{code:r,message:s,actionUrl:n}=pt(e);return new M({code:r,message:s,statusCode:t.status,actionUrl:n})}},ji=new Set(["NAMESPACE_LOCKED","LOCKUP_TRIGGERED","PAYMENT_REQUIRED","LINK_REQUIRED","INSUFFICIENT_SCOPE","PERMISSION_DENIED","KEY_STALE","KEY_EXPIRED"]);function Jr(t){return ji.has(t.toUpperCase())}function Yr(t,e,r,s){let{code:n,message:i,actionUrl:o,extra:a}=pt(e),c=r?.namespace||"",l=r?.serverUrl||s;throw n==="NAMESPACE_LOCKED"||n==="LOCKUP_TRIGGERED"||t===423?new or({message:i||"Namespace is locked",actionUrl:o||`${l}/namespaces/${c}/unlock`,lockedAt:a.lockedAt,reason:a.reason}):n==="PAYMENT_REQUIRED"||t===402?new Tt({message:i,actionUrl:o,amount:a.amount||e.amount,service:a.service||e.service}):n==="LINK_REQUIRED"?new $t({message:i,actionUrl:o||`${l}/namespaces/${c}/link`}):n==="INSUFFICIENT_SCOPE"||n==="PERMISSION_DENIED"||t===403?new gt({message:i,actionUrl:o,missingScopes:a.missingScopes||a.missing_scopes}):new M({code:n,message:i,statusCode:t,actionUrl:o})}function ht(t){if(typeof process<"u"&&process.env)return process.env[t]}Sr();import{writeFileSync as Us}from"fs";import{readFileSync as It}from"fs";import{basename as ho}from"path";var Qi="\x1B[1m",eo="\x1B[2m",to="\x1B[31m",ro="\x1B[32m",so="\x1B[33m",no="\x1B[36m",Xe="\x1B[0m";function A(t){return`${Qi}${t}${Xe}`}function O(t){return`${eo}${t}${Xe}`}function R(t){return`${to}${t}${Xe}`}function H(t){return`${ro}${t}${Xe}`}function K(t){return`${so}${t}${Xe}`}function b(t){return`${no}${t}${Xe}`}import{readFileSync as io,writeFileSync as oo,existsSync as Ps,mkdirSync as ao}from"node:fs";import{join as Is}from"node:path";var Ns="auth-capability-cache.json",co=1440*60*1e3;function lo(t){let e=Is(t,Ns);if(!Ps(e))return{};try{return JSON.parse(io(e,"utf-8"))}catch{return{}}}function uo(t,e){Ps(t)||ao(t,{recursive:!0,mode:448}),oo(Is(t,Ns),JSON.stringify(e,null,2))}async function Ds(t,e){let r=lo(e),s=r[t];if(s&&Date.now()-s.checkedAt<co)return s.supportsBotparty;let n=!1;try{let i=new AbortController,o=setTimeout(()=>i.abort(),3e3),a=await fetch(`https://${t}/api/botparty/auth/me`,{method:"HEAD",signal:i.signal});clearTimeout(o),n=a.ok||a.status===401}catch{n=!1}r[t]={supportsBotparty:n,checkedAt:Date.now()};try{uo(e,r)}catch{}return n}function Er(t,e,r,s){let n=(Date.now()-s)/1e3,i=e.headers.get("content-type")||"",o={http_code:e.status,http_connect:0,http_version:"1.1",response_code:e.status,content_type:i,size_download:r,size_header:0,size_request:0,size_upload:0,speed_download:n>0?Math.round(r/n):0,speed_upload:0,time_appconnect:n,time_connect:n,time_namelookup:0,time_pretransfer:n,time_redirect:0,time_starttransfer:n,time_total:n,url_effective:"",num_connects:1,num_redirects:0,redirect_url:"",ssl_verify_result:0,stdout:"-",stderr:"-",exitcode:0,errormsg:"",method:"",scheme:"",filename_effective:"",onerror:"",urlnum:0},a=t;return a=a.replace(/\\n/g,`
46
46
  `),a=a.replace(/\\r/g,"\r"),a=a.replace(/\\t/g," "),a=a.replace(/\\\\/g,"\\"),a=a.replace(/%\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g,(c,l)=>l in o?String(o[l]):c),a}function po(t,e,r){let s=[],n;try{let i=new URL(e);n=i.pathname+i.search}catch{n=e}s.push(`> ${t} ${n} HTTP/1.1`);try{let i=new URL(e);s.push(`> Host: ${i.host}`)}catch{}for(let[i,o]of Object.entries(r))i.toLowerCase()!=="host"&&s.push(`> ${i}: ${o}`);return s.push(">"),s.join(`
47
47
  `)}function fo(t,e,r){let s=[];return s.push(`< HTTP/1.1 ${t} ${e}`),r.forEach((n,i)=>{s.push(`< ${i}: ${n}`)}),s.push("<"),s.join(`
48
48
  `)}function js(t,e,r){let s=[];return s.push(`HTTP/1.1 ${t} ${e}`),r.forEach((n,i)=>{s.push(`${i}: ${n}`)}),s.push(""),s.join(`
@@ -51,95 +51,95 @@ ${r}
51
51
  `);let u=fo(t.status,t.statusText,t.headers);process.stderr.write(u+`
52
52
  `)}if(e.dumpHeader){let l=mo(t.status,t.statusText,t.headers);e.dumpHeader==="-"?process.stdout.write(l):Us(e.dumpHeader,l)}e.fail&&t.status>=400&&(e.failWithBody||(e.silent||process.stderr.write(`curl: (22) The requested URL returned error: ${t.status} ${t.statusText}
53
53
  `),e.writeOut&&process.stdout.write(Er(e.writeOut,t,a,i)),process.exit(22)));let c="";e.include&&(c+=js(t.status,t.statusText,t.headers)),e.head?!e.include&&!e.verbose&&(c+=js(t.status,t.statusText,t.headers)):c+=o,e.output?e.output==="-"?process.stdout.write(c):Us(e.output,c):c&&process.stdout.write(c),e.failWithBody&&t.status>=400&&(e.silent||process.stderr.write(`curl: (22) The requested URL returned error: ${t.status} ${t.statusText}
54
- `),e.writeOut&&process.stdout.write(Er(e.writeOut,t,a,i)),process.exit(22)),e.writeOut&&process.stdout.write(Er(e.writeOut,t,a,i))}function Hs(t){return t instanceof H&&typeof t.actionUrl=="string"&&!!t.actionUrl}async function Vs(t,e){let r=new Pt;r.exitOverride(),r.name("botparty curl").argument("[url]","URL to request").description("Authenticated fetch \u2014 direct JWT for BotParty-native servers, proxied via Keychains for everything else").allowUnknownOption(!1).option("--wait-on-authlink","If credentials are required, wait for user approval then retry automatically").option("--wait-timeout <seconds>","Max seconds to wait for approval when using --wait-on-authlink (default: no limit)").option("-X, --request <method>","Specify request method").option("-H, --header <header...>","Pass custom header(s) to server (repeatable)").option("-d, --data <data...>","HTTP POST data (repeatable)").option("--data-raw <data...>","HTTP POST data without @ file interpretation (repeatable)").option("--data-binary <data...>","HTTP POST binary data (repeatable)").option("--data-urlencode <data...>","HTTP POST data URL encoded (repeatable)").option("--data-ascii <data...>","HTTP POST ASCII data (repeatable)").option("--json <data...>","HTTP POST JSON data (sets Content-Type and Accept headers)").option("-F, --form <name=content...>","Specify multipart MIME data (repeatable)").option("--form-string <name=content...>","Specify multipart MIME data (no file interpretation)").option("-v, --verbose","Make the operation more talkative").option("-i, --include","Include response headers in output").option("-I, --head","Show document info only (HEAD request)").option("-s, --silent","Silent mode").option("-S, --show-error","Show error even when -s is used").option("-o, --output <file>","Write to file instead of stdout").option("-D, --dump-header <file>","Write response headers to file").option("-w, --write-out <format>","Display information after transfer").option("-f, --fail","Fail fast with no output on HTTP errors").option("--fail-with-body","Fail with output on HTTP errors").option("-L, --location","Follow redirects").option("--max-redirs <num>","Maximum number of redirects").option("--location-trusted","Follow redirects and send auth to other hosts").option("-A, --user-agent <name>","Send User-Agent to server").option("-e, --referer <URL>","Referrer URL").option("-b, --cookie <data...>","Send cookies from string/file (repeatable)").option("-c, --cookie-jar <filename>","Write cookies to filename after operation").option("-u, --user <user:password>","Server user and password").option("--compressed","Request compressed response").option("-r, --range <range>","Retrieve only this byte range").option("--connect-timeout <seconds>","Maximum time for connection").option("-m, --max-time <seconds>","Maximum time for the transfer").option("--retry <num>","Retry request if transient problems occur").option("--retry-delay <seconds>","Wait time between retries").option("--retry-max-time <seconds>","Retry only within this period").option("--retry-all-errors","Retry on all errors").option("--url <url>","URL to work with").option("-G, --get","Put the post data in the URL and use GET").option("-T, --upload-file <file>","Transfer local FILE to destination").option("-k, --insecure","Allow insecure server connections").option("--cacert <file>","CA certificate to verify peer against").option("--capath <dir>","CA directory to verify peer against").option("--cert <cert[:passwd]>","Client certificate file and password").option("--cert-type <type>","Certificate type (DER/PEM/ENG)").option("--key <key>","Private key file name").option("--key-type <type>","Private key file type (DER/PEM/ENG)").option("--pass <phrase>","Pass phrase for the private key").option("--ciphers <list>","SSL ciphers to use").option("-1, --tlsv1","Use TLSv1.0 or greater").option("--tlsv1.0","Use TLSv1.0 or greater").option("--tlsv1.1","Use TLSv1.1 or greater").option("--tlsv1.2","Use TLSv1.2 or greater").option("--tlsv1.3","Use TLSv1.3 or greater").option("--ssl","Try SSL/TLS").option("--ssl-reqd","Require SSL/TLS").option("--ssl-no-revoke","Disable cert revocation checks").option("--no-alpn","Disable the ALPN TLS extension").option("--no-npn","Disable the NPN TLS extension").option("--no-sessionid","Disable SSL session-ID reusing").option("-0, --http1.0","Use HTTP 1.0").option("--http1.1","Use HTTP 1.1").option("--http2","Use HTTP 2").option("--http2-prior-knowledge","Use HTTP 2 without HTTP/1.1 Upgrade").option("--http3","Use HTTP v3").option("-4, --ipv4","Resolve names to IPv4 addresses").option("-6, --ipv6","Resolve names to IPv6 addresses").option("-x, --proxy <[protocol://]host[:port]>","Use this proxy").option("-U, --proxy-user <user:password>","Proxy user and password").option("--noproxy <no-proxy-list>","List of hosts which do not use proxy").option("-n, --netrc","Must read .netrc for user name and password").option("--netrc-optional","Use either .netrc or URL").option("--netrc-file <filename>","Specify FILE for netrc").option("-K, --config <file>","Read config from a file").option("--create-dirs","Create necessary local directory hierarchy").option("--raw",'Do HTTP "raw"; no transfer decoding').option("--no-keepalive","Disable TCP keepalive on the connection").option("--keepalive-time <seconds>","Interval time for keepalive probes").option("-N, --no-buffer","Disable buffering of the output stream").option("-#, --progress-bar","Display transfer progress as a bar").option("--stderr <file>","Where to redirect stderr").option("--trace <file>","Write a debug trace to FILE").option("--trace-ascii <file>","Like --trace, but without hex output").option("--trace-time","Add time stamps to trace/verbose output").option("--path-as-is","Do not squash .. sequences in URL path").option("--tcp-fastopen","Use TCP Fast Open").option("--tcp-nodelay","Use the TCP_NODELAY option").option("-j, --junk-session-cookies","Ignore session cookies read from file").option("-O, --remote-name","Write output to a file named as the remote file").option("--remote-name-all","Use the remote file name for all URLs").option("-R, --remote-time","Set the remote file time on the local output").option("-J, --remote-header-name","Use the header-provided filename").option("-C, --continue-at <offset>","Resumed transfer offset").option("-g, --globoff","Disable URL sequences and ranges using {} and []").option("--limit-rate <speed>","Limit transfer speed to RATE").option("--max-filesize <bytes>","Maximum file size to download").option("--interface <name>","Use network INTERFACE (or address)").option("--local-port <num/range>","Force use of RANGE for local port numbers").option("--dns-servers <addresses>","DNS server addrs to use").option("--dns-interface <interface>","Interface to use for DNS requests").option("--dns-ipv4-addr <address>","IPv4 address to use for DNS requests").option("--dns-ipv6-addr <address>","IPv6 address to use for DNS requests").option("--expect100-timeout <seconds>","How long to wait for 100-continue").option("--happy-eyeballs-timeout-ms <milliseconds>","Time for IPv6 before trying IPv4").action(async(n,i)=>{let o;try{let a=e(),c=n||i.url;c||(process.stderr.write(`curl: no URL specified!
54
+ `),e.writeOut&&process.stdout.write(Er(e.writeOut,t,a,i)),process.exit(22)),e.writeOut&&process.stdout.write(Er(e.writeOut,t,a,i))}function Hs(t){return t instanceof M&&typeof t.actionUrl=="string"&&!!t.actionUrl}async function Vs(t,e){let r=new Pt;r.exitOverride(),r.name("botparty curl").argument("[url]","URL to request").description("Authenticated fetch \u2014 direct JWT for BotParty-native servers, proxied via Keychains for everything else").allowUnknownOption(!1).option("--wait-on-authlink","If credentials are required, wait for user approval then retry automatically").option("--wait-timeout <seconds>","Max seconds to wait for approval when using --wait-on-authlink (default: no limit)").option("-X, --request <method>","Specify request method").option("-H, --header <header...>","Pass custom header(s) to server (repeatable)").option("-d, --data <data...>","HTTP POST data (repeatable)").option("--data-raw <data...>","HTTP POST data without @ file interpretation (repeatable)").option("--data-binary <data...>","HTTP POST binary data (repeatable)").option("--data-urlencode <data...>","HTTP POST data URL encoded (repeatable)").option("--data-ascii <data...>","HTTP POST ASCII data (repeatable)").option("--json <data...>","HTTP POST JSON data (sets Content-Type and Accept headers)").option("-F, --form <name=content...>","Specify multipart MIME data (repeatable)").option("--form-string <name=content...>","Specify multipart MIME data (no file interpretation)").option("-v, --verbose","Make the operation more talkative").option("-i, --include","Include response headers in output").option("-I, --head","Show document info only (HEAD request)").option("-s, --silent","Silent mode").option("-S, --show-error","Show error even when -s is used").option("-o, --output <file>","Write to file instead of stdout").option("-D, --dump-header <file>","Write response headers to file").option("-w, --write-out <format>","Display information after transfer").option("-f, --fail","Fail fast with no output on HTTP errors").option("--fail-with-body","Fail with output on HTTP errors").option("-L, --location","Follow redirects").option("--max-redirs <num>","Maximum number of redirects").option("--location-trusted","Follow redirects and send auth to other hosts").option("-A, --user-agent <name>","Send User-Agent to server").option("-e, --referer <URL>","Referrer URL").option("-b, --cookie <data...>","Send cookies from string/file (repeatable)").option("-c, --cookie-jar <filename>","Write cookies to filename after operation").option("-u, --user <user:password>","Server user and password").option("--compressed","Request compressed response").option("-r, --range <range>","Retrieve only this byte range").option("--connect-timeout <seconds>","Maximum time for connection").option("-m, --max-time <seconds>","Maximum time for the transfer").option("--retry <num>","Retry request if transient problems occur").option("--retry-delay <seconds>","Wait time between retries").option("--retry-max-time <seconds>","Retry only within this period").option("--retry-all-errors","Retry on all errors").option("--url <url>","URL to work with").option("-G, --get","Put the post data in the URL and use GET").option("-T, --upload-file <file>","Transfer local FILE to destination").option("-k, --insecure","Allow insecure server connections").option("--cacert <file>","CA certificate to verify peer against").option("--capath <dir>","CA directory to verify peer against").option("--cert <cert[:passwd]>","Client certificate file and password").option("--cert-type <type>","Certificate type (DER/PEM/ENG)").option("--key <key>","Private key file name").option("--key-type <type>","Private key file type (DER/PEM/ENG)").option("--pass <phrase>","Pass phrase for the private key").option("--ciphers <list>","SSL ciphers to use").option("-1, --tlsv1","Use TLSv1.0 or greater").option("--tlsv1.0","Use TLSv1.0 or greater").option("--tlsv1.1","Use TLSv1.1 or greater").option("--tlsv1.2","Use TLSv1.2 or greater").option("--tlsv1.3","Use TLSv1.3 or greater").option("--ssl","Try SSL/TLS").option("--ssl-reqd","Require SSL/TLS").option("--ssl-no-revoke","Disable cert revocation checks").option("--no-alpn","Disable the ALPN TLS extension").option("--no-npn","Disable the NPN TLS extension").option("--no-sessionid","Disable SSL session-ID reusing").option("-0, --http1.0","Use HTTP 1.0").option("--http1.1","Use HTTP 1.1").option("--http2","Use HTTP 2").option("--http2-prior-knowledge","Use HTTP 2 without HTTP/1.1 Upgrade").option("--http3","Use HTTP v3").option("-4, --ipv4","Resolve names to IPv4 addresses").option("-6, --ipv6","Resolve names to IPv6 addresses").option("-x, --proxy <[protocol://]host[:port]>","Use this proxy").option("-U, --proxy-user <user:password>","Proxy user and password").option("--noproxy <no-proxy-list>","List of hosts which do not use proxy").option("-n, --netrc","Must read .netrc for user name and password").option("--netrc-optional","Use either .netrc or URL").option("--netrc-file <filename>","Specify FILE for netrc").option("-K, --config <file>","Read config from a file").option("--create-dirs","Create necessary local directory hierarchy").option("--raw",'Do HTTP "raw"; no transfer decoding').option("--no-keepalive","Disable TCP keepalive on the connection").option("--keepalive-time <seconds>","Interval time for keepalive probes").option("-N, --no-buffer","Disable buffering of the output stream").option("-#, --progress-bar","Display transfer progress as a bar").option("--stderr <file>","Where to redirect stderr").option("--trace <file>","Write a debug trace to FILE").option("--trace-ascii <file>","Like --trace, but without hex output").option("--trace-time","Add time stamps to trace/verbose output").option("--path-as-is","Do not squash .. sequences in URL path").option("--tcp-fastopen","Use TCP Fast Open").option("--tcp-nodelay","Use the TCP_NODELAY option").option("-j, --junk-session-cookies","Ignore session cookies read from file").option("-O, --remote-name","Write output to a file named as the remote file").option("--remote-name-all","Use the remote file name for all URLs").option("-R, --remote-time","Set the remote file time on the local output").option("-J, --remote-header-name","Use the header-provided filename").option("-C, --continue-at <offset>","Resumed transfer offset").option("-g, --globoff","Disable URL sequences and ranges using {} and []").option("--limit-rate <speed>","Limit transfer speed to RATE").option("--max-filesize <bytes>","Maximum file size to download").option("--interface <name>","Use network INTERFACE (or address)").option("--local-port <num/range>","Force use of RANGE for local port numbers").option("--dns-servers <addresses>","DNS server addrs to use").option("--dns-interface <interface>","Interface to use for DNS requests").option("--dns-ipv4-addr <address>","IPv4 address to use for DNS requests").option("--dns-ipv6-addr <address>","IPv6 address to use for DNS requests").option("--expect100-timeout <seconds>","How long to wait for 100-continue").option("--happy-eyeballs-timeout-ms <milliseconds>","Time for IPv6 before trying IPv4").action(async(n,i)=>{let o;try{let a=e(),c=n||i.url;c||(process.stderr.write(`curl: no URL specified!
55
55
  curl: try 'botparty curl --help' for more information
56
- `),process.exit(2));let l={};if(i.header)for(let I of i.header){let L=I.indexOf(":");if(L>0){let U=I.slice(0,L).trim(),ye=I.slice(L+1).trim();ye===""?delete l[U]:l[U]=ye}else I.endsWith(";")&&(l[I.slice(0,-1).trim()]="")}if(i.userAgent&&(l["User-Agent"]=i.userAgent),i.referer&&(l.Referer=i.referer),i.cookie&&(l.Cookie=i.cookie.join("; ")),i.user){let I=Buffer.from(i.user).toString("base64");l.Authorization=`Basic ${I}`}i.compressed&&(l["Accept-Encoding"]="gzip, deflate, br"),i.range&&(l.Range=`bytes=${i.range}`),i.json&&i.json.length>0&&(!l["Content-Type"]&&!l["content-type"]&&(l["Content-Type"]="application/json"),!l.Accept&&!l.accept&&(l.Accept="application/json"));let u=vo(i),d=go(i),m=c;if(i.get&&d){let I=m.includes("?")?"&":"?";m=m+I+d,d=void 0}if(!d&&Ms(i)){let I=new FormData,L=(U,ye)=>{let ue=U.indexOf("=");if(ue<=0)return;let ct=U.slice(0,ue),X=U.slice(ue+1);if(ye&&X.startsWith("@"))try{let Ft=It(X.slice(1)),xt=new Blob([Ft]);I.append(ct,xt,ho(X.slice(1)))}catch{process.stderr.write(`curl: (26) Failed to open/read local data from file: ${X.slice(1)}
57
- `),process.exit(26)}else I.append(ct,X)};if(i.form)for(let U of i.form)L(U,!0);if(i.formString)for(let U of i.formString)L(U,!1);d=I}if(i.uploadFile&&!d)try{d=It(i.uploadFile,"utf-8")}catch{process.stderr.write(`curl: (26) Failed to open/read local data from file: ${i.uploadFile}
58
- `),process.exit(26)}d&&!l["Content-Type"]&&!l["content-type"]&&(i.json&&i.json.length>0?l["Content-Type"]="application/json":l["Content-Type"]="application/x-www-form-urlencoded"),o={url:m,method:u,headers:l,body:typeof d=="string"?d:void 0};let x=Date.now(),R=!1;try{let I=new URL(o.url);R=await Ds(I.hostname,a.stateDir)}catch{}let Te=i.retry?parseInt(i.retry,10):0,le=i.retryDelay?parseInt(i.retryDelay,10)*1e3:1e3,re=null,se=null;for(let I=0;I<=Te;I++)try{if(R){let L=await a.generateToken(),U=new Headers(o.headers);if(U.set("Authorization",`Bearer ${L}`),se=await fetch(o.url,{method:o.method,headers:U,body:o.body}),se.status===401){await a.keys.rotateCurrent();let ye=await a.generateToken(),ue=new Headers(o.headers);ue.set("Authorization",`Bearer ${ye}`),se=await fetch(o.url,{method:o.method,headers:ue,body:o.body})}}else se=await a.fetch(o.url,{method:o.method,headers:o.headers,body:o.body});if(se.status>=500&&I<Te){re=new Error(`HTTP ${se.status}`),await new Promise(L=>setTimeout(L,le));continue}break}catch(L){if(re=L,I<Te){await new Promise(U=>setTimeout(U,le));continue}throw L}if(!se)throw re;await Ls(se,i,o.method,o.url,o.headers,x)}catch(a){if(i.silent&&!i.showError&&process.exit(1),Hs(a)){if(i.waitOnAuthlink){process.stderr.write(`
59
- `),process.stderr.write(` ${F("Authorization required:")} ${a.message}
56
+ `),process.exit(2));let l={};if(i.header)for(let P of i.header){let j=P.indexOf(":");if(j>0){let N=P.slice(0,j).trim(),ve=P.slice(j+1).trim();ve===""?delete l[N]:l[N]=ve}else P.endsWith(";")&&(l[P.slice(0,-1).trim()]="")}if(i.userAgent&&(l["User-Agent"]=i.userAgent),i.referer&&(l.Referer=i.referer),i.cookie&&(l.Cookie=i.cookie.join("; ")),i.user){let P=Buffer.from(i.user).toString("base64");l.Authorization=`Basic ${P}`}i.compressed&&(l["Accept-Encoding"]="gzip, deflate, br"),i.range&&(l.Range=`bytes=${i.range}`),i.json&&i.json.length>0&&(!l["Content-Type"]&&!l["content-type"]&&(l["Content-Type"]="application/json"),!l.Accept&&!l.accept&&(l.Accept="application/json"));let u=vo(i),d=go(i),m=c;if(i.get&&d){let P=m.includes("?")?"&":"?";m=m+P+d,d=void 0}if(!d&&Ms(i)){let P=new FormData,j=(N,ve)=>{let ue=N.indexOf("=");if(ue<=0)return;let ct=N.slice(0,ue),ee=N.slice(ue+1);if(ve&&ee.startsWith("@"))try{let Ft=It(ee.slice(1)),xt=new Blob([Ft]);P.append(ct,xt,ho(ee.slice(1)))}catch{process.stderr.write(`curl: (26) Failed to open/read local data from file: ${ee.slice(1)}
57
+ `),process.exit(26)}else P.append(ct,ee)};if(i.form)for(let N of i.form)j(N,!0);if(i.formString)for(let N of i.formString)j(N,!1);d=P}if(i.uploadFile&&!d)try{d=It(i.uploadFile,"utf-8")}catch{process.stderr.write(`curl: (26) Failed to open/read local data from file: ${i.uploadFile}
58
+ `),process.exit(26)}d&&!l["Content-Type"]&&!l["content-type"]&&(i.json&&i.json.length>0?l["Content-Type"]="application/json":l["Content-Type"]="application/x-www-form-urlencoded"),o={url:m,method:u,headers:l,body:typeof d=="string"?d:void 0};let w=Date.now(),I=!1;try{let P=new URL(o.url);I=await Ds(P.hostname,a.stateDir)}catch{}let ne=i.retry?parseInt(i.retry,10):0,ye=i.retryDelay?parseInt(i.retryDelay,10)*1e3:1e3,U=null,z=null;for(let P=0;P<=ne;P++)try{if(I){let j=await a.generateToken(),N=new Headers(o.headers);if(N.set("Authorization",`Bearer ${j}`),z=await fetch(o.url,{method:o.method,headers:N,body:o.body}),z.status===401){await a.keys.rotateCurrent();let ve=await a.generateToken(),ue=new Headers(o.headers);ue.set("Authorization",`Bearer ${ve}`),z=await fetch(o.url,{method:o.method,headers:ue,body:o.body})}}else z=await a.fetch(o.url,{method:o.method,headers:o.headers,body:o.body});if(z.status>=500&&P<ne){U=new Error(`HTTP ${z.status}`),await new Promise(j=>setTimeout(j,ye));continue}break}catch(j){if(U=j,P<ne){await new Promise(N=>setTimeout(N,ye));continue}throw j}if(!z)throw U;await Ls(z,i,o.method,o.url,o.headers,w)}catch(a){if(i.silent&&!i.showError&&process.exit(1),Hs(a)){if(i.waitOnAuthlink){process.stderr.write(`
59
+ `),process.stderr.write(` ${K("Authorization required:")} ${a.message}
60
60
  `),process.stderr.write(` ${O("Auth URL:")} ${b(a.actionUrl)}
61
61
  `),process.stderr.write(` ${O("Open this link to authorize, then the request will retry.")}
62
62
  `),process.stderr.write(`
63
- ${F("Waiting for user to approve...")}
64
- `);try{let c=i.waitTimeout?parseInt(i.waitTimeout,10)*1e3:void 0,l=2e3,u=c?Date.now()+c:1/0,d=0,m=!1;for(;Date.now()<u;){await new Promise(x=>setTimeout(x,l)),d++,d%30===0&&process.stderr.write(`
65
- `),process.stderr.write(O("."));try{let x=e();if(o){let R=await x.fetch(o.url,{method:o.method,headers:o.headers,body:o.body});process.stderr.write(`
63
+ ${K("Waiting for user to approve...")}
64
+ `);try{let c=i.waitTimeout?parseInt(i.waitTimeout,10)*1e3:void 0,l=2e3,u=c?Date.now()+c:1/0,d=0,m=!1;for(;Date.now()<u;){await new Promise(w=>setTimeout(w,l)),d++,d%30===0&&process.stderr.write(`
65
+ `),process.stderr.write(O("."));try{let w=e();if(o){let I=await w.fetch(o.url,{method:o.method,headers:o.headers,body:o.body});process.stderr.write(`
66
66
 
67
- ${j("\u2713")} Authorization approved!
67
+ ${H("\u2713")} Authorization approved!
68
68
 
69
- `),m=!0,await Ls(R,i,o.method,o.url,o.headers,Date.now());return}}catch(x){if(Hs(x))continue;throw x}}m||(process.stderr.write(`
69
+ `),m=!0,await Ls(I,i,o.method,o.url,o.headers,Date.now());return}}catch(w){if(Hs(w))continue;throw w}}m||(process.stderr.write(`
70
70
 
71
- ${P("Timed out waiting for approval.")}
71
+ ${R("Timed out waiting for approval.")}
72
72
 
73
73
  `),process.exit(1))}catch(c){process.stderr.write(`
74
74
 
75
- `),process.stderr.write(` ${P(c instanceof Error?c.message:String(c))}
75
+ `),process.stderr.write(` ${R(c instanceof Error?c.message:String(c))}
76
76
 
77
77
  `),process.exit(1)}}process.stderr.write(`
78
- `),process.stderr.write(` ${F("Credentials required:")} ${a.message}
78
+ `),process.stderr.write(` ${K("Credentials required:")} ${a.message}
79
79
  `),process.stderr.write(`
80
- `),process.stderr.write(` ${S("Authorize at:")}
80
+ `),process.stderr.write(` ${A("Authorize at:")}
81
81
  `),process.stderr.write(` ${b(a.actionUrl)}
82
82
  `),process.stderr.write(`
83
83
  `)}else process.stderr.write(`curl: (6) ${a instanceof Error?a.message:a}
84
84
  `);process.exit(1)}});try{await r.parseAsync(t,{from:"user"})}catch(n){if(n&&typeof n=="object"&&"exitCode"in n){let i=n;process.exit(i.exitCode)}throw n}}Dt();Hr();Qe();var yn=[{shorthand:"mongo",description:"MongoDB databases \u2014 create, manage credentials, backups"},{shorthand:"git",description:"Git repositories \u2014 create, push/pull, token management"},{shorthand:"s3",description:"S3 storage \u2014 buckets, presigned URLs, IAM credentials"},{shorthand:"deploy",description:"Deployments \u2014 deploy to Vercel with no account needed"},{shorthand:"domains",description:"Domains \u2014 register, configure DNS records"},{shorthand:"upstash",description:"Upstash \u2014 Redis, Vector indices, QStash queues"},{shorthand:"vps",description:"VPS \u2014 bare-metal servers, SSH sessions, command exec"},{shorthand:"vms",description:"VMs \u2014 Docker containers with persistent storage"}];function Na(){console.log(`
85
- ${S("botparty services")} \u2014 discover and manage BotParty-compatible services
85
+ ${A("botparty services")} \u2014 discover and manage BotParty-compatible services
86
86
 
87
- ${S("USAGE")}
87
+ ${A("USAGE")}
88
88
  botparty services <domain> [action] [--params]
89
89
 
90
90
  Use a full domain or a shorthand \u2014 e.g. ${b('"mongo"')} resolves to ${O("mongo.botparty.club")}.
91
91
  Omit the action to list all available actions on a service.
92
92
 
93
- ${S("EXAMPLES")}
93
+ ${A("EXAMPLES")}
94
94
  botparty services mongo ${O("List all actions on mongo.botparty.club")}
95
95
  botparty services mongo databases.list ${O("List your MongoDB databases")}
96
96
  botparty services mongo databases.create --slug my-db
97
97
  botparty services deploy projects.deploy --projectName my-site --file ./dist/
98
98
  botparty services example.com ${O("Discover actions on any domain")}
99
99
 
100
- ${S("BOTPARTY SERVICES")}
100
+ ${A("BOTPARTY SERVICES")}
101
101
  `);let t=Math.max(...yn.map(e=>e.shorthand.length));for(let e of yn){let r=e.shorthand.padEnd(t+2);console.log(` ${b(r)}${e.description}`)}console.log(`
102
102
  Any domain that publishes ${O("/.well-known/botparty/services.json")} is supported.
103
- `)}function Da(t){return t.includes(".")?t:`${t}.botparty.club`}async function vn(t){let e=process.argv.slice(2),r=e.findIndex(c=>c==="services"),s=r>=0?e.slice(r+1):[],n=s[0]&&!s[0].startsWith("-")?s[0]:void 0;if(!n){Na();return}let i=Da(n),o=s[1]&&!s[1].startsWith("-")?s[1]:void 0,a=s.slice(o?2:1);try{if(!o&&a.length===0)await Cr(i);else{let c=await we(i);!(o&&(c.actions.some(u=>u.slug===o)||c.actions.some(u=>u.slug.startsWith(o+"."))))&&c.defaultAction&&(a=s.slice(1),o=c.defaultAction),await Lr(i,o,a,t)}}catch(c){c.code==="ENOTFOUND"||c.cause?.code==="ENOTFOUND"?console.error(`\x1B[31mError:\x1B[0m Could not connect to ${i}`):c.message?console.error(`\x1B[31mError:\x1B[0m ${c.message}`):console.error(c),process.exit(1)}}Qe();var C=!1;function D(t){console.log(JSON.stringify({ok:!0,...t},null,2))}function T(t,e=1){C?console.log(JSON.stringify({ok:!1,error:{message:t}},null,2)):console.error(`${P("error")}: ${t}`),process.exit(e)}function Ua(t){if(C){let e={ok:!1};t instanceof H?e.error={code:t.code,message:t.message,statusCode:t.statusCode,...t.actionUrl&&{actionUrl:t.actionUrl},...t instanceof Tt&&t.amount&&{amount:t.amount},...t instanceof gt&&t.missingScopes&&{missingScopes:t.missingScopes}}:t instanceof Error?e.error={message:t.message}:e.error={message:String(t)},console.log(JSON.stringify(e,null,2)),process.exit(1)}t instanceof or&&(console.error(`
104
- ${P("NAMESPACE LOCKED")}: ${t.message}`),t.actionUrl&&console.error(`
103
+ `)}function Da(t){return t.includes(".")?t:`${t}.botparty.club`}async function vn(t){let e=process.argv.slice(2),r=e.findIndex(c=>c==="services"),s=r>=0?e.slice(r+1):[],n=s[0]&&!s[0].startsWith("-")?s[0]:void 0;if(!n){Na();return}let i=Da(n),o=s[1]&&!s[1].startsWith("-")?s[1]:void 0,a=s.slice(o?2:1);try{if(!o&&a.length===0)await Cr(i);else{let c=await xe(i);!(o&&(c.actions.some(u=>u.slug===o)||c.actions.some(u=>u.slug.startsWith(o+"."))))&&c.defaultAction&&(a=s.slice(1),o=c.defaultAction),await Lr(i,o,a,t)}}catch(c){c.code==="ENOTFOUND"||c.cause?.code==="ENOTFOUND"?console.error(`\x1B[31mError:\x1B[0m Could not connect to ${i}`):c.message?console.error(`\x1B[31mError:\x1B[0m ${c.message}`):console.error(c),process.exit(1)}}Qe();var C=!1;function L(t){console.log(JSON.stringify({ok:!0,...t},null,2))}function T(t,e=1){C?console.log(JSON.stringify({ok:!1,error:{message:t}},null,2)):console.error(`${R("error")}: ${t}`),process.exit(e)}function Ua(t){if(C){let e={ok:!1};t instanceof M?e.error={code:t.code,message:t.message,statusCode:t.statusCode,...t.actionUrl&&{actionUrl:t.actionUrl},...t instanceof Tt&&t.amount&&{amount:t.amount},...t instanceof gt&&t.missingScopes&&{missingScopes:t.missingScopes}}:t instanceof Error?e.error={message:t.message}:e.error={message:String(t)},console.log(JSON.stringify(e,null,2)),process.exit(1)}t instanceof or&&(console.error(`
104
+ ${R("NAMESPACE LOCKED")}: ${t.message}`),t.actionUrl&&console.error(`
105
105
  A human must unlock it at:
106
106
  ${b(t.actionUrl)}`),process.exit(1)),t instanceof Tt&&(console.error(`
107
- ${F("PAYMENT REQUIRED")}: ${t.message}`),t.amount&&console.error(` Amount: $${(t.amount/1e6).toFixed(6)}`),t.actionUrl&&console.error(`
107
+ ${K("PAYMENT REQUIRED")}: ${t.message}`),t.amount&&console.error(` Amount: $${(t.amount/1e6).toFixed(6)}`),t.actionUrl&&console.error(`
108
108
  Complete payment at:
109
109
  ${b(t.actionUrl)}`),process.exit(1)),t instanceof gt&&(console.error(`
110
- ${P("PERMISSION DENIED")}: ${t.message}`),t.missingScopes?.length&&console.error(` Missing scopes: ${t.missingScopes.join(", ")}`),t.actionUrl&&console.error(`
110
+ ${R("PERMISSION DENIED")}: ${t.message}`),t.missingScopes?.length&&console.error(` Missing scopes: ${t.missingScopes.join(", ")}`),t.actionUrl&&console.error(`
111
111
  Grant access at:
112
112
  ${b(t.actionUrl)}`),process.exit(1)),t instanceof $t&&(console.error(`
113
- ${F("LINK REQUIRED")}: ${t.message}`),t.actionUrl&&console.error(`
113
+ ${K("LINK REQUIRED")}: ${t.message}`),t.actionUrl&&console.error(`
114
114
  Link a human account at:
115
- ${b(t.actionUrl)}`),process.exit(1)),t instanceof H&&(console.error(`
116
- ${P(t.code)}: ${t.message}`),t.actionUrl&&console.error(`
115
+ ${b(t.actionUrl)}`),process.exit(1)),t instanceof M&&(console.error(`
116
+ ${R(t.code)}: ${t.message}`),t.actionUrl&&console.error(`
117
117
  ${b(t.actionUrl)}`),process.exit(1)),t instanceof Error&&(console.error(`
118
- ${P("error")}: ${t.message}`),process.exit(1)),console.error(t),process.exit(1)}var ja=new Set(["header","H"]);function La(t){let e=t.slice(2),r=[],s={},n="help",i="",o=0;e[0]&&!e[0].startsWith("-")&&(n=e[0],o=1,["keys","connections","conn","invites","dependents","deps"].includes(n)&&e[1]&&!e[1].startsWith("-")&&(i=e[1],o=2));function a(c,l){if(ja.has(c)&&typeof l=="string"){let u=s[c];Array.isArray(u)?u.push(l):typeof u=="string"?s[c]=[u,l]:s[c]=[l]}else s[c]=l}for(let c=o;c<e.length;c++){let l=e[c];if(l.startsWith("--")){let u=l.indexOf("=");u>-1?a(l.slice(2,u),l.slice(u+1)):c+1<e.length&&!e[c+1].startsWith("-")?(a(l.slice(2),e[c+1]),c++):a(l.slice(2),!0)}else l.startsWith("-")&&l.length===2?c+1<e.length&&!e[c+1].startsWith("-")?(a(l.slice(1),e[c+1]),c++):a(l.slice(1),!0):r.push(l)}return{command:n,subcommand:i,positional:r,flags:s}}function N(t){return new vs({serverUrl:typeof t.server=="string"?t.server:void 0,stateDir:typeof t["state-dir"]=="string"?t["state-dir"]:void 0,inviteToken:typeof t["invite-token"]=="string"?t["invite-token"]:void 0,proxyUrl:typeof t["proxy-url"]=="string"?t["proxy-url"]:void 0})}function te(t){return new Date(t).toLocaleString()}function Vr(t){let e=new Date(t).getTime()-Date.now();if(e<=0)return P("expired");let r=Math.floor(e/6e4),s=Math.floor(e%6e4/1e3);return r>0?`${r}m ${s}s`:`${s}s`}async function Ha(t,e){let r=N(t);if(r.isRegistered()){let c=r.whoami();C?D({alreadyRegistered:!0,namespace:c.namespace,keyId:c.keyId,serverUrl:c.serverUrl}):(console.log(`Already registered as ${S(c.namespace)}`),console.log(` Key ID: ${c.keyId}`),console.log(` Server: ${O(c.serverUrl)}`),console.log(`
119
- Use ${b("botparty reset")} to clear and re-register.`));return}let s=e[0]||(typeof t.namespace=="string"?t.namespace:void 0),n=typeof t.name=="string"?t.name:void 0,i=typeof t.ttl=="string"?parseInt(t.ttl,10):void 0,o=typeof t["invite-token"]=="string"?t["invite-token"]:void 0;i&&(r.rotationTTL=i),C||console.log("Registering namespace...");let a=await r.register(s,n,{inviteToken:o});C?D({namespace:a.namespace,keyId:a.keyId,role:a.role,rotationTTL:a.rotationTTL,...a.parentNamespace&&{parentNamespace:a.parentNamespace},...a.inheritedScopes&&{inheritedScopes:a.inheritedScopes}}):(console.log(`
120
- ${j("Registered!")} ${S(a.namespace)}`),console.log(` Key ID: ${a.keyId}`),console.log(` Role: ${a.role}`),console.log(` Rotation TTL: ${a.rotationTTL} min`),a.parentNamespace&&console.log(` Parent: ${b(a.parentNamespace)}`),a.inheritedScopes&&console.log(` Inherited: ${a.inheritedScopes.join(", ")}`),console.log(`
121
- Identity saved to ${O("~/.botparty/")}`))}async function Ma(t){let r=N(t).whoami();r||T("Not registered. Run: botparty init"),C?D(r):(console.log(S("Identity")),console.log(` Namespace: ${b(r.namespace)}`),console.log(` Key ID: ${r.keyId}`),console.log(` Algorithm: ${r.algorithm}`),console.log(` Rotation TTL: ${r.rotationTTL} min`),console.log(` Last rotated: ${te(r.rotatedAt)}`),console.log(` Stale at: ${te(r.staleAt)} (${Vr(r.staleAt)})`),r.label&&console.log(` Label: ${r.label}`),console.log(` Server: ${O(r.serverUrl)}`))}async function Va(t,e){let r=N(t),s=e[0]||r.getIdentity()?.namespace;s||T("Not registered and no namespace provided. Run: botparty init");let n=await r.info(s);C?D(n):(console.log(S("Namespace Info")),console.log(` Namespace: ${b(n.namespace)}`),console.log(` Status: ${n.status==="active"?j(n.status):P(n.status)}`),console.log(` Linked: ${n.linked?j("yes"):F("no")}`),console.log(` Active keys: ${n.activeKeys}`),console.log(` Created: ${te(n.createdAt)}`),n.lockedAt&&console.log(` Locked at: ${P(te(n.lockedAt))}`))}async function Wa(t){let e=N(t);e.isRegistered()||T("Not registered. Run: botparty init");let{url:r}=await e.link();C?D({url:r}):(console.log(`Share this link with your human to claim ownership:
118
+ ${R("error")}: ${t.message}`),process.exit(1)),console.error(t),process.exit(1)}var ja=new Set(["header","H"]);function La(t){let e=t.slice(2),r=[],s={},n="help",i="",o=0;e[0]&&!e[0].startsWith("-")&&(n=e[0],o=1,["keys","connections","conn","invites","dependents","deps"].includes(n)&&e[1]&&!e[1].startsWith("-")&&(i=e[1],o=2));function a(c,l){if(ja.has(c)&&typeof l=="string"){let u=s[c];Array.isArray(u)?u.push(l):typeof u=="string"?s[c]=[u,l]:s[c]=[l]}else s[c]=l}for(let c=o;c<e.length;c++){let l=e[c];if(l.startsWith("--")){let u=l.indexOf("=");u>-1?a(l.slice(2,u),l.slice(u+1)):c+1<e.length&&!e[c+1].startsWith("-")?(a(l.slice(2),e[c+1]),c++):a(l.slice(2),!0)}else l.startsWith("-")&&l.length===2?c+1<e.length&&!e[c+1].startsWith("-")?(a(l.slice(1),e[c+1]),c++):a(l.slice(1),!0):r.push(l)}return{command:n,subcommand:i,positional:r,flags:s}}function D(t){return new vs({serverUrl:typeof t.server=="string"?t.server:void 0,stateDir:typeof t["state-dir"]=="string"?t["state-dir"]:void 0,inviteToken:typeof t["invite-token"]=="string"?t["invite-token"]:void 0,proxyUrl:typeof t["proxy-url"]=="string"?t["proxy-url"]:void 0})}function se(t){return new Date(t).toLocaleString()}function Vr(t){let e=new Date(t).getTime()-Date.now();if(e<=0)return R("expired");let r=Math.floor(e/6e4),s=Math.floor(e%6e4/1e3);return r>0?`${r}m ${s}s`:`${s}s`}async function Ha(t,e){let r=D(t);if(r.isRegistered()){let c=r.whoami();C?L({alreadyRegistered:!0,namespace:c.namespace,keyId:c.keyId,serverUrl:c.serverUrl}):(console.log(`Already registered as ${A(c.namespace)}`),console.log(` Key ID: ${c.keyId}`),console.log(` Server: ${O(c.serverUrl)}`),console.log(`
119
+ Use ${b("botparty reset")} to clear and re-register.`));return}let s=e[0]||(typeof t.namespace=="string"?t.namespace:void 0),n=typeof t.name=="string"?t.name:void 0,i=typeof t.ttl=="string"?parseInt(t.ttl,10):void 0,o=typeof t["invite-token"]=="string"?t["invite-token"]:void 0;i&&(r.rotationTTL=i),C||console.log("Registering namespace...");let a=await r.register(s,n,{inviteToken:o});C?L({namespace:a.namespace,keyId:a.keyId,role:a.role,rotationTTL:a.rotationTTL,...a.parentNamespace&&{parentNamespace:a.parentNamespace},...a.inheritedScopes&&{inheritedScopes:a.inheritedScopes}}):(console.log(`
120
+ ${H("Registered!")} ${A(a.namespace)}`),console.log(` Key ID: ${a.keyId}`),console.log(` Role: ${a.role}`),console.log(` Rotation TTL: ${a.rotationTTL} min`),a.parentNamespace&&console.log(` Parent: ${b(a.parentNamespace)}`),a.inheritedScopes&&console.log(` Inherited: ${a.inheritedScopes.join(", ")}`),console.log(`
121
+ Identity saved to ${O("~/.botparty/")}`))}async function Ma(t){let r=D(t).whoami();r||T("Not registered. Run: botparty init"),C?L(r):(console.log(A("Identity")),console.log(` Namespace: ${b(r.namespace)}`),console.log(` Key ID: ${r.keyId}`),console.log(` Algorithm: ${r.algorithm}`),console.log(` Rotation TTL: ${r.rotationTTL} min`),console.log(` Last rotated: ${se(r.rotatedAt)}`),console.log(` Stale at: ${se(r.staleAt)} (${Vr(r.staleAt)})`),r.label&&console.log(` Label: ${r.label}`),console.log(` Server: ${O(r.serverUrl)}`))}async function Va(t,e){let r=D(t),s=e[0]||r.getIdentity()?.namespace;s||T("Not registered and no namespace provided. Run: botparty init");let n=await r.info(s);C?L(n):(console.log(A("Namespace Info")),console.log(` Namespace: ${b(n.namespace)}`),console.log(` Status: ${n.status==="active"?H(n.status):R(n.status)}`),console.log(` Linked: ${n.linked?H("yes"):K("no")}`),console.log(` Active keys: ${n.activeKeys}`),console.log(` Created: ${se(n.createdAt)}`),n.lockedAt&&console.log(` Locked at: ${R(se(n.lockedAt))}`))}async function Wa(t){let e=D(t);e.isRegistered()||T("Not registered. Run: botparty init");let{url:r}=await e.link();C?L({url:r}):(console.log(`Share this link with your human to claim ownership:
122
122
  `),console.log(` ${b(r)}`),console.log(`
123
- ${O("The link expires in 5 minutes.")}`))}async function Fa(t){let e=N(t);e.isRegistered()||T("Not registered.");let r=e.whoami();if(t.yes!==!0&&t.y!==!0){C&&T("--yes flag required to confirm destruction"),console.log(`${P("WARNING")}: This will permanently destroy namespace ${S(r.namespace)}.`),console.log(`All keys, links, and data will be deleted.
124
- `),console.log(`Re-run with ${b("--yes")} to confirm.`);return}await e.destroy(),C?D({namespace:r.namespace,destroyed:!0}):console.log(`${j("Destroyed")} namespace ${S(r.namespace)}`)}async function Ka(t){N(t).reset(),C?D({reset:!0}):(console.log(`${j("Local state cleared.")} The namespace still exists on the server.`),console.log(`Run ${b("botparty init")} to register a new namespace.`))}async function qa(t){let r=await N(t).generateToken();C?D({token:r}):console.log(r)}async function Ba(t){let e=process.argv.slice(2),r=e.findIndex(n=>n==="curl"||n==="fetch"),s=r>=0?e.slice(r+1):e.slice(1);await Vs(s,()=>N(t))}async function Ga(t){let e=N(t),r=await e.keys.list();if(C){D({keys:r});return}if(r.length===0){console.log("No keys found.");return}let s=e.getIdentity();for(let n of r){let i=s&&n.id===s.keyId,o=[];n.isRoot&&o.push(b("root")),i&&o.push(j("current"));let a=new Date(n.staleAt).getTime();Date.now()>a?o.push(P("stale")):o.push(`stale in ${Vr(n.staleAt)}`),console.log(`${S(n.id)} ${o.join(" | ")}`),console.log(` Fingerprint: ${O(n.fingerprint)}`),console.log(` Algorithm: ${n.algorithm}`),console.log(` Role: ${n.role}`),n.label&&console.log(` Label: ${n.label}`),console.log(` Scopes: ${n.scopes.join(", ")}`),console.log(` Rotation TTL: ${n.rotationTTL} min`),console.log(` Last rotated: ${te(n.rotatedAt)}`),n.expiresAt&&console.log(` Expires at: ${te(n.expiresAt)}`),n.lastUsedAt&&console.log(` Last used: ${te(n.lastUsedAt)} from ${n.lastUsedIp}`),console.log("")}}async function za(t){let e=typeof t.label=="string"?t.label:void 0,r=typeof t.scopes=="string"?t.scopes.split(","):void 0,s=typeof t.ttl=="string"?parseInt(t.ttl,10):void 0,n=typeof t.expires=="string"?t.expires:void 0,i=typeof t["public-key"]=="string"?t["public-key"]:void 0;i||T("--public-key is required (PEM-encoded public key)"),r?.length||T("--scopes is required (comma-separated)"),s||T("--ttl is required (rotation TTL in minutes)");let a=await N(t).keys.add({publicKey:i,label:e,scopes:r,rotationTTL:s,expiresAt:n});C?D(a):(console.log(`${j("Key added")}`),console.log(` ID: ${S(a.id)}`),console.log(` Fingerprint: ${a.fingerprint}`),console.log(` Scopes: ${a.scopes.join(", ")}`),console.log(` Rotation TTL: ${a.rotationTTL} min`))}async function Za(t,e){let r=e[0]||void 0,s=N(t);C||console.log("Rotating key...");let n=await s.keys.rotate(r);C?D(n):(console.log(`
125
- ${j("Key rotated")}`),console.log(` ID: ${S(n.id)}`),console.log(` Fingerprint: ${n.fingerprint}`),console.log(` Stale at: ${te(n.staleAt)} (${Vr(n.staleAt)})`))}async function Ja(t,e){let r=e[0];r||T("Usage: botparty keys delete <keyId>");let s=N(t);if(t.yes!==!0&&t.y!==!0){C&&T("--yes flag required to confirm deletion"),console.log(`${F("WARNING")}: This will delete key ${S(r)} and all sub-keys.`),console.log(`Re-run with ${b("--yes")} to confirm.`);return}await s.keys.delete(r),C?D({keyId:r,deleted:!0}):console.log(`${j("Deleted")} key ${S(r)}`)}async function Ya(t,e){let r=e[0];r||T("Usage: botparty keys invalidate <keyId>");let s=typeof t.reason=="string"?t.reason:void 0,n=N(t);if(t.yes!==!0&&t.y!==!0){C&&T("--yes flag required to confirm invalidation"),console.log(`${P("DANGER")}: This will invalidate key ${S(r)} and ${P("LOCK THE ENTIRE NAMESPACE")}.`),console.log(`All JWTs will be rejected until a human unlocks it.
126
- `),console.log(`Re-run with ${b("--yes")} to confirm.`);return}await n.keys.invalidate(r,s),C?D({keyId:r,invalidated:!0,namespaceLocked:!0}):(console.log(`${P("Key invalidated")} \u2014 namespace is now ${P("LOCKED")}.`),console.log("A human must unlock it at the BotParty web UI."))}async function Xa(t){let e=N(t);e.isRegistered()||T("Not registered. Run: botparty init");let r=await e.generateToken(),s=typeof t.scopes=="string"?t.scopes.split(","):void 0,n=typeof t.expires=="string"?t.expires:void 0,i=await fetch(`${e.serverUrl}/api/v1/namespaces/invites`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({scopes:s,expiresIn:n})});if(!i.ok){let a=await i.json().catch(()=>({error:i.statusText}));T(a.error||`HTTP ${i.status}`)}let o=await i.json();C?D(o):(console.log(`${j("Invite created")}`),console.log(` Token ID: ${S(o.tokenId)}`),console.log(` Token: ${o.inviteToken}`),console.log(`
127
- Share the token or set ${b("BOTPARTY_INVITE_TOKEN")} env var.`))}async function Qa(t){let e=N(t);e.isRegistered()||T("Not registered. Run: botparty init");let r=await e.generateToken(),s=typeof t.status=="string"?`?status=${t.status}`:"",n=await fetch(`${e.serverUrl}/api/v1/namespaces/invites${s}`,{headers:{Authorization:`Bearer ${r}`}});if(!n.ok){let o=await n.json().catch(()=>({error:n.statusText}));T(o.error||`HTTP ${n.status}`)}let{invites:i}=await n.json();if(C){D({invites:i});return}if(i.length===0){console.log(O("No invites found."));return}console.log(`
128
- ${S("Invites")} (${i.length})
129
- `);for(let o of i){let a=o.status==="active"?j(o.status):o.status==="pending"?F(o.status):P(o.status);console.log(` ${S(o.tokenId)} ${a}`),console.log(` Scopes: ${o.scopes.join(", ")}`),o.childNamespace&&console.log(` Child: ${b(o.childNamespace)}`),console.log(` Created: ${te(o.createdAt)}`),console.log("")}}async function ec(t){let e=N(t);e.isRegistered()||T("Not registered. Run: botparty init");let r=await e.generateToken(),s=await fetch(`${e.serverUrl}/api/v1/namespaces/dependents`,{headers:{Authorization:`Bearer ${r}`}});if(!s.ok){let i=await s.json().catch(()=>({error:s.statusText}));T(i.error||`HTTP ${s.status}`)}let{dependents:n}=await s.json();if(C){D({dependents:n});return}if(n.length===0){console.log(O("No dependents found."));return}console.log(`
130
- ${S("Dependents")} (${n.length})
131
- `);for(let i of n){let o=i.status==="active"?j(i.status):i.status==="pending"?F(i.status):P(i.status);console.log(` ${S(i.tokenId)} ${o}`),i.childNamespace&&console.log(` Namespace: ${b(i.childNamespace)}`),console.log(` Scopes: ${i.scopes.join(", ")}`),console.log(` Created: ${te(i.createdAt)}`),i.revokedAt&&console.log(` Revoked: ${P(te(i.revokedAt))}`),console.log("")}}async function tc(t,e){let r=e[0];r||T("Usage: botparty dependents revoke <tokenId>");let s=N(t);if(s.isRegistered()||T("Not registered. Run: botparty init"),t.yes!==!0&&t.y!==!0){C&&T("--yes flag required to confirm revocation"),console.log(`${F("WARNING")}: This will revoke access for the child namespace linked to token ${S(r)}.`),console.log(`The child namespace will be ${P("LOCKED")}.`),console.log(`
132
- Re-run with ${b("--yes")} to confirm.`);return}let n=await s.generateToken(),i=await fetch(`${s.serverUrl}/api/v1/namespaces/dependents?tokenId=${encodeURIComponent(r)}`,{method:"DELETE",headers:{Authorization:`Bearer ${n}`}});if(!i.ok){let a=await i.json().catch(()=>({error:i.statusText}));T(a.error||`HTTP ${i.status}`)}let o=await i.json();C?D({revoked:!0,tokenId:r,childNamespace:o.childNamespace}):(console.log(`${j("Revoked")} token ${S(r)}`),o.childNamespace&&console.log(` Child namespace ${S(o.childNamespace)} is now ${P("LOCKED")}.`))}async function Mr(t,e,r){let s=await e.generateToken(),n=new Headers(r?.headers);return n.set("Authorization",`Bearer ${s}`),fetch(`${e.proxyUrl}${t}`,{...r,headers:n})}async function rc(t){let e=N(t),r=new URLSearchParams;typeof t.provider=="string"&&r.set("provider",t.provider),typeof t.status=="string"&&r.set("status",t.status);let s=r.toString(),n=await Mr(`/api/botparty/connections${s?`?${s}`:""}`,e);if(!n.ok){let a=await n.json().catch(()=>({error:n.statusText}));T(a.error||`HTTP ${n.status}`)}let o=(await n.json()).connections;if(C){D({connections:o});return}if(o.length===0){console.log(O("No connections found."));return}console.log(`
133
- ${S("Connections")} (${o.length})
134
- `);for(let a of o){let c=a.status==="active"?j("active"):F(a.status),l=a.type==="api_key"?O("[api_key]"):O("[oauth]"),u=a.accountLabel&&a.accountLabel!=="default"?O(` (${a.accountLabel})`):"",d=a.accountIdentifier?O(` \u2014 ${a.accountIdentifier}`):"";console.log(` ${S(a.displayName||a.provider)} ${l} ${c}${u}${d}`),console.log(` ${O("id:")} ${a.id}`),a.keyNames?.length&&console.log(` ${O("keys:")} ${a.keyNames.join(", ")}`),a.scopes?.length&&console.log(` ${O("scopes:")} ${a.scopes.join(", ")}`)}console.log("")}function sc(t,e){let r=e.toLowerCase();if(t.id===e||t.provider.toLowerCase()===r||t.displayName?.toLowerCase()===r||t.domain?.toLowerCase()===r)return!0;let s=t.domain?.toLowerCase().replace(/\.(com|io|dev|org|net|ai|club)$/,"");return!!(s&&s===r)}async function nc(t,e){let r=e[0];r||T("Usage: botparty connections delete <name|provider|id> [--yes]");let s=N(t),n=await Mr("/api/botparty/connections",s);if(!n.ok){let l=await n.json().catch(()=>({error:n.statusText}));T(l.error||`HTTP ${n.status}`)}let{connections:i}=await n.json(),o=i.filter(l=>sc(l,r));if(o.length===0&&T(`No connection found matching "${r}". Run: botparty connections list`),o.length>1){console.error(`${F("Multiple connections match")} "${r}":
135
- `);for(let l of o){let u=l.accountLabel&&l.accountLabel!=="default"?O(` (${l.accountLabel})`):"";console.error(` ${S(l.displayName||l.provider)}${u} ${O(l.id)}`)}console.error(`
136
- Specify the exact connection ID to delete.`),process.exit(1)}let a=o[0];t.yes!==!0&&t.y!==!0&&T(`This will permanently delete ${S(a.displayName||a.provider)} (${a.id}). Pass --yes to confirm.`);let c=await Mr(`/api/botparty/connections?id=${encodeURIComponent(a.id)}`,s,{method:"DELETE"});if(!c.ok){let l=await c.json().catch(()=>({error:c.statusText}));T(l.error||`HTTP ${c.status}`)}C?D({deleted:!0,connectionId:a.id,provider:a.provider}):console.log(`${j("Deleted")} ${S(a.displayName||a.provider)} (${a.id})`)}function ic(){console.log(`
137
- ${S("botparty")} \u2014 federated bot identity, authentication, and payments
138
-
139
- ${S("USAGE")}
123
+ ${O("The link expires in 5 minutes.")}`))}async function Fa(t){let e=D(t);e.isRegistered()||T("Not registered.");let r=e.whoami();if(t.yes!==!0&&t.y!==!0){C&&T("--yes flag required to confirm destruction"),console.log(`${R("WARNING")}: This will permanently destroy namespace ${A(r.namespace)}.`),console.log(`All keys, links, and data will be deleted.
124
+ `),console.log(`Re-run with ${b("--yes")} to confirm.`);return}await e.destroy(),C?L({namespace:r.namespace,destroyed:!0}):console.log(`${H("Destroyed")} namespace ${A(r.namespace)}`)}async function Ka(t){D(t).reset(),C?L({reset:!0}):(console.log(`${H("Local state cleared.")} The namespace still exists on the server.`),console.log(`Run ${b("botparty init")} to register a new namespace.`))}async function qa(t){let r=await D(t).generateToken();C?L({token:r}):console.log(r)}async function Ba(t){let e=process.argv.slice(2),r=e.findIndex(n=>n==="curl"||n==="fetch"),s=r>=0?e.slice(r+1):e.slice(1);await Vs(s,()=>D(t))}async function Ga(t){let e=D(t),r=await e.keys.list();if(C){L({keys:r});return}if(r.length===0){console.log("No keys found.");return}let s=e.getIdentity();for(let n of r){let i=s&&n.id===s.keyId,o=[];n.isRoot&&o.push(b("root")),i&&o.push(H("current"));let a=new Date(n.staleAt).getTime();Date.now()>a?o.push(R("stale")):o.push(`stale in ${Vr(n.staleAt)}`),console.log(`${A(n.id)} ${o.join(" | ")}`),console.log(` Fingerprint: ${O(n.fingerprint)}`),console.log(` Algorithm: ${n.algorithm}`),console.log(` Role: ${n.role}`),n.label&&console.log(` Label: ${n.label}`),console.log(` Scopes: ${n.scopes.join(", ")}`),console.log(` Rotation TTL: ${n.rotationTTL} min`),console.log(` Last rotated: ${se(n.rotatedAt)}`),n.expiresAt&&console.log(` Expires at: ${se(n.expiresAt)}`),n.lastUsedAt&&console.log(` Last used: ${se(n.lastUsedAt)} from ${n.lastUsedIp}`),console.log("")}}async function za(t){let e=typeof t.label=="string"?t.label:void 0,r=typeof t.scopes=="string"?t.scopes.split(","):void 0,s=typeof t.ttl=="string"?parseInt(t.ttl,10):void 0,n=typeof t.expires=="string"?t.expires:void 0,i=typeof t["public-key"]=="string"?t["public-key"]:void 0;i||T("--public-key is required (PEM-encoded public key)"),r?.length||T("--scopes is required (comma-separated)"),s||T("--ttl is required (rotation TTL in minutes)");let a=await D(t).keys.add({publicKey:i,label:e,scopes:r,rotationTTL:s,expiresAt:n});C?L(a):(console.log(`${H("Key added")}`),console.log(` ID: ${A(a.id)}`),console.log(` Fingerprint: ${a.fingerprint}`),console.log(` Scopes: ${a.scopes.join(", ")}`),console.log(` Rotation TTL: ${a.rotationTTL} min`))}async function Za(t,e){let r=e[0]||void 0,s=D(t);C||console.log("Rotating key...");let n=await s.keys.rotate(r);C?L(n):(console.log(`
125
+ ${H("Key rotated")}`),console.log(` ID: ${A(n.id)}`),console.log(` Fingerprint: ${n.fingerprint}`),console.log(` Stale at: ${se(n.staleAt)} (${Vr(n.staleAt)})`))}async function Ja(t,e){let r=e[0];r||T("Usage: botparty keys delete <keyId>");let s=D(t);if(t.yes!==!0&&t.y!==!0){C&&T("--yes flag required to confirm deletion"),console.log(`${K("WARNING")}: This will delete key ${A(r)} and all sub-keys.`),console.log(`Re-run with ${b("--yes")} to confirm.`);return}await s.keys.delete(r),C?L({keyId:r,deleted:!0}):console.log(`${H("Deleted")} key ${A(r)}`)}async function Ya(t,e){let r=e[0];r||T("Usage: botparty keys invalidate <keyId>");let s=typeof t.reason=="string"?t.reason:void 0,n=D(t);if(t.yes!==!0&&t.y!==!0){C&&T("--yes flag required to confirm invalidation"),console.log(`${R("DANGER")}: This will invalidate key ${A(r)} and ${R("LOCK THE ENTIRE NAMESPACE")}.`),console.log(`All JWTs will be rejected until a human unlocks it.
126
+ `),console.log(`Re-run with ${b("--yes")} to confirm.`);return}await n.keys.invalidate(r,s),C?L({keyId:r,invalidated:!0,namespaceLocked:!0}):(console.log(`${R("Key invalidated")} \u2014 namespace is now ${R("LOCKED")}.`),console.log("A human must unlock it at the BotParty web UI."))}async function Xa(t){let e=D(t);e.isRegistered()||T("Not registered. Run: botparty init");let r=await e.generateToken(),s=typeof t.scopes=="string"?t.scopes.split(","):void 0,n=typeof t.expires=="string"?t.expires:void 0,i=await fetch(`${e.serverUrl}/api/v1/namespaces/invites`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({scopes:s,expiresIn:n})});if(!i.ok){let a=await i.json().catch(()=>({error:i.statusText}));T(a.error||`HTTP ${i.status}`)}let o=await i.json();C?L(o):(console.log(`${H("Invite created")}`),console.log(` Token ID: ${A(o.tokenId)}`),console.log(` Token: ${o.inviteToken}`),console.log(`
127
+ Share the token or set ${b("BOTPARTY_INVITE_TOKEN")} env var.`))}async function Qa(t){let e=D(t);e.isRegistered()||T("Not registered. Run: botparty init");let r=await e.generateToken(),s=typeof t.status=="string"?`?status=${t.status}`:"",n=await fetch(`${e.serverUrl}/api/v1/namespaces/invites${s}`,{headers:{Authorization:`Bearer ${r}`}});if(!n.ok){let o=await n.json().catch(()=>({error:n.statusText}));T(o.error||`HTTP ${n.status}`)}let{invites:i}=await n.json();if(C){L({invites:i});return}if(i.length===0){console.log(O("No invites found."));return}console.log(`
128
+ ${A("Invites")} (${i.length})
129
+ `);for(let o of i){let a=o.status==="active"?H(o.status):o.status==="pending"?K(o.status):R(o.status);console.log(` ${A(o.tokenId)} ${a}`),console.log(` Scopes: ${o.scopes.join(", ")}`),o.childNamespace&&console.log(` Child: ${b(o.childNamespace)}`),console.log(` Created: ${se(o.createdAt)}`),console.log("")}}async function ec(t){let e=D(t);e.isRegistered()||T("Not registered. Run: botparty init");let r=await e.generateToken(),s=await fetch(`${e.serverUrl}/api/v1/namespaces/dependents`,{headers:{Authorization:`Bearer ${r}`}});if(!s.ok){let i=await s.json().catch(()=>({error:s.statusText}));T(i.error||`HTTP ${s.status}`)}let{dependents:n}=await s.json();if(C){L({dependents:n});return}if(n.length===0){console.log(O("No dependents found."));return}console.log(`
130
+ ${A("Dependents")} (${n.length})
131
+ `);for(let i of n){let o=i.status==="active"?H(i.status):i.status==="pending"?K(i.status):R(i.status);console.log(` ${A(i.tokenId)} ${o}`),i.childNamespace&&console.log(` Namespace: ${b(i.childNamespace)}`),console.log(` Scopes: ${i.scopes.join(", ")}`),console.log(` Created: ${se(i.createdAt)}`),i.revokedAt&&console.log(` Revoked: ${R(se(i.revokedAt))}`),console.log("")}}async function tc(t,e){let r=e[0];r||T("Usage: botparty dependents revoke <tokenId>");let s=D(t);if(s.isRegistered()||T("Not registered. Run: botparty init"),t.yes!==!0&&t.y!==!0){C&&T("--yes flag required to confirm revocation"),console.log(`${K("WARNING")}: This will revoke access for the child namespace linked to token ${A(r)}.`),console.log(`The child namespace will be ${R("LOCKED")}.`),console.log(`
132
+ Re-run with ${b("--yes")} to confirm.`);return}let n=await s.generateToken(),i=await fetch(`${s.serverUrl}/api/v1/namespaces/dependents?tokenId=${encodeURIComponent(r)}`,{method:"DELETE",headers:{Authorization:`Bearer ${n}`}});if(!i.ok){let a=await i.json().catch(()=>({error:i.statusText}));T(a.error||`HTTP ${i.status}`)}let o=await i.json();C?L({revoked:!0,tokenId:r,childNamespace:o.childNamespace}):(console.log(`${H("Revoked")} token ${A(r)}`),o.childNamespace&&console.log(` Child namespace ${A(o.childNamespace)} is now ${R("LOCKED")}.`))}async function Mr(t,e,r){let s=await e.generateToken(),n=new Headers(r?.headers);return n.set("Authorization",`Bearer ${s}`),fetch(`${e.proxyUrl}${t}`,{...r,headers:n})}async function rc(t){let e=D(t),r=new URLSearchParams;typeof t.provider=="string"&&r.set("provider",t.provider),typeof t.status=="string"&&r.set("status",t.status);let s=r.toString(),n=await Mr(`/api/botparty/connections${s?`?${s}`:""}`,e);if(!n.ok){let a=await n.json().catch(()=>({error:n.statusText}));T(a.error||`HTTP ${n.status}`)}let o=(await n.json()).connections;if(C){L({connections:o});return}if(o.length===0){console.log(O("No connections found."));return}console.log(`
133
+ ${A("Connections")} (${o.length})
134
+ `);for(let a of o){let c=a.status==="active"?H("active"):K(a.status),l=a.type==="api_key"?O("[api_key]"):O("[oauth]"),u=a.accountLabel&&a.accountLabel!=="default"?O(` (${a.accountLabel})`):"",d=a.accountIdentifier?O(` \u2014 ${a.accountIdentifier}`):"";console.log(` ${A(a.displayName||a.provider)} ${l} ${c}${u}${d}`),console.log(` ${O("id:")} ${a.id}`),a.keyNames?.length&&console.log(` ${O("keys:")} ${a.keyNames.join(", ")}`),a.scopes?.length&&console.log(` ${O("scopes:")} ${a.scopes.join(", ")}`)}console.log("")}function sc(t,e){let r=e.toLowerCase();if(t.id===e||t.provider.toLowerCase()===r||t.displayName?.toLowerCase()===r||t.domain?.toLowerCase()===r)return!0;let s=t.domain?.toLowerCase().replace(/\.(com|io|dev|org|net|ai|club)$/,"");return!!(s&&s===r)}async function nc(t,e){let r=e[0];r||T("Usage: botparty connections delete <name|provider|id> [--yes]");let s=D(t),n=await Mr("/api/botparty/connections",s);if(!n.ok){let l=await n.json().catch(()=>({error:n.statusText}));T(l.error||`HTTP ${n.status}`)}let{connections:i}=await n.json(),o=i.filter(l=>sc(l,r));if(o.length===0&&T(`No connection found matching "${r}". Run: botparty connections list`),o.length>1){console.error(`${K("Multiple connections match")} "${r}":
135
+ `);for(let l of o){let u=l.accountLabel&&l.accountLabel!=="default"?O(` (${l.accountLabel})`):"";console.error(` ${A(l.displayName||l.provider)}${u} ${O(l.id)}`)}console.error(`
136
+ Specify the exact connection ID to delete.`),process.exit(1)}let a=o[0];t.yes!==!0&&t.y!==!0&&T(`This will permanently delete ${A(a.displayName||a.provider)} (${a.id}). Pass --yes to confirm.`);let c=await Mr(`/api/botparty/connections?id=${encodeURIComponent(a.id)}`,s,{method:"DELETE"});if(!c.ok){let l=await c.json().catch(()=>({error:c.statusText}));T(l.error||`HTTP ${c.status}`)}C?L({deleted:!0,connectionId:a.id,provider:a.provider}):console.log(`${H("Deleted")} ${A(a.displayName||a.provider)} (${a.id})`)}function ic(){console.log(`
137
+ ${A("botparty")} \u2014 federated bot identity, authentication, and payments
138
+
139
+ ${A("USAGE")}
140
140
  botparty <command> [options]
141
141
 
142
- ${S("COMMANDS")}
142
+ ${A("COMMANDS")}
143
143
  ${b("init")} [namespace] Register a new namespace
144
144
  --name <name> Human-readable label
145
145
  --ttl <minutes> Key rotation TTL (default: 15)
@@ -189,17 +189,17 @@ ${S("COMMANDS")}
189
189
 
190
190
  ${b("destroy")} Destroy namespace (--yes to confirm)
191
191
 
192
- ${S("GLOBAL OPTIONS")}
192
+ ${A("GLOBAL OPTIONS")}
193
193
  --server <url> BotParty server URL
194
194
  --state-dir <path> Local state directory (default: ~/.botparty)
195
195
  --json Output machine-readable JSON
196
196
 
197
- ${S("ENVIRONMENT")}
197
+ ${A("ENVIRONMENT")}
198
198
  BOTPARTY_SERVER_URL Server URL override
199
199
  BOTPARTY_STATE_DIR State directory override
200
200
  BOTPARTY_INVITE_TOKEN Invite token for auto-registration as child namespace
201
201
 
202
- ${S("EXAMPLES")}
202
+ ${A("EXAMPLES")}
203
203
  botparty init # Auto-generate namespace
204
204
  botparty init my-cool-bot --ttl 30 # Custom namespace
205
205
  botparty curl https://api.example.com # Authenticated fetch
@@ -211,4 +211,4 @@ ${S("EXAMPLES")}
211
211
  botparty keys rotate # Rotate current key
212
212
  botparty connections list # Show credential connections
213
213
  botparty link # Get link URL for human
214
- `)}async function oc(){let{command:t,subcommand:e,positional:r,flags:s}=La(process.argv);if(s.json===!0&&(C=!0),s.version===!0||s.v===!0&&t!=="curl"&&t!=="fetch"||t==="version"){C?D({version:"0.0.1"}):console.log("botparty 0.0.1");return}if((s.help===!0||s.h===!0||t==="help")&&!["curl","fetch","services","svc"].includes(t)){let i=t.includes(".")?t:`${t}.botparty.club`;if(!(t!=="help"&&await Nt(i))){ic();return}}try{switch(t){case"init":case"join":await Ha(s,r);break;case"whoami":await Ma(s);break;case"info":await Va(s,r);break;case"link":await Wa(s);break;case"destroy":await Fa(s);break;case"reset":await Ka(s);break;case"token":await qa(s);break;case"curl":case"fetch":await Ba(s);break;case"services":case"svc":await vn(()=>N(s));break;case"keys":switch(e){case"list":case"ls":await Ga(s);break;case"add":await za(s);break;case"rotate":await Za(s,r);break;case"delete":case"rm":await Ja(s,r);break;case"invalidate":case"panic":await Ya(s,r);break;default:T(`Unknown keys subcommand: ${e||"(none)"}. Run: botparty keys list`)}break;case"invites":switch(e){case"create":await Xa(s);break;case"list":case"ls":case"":await Qa(s);break;default:T(`Unknown invites subcommand: ${e}. Try: botparty invites list`)}break;case"dependents":case"deps":switch(e){case"list":case"ls":case"":await ec(s);break;case"revoke":await tc(s,r);break;default:T(`Unknown dependents subcommand: ${e}. Try: botparty dependents list`)}break;case"connections":case"conn":switch(e){case"list":case"ls":case"":await rc(s);break;case"delete":case"rm":await nc(s,r);break;default:T(`Unknown connections subcommand: ${e}. Run: botparty connections list`)}break;default:{let n=t.includes(".")?t:`${t}.botparty.club`;if(await Nt(n)){let{discover:o}=await Promise.resolve().then(()=>(Dt(),Ks)),{execute:a}=await Promise.resolve().then(()=>(Hr(),gn)),{fetchServicesIndex:c}=await Promise.resolve().then(()=>(Qe(),Ws)),l=process.argv.slice(2),u=l.indexOf(t),d=u>=0?l.slice(u+1):[],m=d[0]&&!d[0].startsWith("-")?d[0]:void 0,x=d.slice(m?1:0);try{if(!m&&x.length===0)await o(n);else{let R=await c(n);!(m&&(R.actions.some(le=>le.slug===m)||R.actions.some(le=>le.slug.startsWith(m+"."))))&&R.defaultAction&&(x=d,m=R.defaultAction),await a(n,m,x,()=>N(s))}}catch(R){R.code==="ENOTFOUND"||R.cause?.code==="ENOTFOUND"?console.error(`${P("error")}: Could not connect to ${n}`):console.error(`${P("error")}: ${R.message||R}`),process.exit(1)}}else T(`Unknown command: ${t}. Run: botparty --help`);break}}}catch(n){Ua(n)}}oc();
214
+ `)}async function oc(){let{command:t,subcommand:e,positional:r,flags:s}=La(process.argv);if(s.json===!0&&(C=!0),s.version===!0||s.v===!0&&t!=="curl"&&t!=="fetch"||t==="version"){C?L({version:"0.0.1"}):console.log("botparty 0.0.1");return}if((s.help===!0||s.h===!0||t==="help")&&!["curl","fetch","services","svc"].includes(t)){let i=t.includes(".")?t:`${t}.botparty.club`;if(!(t!=="help"&&await Nt(i))){ic();return}}try{switch(t){case"init":case"join":await Ha(s,r);break;case"whoami":await Ma(s);break;case"info":await Va(s,r);break;case"link":await Wa(s);break;case"destroy":await Fa(s);break;case"reset":await Ka(s);break;case"token":await qa(s);break;case"curl":case"fetch":await Ba(s);break;case"services":case"svc":await vn(()=>D(s));break;case"keys":switch(e){case"list":case"ls":await Ga(s);break;case"add":await za(s);break;case"rotate":await Za(s,r);break;case"delete":case"rm":await Ja(s,r);break;case"invalidate":case"panic":await Ya(s,r);break;default:T(`Unknown keys subcommand: ${e||"(none)"}. Run: botparty keys list`)}break;case"invites":switch(e){case"create":await Xa(s);break;case"list":case"ls":case"":await Qa(s);break;default:T(`Unknown invites subcommand: ${e}. Try: botparty invites list`)}break;case"dependents":case"deps":switch(e){case"list":case"ls":case"":await ec(s);break;case"revoke":await tc(s,r);break;default:T(`Unknown dependents subcommand: ${e}. Try: botparty dependents list`)}break;case"connections":case"conn":switch(e){case"list":case"ls":case"":await rc(s);break;case"delete":case"rm":await nc(s,r);break;default:T(`Unknown connections subcommand: ${e}. Run: botparty connections list`)}break;default:{let n=t.includes(".")?t:`${t}.botparty.club`;if(await Nt(n)){let{discover:o}=await Promise.resolve().then(()=>(Dt(),Ks)),{execute:a}=await Promise.resolve().then(()=>(Hr(),gn)),{fetchServicesIndex:c}=await Promise.resolve().then(()=>(Qe(),Ws)),l=process.argv.slice(2),u=l.indexOf(t),d=u>=0?l.slice(u+1):[],m=await c(n),w=d[0]&&!d[0].startsWith("-")?d[0]:void 0,I=d.slice(w?1:0),ne=w&&(m.actions.some(U=>U.slug===w)||m.actions.some(U=>U.slug.startsWith(w+"."))),ye=!ne&&m.defaultAction?m.defaultAction:w;if(m.cliPackage&&ye&&(!m.cliActions||m.cliActions.includes(ye))){m.cliPackage.startsWith("@botparty/")||T(`Untrusted CLI package: ${m.cliPackage} (must start with @botparty/)`);let{spawn:z}=await import("node:child_process"),P=!ne&&m.defaultAction?d:I,j=z("npx",["-y",`${m.cliPackage}@latest`,...P],{stdio:"inherit",shell:!0});j.on("close",N=>process.exit(N??0)),j.on("error",N=>{console.error(`${R("error")}: Failed to run ${m.cliPackage}: ${N.message}`),process.exit(1)}),await new Promise(()=>{})}try{!w&&I.length===0?await o(n):(!ne&&m.defaultAction&&(I=d,w=m.defaultAction),await a(n,w,I,()=>D(s)))}catch(U){U.code==="ENOTFOUND"||U.cause?.code==="ENOTFOUND"?console.error(`${R("error")}: Could not connect to ${n}`):console.error(`${R("error")}: ${U.message||U}`),process.exit(1)}}else T(`Unknown command: ${t}. Run: botparty --help`);break}}}catch(n){Ua(n)}}oc();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "botparty",
3
- "version": "0.0.51",
3
+ "version": "0.0.53",
4
4
  "description": "CLI for BotParty — federated bot identity, authentication, and payments",
5
5
  "type": "module",
6
6
  "bin": {