botparty 0.0.42 → 0.0.43
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +113 -113
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,70 +1,70 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __createRequire } from "module";
|
|
3
3
|
const require = __createRequire(import.meta.url);
|
|
4
|
-
var
|
|
5
|
-
`)}displayWidth(e){return
|
|
4
|
+
var mn=Object.create;var Vt=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 M=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ae=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Wt=(t,e)=>{for(var r in e)Vt(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&&Vt(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?Vt(r,"default",{value:t,enumerable:!0}):r,t));var mt=Ae(ar=>{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}},or=class extends Tt{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};ar.CommanderError=Tt;ar.InvalidArgumentError=or});var Ct=Ae(lr=>{var{InvalidArgumentError:Ii}=mt(),cr=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+"]"}lr.Argument=cr;lr.humanReadableArgName=Ni});var hr=Ae(dr=>{var{humanReadableArgName:Di}=Ct(),ur=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,y){return r.formatItem(d,s,y,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,y)=>{let k=d.map(W=>i(r.styleOptionTerm(r.optionTerm(W)),r.styleOptionDescription(r.optionDescription(W))));o=o.concat(this.formatItemList(y,k,r))}),r.showGlobalOptions){let d=r.visibleGlobalOptions(e).map(y=>i(r.styleOptionTerm(r.optionTerm(y)),r.styleOptionDescription(r.optionDescription(y))));o=o.concat(this.formatItemList("Global Options:",d,r))}return this.groupItems(e.commands,r.visibleCommands(e),d=>d.helpGroup()||"Commands:").forEach((d,y)=>{let k=d.map(W=>i(r.styleSubcommandTerm(r.subcommandTerm(W)),r.styleSubcommandDescription(r.subcommandDescription(W))));o=o.concat(this.formatItemList(y,k,r))}),o.join(`
|
|
5
|
+
`)}displayWidth(e){return gs(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
|
|
8
|
-
`)}};function
|
|
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 y=u.trimStart();c=[y],l=this.displayWidth(y)}),i.push(c.join(""))}),i.join(`
|
|
8
|
+
`)}};function gs(t){let e=/\x1b\[\d*(;\d*)*m/g;return t.replace(e,"")}dr.Help=ur;dr.stripColor=gs});var gr=Ae(mr=>{var{InvalidArgumentError:Ui}=mt(),pr=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?ys(this.name().replace(/^no-/,"")):ys(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}},fr=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 ys(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}
|
|
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}}
|
|
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}}mr.Option=pr;mr.DualOptions=fr});var _s=Ae(vs=>{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?`
|
|
15
15
|
(Did you mean one of ${s.join(", ")}?)`:s.length===1?`
|
|
16
|
-
(Did you mean ${s[0]}?)`:""}
|
|
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
|
|
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
|
|
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
|
|
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(
|
|
16
|
+
(Did you mean ${s[0]}?)`:""}vs.suggestSimilar=Hi});var xs=Ae(wr=>{var Mi=ct("node:events").EventEmitter,yr=ct("node:child_process"),de=ct("node:path"),$t=ct("node:fs"),T=ct("node:process"),{Argument:Vi,humanReadableArgName:Wi}=Ct(),{CommanderError:vr}=mt(),{Help:Ki,stripColor:Fi}=hr(),{Option:bs,DualOptions:Bi}=gr(),{suggestSimilar:ws}=_s(),_r=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=>T.stdout.write(r),writeErr:r=>T.stderr.write(r),outputError:(r,s)=>s(r),getOutHelpWidth:()=>T.stdout.isTTY?T.stdout.columns:void 0,getErrHelpWidth:()=>T.stderr.isTTY?T.stderr.columns:void 0,getOutHasColors:()=>br()??(T.stdout.isTTY&&T.stdout.hasColors?.()),getErrHasColors:()=>br()??(T.stderr.isTTY&&T.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 vr(e,r,s)),T.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 bs(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 bs)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){T.versions?.electron&&(r.from="electron");let n=T.execArgv??[];(n.includes("-e")||n.includes("--eval")||n.includes("-p")||n.includes("--print"))&&(r.from="eval")}e===void 0&&(e=T.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":T.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($t.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
|
|
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 y=de.resolve(u,d);if($t.existsSync(y))return y;if(n.includes(de.extname(d)))return;let k=n.find(W=>$t.existsSync(`${y}${W}`));if(k)return`${y}${k}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let u;try{u=$t.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;T.platform!=="win32"?s?(r.unshift(o),r=ks(T.execArgv).concat(r),c=yr.spawn(T.argv[0],r,{stdio:"inherit"})):c=yr.spawn(o,r,{stdio:"inherit"}):(this._checkForMissingExecutable(o,a,e._name),r.unshift(o),r=ks(T.execArgv).concat(r),c=yr.spawn(T.execPath,r,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(d=>{T.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 vr(u,"commander.executeSubCommandAsync","(close)")):T.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)T.exit(1);else{let d=new vr(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(y=>y.short).some(y=>/^-\d$/.test(y))):!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 y=e[l++];y===void 0&&this.optionMissingArgument(d),this.emit(`option:${d.name()}`,y)}else if(d.optional){let y=null;l<e.length&&(!i(e[l])||o(e[l]))&&(y=e[l++]),this.emit(`option:${d.name()}`,y)}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("="),y=this._findOption(u.slice(0,d));if(y&&(y.required||y.optional)){this.emit(`option:${y.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 T.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()}`,T.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new
|
|
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=>
|
|
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 T.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()}`,T.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=ws(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=ws(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(T.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
|
|
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 br(){if(T.env.NO_COLOR||T.env.FORCE_COLOR==="0"||T.env.FORCE_COLOR==="false")return!1;if(T.env.FORCE_COLOR||T.env.CLICOLOR_FORCE!==void 0)return!0}wr.Command=_r;wr.useColor=br});var Ts=Ae(z=>{var{Argument:Ss}=Ct(),{Command:kr}=xs(),{CommanderError:qi,InvalidArgumentError:As}=mt(),{Help:Gi}=hr(),{Option:Es}=gr();z.program=new kr;z.createCommand=t=>new kr(t);z.createOption=(t,e)=>new Es(t,e);z.createArgument=(t,e)=>new Ss(t,e);z.Command=kr;z.Option=Es;z.Argument=Ss;z.Help=Gi;z.CommanderError=qi;z.InvalidArgumentError=As;z.InvalidOptionArgumentError=As});var Cs,Pc,Ic,Nc,Dc,Uc,jc,Lc,Ot,Hc,Mc,Vc,xr=M(()=>{Cs=wn(Ts(),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 Ar(t){return(t.includes("://")?t:`https://${t}`).replace(/\/$/,"")}async function gt(t){let e=`${Ar(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 Hs(t,e){let r=`${Ar(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 Ms(t){try{let e=`${Ar(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=M(()=>{"use strict"});var Ws={};Wt(Ws,{discover:()=>Er,listSubActions:()=>Tr});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 Er(t){let e=await gt(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=
|
|
31
|
+
`);let r=fo(e.actions);Vs(r),console.log()}async function Tr(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(`
|
|
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 At=V(()=>{"use strict";St()});var S,_r,f,ne,ut=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})(S||(S={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(_r||(_r={}));f=S.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ne=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,oo,q,Et=V(()=>{ut();h=S.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"]),oo=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),q=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(i){return i.message},s={_errors:[]},n=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(n);else if(o.code==="invalid_return_type")n(o.returnTypeError);else if(o.code==="invalid_arguments")n(o.argumentsError);else if(o.path.length===0)s._errors.push(r(o));else{let a=s,c=0;for(;c<o.path.length;){let l=o.path[c];c===o.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(r(o))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return n(this),s}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,S.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},s=[];for(let n of this.issues)if(n.path.length>0){let i=n.path[0];r[i]=r[i]||[],r[i].push(e(n))}else s.push(e(n));return{formErrors:s,fieldErrors:r}}get formErrors(){return this.flatten()}};q.create=t=>new q(t)});var ao,le,br=V(()=>{Et();ut();ao=(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,S.jsonStringifyReplacer)}`;break;case h.unrecognized_keys:r=`Unrecognized key(s) in object: ${S.joinValues(t.keys,", ")}`;break;case h.invalid_union:r="Invalid input";break;case h.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${S.joinValues(t.options)}`;break;case h.invalid_enum_value:r=`Invalid enum value. Expected ${S.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}"`:S.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,S.assertNever(t)}return{message:r}},le=ao});function co(t){Is=t}function qe(){return Is}var Is,Tt=V(()=>{br();Is=le});function p(t,e){let r=qe(),s=dt({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===le?void 0:le].filter(n=>!!n)});t.common.issues.push(s)}var dt,lo,H,y,Se,M,$t,Ct,me,Be,wr=V(()=>{Tt();br();dt=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}},lo=[];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 y;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 y;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}}},y=Object.freeze({status:"aborted"}),Se=t=>({status:"dirty",value:t}),M=t=>({status:"valid",value:t}),$t=t=>t.status==="aborted",Ct=t=>t.status==="dirty",me=t=>t.status==="valid",Be=t=>typeof Promise<"u"&&t instanceof Promise});var Ns=V(()=>{});var m,Ds=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 Hs(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 To(t){return new RegExp(`^${Hs(t)}$`)}function Ms(t){let e=`${Ls}T${Hs(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 $o(t,e){return!!((e==="v4"||!e)&&bo.test(t)||(e==="v6"||!e)&&xo.test(t))}function Co(t,e){if(!go.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 Oo(t,e){return!!((e==="v4"||!e)&&wo.test(t)||(e==="v6"||!e)&&ko.test(t))}function Ro(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 Ge(t){if(t instanceof B){let e={};for(let r in t.shape){let s=t.shape[r];e[r]=J.create(Ge(s))}return new B({...t._def,shape:()=>e})}else return t instanceof he?new he({...t._def,type:Ge(t.element)}):t instanceof J?J.create(Ge(t.unwrap())):t instanceof oe?oe.create(Ge(t.unwrap())):t instanceof ie?ie.create(t.items.map(e=>Ge(e))):t}function kr(t,e){let r=ne(t),s=ne(e);if(t===e)return{valid:!0,data:t};if(r===f.object&&s===f.object){let n=S.objectKeys(e),i=S.objectKeys(t).filter(a=>n.indexOf(a)!==-1),o={...t,...e};for(let a of i){let c=kr(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=kr(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 Vs(t,e){return new De({values:t,typeName:v.ZodEnum,...w(e)})}function js(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Ws(t,e={},r){return t?ye.create().superRefine((s,n)=>{let i=t(s);if(i instanceof Promise)return i.then(o=>{if(!o){let a=js(e,s),c=a.fatal??r??!0;n.addIssue({code:"custom",...a,fatal:c})}});if(!i){let o=js(e,s),a=o.fatal??r??!0;n.addIssue({code:"custom",...o,fatal:a})}}):ye.create()}var Y,Us,x,uo,ho,po,fo,mo,go,yo,vo,_o,xr,bo,wo,xo,ko,So,Ao,Ls,Eo,ge,Ae,Ee,Te,$e,ze,Ce,Oe,ye,de,ee,Ze,he,B,Re,ue,Ot,Pe,ie,Rt,Je,Ye,Pt,Ie,Ne,De,Ue,ve,X,J,oe,je,Le,Xe,Po,ht,pt,He,Io,v,No,Ks,Fs,Do,Uo,qs,jo,Lo,Ho,Mo,Vo,Wo,Ko,Fo,qo,Bo,Go,zo,Zo,Jo,Yo,Xo,Qo,ea,ta,ra,sa,na,ia,oa,aa,ca,la,ua,da,ha,pa,fa,ma,ga,Bs=V(()=>{Et();Tt();Ds();wr();ut();Y=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}},Us=(t,e)=>{if(me(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new q(t.common.issues);return this._error=r,this._error}}};x=class{get description(){return this._def.description}_getType(e){return ne(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:ne(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:ne(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Be(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:ne(e)},n=this._parseSync({data:e,path:s.path,parent:s});return Us(s,n)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ne(e)};if(!this["~standard"].async)try{let s=this._parseSync({data:e,path:[],parent:r});return me(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=>me(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:ne(e)},n=this._parse({data:e,path:s.path,parent:s}),i=await(Be(n)?n:Promise.resolve(n));return Us(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 X({schema:this,typeName:v.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 J.create(this,this._def)}nullable(){return oe.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return he.create(this)}promise(){return ve.create(this,this._def)}or(e){return Re.create([this,e],this._def)}and(e){return Pe.create(this,e,this._def)}transform(e){return new X({...w(this._def),schema:this,typeName:v.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new je({...w(this._def),innerType:this,defaultValue:r,typeName:v.ZodDefault})}brand(){return new ht({typeName:v.ZodBranded,type:this,...w(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Le({...w(this._def),innerType:this,catchValue:r,typeName:v.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return pt.create(this,e)}readonly(){return He.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},uo=/^c[^\s-]{8,}$/i,ho=/^[0-9a-z]+$/,po=/^[0-9A-HJKMNP-TV-Z]{26}$/i,fo=/^[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,mo=/^[a-z0-9_-]{21}$/i,go=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,yo=/^[-+]?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)?)??$/,vo=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_o="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",bo=/^(?:(?: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])$/,wo=/^(?:(?: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])$/,xo=/^(([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]))$/,ko=/^(([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])$/,So=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ao=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ls="((\\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])))",Eo=new RegExp(`^${Ls}$`);ge=class t extends x{_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}),y}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")vo.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")xr||(xr=new RegExp(_o,"u")),xr.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")fo.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")mo.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")uo.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")ho.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")po.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"?Ms(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"?Eo.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:h.invalid_string,validation:"date",message:i.message}),s.dirty()):i.kind==="time"?To(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"?yo.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"duration",code:h.invalid_string,message:i.message}),s.dirty()):i.kind==="ip"?$o(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"?Co(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"?Oo(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"?So.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"base64",code:h.invalid_string,message:i.message}),s.dirty()):i.kind==="base64url"?Ao.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"base64url",code:h.invalid_string,message:i.message}),s.dirty()):S.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}};ge.create=t=>new ge({checks:[],typeName:v.ZodString,coerce:t?.coerce??!1,...w(t)});Ae=class t extends x{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}),y}let s,n=new H;for(let i of this._def.checks)i.kind==="int"?S.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"?Ro(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()):S.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"&&S.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)}};Ae.create=t=>new Ae({checks:[],typeName:v.ZodNumber,coerce:t?.coerce||!1,...w(t)});Ee=class t extends x{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()):S.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}),y}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}};Ee.create=t=>new Ee({checks:[],typeName:v.ZodBigInt,coerce:t?.coerce??!1,...w(t)});Te=class extends x{_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}),y}return M(e.data)}};Te.create=t=>new Te({typeName:v.ZodBoolean,coerce:t?.coerce||!1,...w(t)});$e=class t extends x{_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}),y}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return p(i,{code:h.invalid_date}),y}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()):S.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}};$e.create=t=>new $e({checks:[],coerce:t?.coerce||!1,typeName:v.ZodDate,...w(t)});ze=class extends x{_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}),y}return M(e.data)}};ze.create=t=>new ze({typeName:v.ZodSymbol,...w(t)});Ce=class extends x{_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}),y}return M(e.data)}};Ce.create=t=>new Ce({typeName:v.ZodUndefined,...w(t)});Oe=class extends x{_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}),y}return M(e.data)}};Oe.create=t=>new Oe({typeName:v.ZodNull,...w(t)});ye=class extends x{constructor(){super(...arguments),this._any=!0}_parse(e){return M(e.data)}};ye.create=t=>new ye({typeName:v.ZodAny,...w(t)});de=class extends x{constructor(){super(...arguments),this._unknown=!0}_parse(e){return M(e.data)}};de.create=t=>new de({typeName:v.ZodUnknown,...w(t)});ee=class extends x{_parse(e){let r=this._getOrReturnCtx(e);return p(r,{code:h.invalid_type,expected:f.never,received:r.parsedType}),y}};ee.create=t=>new ee({typeName:v.ZodNever,...w(t)});Ze=class extends x{_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}),y}return M(e.data)}};Ze.create=t=>new Ze({typeName:v.ZodVoid,...w(t)});he=class t extends x{_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}),y;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 Y(r,o,r.path,a)))).then(o=>H.mergeArray(s,o));let i=[...r.data].map((o,a)=>n.type._parseSync(new Y(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)}};he.create=(t,e)=>new he({type:t,minLength:null,maxLength:null,exactLength:null,typeName:v.ZodArray,...w(e)});B=class t extends x{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=S.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}),y}let{status:s,ctx:n}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof ee&&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 Y(n,d,n.path,l)),alwaysSet:l in n.data})}if(this._def.catchall instanceof ee){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 Y(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:v.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 S.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 S.objectKeys(this.shape))e[s]||(r[s]=this.shape[s]);return new t({...this._def,shape:()=>r})}deepPartial(){return Ge(this)}partial(e){let r={};for(let s of S.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 S.objectKeys(this.shape))if(e&&!e[s])r[s]=this.shape[s];else{let i=this.shape[s];for(;i instanceof J;)i=i._def.innerType;r[s]=i}return new t({...this._def,shape:()=>r})}keyof(){return Vs(S.objectKeys(this.shape))}};B.create=(t,e)=>new B({shape:()=>t,unknownKeys:"strip",catchall:ee.create(),typeName:v.ZodObject,...w(e)});B.strictCreate=(t,e)=>new B({shape:()=>t,unknownKeys:"strict",catchall:ee.create(),typeName:v.ZodObject,...w(e)});B.lazycreate=(t,e)=>new B({shape:t,unknownKeys:"strip",catchall:ee.create(),typeName:v.ZodObject,...w(e)});Re=class extends x{_parse(e){let{ctx:r}=this._processInputParams(e),s=this._def.options;function n(i){for(let a of i)if(a.result.status==="valid")return a.result;for(let a of i)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(a=>new q(a.ctx.common.issues));return p(r,{code:h.invalid_union,unionErrors:o}),y}if(r.common.async)return Promise.all(s.map(async i=>{let o={...r,common:{...r.common,issues:[]},parent:null};return{result:await i._parseAsync({data:r.data,path:r.path,parent:o}),ctx:o}})).then(n);{let i,o=[];for(let c of s){let l={...r,common:{...r.common,issues:[]},parent:null},u=c._parseSync({data:r.data,path:r.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!i&&(i={result:u,ctx:l}),l.common.issues.length&&o.push(l.common.issues)}if(i)return r.common.issues.push(...i.ctx.common.issues),i.result;let a=o.map(c=>new q(c));return p(r,{code:h.invalid_union,unionErrors:a}),y}}get options(){return this._def.options}};Re.create=(t,e)=>new Re({options:t,typeName:v.ZodUnion,...w(e)});ue=t=>t instanceof Ie?ue(t.schema):t instanceof X?ue(t.innerType()):t instanceof Ne?[t.value]:t instanceof De?t.options:t instanceof Ue?S.objectValues(t.enum):t instanceof je?ue(t._def.innerType):t instanceof Ce?[void 0]:t instanceof Oe?[null]:t instanceof J?[void 0,...ue(t.unwrap())]:t instanceof oe?[null,...ue(t.unwrap())]:t instanceof ht||t instanceof He?ue(t.unwrap()):t instanceof Le?ue(t._def.innerType):[],Ot=class t extends x{_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}),y;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]}),y)}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=ue(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:v.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:n,...w(s)})}};Pe=class extends x{_parse(e){let{status:r,ctx:s}=this._processInputParams(e),n=(i,o)=>{if($t(i)||$t(o))return y;let a=kr(i.value,o.value);return a.valid?((Ct(i)||Ct(o))&&r.dirty(),{status:r.value,value:a.data}):(p(s,{code:h.invalid_intersection_types}),y)};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}))}};Pe.create=(t,e,r)=>new Pe({left:t,right:e,typeName:v.ZodIntersection,...w(r)});ie=class t extends x{_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}),y;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"}),y;!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 Y(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})}};ie.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ie({items:t,typeName:v.ZodTuple,rest:null,...w(e)})};Rt=class t extends x{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}),y;let n=[],i=this._def.keyType,o=this._def.valueType;for(let a in s.data)n.push({key:i._parse(new Y(s,a,s.path,a)),value:o._parse(new Y(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 x?new t({keyType:e,valueType:r,typeName:v.ZodRecord,...w(s)}):new t({keyType:ge.create(),valueType:e,typeName:v.ZodRecord,...w(r)})}},Je=class extends x{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}),y;let n=this._def.keyType,i=this._def.valueType,o=[...s.data.entries()].map(([a,c],l)=>({key:n._parse(new Y(s,a,s.path,[l,"key"])),value:i._parse(new Y(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 y;(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 y;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(l.value,u.value)}return{status:r.value,value:a}}}};Je.create=(t,e,r)=>new Je({valueType:e,keyType:t,typeName:v.ZodMap,...w(r)});Ye=class t extends x{_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}),y;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 y;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 Y(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)}};Ye.create=(t,e)=>new Ye({valueType:t,minSize:null,maxSize:null,typeName:v.ZodSet,...w(e)});Pt=class t extends x{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}),y;function s(a,c){return dt({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,qe(),le].filter(l=>!!l),issueData:{code:h.invalid_arguments,argumentsError:c}})}function n(a,c){return dt({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,qe(),le].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 ve){let a=this;return M(async function(...c){let l=new q([]),u=await a._def.args.parseAsync(c,i).catch(A=>{throw l.addIssue(s(c,A)),l}),d=await Reflect.apply(o,this,u);return await a._def.returns._def.type.parseAsync(d,i).catch(A=>{throw l.addIssue(n(d,A)),l})})}else{let a=this;return M(function(...c){let l=a._def.args.safeParse(c,i);if(!l.success)throw new q([s(c,l.error)]);let u=Reflect.apply(o,this,l.data),d=a._def.returns.safeParse(u,i);if(!d.success)throw new q([n(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:ie.create(e).rest(de.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||ie.create([]).rest(de.create()),returns:r||de.create(),typeName:v.ZodFunction,...w(s)})}},Ie=class extends x{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})}};Ie.create=(t,e)=>new Ie({getter:t,typeName:v.ZodLazy,...w(e)});Ne=class extends x{_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}),y}return{status:"valid",value:e.data}}get value(){return this._def.value}};Ne.create=(t,e)=>new Ne({value:t,typeName:v.ZodLiteral,...w(e)});De=class t extends x{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),s=this._def.values;return p(r,{expected:S.joinValues(s),received:r.parsedType,code:h.invalid_type}),y}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}),y}return M(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})}};De.create=Vs;Ue=class extends x{_parse(e){let r=S.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==f.string&&s.parsedType!==f.number){let n=S.objectValues(r);return p(s,{expected:S.joinValues(n),received:s.parsedType,code:h.invalid_type}),y}if(this._cache||(this._cache=new Set(S.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let n=S.objectValues(r);return p(s,{received:s.data,code:h.invalid_enum_value,options:n}),y}return M(e.data)}get enum(){return this._def.values}};Ue.create=(t,e)=>new Ue({values:t,typeName:v.ZodNativeEnum,...w(e)});ve=class extends x{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}),y;let s=r.parsedType===f.promise?r.data:Promise.resolve(r.data);return M(s.then(n=>this._def.type.parseAsync(n,{path:r.path,errorMap:r.common.contextualErrorMap})))}};ve.create=(t,e)=>new ve({type:t,typeName:v.ZodPromise,...w(e)});X=class extends x{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===v.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 y;let c=await this._def.schema._parseAsync({data:a,path:s.path,parent:s});return c.status==="aborted"?y:c.status==="dirty"?Se(c.value):r.value==="dirty"?Se(c.value):c});{if(r.value==="aborted")return y;let a=this._def.schema._parseSync({data:o,path:s.path,parent:s});return a.status==="aborted"?y:a.status==="dirty"?Se(a.value):r.value==="dirty"?Se(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"?y:(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"?y:(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(!me(o))return y;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=>me(o)?Promise.resolve(n.transform(o.value,i)).then(a=>({status:r.value,value:a})):y);S.assertNever(n)}};X.create=(t,e,r)=>new X({schema:t,typeName:v.ZodEffects,effect:e,...w(r)});X.createWithPreprocess=(t,e,r)=>new X({schema:e,effect:{type:"preprocess",transform:t},typeName:v.ZodEffects,...w(r)});J=class extends x{_parse(e){return this._getType(e)===f.undefined?M(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};J.create=(t,e)=>new J({innerType:t,typeName:v.ZodOptional,...w(e)});oe=class extends x{_parse(e){return this._getType(e)===f.null?M(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};oe.create=(t,e)=>new oe({innerType:t,typeName:v.ZodNullable,...w(e)});je=class extends x{_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}};je.create=(t,e)=>new je({innerType:t,typeName:v.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...w(e)});Le=class extends x{_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 Be(n)?n.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new q(s.common.issues)},input:s.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new q(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};Le.create=(t,e)=>new Le({innerType:t,typeName:v.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...w(e)});Xe=class extends x{_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}),y}return{status:"valid",value:e.data}}};Xe.create=t=>new Xe({typeName:v.ZodNaN,...w(t)});Po=Symbol("zod_brand"),ht=class extends x{_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}},pt=class t extends x{_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"?y:i.status==="dirty"?(r.dirty(),Se(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"?y: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:v.ZodPipeline})}},He=class extends x{_parse(e){let r=this._def.innerType._parse(e),s=n=>(me(n)&&(n.value=Object.freeze(n.value)),n);return Be(r)?r.then(n=>s(n)):s(r)}unwrap(){return this._def.innerType}};He.create=(t,e)=>new He({innerType:t,typeName:v.ZodReadonly,...w(e)});Io={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"})(v||(v={}));No=(t,e={message:`Input not instance of ${t.name}`})=>Ws(r=>r instanceof t,e),Ks=ge.create,Fs=Ae.create,Do=Xe.create,Uo=Ee.create,qs=Te.create,jo=$e.create,Lo=ze.create,Ho=Ce.create,Mo=Oe.create,Vo=ye.create,Wo=de.create,Ko=ee.create,Fo=Ze.create,qo=he.create,Bo=B.create,Go=B.strictCreate,zo=Re.create,Zo=Ot.create,Jo=Pe.create,Yo=ie.create,Xo=Rt.create,Qo=Je.create,ea=Ye.create,ta=Pt.create,ra=Ie.create,sa=Ne.create,na=De.create,ia=Ue.create,oa=ve.create,aa=X.create,ca=J.create,la=oe.create,ua=X.createWithPreprocess,da=pt.create,ha=()=>Ks().optional(),pa=()=>Fs().optional(),fa=()=>qs().optional(),ma={string:(t=>ge.create({...t,coerce:!0})),number:(t=>Ae.create({...t,coerce:!0})),boolean:(t=>Te.create({...t,coerce:!0})),bigint:(t=>Ee.create({...t,coerce:!0})),date:(t=>$e.create({...t,coerce:!0}))},ga=y});var G={};Nt(G,{BRAND:()=>Po,DIRTY:()=>Se,EMPTY_PATH:()=>lo,INVALID:()=>y,NEVER:()=>ga,OK:()=>M,ParseStatus:()=>H,Schema:()=>x,ZodAny:()=>ye,ZodArray:()=>he,ZodBigInt:()=>Ee,ZodBoolean:()=>Te,ZodBranded:()=>ht,ZodCatch:()=>Le,ZodDate:()=>$e,ZodDefault:()=>je,ZodDiscriminatedUnion:()=>Ot,ZodEffects:()=>X,ZodEnum:()=>De,ZodError:()=>q,ZodFirstPartyTypeKind:()=>v,ZodFunction:()=>Pt,ZodIntersection:()=>Pe,ZodIssueCode:()=>h,ZodLazy:()=>Ie,ZodLiteral:()=>Ne,ZodMap:()=>Je,ZodNaN:()=>Xe,ZodNativeEnum:()=>Ue,ZodNever:()=>ee,ZodNull:()=>Oe,ZodNullable:()=>oe,ZodNumber:()=>Ae,ZodObject:()=>B,ZodOptional:()=>J,ZodParsedType:()=>f,ZodPipeline:()=>pt,ZodPromise:()=>ve,ZodReadonly:()=>He,ZodRecord:()=>Rt,ZodSchema:()=>x,ZodSet:()=>Ye,ZodString:()=>ge,ZodSymbol:()=>ze,ZodTransformer:()=>X,ZodTuple:()=>ie,ZodType:()=>x,ZodUndefined:()=>Ce,ZodUnion:()=>Re,ZodUnknown:()=>de,ZodVoid:()=>Ze,addIssueToContext:()=>p,any:()=>Vo,array:()=>qo,bigint:()=>Uo,boolean:()=>qs,coerce:()=>ma,custom:()=>Ws,date:()=>jo,datetimeRegex:()=>Ms,defaultErrorMap:()=>le,discriminatedUnion:()=>Zo,effect:()=>aa,enum:()=>na,function:()=>ta,getErrorMap:()=>qe,getParsedType:()=>ne,instanceof:()=>No,intersection:()=>Jo,isAborted:()=>$t,isAsync:()=>Be,isDirty:()=>Ct,isValid:()=>me,late:()=>Io,lazy:()=>ra,literal:()=>sa,makeIssue:()=>dt,map:()=>Qo,nan:()=>Do,nativeEnum:()=>ia,never:()=>Ko,null:()=>Mo,nullable:()=>la,number:()=>Fs,object:()=>Bo,objectUtil:()=>_r,oboolean:()=>fa,onumber:()=>pa,optional:()=>ca,ostring:()=>ha,pipeline:()=>da,preprocess:()=>ua,promise:()=>oa,quotelessJson:()=>oo,record:()=>Xo,set:()=>ea,setErrorMap:()=>co,strictObject:()=>Go,string:()=>Ks,symbol:()=>Lo,transformer:()=>aa,tuple:()=>Yo,undefined:()=>Ho,union:()=>zo,unknown:()=>Wo,util:()=>S,void:()=>Fo});var Sr=V(()=>{Tt();wr();Ns();ut();Bs();Et()});var Gs=V(()=>{Sr();Sr()});function zs(t){switch(t.type){case"string":{let e=G.string();return t.pattern&&(e=e.regex(new RegExp(t.pattern))),t.minLength&&(e=e.min(t.minLength)),t.maxLength&&(e=e.max(t.maxLength)),t.enum?G.enum(t.enum):e}case"integer":case"number":{let e=t.type==="integer"?G.coerce.number().int():G.coerce.number();return t.minimum!==void 0&&(e=e.min(t.minimum)),t.maximum!==void 0&&(e=e.max(t.maximum)),e}case"boolean":return G.preprocess(e=>e==="true"||e===!0?!0:e==="false"||e===!1?!1:e,G.boolean());case"array":return G.array(t.items?zs(t.items):G.any());case"object":return G.record(G.any());default:return G.any()}}function Zs(t,e){let r=zs(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 Js=V(()=>{"use strict";Gs()});import*as _e from"node:fs";import*as te from"node:path";function va(t){let e=te.extname(t).toLowerCase();return!!(ya.has(e)||e==="")}function Ys(t){let e=te.resolve(t),r=_e.readFileSync(e),s=te.relative(process.cwd(),e);if(va(t))return{path:s,contents:r.toString("utf-8")};let n=te.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 Xs(t){let e=[];for(let r of t){let s=te.resolve(r);if(_e.statSync(s).isDirectory()){let i=Qs(s);for(let o of i)e.push(Ys(o))}else e.push(Ys(s))}return e}function Qs(t){let e=[],r=_e.readdirSync(t,{withFileTypes:!0});for(let s of r){let n=te.join(t,s.name);s.isDirectory()?e.push(...Qs(n)):e.push(n)}return e}function en(t){if(t.startsWith("-"))return!1;try{let e=te.resolve(t);return _e.existsSync(e)}catch{return!1}}var ya,tn=V(()=>{"use strict";ya=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 rn={};Nt(rn,{execute:()=>Ar});function _a(t,e){let r={},s=[],n=[...e.params.path,...e.params.query,...e.params.body],i=new Map(n.map(a=>[a.name,a])),o=0;for(;o<t.length;){let a=t[o];if(a.startsWith("--")){let c=a.slice(2);if(c==="file"||c==="files"){for(o++;o<t.length&&!t[o].startsWith("--");)s.push(t[o]),o++;continue}let l=i.get(c),u=t[o+1];if(l?.type?.type==="boolean"&&(!u||u.startsWith("--"))){r[c]=!0,o++;continue}u!==void 0&&!u.startsWith("--")?(l?r[c]=Zs(u,l.type):r[c]=u,o+=2):(r[c]=!0,o++)}else e.params.files&&en(a)&&s.push(a),o++}return{params:r,filePaths:s}}async function Ar(t,e,r,s){let n=await lt(t),i=n.actions.find(b=>b.slug===e),o=n.actions.some(b=>b.slug.startsWith(e+"."));if(!i&&o)return vr(t,e);if(!i){console.error(`\x1B[31mAction "${e}" not found.\x1B[0m`);let b=n.actions.filter(P=>P.slug.includes(e)).map(P=>P.slug);if(b.length>0){console.log(`
|
|
35
|
-
Did you mean:`);for(let P of
|
|
36
|
-
\x1B[
|
|
37
|
-
\x1B[
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
\x1B[1mExample:\x1B[0m`),console.log(` Input: ${JSON.stringify(t.example.input)}`),console.log(` Output: ${JSON.stringify(t.example.output)}`)),console.log()}var Er=V(()=>{"use strict";St();At();Js();tn()});import{readFileSync as Xr,writeFileSync as zt,mkdirSync as si,existsSync as yt,unlinkSync as Zt,statSync as ni,renameSync as Qr}from"node:fs";import{join as fe}from"node:path";import{homedir as ii}from"node:os";import{randomBytes as es}from"node:crypto";var Lr=new TextEncoder,Cr=new TextDecoder,Za=2**32;function fn(...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 Dt(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 Hr(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 Mr(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 mn(t){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof t=="string"?t:Cr.decode(t),{alphabet:"base64url"});let e=t;e instanceof Uint8Array&&(e=Cr.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/");try{return Mr(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}function Ut(t){let e=t;return typeof e=="string"&&(e=Lr.encode(e)),Uint8Array.prototype.toBase64?e.toBase64({alphabet:"base64url",omitPadding:!0}):Hr(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}var pe=(t,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`),Me=(t,e)=>t.name===e;function gn(t){return parseInt(t.name.slice(4),10)}function jt(t,e){if(gn(t.hash)!==e)throw pe(`SHA-${e}`,"algorithm.hash")}function yn(t){switch(t){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function vn(t,e){if(e&&!t.usages.includes(e))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${e}.`)}function _n(t,e,r){switch(e){case"HS256":case"HS384":case"HS512":{if(!Me(t.algorithm,"HMAC"))throw pe("HMAC");jt(t.algorithm,parseInt(e.slice(2),10));break}case"RS256":case"RS384":case"RS512":{if(!Me(t.algorithm,"RSASSA-PKCS1-v1_5"))throw pe("RSASSA-PKCS1-v1_5");jt(t.algorithm,parseInt(e.slice(2),10));break}case"PS256":case"PS384":case"PS512":{if(!Me(t.algorithm,"RSA-PSS"))throw pe("RSA-PSS");jt(t.algorithm,parseInt(e.slice(2),10));break}case"Ed25519":case"EdDSA":{if(!Me(t.algorithm,"Ed25519"))throw pe("Ed25519");break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{if(!Me(t.algorithm,e))throw pe(e);break}case"ES256":case"ES384":case"ES512":{if(!Me(t.algorithm,"ECDSA"))throw pe("ECDSA");let s=yn(e);if(t.algorithm.namedCurve!==s)throw pe(s,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}vn(t,r)}function Vr(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 Wr=(t,...e)=>Vr("Key must be ",t,...e),Kr=(t,e,...r)=>Vr(`Key for the ${t} algorithm must be `,e,...r),Kt=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(t,e){super(t,e),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},z=class extends Kt{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},rt=class extends Kt{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},bn=class extends Kt{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"},Ft=t=>{if(t?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return t instanceof CryptoKey}catch{return!1}},qt=t=>t?.[Symbol.toStringTag]==="KeyObject",Fr=t=>Ft(t)||qt(t),Ja=Symbol();function Or(t,e){if(t)throw new TypeError(`${e} can only be called once`)}var wn=t=>typeof t=="object"&&t!==null;function qr(t){if(!wn(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 xn(...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 Bt=t=>qr(t)&&typeof t.kty=="string",kn=t=>t.kty!=="oct"&&(t.kty==="AKP"&&typeof t.priv=="string"||typeof t.d=="string"),Sn=t=>t.kty!=="oct"&&t.d===void 0&&t.priv===void 0,An=t=>t.kty==="oct"&&typeof t.k=="string";function En(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 Tn(t,e){let r=`SHA-${t.slice(-3)}`;switch(t){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:parseInt(t.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:e.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:t};default:throw new z(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}async function $n(t,e,r){if(e instanceof Uint8Array){if(!t.startsWith("HS"))throw new TypeError(Wr(e,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",e,{hash:`SHA-${t.slice(-3)}`,name:"HMAC"},!1,[r])}return _n(e,t,r),e}async function Cn(t,e,r){let s=await $n(t,e,"sign");En(t,s);let n=await crypto.subtle.sign(Tn(t,s.algorithm),s,r);return new Uint8Array(n)}var mt='Invalid or unsupported JWK "alg" (Algorithm) Parameter value';function On(t){let e,r;switch(t.kty){case"AKP":{switch(t.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":e={name:t.alg},r=t.priv?["sign"]:["verify"];break;default:throw new z(mt)}break}case"RSA":{switch(t.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(t.alg.slice(-3),10)||1}`},r=t.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new z(mt)}break}case"EC":{switch(t.alg){case"ES256":case"ES384":case"ES512":e={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[t.alg]},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new z(mt)}break}case"OKP":{switch(t.alg){case"Ed25519":case"EdDSA":e={name:"Ed25519"},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new z(mt)}break}default:throw new z('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:r}}async function Rn(t){if(!t.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:e,keyUsages:r}=On(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 Ve="given KeyObject instance cannot be used for this algorithm",Ke,Rr=async(t,e,r,s=!1)=>{Ke||=new WeakMap;let n=Ke.get(t);if(n?.[r])return n[r];let i=await Rn({...e,alg:r});return s&&Object.freeze(t),n?n[r]=i:Ke.set(t,{[r]:i}),i},Pn=(t,e)=>{Ke||=new WeakMap;let r=Ke.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(Ve)}i=t.toCryptoKey(t.asymmetricKeyType,n,s?[]:["deriveBits"])}if(t.asymmetricKeyType==="ed25519"){if(e!=="EdDSA"&&e!=="Ed25519")throw new TypeError(Ve);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(Ve);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(Ve)}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(Ve);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(Ve);return r?r[e]=i:Ke.set(t,{[e]:i}),i};async function In(t,e){if(t instanceof Uint8Array||Ft(t))return t;if(qt(t)){if(t.type==="secret")return t.export();if("toCryptoKey"in t&&typeof t.toCryptoKey=="function")try{return Pn(t,e)}catch(s){if(s instanceof TypeError)throw s}let r=t.export({format:"jwk"});return Rr(t,r,e)}if(Bt(t))return t.k?mn(t.k):Rr(t,t,e,!0);throw new Error("unreachable")}var Nn=(t,e)=>{let r=(t.match(/.{1,64}/g)||[]).join(`
|
|
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=M(()=>{"use strict";Pt()});var A,Cr,f,re,yt=M(()=>{(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})})(Cr||(Cr={}));f=A.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),re=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=M(()=>{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,$r=M(()=>{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 Ye(){return Ks}var Ks,Dt=M(()=>{$r();Ks=he});function p(t,e){let r=Ye(),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,L,v,Ce,V,Ut,jt,be,Xe,Or=M(()=>{Dt();$r();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=[];L=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"}),Ce=t=>({status:"dirty",value:t}),V=t=>({status:"valid",value:t}),Ut=t=>t.status==="aborted",jt=t=>t.status==="dirty",be=t=>t.status==="valid",Xe=t=>typeof Promise<"u"&&t instanceof Promise});var Fs=M(()=>{});var m,Bs=M(()=>{(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)&&Co.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)&&$o.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 Qe(t){if(t instanceof B){let e={};for(let r in t.shape){let s=t.shape[r];e[r]=Z.create(Qe(s))}return new B({...t._def,shape:()=>e})}else return t instanceof me?new me({...t._def,type:Qe(t.element)}):t instanceof Z?Z.create(Qe(t.unwrap())):t instanceof ne?ne.create(Qe(t.unwrap())):t instanceof se?se.create(t.items.map(e=>Qe(e))):t}function Pr(t,e){let r=re(t),s=re(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=Pr(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=Pr(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 He({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?ke.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})}}):ke.create()}var J,qs,x,_o,bo,wo,ko,xo,So,Ao,Eo,To,Rr,Co,$o,Oo,Ro,Po,Io,zs,No,we,$e,Oe,Re,Pe,et,Ie,Ne,ke,fe,X,tt,me,B,De,pe,Lt,Ue,se,Ht,rt,st,Mt,je,Le,He,Me,xe,Y,Z,ne,Ve,We,nt,Mo,_t,bt,Ke,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,ka,xa,Sa,rn=M(()=>{Nt();Dt();Bs();Or();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}}};x=class{get description(){return this._def.description}_getType(e){return re(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:re(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new L,ctx:{common:e.parent.common,data:e.data,parsedType:re(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Xe(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:re(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:re(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:re(e)},n=this._parse({data:e,path:s.path,parent:s}),i=await(Xe(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 ne.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return me.create(this)}promise(){return xe.create(this,this._def)}or(e){return De.create([this,e],this._def)}and(e){return Ue.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 Ve({...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 We({...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 Ke.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,ko=/^[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,xo=/^[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})+$",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])$/,$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])\/(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 x{_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 L,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")Rr||(Rr=new RegExp(To,"u")),Rr.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")ko.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")xo.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 x{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 L;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)});Oe=class t extends x{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 L;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}};Oe.create=t=>new Oe({checks:[],typeName:_.ZodBigInt,coerce:t?.coerce??!1,...w(t)});Re=class extends x{_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 V(e.data)}};Re.create=t=>new Re({typeName:_.ZodBoolean,coerce:t?.coerce||!1,...w(t)});Pe=class t extends x{_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 L,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}};Pe.create=t=>new Pe({checks:[],coerce:t?.coerce||!1,typeName:_.ZodDate,...w(t)});et=class extends x{_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 V(e.data)}};et.create=t=>new et({typeName:_.ZodSymbol,...w(t)});Ie=class extends x{_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 V(e.data)}};Ie.create=t=>new Ie({typeName:_.ZodUndefined,...w(t)});Ne=class extends x{_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 V(e.data)}};Ne.create=t=>new Ne({typeName:_.ZodNull,...w(t)});ke=class extends x{constructor(){super(...arguments),this._any=!0}_parse(e){return V(e.data)}};ke.create=t=>new ke({typeName:_.ZodAny,...w(t)});fe=class extends x{constructor(){super(...arguments),this._unknown=!0}_parse(e){return V(e.data)}};fe.create=t=>new fe({typeName:_.ZodUnknown,...w(t)});X=class extends x{_parse(e){let r=this._getOrReturnCtx(e);return p(r,{code:h.invalid_type,expected:f.never,received:r.parsedType}),v}};X.create=t=>new X({typeName:_.ZodNever,...w(t)});tt=class extends x{_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 V(e.data)}};tt.create=t=>new tt({typeName:_.ZodVoid,...w(t)});me=class t extends x{_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=>L.mergeArray(s,o));let i=[...r.data].map((o,a)=>n.type._parseSync(new J(r,o,r.path,a)));return L.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 x{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 X&&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 X){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,y=await u.value;l.push({key:d,value:y,alwaysSet:u.alwaysSet})}return l}).then(l=>L.mergeObjectSync(s,l)):L.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 Qe(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:X.create(),typeName:_.ZodObject,...w(e)});B.strictCreate=(t,e)=>new B({shape:()=>t,unknownKeys:"strict",catchall:X.create(),typeName:_.ZodObject,...w(e)});B.lazycreate=(t,e)=>new B({shape:t,unknownKeys:"strip",catchall:X.create(),typeName:_.ZodObject,...w(e)});De=class extends x{_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}};De.create=(t,e)=>new De({options:t,typeName:_.ZodUnion,...w(e)});pe=t=>t instanceof je?pe(t.schema):t instanceof Y?pe(t.innerType()):t instanceof Le?[t.value]:t instanceof He?t.options:t instanceof Me?A.objectValues(t.enum):t instanceof Ve?pe(t._def.innerType):t instanceof Ie?[void 0]:t instanceof Ne?[null]:t instanceof Z?[void 0,...pe(t.unwrap())]:t instanceof ne?[null,...pe(t.unwrap())]:t instanceof _t||t instanceof Ke?pe(t.unwrap()):t instanceof We?pe(t._def.innerType):[],Lt=class t extends x{_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)})}};Ue=class extends x{_parse(e){let{status:r,ctx:s}=this._processInputParams(e),n=(i,o)=>{if(Ut(i)||Ut(o))return v;let a=Pr(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}))}};Ue.create=(t,e,r)=>new Ue({left:t,right:e,typeName:_.ZodIntersection,...w(r)});se=class t extends x{_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=>L.mergeArray(r,o)):L.mergeArray(r,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};se.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new se({items:t,typeName:_.ZodTuple,rest:null,...w(e)})};Ht=class t extends x{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?L.mergeObjectAsync(r,n):L.mergeObjectSync(r,n)}get element(){return this._def.valueType}static create(e,r,s){return r instanceof x?new t({keyType:e,valueType:r,typeName:_.ZodRecord,...w(s)}):new t({keyType:we.create(),valueType:e,typeName:_.ZodRecord,...w(r)})}},rt=class extends x{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}}}};rt.create=(t,e,r)=>new rt({valueType:e,keyType:t,typeName:_.ZodMap,...w(r)});st=class t extends x{_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)}};st.create=(t,e)=>new st({valueType:t,minSize:null,maxSize:null,typeName:_.ZodSet,...w(e)});Mt=class t extends x{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,Ye(),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,Ye(),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 xe){let a=this;return V(async function(...c){let l=new F([]),u=await a._def.args.parseAsync(c,i).catch(k=>{throw l.addIssue(s(c,k)),l}),d=await Reflect.apply(o,this,u);return await a._def.returns._def.type.parseAsync(d,i).catch(k=>{throw l.addIssue(n(d,k)),l})})}else{let a=this;return V(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:se.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||se.create([]).rest(fe.create()),returns:r||fe.create(),typeName:_.ZodFunction,...w(s)})}},je=class extends x{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})}};je.create=(t,e)=>new je({getter:t,typeName:_.ZodLazy,...w(e)});Le=class extends x{_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}};Le.create=(t,e)=>new Le({value:t,typeName:_.ZodLiteral,...w(e)});He=class t extends x{_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 V(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})}};He.create=Ys;Me=class extends x{_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 V(e.data)}get enum(){return this._def.values}};Me.create=(t,e)=>new Me({values:t,typeName:_.ZodNativeEnum,...w(e)});xe=class extends x{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 V(s.then(n=>this._def.type.parseAsync(n,{path:r.path,errorMap:r.common.contextualErrorMap})))}};xe.create=(t,e)=>new xe({type:t,typeName:_.ZodPromise,...w(e)});Y=class extends x{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"?Ce(c.value):r.value==="dirty"?Ce(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"?Ce(a.value):r.value==="dirty"?Ce(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 x{_parse(e){return this._getType(e)===f.undefined?V(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Z.create=(t,e)=>new Z({innerType:t,typeName:_.ZodOptional,...w(e)});ne=class extends x{_parse(e){return this._getType(e)===f.null?V(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ne.create=(t,e)=>new ne({innerType:t,typeName:_.ZodNullable,...w(e)});Ve=class extends x{_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}};Ve.create=(t,e)=>new Ve({innerType:t,typeName:_.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...w(e)});We=class extends x{_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 Xe(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}};We.create=(t,e)=>new We({innerType:t,typeName:_.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...w(e)});nt=class extends x{_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}}};nt.create=t=>new nt({typeName:_.ZodNaN,...w(t)});Mo=Symbol("zod_brand"),_t=class extends x{_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 x{_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(),Ce(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})}},Ke=class extends x{_parse(e){let r=this._def.innerType._parse(e),s=n=>(be(n)&&(n.value=Object.freeze(n.value)),n);return Xe(r)?r.then(n=>s(n)):s(r)}unwrap(){return this._def.innerType}};Ke.create=(t,e)=>new Ke({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=nt.create,Fo=Oe.create,tn=Re.create,Bo=Pe.create,qo=et.create,Go=Ie.create,zo=Ne.create,Zo=ke.create,Jo=fe.create,Yo=X.create,Xo=tt.create,Qo=me.create,ea=B.create,ta=B.strictCreate,ra=De.create,sa=Lt.create,na=Ue.create,ia=se.create,oa=Ht.create,aa=rt.create,ca=st.create,la=Mt.create,ua=je.create,da=Le.create,ha=He.create,pa=Me.create,fa=xe.create,ma=Y.create,ga=Z.create,ya=ne.create,va=Y.createWithPreprocess,_a=bt.create,ba=()=>Qs().optional(),wa=()=>en().optional(),ka=()=>tn().optional(),xa={string:(t=>we.create({...t,coerce:!0})),number:(t=>$e.create({...t,coerce:!0})),boolean:(t=>Re.create({...t,coerce:!0})),bigint:(t=>Oe.create({...t,coerce:!0})),date:(t=>Pe.create({...t,coerce:!0}))},Sa=v});var q={};Wt(q,{BRAND:()=>Mo,DIRTY:()=>Ce,EMPTY_PATH:()=>vo,INVALID:()=>v,NEVER:()=>Sa,OK:()=>V,ParseStatus:()=>L,Schema:()=>x,ZodAny:()=>ke,ZodArray:()=>me,ZodBigInt:()=>Oe,ZodBoolean:()=>Re,ZodBranded:()=>_t,ZodCatch:()=>We,ZodDate:()=>Pe,ZodDefault:()=>Ve,ZodDiscriminatedUnion:()=>Lt,ZodEffects:()=>Y,ZodEnum:()=>He,ZodError:()=>F,ZodFirstPartyTypeKind:()=>_,ZodFunction:()=>Mt,ZodIntersection:()=>Ue,ZodIssueCode:()=>h,ZodLazy:()=>je,ZodLiteral:()=>Le,ZodMap:()=>rt,ZodNaN:()=>nt,ZodNativeEnum:()=>Me,ZodNever:()=>X,ZodNull:()=>Ne,ZodNullable:()=>ne,ZodNumber:()=>$e,ZodObject:()=>B,ZodOptional:()=>Z,ZodParsedType:()=>f,ZodPipeline:()=>bt,ZodPromise:()=>xe,ZodReadonly:()=>Ke,ZodRecord:()=>Ht,ZodSchema:()=>x,ZodSet:()=>st,ZodString:()=>we,ZodSymbol:()=>et,ZodTransformer:()=>Y,ZodTuple:()=>se,ZodType:()=>x,ZodUndefined:()=>Ie,ZodUnion:()=>De,ZodUnknown:()=>fe,ZodVoid:()=>tt,addIssueToContext:()=>p,any:()=>Zo,array:()=>Qo,bigint:()=>Fo,boolean:()=>tn,coerce:()=>xa,custom:()=>Xs,date:()=>Bo,datetimeRegex:()=>Js,defaultErrorMap:()=>he,discriminatedUnion:()=>sa,effect:()=>ma,enum:()=>ha,function:()=>la,getErrorMap:()=>Ye,getParsedType:()=>re,instanceof:()=>Wo,intersection:()=>na,isAborted:()=>Ut,isAsync:()=>Xe,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:()=>Cr,oboolean:()=>ka,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 Ir=M(()=>{Dt();Or();Fs();yt();rn();Nt()});var sn=M(()=>{Ir();Ir()});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 Nr(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=M(()=>{"use strict";sn()});import*as Fe from"node:fs";import*as ie from"node:path";function Ea(t){let e=ie.extname(t).toLowerCase();return!!(Aa.has(e)||e==="")}function an(t){let e=ie.resolve(t),r=Fe.readFileSync(e),s=ie.relative(process.cwd(),e);if(Ea(t))return{path:s,contents:r.toString("utf-8")};let n=ie.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=ie.resolve(r);if(Fe.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=Fe.readdirSync(t,{withFileTypes:!0});for(let s of r){let n=ie.join(t,s.name);s.isDirectory()?e.push(...ln(n)):e.push(n)}return e}var Aa,un=M(()=>{"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={};Wt(dn,{execute:()=>Dr});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 Dr(t,e,r,s){let n=await gt(t),i=n.actions.find(g=>g.slug===e),o=n.actions.some(g=>g.slug.startsWith(e+"."));if(!i&&o)return Tr(t,e);if(!i){console.error(`\x1B[31mAction "${e}" not found.\x1B[0m`);let g=n.actions.filter(P=>P.slug.includes(e)).map(P=>P.slug);if(g.length>0){console.log(`
|
|
35
|
+
Did you mean:`);for(let P of g)console.log(` \x1B[36m${P}\x1B[0m`)}process.exit(1)}let a=await Hs(t,e),c=[...a.params.path,...a.params.query,...a.params.body],l=new Map(c.map(g=>[g.name,g])),u=Ta(a),d=new Ot().exitOverride().name(e).description(a.description).allowUnknownOption(!1).configureOutput({writeOut:g=>process.stdout.write(g),writeErr:g=>process.stderr.write(g)});if(a.payment.mode!=="free"){let g=a.payment.description?`${a.payment.mode} \u2014 ${a.payment.description}`:a.payment.mode;d.addHelpText("after",`
|
|
36
|
+
\x1B[33mPayment: ${g}\x1B[0m`)}d.addHelpText("after",`
|
|
37
|
+
\x1B[90m${a.method} ${a.endpoint}\x1B[0m`),a.example&&d.addHelpText("after",`
|
|
38
|
+
Example:
|
|
39
|
+
Input: ${JSON.stringify(a.example.input)}
|
|
40
|
+
Output: ${JSON.stringify(a.example.output)}`);for(let g of u){let P=l.get(g),Hr=P?.required?`<${g}>`:`[${g}]`;d.argument(Hr,P?.description??"")}for(let g of c)g.type?.type==="boolean"?d.option(`--${g.name}`,g.description):d.option(`--${g.name} <value>`,g.description);a.params.files&&(d.option("--file <paths...>","File(s) to upload"),d.option("--files <paths...>","File(s) to upload"));let y={},k=[];d.action((...g)=>{let P=g.pop(),Hr=g.pop(),ot={};for(let[ue,ye]of Object.entries(P)){if(ue==="file"||ue==="files"){k.push(...ye);continue}let at=l.get(ue);at&&typeof ye=="string"?ot[ue]=Nr(ye,at.type):ot[ue]=ye}u.forEach((ue,ye)=>{if(g[ye]!==void 0&&ot[ue]===void 0){let at=l.get(ue);ot[ue]=at?Nr(String(g[ye]),at.type):g[ye]}}),y=ot});try{await d.parseAsync(r,{from:"user"})}catch(g){throw g?.exitCode!==void 0&&process.exit(g.exitCode),g}let W=s(),Be=W.getIdentity();Be||(console.error("\x1B[31mNot registered. Run: botparty init\x1B[0m"),process.exit(1));let oe=y,it=Be.namespace,ee=n.baseUrl.replace("{namespace}",it),R=a.endpoint;for(let g of a.params.path){let P=oe[g.name];P!==void 0?(R=R.replace(`{${g.name}}`,String(P)),delete oe[g.name]):g.required&&(console.error(`\x1B[31mMissing required path parameter: --${g.name}\x1B[0m`),process.exit(1))}let H=new URLSearchParams;for(let g of a.params.query){let P=oe[g.name];P!==void 0?(H.set(g.name,String(P)),delete oe[g.name]):g.required&&(console.error(`\x1B[31mMissing required query parameter: --${g.name}\x1B[0m`),process.exit(1))}let U=t.includes("://")?t:`https://${t}`,ae=H.toString(),ce=`${U.replace(/\/$/,"")}${ee}${R}${ae?"?"+ae:""}`,ge={method:a.method};if(["POST","PUT","PATCH"].includes(a.method)){let g={};for(let P of a.params.body)oe[P.name]!==void 0?g[P.name]=oe[P.name]:P.required&&(console.error(`\x1B[31mMissing required body parameter: --${P.name}\x1B[0m`),process.exit(1));if(a.params.files&&k.length>0){let P=cn(k);g[a.params.files.bodyKey]=P}Object.keys(g).length>0&&(ge.body=JSON.stringify(g),ge.headers={"Content-Type":"application/json"})}console.log(`\x1B[90m${a.method} ${ce}\x1B[0m`);let Se=await W.generateToken({role:"admin"}),wt=new Headers(ge.headers);wt.set("Authorization",`Bearer ${Se}`),ge.headers=wt;let le=await fetch(ce,ge),fn=le.headers.get("content-type")||"";if(!le.ok){let g=await le.text();console.error(`\x1B[31m${le.status} ${le.statusText}\x1B[0m`);try{console.error(JSON.stringify(JSON.parse(g),null,2))}catch{console.error(g)}process.exit(1)}if(fn.includes("application/json")){let g=await le.json();console.log(JSON.stringify(g,null,2))}else{let g=await le.text();console.log(g)}}var Ur=M(()=>{"use strict";xr();Pt();It();on();un()});import{readFileSync as ls,writeFileSync as rr,mkdirSync as di,existsSync as St,unlinkSync as sr,statSync as hi,renameSync as us}from"node:fs";import{join as _e}from"node:path";import{homedir as pi}from"node:os";import{randomBytes as ds}from"node:crypto";var Zr=new TextEncoder,Mr=new TextDecoder,rc=2**32;function kn(...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 Kt(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 Jr(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 Yr(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 xn(t){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof t=="string"?t:Mr.decode(t),{alphabet:"base64url"});let e=t;e instanceof Uint8Array&&(e=Mr.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/");try{return Yr(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}function Ft(t){let e=t;return typeof e=="string"&&(e=Zr.encode(e)),Uint8Array.prototype.toBase64?e.toBase64({alphabet:"base64url",omitPadding:!0}):Jr(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}`),qe=(t,e)=>t.name===e;function Sn(t){return parseInt(t.name.slice(4),10)}function Bt(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(!qe(t.algorithm,"HMAC"))throw ve("HMAC");Bt(t.algorithm,parseInt(e.slice(2),10));break}case"RS256":case"RS384":case"RS512":{if(!qe(t.algorithm,"RSASSA-PKCS1-v1_5"))throw ve("RSASSA-PKCS1-v1_5");Bt(t.algorithm,parseInt(e.slice(2),10));break}case"PS256":case"PS384":case"PS512":{if(!qe(t.algorithm,"RSA-PSS"))throw ve("RSA-PSS");Bt(t.algorithm,parseInt(e.slice(2),10));break}case"Ed25519":case"EdDSA":{if(!qe(t.algorithm,"Ed25519"))throw ve("Ed25519");break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{if(!qe(t.algorithm,e))throw ve(e);break}case"ES256":case"ES384":case"ES512":{if(!qe(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 Xr(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 Qr=(t,...e)=>Xr("Key must be ",t,...e),es=(t,e,...r)=>Xr(`Key for the ${t} algorithm must be `,e,...r),Yt=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 Yt{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},lt=class extends Yt{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},Cn=class extends Yt{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"},Xt=t=>{if(t?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return t instanceof CryptoKey}catch{return!1}},Qt=t=>t?.[Symbol.toStringTag]==="KeyObject",ts=t=>Xt(t)||Qt(t),sc=Symbol();function Vr(t,e){if(t)throw new TypeError(`${e} can only be called once`)}var $n=t=>typeof t=="object"&&t!==null;function rs(t){if(!$n(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 er=t=>rs(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(Qr(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 kt='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(kt)}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(kt)}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(kt)}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(kt)}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 Ge="given KeyObject instance cannot be used for this algorithm",Ze,Wr=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(Ge)}i=t.toCryptoKey(t.asymmetricKeyType,n,s?[]:["deriveBits"])}if(t.asymmetricKeyType==="ed25519"){if(e!=="EdDSA"&&e!=="Ed25519")throw new TypeError(Ge);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(Ge);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(Ge)}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(Ge);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(Ge);return r?r[e]=i:Ze.set(t,{[e]:i}),i};async function Vn(t,e){if(t instanceof Uint8Array||Xt(t))return t;if(Qt(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 Wr(t,r,e)}if(er(t))return t.k?xn(t.k):Wr(t,t,e,!0);throw new Error("unreachable")}var Wn=(t,e)=>{let r=(t.match(/.{1,64}/g)||[]).join(`
|
|
41
41
|
`);return`-----BEGIN ${e}-----
|
|
42
42
|
${r}
|
|
43
|
-
-----END ${e}-----`},Br=async(t,e,r)=>{if(qt(r)){if(r.type!==t)throw new TypeError(`key is not a ${t} key`);return r.export({format:"pem",type:e})}if(!Ft(r))throw new TypeError(Wr(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 Nn(Hr(new Uint8Array(await crypto.subtle.exportKey(e,r))),`${t.toUpperCase()} KEY`)},Dn=t=>Br("public","spki",t),Un=t=>Br("private","pkcs8",t),Lt=(t,e)=>{if(t.byteLength!==e.length)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0},jn=t=>({data:t,pos:0}),it=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},ot=(t,e,r)=>{if(t.data[t.pos++]!==e)throw new Error(r)},Gr=(t,e)=>{let r=t.data.subarray(t.pos,t.pos+e);return t.pos+=e,r},Ln=t=>{ot(t,6,"Expected algorithm OID");let e=it(t);return Gr(t,e)};function Hn(t){ot(t,48,"Invalid PKCS#8 structure"),it(t),ot(t,2,"Expected version field");let e=it(t);t.pos+=e,ot(t,48,"Expected algorithm identifier");let r=it(t);return{algIdStart:t.pos,algIdLength:r}}var Mn=t=>{let e=Ln(t);if(Lt(e,[43,101,110]))return"X25519";if(!Lt(e,[42,134,72,206,61,2,1]))throw new Error("Unsupported key algorithm");ot(t,6,"Expected curve OID");let r=it(t),s=Gr(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(Lt(s,i))return n;throw new Error("Unsupported named curve")},Vn=async(t,e,r,s)=>{let n,i,o=t==="spki",a=()=>o?["verify"]:["sign"],c=()=>o?["encrypt","wrapKey"]:["decrypt","unwrapKey"];switch(r){case"PS256":case"PS384":case"PS512":n={name:"RSA-PSS",hash:`SHA-${r.slice(-3)}`},i=a();break;case"RS256":case"RS384":case"RS512":n={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${r.slice(-3)}`},i=a();break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":n={name:"RSA-OAEP",hash:`SHA-${parseInt(r.slice(-3),10)||1}`},i=c();break;case"ES256":case"ES384":case"ES512":{n={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[r]},i=a();break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{try{let l=s.getNamedCurve(e);n=l==="X25519"?{name:"X25519"}:{name:"ECDH",namedCurve:l}}catch{throw new z("Invalid or unsupported key format")}i=o?[]:["deriveBits"];break}case"Ed25519":case"EdDSA":n={name:"Ed25519"},i=a();break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":n={name:r},i=a();break;default:throw new z('Invalid or unsupported "alg" (Algorithm) value')}return crypto.subtle.importKey(t,e,n,s?.extractable??!!o,i)},Wn=(t,e)=>Mr(t.replace(e,"")),Kn=(t,e,r)=>{let s=Wn(t,/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g),n=r;return e?.startsWith?.("ECDH-ES")&&(n||={},n.getNamedCurve=i=>{let o=jn(i);return Hn(o),Mn(o)}),Vn("pkcs8",s,e,n)};async function zr(t,e,r){if(typeof t!="string"||t.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return Kn(t,e,r)}async function Fn(t){return Dn(t)}async function qn(t){return Un(t)}function Bn(t,e,r,s,n){if(n.crit!==void 0&&s?.crit===void 0)throw new t('"crit" (Critical) Header Parameter MUST be integrity protected');if(!s||s.crit===void 0)return new Set;if(!Array.isArray(s.crit)||s.crit.length===0||s.crit.some(o=>typeof o!="string"||o.length===0))throw new t('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;r!==void 0?i=new Map([...Object.entries(r),...e.entries()]):i=e;for(let o of s.crit){if(!i.has(o))throw new z(`Extension Header Parameter "${o}" is not recognized`);if(n[o]===void 0)throw new t(`Extension Header Parameter "${o}" is missing`);if(i.get(o)&&s[o]===void 0)throw new t(`Extension Header Parameter "${o}" MUST be integrity protected`)}return new Set(s.crit)}var We=t=>t?.[Symbol.toStringTag],Vt=(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},Gn=(t,e,r)=>{if(!(e instanceof Uint8Array)){if(Bt(e)){if(An(e)&&Vt(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(!Fr(e))throw new TypeError(Kr(t,e,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(e.type!=="secret")throw new TypeError(`${We(e)} instances for symmetric algorithms must be of type "secret"`)}},zn=(t,e,r)=>{if(Bt(e))switch(r){case"decrypt":case"sign":if(kn(e)&&Vt(t,e,r))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if(Sn(e)&&Vt(t,e,r))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!Fr(e))throw new TypeError(Kr(t,e,"CryptoKey","KeyObject","JSON Web Key"));if(e.type==="secret")throw new TypeError(`${We(e)} instances for asymmetric algorithms must not be of type "secret"`);if(e.type==="public")switch(r){case"sign":throw new TypeError(`${We(e)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${We(e)} instances for asymmetric algorithm decryption must be of type "private"`)}if(e.type==="private")switch(r){case"verify":throw new TypeError(`${We(e)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${We(e)} instances for asymmetric algorithm encryption must be of type "public"`)}};function Zn(t,e,r){switch(t.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":Gn(t,e,r);break;default:zn(t,e,r)}}var xe=t=>Math.floor(t.getTime()/1e3),Zr=60,Jr=Zr*60,Gt=Jr*24,Jn=Gt*7,Yn=Gt*365.25,Xn=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function Ht(t){let e=Xn.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*Zr);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(r*Jr);break;case"day":case"days":case"d":n=Math.round(r*Gt);break;case"week":case"weeks":case"w":n=Math.round(r*Jn);break;default:n=Math.round(r*Yn);break}return e[1]==="-"||e[4]==="ago"?-n:n}function ke(t,e){if(!Number.isFinite(e))throw new TypeError(`Invalid ${t} input`);return e}var Qn=class{#e;constructor(t){if(!qr(t))throw new TypeError("JWT Claims Set MUST be an object");this.#e=structuredClone(t)}data(){return Lr.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=ke("setNotBefore",t):t instanceof Date?this.#e.nbf=ke("setNotBefore",xe(t)):this.#e.nbf=xe(new Date)+Ht(t)}set exp(t){typeof t=="number"?this.#e.exp=ke("setExpirationTime",t):t instanceof Date?this.#e.exp=ke("setExpirationTime",xe(t)):this.#e.exp=xe(new Date)+Ht(t)}set iat(t){t===void 0?this.#e.iat=xe(new Date):t instanceof Date?this.#e.iat=ke("setIssuedAt",xe(t)):typeof t=="string"?this.#e.iat=ke("setIssuedAt",xe(new Date)+Ht(t)):this.#e.iat=ke("setIssuedAt",t)}},Yr=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 Or(this.#t,"setProtectedHeader"),this.#t=t,this}setUnprotectedHeader(t){return Or(this.#r,"setUnprotectedHeader"),this.#r=t,this}async sign(t,e){if(!this.#t&&!this.#r)throw new rt("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!xn(this.#t,this.#r))throw new rt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let r={...this.#t,...this.#r},s=Bn(rt,new Map([["b64",!0]]),e?.crit,this.#t,r),n=!0;if(s.has("b64")&&(n=this.#t.b64,typeof n!="boolean"))throw new rt('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:i}=r;if(typeof i!="string"||!i)throw new rt('JWS "alg" (Algorithm) Header Parameter missing or invalid');Zn(i,t,"sign");let o,a;n?(o=Ut(this.#e),a=Dt(o)):(a=this.#e,o="");let c,l;this.#t?(c=Ut(JSON.stringify(this.#t)),l=Dt(c)):(c="",l=new Uint8Array);let u=fn(l,Dt("."),a),d=await In(t,i),g=await Cn(i,d,u),A={signature:Ut(g),payload:o};return this.#r&&(A.header=this.#r),this.#t&&(A.protected=c),A}},ei=class{#e;constructor(t){this.#e=new Yr(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}`}},ti=class{#e;#t;constructor(t={}){this.#t=new Qn(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 ei(this.#t.data());if(r.setProtectedHeader(this.#e),Array.isArray(this.#e?.crit)&&this.#e.crit.includes("b64")&&this.#e.b64===!1)throw new bn("JWTs MUST NOT use unencoded payload");return r.sign(t,e)}};function Mt(t){let e=t?.modulusLength??2048;if(typeof e!="number"||e<2048)throw new z("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return e}async function ri(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:Mt(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:Mt(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:Mt(e)},s=["decrypt","unwrapKey","encrypt","wrapKey"];break;case"ES256":r={name:"ECDSA",namedCurve:"P-256"},s=["sign","verify"];break;case"ES384":r={name:"ECDSA",namedCurve:"P-384"},s=["sign","verify"];break;case"ES512":r={name:"ECDSA",namedCurve:"P-521"},s=["sign","verify"];break;case"Ed25519":case"EdDSA":{s=["sign","verify"],r={name:"Ed25519"};break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{s=["sign","verify"],r={name:t};break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{s=["deriveBits"];let n=e?.crv??"P-256";switch(n){case"P-256":case"P-384":case"P-521":{r={name:"ECDH",namedCurve:n};break}case"X25519":r={name:"X25519"};break;default:throw new z("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519")}break}default:throw new z('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return crypto.subtle.generateKey(r,e?.extractable??!1,s)}var oi="https://id.botparty.club",ai="EdDSA",ci=15,Pr=6e4,li=3e4,ui="5m",di=3,hi=["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"],pi=["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}},Jt=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"}},vt=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}},at=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}},_t=class extends L{constructor(t){super({code:"LINK_REQUIRED",message:t.message,statusCode:403,actionUrl:t.actionUrl}),this.name="LinkRequiredError"}};function Ir(t){let e=es(4);return t[e.readUInt32BE(0)%t.length]}function fi(){return`${Ir(hi)}-${Ir(pi)}`}function mi(){let t=fi(),e=es(2).toString("hex");return`${t}-${e}`}function gi(){return fe(ii(),".botparty")}function Yt(t){yt(t)||si(t,{recursive:!0,mode:448})}function yi(t){let e=fe(t,"identity.json");if(!yt(e))return null;try{return JSON.parse(Xr(e,"utf-8"))}catch{return null}}function ts(t,e){Yt(t);let r=fe(t,"identity.json"),s=r+".tmp";zt(s,JSON.stringify(e,null,2),{mode:384}),Qr(s,r)}function vi(t){let e=fe(t,"private.pem");if(!yt(e))return null;try{return Xr(e,"utf-8")}catch{return null}}function rs(t,e){Yt(t);let r=fe(t,"private.pem"),s=r+".tmp";zt(s,e,{mode:384}),Qr(s,r)}function Nr(t){for(let e of["identity.json","private.pem"]){let r=fe(t,e);yt(r)&&Zt(r)}}function _i(t){let e=fe(t,"rotation.lock");Yt(t);for(let r=0;r<2;r++)try{zt(e,`${process.pid}:${Date.now()}`,{flag:"wx",mode:384});return}catch(s){if(s.code!=="EEXIST")throw s;try{let n=ni(e);if(Date.now()-n.mtimeMs>li){Zt(e);continue}}catch{continue}throw s}}function bi(t){try{Zt(fe(t,"rotation.lock"))}catch{}}async function ss(t){let e={extractable:!0};t==="EdDSA"&&(e.crv="Ed25519");let{privateKey:r,publicKey:s}=await ri(t,e),n=await qn(r),i=await Fn(s);return{privateKey:r,publicKey:s,privatePem:n,publicPem:i}}async function wi(t,e,r){let s=await zr(e,r);return(await new Yr(new TextEncoder().encode(t)).setProtectedHeader({alg:r}).sign(s)).signature}async function Wt(t,e,r,s,n){let i=s,o=await zr(r,i);return new ti({...n}).setProtectedHeader({alg:i,kid:e}).setIssuer(t).setSubject(t).setIssuedAt().setExpirationTime(ui).sign(o)}async function se(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 Dr(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 gt(t){try{return await t.clone().json()}catch{return null}}function nt(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 xi=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)}},ki=class{constructor(t){this.client=t}async list(){let t=await this.client.generateToken(),e=await se(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 se(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 se(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 se(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 ss(e.algorithm),i=await Wt(e.namespace,e.keyId,r,e.algorithm),o=await se(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 rs(this.client.stateDir,n.privatePem),ts(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 se(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)}},ns=class{serverUrl;stateDir;proxyUrl;keys;algorithm;rotationTTL;inviteToken;_rotationPromise=null;constructor(t={}){this.serverUrl=(t.serverUrl||st("BOTPARTY_SERVER_URL")||oi).replace(/\/$/,""),this.proxyUrl=(t.proxyUrl||st("BOTPARTY_PROXY_URL")||st("KEYCHAINS_PROXY_URL")||"https://keychains.dev").replace(/\/$/,""),this.stateDir=t.stateDir||st("BOTPARTY_STATE_DIR")||gi(),this.algorithm=t.algorithm||ai,this.rotationTTL=t.rotationTTL||ci,this.inviteToken=t.inviteToken||st("BOTPARTY_INVITE_TOKEN"),this.keys=new ki(this)}getIdentity(){return yi(this.stateDir)}getPrivateKey(){return vi(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<di;){s||(s=mi());let o=e||s,a=await ss(this.algorithm),c=await se(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 wi(u,a.privatePem,this.algorithm),g=await se(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 A=await g.json();return rs(this.stateDir,a.privatePem),ts(this.stateDir,{serverUrl:this.serverUrl,namespace:s,keyId:A.keyId,algorithm:this.algorithm,rotatedAt:A.rotatedAt,rotationTTL:A.rotationTTL,label:o,...A.parentNamespace&&{parentNamespace:A.parentNamespace},...A.inheritedScopes&&{inheritedScopes:A.inheritedScopes}}),A}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-Pr)return this._rotationPromise=this._lockedRotate().finally(()=>{this._rotationPromise=null}),this._rotationPromise}async _lockedRotate(){_i(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-Pr)return;await this.keys.rotateCurrent()}finally{bi(this.stateDir)}}async generateToken(t){await this.ensureRegistered(),await this.ensureFreshKey();let e=this.getIdentity(),r=this.getPrivateKey();return Wt(e.namespace,e.keyId,r,e.algorithm,t)}async fetch(t,e={}){let r=await this.generateToken(),s=Dr(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 gt(i);if(o){let{code:a}=nt(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 gt(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=Dr(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 at({message:o.message||"Missing required credentials",actionUrl:c,missingScopes:d}):new _t({message:o.message||"Missing required credentials",actionUrl:c})}let{code:l}=nt(o);Ur(l)&&jr(i.status,o,this.getIdentity(),this.serverUrl)}}if([401,402,423].includes(i.status)){let o=await gt(i);if(o){let{code:a}=nt(o);(Ur(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 se(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 se(this.serverUrl,"/api/v1/namespaces",{method:"DELETE",token:t});if(!e.ok&&e.status!==204)throw await this._apiError(e);Nr(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 Wt(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 xi(this,t)}reset(){Nr(this.stateDir)}async _apiError(t){let e=await gt(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}=nt(e);return new L({code:r,message:s,statusCode:t.status,actionUrl:n})}},Si=new Set(["NAMESPACE_LOCKED","LOCKUP_TRIGGERED","PAYMENT_REQUIRED","LINK_REQUIRED","INSUFFICIENT_SCOPE","PERMISSION_DENIED","KEY_STALE","KEY_EXPIRED"]);function Ur(t){return Si.has(t.toUpperCase())}function jr(t,e,r,s){let{code:n,message:i,actionUrl:o,extra:a}=nt(e),c=r?.namespace||"",l=r?.serverUrl||s;throw n==="NAMESPACE_LOCKED"||n==="LOCKUP_TRIGGERED"||t===423?new Jt({message:i||"Namespace is locked",actionUrl:o||`${l}/namespaces/${c}/unlock`,lockedAt:a.lockedAt,reason:a.reason}):n==="PAYMENT_REQUIRED"||t===402?new vt({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 at({message:i,actionUrl:o,missingScopes:a.missingScopes||a.missing_scopes}):new L({code:n,message:i,statusCode:t,actionUrl:o})}function st(t){if(typeof process<"u"&&process.env)return process.env[t]}import{writeFileSync as ks}from"fs";import{readFileSync as kt}from"fs";import{basename as Xi}from"path";var ys=pn(gs(),1),{program:Ac,createCommand:Ec,createArgument:Tc,createOption:$c,CommanderError:Cc,InvalidArgumentError:Oc,InvalidOptionArgumentError:Rc,Command:vs,Argument:Pc,Option:Ic,Help:Nc}=ys.default;var Mi="\x1B[1m",Vi="\x1B[2m",Wi="\x1B[31m",Ki="\x1B[32m",Fi="\x1B[33m",qi="\x1B[36m",Fe="\x1B[0m";function k(t){return`${Mi}${t}${Fe}`}function C(t){return`${Vi}${t}${Fe}`}function O(t){return`${Wi}${t}${Fe}`}function U(t){return`${Ki}${t}${Fe}`}function F(t){return`${Fi}${t}${Fe}`}function _(t){return`${qi}${t}${Fe}`}import{readFileSync as Bi,writeFileSync as Gi,existsSync as _s,mkdirSync as zi}from"node:fs";import{join as bs}from"node:path";var ws="auth-capability-cache.json",Zi=1440*60*1e3;function Ji(t){let e=bs(t,ws);if(!_s(e))return{};try{return JSON.parse(Bi(e,"utf-8"))}catch{return{}}}function Yi(t,e){_s(t)||zi(t,{recursive:!0,mode:448}),Gi(bs(t,ws),JSON.stringify(e,null,2))}async function xs(t,e){let r=Ji(e),s=r[t];if(s&&Date.now()-s.checkedAt<Zi)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{Yi(e,r)}catch{}return n}function mr(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,`
|
|
44
|
-
`),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
|
|
45
|
-
`)}function
|
|
46
|
-
`)}function
|
|
47
|
-
`)}function
|
|
48
|
-
`)}function
|
|
49
|
-
`);let u=
|
|
50
|
-
`)}if(e.dumpHeader){let l=
|
|
51
|
-
`),e.writeOut&&process.stdout.write(
|
|
52
|
-
`),e.writeOut&&process.stdout.write(
|
|
43
|
+
-----END ${e}-----`},ss=async(t,e,r)=>{if(Qt(r)){if(r.type!==t)throw new TypeError(`key is not a ${t} key`);return r.export({format:"pem",type:e})}if(!Xt(r))throw new TypeError(Qr(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(Jr(new Uint8Array(await crypto.subtle.exportKey(e,r))),`${t.toUpperCase()} KEY`)},Kn=t=>ss("public","spki",t),Fn=t=>ss("private","pkcs8",t),qt=(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)},ns=(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 ns(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(qt(e,[43,101,110]))return"X25519";if(!qt(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=ns(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(qt(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)=>Yr(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 is(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 ze=t=>t?.[Symbol.toStringTag],Zt=(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(er(e)){if(In(e)&&Zt(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(!ts(e))throw new TypeError(es(t,e,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(e.type!=="secret")throw new TypeError(`${ze(e)} instances for symmetric algorithms must be of type "secret"`)}},ri=(t,e,r)=>{if(er(e))switch(r){case"decrypt":case"sign":if(Rn(e)&&Zt(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)&&Zt(t,e,r))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!ts(e))throw new TypeError(es(t,e,"CryptoKey","KeyObject","JSON Web Key"));if(e.type==="secret")throw new TypeError(`${ze(e)} instances for asymmetric algorithms must not be of type "secret"`);if(e.type==="public")switch(r){case"sign":throw new TypeError(`${ze(e)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${ze(e)} instances for asymmetric algorithm decryption must be of type "private"`)}if(e.type==="private")switch(r){case"verify":throw new TypeError(`${ze(e)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${ze(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 Ee=t=>Math.floor(t.getTime()/1e3),os=60,as=os*60,tr=as*24,ni=tr*7,ii=tr*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 Gt(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*os);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(r*as);break;case"day":case"days":case"d":n=Math.round(r*tr);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 Te(t,e){if(!Number.isFinite(e))throw new TypeError(`Invalid ${t} input`);return e}var ai=class{#e;constructor(t){if(!rs(t))throw new TypeError("JWT Claims Set MUST be an object");this.#e=structuredClone(t)}data(){return Zr.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=Te("setNotBefore",t):t instanceof Date?this.#e.nbf=Te("setNotBefore",Ee(t)):this.#e.nbf=Ee(new Date)+Gt(t)}set exp(t){typeof t=="number"?this.#e.exp=Te("setExpirationTime",t):t instanceof Date?this.#e.exp=Te("setExpirationTime",Ee(t)):this.#e.exp=Ee(new Date)+Gt(t)}set iat(t){t===void 0?this.#e.iat=Ee(new Date):t instanceof Date?this.#e.iat=Te("setIssuedAt",Ee(t)):typeof t=="string"?this.#e.iat=Te("setIssuedAt",Ee(new Date)+Gt(t)):this.#e.iat=Te("setIssuedAt",t)}},cs=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 Vr(this.#t,"setProtectedHeader"),this.#t=t,this}setUnprotectedHeader(t){return Vr(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=Ft(this.#e),a=Kt(o)):(a=this.#e,o="");let c,l;this.#t?(c=Ft(JSON.stringify(this.#t)),l=Kt(c)):(c="",l=new Uint8Array);let u=kn(l,Kt("."),a),d=await Vn(t,i),y=await jn(i,d,u),k={signature:Ft(y),payload:o};return this.#r&&(k.header=this.#r),this.#t&&(k.protected=c),k}},ci=class{#e;constructor(t){this.#e=new cs(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 Cn("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,Kr=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"],j=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}},nr=class extends j{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 j{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 j{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 j{constructor(t){super({code:"LINK_REQUIRED",message:t.message,statusCode:403,actionUrl:t.actionUrl}),this.name="LinkRequiredError"}};function Fr(t){let e=ds(4);return t[e.readUInt32BE(0)%t.length]}function ki(){return`${Fr(bi)}-${Fr(wi)}`}function xi(){let t=ki(),e=ds(2).toString("hex");return`${t}-${e}`}function Si(){return _e(pi(),".botparty")}function ir(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(ls(e,"utf-8"))}catch{return null}}function hs(t,e){ir(t);let r=_e(t,"identity.json"),s=r+".tmp";rr(s,JSON.stringify(e,null,2),{mode:384}),us(s,r)}function Ei(t){let e=_e(t,"private.pem");if(!St(e))return null;try{return ls(e,"utf-8")}catch{return null}}function ps(t,e){ir(t);let r=_e(t,"private.pem"),s=r+".tmp";rr(s,e,{mode:384}),us(s,r)}function Br(t){for(let e of["identity.json","private.pem"]){let r=_e(t,e);St(r)&&sr(r)}}function Ti(t){let e=_e(t,"rotation.lock");ir(t);for(let r=0;r<2;r++)try{rr(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){sr(e);continue}}catch{continue}throw s}}function Ci(t){try{sr(_e(t,"rotation.lock"))}catch{}}async function fs(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 $i(t,e,r){let s=await is(e,r);return(await new cs(new TextEncoder().encode(t)).setProtectedHeader({alg:r}).sign(s)).signature}async function Jt(t,e,r,s,n){let i=s,o=await is(r,i);return new li({...n}).setProtectedHeader({alg:i,kid:e}).setIssuer(t).setSubject(t).setIssuedAt().setExpirationTime(vi).sign(o)}async function te(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 qr(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 xt(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 te(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 j({code:"KEY_NOT_FOUND",message:`Key ${t} not found`,statusCode:404});return e}async add(t){let e=await this.client.generateToken(),r=await te(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 te(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 te(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 j({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 fs(e.algorithm),i=await Jt(e.namespace,e.keyId,r,e.algorithm),o=await te(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 ps(this.client.stateDir,n.privatePem),hs(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 te(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)}},ms=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=xi());let o=e||s,a=await fs(this.algorithm),c=await te(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 j({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 j({code:l.error||"REGISTRATION_FAILED",message:l.message||l.error||"Registration failed",statusCode:c.status});let u=l.challenge,d=await $i(u,a.privatePem,this.algorithm),y=await te(this.serverUrl,"/api/v1/namespaces/register/verify",{method:"POST",body:JSON.stringify({namespace:s,challenge:u,signature:d})});if(!y.ok)throw await this._apiError(y);let k=await y.json();return ps(this.stateDir,a.privatePem),hs(this.stateDir,{serverUrl:this.serverUrl,namespace:s,keyId:k.keyId,algorithm:this.algorithm,rotatedAt:k.rotatedAt,rotationTTL:k.rotationTTL,label:o,...k.parentNamespace&&{parentNamespace:k.parentNamespace},...k.inheritedScopes&&{inheritedScopes:k.inheritedScopes}}),k}throw new j({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-Kr)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-Kr)return;await this.keys.rotateCurrent()}finally{Ci(this.stateDir)}}async generateToken(t){await this.ensureRegistered(),await this.ensureFreshKey();let e=this.getIdentity(),r=this.getPrivateKey();return Jt(e.namespace,e.keyId,r,e.algorithm,t)}async fetch(t,e={}){let r=await this.generateToken(),s=qr(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 xt(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 xt(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=qr(t,u),y=new Headers(e.headers);return y.set("X-Proxy-Authorization",`Bearer ${r}`),fetch(d,{...e,headers:y})}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);Gr(l)&&zr(i.status,o,this.getIdentity(),this.serverUrl)}}if([401,402,423].includes(i.status)){let o=await xt(i);if(o){let{code:a}=dt(o);(Gr(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 te(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 te(this.serverUrl,"/api/v1/namespaces",{method:"DELETE",token:t});if(!e.ok&&e.status!==204)throw await this._apiError(e);Br(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 Jt(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(){Br(this.stateDir)}async _apiError(t){let e=await xt(t);if(!e)return new j({code:"UNKNOWN",message:`Request failed with status ${t.status}`,statusCode:t.status});let{code:r,message:s,actionUrl:n}=dt(e);return new j({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 Gr(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 nr({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 j({code:n,message:i,statusCode:t,actionUrl:o})}function ut(t){if(typeof process<"u"&&process.env)return process.env[t]}xr();import{writeFileSync as Is}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",Je="\x1B[0m";function S(t){return`${zi}${t}${Je}`}function $(t){return`${Zi}${t}${Je}`}function O(t){return`${Ji}${t}${Je}`}function D(t){return`${Yi}${t}${Je}`}function K(t){return`${Xi}${t}${Je}`}function b(t){return`${Qi}${t}${Je}`}import{readFileSync as eo,writeFileSync as to,existsSync as $s,mkdirSync as ro}from"node:fs";import{join as Os}from"node:path";var Rs="auth-capability-cache.json",so=1440*60*1e3;function no(t){let e=Os(t,Rs);if(!$s(e))return{};try{return JSON.parse(eo(e,"utf-8"))}catch{return{}}}function io(t,e){$s(t)||ro(t,{recursive:!0,mode:448}),to(Os(t,Rs),JSON.stringify(e,null,2))}async function Ps(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 Sr(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,`
|
|
44
|
+
`),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(`
|
|
45
|
+
`)}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(`
|
|
46
|
+
`)}function Ns(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(`
|
|
47
|
+
`)}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(`
|
|
48
|
+
`)}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 js(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||js(t)?"POST":t.uploadFile?"PUT":"GET"}async function Ds(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+`
|
|
49
|
+
`);let u=co(t.status,t.statusText,t.headers);process.stderr.write(u+`
|
|
50
|
+
`)}if(e.dumpHeader){let l=lo(t.status,t.statusText,t.headers);e.dumpHeader==="-"?process.stdout.write(l):Is(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}
|
|
51
|
+
`),e.writeOut&&process.stdout.write(Sr(e.writeOut,t,a,i)),process.exit(22)));let c="";e.include&&(c+=Ns(t.status,t.statusText,t.headers)),e.head?!e.include&&!e.verbose&&(c+=Ns(t.status,t.statusText,t.headers)):c+=o,e.output?e.output==="-"?process.stdout.write(c):Is(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}
|
|
52
|
+
`),e.writeOut&&process.stdout.write(Sr(e.writeOut,t,a,i)),process.exit(22)),e.writeOut&&process.stdout.write(Sr(e.writeOut,t,a,i))}function Us(t){return t instanceof j&&typeof t.actionUrl=="string"&&!!t.actionUrl}async function Ls(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!
|
|
53
53
|
curl: try 'botparty curl --help' for more information
|
|
54
|
-
`),process.exit(2));let l={};if(i.header)for(let R of i.header){let
|
|
55
|
-
`),process.exit(26)}else R.append(
|
|
56
|
-
`),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:
|
|
57
|
-
`),process.stderr.write(` ${
|
|
58
|
-
`),process.stderr.write(` ${
|
|
59
|
-
`),process.stderr.write(` ${
|
|
54
|
+
`),process.exit(2));let l={};if(i.header)for(let R of i.header){let H=R.indexOf(":");if(H>0){let U=R.slice(0,H).trim(),ae=R.slice(H+1).trim();ae===""?delete l[U]:l[U]=ae}else R.endsWith(";")&&(l[R.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 R=Buffer.from(i.user).toString("base64");l.Authorization=`Basic ${R}`}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),y=c;if(i.get&&d){let R=y.includes("?")?"&":"?";y=y+R+d,d=void 0}if(!d&&js(i)){let R=new FormData,H=(U,ae)=>{let ce=U.indexOf("=");if(ce<=0)return;let ge=U.slice(0,ce),Se=U.slice(ce+1);if(ae&&Se.startsWith("@"))try{let wt=Rt(Se.slice(1)),le=new Blob([wt]);R.append(ge,le,oo(Se.slice(1)))}catch{process.stderr.write(`curl: (26) Failed to open/read local data from file: ${Se.slice(1)}
|
|
55
|
+
`),process.exit(26)}else R.append(ge,Se)};if(i.form)for(let U of i.form)H(U,!0);if(i.formString)for(let U of i.formString)H(U,!1);d=R}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}
|
|
56
|
+
`),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:y,method:u,headers:l,body:typeof d=="string"?d:void 0};let k=Date.now(),W=!1;try{let R=new URL(o.url);W=await Ps(R.hostname,a.stateDir)}catch{}let Be=i.retry?parseInt(i.retry,10):0,oe=i.retryDelay?parseInt(i.retryDelay,10)*1e3:1e3,it=null,ee=null;for(let R=0;R<=Be;R++)try{if(W){let H=await a.generateToken(),U=new Headers(o.headers);if(U.set("Authorization",`Bearer ${H}`),ee=await fetch(o.url,{method:o.method,headers:U,body:o.body}),ee.status===401){await a.keys.rotateCurrent();let ae=await a.generateToken(),ce=new Headers(o.headers);ce.set("Authorization",`Bearer ${ae}`),ee=await fetch(o.url,{method:o.method,headers:ce,body:o.body})}}else ee=await a.fetch(o.url,{method:o.method,headers:o.headers,body:o.body});if(ee.status>=500&&R<Be){it=new Error(`HTTP ${ee.status}`),await new Promise(H=>setTimeout(H,oe));continue}break}catch(H){if(it=H,R<Be){await new Promise(U=>setTimeout(U,oe));continue}throw H}if(!ee)throw it;await Ds(ee,i,o.method,o.url,o.headers,k)}catch(a){if(i.silent&&!i.showError&&process.exit(1),Us(a)){if(i.waitOnAuthlink){process.stderr.write(`
|
|
57
|
+
`),process.stderr.write(` ${K("Authorization required:")} ${a.message}
|
|
58
|
+
`),process.stderr.write(` ${$("Auth URL:")} ${b(a.actionUrl)}
|
|
59
|
+
`),process.stderr.write(` ${$("Open this link to authorize, then the request will retry.")}
|
|
60
60
|
`),process.stderr.write(`
|
|
61
|
-
${
|
|
62
|
-
`);try{let c=i.waitTimeout?parseInt(i.waitTimeout,10)*1e3:void 0,l=2e3,u=c?Date.now()+c:1/0,d=0,
|
|
63
|
-
`),process.stderr.write(
|
|
61
|
+
${K("Waiting for user to approve...")}
|
|
62
|
+
`);try{let c=i.waitTimeout?parseInt(i.waitTimeout,10)*1e3:void 0,l=2e3,u=c?Date.now()+c:1/0,d=0,y=!1;for(;Date.now()<u;){await new Promise(k=>setTimeout(k,l)),d++,d%30===0&&process.stderr.write(`
|
|
63
|
+
`),process.stderr.write($("."));try{let k=e();if(o){let W=await k.fetch(o.url,{method:o.method,headers:o.headers,body:o.body});process.stderr.write(`
|
|
64
64
|
|
|
65
|
-
${
|
|
65
|
+
${D("\u2713")} Authorization approved!
|
|
66
66
|
|
|
67
|
-
`),
|
|
67
|
+
`),y=!0,await Ds(W,i,o.method,o.url,o.headers,Date.now());return}}catch(k){if(Us(k))continue;throw k}}y||(process.stderr.write(`
|
|
68
68
|
|
|
69
69
|
${O("Timed out waiting for approval.")}
|
|
70
70
|
|
|
@@ -73,131 +73,131 @@ curl: try 'botparty curl --help' for more information
|
|
|
73
73
|
`),process.stderr.write(` ${O(c instanceof Error?c.message:String(c))}
|
|
74
74
|
|
|
75
75
|
`),process.exit(1)}}process.stderr.write(`
|
|
76
|
-
`),process.stderr.write(` ${
|
|
76
|
+
`),process.stderr.write(` ${K("Credentials required:")} ${a.message}
|
|
77
77
|
`),process.stderr.write(`
|
|
78
|
-
`),process.stderr.write(` ${
|
|
79
|
-
`),process.stderr.write(` ${
|
|
78
|
+
`),process.stderr.write(` ${S("Authorize at:")}
|
|
79
|
+
`),process.stderr.write(` ${b(a.actionUrl)}
|
|
80
80
|
`),process.stderr.write(`
|
|
81
81
|
`)}else process.stderr.write(`curl: (6) ${a instanceof Error?a.message:a}
|
|
82
|
-
`);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}}
|
|
83
|
-
${
|
|
82
|
+
`);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();Ur();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 Ca(){console.log(`
|
|
83
|
+
${S("botparty services")} \u2014 discover and manage BotParty-compatible services
|
|
84
84
|
|
|
85
|
-
${
|
|
85
|
+
${S("USAGE")}
|
|
86
86
|
botparty services <domain> [action] [--params]
|
|
87
87
|
|
|
88
|
-
Use a full domain or a shorthand \u2014 e.g. ${
|
|
88
|
+
Use a full domain or a shorthand \u2014 e.g. ${b('"mongo"')} resolves to ${$("mongo.botparty.club")}.
|
|
89
89
|
Omit the action to list all available actions on a service.
|
|
90
90
|
|
|
91
|
-
${
|
|
92
|
-
botparty services mongo ${
|
|
93
|
-
botparty services mongo databases.list ${
|
|
91
|
+
${S("EXAMPLES")}
|
|
92
|
+
botparty services mongo ${$("List all actions on mongo.botparty.club")}
|
|
93
|
+
botparty services mongo databases.list ${$("List your MongoDB databases")}
|
|
94
94
|
botparty services mongo databases.create --slug my-db
|
|
95
95
|
botparty services deploy projects.deploy --projectName my-site --file ./dist/
|
|
96
|
-
botparty services example.com ${
|
|
96
|
+
botparty services example.com ${$("Discover actions on any domain")}
|
|
97
97
|
|
|
98
|
-
${
|
|
99
|
-
`);let t=Math.max(...
|
|
100
|
-
Any domain that publishes ${
|
|
101
|
-
`)}function
|
|
98
|
+
${S("BOTPARTY SERVICES")}
|
|
99
|
+
`);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(`
|
|
100
|
+
Any domain that publishes ${$("/.well-known/botparty/services.json")} is supported.
|
|
101
|
+
`)}function $a(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){Ca();return}let i=$a(n),o=s[1]&&!s[1].startsWith("-")?s[1]:void 0,a=s.slice(o?2:1);try{o?await Dr(i,o,a,t):await Er(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 E(t,e=1){C?console.log(JSON.stringify({ok:!1,error:{message:t}},null,2)):console.error(`${O("error")}: ${t}`),process.exit(e)}function Oa(t){if(C){let e={ok:!1};t instanceof j?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 nr&&(console.error(`
|
|
102
102
|
${O("NAMESPACE LOCKED")}: ${t.message}`),t.actionUrl&&console.error(`
|
|
103
103
|
A human must unlock it at:
|
|
104
|
-
${
|
|
105
|
-
${
|
|
104
|
+
${b(t.actionUrl)}`),process.exit(1)),t instanceof At&&(console.error(`
|
|
105
|
+
${K("PAYMENT REQUIRED")}: ${t.message}`),t.amount&&console.error(` Amount: $${(t.amount/1e6).toFixed(6)}`),t.actionUrl&&console.error(`
|
|
106
106
|
Complete payment at:
|
|
107
|
-
${
|
|
107
|
+
${b(t.actionUrl)}`),process.exit(1)),t instanceof ft&&(console.error(`
|
|
108
108
|
${O("PERMISSION DENIED")}: ${t.message}`),t.missingScopes?.length&&console.error(` Missing scopes: ${t.missingScopes.join(", ")}`),t.actionUrl&&console.error(`
|
|
109
109
|
Grant access at:
|
|
110
|
-
${
|
|
111
|
-
${
|
|
110
|
+
${b(t.actionUrl)}`),process.exit(1)),t instanceof Et&&(console.error(`
|
|
111
|
+
${K("LINK REQUIRED")}: ${t.message}`),t.actionUrl&&console.error(`
|
|
112
112
|
Link a human account at:
|
|
113
|
-
${
|
|
113
|
+
${b(t.actionUrl)}`),process.exit(1)),t instanceof j&&(console.error(`
|
|
114
114
|
${O(t.code)}: ${t.message}`),t.actionUrl&&console.error(`
|
|
115
|
-
${
|
|
116
|
-
${O("error")}: ${t.message}`),process.exit(1)),console.error(t),process.exit(1)}var
|
|
117
|
-
Use ${
|
|
118
|
-
${
|
|
119
|
-
Identity saved to ${
|
|
120
|
-
`),console.log(` ${
|
|
121
|
-
${
|
|
122
|
-
`),console.log(`Re-run with ${
|
|
123
|
-
${
|
|
124
|
-
`),console.log(`Re-run with ${
|
|
125
|
-
Share the token or set ${
|
|
126
|
-
${
|
|
127
|
-
`);for(let o of i){let a=o.status==="active"?
|
|
128
|
-
${
|
|
129
|
-
`);for(let i of n){let o=i.status==="active"?
|
|
130
|
-
Re-run with ${
|
|
131
|
-
${
|
|
132
|
-
`);for(let a of o){let c=a.status==="active"?
|
|
133
|
-
`);for(let l of o){let u=l.accountLabel&&l.accountLabel!=="default"
|
|
134
|
-
Specify the exact connection ID to delete.`),process.exit(1)}let a=o[0];t.yes!==!0&&t.y!==!0&&E(`This will permanently delete ${
|
|
135
|
-
${
|
|
136
|
-
|
|
137
|
-
${
|
|
115
|
+
${b(t.actionUrl)}`),process.exit(1)),t instanceof Error&&(console.error(`
|
|
116
|
+
${O("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 ms({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 Q(t){return new Date(t).toLocaleString()}function Lr(t){let e=new Date(t).getTime()-Date.now();if(e<=0)return O("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: ${$(c.serverUrl)}`),console.log(`
|
|
117
|
+
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(`
|
|
118
|
+
${D("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(`
|
|
119
|
+
Identity saved to ${$("~/.botparty/")}`))}async function Na(t){let r=I(t).whoami();r||E("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: ${Q(r.rotatedAt)}`),console.log(` Stale at: ${Q(r.staleAt)} (${Lr(r.staleAt)})`),r.label&&console.log(` Label: ${r.label}`),console.log(` Server: ${$(r.serverUrl)}`))}async function Da(t,e){let r=I(t),s=e[0]||r.getIdentity()?.namespace;s||E("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"?D(n.status):O(n.status)}`),console.log(` Linked: ${n.linked?D("yes"):K("no")}`),console.log(` Active keys: ${n.activeKeys}`),console.log(` Created: ${Q(n.createdAt)}`),n.lockedAt&&console.log(` Locked at: ${O(Q(n.lockedAt))}`))}async function Ua(t){let e=I(t);e.isRegistered()||E("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:
|
|
120
|
+
`),console.log(` ${b(r)}`),console.log(`
|
|
121
|
+
${$("The link expires in 5 minutes.")}`))}async function ja(t){let e=I(t);e.isRegistered()||E("Not registered.");let r=e.whoami();if(t.yes!==!0&&t.y!==!0){C&&E("--yes flag required to confirm destruction"),console.log(`${O("WARNING")}: This will permanently destroy namespace ${S(r.namespace)}.`),console.log(`All keys, links, and data will be deleted.
|
|
122
|
+
`),console.log(`Re-run with ${b("--yes")} to confirm.`);return}await e.destroy(),C?N({namespace:r.namespace,destroyed:!0}):console.log(`${D("Destroyed")} namespace ${S(r.namespace)}`)}async function La(t){I(t).reset(),C?N({reset:!0}):(console.log(`${D("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 Ls(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(D("current"));let a=new Date(n.staleAt).getTime();Date.now()>a?o.push(O("stale")):o.push(`stale in ${Lr(n.staleAt)}`),console.log(`${S(n.id)} ${o.join(" | ")}`),console.log(` Fingerprint: ${$(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: ${Q(n.rotatedAt)}`),n.expiresAt&&console.log(` Expires at: ${Q(n.expiresAt)}`),n.lastUsedAt&&console.log(` Last used: ${Q(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||E("--public-key is required (PEM-encoded public key)"),r?.length||E("--scopes is required (comma-separated)"),s||E("--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(`${D("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(`
|
|
123
|
+
${D("Key rotated")}`),console.log(` ID: ${S(n.id)}`),console.log(` Fingerprint: ${n.fingerprint}`),console.log(` Stale at: ${Q(n.staleAt)} (${Lr(n.staleAt)})`))}async function Fa(t,e){let r=e[0];r||E("Usage: botparty keys delete <keyId>");let s=I(t);if(t.yes!==!0&&t.y!==!0){C&&E("--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(`${D("Deleted")} key ${S(r)}`)}async function Ba(t,e){let r=e[0];r||E("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&&E("--yes flag required to confirm invalidation"),console.log(`${O("DANGER")}: This will invalidate key ${S(r)} and ${O("LOCK THE ENTIRE NAMESPACE")}.`),console.log(`All JWTs will be rejected until a human unlocks it.
|
|
124
|
+
`),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(`${O("Key invalidated")} \u2014 namespace is now ${O("LOCKED")}.`),console.log("A human must unlock it at the BotParty web UI."))}async function qa(t){let e=I(t);e.isRegistered()||E("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}));E(a.error||`HTTP ${i.status}`)}let o=await i.json();C?N(o):(console.log(`${D("Invite created")}`),console.log(` Token ID: ${S(o.tokenId)}`),console.log(` Token: ${o.inviteToken}`),console.log(`
|
|
125
|
+
Share the token or set ${b("BOTPARTY_INVITE_TOKEN")} env var.`))}async function Ga(t){let e=I(t);e.isRegistered()||E("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}));E(o.error||`HTTP ${n.status}`)}let{invites:i}=await n.json();if(C){N({invites:i});return}if(i.length===0){console.log($("No invites found."));return}console.log(`
|
|
126
|
+
${S("Invites")} (${i.length})
|
|
127
|
+
`);for(let o of i){let a=o.status==="active"?D(o.status):o.status==="pending"?K(o.status):O(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: ${Q(o.createdAt)}`),console.log("")}}async function za(t){let e=I(t);e.isRegistered()||E("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}));E(i.error||`HTTP ${s.status}`)}let{dependents:n}=await s.json();if(C){N({dependents:n});return}if(n.length===0){console.log($("No dependents found."));return}console.log(`
|
|
128
|
+
${S("Dependents")} (${n.length})
|
|
129
|
+
`);for(let i of n){let o=i.status==="active"?D(i.status):i.status==="pending"?K(i.status):O(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: ${Q(i.createdAt)}`),i.revokedAt&&console.log(` Revoked: ${O(Q(i.revokedAt))}`),console.log("")}}async function Za(t,e){let r=e[0];r||E("Usage: botparty dependents revoke <tokenId>");let s=I(t);if(s.isRegistered()||E("Not registered. Run: botparty init"),t.yes!==!0&&t.y!==!0){C&&E("--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 ${O("LOCKED")}.`),console.log(`
|
|
130
|
+
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}));E(a.error||`HTTP ${i.status}`)}let o=await i.json();C?N({revoked:!0,tokenId:r,childNamespace:o.childNamespace}):(console.log(`${D("Revoked")} token ${S(r)}`),o.childNamespace&&console.log(` Child namespace ${S(o.childNamespace)} is now ${O("LOCKED")}.`))}async function jr(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 jr(`/api/botparty/connections${s?`?${s}`:""}`,e);if(!n.ok){let a=await n.json().catch(()=>({error:n.statusText}));E(a.error||`HTTP ${n.status}`)}let o=(await n.json()).connections;if(C){N({connections:o});return}if(o.length===0){console.log($("No connections found."));return}console.log(`
|
|
131
|
+
${S("Connections")} (${o.length})
|
|
132
|
+
`);for(let a of o){let c=a.status==="active"?D("active"):K(a.status),l=a.type==="api_key"?$("[api_key]"):$("[oauth]"),u=a.accountLabel&&a.accountLabel!=="default"?$(` (${a.accountLabel})`):"",d=a.accountIdentifier?$(` \u2014 ${a.accountIdentifier}`):"";console.log(` ${S(a.displayName||a.provider)} ${l} ${c}${u}${d}`),console.log(` ${$("id:")} ${a.id}`),a.keyNames?.length&&console.log(` ${$("keys:")} ${a.keyNames.join(", ")}`),a.scopes?.length&&console.log(` ${$("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||E("Usage: botparty connections delete <name|provider|id> [--yes]");let s=I(t),n=await jr("/api/botparty/connections",s);if(!n.ok){let l=await n.json().catch(()=>({error:n.statusText}));E(l.error||`HTTP ${n.status}`)}let{connections:i}=await n.json(),o=i.filter(l=>Ya(l,r));if(o.length===0&&E(`No connection found matching "${r}". Run: botparty connections list`),o.length>1){console.error(`${K("Multiple connections match")} "${r}":
|
|
133
|
+
`);for(let l of o){let u=l.accountLabel&&l.accountLabel!=="default"?$(` (${l.accountLabel})`):"";console.error(` ${S(l.displayName||l.provider)}${u} ${$(l.id)}`)}console.error(`
|
|
134
|
+
Specify the exact connection ID to delete.`),process.exit(1)}let a=o[0];t.yes!==!0&&t.y!==!0&&E(`This will permanently delete ${S(a.displayName||a.provider)} (${a.id}). Pass --yes to confirm.`);let c=await jr(`/api/botparty/connections?id=${encodeURIComponent(a.id)}`,s,{method:"DELETE"});if(!c.ok){let l=await c.json().catch(()=>({error:c.statusText}));E(l.error||`HTTP ${c.status}`)}C?N({deleted:!0,connectionId:a.id,provider:a.provider}):console.log(`${D("Deleted")} ${S(a.displayName||a.provider)} (${a.id})`)}function Qa(){console.log(`
|
|
135
|
+
${S("botparty")} \u2014 federated bot identity, authentication, and payments
|
|
136
|
+
|
|
137
|
+
${S("USAGE")}
|
|
138
138
|
botparty <command> [options]
|
|
139
139
|
|
|
140
|
-
${
|
|
141
|
-
${
|
|
140
|
+
${S("COMMANDS")}
|
|
141
|
+
${b("init")} [namespace] Register a new namespace
|
|
142
142
|
--name <name> Human-readable label
|
|
143
143
|
--ttl <minutes> Key rotation TTL (default: 15)
|
|
144
144
|
--invite-token <token> Register as child of an invite's parent
|
|
145
145
|
|
|
146
|
-
${
|
|
147
|
-
${
|
|
148
|
-
${
|
|
149
|
-
${
|
|
150
|
-
${
|
|
146
|
+
${b("whoami")} Show current identity
|
|
147
|
+
${b("info")} [namespace] Show namespace info from server
|
|
148
|
+
${b("link")} Generate a link URL for a human
|
|
149
|
+
${b("token")} Generate a JWT token (stdout)
|
|
150
|
+
${b("reset")} Clear local state
|
|
151
151
|
|
|
152
|
-
${
|
|
152
|
+
${b("services")} [domain] [action] Discover and invoke BotParty-compatible services
|
|
153
153
|
Use a shorthand like "mongo" or a full domain.
|
|
154
|
-
Run ${
|
|
154
|
+
Run ${b("botparty services")} for details.
|
|
155
155
|
|
|
156
|
-
${
|
|
156
|
+
${b("curl")} <url> Authenticated fetch (direct or proxied)
|
|
157
157
|
-X, --method <METHOD> HTTP method (default: GET)
|
|
158
158
|
-d, --data <body> Request body
|
|
159
159
|
-H, --header <header> Additional header
|
|
160
160
|
|
|
161
|
-
${
|
|
161
|
+
${b("invites create")} Create an invite token for child namespaces
|
|
162
162
|
--scopes <s1,s2> Comma-separated scopes (default: all)
|
|
163
163
|
--expires <duration> Expiry (e.g. 24h, 7d; default: 24h)
|
|
164
|
-
${
|
|
164
|
+
${b("invites list")} List invites
|
|
165
165
|
--status <status> Filter by status (pending/active/revoked)
|
|
166
166
|
|
|
167
|
-
${
|
|
168
|
-
${
|
|
167
|
+
${b("dependents list")} List child namespaces
|
|
168
|
+
${b("dependents revoke")} <tokenId> Revoke a child's access (--yes)
|
|
169
169
|
|
|
170
|
-
${
|
|
171
|
-
${
|
|
170
|
+
${b("keys list")} List all keys
|
|
171
|
+
${b("keys add")} Add a delegated key
|
|
172
172
|
--public-key <pem> PEM-encoded public key
|
|
173
173
|
--scopes <s1,s2> Comma-separated scopes
|
|
174
174
|
--ttl <minutes> Rotation TTL
|
|
175
175
|
--label <label> Human-readable label
|
|
176
176
|
--expires <iso> Hard expiry timestamp
|
|
177
177
|
|
|
178
|
-
${
|
|
179
|
-
${
|
|
180
|
-
${
|
|
178
|
+
${b("keys rotate")} [keyId] Rotate a key (default: current)
|
|
179
|
+
${b("keys delete")} <keyId> Delete a key (--yes to confirm)
|
|
180
|
+
${b("keys invalidate")} <keyId> Panic button \u2014 locks namespace
|
|
181
181
|
--reason <text> Reason for invalidation
|
|
182
182
|
|
|
183
|
-
${
|
|
183
|
+
${b("connections list")} List credential connections
|
|
184
184
|
--provider <domain> Filter by provider
|
|
185
185
|
--status <status> Filter by status
|
|
186
|
-
${
|
|
186
|
+
${b("connections delete")} <name> Delete a connection by name, provider, or ID (--yes)
|
|
187
187
|
|
|
188
|
-
${
|
|
188
|
+
${b("destroy")} Destroy namespace (--yes to confirm)
|
|
189
189
|
|
|
190
|
-
${
|
|
190
|
+
${S("GLOBAL OPTIONS")}
|
|
191
191
|
--server <url> BotParty server URL
|
|
192
192
|
--state-dir <path> Local state directory (default: ~/.botparty)
|
|
193
193
|
--json Output machine-readable JSON
|
|
194
194
|
|
|
195
|
-
${
|
|
195
|
+
${S("ENVIRONMENT")}
|
|
196
196
|
BOTPARTY_SERVER_URL Server URL override
|
|
197
197
|
BOTPARTY_STATE_DIR State directory override
|
|
198
198
|
BOTPARTY_INVITE_TOKEN Invite token for auto-registration as child namespace
|
|
199
199
|
|
|
200
|
-
${
|
|
200
|
+
${S("EXAMPLES")}
|
|
201
201
|
botparty init # Auto-generate namespace
|
|
202
202
|
botparty init my-cool-bot --ttl 30 # Custom namespace
|
|
203
203
|
botparty curl https://api.example.com # Authenticated fetch
|
|
@@ -209,4 +209,4 @@ ${k("EXAMPLES")}
|
|
|
209
209
|
botparty keys rotate # Rotate current key
|
|
210
210
|
botparty connections list # Show credential connections
|
|
211
211
|
botparty link # Get link URL for human
|
|
212
|
-
`)}async function
|
|
212
|
+
`)}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")&&t!=="curl"&&t!=="fetch"){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:E(`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:E(`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:E(`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:E(`Unknown connections subcommand: ${e}. Run: botparty connections list`)}break;default:{let n=t.includes(".")?t:`${t}.botparty.club`;if(await Ms(n)){let{discover:o}=await Promise.resolve().then(()=>(It(),Ws)),{execute:a}=await Promise.resolve().then(()=>(Ur(),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,y=u.slice(d?1:0);try{d?await a(n,d,y,()=>I(s)):await o(n)}catch(k){k.code==="ENOTFOUND"||k.cause?.code==="ENOTFOUND"?console.error(`${O("error")}: Could not connect to ${n}`):console.error(`${O("error")}: ${k.message||k}`),process.exit(1)}}else E(`Unknown command: ${t}. Run: botparty --help`);break}}}catch(n){Oa(n)}}ec();
|