botparty 0.0.45 → 0.0.47

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 +64 -64
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,78 +1,78 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __createRequire } from "module";
3
3
  const require = __createRequire(import.meta.url);
4
- var mn=Object.create;var Wt=Object.defineProperty;var gn=Object.getOwnPropertyDescriptor;var yn=Object.getOwnPropertyNames;var vn=Object.getPrototypeOf,_n=Object.prototype.hasOwnProperty;var ct=(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 Se=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Kt=(t,e)=>{for(var r in e)Wt(t,r,{get:e[r],enumerable:!0})},bn=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of yn(e))!_n.call(t,n)&&n!==r&&Wt(t,n,{get:()=>e[n],enumerable:!(s=gn(e,n))||s.enumerable});return t};var wn=(t,e,r)=>(r=t!=null?mn(vn(t)):{},bn(e||!t||!t.__esModule?Wt(r,"default",{value:t,enumerable:!0}):r,t));var mt=Se(cr=>{var Tt=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}},ar=class extends Tt{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};cr.CommanderError=Tt;cr.InvalidArgumentError=ar});var $t=Se(ur=>{var{InvalidArgumentError:Ii}=mt(),lr=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 Ii(`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 Ni(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}ur.Argument=lr;ur.humanReadableArgName=Ni});var pr=Se(hr=>{var{humanReadableArgName:Di}=$t(),dr=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=>Di(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,g){return r.formatItem(d,s,g,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,g)=>{let x=d.map(M=>i(r.styleOptionTerm(r.optionTerm(M)),r.styleOptionDescription(r.optionDescription(M))));o=o.concat(this.formatItemList(g,x,r))}),r.showGlobalOptions){let d=r.visibleGlobalOptions(e).map(g=>i(r.styleOptionTerm(r.optionTerm(g)),r.styleOptionDescription(r.optionDescription(g))));o=o.concat(this.formatItemList("Global Options:",d,r))}return this.groupItems(e.commands,r.visibleCommands(e),d=>d.helpGroup()||"Commands:").forEach((d,g)=>{let x=d.map(M=>i(r.styleSubcommandTerm(r.subcommandTerm(M)),r.styleSubcommandDescription(r.subcommandDescription(M))));o=o.concat(this.formatItemList(g,x,r))}),o.join(`
5
- `)}displayWidth(e){return ys(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,`
4
+ var vn=Object.create;var Ft=Object.defineProperty;var _n=Object.getOwnPropertyDescriptor;var bn=Object.getOwnPropertyNames;var wn=Object.getPrototypeOf,xn=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 $e=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),kt=(t,e)=>{for(var r in e)Ft(t,r,{get:e[r],enumerable:!0})},kn=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of bn(e))!xn.call(t,n)&&n!==r&&Ft(t,n,{get:()=>e[n],enumerable:!(s=_n(e,n))||s.enumerable});return t};var Sn=(t,e,r)=>(r=t!=null?vn(wn(t)):{},kn(e||!t||!t.__esModule?Ft(r,"default",{value:t,enumerable:!0}):r,t));var yt=$e(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=$e(dr=>{var{InvalidArgumentError:Ui}=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 Ui(`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 ji(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}dr.Argument=ur;dr.humanReadableArgName=ji});var fr=$e(pr=>{var{humanReadableArgName:Li}=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=>Li(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(`
5
+ `)}displayWidth(e){return vs(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
- ${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 g=u.trimStart();c=[g],l=this.displayWidth(g)}),i.push(c.join(""))}),i.join(`
8
- `)}};function ys(t){let e=/\x1b\[\d*(;\d*)*m/g;return t.replace(e,"")}hr.Help=dr;hr.stripColor=ys});var yr=Se(gr=>{var{InvalidArgumentError:Ui}=mt(),fr=class{constructor(e,r){this.flags=e,this.description=r||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let s=ji(e);this.short=s.shortFlag,this.long=s.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(e,r){return this.defaultValue=e,this.defaultValueDescription=r,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let r=e;return typeof e=="string"&&(r={[e]:!0}),this.implied=Object.assign(this.implied||{},r),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_collectValue(e,r){return r===this.defaultValue||!Array.isArray(r)?[e]:(r.push(e),r)}choices(e){return this.argChoices=e.slice(),this.parseArg=(r,s)=>{if(!this.argChoices.includes(r))throw new Ui(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(r,s):r},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?vs(this.name().replace(/^no-/,"")):vs(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},mr=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(r=>{r.negate?this.negativeOptions.set(r.attributeName(),r):this.positiveOptions.set(r.attributeName(),r)}),this.negativeOptions.forEach((r,s)=>{this.positiveOptions.has(s)&&this.dualOptions.add(s)})}valueFromOption(e,r){let s=r.attributeName();if(!this.dualOptions.has(s))return!0;let n=this.negativeOptions.get(s).presetArg,i=n!==void 0?n:!1;return r.negate===(i===e)}};function vs(t){return t.split("-").reduce((e,r)=>e+r[0].toUpperCase()+r.slice(1))}function ji(t){let e,r,s=/^-[^-]$/,n=/^--[^-]/,i=t.split(/[ |,]+/).concat("guard");if(s.test(i[0])&&(e=i.shift()),n.test(i[0])&&(r=i.shift()),!e&&s.test(i[0])&&(e=i.shift()),!e&&n.test(i[0])&&(e=r,r=i.shift()),i[0].startsWith("-")){let o=i[0],a=`option creation failed due to '${o}' in option flags '${t}'`;throw/^-[^-][^-]/.test(o)?new Error(`${a}
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(`
8
+ `)}};function vs(t){let e=/\x1b\[\d*(;\d*)*m/g;return t.replace(e,"")}pr.Help=hr;pr.stripColor=vs});var vr=$e(yr=>{var{InvalidArgumentError:Hi}=yt(),mr=class{constructor(e,r){this.flags=e,this.description=r||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let s=Mi(e);this.short=s.shortFlag,this.long=s.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(e,r){return this.defaultValue=e,this.defaultValueDescription=r,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let r=e;return typeof e=="string"&&(r={[e]:!0}),this.implied=Object.assign(this.implied||{},r),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_collectValue(e,r){return r===this.defaultValue||!Array.isArray(r)?[e]:(r.push(e),r)}choices(e){return this.argChoices=e.slice(),this.parseArg=(r,s)=>{if(!this.argChoices.includes(r))throw new Hi(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(r,s):r},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?_s(this.name().replace(/^no-/,"")):_s(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},gr=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(r=>{r.negate?this.negativeOptions.set(r.attributeName(),r):this.positiveOptions.set(r.attributeName(),r)}),this.negativeOptions.forEach((r,s)=>{this.positiveOptions.has(s)&&this.dualOptions.add(s)})}valueFromOption(e,r){let s=r.attributeName();if(!this.dualOptions.has(s))return!0;let n=this.negativeOptions.get(s).presetArg,i=n!==void 0?n:!1;return r.negate===(i===e)}};function _s(t){return t.split("-").reduce((e,r)=>e+r[0].toUpperCase()+r.slice(1))}function Mi(t){let e,r,s=/^-[^-]$/,n=/^--[^-]/,i=t.split(/[ |,]+/).concat("guard");if(s.test(i[0])&&(e=i.shift()),n.test(i[0])&&(r=i.shift()),!e&&s.test(i[0])&&(e=i.shift()),!e&&n.test(i[0])&&(e=r,r=i.shift()),i[0].startsWith("-")){let o=i[0],a=`option creation failed due to '${o}' in option flags '${t}'`;throw/^-[^-][^-]/.test(o)?new Error(`${a}
9
9
  - a short flag is a single dash and a single character
10
10
  - either use a single dash and a single character (for a short flag)
11
11
  - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):s.test(o)?new Error(`${a}
12
12
  - too many short flags`):n.test(o)?new Error(`${a}
13
13
  - too many long flags`):new Error(`${a}
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}}gr.Option=fr;gr.DualOptions=mr});var bs=Se(_s=>{function Li(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 Hi(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=Li(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?`
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 ws=$e(bs=>{function Vi(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 Wi(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=Vi(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]}?)`:""}_s.suggestSimilar=Hi});var Ss=Se(xr=>{var Mi=ct("node:events").EventEmitter,vr=ct("node:child_process"),de=ct("node:path"),Ct=ct("node:fs"),$=ct("node:process"),{Argument:Vi,humanReadableArgName:Wi}=$t(),{CommanderError:_r}=mt(),{Help:Ki,stripColor:Fi}=pr(),{Option:ws,DualOptions:Bi}=yr(),{suggestSimilar:xs}=bs(),br=class t extends Mi{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:()=>wr()??($.stdout.isTTY&&$.stdout.hasColors?.()),getErrHasColors:()=>wr()??($.stderr.isTTY&&$.stderr.hasColors?.()),stripColor:r=>Fi(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 Ki,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
- - 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 Vi(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
- 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 _r(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 ws(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
- - 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 ws)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
- - 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(Ct.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
16
+ (Did you mean ${s[0]}?)`:""}bs.suggestSimilar=Wi});var As=$e(kr=>{var Ki=ut("node:events").EventEmitter,_r=ut("node:child_process"),he=ut("node:path"),Rt=ut("node:fs"),$=ut("node:process"),{Argument:Fi,humanReadableArgName:qi}=Ot(),{CommanderError:br}=yt(),{Help:Bi,stripColor:Gi}=fr(),{Option:xs,DualOptions:zi}=vr(),{suggestSimilar:ks}=ws(),wr=class t extends Ki{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=>Gi(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 Bi,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
+ - 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 Fi(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
+ 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 xs(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
+ - 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 xs)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
+ - 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 g=de.resolve(u,d);if(Ct.existsSync(g))return g;if(n.includes(de.extname(d)))return;let x=n.find(M=>Ct.existsSync(`${g}${M}`));if(x)return`${g}${x}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let u;try{u=Ct.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=de.resolve(de.dirname(u),a)}if(a){let u=i(a,o);if(!u&&!e._executableFile&&this._scriptPath){let d=de.basename(this._scriptPath,de.extname(this._scriptPath));d!==this._name&&(u=i(a,`${d}-${e._name}`))}o=u||o}s=n.includes(de.extname(o));let c;$.platform!=="win32"?s?(r.unshift(o),r=ks($.execArgv).concat(r),c=vr.spawn($.argv[0],r,{stdio:"inherit"})):c=vr.spawn(o,r,{stdio:"inherit"}):(this._checkForMissingExecutable(o,a,e._name),r.unshift(o),r=ks($.execArgv).concat(r),c=vr.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 _r(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 _r(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(g=>g.short).some(g=>/^-\d$/.test(g))):!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 g=e[l++];g===void 0&&this.optionMissingArgument(d),this.emit(`option:${d.name()}`,g)}else if(d.optional){let g=null;l<e.length&&(!i(e[l])||o(e[l]))&&(g=e[l++]),this.emit(`option:${d.name()}`,g)}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("="),g=this._findOption(u.slice(0,d));if(g&&(g.required||g.optional)){this.emit(`option:${g.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 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=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 Bi(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=xs(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=xs(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
- `),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=>Wi(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=de.basename(e,de.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.
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 zi(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=ks(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=ks(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
+ `),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=>qi(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 ks(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 wr(){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}xr.Command=br;xr.useColor=wr});var $s=Se(z=>{var{Argument:As}=$t(),{Command:kr}=Ss(),{CommanderError:qi,InvalidArgumentError:Es}=mt(),{Help:Gi}=pr(),{Option:Ts}=yr();z.program=new kr;z.createCommand=t=>new kr(t);z.createOption=(t,e)=>new Ts(t,e);z.createArgument=(t,e)=>new As(t,e);z.Command=kr;z.Option=Ts;z.Argument=As;z.Help=Gi;z.CommanderError=qi;z.InvalidArgumentError=Es;z.InvalidOptionArgumentError=Es});var Cs,Pc,Ic,Nc,Dc,Uc,jc,Lc,Ot,Hc,Mc,Vc,Sr=V(()=>{Cs=wn($s(),1),{program:Pc,createCommand:Ic,createArgument:Nc,createOption:Dc,CommanderError:Uc,InvalidArgumentError:jc,InvalidOptionArgumentError:Lc,Command:Ot,Argument:Hc,Option:Mc,Help:Vc}=Cs.default});function Er(t){return(t.includes("://")?t:`https://${t}`).replace(/\/$/,"")}async function gt(t){let e=`${Er(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 Ms(t,e){let r=`${Er(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 Tr(t){try{let e=`${Er(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 Pt=V(()=>{"use strict"});var Ws={};Kt(Ws,{discover:()=>$r,listSubActions:()=>Cr});function fo(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 Vs(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 ");Vs(i,c,a,!1)})}async function $r(t){let e=await gt(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 Cs=$e(z=>{var{Argument:Es}=Ot(),{Command:Sr}=As(),{CommanderError:Zi,InvalidArgumentError:Ts}=yt(),{Help:Ji}=fr(),{Option:$s}=vr();z.program=new Sr;z.createCommand=t=>new Sr(t);z.createOption=(t,e)=>new $s(t,e);z.createArgument=(t,e)=>new Es(t,e);z.Command=Sr;z.Option=$s;z.Argument=Es;z.Help=Ji;z.CommanderError=Zi;z.InvalidArgumentError=Ts;z.InvalidOptionArgumentError=Ts});var Os,Uc,jc,Lc,Hc,Mc,Vc,Wc,Pt,Kc,Fc,qc,Ar=V(()=>{Os=Sn(Cs(),1),{program:Uc,createCommand:jc,createArgument:Lc,createOption:Hc,CommanderError:Mc,InvalidArgumentError:Vc,InvalidOptionArgumentError:Wc,Command:Pt,Argument:Kc,Option:Fc,Help:qc}=Os.default});var Vs={};kt(Vs,{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 yo(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 Ws(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 ");Ws(i,c,a,!1)})}async function Cr(t){let e=await we(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=fo(e.actions);Vs(r),console.log()}async function Cr(t,e){let r=await gt(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=yo(e.actions);Ws(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(`
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 It=V(()=>{"use strict";Pt()});var A,Or,f,ie,yt=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})(A||(A={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Or||(Or={}));f=A.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ie=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,mo,F,Nt=V(()=>{yt();h=A.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"]),mo=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),F=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,A.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()}};F.create=t=>new F(t)});var go,he,Rr=V(()=>{Nt();yt();go=(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,A.jsonStringifyReplacer)}`;break;case h.unrecognized_keys:r=`Unrecognized key(s) in object: ${A.joinValues(t.keys,", ")}`;break;case h.invalid_union:r="Invalid input";break;case h.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${A.joinValues(t.options)}`;break;case h.invalid_enum_value:r=`Invalid enum value. Expected ${A.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}"`:A.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,A.assertNever(t)}return{message:r}},he=go});function yo(t){Ks=t}function Je(){return Ks}var Ks,Dt=V(()=>{Rr();Ks=he});function p(t,e){let r=Je(),s=vt({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===he?void 0:he].filter(n=>!!n)});t.common.issues.push(s)}var vt,vo,H,v,Te,W,Ut,jt,be,Ye,Pr=V(()=>{Dt();Rr();vt=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}},vo=[];H=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"}),Te=t=>({status:"dirty",value:t}),W=t=>({status:"valid",value:t}),Ut=t=>t.status==="aborted",jt=t=>t.status==="dirty",be=t=>t.status==="valid",Ye=t=>typeof Promise<"u"&&t instanceof Promise});var Fs=V(()=>{});var m,Bs=V(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(m||(m={}))});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 Zs(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 Do(t){return new RegExp(`^${Zs(t)}$`)}function Js(t){let e=`${zs}T${Zs(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 Uo(t,e){return!!((e==="v4"||!e)&&$o.test(t)||(e==="v6"||!e)&&Oo.test(t))}function jo(t,e){if(!So.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 Lo(t,e){return!!((e==="v4"||!e)&&Co.test(t)||(e==="v6"||!e)&&Ro.test(t))}function Ho(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 Xe(t){if(t instanceof B){let e={};for(let r in t.shape){let s=t.shape[r];e[r]=Z.create(Xe(s))}return new B({...t._def,shape:()=>e})}else return t instanceof me?new me({...t._def,type:Xe(t.element)}):t instanceof Z?Z.create(Xe(t.unwrap())):t instanceof ae?ae.create(Xe(t.unwrap())):t instanceof oe?oe.create(t.items.map(e=>Xe(e))):t}function Nr(t,e){let r=ie(t),s=ie(e);if(t===e)return{valid:!0,data:t};if(r===f.object&&s===f.object){let n=A.objectKeys(e),i=A.objectKeys(t).filter(a=>n.indexOf(a)!==-1),o={...t,...e};for(let a of i){let c=Nr(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=Nr(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 Ys(t,e){return new Le({values:t,typeName:_.ZodEnum,...w(e)})}function Gs(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Xs(t,e={},r){return t?xe.create().superRefine((s,n)=>{let i=t(s);if(i instanceof Promise)return i.then(o=>{if(!o){let a=Gs(e,s),c=a.fatal??r??!0;n.addIssue({code:"custom",...a,fatal:c})}});if(!i){let o=Gs(e,s),a=o.fatal??r??!0;n.addIssue({code:"custom",...o,fatal:a})}}):xe.create()}var J,qs,k,_o,bo,wo,xo,ko,So,Ao,Eo,To,Ir,$o,Co,Oo,Ro,Po,Io,zs,No,we,$e,Ce,Oe,Re,Qe,Pe,Ie,xe,fe,Q,et,me,B,Ne,pe,Lt,De,oe,Ht,tt,rt,Mt,Ue,je,Le,He,ke,Y,Z,ae,Me,Ve,st,Mo,_t,bt,We,Vo,_,Wo,Qs,en,Ko,Fo,tn,Bo,qo,Go,zo,Zo,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,rn=V(()=>{Nt();Dt();Bs();Pr();yt();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}},qs=(t,e)=>{if(be(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 F(t.common.issues);return this._error=r,this._error}}};k=class{get description(){return this._def.description}_getType(e){return ie(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:ie(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new H,ctx:{common:e.parent.common,data:e.data,parsedType:ie(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Ye(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:ie(e)},n=this._parseSync({data:e,path:s.path,parent:s});return qs(s,n)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ie(e)};if(!this["~standard"].async)try{let s=this._parseSync({data:e,path:[],parent:r});return be(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=>be(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:ie(e)},n=this._parse({data:e,path:s.path,parent:s}),i=await(Ye(n)?n:Promise.resolve(n));return qs(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 ae.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return me.create(this)}promise(){return ke.create(this,this._def)}or(e){return Ne.create([this,e],this._def)}and(e){return De.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 Me({...w(this._def),innerType:this,defaultValue:r,typeName:_.ZodDefault})}brand(){return new _t({typeName:_.ZodBranded,type:this,...w(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Ve({...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 bt.create(this,e)}readonly(){return We.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},_o=/^c[^\s-]{8,}$/i,bo=/^[0-9a-z]+$/,wo=/^[0-9A-HJKMNP-TV-Z]{26}$/i,xo=/^[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,ko=/^[a-z0-9_-]{21}$/i,So=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Ao=/^[-+]?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)?)??$/,Eo=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,To="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",$o=/^(?:(?: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])$/,Co=/^(?:(?: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])$/,Oo=/^(([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]))$/,Ro=/^(([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])$/,Po=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Io=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,zs="((\\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])))",No=new RegExp(`^${zs}$`);we=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 H,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")Eo.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")Ir||(Ir=new RegExp(To,"u")),Ir.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")xo.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")ko.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")_o.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")bo.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")wo.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"?Js(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"?No.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:h.invalid_string,validation:"date",message:i.message}),s.dirty()):i.kind==="time"?Do(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"?Ao.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"duration",code:h.invalid_string,message:i.message}),s.dirty()):i.kind==="ip"?Uo(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"?jo(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"?Lo(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"?Po.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"base64",code:h.invalid_string,message:i.message}),s.dirty()):i.kind==="base64url"?Io.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"base64url",code:h.invalid_string,message:i.message}),s.dirty()):A.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,...m.errToObj(s)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...m.errToObj(e)})}url(e){return this._addCheck({kind:"url",...m.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...m.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...m.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...m.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...m.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...m.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...m.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...m.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...m.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...m.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...m.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...m.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,...m.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,...m.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...m.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...m.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...m.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...m.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...m.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...m.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...m.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...m.errToObj(r)})}nonempty(e){return this.min(1,m.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}};we.create=t=>new we({checks:[],typeName:_.ZodString,coerce:t?.coerce??!1,...w(t)});$e=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 H;for(let i of this._def.checks)i.kind==="int"?A.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"?Ho(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()):A.assertNever(i);return{status:n.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,m.toString(r))}gt(e,r){return this.setLimit("min",e,!1,m.toString(r))}lte(e,r){return this.setLimit("max",e,!0,m.toString(r))}lt(e,r){return this.setLimit("max",e,!1,m.toString(r))}setLimit(e,r,s,n){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:s,message:m.toString(n)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:m.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:m.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:m.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:m.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:m.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:m.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:m.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:m.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:m.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"&&A.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)}};$e.create=t=>new $e({checks:[],typeName:_.ZodNumber,coerce:t?.coerce||!1,...w(t)});Ce=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 H;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()):A.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,m.toString(r))}gt(e,r){return this.setLimit("min",e,!1,m.toString(r))}lte(e,r){return this.setLimit("max",e,!0,m.toString(r))}lt(e,r){return this.setLimit("max",e,!1,m.toString(r))}setLimit(e,r,s,n){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:s,message:m.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:m.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:m.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:m.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:m.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:m.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}};Ce.create=t=>new Ce({checks:[],typeName:_.ZodBigInt,coerce:t?.coerce??!1,...w(t)});Oe=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)}};Oe.create=t=>new Oe({typeName:_.ZodBoolean,coerce:t?.coerce||!1,...w(t)});Re=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 H,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()):A.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:m.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:m.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}};Re.create=t=>new Re({checks:[],coerce:t?.coerce||!1,typeName:_.ZodDate,...w(t)});Qe=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)}};Qe.create=t=>new Qe({typeName:_.ZodSymbol,...w(t)});Pe=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)}};Pe.create=t=>new Pe({typeName:_.ZodUndefined,...w(t)});Ie=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)}};Ie.create=t=>new Ie({typeName:_.ZodNull,...w(t)});xe=class extends k{constructor(){super(...arguments),this._any=!0}_parse(e){return W(e.data)}};xe.create=t=>new xe({typeName:_.ZodAny,...w(t)});fe=class extends k{constructor(){super(...arguments),this._unknown=!0}_parse(e){return W(e.data)}};fe.create=t=>new fe({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)});et=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)}};et.create=t=>new et({typeName:_.ZodVoid,...w(t)});me=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=>H.mergeArray(s,o));let i=[...r.data].map((o,a)=>n.type._parseSync(new J(r,o,r.path,a)));return H.mergeArray(s,i)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:m.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:m.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:m.toString(r)}})}nonempty(e){return this.min(1,e)}};me.create=(t,e)=>new me({type:t,minLength:null,maxLength:null,exactLength:null,typeName:_.ZodArray,...w(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=A.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,g=await u.value;l.push({key:d,value:g,alwaysSet:u.alwaysSet})}return l}).then(l=>H.mergeObjectSync(s,l)):H.mergeObjectSync(s,c)}get shape(){return this._def.shape()}strict(e){return m.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:m.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 A.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 A.objectKeys(this.shape))e[s]||(r[s]=this.shape[s]);return new t({...this._def,shape:()=>r})}deepPartial(){return Xe(this)}partial(e){let r={};for(let s of A.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 A.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 Ys(A.objectKeys(this.shape))}};B.create=(t,e)=>new B({shape:()=>t,unknownKeys:"strip",catchall:Q.create(),typeName:_.ZodObject,...w(e)});B.strictCreate=(t,e)=>new B({shape:()=>t,unknownKeys:"strict",catchall:Q.create(),typeName:_.ZodObject,...w(e)});B.lazycreate=(t,e)=>new B({shape:t,unknownKeys:"strip",catchall:Q.create(),typeName:_.ZodObject,...w(e)});Ne=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 F(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 F(c));return p(r,{code:h.invalid_union,unionErrors:a}),v}}get options(){return this._def.options}};Ne.create=(t,e)=>new Ne({options:t,typeName:_.ZodUnion,...w(e)});pe=t=>t instanceof Ue?pe(t.schema):t instanceof Y?pe(t.innerType()):t instanceof je?[t.value]:t instanceof Le?t.options:t instanceof He?A.objectValues(t.enum):t instanceof Me?pe(t._def.innerType):t instanceof Pe?[void 0]:t instanceof Ie?[null]:t instanceof Z?[void 0,...pe(t.unwrap())]:t instanceof ae?[null,...pe(t.unwrap())]:t instanceof _t||t instanceof We?pe(t.unwrap()):t instanceof Ve?pe(t._def.innerType):[],Lt=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=pe(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)})}};De=class extends k{_parse(e){let{status:r,ctx:s}=this._processInputParams(e),n=(i,o)=>{if(Ut(i)||Ut(o))return v;let a=Nr(i.value,o.value);return a.valid?((jt(i)||jt(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}))}};De.create=(t,e,r)=>new De({left:t,right:e,typeName:_.ZodIntersection,...w(r)});oe=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=>H.mergeArray(r,o)):H.mergeArray(r,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};oe.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new oe({items:t,typeName:_.ZodTuple,rest:null,...w(e)})};Ht=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?H.mergeObjectAsync(r,n):H.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:we.create(),valueType:e,typeName:_.ZodRecord,...w(r)})}},tt=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}}}};tt.create=(t,e,r)=>new tt({valueType:e,keyType:t,typeName:_.ZodMap,...w(r)});rt=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:m.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:m.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};rt.create=(t,e)=>new rt({valueType:t,minSize:null,maxSize:null,typeName:_.ZodSet,...w(e)});Mt=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 vt({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Je(),he].filter(l=>!!l),issueData:{code:h.invalid_arguments,argumentsError:c}})}function n(a,c){return vt({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Je(),he].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 ke){let a=this;return W(async function(...c){let l=new F([]),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 F([s(c,l.error)]);let u=Reflect.apply(o,this,l.data),d=a._def.returns.safeParse(u,i);if(!d.success)throw new F([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:oe.create(e).rest(fe.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||oe.create([]).rest(fe.create()),returns:r||fe.create(),typeName:_.ZodFunction,...w(s)})}},Ue=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})}};Ue.create=(t,e)=>new Ue({getter:t,typeName:_.ZodLazy,...w(e)});je=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}};je.create=(t,e)=>new je({value:t,typeName:_.ZodLiteral,...w(e)});Le=class t extends k{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),s=this._def.values;return p(r,{expected:A.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})}};Le.create=Ys;He=class extends k{_parse(e){let r=A.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==f.string&&s.parsedType!==f.number){let n=A.objectValues(r);return p(s,{expected:A.joinValues(n),received:s.parsedType,code:h.invalid_type}),v}if(this._cache||(this._cache=new Set(A.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let n=A.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}};He.create=(t,e)=>new He({values:t,typeName:_.ZodNativeEnum,...w(e)});ke=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})))}};ke.create=(t,e)=>new ke({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"?Te(c.value):r.value==="dirty"?Te(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"?Te(a.value):r.value==="dirty"?Te(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(!be(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=>be(o)?Promise.resolve(n.transform(o.value,i)).then(a=>({status:r.value,value:a})):v);A.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)});ae=class extends k{_parse(e){return this._getType(e)===f.null?W(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ae.create=(t,e)=>new ae({innerType:t,typeName:_.ZodNullable,...w(e)});Me=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}};Me.create=(t,e)=>new Me({innerType:t,typeName:_.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...w(e)});Ve=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 Ye(n)?n.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new F(s.common.issues)},input:s.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new F(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};Ve.create=(t,e)=>new Ve({innerType:t,typeName:_.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...w(e)});st=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}}};st.create=t=>new st({typeName:_.ZodNaN,...w(t)});Mo=Symbol("zod_brand"),_t=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}},bt=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(),Te(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})}},We=class extends k{_parse(e){let r=this._def.innerType._parse(e),s=n=>(be(n)&&(n.value=Object.freeze(n.value)),n);return Ye(r)?r.then(n=>s(n)):s(r)}unwrap(){return this._def.innerType}};We.create=(t,e)=>new We({innerType:t,typeName:_.ZodReadonly,...w(e)});Vo={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"})(_||(_={}));Wo=(t,e={message:`Input not instance of ${t.name}`})=>Xs(r=>r instanceof t,e),Qs=we.create,en=$e.create,Ko=st.create,Fo=Ce.create,tn=Oe.create,Bo=Re.create,qo=Qe.create,Go=Pe.create,zo=Ie.create,Zo=xe.create,Jo=fe.create,Yo=Q.create,Xo=et.create,Qo=me.create,ea=B.create,ta=B.strictCreate,ra=Ne.create,sa=Lt.create,na=De.create,ia=oe.create,oa=Ht.create,aa=tt.create,ca=rt.create,la=Mt.create,ua=Ue.create,da=je.create,ha=Le.create,pa=He.create,fa=ke.create,ma=Y.create,ga=Z.create,ya=ae.create,va=Y.createWithPreprocess,_a=bt.create,ba=()=>Qs().optional(),wa=()=>en().optional(),xa=()=>tn().optional(),ka={string:(t=>we.create({...t,coerce:!0})),number:(t=>$e.create({...t,coerce:!0})),boolean:(t=>Oe.create({...t,coerce:!0})),bigint:(t=>Ce.create({...t,coerce:!0})),date:(t=>Re.create({...t,coerce:!0}))},Sa=v});var q={};Kt(q,{BRAND:()=>Mo,DIRTY:()=>Te,EMPTY_PATH:()=>vo,INVALID:()=>v,NEVER:()=>Sa,OK:()=>W,ParseStatus:()=>H,Schema:()=>k,ZodAny:()=>xe,ZodArray:()=>me,ZodBigInt:()=>Ce,ZodBoolean:()=>Oe,ZodBranded:()=>_t,ZodCatch:()=>Ve,ZodDate:()=>Re,ZodDefault:()=>Me,ZodDiscriminatedUnion:()=>Lt,ZodEffects:()=>Y,ZodEnum:()=>Le,ZodError:()=>F,ZodFirstPartyTypeKind:()=>_,ZodFunction:()=>Mt,ZodIntersection:()=>De,ZodIssueCode:()=>h,ZodLazy:()=>Ue,ZodLiteral:()=>je,ZodMap:()=>tt,ZodNaN:()=>st,ZodNativeEnum:()=>He,ZodNever:()=>Q,ZodNull:()=>Ie,ZodNullable:()=>ae,ZodNumber:()=>$e,ZodObject:()=>B,ZodOptional:()=>Z,ZodParsedType:()=>f,ZodPipeline:()=>bt,ZodPromise:()=>ke,ZodReadonly:()=>We,ZodRecord:()=>Ht,ZodSchema:()=>k,ZodSet:()=>rt,ZodString:()=>we,ZodSymbol:()=>Qe,ZodTransformer:()=>Y,ZodTuple:()=>oe,ZodType:()=>k,ZodUndefined:()=>Pe,ZodUnion:()=>Ne,ZodUnknown:()=>fe,ZodVoid:()=>et,addIssueToContext:()=>p,any:()=>Zo,array:()=>Qo,bigint:()=>Fo,boolean:()=>tn,coerce:()=>ka,custom:()=>Xs,date:()=>Bo,datetimeRegex:()=>Js,defaultErrorMap:()=>he,discriminatedUnion:()=>sa,effect:()=>ma,enum:()=>ha,function:()=>la,getErrorMap:()=>Je,getParsedType:()=>ie,instanceof:()=>Wo,intersection:()=>na,isAborted:()=>Ut,isAsync:()=>Ye,isDirty:()=>jt,isValid:()=>be,late:()=>Vo,lazy:()=>ua,literal:()=>da,makeIssue:()=>vt,map:()=>aa,nan:()=>Ko,nativeEnum:()=>pa,never:()=>Yo,null:()=>zo,nullable:()=>ya,number:()=>en,object:()=>ea,objectUtil:()=>Or,oboolean:()=>xa,onumber:()=>wa,optional:()=>ga,ostring:()=>ba,pipeline:()=>_a,preprocess:()=>va,promise:()=>fa,quotelessJson:()=>mo,record:()=>oa,set:()=>ca,setErrorMap:()=>yo,strictObject:()=>ta,string:()=>Qs,symbol:()=>qo,transformer:()=>ma,tuple:()=>ia,undefined:()=>Go,union:()=>ra,unknown:()=>Jo,util:()=>A,void:()=>Xo});var Dr=V(()=>{Dt();Pr();Fs();yt();rn();Nt()});var sn=V(()=>{Dr();Dr()});function nn(t){switch(t.type){case"string":{let e=q.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?q.enum(t.enum):e}case"integer":case"number":{let e=t.type==="integer"?q.coerce.number().int():q.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 q.preprocess(e=>e==="true"||e===!0?!0:e==="false"||e===!1?!1:e,q.boolean());case"array":return q.array(t.items?nn(t.items):q.any());case"object":return q.record(q.any());default:return q.any()}}function Ur(t,e){let r=nn(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 on=V(()=>{"use strict";sn()});import*as Ke from"node:fs";import*as ce from"node:path";function Ea(t){let e=ce.extname(t).toLowerCase();return!!(Aa.has(e)||e==="")}function an(t){let e=ce.resolve(t),r=Ke.readFileSync(e),s=ce.relative(process.cwd(),e);if(Ea(t))return{path:s,contents:r.toString("utf-8")};let n=ce.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 cn(t){let e=[];for(let r of t){let s=ce.resolve(r);if(Ke.statSync(s).isDirectory()){let i=ln(s);for(let o of i)e.push(an(o))}else e.push(an(s))}return e}function ln(t){let e=[],r=Ke.readdirSync(t,{withFileTypes:!0});for(let s of r){let n=ce.join(t,s.name);s.isDirectory()?e.push(...ln(n)):e.push(n)}return e}var Aa,un=V(()=>{"use strict";Aa=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 dn={};Kt(dn,{execute:()=>jr});function Ta(t){return t.args?t.args:[...t.params.path.filter(e=>e.required),...t.params.body.filter(e=>e.required)].map(e=>e.name)}async function jr(t,e,r,s){let n=await gt(t),i=n.actions.find(y=>y.slug===e),o=n.actions.some(y=>y.slug.startsWith(e+"."));if(!i&&o)return Cr(t,e);if(!i){console.error(`\x1B[31mAction "${e}" not found.\x1B[0m`);let y=n.actions.filter(E=>E.slug.includes(e)).map(E=>E.slug);if(y.length>0){console.log(`
35
- Did you mean:`);for(let E of y)console.log(` \x1B[36m${E}\x1B[0m`)}process.exit(1)}let a=await Ms(t,e),c=[...a.params.path,...a.params.query,...a.params.body],l=new Map(c.map(y=>[y.name,y])),u=Ta(a),d=new Ot().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=V(()=>{"use strict";Qe()});var E,Rr,f,ie,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"]),ie=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,vo,F,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"]),vo=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),F=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()}};F.create=t=>new F(t)});var _o,pe,Pr=V(()=>{Ut();vt();_o=(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=_o});function bo(t){Fs=t}function et(){return Fs}var Fs,jt=V(()=>{Pr();Fs=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,wo,M,v,Re,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}},wo=[];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"}),Re=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 qs=V(()=>{});var g,Bs=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 Js(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 Lo(t){return new RegExp(`^${Js(t)}$`)}function Ys(t){let e=`${Zs}T${Js(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 Ho(t,e){return!!((e==="v4"||!e)&&Ro.test(t)||(e==="v6"||!e)&&Io.test(t))}function Mo(t,e){if(!To.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 Vo(t,e){return!!((e==="v4"||!e)&&Po.test(t)||(e==="v6"||!e)&&No.test(t))}function Wo(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 ae?ae.create(rt(t.unwrap())):t instanceof oe?oe.create(t.items.map(e=>rt(e))):t}function Dr(t,e){let r=ie(t),s=ie(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 Xs(t,e){return new We({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 Qs(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,Gs,k,xo,ko,So,Ao,Eo,To,$o,Co,Oo,Nr,Ro,Po,Io,No,Do,Uo,Zs,jo,ke,Pe,Ie,Ne,De,st,Ue,je,Se,me,Q,nt,ge,q,Le,fe,Mt,He,oe,Vt,it,ot,Wt,Me,Ve,We,Ke,Ae,Y,Z,ae,Fe,qe,at,Ko,bt,wt,Be,Fo,_,qo,en,tn,Bo,Go,rn,zo,Zo,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,sn=V(()=>{Ut();jt();Bs();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}},Gs=(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 F(t.common.issues);return this._error=r,this._error}}};k=class{get description(){return this._def.description}_getType(e){return ie(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:ie(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:ie(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:ie(e)},n=this._parseSync({data:e,path:s.path,parent:s});return Gs(s,n)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ie(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:ie(e)},n=this._parse({data:e,path:s.path,parent:s}),i=await(tt(n)?n:Promise.resolve(n));return Gs(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 ae.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ge.create(this)}promise(){return Ae.create(this,this._def)}or(e){return Le.create([this,e],this._def)}and(e){return He.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 Fe({...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 qe({...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 Be.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},xo=/^c[^\s-]{8,}$/i,ko=/^[0-9a-z]+$/,So=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ao=/^[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,Eo=/^[a-z0-9_-]{21}$/i,To=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,$o=/^[-+]?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)?)??$/,Co=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Oo="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ro=/^(?:(?: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])$/,Po=/^(?:(?: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])$/,Io=/^(([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]))$/,No=/^(([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])$/,Do=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Uo=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Zs="((\\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])))",jo=new RegExp(`^${Zs}$`);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")Co.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(Oo,"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")Ao.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")Eo.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")xo.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")ko.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")So.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"?Ys(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"?jo.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:h.invalid_string,validation:"date",message:i.message}),s.dirty()):i.kind==="time"?Lo(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"?$o.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"duration",code:h.invalid_string,message:i.message}),s.dirty()):i.kind==="ip"?Ho(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"?Mo(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"?Vo(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"?Do.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"base64",code:h.invalid_string,message:i.message}),s.dirty()):i.kind==="base64url"?Uo.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)});Pe=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"?Wo(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)}};Pe.create=t=>new Pe({checks:[],typeName:_.ZodNumber,coerce:t?.coerce||!1,...w(t)});Ie=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}};Ie.create=t=>new Ie({checks:[],typeName:_.ZodBigInt,coerce:t?.coerce??!1,...w(t)});Ne=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)}};Ne.create=t=>new Ne({typeName:_.ZodBoolean,coerce:t?.coerce||!1,...w(t)});De=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}};De.create=t=>new De({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)});Ue=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)}};Ue.create=t=>new Ue({typeName:_.ZodUndefined,...w(t)});je=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)}};je.create=t=>new je({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 Xs(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)});Le=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 F(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 F(c));return p(r,{code:h.invalid_union,unionErrors:a}),v}}get options(){return this._def.options}};Le.create=(t,e)=>new Le({options:t,typeName:_.ZodUnion,...w(e)});fe=t=>t instanceof Me?fe(t.schema):t instanceof Y?fe(t.innerType()):t instanceof Ve?[t.value]:t instanceof We?t.options:t instanceof Ke?E.objectValues(t.enum):t instanceof Fe?fe(t._def.innerType):t instanceof Ue?[void 0]:t instanceof je?[null]:t instanceof Z?[void 0,...fe(t.unwrap())]:t instanceof ae?[null,...fe(t.unwrap())]:t instanceof bt||t instanceof Be?fe(t.unwrap()):t instanceof qe?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)})}};He=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}))}};He.create=(t,e,r)=>new He({left:t,right:e,typeName:_.ZodIntersection,...w(r)});oe=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})}};oe.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new oe({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 F([]),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 F([s(c,l.error)]);let u=Reflect.apply(o,this,l.data),d=a._def.returns.safeParse(u,i);if(!d.success)throw new F([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:oe.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||oe.create([]).rest(me.create()),returns:r||me.create(),typeName:_.ZodFunction,...w(s)})}},Me=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})}};Me.create=(t,e)=>new Me({getter:t,typeName:_.ZodLazy,...w(e)});Ve=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}};Ve.create=(t,e)=>new Ve({value:t,typeName:_.ZodLiteral,...w(e)});We=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})}};We.create=Xs;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"?Re(c.value):r.value==="dirty"?Re(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"?Re(a.value):r.value==="dirty"?Re(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)});ae=class extends k{_parse(e){return this._getType(e)===f.null?W(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ae.create=(t,e)=>new ae({innerType:t,typeName:_.ZodNullable,...w(e)});Fe=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}};Fe.create=(t,e)=>new Fe({innerType:t,typeName:_.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...w(e)});qe=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 F(s.common.issues)},input:s.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new F(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};qe.create=(t,e)=>new qe({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)});Ko=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(),Re(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})}},Be=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}};Be.create=(t,e)=>new Be({innerType:t,typeName:_.ZodReadonly,...w(e)});Fo={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"})(_||(_={}));qo=(t,e={message:`Input not instance of ${t.name}`})=>Qs(r=>r instanceof t,e),en=ke.create,tn=Pe.create,Bo=at.create,Go=Ie.create,rn=Ne.create,zo=De.create,Zo=st.create,Jo=Ue.create,Yo=je.create,Xo=Se.create,Qo=me.create,ea=Q.create,ta=nt.create,ra=ge.create,sa=q.create,na=q.strictCreate,ia=Le.create,oa=Mt.create,aa=He.create,ca=oe.create,la=Vt.create,ua=it.create,da=ot.create,ha=Wt.create,pa=Me.create,fa=Ve.create,ma=We.create,ga=Ke.create,ya=Ae.create,va=Y.create,_a=Z.create,ba=ae.create,wa=Y.createWithPreprocess,xa=wt.create,ka=()=>en().optional(),Sa=()=>tn().optional(),Aa=()=>rn().optional(),Ea={string:(t=>ke.create({...t,coerce:!0})),number:(t=>Pe.create({...t,coerce:!0})),boolean:(t=>Ne.create({...t,coerce:!0})),bigint:(t=>Ie.create({...t,coerce:!0})),date:(t=>De.create({...t,coerce:!0}))},Ta=v});var B={};kt(B,{BRAND:()=>Ko,DIRTY:()=>Re,EMPTY_PATH:()=>wo,INVALID:()=>v,NEVER:()=>Ta,OK:()=>W,ParseStatus:()=>M,Schema:()=>k,ZodAny:()=>Se,ZodArray:()=>ge,ZodBigInt:()=>Ie,ZodBoolean:()=>Ne,ZodBranded:()=>bt,ZodCatch:()=>qe,ZodDate:()=>De,ZodDefault:()=>Fe,ZodDiscriminatedUnion:()=>Mt,ZodEffects:()=>Y,ZodEnum:()=>We,ZodError:()=>F,ZodFirstPartyTypeKind:()=>_,ZodFunction:()=>Wt,ZodIntersection:()=>He,ZodIssueCode:()=>h,ZodLazy:()=>Me,ZodLiteral:()=>Ve,ZodMap:()=>it,ZodNaN:()=>at,ZodNativeEnum:()=>Ke,ZodNever:()=>Q,ZodNull:()=>je,ZodNullable:()=>ae,ZodNumber:()=>Pe,ZodObject:()=>q,ZodOptional:()=>Z,ZodParsedType:()=>f,ZodPipeline:()=>wt,ZodPromise:()=>Ae,ZodReadonly:()=>Be,ZodRecord:()=>Vt,ZodSchema:()=>k,ZodSet:()=>ot,ZodString:()=>ke,ZodSymbol:()=>st,ZodTransformer:()=>Y,ZodTuple:()=>oe,ZodType:()=>k,ZodUndefined:()=>Ue,ZodUnion:()=>Le,ZodUnknown:()=>me,ZodVoid:()=>nt,addIssueToContext:()=>p,any:()=>Xo,array:()=>ra,bigint:()=>Go,boolean:()=>rn,coerce:()=>Ea,custom:()=>Qs,date:()=>zo,datetimeRegex:()=>Ys,defaultErrorMap:()=>pe,discriminatedUnion:()=>oa,effect:()=>va,enum:()=>ma,function:()=>ha,getErrorMap:()=>et,getParsedType:()=>ie,instanceof:()=>qo,intersection:()=>aa,isAborted:()=>Lt,isAsync:()=>tt,isDirty:()=>Ht,isValid:()=>xe,late:()=>Fo,lazy:()=>pa,literal:()=>fa,makeIssue:()=>_t,map:()=>ua,nan:()=>Bo,nativeEnum:()=>ga,never:()=>ea,null:()=>Yo,nullable:()=>ba,number:()=>tn,object:()=>sa,objectUtil:()=>Rr,oboolean:()=>Aa,onumber:()=>Sa,optional:()=>_a,ostring:()=>ka,pipeline:()=>xa,preprocess:()=>wa,promise:()=>ya,quotelessJson:()=>vo,record:()=>la,set:()=>da,setErrorMap:()=>bo,strictObject:()=>na,string:()=>en,symbol:()=>Zo,transformer:()=>va,tuple:()=>ca,undefined:()=>Jo,union:()=>ia,unknown:()=>Qo,util:()=>E,void:()=>ta});var Ur=V(()=>{jt();Ir();qs();vt();sn();Ut()});var nn=V(()=>{Ur();Ur()});function on(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?on(t.items):B.any());case"object":return B.record(B.any());default:return B.any()}}function jr(t,e){let r=on(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 an=V(()=>{"use strict";nn()});import*as Ge from"node:fs";import*as ce from"node:path";function Ca(t){let e=ce.extname(t).toLowerCase();return!!($a.has(e)||e==="")}function cn(t){let e=ce.resolve(t),r=Ge.readFileSync(e),s=ce.relative(process.cwd(),e);if(Ca(t))return{path:s,contents:r.toString("utf-8")};let n=ce.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 ln(t){let e=[];for(let r of t){let s=ce.resolve(r);if(Ge.statSync(s).isDirectory()){let i=un(s);for(let o of i)e.push(cn(o))}else e.push(cn(s))}return e}function un(t){let e=[],r=Ge.readdirSync(t,{withFileTypes:!0});for(let s of r){let n=ce.join(t,s.name);s.isDirectory()?e.push(...un(n)):e.push(n)}return e}var $a,dn=V(()=>{"use strict";$a=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 fn={};kt(fn,{execute:()=>Lr});import*as hn from"node:fs";import*as pn from"node:path";function Oa(t){try{let e=pn.join(process.cwd(),t),r=hn.readFileSync(e,"utf-8"),s=JSON.parse(r);if(s&&typeof s=="object"&&!Array.isArray(s))return s}catch{}return{}}function Ra(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=Ra(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 g=u.map(y=>l.get(y)?.required?`<${y}>`:`[${y}]`);g.push("[options]"),d.usage(g.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={},M=[];d.action(()=>{let y=d.opts(),E=d.args,ot={};for(let[ue,ye]of Object.entries(y)){if(ue==="file"||ue==="files"){M.push(...ye);continue}let at=l.get(ue);at&&typeof ye=="string"?ot[ue]=Ur(ye,at.type):ot[ue]=ye}u.forEach((ue,ye)=>{if(E[ye]!==void 0&&ot[ue]===void 0){let at=l.get(ue);ot[ue]=at?Ur(String(E[ye]),at.type):E[ye]}}),x=ot});try{await d.parseAsync(r,{from:"user"})}catch(y){throw y?.exitCode!==void 0&&process.exit(y.exitCode),y}r.length===0&&c.some(E=>E.required)&&d.help();let Fe=s(),nt=Fe.getIdentity();nt||(console.error("\x1B[31mNot registered. Run: botparty init\x1B[0m"),process.exit(1));let te=x,re=nt.namespace,P=n.baseUrl.replace("{namespace}",re),j=a.endpoint;for(let y of a.params.path){let E=te[y.name];E!==void 0?(j=j.replace(`{${y.name}}`,String(E)),delete te[y.name]):y.required&&(console.error(`\x1B[31mMissing required path parameter: --${y.name}\x1B[0m`),process.exit(1))}let D=new URLSearchParams;for(let y of a.params.query){let E=te[y.name];E!==void 0?(D.set(y.name,String(E)),delete te[y.name]):y.required&&(console.error(`\x1B[31mMissing required query parameter: --${y.name}\x1B[0m`),process.exit(1))}let ge=t.includes("://")?t:`https://${t}`,le=D.toString(),it=`${ge.replace(/\/$/,"")}${P}${j}${le?"?"+le:""}`,X={method:a.method};if(["POST","PUT","PATCH"].includes(a.method)){let y={};for(let E of a.params.body)te[E.name]!==void 0?y[E.name]=te[E.name]:E.required&&(console.error(`\x1B[31mMissing required body parameter: --${E.name}\x1B[0m`),process.exit(1));if(a.params.files&&M.length>0){let E=cn(M);y[a.params.files.bodyKey]=E}Object.keys(y).length>0&&(X.body=JSON.stringify(y),X.headers={"Content-Type":"application/json"})}console.log(`\x1B[90m${a.method} ${it}\x1B[0m`);let Vt=await Fe.generateToken({role:"admin"}),wt=new Headers(X.headers);wt.set("Authorization",`Bearer ${Vt}`),X.headers=wt;let se=await fetch(it,X),fn=se.headers.get("content-type")||"";if(!se.ok){let y=await se.text();try{let E=JSON.parse(y);E?.error?.code&&E?.error?.message?(console.error(`\x1B[31m${E.error.code}\x1B[0m \x1B[90m(${se.status})\x1B[0m`),console.error(`
41
- ${E.error.message}`),E.error.details&&console.error(`
42
- \x1B[90m${JSON.stringify(E.error.details,null,2)}\x1B[0m`)):(console.error(`\x1B[31m${se.status} ${se.statusText}\x1B[0m`),console.error(JSON.stringify(E,null,2)))}catch{console.error(`\x1B[31m${se.status} ${se.statusText}\x1B[0m`),y&&console.error(y)}process.exit(1)}if(fn.includes("application/json")){let y=await se.json();console.log(JSON.stringify(y,null,2))}else{let y=await se.text();console.log(y)}}var Lr=V(()=>{"use strict";Sr();Pt();It();on();un()});import{readFileSync as us,writeFileSync as sr,mkdirSync as di,existsSync as St,unlinkSync as nr,statSync as hi,renameSync as ds}from"node:fs";import{join as _e}from"node:path";import{homedir as pi}from"node:os";import{randomBytes as hs}from"node:crypto";var Jr=new TextEncoder,Vr=new TextDecoder,rc=2**32;function xn(...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 Ft(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 Yr(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 Xr(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 kn(t){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof t=="string"?t:Vr.decode(t),{alphabet:"base64url"});let e=t;e instanceof Uint8Array&&(e=Vr.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/");try{return Xr(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=Jr.encode(e)),Uint8Array.prototype.toBase64?e.toBase64({alphabet:"base64url",omitPadding:!0}):Yr(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}var ve=(t,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`),Be=(t,e)=>t.name===e;function Sn(t){return parseInt(t.name.slice(4),10)}function qt(t,e){if(Sn(t.hash)!==e)throw ve(`SHA-${e}`,"algorithm.hash")}function An(t){switch(t){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function En(t,e){if(e&&!t.usages.includes(e))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${e}.`)}function Tn(t,e,r){switch(e){case"HS256":case"HS384":case"HS512":{if(!Be(t.algorithm,"HMAC"))throw ve("HMAC");qt(t.algorithm,parseInt(e.slice(2),10));break}case"RS256":case"RS384":case"RS512":{if(!Be(t.algorithm,"RSASSA-PKCS1-v1_5"))throw ve("RSASSA-PKCS1-v1_5");qt(t.algorithm,parseInt(e.slice(2),10));break}case"PS256":case"PS384":case"PS512":{if(!Be(t.algorithm,"RSA-PSS"))throw ve("RSA-PSS");qt(t.algorithm,parseInt(e.slice(2),10));break}case"Ed25519":case"EdDSA":{if(!Be(t.algorithm,"Ed25519"))throw ve("Ed25519");break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{if(!Be(t.algorithm,e))throw ve(e);break}case"ES256":case"ES384":case"ES512":{if(!Be(t.algorithm,"ECDSA"))throw ve("ECDSA");let s=An(e);if(t.algorithm.namedCurve!==s)throw ve(s,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}En(t,r)}function Qr(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 es=(t,...e)=>Qr("Key must be ",t,...e),ts=(t,e,...r)=>Qr(`Key for the ${t} algorithm must be `,e,...r),Xt=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 Xt{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},lt=class extends Xt{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},$n=class extends Xt{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"},Qt=t=>{if(t?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return t instanceof CryptoKey}catch{return!1}},er=t=>t?.[Symbol.toStringTag]==="KeyObject",rs=t=>Qt(t)||er(t),sc=Symbol();function Wr(t,e){if(t)throw new TypeError(`${e} can only be called once`)}var Cn=t=>typeof t=="object"&&t!==null;function ss(t){if(!Cn(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 On(...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 tr=t=>ss(t)&&typeof t.kty=="string",Rn=t=>t.kty!=="oct"&&(t.kty==="AKP"&&typeof t.priv=="string"||typeof t.d=="string"),Pn=t=>t.kty!=="oct"&&t.d===void 0&&t.priv===void 0,In=t=>t.kty==="oct"&&typeof t.k=="string";function Nn(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 Dn(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 Un(t,e,r){if(e instanceof Uint8Array){if(!t.startsWith("HS"))throw new TypeError(es(e,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",e,{hash:`SHA-${t.slice(-3)}`,name:"HMAC"},!1,[r])}return Tn(e,t,r),e}async function jn(t,e,r){let s=await Un(t,e,"sign");Nn(t,s);let n=await crypto.subtle.sign(Dn(t,s.algorithm),s,r);return new Uint8Array(n)}var xt='Invalid or unsupported JWK "alg" (Algorithm) Parameter value';function Ln(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(xt)}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(xt)}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(xt)}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(xt)}break}default:throw new G('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:r}}async function Hn(t){if(!t.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:e,keyUsages:r}=Ln(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 qe="given KeyObject instance cannot be used for this algorithm",ze,Kr=async(t,e,r,s=!1)=>{ze||=new WeakMap;let n=ze.get(t);if(n?.[r])return n[r];let i=await Hn({...e,alg:r});return s&&Object.freeze(t),n?n[r]=i:ze.set(t,{[r]:i}),i},Mn=(t,e)=>{ze||=new WeakMap;let r=ze.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(qe)}i=t.toCryptoKey(t.asymmetricKeyType,n,s?[]:["deriveBits"])}if(t.asymmetricKeyType==="ed25519"){if(e!=="EdDSA"&&e!=="Ed25519")throw new TypeError(qe);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(qe);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(qe)}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(qe);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(qe);return r?r[e]=i:ze.set(t,{[e]:i}),i};async function Vn(t,e){if(t instanceof Uint8Array||Qt(t))return t;if(er(t)){if(t.type==="secret")return t.export();if("toCryptoKey"in t&&typeof t.toCryptoKey=="function")try{return Mn(t,e)}catch(s){if(s instanceof TypeError)throw s}let r=t.export({format:"jwk"});return Kr(t,r,e)}if(tr(t))return t.k?kn(t.k):Kr(t,t,e,!0);throw new Error("unreachable")}var Wn=(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 x={},R=[];d.action(()=>{let y=d.opts(),A=d.args,Te={};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"?Te[de]=jr(ve,lt.type):Te[de]=ve}u.forEach((de,ve)=>{if(A[ve]!==void 0&&Te[de]===void 0){let lt=l.get(de);Te[de]=lt?jr(String(A[ve]),lt.type):A[ve]}}),x=Te});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=Oa(n.configFile);for(let[A,Te]of Object.entries(y))x[A]===void 0&&(x[A]=Te)}let Ee=s(),le=Ee.getIdentity();le||(console.error("\x1B[31mNot registered. Run: botparty init\x1B[0m"),process.exit(1));let te=x,re=le.namespace,I=n.baseUrl.replace("{namespace}",re),L=a.endpoint;for(let y of a.params.path){let A=te[y.name];A!==void 0?(L=L.replace(`{${y.name}}`,String(A)),delete te[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=te[y.name];A!==void 0?(U.set(y.name,String(A)),delete te[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)te[A.name]!==void 0?y[A.name]=te[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=ln(R);y[a.params.files.bodyKey]=A}Object.keys(y).length>0&&(X.body=JSON.stringify(y),X.headers={"Content-Type":"application/json"})}console.log(`\x1B[90m${a.method} ${ct}\x1B[0m`);let Kt=await Ee.generateToken({role:"admin"}),xt=new Headers(X.headers);xt.set("Authorization",`Bearer ${Kt}`),X.headers=xt;let se=await fetch(ct,X),yn=se.headers.get("content-type")||"";if(!se.ok){let y=await se.text();try{let A=JSON.parse(y);A?.error?.code&&A?.error?.message?(console.error(`\x1B[31m${A.error.code}\x1B[0m \x1B[90m(${se.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${se.status} ${se.statusText}\x1B[0m`),console.error(JSON.stringify(A,null,2)))}catch{console.error(`\x1B[31m${se.status} ${se.statusText}\x1B[0m`),y&&console.error(y)}process.exit(1)}if(yn.includes("application/json")){let y=await se.json();console.log(JSON.stringify(y,null,2))}else{let y=await se.text();console.log(y)}}var Hr=V(()=>{"use strict";Ar();Qe();Dt();an();dn()});import{readFileSync as ds,writeFileSync as nr,mkdirSync as fi,existsSync as Et,unlinkSync as ir,statSync as mi,renameSync as hs}from"node:fs";import{join as be}from"node:path";import{homedir as gi}from"node:os";import{randomBytes as ps}from"node:crypto";var Yr=new TextEncoder,Wr=new TextDecoder,oc=2**32;function An(...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 Xr(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 Qr(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 En(t){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof t=="string"?t:Wr.decode(t),{alphabet:"base64url"});let e=t;e instanceof Uint8Array&&(e=Wr.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/");try{return Qr(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=Yr.encode(e)),Uint8Array.prototype.toBase64?e.toBase64({alphabet:"base64url",omitPadding:!0}):Xr(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 Tn(t){return parseInt(t.name.slice(4),10)}function Gt(t,e){if(Tn(t.hash)!==e)throw _e(`SHA-${e}`,"algorithm.hash")}function $n(t){switch(t){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Cn(t,e){if(e&&!t.usages.includes(e))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${e}.`)}function On(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=$n(e);if(t.algorithm.namedCurve!==s)throw _e(s,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Cn(t,r)}function es(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 ts=(t,...e)=>es("Key must be ",t,...e),rs=(t,e,...r)=>es(`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"},Rn=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",ss=t=>er(t)||tr(t),ac=Symbol();function Kr(t,e){if(t)throw new TypeError(`${e} can only be called once`)}var Pn=t=>typeof t=="object"&&t!==null;function ns(t){if(!Pn(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 In(...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=>ns(t)&&typeof t.kty=="string",Nn=t=>t.kty!=="oct"&&(t.kty==="AKP"&&typeof t.priv=="string"||typeof t.d=="string"),Dn=t=>t.kty!=="oct"&&t.d===void 0&&t.priv===void 0,Un=t=>t.kty==="oct"&&typeof t.k=="string";function jn(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 Ln(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 Hn(t,e,r){if(e instanceof Uint8Array){if(!t.startsWith("HS"))throw new TypeError(ts(e,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",e,{hash:`SHA-${t.slice(-3)}`,name:"HMAC"},!1,[r])}return On(e,t,r),e}async function Mn(t,e,r){let s=await Hn(t,e,"sign");jn(t,s);let n=await crypto.subtle.sign(Ln(t,s.algorithm),s,r);return new Uint8Array(n)}var St='Invalid or unsupported JWK "alg" (Algorithm) Parameter value';function Vn(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 Wn(t){if(!t.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:e,keyUsages:r}=Vn(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,Fr=async(t,e,r,s=!1)=>{Ye||=new WeakMap;let n=Ye.get(t);if(n?.[r])return n[r];let i=await Wn({...e,alg:r});return s&&Object.freeze(t),n?n[r]=i:Ye.set(t,{[r]:i}),i},Kn=(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 Fn(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 Kn(t,e)}catch(s){if(s instanceof TypeError)throw s}let r=t.export({format:"jwk"});return Fr(t,r,e)}if(rr(t))return t.k?En(t.k):Fr(t,t,e,!0);throw new Error("unreachable")}var qn=(t,e)=>{let r=(t.match(/.{1,64}/g)||[]).join(`
43
43
  `);return`-----BEGIN ${e}-----
44
44
  ${r}
45
- -----END ${e}-----`},ns=async(t,e,r)=>{if(er(r)){if(r.type!==t)throw new TypeError(`key is not a ${t} key`);return r.export({format:"pem",type:e})}if(!Qt(r))throw new TypeError(es(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 Wn(Yr(new Uint8Array(await crypto.subtle.exportKey(e,r))),`${t.toUpperCase()} KEY`)},Kn=t=>ns("public","spki",t),Fn=t=>ns("private","pkcs8",t),Gt=(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},Bn=t=>({data:t,pos:0}),ht=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},pt=(t,e,r)=>{if(t.data[t.pos++]!==e)throw new Error(r)},is=(t,e)=>{let r=t.data.subarray(t.pos,t.pos+e);return t.pos+=e,r},qn=t=>{pt(t,6,"Expected algorithm OID");let e=ht(t);return is(t,e)};function Gn(t){pt(t,48,"Invalid PKCS#8 structure"),ht(t),pt(t,2,"Expected version field");let e=ht(t);t.pos+=e,pt(t,48,"Expected algorithm identifier");let r=ht(t);return{algIdStart:t.pos,algIdLength:r}}var zn=t=>{let e=qn(t);if(Gt(e,[43,101,110]))return"X25519";if(!Gt(e,[42,134,72,206,61,2,1]))throw new Error("Unsupported key algorithm");pt(t,6,"Expected curve OID");let r=ht(t),s=is(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(Gt(s,i))return n;throw new Error("Unsupported named curve")},Zn=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)},Jn=(t,e)=>Xr(t.replace(e,"")),Yn=(t,e,r)=>{let s=Jn(t,/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g),n=r;return e?.startsWith?.("ECDH-ES")&&(n||={},n.getNamedCurve=i=>{let o=Bn(i);return Gn(o),zn(o)}),Zn("pkcs8",s,e,n)};async function os(t,e,r){if(typeof t!="string"||t.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return Yn(t,e,r)}async function Xn(t){return Kn(t)}async function Qn(t){return Fn(t)}function ei(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 Ge=t=>t?.[Symbol.toStringTag],Jt=(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},ti=(t,e,r)=>{if(!(e instanceof Uint8Array)){if(tr(e)){if(In(e)&&Jt(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(!rs(e))throw new TypeError(ts(t,e,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(e.type!=="secret")throw new TypeError(`${Ge(e)} instances for symmetric algorithms must be of type "secret"`)}},ri=(t,e,r)=>{if(tr(e))switch(r){case"decrypt":case"sign":if(Rn(e)&&Jt(t,e,r))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if(Pn(e)&&Jt(t,e,r))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!rs(e))throw new TypeError(ts(t,e,"CryptoKey","KeyObject","JSON Web Key"));if(e.type==="secret")throw new TypeError(`${Ge(e)} instances for asymmetric algorithms must not be of type "secret"`);if(e.type==="public")switch(r){case"sign":throw new TypeError(`${Ge(e)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${Ge(e)} instances for asymmetric algorithm decryption must be of type "private"`)}if(e.type==="private")switch(r){case"verify":throw new TypeError(`${Ge(e)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${Ge(e)} instances for asymmetric algorithm encryption must be of type "public"`)}};function si(t,e,r){switch(t.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":ti(t,e,r);break;default:ri(t,e,r)}}var Ae=t=>Math.floor(t.getTime()/1e3),as=60,cs=as*60,rr=cs*24,ni=rr*7,ii=rr*365.25,oi=/^(\+|\-)? ?(\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=oi.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*as);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(r*cs);break;case"day":case"days":case"d":n=Math.round(r*rr);break;case"week":case"weeks":case"w":n=Math.round(r*ni);break;default:n=Math.round(r*ii);break}return e[1]==="-"||e[4]==="ago"?-n:n}function Ee(t,e){if(!Number.isFinite(e))throw new TypeError(`Invalid ${t} input`);return e}var ai=class{#e;constructor(t){if(!ss(t))throw new TypeError("JWT Claims Set MUST be an object");this.#e=structuredClone(t)}data(){return Jr.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=Ee("setNotBefore",t):t instanceof Date?this.#e.nbf=Ee("setNotBefore",Ae(t)):this.#e.nbf=Ae(new Date)+zt(t)}set exp(t){typeof t=="number"?this.#e.exp=Ee("setExpirationTime",t):t instanceof Date?this.#e.exp=Ee("setExpirationTime",Ae(t)):this.#e.exp=Ae(new Date)+zt(t)}set iat(t){t===void 0?this.#e.iat=Ae(new Date):t instanceof Date?this.#e.iat=Ee("setIssuedAt",Ae(t)):typeof t=="string"?this.#e.iat=Ee("setIssuedAt",Ae(new Date)+zt(t)):this.#e.iat=Ee("setIssuedAt",t)}},ls=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 Wr(this.#t,"setProtectedHeader"),this.#t=t,this}setUnprotectedHeader(t){return Wr(this.#r,"setUnprotectedHeader"),this.#r=t,this}async sign(t,e){if(!this.#t&&!this.#r)throw new lt("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!On(this.#t,this.#r))throw new lt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let r={...this.#t,...this.#r},s=ei(lt,new Map([["b64",!0]]),e?.crit,this.#t,r),n=!0;if(s.has("b64")&&(n=this.#t.b64,typeof n!="boolean"))throw new lt('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:i}=r;if(typeof i!="string"||!i)throw new lt('JWS "alg" (Algorithm) Header Parameter missing or invalid');si(i,t,"sign");let o,a;n?(o=Bt(this.#e),a=Ft(o)):(a=this.#e,o="");let c,l;this.#t?(c=Bt(JSON.stringify(this.#t)),l=Ft(c)):(c="",l=new Uint8Array);let u=xn(l,Ft("."),a),d=await Vn(t,i),g=await jn(i,d,u),x={signature:Bt(g),payload:o};return this.#r&&(x.header=this.#r),this.#t&&(x.protected=c),x}},ci=class{#e;constructor(t){this.#e=new ls(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}`}},li=class{#e;#t;constructor(t={}){this.#t=new ai(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 ci(this.#t.data());if(r.setProtectedHeader(this.#e),Array.isArray(this.#e?.crit)&&this.#e.crit.includes("b64")&&this.#e.b64===!1)throw new $n("JWTs MUST NOT use unencoded payload");return r.sign(t,e)}};function Zt(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 ui(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:Zt(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:Zt(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:Zt(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 fi="https://id.botparty.club",mi="EdDSA",gi=15,Fr=6e4,yi=3e4,vi="5m",_i=3,bi=["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"],wi=["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"],L=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}},ir=class extends L{constructor(t){super({code:"NAMESPACE_LOCKED",message:t.message,statusCode:423,actionUrl:t.actionUrl,details:{lockedAt:t.lockedAt,reason:t.reason}}),this.name="NamespaceLockedError"}},At=class extends L{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}},ft=class extends L{missingScopes;constructor(t){super({code:"INSUFFICIENT_PERMISSION",message:t.message,statusCode:403,actionUrl:t.actionUrl}),this.name="InsufficientPermissionError",this.missingScopes=t.missingScopes}},Et=class extends L{constructor(t){super({code:"LINK_REQUIRED",message:t.message,statusCode:403,actionUrl:t.actionUrl}),this.name="LinkRequiredError"}};function Br(t){let e=hs(4);return t[e.readUInt32BE(0)%t.length]}function xi(){return`${Br(bi)}-${Br(wi)}`}function ki(){let t=xi(),e=hs(2).toString("hex");return`${t}-${e}`}function Si(){return _e(pi(),".botparty")}function or(t){St(t)||di(t,{recursive:!0,mode:448})}function Ai(t){let e=_e(t,"identity.json");if(!St(e))return null;try{return JSON.parse(us(e,"utf-8"))}catch{return null}}function ps(t,e){or(t);let r=_e(t,"identity.json"),s=r+".tmp";sr(s,JSON.stringify(e,null,2),{mode:384}),ds(s,r)}function Ei(t){let e=_e(t,"private.pem");if(!St(e))return null;try{return us(e,"utf-8")}catch{return null}}function fs(t,e){or(t);let r=_e(t,"private.pem"),s=r+".tmp";sr(s,e,{mode:384}),ds(s,r)}function qr(t){for(let e of["identity.json","private.pem"]){let r=_e(t,e);St(r)&&nr(r)}}function Ti(t){let e=_e(t,"rotation.lock");or(t);for(let r=0;r<2;r++)try{sr(e,`${process.pid}:${Date.now()}`,{flag:"wx",mode:384});return}catch(s){if(s.code!=="EEXIST")throw s;try{let n=hi(e);if(Date.now()-n.mtimeMs>yi){nr(e);continue}}catch{continue}throw s}}function $i(t){try{nr(_e(t,"rotation.lock"))}catch{}}async function ms(t){let e={extractable:!0};t==="EdDSA"&&(e.crv="Ed25519");let{privateKey:r,publicKey:s}=await ui(t,e),n=await Qn(r),i=await Xn(s);return{privateKey:r,publicKey:s,privatePem:n,publicPem:i}}async function Ci(t,e,r){let s=await os(e,r);return(await new ls(new TextEncoder().encode(t)).setProtectedHeader({alg:r}).sign(s)).signature}async function Yt(t,e,r,s,n){let i=s,o=await os(r,i);return new li({...n}).setProtectedHeader({alg:i,kid:e}).setIssuer(t).setSubject(t).setIssuedAt().setExpirationTime(vi).sign(o)}async function ne(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 Gr(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 kt(t){try{return await t.clone().json()}catch{return null}}function dt(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 Oi=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)}},Ri=class{constructor(t){this.client=t}async list(){let t=await this.client.generateToken(),e=await ne(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 L({code:"KEY_NOT_FOUND",message:`Key ${t} not found`,statusCode:404});return e}async add(t){let e=await this.client.generateToken(),r=await ne(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 ne(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 ne(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 L({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 ms(e.algorithm),i=await Yt(e.namespace,e.keyId,r,e.algorithm),o=await ne(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 fs(this.client.stateDir,n.privatePem),ps(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 ne(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)}},gs=class{serverUrl;stateDir;proxyUrl;keys;algorithm;rotationTTL;inviteToken;_rotationPromise=null;constructor(t={}){this.serverUrl=(t.serverUrl||ut("BOTPARTY_SERVER_URL")||fi).replace(/\/$/,""),this.proxyUrl=(t.proxyUrl||ut("BOTPARTY_PROXY_URL")||ut("KEYCHAINS_PROXY_URL")||"https://keychains.dev").replace(/\/$/,""),this.stateDir=t.stateDir||ut("BOTPARTY_STATE_DIR")||Si(),this.algorithm=t.algorithm||mi,this.rotationTTL=t.rotationTTL||gi,this.inviteToken=t.inviteToken||ut("BOTPARTY_INVITE_TOKEN"),this.keys=new Ri(this)}getIdentity(){return Ai(this.stateDir)}getPrivateKey(){return Ei(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<_i;){s||(s=ki());let o=e||s,a=await ms(this.algorithm),c=await ne(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 L({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 L({code:l.error||"REGISTRATION_FAILED",message:l.message||l.error||"Registration failed",statusCode:c.status});let u=l.challenge,d=await Ci(u,a.privatePem,this.algorithm),g=await ne(this.serverUrl,"/api/v1/namespaces/register/verify",{method:"POST",body:JSON.stringify({namespace:s,challenge:u,signature:d})});if(!g.ok)throw await this._apiError(g);let x=await g.json();return fs(this.stateDir,a.privatePem),ps(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 L({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-Fr)return this._rotationPromise=this._lockedRotate().finally(()=>{this._rotationPromise=null}),this._rotationPromise}async _lockedRotate(){Ti(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-Fr)return;await this.keys.rotateCurrent()}finally{$i(this.stateDir)}}async generateToken(t){await this.ensureRegistered(),await this.ensureFreshKey();let e=this.getIdentity(),r=this.getPrivateKey();return Yt(e.namespace,e.keyId,r,e.algorithm,t)}async fetch(t,e={}){let r=await this.generateToken(),s=Gr(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 kt(i);if(o){let{code:a}=dt(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 kt(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=Gr(t,u),g=new Headers(e.headers);return g.set("X-Proxy-Authorization",`Bearer ${r}`),fetch(d,{...e,headers:g})}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 ft({message:o.message||"Missing required credentials",actionUrl:c,missingScopes:d}):new Et({message:o.message||"Missing required credentials",actionUrl:c})}let{code:l}=dt(o);zr(l)&&Zr(i.status,o,this.getIdentity(),this.serverUrl)}}if([401,402,423].includes(i.status)){let o=await kt(i);if(o){let{code:a}=dt(o);(zr(a)||i.status===402||i.status===423)&&Zr(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 ne(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 ne(this.serverUrl,"/api/v1/namespaces",{method:"DELETE",token:t});if(!e.ok&&e.status!==204)throw await this._apiError(e);qr(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 Yt(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 Oi(this,t)}reset(){qr(this.stateDir)}async _apiError(t){let e=await kt(t);if(!e)return new L({code:"UNKNOWN",message:`Request failed with status ${t.status}`,statusCode:t.status});let{code:r,message:s,actionUrl:n}=dt(e);return new L({code:r,message:s,statusCode:t.status,actionUrl:n})}},Pi=new Set(["NAMESPACE_LOCKED","LOCKUP_TRIGGERED","PAYMENT_REQUIRED","LINK_REQUIRED","INSUFFICIENT_SCOPE","PERMISSION_DENIED","KEY_STALE","KEY_EXPIRED"]);function zr(t){return Pi.has(t.toUpperCase())}function Zr(t,e,r,s){let{code:n,message:i,actionUrl:o,extra:a}=dt(e),c=r?.namespace||"",l=r?.serverUrl||s;throw n==="NAMESPACE_LOCKED"||n==="LOCKUP_TRIGGERED"||t===423?new ir({message:i||"Namespace is locked",actionUrl:o||`${l}/namespaces/${c}/unlock`,lockedAt:a.lockedAt,reason:a.reason}):n==="PAYMENT_REQUIRED"||t===402?new At({message:i,actionUrl:o,amount:a.amount||e.amount,service:a.service||e.service}):n==="LINK_REQUIRED"?new Et({message:i,actionUrl:o||`${l}/namespaces/${c}/link`}):n==="INSUFFICIENT_SCOPE"||n==="PERMISSION_DENIED"||t===403?new ft({message:i,actionUrl:o,missingScopes:a.missingScopes||a.missing_scopes}):new L({code:n,message:i,statusCode:t,actionUrl:o})}function ut(t){if(typeof process<"u"&&process.env)return process.env[t]}Sr();import{writeFileSync as Ns}from"fs";import{readFileSync as Rt}from"fs";import{basename as oo}from"path";var zi="\x1B[1m",Zi="\x1B[2m",Ji="\x1B[31m",Yi="\x1B[32m",Xi="\x1B[33m",Qi="\x1B[36m",Ze="\x1B[0m";function S(t){return`${zi}${t}${Ze}`}function O(t){return`${Zi}${t}${Ze}`}function R(t){return`${Ji}${t}${Ze}`}function U(t){return`${Yi}${t}${Ze}`}function K(t){return`${Xi}${t}${Ze}`}function b(t){return`${Qi}${t}${Ze}`}import{readFileSync as eo,writeFileSync as to,existsSync as Os,mkdirSync as ro}from"node:fs";import{join as Rs}from"node:path";var Ps="auth-capability-cache.json",so=1440*60*1e3;function no(t){let e=Rs(t,Ps);if(!Os(e))return{};try{return JSON.parse(eo(e,"utf-8"))}catch{return{}}}function io(t,e){Os(t)||ro(t,{recursive:!0,mode:448}),to(Rs(t,Ps),JSON.stringify(e,null,2))}async function Is(t,e){let r=no(e),s=r[t];if(s&&Date.now()-s.checkedAt<so)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{io(e,r)}catch{}return n}function Ar(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
- `),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 ao(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
- `)}function co(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
- `)}function Ds(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(`
49
- `)}function lo(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(`
50
- `)}function uo(t){let e=[];if(t.data)for(let r of t.data)if(r.startsWith("@"))try{e.push(Rt(r.slice(1),"utf-8"))}catch{e.push(r)}else e.push(r);if(t.dataRaw)for(let r of t.dataRaw)e.push(r);if(t.dataBinary)for(let r of t.dataBinary)if(r.startsWith("@"))try{e.push(Rt(r.slice(1),"utf-8"))}catch{e.push(r)}else e.push(r);if(t.dataUrlencode)for(let r of t.dataUrlencode){let s=r.indexOf("=");if(s>0){let n=r.slice(0,s),i=r.slice(s+1);e.push(`${encodeURIComponent(n)}=${encodeURIComponent(i)}`)}else r.startsWith("=")?e.push(encodeURIComponent(r.slice(1))):e.push(encodeURIComponent(r))}if(t.dataAscii)for(let r of t.dataAscii)e.push(r);if(t.json)for(let r of t.json)e.push(r);if(e.length!==0)return e.join("&")}function ho(t){return!!(t.data&&t.data.length>0||t.dataRaw&&t.dataRaw.length>0||t.dataBinary&&t.dataBinary.length>0||t.dataUrlencode&&t.dataUrlencode.length>0||t.dataAscii&&t.dataAscii.length>0||t.json&&t.json.length>0)}function Ls(t){return!!(t.form&&t.form.length>0||t.formString&&t.formString.length>0)}function po(t){return t.request?t.request.toUpperCase():t.head?"HEAD":ho(t)&&!t.get||Ls(t)?"POST":t.uploadFile?"PUT":"GET"}async function Us(t,e,r,s,n,i){let o=await t.text(),a=Buffer.byteLength(o,"utf-8");if(e.verbose){let l=ao(r,s,n);process.stderr.write(l+`
51
- `);let u=co(t.status,t.statusText,t.headers);process.stderr.write(u+`
52
- `)}if(e.dumpHeader){let l=lo(t.status,t.statusText,t.headers);e.dumpHeader==="-"?process.stdout.write(l):Ns(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
- `),e.writeOut&&process.stdout.write(Ar(e.writeOut,t,a,i)),process.exit(22)));let c="";e.include&&(c+=Ds(t.status,t.statusText,t.headers)),e.head?!e.include&&!e.verbose&&(c+=Ds(t.status,t.statusText,t.headers)):c+=o,e.output?e.output==="-"?process.stdout.write(c):Ns(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(Ar(e.writeOut,t,a,i)),process.exit(22)),e.writeOut&&process.stdout.write(Ar(e.writeOut,t,a,i))}function js(t){return t instanceof L&&typeof t.actionUrl=="string"&&!!t.actionUrl}async function Hs(t,e){let r=new Ot;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!
45
+ -----END ${e}-----`},is=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(ts(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 qn(Xr(new Uint8Array(await crypto.subtle.exportKey(e,r))),`${t.toUpperCase()} KEY`)},Bn=t=>is("public","spki",t),Gn=t=>is("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},zn=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)},os=(t,e)=>{let r=t.data.subarray(t.pos,t.pos+e);return t.pos+=e,r},Zn=t=>{mt(t,6,"Expected algorithm OID");let e=ft(t);return os(t,e)};function Jn(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 Yn=t=>{let e=Zn(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=os(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")},Xn=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)},Qn=(t,e)=>Qr(t.replace(e,"")),ei=(t,e,r)=>{let s=Qn(t,/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g),n=r;return e?.startsWith?.("ECDH-ES")&&(n||={},n.getNamedCurve=i=>{let o=zn(i);return Jn(o),Yn(o)}),Xn("pkcs8",s,e,n)};async function as(t,e,r){if(typeof t!="string"||t.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return ei(t,e,r)}async function ti(t){return Bn(t)}async function ri(t){return Gn(t)}function si(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},ni=(t,e,r)=>{if(!(e instanceof Uint8Array)){if(rr(e)){if(Un(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(!ss(e))throw new TypeError(rs(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"`)}},ii=(t,e,r)=>{if(rr(e))switch(r){case"decrypt":case"sign":if(Nn(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(Dn(e)&&Yt(t,e,r))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!ss(e))throw new TypeError(rs(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 oi(t,e,r){switch(t.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":ni(t,e,r);break;default:ii(t,e,r)}}var Ce=t=>Math.floor(t.getTime()/1e3),cs=60,ls=cs*60,sr=ls*24,ai=sr*7,ci=sr*365.25,li=/^(\+|\-)? ?(\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=li.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*cs);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(r*ls);break;case"day":case"days":case"d":n=Math.round(r*sr);break;case"week":case"weeks":case"w":n=Math.round(r*ai);break;default:n=Math.round(r*ci);break}return e[1]==="-"||e[4]==="ago"?-n:n}function Oe(t,e){if(!Number.isFinite(e))throw new TypeError(`Invalid ${t} input`);return e}var ui=class{#e;constructor(t){if(!ns(t))throw new TypeError("JWT Claims Set MUST be an object");this.#e=structuredClone(t)}data(){return Yr.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=Oe("setNotBefore",t):t instanceof Date?this.#e.nbf=Oe("setNotBefore",Ce(t)):this.#e.nbf=Ce(new Date)+Zt(t)}set exp(t){typeof t=="number"?this.#e.exp=Oe("setExpirationTime",t):t instanceof Date?this.#e.exp=Oe("setExpirationTime",Ce(t)):this.#e.exp=Ce(new Date)+Zt(t)}set iat(t){t===void 0?this.#e.iat=Ce(new Date):t instanceof Date?this.#e.iat=Oe("setIssuedAt",Ce(t)):typeof t=="string"?this.#e.iat=Oe("setIssuedAt",Ce(new Date)+Zt(t)):this.#e.iat=Oe("setIssuedAt",t)}},us=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(!In(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=si(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');oi(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=An(l,qt("."),a),d=await Fn(t,i),m=await Mn(i,d,u),x={signature:Bt(m),payload:o};return this.#r&&(x.header=this.#r),this.#t&&(x.protected=c),x}},di=class{#e;constructor(t){this.#e=new us(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}`}},hi=class{#e;#t;constructor(t={}){this.#t=new ui(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 di(this.#t.data());if(r.setProtectedHeader(this.#e),Array.isArray(this.#e?.crit)&&this.#e.crit.includes("b64")&&this.#e.b64===!1)throw new Rn("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 pi(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 yi="https://id.botparty.club",vi="EdDSA",_i=15,qr=6e4,bi=3e4,wi="5m",xi=3,ki=["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"],Si=["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 Br(t){let e=ps(4);return t[e.readUInt32BE(0)%t.length]}function Ai(){return`${Br(ki)}-${Br(Si)}`}function Ei(){let t=Ai(),e=ps(2).toString("hex");return`${t}-${e}`}function Ti(){return be(gi(),".botparty")}function ar(t){Et(t)||fi(t,{recursive:!0,mode:448})}function $i(t){let e=be(t,"identity.json");if(!Et(e))return null;try{return JSON.parse(ds(e,"utf-8"))}catch{return null}}function fs(t,e){ar(t);let r=be(t,"identity.json"),s=r+".tmp";nr(s,JSON.stringify(e,null,2),{mode:384}),hs(s,r)}function Ci(t){let e=be(t,"private.pem");if(!Et(e))return null;try{return ds(e,"utf-8")}catch{return null}}function ms(t,e){ar(t);let r=be(t,"private.pem"),s=r+".tmp";nr(s,e,{mode:384}),hs(s,r)}function Gr(t){for(let e of["identity.json","private.pem"]){let r=be(t,e);Et(r)&&ir(r)}}function Oi(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=mi(e);if(Date.now()-n.mtimeMs>bi){ir(e);continue}}catch{continue}throw s}}function Ri(t){try{ir(be(t,"rotation.lock"))}catch{}}async function gs(t){let e={extractable:!0};t==="EdDSA"&&(e.crv="Ed25519");let{privateKey:r,publicKey:s}=await pi(t,e),n=await ri(r),i=await ti(s);return{privateKey:r,publicKey:s,privatePem:n,publicPem:i}}async function Pi(t,e,r){let s=await as(e,r);return(await new us(new TextEncoder().encode(t)).setProtectedHeader({alg:r}).sign(s)).signature}async function Xt(t,e,r,s,n){let i=s,o=await as(r,i);return new hi({...n}).setProtectedHeader({alg:i,kid:e}).setIssuer(t).setSubject(t).setIssuedAt().setExpirationTime(wi).sign(o)}async function ne(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 Ii=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)}},Ni=class{constructor(t){this.client=t}async list(){let t=await this.client.generateToken(),e=await ne(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 ne(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 ne(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 ne(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 gs(e.algorithm),i=await Xt(e.namespace,e.keyId,r,e.algorithm),o=await ne(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 ms(this.client.stateDir,n.privatePem),fs(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 ne(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)}},ys=class{serverUrl;stateDir;proxyUrl;keys;algorithm;rotationTTL;inviteToken;_rotationPromise=null;constructor(t={}){this.serverUrl=(t.serverUrl||ht("BOTPARTY_SERVER_URL")||yi).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")||Ti(),this.algorithm=t.algorithm||vi,this.rotationTTL=t.rotationTTL||_i,this.inviteToken=t.inviteToken||ht("BOTPARTY_INVITE_TOKEN"),this.keys=new Ni(this)}getIdentity(){return $i(this.stateDir)}getPrivateKey(){return Ci(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<xi;){s||(s=Ei());let o=e||s,a=await gs(this.algorithm),c=await ne(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 Pi(u,a.privatePem,this.algorithm),m=await ne(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 ms(this.stateDir,a.privatePem),fs(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-qr)return this._rotationPromise=this._lockedRotate().finally(()=>{this._rotationPromise=null}),this._rotationPromise}async _lockedRotate(){Oi(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-qr)return;await this.keys.rotateCurrent()}finally{Ri(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);Zr(l)&&Jr(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);(Zr(a)||i.status===402||i.status===423)&&Jr(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 ne(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 ne(this.serverUrl,"/api/v1/namespaces",{method:"DELETE",token:t});if(!e.ok&&e.status!==204)throw await this._apiError(e);Gr(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 Ii(this,t)}reset(){Gr(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})}},Di=new Set(["NAMESPACE_LOCKED","LOCKUP_TRIGGERED","PAYMENT_REQUIRED","LINK_REQUIRED","INSUFFICIENT_SCOPE","PERMISSION_DENIED","KEY_STALE","KEY_EXPIRED"]);function Zr(t){return Di.has(t.toUpperCase())}function Jr(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 Ds}from"fs";import{readFileSync as It}from"fs";import{basename as lo}from"path";var Yi="\x1B[1m",Xi="\x1B[2m",Qi="\x1B[31m",eo="\x1B[32m",to="\x1B[33m",ro="\x1B[36m",Xe="\x1B[0m";function S(t){return`${Yi}${t}${Xe}`}function O(t){return`${Xi}${t}${Xe}`}function P(t){return`${Qi}${t}${Xe}`}function j(t){return`${eo}${t}${Xe}`}function K(t){return`${to}${t}${Xe}`}function b(t){return`${ro}${t}${Xe}`}import{readFileSync as so,writeFileSync as no,existsSync as Rs,mkdirSync as io}from"node:fs";import{join as Ps}from"node:path";var Is="auth-capability-cache.json",oo=1440*60*1e3;function ao(t){let e=Ps(t,Is);if(!Rs(e))return{};try{return JSON.parse(so(e,"utf-8"))}catch{return{}}}function co(t,e){Rs(t)||io(t,{recursive:!0,mode:448}),no(Ps(t,Is),JSON.stringify(e,null,2))}async function Ns(t,e){let r=ao(e),s=r[t];if(s&&Date.now()-s.checkedAt<oo)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{co(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
+ `),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 uo(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
+ `)}function ho(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
+ `)}function Us(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(`
49
+ `)}function po(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(`
50
+ `)}function fo(t){let e=[];if(t.data)for(let r of t.data)if(r.startsWith("@"))try{e.push(It(r.slice(1),"utf-8"))}catch{e.push(r)}else e.push(r);if(t.dataRaw)for(let r of t.dataRaw)e.push(r);if(t.dataBinary)for(let r of t.dataBinary)if(r.startsWith("@"))try{e.push(It(r.slice(1),"utf-8"))}catch{e.push(r)}else e.push(r);if(t.dataUrlencode)for(let r of t.dataUrlencode){let s=r.indexOf("=");if(s>0){let n=r.slice(0,s),i=r.slice(s+1);e.push(`${encodeURIComponent(n)}=${encodeURIComponent(i)}`)}else r.startsWith("=")?e.push(encodeURIComponent(r.slice(1))):e.push(encodeURIComponent(r))}if(t.dataAscii)for(let r of t.dataAscii)e.push(r);if(t.json)for(let r of t.json)e.push(r);if(e.length!==0)return e.join("&")}function mo(t){return!!(t.data&&t.data.length>0||t.dataRaw&&t.dataRaw.length>0||t.dataBinary&&t.dataBinary.length>0||t.dataUrlencode&&t.dataUrlencode.length>0||t.dataAscii&&t.dataAscii.length>0||t.json&&t.json.length>0)}function Hs(t){return!!(t.form&&t.form.length>0||t.formString&&t.formString.length>0)}function go(t){return t.request?t.request.toUpperCase():t.head?"HEAD":mo(t)&&!t.get||Hs(t)?"POST":t.uploadFile?"PUT":"GET"}async function js(t,e,r,s,n,i){let o=await t.text(),a=Buffer.byteLength(o,"utf-8");if(e.verbose){let l=uo(r,s,n);process.stderr.write(l+`
51
+ `);let u=ho(t.status,t.statusText,t.headers);process.stderr.write(u+`
52
+ `)}if(e.dumpHeader){let l=po(t.status,t.statusText,t.headers);e.dumpHeader==="-"?process.stdout.write(l):Ds(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
+ `),e.writeOut&&process.stdout.write(Er(e.writeOut,t,a,i)),process.exit(22)));let c="";e.include&&(c+=Us(t.status,t.statusText,t.headers)),e.head?!e.include&&!e.verbose&&(c+=Us(t.status,t.statusText,t.headers)):c+=o,e.output?e.output==="-"?process.stdout.write(c):Ds(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 Ls(t){return t instanceof H&&typeof t.actionUrl=="string"&&!!t.actionUrl}async function Ms(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 P of i.header){let j=P.indexOf(":");if(j>0){let D=P.slice(0,j).trim(),ge=P.slice(j+1).trim();ge===""?delete l[D]:l[D]=ge}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=po(i),d=uo(i),g=c;if(i.get&&d){let P=g.includes("?")?"&":"?";g=g+P+d,d=void 0}if(!d&&Ls(i)){let P=new FormData,j=(D,ge)=>{let le=D.indexOf("=");if(le<=0)return;let it=D.slice(0,le),X=D.slice(le+1);if(ge&&X.startsWith("@"))try{let Vt=Rt(X.slice(1)),wt=new Blob([Vt]);P.append(it,wt,oo(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 P.append(it,X)};if(i.form)for(let D of i.form)j(D,!0);if(i.formString)for(let D of i.formString)j(D,!1);d=P}if(i.uploadFile&&!d)try{d=Rt(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:g,method:u,headers:l,body:typeof d=="string"?d:void 0};let x=Date.now(),M=!1;try{let P=new URL(o.url);M=await Is(P.hostname,a.stateDir)}catch{}let Fe=i.retry?parseInt(i.retry,10):0,nt=i.retryDelay?parseInt(i.retryDelay,10)*1e3:1e3,te=null,re=null;for(let P=0;P<=Fe;P++)try{if(M){let j=await a.generateToken(),D=new Headers(o.headers);if(D.set("Authorization",`Bearer ${j}`),re=await fetch(o.url,{method:o.method,headers:D,body:o.body}),re.status===401){await a.keys.rotateCurrent();let ge=await a.generateToken(),le=new Headers(o.headers);le.set("Authorization",`Bearer ${ge}`),re=await fetch(o.url,{method:o.method,headers:le,body:o.body})}}else re=await a.fetch(o.url,{method:o.method,headers:o.headers,body:o.body});if(re.status>=500&&P<Fe){te=new Error(`HTTP ${re.status}`),await new Promise(j=>setTimeout(j,nt));continue}break}catch(j){if(te=j,P<Fe){await new Promise(D=>setTimeout(D,nt));continue}throw j}if(!re)throw te;await Us(re,i,o.method,o.url,o.headers,x)}catch(a){if(i.silent&&!i.showError&&process.exit(1),js(a)){if(i.waitOnAuthlink){process.stderr.write(`
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=go(i),d=fo(i),m=c;if(i.get&&d){let I=m.includes("?")?"&":"?";m=m+I+d,d=void 0}if(!d&&Hs(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 Kt=It(X.slice(1)),xt=new Blob([Kt]);I.append(ct,xt,lo(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 Ns(I.hostname,a.stateDir)}catch{}let Ee=i.retry?parseInt(i.retry,10):0,le=i.retryDelay?parseInt(i.retryDelay,10)*1e3:1e3,te=null,re=null;for(let I=0;I<=Ee;I++)try{if(R){let L=await a.generateToken(),U=new Headers(o.headers);if(U.set("Authorization",`Bearer ${L}`),re=await fetch(o.url,{method:o.method,headers:U,body:o.body}),re.status===401){await a.keys.rotateCurrent();let ye=await a.generateToken(),ue=new Headers(o.headers);ue.set("Authorization",`Bearer ${ye}`),re=await fetch(o.url,{method:o.method,headers:ue,body:o.body})}}else re=await a.fetch(o.url,{method:o.method,headers:o.headers,body:o.body});if(re.status>=500&&I<Ee){te=new Error(`HTTP ${re.status}`),await new Promise(L=>setTimeout(L,le));continue}break}catch(L){if(te=L,I<Ee){await new Promise(U=>setTimeout(U,le));continue}throw L}if(!re)throw te;await js(re,i,o.method,o.url,o.headers,x)}catch(a){if(i.silent&&!i.showError&&process.exit(1),Ls(a)){if(i.waitOnAuthlink){process.stderr.write(`
59
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
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,g=!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 M=await x.fetch(o.url,{method:o.method,headers:o.headers,body:o.body});process.stderr.write(`
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(`
66
66
 
67
- ${U("\u2713")} Authorization approved!
67
+ ${j("\u2713")} Authorization approved!
68
68
 
69
- `),g=!0,await Us(M,i,o.method,o.url,o.headers,Date.now());return}}catch(x){if(js(x))continue;throw x}}g||(process.stderr.write(`
69
+ `),m=!0,await js(R,i,o.method,o.url,o.headers,Date.now());return}}catch(x){if(Ls(x))continue;throw x}}m||(process.stderr.write(`
70
70
 
71
- ${R("Timed out waiting for approval.")}
71
+ ${P("Timed out waiting for approval.")}
72
72
 
73
73
  `),process.exit(1))}catch(c){process.stderr.write(`
74
74
 
75
- `),process.stderr.write(` ${R(c instanceof Error?c.message:String(c))}
75
+ `),process.stderr.write(` ${P(c instanceof Error?c.message:String(c))}
76
76
 
77
77
  `),process.exit(1)}}process.stderr.write(`
78
78
  `),process.stderr.write(` ${K("Credentials required:")} ${a.message}
@@ -81,7 +81,7 @@ curl: try 'botparty curl --help' for more information
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
- `);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}}It();Lr();var hn=[{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 $a(){console.log(`
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 mn=[{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 Pa(){console.log(`
85
85
  ${S("botparty services")} \u2014 discover and manage BotParty-compatible services
86
86
 
87
87
  ${S("USAGE")}
@@ -98,42 +98,42 @@ ${S("EXAMPLES")}
98
98
  botparty services example.com ${O("Discover actions on any domain")}
99
99
 
100
100
  ${S("BOTPARTY SERVICES")}
101
- `);let t=Math.max(...hn.map(e=>e.shorthand.length));for(let e of hn){let r=e.shorthand.padEnd(t+2);console.log(` ${b(r)}${e.description}`)}console.log(`
101
+ `);let t=Math.max(...mn.map(e=>e.shorthand.length));for(let e of mn){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 Ca(t){return t.includes(".")?t:`${t}.botparty.club`}async function pn(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){$a();return}let i=Ca(n),o=s[1]&&!s[1].startsWith("-")?s[1]:void 0,a=s.slice(o?2:1);try{o?await jr(i,o,a,t):await $r(i)}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)}}Pt();var C=!1;function N(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 Oa(t){if(C){let e={ok:!1};t instanceof L?e.error={code:t.code,message:t.message,statusCode:t.statusCode,...t.actionUrl&&{actionUrl:t.actionUrl},...t instanceof At&&t.amount&&{amount:t.amount},...t instanceof ft&&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 ir&&(console.error(`
104
- ${R("NAMESPACE LOCKED")}: ${t.message}`),t.actionUrl&&console.error(`
103
+ `)}function Ia(t){return t.includes(".")?t:`${t}.botparty.club`}async function gn(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){Pa();return}let i=Ia(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 Na(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(`
105
105
  A human must unlock it at:
106
- ${b(t.actionUrl)}`),process.exit(1)),t instanceof At&&(console.error(`
106
+ ${b(t.actionUrl)}`),process.exit(1)),t instanceof Tt&&(console.error(`
107
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
- ${b(t.actionUrl)}`),process.exit(1)),t instanceof ft&&(console.error(`
110
- ${R("PERMISSION DENIED")}: ${t.message}`),t.missingScopes?.length&&console.error(` Missing scopes: ${t.missingScopes.join(", ")}`),t.actionUrl&&console.error(`
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(`
111
111
  Grant access at:
112
- ${b(t.actionUrl)}`),process.exit(1)),t instanceof Et&&(console.error(`
112
+ ${b(t.actionUrl)}`),process.exit(1)),t instanceof $t&&(console.error(`
113
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 L&&(console.error(`
116
- ${R(t.code)}: ${t.message}`),t.actionUrl&&console.error(`
115
+ ${b(t.actionUrl)}`),process.exit(1)),t instanceof H&&(console.error(`
116
+ ${P(t.code)}: ${t.message}`),t.actionUrl&&console.error(`
117
117
  ${b(t.actionUrl)}`),process.exit(1)),t instanceof Error&&(console.error(`
118
- ${R("error")}: ${t.message}`),process.exit(1)),console.error(t),process.exit(1)}var Ra=new Set(["header","H"]);function Pa(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(Ra.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 I(t){return new gs({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 ee(t){return new Date(t).toLocaleString()}function Mr(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 Ia(t,e){let r=I(t);if(r.isRegistered()){let c=r.whoami();C?N({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?N({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
- ${U("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 Na(t){let r=I(t).whoami();r||T("Not registered. Run: botparty init"),C?N(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: ${ee(r.rotatedAt)}`),console.log(` Stale at: ${ee(r.staleAt)} (${Mr(r.staleAt)})`),r.label&&console.log(` Label: ${r.label}`),console.log(` Server: ${O(r.serverUrl)}`))}async function Da(t,e){let r=I(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?N(n):(console.log(S("Namespace Info")),console.log(` Namespace: ${b(n.namespace)}`),console.log(` Status: ${n.status==="active"?U(n.status):R(n.status)}`),console.log(` Linked: ${n.linked?U("yes"):K("no")}`),console.log(` Active keys: ${n.activeKeys}`),console.log(` Created: ${ee(n.createdAt)}`),n.lockedAt&&console.log(` Locked at: ${R(ee(n.lockedAt))}`))}async function Ua(t){let e=I(t);e.isRegistered()||T("Not registered. Run: botparty init");let{url:r}=await e.link();C?N({url:r}):(console.log(`Share this link with your human to claim ownership:
118
+ ${P("error")}: ${t.message}`),process.exit(1)),console.error(t),process.exit(1)}var Da=new Set(["header","H"]);function Ua(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(Da.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 ys({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 ee(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 ja(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 La(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: ${ee(r.rotatedAt)}`),console.log(` Stale at: ${ee(r.staleAt)} (${Vr(r.staleAt)})`),r.label&&console.log(` Label: ${r.label}`),console.log(` Server: ${O(r.serverUrl)}`))}async function Ha(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"):K("no")}`),console.log(` Active keys: ${n.activeKeys}`),console.log(` Created: ${ee(n.createdAt)}`),n.lockedAt&&console.log(` Locked at: ${P(ee(n.lockedAt))}`))}async function Ma(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:
122
122
  `),console.log(` ${b(r)}`),console.log(`
123
- ${O("The link expires in 5 minutes.")}`))}async function ja(t){let e=I(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 ${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?N({namespace:r.namespace,destroyed:!0}):console.log(`${U("Destroyed")} namespace ${S(r.namespace)}`)}async function La(t){I(t).reset(),C?N({reset:!0}):(console.log(`${U("Local state cleared.")} The namespace still exists on the server.`),console.log(`Run ${b("botparty init")} to register a new namespace.`))}async function Ha(t){let r=await I(t).generateToken();C?N({token:r}):console.log(r)}async function Ma(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 Hs(s,()=>I(t))}async function Va(t){let e=I(t),r=await e.keys.list();if(C){N({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(U("current"));let a=new Date(n.staleAt).getTime();Date.now()>a?o.push(R("stale")):o.push(`stale in ${Mr(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: ${ee(n.rotatedAt)}`),n.expiresAt&&console.log(` Expires at: ${ee(n.expiresAt)}`),n.lastUsedAt&&console.log(` Last used: ${ee(n.lastUsedAt)} from ${n.lastUsedIp}`),console.log("")}}async function Wa(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 I(t).keys.add({publicKey:i,label:e,scopes:r,rotationTTL:s,expiresAt:n});C?N(a):(console.log(`${U("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 Ka(t,e){let r=e[0]||void 0,s=I(t);C||console.log("Rotating key...");let n=await s.keys.rotate(r);C?N(n):(console.log(`
125
- ${U("Key rotated")}`),console.log(` ID: ${S(n.id)}`),console.log(` Fingerprint: ${n.fingerprint}`),console.log(` Stale at: ${ee(n.staleAt)} (${Mr(n.staleAt)})`))}async function Fa(t,e){let r=e[0];r||T("Usage: botparty keys delete <keyId>");let s=I(t);if(t.yes!==!0&&t.y!==!0){C&&T("--yes flag required to confirm deletion"),console.log(`${K("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?N({keyId:r,deleted:!0}):console.log(`${U("Deleted")} key ${S(r)}`)}async function Ba(t,e){let r=e[0];r||T("Usage: botparty keys invalidate <keyId>");let s=typeof t.reason=="string"?t.reason:void 0,n=I(t);if(t.yes!==!0&&t.y!==!0){C&&T("--yes flag required to confirm invalidation"),console.log(`${R("DANGER")}: This will invalidate key ${S(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?N({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 qa(t){let e=I(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?N(o):(console.log(`${U("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 Ga(t){let e=I(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){N({invites:i});return}if(i.length===0){console.log(O("No invites found."));return}console.log(`
123
+ ${O("The link expires in 5 minutes.")}`))}async function Va(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 Wa(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 Ka(t){let r=await N(t).generateToken();C?D({token:r}):console.log(r)}async function Fa(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 Ms(s,()=>N(t))}async function qa(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: ${ee(n.rotatedAt)}`),n.expiresAt&&console.log(` Expires at: ${ee(n.expiresAt)}`),n.lastUsedAt&&console.log(` Last used: ${ee(n.lastUsedAt)} from ${n.lastUsedIp}`),console.log("")}}async function Ba(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 Ga(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: ${ee(n.staleAt)} (${Vr(n.staleAt)})`))}async function za(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(`${K("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 Za(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 Ja(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 Ya(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
128
  ${S("Invites")} (${i.length})
129
- `);for(let o of i){let a=o.status==="active"?U(o.status):o.status==="pending"?K(o.status):R(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: ${ee(o.createdAt)}`),console.log("")}}async function za(t){let e=I(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){N({dependents:n});return}if(n.length===0){console.log(O("No dependents found."));return}console.log(`
129
+ `);for(let o of i){let a=o.status==="active"?j(o.status):o.status==="pending"?K(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: ${ee(o.createdAt)}`),console.log("")}}async function Xa(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
130
  ${S("Dependents")} (${n.length})
131
- `);for(let i of n){let o=i.status==="active"?U(i.status):i.status==="pending"?K(i.status):R(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: ${ee(i.createdAt)}`),i.revokedAt&&console.log(` Revoked: ${R(ee(i.revokedAt))}`),console.log("")}}async function Za(t,e){let r=e[0];r||T("Usage: botparty dependents revoke <tokenId>");let s=I(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 ${S(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?N({revoked:!0,tokenId:r,childNamespace:o.childNamespace}):(console.log(`${U("Revoked")} token ${S(r)}`),o.childNamespace&&console.log(` Child namespace ${S(o.childNamespace)} is now ${R("LOCKED")}.`))}async function Hr(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 Ja(t){let e=I(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 Hr(`/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){N({connections:o});return}if(o.length===0){console.log(O("No connections found."));return}console.log(`
131
+ `);for(let i of n){let o=i.status==="active"?j(i.status):i.status==="pending"?K(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: ${ee(i.createdAt)}`),i.revokedAt&&console.log(` Revoked: ${P(ee(i.revokedAt))}`),console.log("")}}async function Qa(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(`${K("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 ec(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
133
  ${S("Connections")} (${o.length})
134
- `);for(let a of o){let c=a.status==="active"?U("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(` ${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 Ya(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 Xa(t,e){let r=e[0];r||T("Usage: botparty connections delete <name|provider|id> [--yes]");let s=I(t),n=await Hr("/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=>Ya(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}":
134
+ `);for(let a of o){let c=a.status==="active"?j("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(` ${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 tc(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 rc(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=>tc(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
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 Hr(`/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?N({deleted:!0,connectionId:a.id,provider:a.provider}):console.log(`${U("Deleted")} ${S(a.displayName||a.provider)} (${a.id})`)}function Qa(){console.log(`
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 sc(){console.log(`
137
137
  ${S("botparty")} \u2014 federated bot identity, authentication, and payments
138
138
 
139
139
  ${S("USAGE")}
@@ -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 ec(){let{command:t,subcommand:e,positional:r,flags:s}=Pa(process.argv);if(s.json===!0&&(C=!0),s.version===!0||s.v===!0&&t!=="curl"&&t!=="fetch"||t==="version"){C?N({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 Tr(i))){Qa();return}}try{switch(t){case"init":case"join":await Ia(s,r);break;case"whoami":await Na(s);break;case"info":await Da(s,r);break;case"link":await Ua(s);break;case"destroy":await ja(s);break;case"reset":await La(s);break;case"token":await Ha(s);break;case"curl":case"fetch":await Ma(s);break;case"services":case"svc":await pn(()=>I(s));break;case"keys":switch(e){case"list":case"ls":await Va(s);break;case"add":await Wa(s);break;case"rotate":await Ka(s,r);break;case"delete":case"rm":await Fa(s,r);break;case"invalidate":case"panic":await Ba(s,r);break;default:T(`Unknown keys subcommand: ${e||"(none)"}. Run: botparty keys list`)}break;case"invites":switch(e){case"create":await qa(s);break;case"list":case"ls":case"":await Ga(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 za(s);break;case"revoke":await Za(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 Ja(s);break;case"delete":case"rm":await Xa(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 Tr(n)){let{discover:o}=await Promise.resolve().then(()=>(It(),Ws)),{execute:a}=await Promise.resolve().then(()=>(Lr(),dn)),c=process.argv.slice(2),l=c.indexOf(t),u=l>=0?c.slice(l+1):[],d=u[0]&&!u[0].startsWith("-")?u[0]:void 0,g=u.slice(d?1:0);try{d?await a(n,d,g,()=>I(s)):await o(n)}catch(x){x.code==="ENOTFOUND"||x.cause?.code==="ENOTFOUND"?console.error(`${R("error")}: Could not connect to ${n}`):console.error(`${R("error")}: ${x.message||x}`),process.exit(1)}}else T(`Unknown command: ${t}. Run: botparty --help`);break}}}catch(n){Oa(n)}}ec();
214
+ `)}async function nc(){let{command:t,subcommand:e,positional:r,flags:s}=Ua(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))){sc();return}}try{switch(t){case"init":case"join":await ja(s,r);break;case"whoami":await La(s);break;case"info":await Ha(s,r);break;case"link":await Ma(s);break;case"destroy":await Va(s);break;case"reset":await Wa(s);break;case"token":await Ka(s);break;case"curl":case"fetch":await Fa(s);break;case"services":case"svc":await gn(()=>N(s));break;case"keys":switch(e){case"list":case"ls":await qa(s);break;case"add":await Ba(s);break;case"rotate":await Ga(s,r);break;case"delete":case"rm":await za(s,r);break;case"invalidate":case"panic":await Za(s,r);break;default:T(`Unknown keys subcommand: ${e||"(none)"}. Run: botparty keys list`)}break;case"invites":switch(e){case"create":await Ja(s);break;case"list":case"ls":case"":await Ya(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 Xa(s);break;case"revoke":await Qa(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 ec(s);break;case"delete":case"rm":await rc(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(),fn)),{fetchServicesIndex:c}=await Promise.resolve().then(()=>(Qe(),Vs)),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){Na(n)}}nc();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "botparty",
3
- "version": "0.0.45",
3
+ "version": "0.0.47",
4
4
  "description": "CLI for BotParty — federated bot identity, authentication, and payments",
5
5
  "type": "module",
6
6
  "bin": {