botparty 0.0.39 → 0.0.40
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 +40 -40
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,48 +1,48 @@
|
|
|
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 Xt=Object.create;var Qe=Object.defineProperty;var Qt=Object.getOwnPropertyDescriptor;var Zt=Object.getOwnPropertyNames;var er=Object.getPrototypeOf,tr=Object.prototype.hasOwnProperty;var G=(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 N=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var rr=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Zt(e))!tr.call(t,i)&&i!==r&&Qe(t,i,{get:()=>e[i],enumerable:!(n=Qt(e,i))||n.enumerable});return t};var nr=(t,e,r)=>(r=t!=null?Xt(er(t)):{},rr(e||!t||!t.__esModule?Qe(r,"default",{value:t,enumerable:!0}):r,t));var ee=N(Re=>{var ae=class extends Error{constructor(e,r,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=r,this.exitCode=e,this.nestedError=void 0}},Pe=class extends ae{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Re.CommanderError=ae;Re.InvalidArgumentError=Pe});var ce=N(Ie=>{var{InvalidArgumentError:gn}=ee(),xe=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,n)=>{if(!this.argChoices.includes(r))throw new gn(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(r,n):r},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function yn(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}Ie.Argument=xe;Ie.humanReadableArgName=yn});var He=N(Ue=>{var{humanReadableArgName:wn}=ce(),De=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(i=>!i._hidden),n=e._getHelpCommand();return n&&!n._hidden&&r.push(n),this.sortSubcommands&&r.sort((i,s)=>i.name().localeCompare(s.name())),r}compareOptions(e,r){let n=i=>i.short?i.short.replace(/^-/,""):i.long.replace(/^--/,"");return n(e).localeCompare(n(r))}visibleOptions(e){let r=e.options.filter(i=>!i.hidden),n=e._getHelpOption();if(n&&!n.hidden){let i=n.short&&e._findOption(n.short),s=n.long&&e._findOption(n.long);!i&&!s?r.push(n):n.long&&!s?r.push(e.createOption(n.long,n.description)):n.short&&!i&&r.push(e.createOption(n.short,n.description))}return this.sortOptions&&r.sort(this.compareOptions),r}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let r=[];for(let n=e.parent;n;n=n.parent){let i=n.options.filter(s=>!s.hidden);r.push(...i)}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(n=>wn(n)).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((n,i)=>Math.max(n,this.displayWidth(r.styleSubcommandTerm(r.subcommandTerm(i)))),0)}longestOptionTermLength(e,r){return r.visibleOptions(e).reduce((n,i)=>Math.max(n,this.displayWidth(r.styleOptionTerm(r.optionTerm(i)))),0)}longestGlobalOptionTermLength(e,r){return r.visibleGlobalOptions(e).reduce((n,i)=>Math.max(n,this.displayWidth(r.styleOptionTerm(r.optionTerm(i)))),0)}longestArgumentTermLength(e,r){return r.visibleArguments(e).reduce((n,i)=>Math.max(n,this.displayWidth(r.styleArgumentTerm(r.argumentTerm(i)))),0)}commandUsage(e){let r=e._name;e._aliases[0]&&(r=r+"|"+e._aliases[0]);let n="";for(let i=e.parent;i;i=i.parent)n=i.name()+" "+n;return n+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(n=>JSON.stringify(n)).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 n=`(${r.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}argumentDescription(e){let r=[];if(e.argChoices&&r.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&r.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),r.length>0){let n=`(${r.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatItemList(e,r,n){return r.length===0?[]:[n.styleTitle(e),...r,""]}groupItems(e,r,n){let i=new Map;return e.forEach(s=>{let o=n(s);i.has(o)||i.set(o,[])}),r.forEach(s=>{let o=n(s);i.has(o)||i.set(o,[]),i.get(o).push(s)}),i}formatHelp(e,r){let n=r.padWidth(e,r),i=r.helpWidth??80;function s(d,h){return r.formatItem(d,n,h,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),i),""]));let c=r.visibleArguments(e).map(d=>s(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,h)=>{let w=d.map(T=>s(r.styleOptionTerm(r.optionTerm(T)),r.styleOptionDescription(r.optionDescription(T))));o=o.concat(this.formatItemList(h,w,r))}),r.showGlobalOptions){let d=r.visibleGlobalOptions(e).map(h=>s(r.styleOptionTerm(r.optionTerm(h)),r.styleOptionDescription(r.optionDescription(h))));o=o.concat(this.formatItemList("Global Options:",d,r))}return this.groupItems(e.commands,r.visibleCommands(e),d=>d.helpGroup()||"Commands:").forEach((d,h)=>{let w=d.map(T=>s(r.styleSubcommandTerm(r.subcommandTerm(T)),r.styleSubcommandDescription(r.subcommandDescription(T))));o=o.concat(this.formatItemList(h,w,r))}),o.join(`
|
|
5
|
+
`)}displayWidth(e){return Ot(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,n,i){let o=" ".repeat(2);if(!n)return o+e;let a=e.padEnd(r+e.length-i.displayWidth(e)),c=2,u=(this.helpWidth??80)-r-c-2,d;return u<this.minWidthToWrap||i.preformatted(n)?d=n:d=i.boxWrap(n,u).replace(/\n/g,`
|
|
6
6
|
`+" ".repeat(r+c)),o+a+" ".repeat(c)+d.replace(/\n/g,`
|
|
7
7
|
${o}`)}boxWrap(e,r){if(r<this.minWidthToWrap)return e;let n=e.split(/\r\n|\n/),i=/[\s]*[^\s]+/g,s=[];return n.forEach(o=>{let a=o.match(i);if(a===null){s.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}s.push(c.join(""));let h=u.trimStart();c=[h],l=this.displayWidth(h)}),s.push(c.join(""))}),s.join(`
|
|
8
|
-
`)}};function
|
|
8
|
+
`)}};function Ot(t){let e=/\x1b\[\d*(;\d*)*m/g;return t.replace(e,"")}Ue.Help=De;Ue.stripColor=Ot});var We=N(Ke=>{var{InvalidArgumentError:bn}=ee(),Ne=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 n=En(e);this.short=n.shortFlag,this.long=n.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,n)=>{if(!this.argChoices.includes(r))throw new bn(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(r,n):r},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?Pt(this.name().replace(/^no-/,"")):Pt(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}},Le=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,n)=>{this.positiveOptions.has(n)&&this.dualOptions.add(n)})}valueFromOption(e,r){let n=r.attributeName();if(!this.dualOptions.has(n))return!0;let i=this.negativeOptions.get(n).presetArg,s=i!==void 0?i:!1;return r.negate===(s===e)}};function Pt(t){return t.split("-").reduce((e,r)=>e+r[0].toUpperCase()+r.slice(1))}function En(t){let e,r,n=/^-[^-]$/,i=/^--[^-]/,s=t.split(/[ |,]+/).concat("guard");if(n.test(s[0])&&(e=s.shift()),i.test(s[0])&&(r=s.shift()),!e&&n.test(s[0])&&(e=s.shift()),!e&&i.test(s[0])&&(e=r,r=s.shift()),s[0].startsWith("-")){let o=s[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')`):n.test(o)?new Error(`${a}
|
|
12
12
|
- too many short flags`):i.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}}Ke.Option=Ne;Ke.DualOptions=Le});var xt=N(Rt=>{function vn(t,e){if(Math.abs(t.length-e.length)>3)return Math.max(t.length,e.length);let r=[];for(let n=0;n<=t.length;n++)r[n]=[n];for(let n=0;n<=e.length;n++)r[0][n]=n;for(let n=1;n<=e.length;n++)for(let i=1;i<=t.length;i++){let s=1;t[i-1]===e[n-1]?s=0:s=1,r[i][n]=Math.min(r[i-1][n]+1,r[i][n-1]+1,r[i-1][n-1]+s),i>1&&n>1&&t[i-1]===e[n-2]&&t[i-2]===e[n-1]&&(r[i][n]=Math.min(r[i][n],r[i-2][n-2]+1))}return r[t.length][e.length]}function _n(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 n=[],i=3,s=.4;return e.forEach(o=>{if(o.length<=1)return;let a=vn(t,o),c=Math.max(t.length,o.length);(c-a)/c>s&&(a<i?(i=a,n=[o]):a===i&&n.push(o))}),n.sort((o,a)=>o.localeCompare(a)),r&&(n=n.map(o=>`--${o}`)),n.length>1?`
|
|
15
15
|
(Did you mean one of ${n.join(", ")}?)`:n.length===1?`
|
|
16
|
-
(Did you mean ${n[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 '${n.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,n){this._exitCallback&&this._exitCallback(new
|
|
19
|
-
- already used by option '${r.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let r=i=>[i.name()].concat(i.aliases()),n=r(e).find(i=>this._findCommand(i));if(n){let i=r(this._findCommand(n)).join("|"),s=r(e).join("|");throw new Error(`cannot add command '${s}' as already have command '${i}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let r=e.name(),n=e.attributeName();if(e.negate){let s=e.long.replace(/^--no-/,"--");this._findOption(s)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let i=(s,o,a)=>{s==null&&e.presetArg!==void 0&&(s=e.presetArg);let c=this.getOptionValue(n);s!==null&&e.parseArg?s=this._callParseArg(e,s,c,o):s!==null&&e.variadic&&(s=e._collectValue(s,c)),s==null&&(e.negate?s=!1:e.isBoolean()||e.optional?s=!0:s=""),this.setOptionValueWithSource(n,s,a)};return this.on("option:"+r,s=>{let o=`error: option '${e.flags}' argument '${s}' is invalid.`;i(s,o,"cli")}),e.envVar&&this.on("optionEnv:"+r,s=>{let o=`error: option '${e.flags}' value '${s}' from env '${e.envVar}' is invalid.`;i(s,o,"env")}),this}_optionEx(e,r,n,i,s){if(typeof r=="object"&&r instanceof
|
|
16
|
+
(Did you mean ${n[0]}?)`:""}Rt.suggestSimilar=_n});var Ht=N(qe=>{var An=G("node:events").EventEmitter,je=G("node:child_process"),D=G("node:path"),le=G("node:fs"),g=G("node:process"),{Argument:kn,humanReadableArgName:Sn}=ce(),{CommanderError:Me}=ee(),{Help:Cn,stripColor:Tn}=He(),{Option:It,DualOptions:$n}=We(),{suggestSimilar:Dt}=xt(),Ve=class t extends An{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=>g.stdout.write(r),writeErr:r=>g.stderr.write(r),outputError:(r,n)=>n(r),getOutHelpWidth:()=>g.stdout.isTTY?g.stdout.columns:void 0,getErrHelpWidth:()=>g.stderr.isTTY?g.stderr.columns:void 0,getOutHasColors:()=>Fe()??(g.stdout.isTTY&&g.stdout.hasColors?.()),getErrHasColors:()=>Fe()??(g.stderr.isTTY&&g.stderr.hasColors?.()),stripColor:r=>Tn(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,n){let i=r,s=n;typeof i=="object"&&i!==null&&(s=i,i=null),s=s||{};let[,o,a]=e.match(/([^ ]+) *(.*)/),c=this.createCommand(o);return i&&(c.description(i),c._executableHandler=!0),s.isDefault&&(this._defaultCommandName=c._name),c._hidden=!!(s.noHelp||s.hidden),c._executableFile=s.executableFile||null,a&&c.arguments(a),this._registerCommand(c),c.parent=this,c.copyInheritedSettings(this),i?this:c}createCommand(e){return new t(e)}createHelp(){return Object.assign(new Cn,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 kn(e,r)}argument(e,r,n,i){let s=this.createArgument(e,r);return typeof n=="function"?s.default(i).argParser(n):s.default(n),this.addArgument(s),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 n=e??"help [command]",[,i,s]=n.match(/([^ ]+) *(.*)/),o=r??"display help for command",a=this.createCommand(i);return a.helpOption(!1),s&&a.arguments(s),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 n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
|
|
18
|
+
Expecting one of '${n.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,n){this._exitCallback&&this._exitCallback(new Me(e,r,n)),g.exit(e)}action(e){let r=n=>{let i=this.registeredArguments.length,s=n.slice(0,i);return this._storeOptionsAsProperties?s[i]=this:s[i]=this.opts(),s.push(this),e.apply(this,s)};return this._actionHandler=r,this}createOption(e,r){return new It(e,r)}_callParseArg(e,r,n,i){try{return e.parseArg(r,n)}catch(s){if(s.code==="commander.invalidArgument"){let o=`${i} ${s.message}`;this.error(o,{exitCode:s.exitCode,code:s.code})}throw s}}_registerOption(e){let r=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(r){let n=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 '${n}'
|
|
19
|
+
- already used by option '${r.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let r=i=>[i.name()].concat(i.aliases()),n=r(e).find(i=>this._findCommand(i));if(n){let i=r(this._findCommand(n)).join("|"),s=r(e).join("|");throw new Error(`cannot add command '${s}' as already have command '${i}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let r=e.name(),n=e.attributeName();if(e.negate){let s=e.long.replace(/^--no-/,"--");this._findOption(s)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let i=(s,o,a)=>{s==null&&e.presetArg!==void 0&&(s=e.presetArg);let c=this.getOptionValue(n);s!==null&&e.parseArg?s=this._callParseArg(e,s,c,o):s!==null&&e.variadic&&(s=e._collectValue(s,c)),s==null&&(e.negate?s=!1:e.isBoolean()||e.optional?s=!0:s=""),this.setOptionValueWithSource(n,s,a)};return this.on("option:"+r,s=>{let o=`error: option '${e.flags}' argument '${s}' is invalid.`;i(s,o,"cli")}),e.envVar&&this.on("optionEnv:"+r,s=>{let o=`error: option '${e.flags}' value '${s}' from env '${e.envVar}' is invalid.`;i(s,o,"env")}),this}_optionEx(e,r,n,i,s){if(typeof r=="object"&&r instanceof It)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(r,n);if(o.makeOptionMandatory(!!e.mandatory),typeof i=="function")o.default(s).argParser(i);else if(i instanceof RegExp){let a=i;i=(c,l)=>{let u=a.exec(c);return u?u[0]:l},o.default(s).argParser(i)}else o.default(i);return this.addOption(o)}option(e,r,n,i){return this._optionEx({},e,r,n,i)}requiredOption(e,r,n,i){return this._optionEx({mandatory:!0},e,r,n,i)}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,n){return this._storeOptionsAsProperties?this[e]=r:this._optionValues[e]=r,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let r;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(r=n.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){g.versions?.electron&&(r.from="electron");let i=g.execArgv??[];(i.includes("-e")||i.includes("--eval")||i.includes("-p")||i.includes("--print"))&&(r.from="eval")}e===void 0&&(e=g.argv),this.rawArgs=e.slice();let n;switch(r.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":g.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=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",n}parse(e,r){this._prepareForParse();let n=this._prepareUserArgs(e,r);return this._parseCommand([],n),this}async parseAsync(e,r){this._prepareForParse();let n=this._prepareUserArgs(e,r);return await this._parseCommand([],n),this}_prepareForParse(){this._savedState===null?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
20
20
|
- either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(e,r,n){if(le.existsSync(e))return;let i=r?`searched for local subcommand relative to directory '${r}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",s=`'${e}' does not exist
|
|
21
21
|
- if '${n}' 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
|
-
- ${i}`;throw new Error(s)}_executeSubCommand(e,r){r=r.slice();let n=!1,i=[".js",".ts",".tsx",".mjs",".cjs"];function s(u,d){let h=D.resolve(u,d);if(le.existsSync(h))return h;if(i.includes(D.extname(d)))return;let w=i.find(T=>le.existsSync(`${h}${T}`));if(w)return`${h}${w}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let u;try{u=le.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=D.resolve(D.dirname(u),a)}if(a){let u=s(a,o);if(!u&&!e._executableFile&&this._scriptPath){let d=D.basename(this._scriptPath,D.extname(this._scriptPath));d!==this._name&&(u=s(a,`${d}-${e._name}`))}o=u||o}n=i.includes(D.extname(o));let c;g.platform!=="win32"?n?(r.unshift(o),r=
|
|
23
|
+
- ${i}`;throw new Error(s)}_executeSubCommand(e,r){r=r.slice();let n=!1,i=[".js",".ts",".tsx",".mjs",".cjs"];function s(u,d){let h=D.resolve(u,d);if(le.existsSync(h))return h;if(i.includes(D.extname(d)))return;let w=i.find(T=>le.existsSync(`${h}${T}`));if(w)return`${h}${w}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let u;try{u=le.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=D.resolve(D.dirname(u),a)}if(a){let u=s(a,o);if(!u&&!e._executableFile&&this._scriptPath){let d=D.basename(this._scriptPath,D.extname(this._scriptPath));d!==this._name&&(u=s(a,`${d}-${e._name}`))}o=u||o}n=i.includes(D.extname(o));let c;g.platform!=="win32"?n?(r.unshift(o),r=Ut(g.execArgv).concat(r),c=je.spawn(g.argv[0],r,{stdio:"inherit"})):c=je.spawn(o,r,{stdio:"inherit"}):(this._checkForMissingExecutable(o,a,e._name),r.unshift(o),r=Ut(g.execArgv).concat(r),c=je.spawn(g.execPath,r,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(d=>{g.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 Me(u,"commander.executeSubCommandAsync","(close)")):g.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)g.exit(1);else{let d=new Me(1,"commander.executeSubCommandAsync","(error)");d.nestedError=u,l(d)}}),this.runningCommand=c}_dispatchSubcommand(e,r,n){let i=this._findCommand(e);i||this.help({error:!0}),i._prepareForParse();let s;return s=this._chainOrCallSubCommandHook(s,i,"preSubcommand"),s=this._chainOrCall(s,()=>{if(i._executableHandler)this._executeSubCommand(i,r.concat(n));else return i._parseCommand(r,n)}),s}_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=(n,i,s)=>{let o=i;if(i!==null&&n.parseArg){let a=`error: command-argument value '${i}' is invalid for argument '${n.name()}'.`;o=this._callParseArg(n,i,s,a)}return o};this._checkNumberOfArguments();let r=[];this.registeredArguments.forEach((n,i)=>{let s=n.defaultValue;n.variadic?i<this.args.length?(s=this.args.slice(i),n.parseArg&&(s=s.reduce((o,a)=>e(n,a,o),n.defaultValue))):s===void 0&&(s=[]):i<this.args.length&&(s=this.args[i],n.parseArg&&(s=e(n,s,n.defaultValue))),r[i]=s}),this.processedArgs=r}_chainOrCall(e,r){return e?.then&&typeof e.then=="function"?e.then(()=>r()):r()}_chainOrCallHooks(e,r){let n=e,i=[];return this._getCommandAndAncestors().reverse().filter(s=>s._lifeCycleHooks[r]!==void 0).forEach(s=>{s._lifeCycleHooks[r].forEach(o=>{i.push({hookedCommand:s,callback:o})})}),r==="postAction"&&i.reverse(),i.forEach(s=>{n=this._chainOrCall(n,()=>s.callback(s.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,r,n){let i=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(s=>{i=this._chainOrCall(i,()=>s(this,r))}),i}_parseCommand(e,r){let n=this.parseOptions(r);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),r=n.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(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},s=`command:${this.name()}`;if(this._actionHandler){i(),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(s,e,r)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent?.listenerCount(s))i(),this._processArguments(),this.parent.emit(s,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():(i(),this._processArguments())}else this.commands.length?(i(),this.help({error:!0})):(i(),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(n=>{let i=n.attributeName();return this.getOptionValue(i)===void 0?!1:this.getOptionValueSource(i)!=="default"});e.filter(n=>n.conflictsWith.length>0).forEach(n=>{let i=e.find(s=>n.conflictsWith.includes(s.attributeName()));i&&this._conflictingOption(n,i)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let r=[],n=[],i=r;function s(u){return u.length>1&&u[0]==="-"}let o=u=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(u)?!this._getCommandAndAncestors().some(d=>d.options.map(h=>h.short).some(h=>/^-\d$/.test(h))):!1,a=null,c=null,l=0;for(;l<e.length||c;){let u=c??e[l++];if(c=null,u==="--"){i===n&&i.push(u),i.push(...e.slice(l));break}if(a&&(!s(u)||o(u))){this.emit(`option:${a.name()}`,u);continue}if(a=null,s(u)){let d=this._findOption(u);if(d){if(d.required){let h=e[l++];h===void 0&&this.optionMissingArgument(d),this.emit(`option:${d.name()}`,h)}else if(d.optional){let h=null;l<e.length&&(!s(e[l])||o(e[l]))&&(h=e[l++]),this.emit(`option:${d.name()}`,h)}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("="),h=this._findOption(u.slice(0,d));if(h&&(h.required||h.optional)){this.emit(`option:${h.name()}`,u.slice(d+1));continue}}if(i===r&&s(u)&&!(this.commands.length===0&&o(u))&&(i=n),(this._enablePositionalOptions||this._passThroughOptions)&&r.length===0&&n.length===0){if(this._findCommand(u)){r.push(u),n.push(...e.slice(l));break}else if(this._getHelpCommand()&&u===this._getHelpCommand().name()){r.push(u,...e.slice(l));break}else if(this._defaultCommandName){n.push(u,...e.slice(l));break}}if(this._passThroughOptions){i.push(u,...e.slice(l));break}i.push(u)}return{operands:r,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},r=this.options.length;for(let n=0;n<r;n++){let i=this.options[n].attributeName();e[i]=i===this._versionOptionName?this._version:this[i]}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 n=r||{},i=n.exitCode||1,s=n.code||"commander.error";this._exit(i,s,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in g.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()}`,g.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 n=this.parent?._findCommand(e);if(n){let i=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${i}'`)}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(n=>
|
|
26
|
+
`),this.outputHelp({error:!0}));let n=r||{},i=n.exitCode||1,s=n.code||"commander.error";this._exit(i,s,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in g.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()}`,g.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new $n(this.options),r=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&r(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(i=>!r(i)).forEach(i=>{this.setOptionValueWithSource(i,n.implied[i],"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 n=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},i=o=>{let a=n(o),c=a.attributeName();return this.getOptionValueSource(c)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},s=`error: ${i(e)} cannot be used with ${i(r)}`;this.error(s,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let r="";if(e.startsWith("--")&&this._showSuggestionAfterError){let i=[],s=this;do{let o=s.createHelp().visibleOptions(s).filter(a=>a.long).map(a=>a.long);i=i.concat(o),s=s.parent}while(s&&!s._enablePositionalOptions);r=Dt(e,i)}let n=`error: unknown option '${e}'${r}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let r=this.registeredArguments.length,n=r===1?"":"s",s=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${r} argument${n} but got ${e.length}.`;this.error(s,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],r="";if(this._showSuggestionAfterError){let i=[];this.createHelp().visibleCommands(this).forEach(s=>{i.push(s.name()),s.alias()&&i.push(s.alias())}),r=Dt(e,i)}let n=`error: unknown command '${e}'${r}`;this.error(n,{code:"commander.unknownCommand"})}version(e,r,n){if(e===void 0)return this._version;this._version=e,r=r||"-V, --version",n=n||"output the version number";let i=this.createOption(r,n);return this._versionOptionName=i.attributeName(),this._registerOption(i),this.on("option:"+i.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 n=this.parent?._findCommand(e);if(n){let i=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${i}'`)}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(n=>Sn(n));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=D.basename(e,D.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let r=this.createHelp(),n=this._getOutputContext(e);r.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let i=r.formatHelp(this,r);return n.hasColors?i:this._outputConfiguration.stripColor(i)}_getOutputContext(e){e=e||{};let r=!!e.error,n,i,s;return r?(n=a=>this._outputConfiguration.writeErr(a),i=this._outputConfiguration.getErrHasColors(),s=this._outputConfiguration.getErrHelpWidth()):(n=a=>this._outputConfiguration.writeOut(a),i=this._outputConfiguration.getOutHasColors(),s=this._outputConfiguration.getOutHelpWidth()),{error:r,write:a=>(i||(a=this._outputConfiguration.stripColor(a)),n(a)),hasColors:i,helpWidth:s}}outputHelp(e){let r;typeof e=="function"&&(r=e,e=void 0);let n=this._getOutputContext(e),i={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(o=>o.emit("beforeAllHelp",i)),this.emit("beforeHelp",i);let s=this.helpInformation({error:n.error});if(r&&(s=r(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",i),this._getCommandAndAncestors().forEach(o=>o.emit("afterAllHelp",i))}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(g.exitCode??0);r===0&&e&&typeof e!="function"&&e.error&&(r=1),this._exit(r,"commander.help","(outputHelp)")}addHelpText(e,r){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
|
|
28
28
|
Expecting one of '${n.join("', '")}'`);let i=`${e}Help`;return this.on(i,s=>{let o;typeof r=="function"?o=r({error:s.error,command:s.command}):o=r,o&&s.write(`${o}
|
|
29
|
-
`)}),this}_outputHelpIfRequested(e){let r=this._getHelpOption();r&&e.find(i=>r.is(i))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function xt(t){return t.map(e=>{if(!e.startsWith("--inspect"))return e;let r,n="127.0.0.1",i="9229",s;return(s=e.match(/^(--inspect(-brk)?)$/))!==null?r=s[1]:(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(r=s[1],/^\d+$/.test(s[3])?i=s[3]:n=s[3]):(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(r=s[1],n=s[3],i=s[4]),r&&i!=="0"?`${r}=${n}:${parseInt(i)+1}`:e})}function je(){if(g.env.NO_COLOR||g.env.FORCE_COLOR==="0"||g.env.FORCE_COLOR==="false")return!1;if(g.env.FORCE_COLOR||g.env.CLICOLOR_FORCE!==void 0)return!0}Me.Command=We;Me.useColor=je});var Nt=H(P=>{var{Argument:Dt}=ce(),{Command:Ve}=It(),{CommanderError:kn,InvalidArgumentError:Ut}=ee(),{Help:Sn}=Ie(),{Option:Ht}=Ne();P.program=new Ve;P.createCommand=t=>new Ve(t);P.createOption=(t,e)=>new Ht(t,e);P.createArgument=(t,e)=>new Dt(t,e);P.Command=Ve;P.Option=Ht;P.Argument=Dt;P.Help=Sn;P.CommanderError=kn;P.InvalidArgumentError=Ut;P.InvalidOptionArgumentError=Ut});import{readFileSync as wt,writeFileSync as bt,mkdirSync as Fr,existsSync as ie,unlinkSync as qr}from"node:fs";import{join as V}from"node:path";import{homedir as Br}from"node:os";import{randomBytes as Et}from"node:crypto";var it=new TextEncoder,ze=new TextDecoder,di=2**32;function tr(...t){let e=t.reduce((i,{length:s})=>i+s,0),r=new Uint8Array(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return r}function pe(t){let e=new Uint8Array(t.length);for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);if(n>127)throw new TypeError("non-ASCII string encountered in encode()");e[r]=n}return e}function st(t){if(Uint8Array.prototype.toBase64)return t.toBase64();let e=32768,r=[];for(let n=0;n<t.length;n+=e)r.push(String.fromCharCode.apply(null,t.subarray(n,n+e)));return btoa(r.join(""))}function ot(t){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(t);let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}function rr(t){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof t=="string"?t:ze.decode(t),{alphabet:"base64url"});let e=t;e instanceof Uint8Array&&(e=ze.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/");try{return ot(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}function me(t){let e=t;return typeof e=="string"&&(e=it.encode(e)),Uint8Array.prototype.toBase64?e.toBase64({alphabet:"base64url",omitPadding:!0}):st(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}var U=(t,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`),K=(t,e)=>t.name===e;function nr(t){return parseInt(t.name.slice(4),10)}function fe(t,e){if(nr(t.hash)!==e)throw U(`SHA-${e}`,"algorithm.hash")}function ir(t){switch(t){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function sr(t,e){if(e&&!t.usages.includes(e))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${e}.`)}function or(t,e,r){switch(e){case"HS256":case"HS384":case"HS512":{if(!K(t.algorithm,"HMAC"))throw U("HMAC");fe(t.algorithm,parseInt(e.slice(2),10));break}case"RS256":case"RS384":case"RS512":{if(!K(t.algorithm,"RSASSA-PKCS1-v1_5"))throw U("RSASSA-PKCS1-v1_5");fe(t.algorithm,parseInt(e.slice(2),10));break}case"PS256":case"PS384":case"PS512":{if(!K(t.algorithm,"RSA-PSS"))throw U("RSA-PSS");fe(t.algorithm,parseInt(e.slice(2),10));break}case"Ed25519":case"EdDSA":{if(!K(t.algorithm,"Ed25519"))throw U("Ed25519");break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{if(!K(t.algorithm,e))throw U(e);break}case"ES256":case"ES384":case"ES512":{if(!K(t.algorithm,"ECDSA"))throw U("ECDSA");let n=ir(e);if(t.algorithm.namedCurve!==n)throw U(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}sr(t,r)}function at(t,e,...r){if(r=r.filter(Boolean),r.length>2){let n=r.pop();t+=`one of type ${r.join(", ")}, or ${n}.`}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 ct=(t,...e)=>at("Key must be ",t,...e),lt=(t,e,...r)=>at(`Key for the ${t} algorithm must be `,e,...r),ve=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)}},O=class extends ve{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},J=class extends ve{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},ar=class extends ve{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"},Ae=t=>{if(t?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return t instanceof CryptoKey}catch{return!1}},_e=t=>t?.[Symbol.toStringTag]==="KeyObject",ut=t=>Ae(t)||_e(t),hi=Symbol();function Xe(t,e){if(t)throw new TypeError(`${e} can only be called once`)}var cr=t=>typeof t=="object"&&t!==null;function dt(t){if(!cr(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 lr(...t){let e=t.filter(Boolean);if(e.length===0||e.length===1)return!0;let r;for(let n of e){let i=Object.keys(n);if(!r||r.size===0){r=new Set(i);continue}for(let s of i){if(r.has(s))return!1;r.add(s)}}return!0}var ke=t=>dt(t)&&typeof t.kty=="string",ur=t=>t.kty!=="oct"&&(t.kty==="AKP"&&typeof t.priv=="string"||typeof t.d=="string"),dr=t=>t.kty!=="oct"&&t.d===void 0&&t.priv===void 0,hr=t=>t.kty==="oct"&&typeof t.k=="string";function pr(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 mr(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 O(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}async function fr(t,e,r){if(e instanceof Uint8Array){if(!t.startsWith("HS"))throw new TypeError(ct(e,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",e,{hash:`SHA-${t.slice(-3)}`,name:"HMAC"},!1,[r])}return or(e,t,r),e}async function gr(t,e,r){let n=await fr(t,e,"sign");pr(t,n);let i=await crypto.subtle.sign(mr(t,n.algorithm),n,r);return new Uint8Array(i)}var re='Invalid or unsupported JWK "alg" (Algorithm) Parameter value';function yr(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 O(re)}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 O(re)}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 O(re)}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 O(re)}break}default:throw new O('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:r}}async function wr(t){if(!t.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:e,keyUsages:r}=yr(t),n={...t};return n.kty!=="AKP"&&delete n.alg,delete n.use,crypto.subtle.importKey("jwk",n,e,t.ext??!(t.d||t.priv),t.key_ops??r)}var W="given KeyObject instance cannot be used for this algorithm",M,Qe=async(t,e,r,n=!1)=>{M||=new WeakMap;let i=M.get(t);if(i?.[r])return i[r];let s=await wr({...e,alg:r});return n&&Object.freeze(t),i?i[r]=s:M.set(t,{[r]:s}),s},br=(t,e)=>{M||=new WeakMap;let r=M.get(t);if(r?.[e])return r[e];let n=t.type==="public",i=!!n,s;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(W)}s=t.toCryptoKey(t.asymmetricKeyType,i,n?[]:["deriveBits"])}if(t.asymmetricKeyType==="ed25519"){if(e!=="EdDSA"&&e!=="Ed25519")throw new TypeError(W);s=t.toCryptoKey(t.asymmetricKeyType,i,[n?"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(W);s=t.toCryptoKey(t.asymmetricKeyType,i,[n?"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(W)}if(e.startsWith("RSA-OAEP"))return t.toCryptoKey({name:"RSA-OAEP",hash:o},i,n?["encrypt"]:["decrypt"]);s=t.toCryptoKey({name:e.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:o},i,[n?"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(W);let a={ES256:"P-256",ES384:"P-384",ES512:"P-521"};a[e]&&o===a[e]&&(s=t.toCryptoKey({name:"ECDSA",namedCurve:o},i,[n?"verify":"sign"])),e.startsWith("ECDH-ES")&&(s=t.toCryptoKey({name:"ECDH",namedCurve:o},i,n?[]:["deriveBits"]))}if(!s)throw new TypeError(W);return r?r[e]=s:M.set(t,{[e]:s}),s};async function Er(t,e){if(t instanceof Uint8Array||Ae(t))return t;if(_e(t)){if(t.type==="secret")return t.export();if("toCryptoKey"in t&&typeof t.toCryptoKey=="function")try{return br(t,e)}catch(n){if(n instanceof TypeError)throw n}let r=t.export({format:"jwk"});return Qe(t,r,e)}if(ke(t))return t.k?rr(t.k):Qe(t,t,e,!0);throw new Error("unreachable")}var vr=(t,e)=>{let r=(t.match(/.{1,64}/g)||[]).join(`
|
|
29
|
+
`)}),this}_outputHelpIfRequested(e){let r=this._getHelpOption();r&&e.find(i=>r.is(i))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Ut(t){return t.map(e=>{if(!e.startsWith("--inspect"))return e;let r,n="127.0.0.1",i="9229",s;return(s=e.match(/^(--inspect(-brk)?)$/))!==null?r=s[1]:(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(r=s[1],/^\d+$/.test(s[3])?i=s[3]:n=s[3]):(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(r=s[1],n=s[3],i=s[4]),r&&i!=="0"?`${r}=${n}:${parseInt(i)+1}`:e})}function Fe(){if(g.env.NO_COLOR||g.env.FORCE_COLOR==="0"||g.env.FORCE_COLOR==="false")return!1;if(g.env.FORCE_COLOR||g.env.CLICOLOR_FORCE!==void 0)return!0}qe.Command=Ve;qe.useColor=Fe});var Wt=N(P=>{var{Argument:Nt}=ce(),{Command:Be}=Ht(),{CommanderError:On,InvalidArgumentError:Lt}=ee(),{Help:Pn}=He(),{Option:Kt}=We();P.program=new Be;P.createCommand=t=>new Be(t);P.createOption=(t,e)=>new Kt(t,e);P.createArgument=(t,e)=>new Nt(t,e);P.Command=Be;P.Option=Kt;P.Argument=Nt;P.Help=Pn;P.CommanderError=On;P.InvalidArgumentError=Lt;P.InvalidOptionArgumentError=Lt});import{readFileSync as _t,writeFileSync as Ce,mkdirSync as Gr,existsSync as ie,unlinkSync as Te,statSync as Jr,renameSync as At}from"node:fs";import{join as H}from"node:path";import{homedir as Yr}from"node:os";import{randomBytes as kt}from"node:crypto";var ct=new TextEncoder,Ze=new TextDecoder,gi=2**32;function ir(...t){let e=t.reduce((i,{length:s})=>i+s,0),r=new Uint8Array(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return r}function pe(t){let e=new Uint8Array(t.length);for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);if(n>127)throw new TypeError("non-ASCII string encountered in encode()");e[r]=n}return e}function lt(t){if(Uint8Array.prototype.toBase64)return t.toBase64();let e=32768,r=[];for(let n=0;n<t.length;n+=e)r.push(String.fromCharCode.apply(null,t.subarray(n,n+e)));return btoa(r.join(""))}function ut(t){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(t);let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}function sr(t){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof t=="string"?t:Ze.decode(t),{alphabet:"base64url"});let e=t;e instanceof Uint8Array&&(e=Ze.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/");try{return ut(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}function me(t){let e=t;return typeof e=="string"&&(e=ct.encode(e)),Uint8Array.prototype.toBase64?e.toBase64({alphabet:"base64url",omitPadding:!0}):lt(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}var U=(t,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`),W=(t,e)=>t.name===e;function or(t){return parseInt(t.name.slice(4),10)}function fe(t,e){if(or(t.hash)!==e)throw U(`SHA-${e}`,"algorithm.hash")}function ar(t){switch(t){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function cr(t,e){if(e&&!t.usages.includes(e))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${e}.`)}function lr(t,e,r){switch(e){case"HS256":case"HS384":case"HS512":{if(!W(t.algorithm,"HMAC"))throw U("HMAC");fe(t.algorithm,parseInt(e.slice(2),10));break}case"RS256":case"RS384":case"RS512":{if(!W(t.algorithm,"RSASSA-PKCS1-v1_5"))throw U("RSASSA-PKCS1-v1_5");fe(t.algorithm,parseInt(e.slice(2),10));break}case"PS256":case"PS384":case"PS512":{if(!W(t.algorithm,"RSA-PSS"))throw U("RSA-PSS");fe(t.algorithm,parseInt(e.slice(2),10));break}case"Ed25519":case"EdDSA":{if(!W(t.algorithm,"Ed25519"))throw U("Ed25519");break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{if(!W(t.algorithm,e))throw U(e);break}case"ES256":case"ES384":case"ES512":{if(!W(t.algorithm,"ECDSA"))throw U("ECDSA");let n=ar(e);if(t.algorithm.namedCurve!==n)throw U(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}cr(t,r)}function dt(t,e,...r){if(r=r.filter(Boolean),r.length>2){let n=r.pop();t+=`one of type ${r.join(", ")}, or ${n}.`}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 ht=(t,...e)=>dt("Key must be ",t,...e),pt=(t,e,...r)=>dt(`Key for the ${t} algorithm must be `,e,...r),ve=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)}},O=class extends ve{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},J=class extends ve{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},ur=class extends ve{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"},_e=t=>{if(t?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return t instanceof CryptoKey}catch{return!1}},Ae=t=>t?.[Symbol.toStringTag]==="KeyObject",mt=t=>_e(t)||Ae(t),yi=Symbol();function et(t,e){if(t)throw new TypeError(`${e} can only be called once`)}var dr=t=>typeof t=="object"&&t!==null;function ft(t){if(!dr(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 hr(...t){let e=t.filter(Boolean);if(e.length===0||e.length===1)return!0;let r;for(let n of e){let i=Object.keys(n);if(!r||r.size===0){r=new Set(i);continue}for(let s of i){if(r.has(s))return!1;r.add(s)}}return!0}var ke=t=>ft(t)&&typeof t.kty=="string",pr=t=>t.kty!=="oct"&&(t.kty==="AKP"&&typeof t.priv=="string"||typeof t.d=="string"),mr=t=>t.kty!=="oct"&&t.d===void 0&&t.priv===void 0,fr=t=>t.kty==="oct"&&typeof t.k=="string";function gr(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 yr(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 O(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}async function wr(t,e,r){if(e instanceof Uint8Array){if(!t.startsWith("HS"))throw new TypeError(ht(e,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",e,{hash:`SHA-${t.slice(-3)}`,name:"HMAC"},!1,[r])}return lr(e,t,r),e}async function br(t,e,r){let n=await wr(t,e,"sign");gr(t,n);let i=await crypto.subtle.sign(yr(t,n.algorithm),n,r);return new Uint8Array(i)}var re='Invalid or unsupported JWK "alg" (Algorithm) Parameter value';function Er(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 O(re)}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 O(re)}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 O(re)}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 O(re)}break}default:throw new O('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:r}}async function vr(t){if(!t.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:e,keyUsages:r}=Er(t),n={...t};return n.kty!=="AKP"&&delete n.alg,delete n.use,crypto.subtle.importKey("jwk",n,e,t.ext??!(t.d||t.priv),t.key_ops??r)}var j="given KeyObject instance cannot be used for this algorithm",V,tt=async(t,e,r,n=!1)=>{V||=new WeakMap;let i=V.get(t);if(i?.[r])return i[r];let s=await vr({...e,alg:r});return n&&Object.freeze(t),i?i[r]=s:V.set(t,{[r]:s}),s},_r=(t,e)=>{V||=new WeakMap;let r=V.get(t);if(r?.[e])return r[e];let n=t.type==="public",i=!!n,s;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(j)}s=t.toCryptoKey(t.asymmetricKeyType,i,n?[]:["deriveBits"])}if(t.asymmetricKeyType==="ed25519"){if(e!=="EdDSA"&&e!=="Ed25519")throw new TypeError(j);s=t.toCryptoKey(t.asymmetricKeyType,i,[n?"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(j);s=t.toCryptoKey(t.asymmetricKeyType,i,[n?"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(j)}if(e.startsWith("RSA-OAEP"))return t.toCryptoKey({name:"RSA-OAEP",hash:o},i,n?["encrypt"]:["decrypt"]);s=t.toCryptoKey({name:e.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:o},i,[n?"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(j);let a={ES256:"P-256",ES384:"P-384",ES512:"P-521"};a[e]&&o===a[e]&&(s=t.toCryptoKey({name:"ECDSA",namedCurve:o},i,[n?"verify":"sign"])),e.startsWith("ECDH-ES")&&(s=t.toCryptoKey({name:"ECDH",namedCurve:o},i,n?[]:["deriveBits"]))}if(!s)throw new TypeError(j);return r?r[e]=s:V.set(t,{[e]:s}),s};async function Ar(t,e){if(t instanceof Uint8Array||_e(t))return t;if(Ae(t)){if(t.type==="secret")return t.export();if("toCryptoKey"in t&&typeof t.toCryptoKey=="function")try{return _r(t,e)}catch(n){if(n instanceof TypeError)throw n}let r=t.export({format:"jwk"});return tt(t,r,e)}if(ke(t))return t.k?sr(t.k):tt(t,t,e,!0);throw new Error("unreachable")}var kr=(t,e)=>{let r=(t.match(/.{1,64}/g)||[]).join(`
|
|
30
30
|
`);return`-----BEGIN ${e}-----
|
|
31
31
|
${r}
|
|
32
|
-
-----END ${e}-----`},ht=async(t,e,r)=>{if(_e(r)){if(r.type!==t)throw new TypeError(`key is not a ${t} key`);return r.export({format:"pem",type:e})}if(!Ae(r))throw new TypeError(ct(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 vr(st(new Uint8Array(await crypto.subtle.exportKey(e,r))),`${t.toUpperCase()} KEY`)},Ar=t=>ht("public","spki",t),_r=t=>ht("private","pkcs8",t),ge=(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},kr=t=>({data:t,pos:0}),X=t=>{let e=t.data[t.pos++];if(e&128){let r=e&127,n=0;for(let i=0;i<r;i++)n=n<<8|t.data[t.pos++];return n}return e},Q=(t,e,r)=>{if(t.data[t.pos++]!==e)throw new Error(r)},pt=(t,e)=>{let r=t.data.subarray(t.pos,t.pos+e);return t.pos+=e,r},Sr=t=>{Q(t,6,"Expected algorithm OID");let e=X(t);return pt(t,e)};function Cr(t){Q(t,48,"Invalid PKCS#8 structure"),X(t),Q(t,2,"Expected version field");let e=X(t);t.pos+=e,Q(t,48,"Expected algorithm identifier");let r=X(t);return{algIdStart:t.pos,algIdLength:r}}var Tr=t=>{let e=Sr(t);if(ge(e,[43,101,110]))return"X25519";if(!ge(e,[42,134,72,206,61,2,1]))throw new Error("Unsupported key algorithm");Q(t,6,"Expected curve OID");let r=X(t),n=pt(t,r);for(let{name:i,oid:s}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(ge(n,s))return i;throw new Error("Unsupported named curve")},$r=async(t,e,r,n)=>{let i,s,o=t==="spki",a=()=>o?["verify"]:["sign"],c=()=>o?["encrypt","wrapKey"]:["decrypt","unwrapKey"];switch(r){case"PS256":case"PS384":case"PS512":i={name:"RSA-PSS",hash:`SHA-${r.slice(-3)}`},s=a();break;case"RS256":case"RS384":case"RS512":i={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${r.slice(-3)}`},s=a();break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":i={name:"RSA-OAEP",hash:`SHA-${parseInt(r.slice(-3),10)||1}`},s=c();break;case"ES256":case"ES384":case"ES512":{i={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[r]},s=a();break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{try{let l=n.getNamedCurve(e);i=l==="X25519"?{name:"X25519"}:{name:"ECDH",namedCurve:l}}catch{throw new O("Invalid or unsupported key format")}s=o?[]:["deriveBits"];break}case"Ed25519":case"EdDSA":i={name:"Ed25519"},s=a();break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":i={name:r},s=a();break;default:throw new O('Invalid or unsupported "alg" (Algorithm) value')}return crypto.subtle.importKey(t,e,i,n?.extractable??!!o,s)},Or=(t,e)=>ot(t.replace(e,"")),Pr=(t,e,r)=>{let n=Or(t,/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g),i=r;return e?.startsWith?.("ECDH-ES")&&(i||={},i.getNamedCurve=s=>{let o=kr(s);return Cr(o),Tr(o)}),$r("pkcs8",n,e,i)};async function mt(t,e,r){if(typeof t!="string"||t.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return Pr(t,e,r)}async function Rr(t){return Ar(t)}async function xr(t){return _r(t)}function Ir(t,e,r,n,i){if(i.crit!==void 0&&n?.crit===void 0)throw new t('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.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 s;r!==void 0?s=new Map([...Object.entries(r),...e.entries()]):s=e;for(let o of n.crit){if(!s.has(o))throw new O(`Extension Header Parameter "${o}" is not recognized`);if(i[o]===void 0)throw new t(`Extension Header Parameter "${o}" is missing`);if(s.get(o)&&n[o]===void 0)throw new t(`Extension Header Parameter "${o}" MUST be integrity protected`)}return new Set(n.crit)}var j=t=>t?.[Symbol.toStringTag],be=(t,e,r)=>{if(e.use!==void 0){let n;switch(r){case"sign":case"verify":n="sig";break;case"encrypt":case"decrypt":n="enc";break}if(e.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" 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 n;switch(!0){case(r==="sign"||r==="verify"):case t==="dir":case t.includes("CBC-HS"):n=r;break;case t.startsWith("PBES2"):n="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(t):!t.includes("GCM")&&t.endsWith("KW")?n=r==="encrypt"?"wrapKey":"unwrapKey":n=r;break;case(r==="encrypt"&&t.startsWith("RSA")):n="wrapKey";break;case r==="decrypt":n=t.startsWith("RSA")?"unwrapKey":"deriveBits";break}if(n&&e.key_ops?.includes?.(n)===!1)throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}return!0},Dr=(t,e,r)=>{if(!(e instanceof Uint8Array)){if(ke(e)){if(hr(e)&&be(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(!ut(e))throw new TypeError(lt(t,e,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(e.type!=="secret")throw new TypeError(`${j(e)} instances for symmetric algorithms must be of type "secret"`)}},Ur=(t,e,r)=>{if(ke(e))switch(r){case"decrypt":case"sign":if(ur(e)&&be(t,e,r))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if(dr(e)&&be(t,e,r))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!ut(e))throw new TypeError(lt(t,e,"CryptoKey","KeyObject","JSON Web Key"));if(e.type==="secret")throw new TypeError(`${j(e)} instances for asymmetric algorithms must not be of type "secret"`);if(e.type==="public")switch(r){case"sign":throw new TypeError(`${j(e)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${j(e)} instances for asymmetric algorithm decryption must be of type "private"`)}if(e.type==="private")switch(r){case"verify":throw new TypeError(`${j(e)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${j(e)} instances for asymmetric algorithm encryption must be of type "public"`)}};function Hr(t,e,r){switch(t.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":Dr(t,e,r);break;default:Ur(t,e,r)}}var N=t=>Math.floor(t.getTime()/1e3),ft=60,gt=ft*60,Se=gt*24,Nr=Se*7,Lr=Se*365.25,Kr=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function ye(t){let e=Kr.exec(t);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");let r=parseFloat(e[2]),n=e[3].toLowerCase(),i;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":i=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":i=Math.round(r*ft);break;case"hour":case"hours":case"hr":case"hrs":case"h":i=Math.round(r*gt);break;case"day":case"days":case"d":i=Math.round(r*Se);break;case"week":case"weeks":case"w":i=Math.round(r*Nr);break;default:i=Math.round(r*Lr);break}return e[1]==="-"||e[4]==="ago"?-i:i}function L(t,e){if(!Number.isFinite(e))throw new TypeError(`Invalid ${t} input`);return e}var Wr=class{#e;constructor(t){if(!dt(t))throw new TypeError("JWT Claims Set MUST be an object");this.#e=structuredClone(t)}data(){return it.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=L("setNotBefore",t):t instanceof Date?this.#e.nbf=L("setNotBefore",N(t)):this.#e.nbf=N(new Date)+ye(t)}set exp(t){typeof t=="number"?this.#e.exp=L("setExpirationTime",t):t instanceof Date?this.#e.exp=L("setExpirationTime",N(t)):this.#e.exp=N(new Date)+ye(t)}set iat(t){t===void 0?this.#e.iat=N(new Date):t instanceof Date?this.#e.iat=L("setIssuedAt",N(t)):typeof t=="string"?this.#e.iat=L("setIssuedAt",N(new Date)+ye(t)):this.#e.iat=L("setIssuedAt",t)}},yt=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 Xe(this.#t,"setProtectedHeader"),this.#t=t,this}setUnprotectedHeader(t){return Xe(this.#r,"setUnprotectedHeader"),this.#r=t,this}async sign(t,e){if(!this.#t&&!this.#r)throw new J("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!lr(this.#t,this.#r))throw new J("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let r={...this.#t,...this.#r},n=Ir(J,new Map([["b64",!0]]),e?.crit,this.#t,r),i=!0;if(n.has("b64")&&(i=this.#t.b64,typeof i!="boolean"))throw new J('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:s}=r;if(typeof s!="string"||!s)throw new J('JWS "alg" (Algorithm) Header Parameter missing or invalid');Hr(s,t,"sign");let o,a;i?(o=me(this.#e),a=pe(o)):(a=this.#e,o="");let c,l;this.#t?(c=me(JSON.stringify(this.#t)),l=pe(c)):(c="",l=new Uint8Array);let u=tr(l,pe("."),a),d=await Er(t,s),h=await gr(s,d,u),w={signature:me(h),payload:o};return this.#r&&(w.header=this.#r),this.#t&&(w.protected=c),w}},jr=class{#e;constructor(t){this.#e=new yt(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}`}},Mr=class{#e;#t;constructor(t={}){this.#t=new Wr(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 jr(this.#t.data());if(r.setProtectedHeader(this.#e),Array.isArray(this.#e?.crit)&&this.#e.crit.includes("b64")&&this.#e.b64===!1)throw new ar("JWTs MUST NOT use unencoded payload");return r.sign(t,e)}};function we(t){let e=t?.modulusLength??2048;if(typeof e!="number"||e<2048)throw new O("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return e}async function Vr(t,e){let r,n;switch(t){case"PS256":case"PS384":case"PS512":r={name:"RSA-PSS",hash:`SHA-${t.slice(-3)}`,publicExponent:Uint8Array.of(1,0,1),modulusLength:we(e)},n=["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:we(e)},n=["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:we(e)},n=["decrypt","unwrapKey","encrypt","wrapKey"];break;case"ES256":r={name:"ECDSA",namedCurve:"P-256"},n=["sign","verify"];break;case"ES384":r={name:"ECDSA",namedCurve:"P-384"},n=["sign","verify"];break;case"ES512":r={name:"ECDSA",namedCurve:"P-521"},n=["sign","verify"];break;case"Ed25519":case"EdDSA":{n=["sign","verify"],r={name:"Ed25519"};break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{n=["sign","verify"],r={name:t};break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{n=["deriveBits"];let i=e?.crv??"P-256";switch(i){case"P-256":case"P-384":case"P-521":{r={name:"ECDH",namedCurve:i};break}case"X25519":r={name:"X25519"};break;default:throw new O("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519")}break}default:throw new O('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return crypto.subtle.generateKey(r,e?.extractable??!1,n)}var Gr="https://id.botparty.club",Jr="EdDSA",Yr=15,zr=6e4,Xr="5m",Qr=3,Zr=["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"],en=["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"],S=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}},Ce=class extends S{constructor(t){super({code:"NAMESPACE_LOCKED",message:t.message,statusCode:423,actionUrl:t.actionUrl,details:{lockedAt:t.lockedAt,reason:t.reason}}),this.name="NamespaceLockedError"}},se=class extends S{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}},Z=class extends S{missingScopes;constructor(t){super({code:"INSUFFICIENT_PERMISSION",message:t.message,statusCode:403,actionUrl:t.actionUrl}),this.name="InsufficientPermissionError",this.missingScopes=t.missingScopes}},oe=class extends S{constructor(t){super({code:"LINK_REQUIRED",message:t.message,statusCode:403,actionUrl:t.actionUrl}),this.name="LinkRequiredError"}};function Ze(t){let e=Et(4);return t[e.readUInt32BE(0)%t.length]}function tn(){return`${Ze(Zr)}-${Ze(en)}`}function rn(){let t=tn(),e=Et(2).toString("hex");return`${t}-${e}`}function nn(){return V(Br(),".botparty")}function vt(t){ie(t)||Fr(t,{recursive:!0,mode:448})}function sn(t){let e=V(t,"identity.json");if(!ie(e))return null;try{return JSON.parse(wt(e,"utf-8"))}catch{return null}}function At(t,e){vt(t);let r=V(t,"identity.json");bt(r,JSON.stringify(e,null,2),{mode:384})}function on(t){let e=V(t,"private.pem");if(!ie(e))return null;try{return wt(e,"utf-8")}catch{return null}}function _t(t,e){vt(t);let r=V(t,"private.pem");bt(r,e,{mode:384})}function et(t){for(let e of["identity.json","private.pem"]){let r=V(t,e);ie(r)&&qr(r)}}async function kt(t){let e={extractable:!0};t==="EdDSA"&&(e.crv="Ed25519");let{privateKey:r,publicKey:n}=await Vr(t,e),i=await xr(r),s=await Rr(n);return{privateKey:r,publicKey:n,privatePem:i,publicPem:s}}async function an(t,e,r){let n=await mt(e,r);return(await new yt(new TextEncoder().encode(t)).setProtectedHeader({alg:r}).sign(n)).signature}async function Ee(t,e,r,n,i){let s=n,o=await mt(r,s);return new Mr({...i}).setProtectedHeader({alg:s,kid:e}).setIssuer(t).setSubject(t).setIssuedAt().setExpirationTime(Xr).sign(o)}async function I(t,e,r={}){let{token:n,...i}=r,s=new Headers(i.headers);return s.set("Content-Type","application/json"),n&&s.set("Authorization",`Bearer ${n}`),fetch(`${t}${e}`,{...i,headers:s})}function tt(t,e){try{let r=new URL(t),n=new URL(e);return r.hostname===n.hostname&&r.port===n.port&&r.protocol===n.protocol?t:`${e}/${r.hostname}${r.pathname}${r.search}`}catch{return`${e}/${t}`}}async function ne(t){try{return await t.clone().json()}catch{return null}}function z(t){let e=t.error,r,n,i,s={};if(typeof e=="object"&&e!==null){let o=e;r=o.code||"UNKNOWN",n=o.message||t.message||"Request failed",i=o.actionUrl||t.actionUrl||o.payTo||t.payTo,s=o}else r=(typeof e=="string"?e:t.code)||"UNKNOWN",n=t.message||(typeof e=="string"?e:"Request failed"),i=t.actionUrl||t.payTo,s=t;return{code:r.toUpperCase(),message:n,actionUrl:i,extra:s}}var cn=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)}},ln=class{constructor(t){this.client=t}async list(){let t=await this.client.generateToken(),e=await I(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 S({code:"KEY_NOT_FOUND",message:`Key ${t} not found`,statusCode:404});return e}async add(t){let e=await this.client.generateToken(),r=await I(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(),n=await I(this.client.serverUrl,`/api/v1/namespaces/keys/${t}`,{method:"PATCH",token:r,body:JSON.stringify(e)});if(!n.ok)throw await this.client._apiError(n);return n.json()}async delete(t){let e=await this.client.generateToken(),r=await I(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 n=t||e.keyId;if(n!==e.keyId)throw new S({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 i=await kt(e.algorithm),s=await Ee(e.namespace,e.keyId,r,e.algorithm),o=await I(e.serverUrl,`/api/v1/namespaces/keys/${n}/rotate`,{method:"POST",token:s,body:JSON.stringify({newPublicKey:i.publicPem})});if(!o.ok)throw await this.client._apiError(o);let a=await o.json();return _t(this.client.stateDir,i.privatePem),At(this.client.stateDir,{...e,rotatedAt:a.rotatedAt}),a}async rotateCurrent(){return this.rotate()}async invalidate(t,e){let r=await this.client.generateToken(),n=await I(this.client.serverUrl,`/api/v1/namespaces/keys/${t}/invalidate`,{method:"POST",token:r,body:JSON.stringify({reason:e})});if(!n.ok)throw await this.client._apiError(n)}},St=class{serverUrl;stateDir;proxyUrl;keys;algorithm;rotationTTL;inviteToken;constructor(t={}){this.serverUrl=(t.serverUrl||Y("BOTPARTY_SERVER_URL")||Gr).replace(/\/$/,""),this.proxyUrl=(t.proxyUrl||Y("BOTPARTY_PROXY_URL")||Y("KEYCHAINS_PROXY_URL")||"https://keychains.dev").replace(/\/$/,""),this.stateDir=t.stateDir||Y("BOTPARTY_STATE_DIR")||nn(),this.algorithm=t.algorithm||Jr,this.rotationTTL=t.rotationTTL||Yr,this.inviteToken=t.inviteToken||Y("BOTPARTY_INVITE_TOKEN"),this.keys=new ln(this)}getIdentity(){return sn(this.stateDir)}getPrivateKey(){return on(this.stateDir)}isRegistered(){return this.getIdentity()!==null&&this.getPrivateKey()!==null}async register(t,e,r){let n=t,i=0,s=r?.inviteToken||this.inviteToken;for(;i<Qr;){n||(n=rn());let o=e||n,a=await kt(this.algorithm),c=await I(this.serverUrl,"/api/v1/namespaces/register",{method:"POST",body:JSON.stringify({namespace:n,publicKey:a.publicPem,rotationTTL:this.rotationTTL,...s&&{inviteToken:s}})}),l=await c.json();if(l.status==="already_registered")throw new S({code:"ALREADY_REGISTERED",message:`Namespace "${n}" is already registered`,statusCode:409});if(c.status===409&&!t){n=void 0,i++;continue}if(!c.ok)throw new S({code:l.error||"REGISTRATION_FAILED",message:l.message||l.error||"Registration failed",statusCode:c.status});let u=l.challenge,d=await an(u,a.privatePem,this.algorithm),h=await I(this.serverUrl,"/api/v1/namespaces/register/verify",{method:"POST",body:JSON.stringify({namespace:n,challenge:u,signature:d})});if(!h.ok)throw await this._apiError(h);let w=await h.json();return _t(this.stateDir,a.privatePem),At(this.stateDir,{serverUrl:this.serverUrl,namespace:n,keyId:w.keyId,algorithm:this.algorithm,rotatedAt:w.rotatedAt,rotationTTL:w.rotationTTL,label:o,...w.parentNamespace&&{parentNamespace:w.parentNamespace},...w.inheritedScopes&&{inheritedScopes:w.inheritedScopes}}),w}throw new S({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(){let t=this.getIdentity();if(!t)throw new Error("Not registered");let e=new Date(t.rotatedAt).getTime()+t.rotationTTL*6e4;Date.now()>=e-zr&&await this.keys.rotateCurrent()}async generateToken(t){await this.ensureRegistered(),await this.ensureFreshKey();let e=this.getIdentity(),r=this.getPrivateKey();return Ee(e.namespace,e.keyId,r,e.algorithm,t)}async fetch(t,e={}){let r=await this.generateToken(),n=tt(t,this.proxyUrl),i=new Headers(e.headers);i.set("X-Proxy-Authorization",`Bearer ${r}`);let s=await fetch(n,{...e,headers:i});if(s.status===401){let o=await ne(s);if(o){let{code:a}=z(o);if(a==="KEY_STALE"){await this.keys.rotateCurrent();let c=await this.generateToken(),l=new Headers(e.headers);l.set("X-Proxy-Authorization",`Bearer ${c}`),s=await fetch(n,{...e,headers:l})}}}if(s.status===403){let o=await ne(s);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=tt(t,u),h=new Headers(e.headers);return h.set("X-Proxy-Authorization",`Bearer ${r}`),fetch(d,{...e,headers:h})}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 Z({message:o.message||"Missing required credentials",actionUrl:c,missingScopes:d}):new oe({message:o.message||"Missing required credentials",actionUrl:c})}let{code:l}=z(o);rt(l)&&nt(s.status,o,this.getIdentity(),this.serverUrl)}}if([401,402,423].includes(s.status)){let o=await ne(s);if(o){let{code:a}=z(o);(rt(a)||s.status===402||s.status===423)&&nt(s.status,o,this.getIdentity(),this.serverUrl)}}return s}async info(t){let e=t||this.getIdentity()?.namespace;if(!e)throw new Error("Not registered and no namespace provided");let r=await I(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 I(this.serverUrl,"/api/v1/namespaces",{method:"DELETE",token:t});if(!e.ok&&e.status!==204)throw await this._apiError(e);et(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 Ee(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 cn(this,t)}reset(){et(this.stateDir)}async _apiError(t){let e=await ne(t);if(!e)return new S({code:"UNKNOWN",message:`Request failed with status ${t.status}`,statusCode:t.status});let{code:r,message:n,actionUrl:i}=z(e);return new S({code:r,message:n,statusCode:t.status,actionUrl:i})}},un=new Set(["NAMESPACE_LOCKED","LOCKUP_TRIGGERED","PAYMENT_REQUIRED","LINK_REQUIRED","INSUFFICIENT_SCOPE","PERMISSION_DENIED","KEY_STALE","KEY_EXPIRED"]);function rt(t){return un.has(t.toUpperCase())}function nt(t,e,r,n){let{code:i,message:s,actionUrl:o,extra:a}=z(e),c=r?.namespace||"",l=r?.serverUrl||n;throw i==="NAMESPACE_LOCKED"||i==="LOCKUP_TRIGGERED"||t===423?new Ce({message:s||"Namespace is locked",actionUrl:o||`${l}/namespaces/${c}/unlock`,lockedAt:a.lockedAt,reason:a.reason}):i==="PAYMENT_REQUIRED"||t===402?new se({message:s,actionUrl:o,amount:a.amount||e.amount,service:a.service||e.service}):i==="LINK_REQUIRED"?new oe({message:s,actionUrl:o||`${l}/namespaces/${c}/link`}):i==="INSUFFICIENT_SCOPE"||i==="PERMISSION_DENIED"||t===403?new Z({message:s,actionUrl:o,missingScopes:a.missingScopes||a.missing_scopes}):new S({code:i,message:s,statusCode:t,actionUrl:o})}function Y(t){if(typeof process<"u"&&process.env)return process.env[t]}import{writeFileSync as Wt}from"fs";import{readFileSync as ue}from"fs";import{basename as xn}from"path";var Lt=er(Nt(),1),{program:ji,createCommand:Mi,createArgument:Vi,createOption:Fi,CommanderError:qi,InvalidArgumentError:Bi,InvalidOptionArgumentError:Gi,Command:Kt,Argument:Ji,Option:Yi,Help:zi}=Lt.default;var Cn="\x1B[1m",Tn="\x1B[2m",$n="\x1B[31m",On="\x1B[32m",Pn="\x1B[33m",Rn="\x1B[36m",F="\x1B[0m";function m(t){return`${Cn}${t}${F}`}function E(t){return`${Tn}${t}${F}`}function b(t){return`${$n}${t}${F}`}function k(t){return`${On}${t}${F}`}function C(t){return`${Pn}${t}${F}`}function p(t){return`${Rn}${t}${F}`}function Fe(t,e,r,n){let i=(Date.now()-n)/1e3,s=e.headers.get("content-type")||"",o={http_code:e.status,http_connect:0,http_version:"1.1",response_code:e.status,content_type:s,size_download:r,size_header:0,size_request:0,size_upload:0,speed_download:i>0?Math.round(r/i):0,speed_upload:0,time_appconnect:i,time_connect:i,time_namelookup:0,time_pretransfer:i,time_redirect:0,time_starttransfer:i,time_total:i,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,`
|
|
33
|
-
`),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
|
|
34
|
-
`)}function
|
|
35
|
-
`)}function
|
|
36
|
-
`)}function
|
|
37
|
-
`)}function
|
|
38
|
-
`);let u=
|
|
39
|
-
`)}if(e.dumpHeader){let l=
|
|
40
|
-
`),e.writeOut&&process.stdout.write(
|
|
41
|
-
`),e.writeOut&&process.stdout.write(
|
|
32
|
+
-----END ${e}-----`},gt=async(t,e,r)=>{if(Ae(r)){if(r.type!==t)throw new TypeError(`key is not a ${t} key`);return r.export({format:"pem",type:e})}if(!_e(r))throw new TypeError(ht(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 kr(lt(new Uint8Array(await crypto.subtle.exportKey(e,r))),`${t.toUpperCase()} KEY`)},Sr=t=>gt("public","spki",t),Cr=t=>gt("private","pkcs8",t),ge=(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},Tr=t=>({data:t,pos:0}),X=t=>{let e=t.data[t.pos++];if(e&128){let r=e&127,n=0;for(let i=0;i<r;i++)n=n<<8|t.data[t.pos++];return n}return e},Q=(t,e,r)=>{if(t.data[t.pos++]!==e)throw new Error(r)},yt=(t,e)=>{let r=t.data.subarray(t.pos,t.pos+e);return t.pos+=e,r},$r=t=>{Q(t,6,"Expected algorithm OID");let e=X(t);return yt(t,e)};function Or(t){Q(t,48,"Invalid PKCS#8 structure"),X(t),Q(t,2,"Expected version field");let e=X(t);t.pos+=e,Q(t,48,"Expected algorithm identifier");let r=X(t);return{algIdStart:t.pos,algIdLength:r}}var Pr=t=>{let e=$r(t);if(ge(e,[43,101,110]))return"X25519";if(!ge(e,[42,134,72,206,61,2,1]))throw new Error("Unsupported key algorithm");Q(t,6,"Expected curve OID");let r=X(t),n=yt(t,r);for(let{name:i,oid:s}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(ge(n,s))return i;throw new Error("Unsupported named curve")},Rr=async(t,e,r,n)=>{let i,s,o=t==="spki",a=()=>o?["verify"]:["sign"],c=()=>o?["encrypt","wrapKey"]:["decrypt","unwrapKey"];switch(r){case"PS256":case"PS384":case"PS512":i={name:"RSA-PSS",hash:`SHA-${r.slice(-3)}`},s=a();break;case"RS256":case"RS384":case"RS512":i={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${r.slice(-3)}`},s=a();break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":i={name:"RSA-OAEP",hash:`SHA-${parseInt(r.slice(-3),10)||1}`},s=c();break;case"ES256":case"ES384":case"ES512":{i={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[r]},s=a();break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{try{let l=n.getNamedCurve(e);i=l==="X25519"?{name:"X25519"}:{name:"ECDH",namedCurve:l}}catch{throw new O("Invalid or unsupported key format")}s=o?[]:["deriveBits"];break}case"Ed25519":case"EdDSA":i={name:"Ed25519"},s=a();break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":i={name:r},s=a();break;default:throw new O('Invalid or unsupported "alg" (Algorithm) value')}return crypto.subtle.importKey(t,e,i,n?.extractable??!!o,s)},xr=(t,e)=>ut(t.replace(e,"")),Ir=(t,e,r)=>{let n=xr(t,/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g),i=r;return e?.startsWith?.("ECDH-ES")&&(i||={},i.getNamedCurve=s=>{let o=Tr(s);return Or(o),Pr(o)}),Rr("pkcs8",n,e,i)};async function wt(t,e,r){if(typeof t!="string"||t.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return Ir(t,e,r)}async function Dr(t){return Sr(t)}async function Ur(t){return Cr(t)}function Hr(t,e,r,n,i){if(i.crit!==void 0&&n?.crit===void 0)throw new t('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.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 s;r!==void 0?s=new Map([...Object.entries(r),...e.entries()]):s=e;for(let o of n.crit){if(!s.has(o))throw new O(`Extension Header Parameter "${o}" is not recognized`);if(i[o]===void 0)throw new t(`Extension Header Parameter "${o}" is missing`);if(s.get(o)&&n[o]===void 0)throw new t(`Extension Header Parameter "${o}" MUST be integrity protected`)}return new Set(n.crit)}var M=t=>t?.[Symbol.toStringTag],be=(t,e,r)=>{if(e.use!==void 0){let n;switch(r){case"sign":case"verify":n="sig";break;case"encrypt":case"decrypt":n="enc";break}if(e.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" 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 n;switch(!0){case(r==="sign"||r==="verify"):case t==="dir":case t.includes("CBC-HS"):n=r;break;case t.startsWith("PBES2"):n="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(t):!t.includes("GCM")&&t.endsWith("KW")?n=r==="encrypt"?"wrapKey":"unwrapKey":n=r;break;case(r==="encrypt"&&t.startsWith("RSA")):n="wrapKey";break;case r==="decrypt":n=t.startsWith("RSA")?"unwrapKey":"deriveBits";break}if(n&&e.key_ops?.includes?.(n)===!1)throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}return!0},Nr=(t,e,r)=>{if(!(e instanceof Uint8Array)){if(ke(e)){if(fr(e)&&be(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(!mt(e))throw new TypeError(pt(t,e,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(e.type!=="secret")throw new TypeError(`${M(e)} instances for symmetric algorithms must be of type "secret"`)}},Lr=(t,e,r)=>{if(ke(e))switch(r){case"decrypt":case"sign":if(pr(e)&&be(t,e,r))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if(mr(e)&&be(t,e,r))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!mt(e))throw new TypeError(pt(t,e,"CryptoKey","KeyObject","JSON Web Key"));if(e.type==="secret")throw new TypeError(`${M(e)} instances for asymmetric algorithms must not be of type "secret"`);if(e.type==="public")switch(r){case"sign":throw new TypeError(`${M(e)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${M(e)} instances for asymmetric algorithm decryption must be of type "private"`)}if(e.type==="private")switch(r){case"verify":throw new TypeError(`${M(e)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${M(e)} instances for asymmetric algorithm encryption must be of type "public"`)}};function Kr(t,e,r){switch(t.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":Nr(t,e,r);break;default:Lr(t,e,r)}}var L=t=>Math.floor(t.getTime()/1e3),bt=60,Et=bt*60,Se=Et*24,Wr=Se*7,jr=Se*365.25,Mr=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function ye(t){let e=Mr.exec(t);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");let r=parseFloat(e[2]),n=e[3].toLowerCase(),i;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":i=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":i=Math.round(r*bt);break;case"hour":case"hours":case"hr":case"hrs":case"h":i=Math.round(r*Et);break;case"day":case"days":case"d":i=Math.round(r*Se);break;case"week":case"weeks":case"w":i=Math.round(r*Wr);break;default:i=Math.round(r*jr);break}return e[1]==="-"||e[4]==="ago"?-i:i}function K(t,e){if(!Number.isFinite(e))throw new TypeError(`Invalid ${t} input`);return e}var Vr=class{#e;constructor(t){if(!ft(t))throw new TypeError("JWT Claims Set MUST be an object");this.#e=structuredClone(t)}data(){return ct.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=K("setNotBefore",t):t instanceof Date?this.#e.nbf=K("setNotBefore",L(t)):this.#e.nbf=L(new Date)+ye(t)}set exp(t){typeof t=="number"?this.#e.exp=K("setExpirationTime",t):t instanceof Date?this.#e.exp=K("setExpirationTime",L(t)):this.#e.exp=L(new Date)+ye(t)}set iat(t){t===void 0?this.#e.iat=L(new Date):t instanceof Date?this.#e.iat=K("setIssuedAt",L(t)):typeof t=="string"?this.#e.iat=K("setIssuedAt",L(new Date)+ye(t)):this.#e.iat=K("setIssuedAt",t)}},vt=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 et(this.#t,"setProtectedHeader"),this.#t=t,this}setUnprotectedHeader(t){return et(this.#r,"setUnprotectedHeader"),this.#r=t,this}async sign(t,e){if(!this.#t&&!this.#r)throw new J("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!hr(this.#t,this.#r))throw new J("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let r={...this.#t,...this.#r},n=Hr(J,new Map([["b64",!0]]),e?.crit,this.#t,r),i=!0;if(n.has("b64")&&(i=this.#t.b64,typeof i!="boolean"))throw new J('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:s}=r;if(typeof s!="string"||!s)throw new J('JWS "alg" (Algorithm) Header Parameter missing or invalid');Kr(s,t,"sign");let o,a;i?(o=me(this.#e),a=pe(o)):(a=this.#e,o="");let c,l;this.#t?(c=me(JSON.stringify(this.#t)),l=pe(c)):(c="",l=new Uint8Array);let u=ir(l,pe("."),a),d=await Ar(t,s),h=await br(s,d,u),w={signature:me(h),payload:o};return this.#r&&(w.header=this.#r),this.#t&&(w.protected=c),w}},Fr=class{#e;constructor(t){this.#e=new vt(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}`}},qr=class{#e;#t;constructor(t={}){this.#t=new Vr(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 Fr(this.#t.data());if(r.setProtectedHeader(this.#e),Array.isArray(this.#e?.crit)&&this.#e.crit.includes("b64")&&this.#e.b64===!1)throw new ur("JWTs MUST NOT use unencoded payload");return r.sign(t,e)}};function we(t){let e=t?.modulusLength??2048;if(typeof e!="number"||e<2048)throw new O("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return e}async function Br(t,e){let r,n;switch(t){case"PS256":case"PS384":case"PS512":r={name:"RSA-PSS",hash:`SHA-${t.slice(-3)}`,publicExponent:Uint8Array.of(1,0,1),modulusLength:we(e)},n=["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:we(e)},n=["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:we(e)},n=["decrypt","unwrapKey","encrypt","wrapKey"];break;case"ES256":r={name:"ECDSA",namedCurve:"P-256"},n=["sign","verify"];break;case"ES384":r={name:"ECDSA",namedCurve:"P-384"},n=["sign","verify"];break;case"ES512":r={name:"ECDSA",namedCurve:"P-521"},n=["sign","verify"];break;case"Ed25519":case"EdDSA":{n=["sign","verify"],r={name:"Ed25519"};break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{n=["sign","verify"],r={name:t};break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{n=["deriveBits"];let i=e?.crv??"P-256";switch(i){case"P-256":case"P-384":case"P-521":{r={name:"ECDH",namedCurve:i};break}case"X25519":r={name:"X25519"};break;default:throw new O("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519")}break}default:throw new O('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return crypto.subtle.generateKey(r,e?.extractable??!1,n)}var zr="https://id.botparty.club",Xr="EdDSA",Qr=15,rt=6e4,Zr=3e4,en="5m",tn=3,rn=["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"],nn=["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"],S=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}},$e=class extends S{constructor(t){super({code:"NAMESPACE_LOCKED",message:t.message,statusCode:423,actionUrl:t.actionUrl,details:{lockedAt:t.lockedAt,reason:t.reason}}),this.name="NamespaceLockedError"}},se=class extends S{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}},Z=class extends S{missingScopes;constructor(t){super({code:"INSUFFICIENT_PERMISSION",message:t.message,statusCode:403,actionUrl:t.actionUrl}),this.name="InsufficientPermissionError",this.missingScopes=t.missingScopes}},oe=class extends S{constructor(t){super({code:"LINK_REQUIRED",message:t.message,statusCode:403,actionUrl:t.actionUrl}),this.name="LinkRequiredError"}};function nt(t){let e=kt(4);return t[e.readUInt32BE(0)%t.length]}function sn(){return`${nt(rn)}-${nt(nn)}`}function on(){let t=sn(),e=kt(2).toString("hex");return`${t}-${e}`}function an(){return H(Yr(),".botparty")}function Oe(t){ie(t)||Gr(t,{recursive:!0,mode:448})}function cn(t){let e=H(t,"identity.json");if(!ie(e))return null;try{return JSON.parse(_t(e,"utf-8"))}catch{return null}}function St(t,e){Oe(t);let r=H(t,"identity.json"),n=r+".tmp";Ce(n,JSON.stringify(e,null,2),{mode:384}),At(n,r)}function ln(t){let e=H(t,"private.pem");if(!ie(e))return null;try{return _t(e,"utf-8")}catch{return null}}function Ct(t,e){Oe(t);let r=H(t,"private.pem"),n=r+".tmp";Ce(n,e,{mode:384}),At(n,r)}function it(t){for(let e of["identity.json","private.pem"]){let r=H(t,e);ie(r)&&Te(r)}}function un(t){let e=H(t,"rotation.lock");Oe(t);for(let r=0;r<2;r++)try{Ce(e,`${process.pid}:${Date.now()}`,{flag:"wx",mode:384});return}catch(n){if(n.code!=="EEXIST")throw n;try{let i=Jr(e);if(Date.now()-i.mtimeMs>Zr){Te(e);continue}}catch{continue}throw n}}function dn(t){try{Te(H(t,"rotation.lock"))}catch{}}async function Tt(t){let e={extractable:!0};t==="EdDSA"&&(e.crv="Ed25519");let{privateKey:r,publicKey:n}=await Br(t,e),i=await Ur(r),s=await Dr(n);return{privateKey:r,publicKey:n,privatePem:i,publicPem:s}}async function hn(t,e,r){let n=await wt(e,r);return(await new vt(new TextEncoder().encode(t)).setProtectedHeader({alg:r}).sign(n)).signature}async function Ee(t,e,r,n,i){let s=n,o=await wt(r,s);return new qr({...i}).setProtectedHeader({alg:s,kid:e}).setIssuer(t).setSubject(t).setIssuedAt().setExpirationTime(en).sign(o)}async function I(t,e,r={}){let{token:n,...i}=r,s=new Headers(i.headers);return s.set("Content-Type","application/json"),n&&s.set("Authorization",`Bearer ${n}`),fetch(`${t}${e}`,{...i,headers:s})}function st(t,e){try{let r=new URL(t),n=new URL(e);return r.hostname===n.hostname&&r.port===n.port&&r.protocol===n.protocol?t:`${e}/${r.hostname}${r.pathname}${r.search}`}catch{return`${e}/${t}`}}async function ne(t){try{return await t.clone().json()}catch{return null}}function z(t){let e=t.error,r,n,i,s={};if(typeof e=="object"&&e!==null){let o=e;r=o.code||"UNKNOWN",n=o.message||t.message||"Request failed",i=o.actionUrl||t.actionUrl||o.payTo||t.payTo,s=o}else r=(typeof e=="string"?e:t.code)||"UNKNOWN",n=t.message||(typeof e=="string"?e:"Request failed"),i=t.actionUrl||t.payTo,s=t;return{code:r.toUpperCase(),message:n,actionUrl:i,extra:s}}var pn=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)}},mn=class{constructor(t){this.client=t}async list(){let t=await this.client.generateToken(),e=await I(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 S({code:"KEY_NOT_FOUND",message:`Key ${t} not found`,statusCode:404});return e}async add(t){let e=await this.client.generateToken(),r=await I(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(),n=await I(this.client.serverUrl,`/api/v1/namespaces/keys/${t}`,{method:"PATCH",token:r,body:JSON.stringify(e)});if(!n.ok)throw await this.client._apiError(n);return n.json()}async delete(t){let e=await this.client.generateToken(),r=await I(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 n=t||e.keyId;if(n!==e.keyId)throw new S({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 i=await Tt(e.algorithm),s=await Ee(e.namespace,e.keyId,r,e.algorithm),o=await I(e.serverUrl,`/api/v1/namespaces/keys/${n}/rotate`,{method:"POST",token:s,body:JSON.stringify({newPublicKey:i.publicPem})});if(!o.ok)throw await this.client._apiError(o);let a=await o.json();return Ct(this.client.stateDir,i.privatePem),St(this.client.stateDir,{...e,rotatedAt:a.rotatedAt}),a}async rotateCurrent(){return this.rotate()}async invalidate(t,e){let r=await this.client.generateToken(),n=await I(this.client.serverUrl,`/api/v1/namespaces/keys/${t}/invalidate`,{method:"POST",token:r,body:JSON.stringify({reason:e})});if(!n.ok)throw await this.client._apiError(n)}},$t=class{serverUrl;stateDir;proxyUrl;keys;algorithm;rotationTTL;inviteToken;_rotationPromise=null;constructor(t={}){this.serverUrl=(t.serverUrl||Y("BOTPARTY_SERVER_URL")||zr).replace(/\/$/,""),this.proxyUrl=(t.proxyUrl||Y("BOTPARTY_PROXY_URL")||Y("KEYCHAINS_PROXY_URL")||"https://keychains.dev").replace(/\/$/,""),this.stateDir=t.stateDir||Y("BOTPARTY_STATE_DIR")||an(),this.algorithm=t.algorithm||Xr,this.rotationTTL=t.rotationTTL||Qr,this.inviteToken=t.inviteToken||Y("BOTPARTY_INVITE_TOKEN"),this.keys=new mn(this)}getIdentity(){return cn(this.stateDir)}getPrivateKey(){return ln(this.stateDir)}isRegistered(){return this.getIdentity()!==null&&this.getPrivateKey()!==null}async register(t,e,r){let n=t,i=0,s=r?.inviteToken||this.inviteToken;for(;i<tn;){n||(n=on());let o=e||n,a=await Tt(this.algorithm),c=await I(this.serverUrl,"/api/v1/namespaces/register",{method:"POST",body:JSON.stringify({namespace:n,publicKey:a.publicPem,rotationTTL:this.rotationTTL,...s&&{inviteToken:s}})}),l=await c.json();if(l.status==="already_registered")throw new S({code:"ALREADY_REGISTERED",message:`Namespace "${n}" is already registered`,statusCode:409});if(c.status===409&&!t){n=void 0,i++;continue}if(!c.ok)throw new S({code:l.error||"REGISTRATION_FAILED",message:l.message||l.error||"Registration failed",statusCode:c.status});let u=l.challenge,d=await hn(u,a.privatePem,this.algorithm),h=await I(this.serverUrl,"/api/v1/namespaces/register/verify",{method:"POST",body:JSON.stringify({namespace:n,challenge:u,signature:d})});if(!h.ok)throw await this._apiError(h);let w=await h.json();return Ct(this.stateDir,a.privatePem),St(this.stateDir,{serverUrl:this.serverUrl,namespace:n,keyId:w.keyId,algorithm:this.algorithm,rotatedAt:w.rotatedAt,rotationTTL:w.rotationTTL,label:o,...w.parentNamespace&&{parentNamespace:w.parentNamespace},...w.inheritedScopes&&{inheritedScopes:w.inheritedScopes}}),w}throw new S({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-rt)return this._rotationPromise=this._lockedRotate().finally(()=>{this._rotationPromise=null}),this._rotationPromise}async _lockedRotate(){un(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-rt)return;await this.keys.rotateCurrent()}finally{dn(this.stateDir)}}async generateToken(t){await this.ensureRegistered(),await this.ensureFreshKey();let e=this.getIdentity(),r=this.getPrivateKey();return Ee(e.namespace,e.keyId,r,e.algorithm,t)}async fetch(t,e={}){let r=await this.generateToken(),n=st(t,this.proxyUrl),i=new Headers(e.headers);i.set("X-Proxy-Authorization",`Bearer ${r}`);let s=await fetch(n,{...e,headers:i});if(s.status===401){let o=await ne(s);if(o){let{code:a}=z(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}`),s=await fetch(n,{...e,headers:l})}}}if(s.status===403){let o=await ne(s);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=st(t,u),h=new Headers(e.headers);return h.set("X-Proxy-Authorization",`Bearer ${r}`),fetch(d,{...e,headers:h})}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 Z({message:o.message||"Missing required credentials",actionUrl:c,missingScopes:d}):new oe({message:o.message||"Missing required credentials",actionUrl:c})}let{code:l}=z(o);ot(l)&&at(s.status,o,this.getIdentity(),this.serverUrl)}}if([401,402,423].includes(s.status)){let o=await ne(s);if(o){let{code:a}=z(o);(ot(a)||s.status===402||s.status===423)&&at(s.status,o,this.getIdentity(),this.serverUrl)}}return s}async info(t){let e=t||this.getIdentity()?.namespace;if(!e)throw new Error("Not registered and no namespace provided");let r=await I(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 I(this.serverUrl,"/api/v1/namespaces",{method:"DELETE",token:t});if(!e.ok&&e.status!==204)throw await this._apiError(e);it(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 Ee(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 pn(this,t)}reset(){it(this.stateDir)}async _apiError(t){let e=await ne(t);if(!e)return new S({code:"UNKNOWN",message:`Request failed with status ${t.status}`,statusCode:t.status});let{code:r,message:n,actionUrl:i}=z(e);return new S({code:r,message:n,statusCode:t.status,actionUrl:i})}},fn=new Set(["NAMESPACE_LOCKED","LOCKUP_TRIGGERED","PAYMENT_REQUIRED","LINK_REQUIRED","INSUFFICIENT_SCOPE","PERMISSION_DENIED","KEY_STALE","KEY_EXPIRED"]);function ot(t){return fn.has(t.toUpperCase())}function at(t,e,r,n){let{code:i,message:s,actionUrl:o,extra:a}=z(e),c=r?.namespace||"",l=r?.serverUrl||n;throw i==="NAMESPACE_LOCKED"||i==="LOCKUP_TRIGGERED"||t===423?new $e({message:s||"Namespace is locked",actionUrl:o||`${l}/namespaces/${c}/unlock`,lockedAt:a.lockedAt,reason:a.reason}):i==="PAYMENT_REQUIRED"||t===402?new se({message:s,actionUrl:o,amount:a.amount||e.amount,service:a.service||e.service}):i==="LINK_REQUIRED"?new oe({message:s,actionUrl:o||`${l}/namespaces/${c}/link`}):i==="INSUFFICIENT_SCOPE"||i==="PERMISSION_DENIED"||t===403?new Z({message:s,actionUrl:o,missingScopes:a.missingScopes||a.missing_scopes}):new S({code:i,message:s,statusCode:t,actionUrl:o})}function Y(t){if(typeof process<"u"&&process.env)return process.env[t]}import{writeFileSync as Vt}from"fs";import{readFileSync as ue}from"fs";import{basename as Nn}from"path";var jt=nr(Wt(),1),{program:Bi,createCommand:Gi,createArgument:Ji,createOption:Yi,CommanderError:zi,InvalidArgumentError:Xi,InvalidOptionArgumentError:Qi,Command:Mt,Argument:Zi,Option:es,Help:ts}=jt.default;var Rn="\x1B[1m",xn="\x1B[2m",In="\x1B[31m",Dn="\x1B[32m",Un="\x1B[33m",Hn="\x1B[36m",F="\x1B[0m";function m(t){return`${Rn}${t}${F}`}function E(t){return`${xn}${t}${F}`}function b(t){return`${In}${t}${F}`}function k(t){return`${Dn}${t}${F}`}function C(t){return`${Un}${t}${F}`}function p(t){return`${Hn}${t}${F}`}function Ge(t,e,r,n){let i=(Date.now()-n)/1e3,s=e.headers.get("content-type")||"",o={http_code:e.status,http_connect:0,http_version:"1.1",response_code:e.status,content_type:s,size_download:r,size_header:0,size_request:0,size_upload:0,speed_download:i>0?Math.round(r/i):0,speed_upload:0,time_appconnect:i,time_connect:i,time_namelookup:0,time_pretransfer:i,time_redirect:0,time_starttransfer:i,time_total:i,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,`
|
|
33
|
+
`),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 Ln(t,e,r){let n=[],i;try{let s=new URL(e);i=s.pathname+s.search}catch{i=e}n.push(`> ${t} ${i} HTTP/1.1`);try{let s=new URL(e);n.push(`> Host: ${s.host}`)}catch{}for(let[s,o]of Object.entries(r))s.toLowerCase()!=="host"&&n.push(`> ${s}: ${o}`);return n.push(">"),n.join(`
|
|
34
|
+
`)}function Kn(t,e,r){let n=[];return n.push(`< HTTP/1.1 ${t} ${e}`),r.forEach((i,s)=>{n.push(`< ${s}: ${i}`)}),n.push("<"),n.join(`
|
|
35
|
+
`)}function Ft(t,e,r){let n=[];return n.push(`HTTP/1.1 ${t} ${e}`),r.forEach((i,s)=>{n.push(`${s}: ${i}`)}),n.push(""),n.join(`
|
|
36
|
+
`)}function Wn(t,e,r){let n=[];return n.push(`HTTP/1.1 ${t} ${e}`),r.forEach((i,s)=>{n.push(`${s}: ${i}`)}),n.push(""),n.join(`
|
|
37
|
+
`)}function jn(t){let e=[];if(t.data)for(let r of t.data)if(r.startsWith("@"))try{e.push(ue(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(ue(r.slice(1),"utf-8"))}catch{e.push(r)}else e.push(r);if(t.dataUrlencode)for(let r of t.dataUrlencode){let n=r.indexOf("=");if(n>0){let i=r.slice(0,n),s=r.slice(n+1);e.push(`${encodeURIComponent(i)}=${encodeURIComponent(s)}`)}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 Mn(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 Gt(t){return!!(t.form&&t.form.length>0||t.formString&&t.formString.length>0)}function Vn(t){return t.request?t.request.toUpperCase():t.head?"HEAD":Mn(t)&&!t.get||Gt(t)?"POST":t.uploadFile?"PUT":"GET"}async function qt(t,e,r,n,i,s){let o=await t.text(),a=Buffer.byteLength(o,"utf-8");if(e.verbose){let l=Ln(r,n,i);process.stderr.write(l+`
|
|
38
|
+
`);let u=Kn(t.status,t.statusText,t.headers);process.stderr.write(u+`
|
|
39
|
+
`)}if(e.dumpHeader){let l=Wn(t.status,t.statusText,t.headers);e.dumpHeader==="-"?process.stdout.write(l):Vt(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}
|
|
40
|
+
`),e.writeOut&&process.stdout.write(Ge(e.writeOut,t,a,s)),process.exit(22)));let c="";e.include&&(c+=Ft(t.status,t.statusText,t.headers)),e.head?!e.include&&!e.verbose&&(c+=Ft(t.status,t.statusText,t.headers)):c+=o,e.output?e.output==="-"?process.stdout.write(c):Vt(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}
|
|
41
|
+
`),e.writeOut&&process.stdout.write(Ge(e.writeOut,t,a,s)),process.exit(22)),e.writeOut&&process.stdout.write(Ge(e.writeOut,t,a,s))}function Bt(t){return t instanceof S&&typeof t.actionUrl=="string"&&!!t.actionUrl}async function Jt(t,e){let r=new Mt;r.exitOverride(),r.name("botparty curl").argument("[url]","URL to request").description("Make a proxied API call (like curl, but through BotParty + Keychains)").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(i,s)=>{let o;try{let a=e(),c=i||s.url;c||(process.stderr.write(`curl: no URL specified!
|
|
42
42
|
curl: try 'botparty curl --help' for more information
|
|
43
|
-
`),process.exit(2));let l={};if(s.header)for(let
|
|
44
|
-
`),process.exit(26)}else
|
|
45
|
-
`),process.exit(26)}d&&!l["Content-Type"]&&!l["content-type"]&&(s.json&&s.json.length>0?l["Content-Type"]="application/json":l["Content-Type"]="application/x-www-form-urlencoded"),o={url:h,method:u,headers:l,body:typeof d=="string"?d:void 0};let w=Date.now(),T=s.retry?parseInt(s.retry,10):0,
|
|
43
|
+
`),process.exit(2));let l={};if(s.header)for(let A of s.header){let R=A.indexOf(":");if(R>0){let $=A.slice(0,R).trim(),te=A.slice(R+1).trim();te===""?delete l[$]:l[$]=te}else A.endsWith(";")&&(l[A.slice(0,-1).trim()]="")}if(s.userAgent&&(l["User-Agent"]=s.userAgent),s.referer&&(l.Referer=s.referer),s.cookie&&(l.Cookie=s.cookie.join("; ")),s.user){let A=Buffer.from(s.user).toString("base64");l.Authorization=`Basic ${A}`}s.compressed&&(l["Accept-Encoding"]="gzip, deflate, br"),s.range&&(l.Range=`bytes=${s.range}`),s.json&&s.json.length>0&&(!l["Content-Type"]&&!l["content-type"]&&(l["Content-Type"]="application/json"),!l.Accept&&!l.accept&&(l.Accept="application/json"));let u=Vn(s),d=jn(s),h=c;if(s.get&&d){let A=h.includes("?")?"&":"?";h=h+A+d,d=void 0}if(!d&&Gt(s)){let A=new FormData,R=($,te)=>{let he=$.indexOf("=");if(he<=0)return;let Xe=$.slice(0,he),B=$.slice(he+1);if(te&&B.startsWith("@"))try{let Yt=ue(B.slice(1)),zt=new Blob([Yt]);A.append(Xe,zt,Nn(B.slice(1)))}catch{process.stderr.write(`curl: (26) Failed to open/read local data from file: ${B.slice(1)}
|
|
44
|
+
`),process.exit(26)}else A.append(Xe,B)};if(s.form)for(let $ of s.form)R($,!0);if(s.formString)for(let $ of s.formString)R($,!1);d=A}if(s.uploadFile&&!d)try{d=ue(s.uploadFile,"utf-8")}catch{process.stderr.write(`curl: (26) Failed to open/read local data from file: ${s.uploadFile}
|
|
45
|
+
`),process.exit(26)}d&&!l["Content-Type"]&&!l["content-type"]&&(s.json&&s.json.length>0?l["Content-Type"]="application/json":l["Content-Type"]="application/x-www-form-urlencoded"),o={url:h,method:u,headers:l,body:typeof d=="string"?d:void 0};let w=Date.now(),T=s.retry?parseInt(s.retry,10):0,ze=s.retryDelay?parseInt(s.retryDelay,10)*1e3:1e3,de=null,q=null;for(let A=0;A<=T;A++)try{if(q=await a.fetch(o.url,{method:o.method,headers:o.headers,body:o.body}),q.status>=500&&A<T){de=new Error(`HTTP ${q.status}`),await new Promise(R=>setTimeout(R,ze));continue}break}catch(R){if(de=R,A<T){await new Promise($=>setTimeout($,ze));continue}throw R}if(!q)throw de;await qt(q,s,o.method,o.url,o.headers,w)}catch(a){if(s.silent&&!s.showError&&process.exit(1),Bt(a)){if(s.waitOnAuthlink){process.stderr.write(`
|
|
46
46
|
`),process.stderr.write(` ${C("Authorization required:")} ${a.message}
|
|
47
47
|
`),process.stderr.write(` ${E("Auth URL:")} ${p(a.actionUrl)}
|
|
48
48
|
`),process.stderr.write(` ${E("Open this link to authorize, then the request will retry.")}
|
|
@@ -53,7 +53,7 @@ curl: try 'botparty curl --help' for more information
|
|
|
53
53
|
|
|
54
54
|
${k("\u2713")} Authorization approved!
|
|
55
55
|
|
|
56
|
-
`),h=!0,await
|
|
56
|
+
`),h=!0,await qt(T,s,o.method,o.url,o.headers,Date.now());return}}catch(w){if(Bt(w))continue;throw w}}h||(process.stderr.write(`
|
|
57
57
|
|
|
58
58
|
${b("Timed out waiting for approval.")}
|
|
59
59
|
|
|
@@ -68,7 +68,7 @@ curl: try 'botparty curl --help' for more information
|
|
|
68
68
|
`),process.stderr.write(` ${p(a.actionUrl)}
|
|
69
69
|
`),process.stderr.write(`
|
|
70
70
|
`)}else process.stderr.write(`curl: (6) ${a instanceof Error?a.message:a}
|
|
71
|
-
`);process.exit(1)}});try{await r.parseAsync(t,{from:"user"})}catch(i){if(i&&typeof i=="object"&&"exitCode"in i){let s=i;process.exit(s.exitCode)}throw i}}var y=!1;function v(t){console.log(JSON.stringify({ok:!0,...t},null,2))}function f(t,e=1){y?console.log(JSON.stringify({ok:!1,error:{message:t}},null,2)):console.error(`${b("error")}: ${t}`),process.exit(e)}function
|
|
71
|
+
`);process.exit(1)}});try{await r.parseAsync(t,{from:"user"})}catch(i){if(i&&typeof i=="object"&&"exitCode"in i){let s=i;process.exit(s.exitCode)}throw i}}var y=!1;function v(t){console.log(JSON.stringify({ok:!0,...t},null,2))}function f(t,e=1){y?console.log(JSON.stringify({ok:!1,error:{message:t}},null,2)):console.error(`${b("error")}: ${t}`),process.exit(e)}function Fn(t){if(y){let e={ok:!1};t instanceof S?e.error={code:t.code,message:t.message,statusCode:t.statusCode,...t.actionUrl&&{actionUrl:t.actionUrl},...t instanceof se&&t.amount&&{amount:t.amount},...t instanceof Z&&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 $e&&(console.error(`
|
|
72
72
|
${b("NAMESPACE LOCKED")}: ${t.message}`),t.actionUrl&&console.error(`
|
|
73
73
|
A human must unlock it at:
|
|
74
74
|
${p(t.actionUrl)}`),process.exit(1)),t instanceof se&&(console.error(`
|
|
@@ -83,25 +83,25 @@ Link a human account at:
|
|
|
83
83
|
${p(t.actionUrl)}`),process.exit(1)),t instanceof S&&(console.error(`
|
|
84
84
|
${b(t.code)}: ${t.message}`),t.actionUrl&&console.error(`
|
|
85
85
|
${p(t.actionUrl)}`),process.exit(1)),t instanceof Error&&(console.error(`
|
|
86
|
-
${b("error")}: ${t.message}`),process.exit(1)),console.error(t),process.exit(1)}var
|
|
86
|
+
${b("error")}: ${t.message}`),process.exit(1)),console.error(t),process.exit(1)}var qn=new Set(["header","H"]);function Bn(t){let e=t.slice(2),r=[],n={},i="help",s="",o=0;e[0]&&!e[0].startsWith("-")&&(i=e[0],o=1,["keys","connections","conn","invites","dependents","deps"].includes(i)&&e[1]&&!e[1].startsWith("-")&&(s=e[1],o=2));function a(c,l){if(qn.has(c)&&typeof l=="string"){let u=n[c];Array.isArray(u)?u.push(l):typeof u=="string"?n[c]=[u,l]:n[c]=[l]}else n[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:i,subcommand:s,positional:r,flags:n}}function _(t){return new $t({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 x(t){return new Date(t).toLocaleString()}function Ye(t){let e=new Date(t).getTime()-Date.now();if(e<=0)return b("expired");let r=Math.floor(e/6e4),n=Math.floor(e%6e4/1e3);return r>0?`${r}m ${n}s`:`${n}s`}async function Gn(t,e){let r=_(t);if(r.isRegistered()){let c=r.whoami();y?v({alreadyRegistered:!0,namespace:c.namespace,keyId:c.keyId,serverUrl:c.serverUrl}):(console.log(`Already registered as ${m(c.namespace)}`),console.log(` Key ID: ${c.keyId}`),console.log(` Server: ${E(c.serverUrl)}`),console.log(`
|
|
87
87
|
Use ${p("botparty reset")} to clear and re-register.`));return}let n=e[0]||(typeof t.namespace=="string"?t.namespace:void 0),i=typeof t.name=="string"?t.name:void 0,s=typeof t.ttl=="string"?parseInt(t.ttl,10):void 0,o=typeof t["invite-token"]=="string"?t["invite-token"]:void 0;s&&(r.rotationTTL=s),y||console.log("Registering namespace...");let a=await r.register(n,i,{inviteToken:o});y?v({namespace:a.namespace,keyId:a.keyId,role:a.role,rotationTTL:a.rotationTTL,...a.parentNamespace&&{parentNamespace:a.parentNamespace},...a.inheritedScopes&&{inheritedScopes:a.inheritedScopes}}):(console.log(`
|
|
88
88
|
${k("Registered!")} ${m(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: ${p(a.parentNamespace)}`),a.inheritedScopes&&console.log(` Inherited: ${a.inheritedScopes.join(", ")}`),console.log(`
|
|
89
|
-
Identity saved to ${E("~/.botparty/")}`))}async function
|
|
89
|
+
Identity saved to ${E("~/.botparty/")}`))}async function Jn(t){let r=_(t).whoami();r||f("Not registered. Run: botparty init"),y?v(r):(console.log(m("Identity")),console.log(` Namespace: ${p(r.namespace)}`),console.log(` Key ID: ${r.keyId}`),console.log(` Algorithm: ${r.algorithm}`),console.log(` Rotation TTL: ${r.rotationTTL} min`),console.log(` Last rotated: ${x(r.rotatedAt)}`),console.log(` Stale at: ${x(r.staleAt)} (${Ye(r.staleAt)})`),r.label&&console.log(` Label: ${r.label}`),console.log(` Server: ${E(r.serverUrl)}`))}async function Yn(t,e){let r=_(t),n=e[0]||r.getIdentity()?.namespace;n||f("Not registered and no namespace provided. Run: botparty init");let i=await r.info(n);y?v(i):(console.log(m("Namespace Info")),console.log(` Namespace: ${p(i.namespace)}`),console.log(` Status: ${i.status==="active"?k(i.status):b(i.status)}`),console.log(` Linked: ${i.linked?k("yes"):C("no")}`),console.log(` Active keys: ${i.activeKeys}`),console.log(` Created: ${x(i.createdAt)}`),i.lockedAt&&console.log(` Locked at: ${b(x(i.lockedAt))}`))}async function zn(t){let e=_(t);e.isRegistered()||f("Not registered. Run: botparty init");let{url:r}=await e.link();y?v({url:r}):(console.log(`Share this link with your human to claim ownership:
|
|
90
90
|
`),console.log(` ${p(r)}`),console.log(`
|
|
91
|
-
${E("The link expires in 5 minutes.")}`))}async function
|
|
92
|
-
`),console.log(`Re-run with ${p("--yes")} to confirm.`);return}await e.destroy(),y?v({namespace:r.namespace,destroyed:!0}):console.log(`${k("Destroyed")} namespace ${m(r.namespace)}`)}async function
|
|
93
|
-
${k("Key rotated")}`),console.log(` ID: ${m(i.id)}`),console.log(` Fingerprint: ${i.fingerprint}`),console.log(` Stale at: ${x(i.staleAt)} (${
|
|
94
|
-
`),console.log(`Re-run with ${p("--yes")} to confirm.`);return}await i.keys.invalidate(r,n),y?v({keyId:r,invalidated:!0,namespaceLocked:!0}):(console.log(`${b("Key invalidated")} \u2014 namespace is now ${b("LOCKED")}.`),console.log("A human must unlock it at the BotParty web UI."))}async function
|
|
95
|
-
Share the token or set ${p("BOTPARTY_INVITE_TOKEN")} env var.`))}async function
|
|
91
|
+
${E("The link expires in 5 minutes.")}`))}async function Xn(t){let e=_(t);e.isRegistered()||f("Not registered.");let r=e.whoami();if(t.yes!==!0&&t.y!==!0){y&&f("--yes flag required to confirm destruction"),console.log(`${b("WARNING")}: This will permanently destroy namespace ${m(r.namespace)}.`),console.log(`All keys, links, and data will be deleted.
|
|
92
|
+
`),console.log(`Re-run with ${p("--yes")} to confirm.`);return}await e.destroy(),y?v({namespace:r.namespace,destroyed:!0}):console.log(`${k("Destroyed")} namespace ${m(r.namespace)}`)}async function Qn(t){_(t).reset(),y?v({reset:!0}):(console.log(`${k("Local state cleared.")} The namespace still exists on the server.`),console.log(`Run ${p("botparty init")} to register a new namespace.`))}async function Zn(t){let r=await _(t).generateToken();y?v({token:r}):console.log(r)}async function ei(t){let e=process.argv.slice(2),r=e.findIndex(i=>i==="curl"||i==="fetch"),n=r>=0?e.slice(r+1):e.slice(1);await Jt(n,()=>_(t))}async function ti(t){let e=_(t),r=await e.keys.list();if(y){v({keys:r});return}if(r.length===0){console.log("No keys found.");return}let n=e.getIdentity();for(let i of r){let s=n&&i.id===n.keyId,o=[];i.isRoot&&o.push(p("root")),s&&o.push(k("current"));let a=new Date(i.staleAt).getTime();Date.now()>a?o.push(b("stale")):o.push(`stale in ${Ye(i.staleAt)}`),console.log(`${m(i.id)} ${o.join(" | ")}`),console.log(` Fingerprint: ${E(i.fingerprint)}`),console.log(` Algorithm: ${i.algorithm}`),console.log(` Role: ${i.role}`),i.label&&console.log(` Label: ${i.label}`),console.log(` Scopes: ${i.scopes.join(", ")}`),console.log(` Rotation TTL: ${i.rotationTTL} min`),console.log(` Last rotated: ${x(i.rotatedAt)}`),i.expiresAt&&console.log(` Expires at: ${x(i.expiresAt)}`),i.lastUsedAt&&console.log(` Last used: ${x(i.lastUsedAt)} from ${i.lastUsedIp}`),console.log("")}}async function ri(t){let e=typeof t.label=="string"?t.label:void 0,r=typeof t.scopes=="string"?t.scopes.split(","):void 0,n=typeof t.ttl=="string"?parseInt(t.ttl,10):void 0,i=typeof t.expires=="string"?t.expires:void 0,s=typeof t["public-key"]=="string"?t["public-key"]:void 0;s||f("--public-key is required (PEM-encoded public key)"),r?.length||f("--scopes is required (comma-separated)"),n||f("--ttl is required (rotation TTL in minutes)");let a=await _(t).keys.add({publicKey:s,label:e,scopes:r,rotationTTL:n,expiresAt:i});y?v(a):(console.log(`${k("Key added")}`),console.log(` ID: ${m(a.id)}`),console.log(` Fingerprint: ${a.fingerprint}`),console.log(` Scopes: ${a.scopes.join(", ")}`),console.log(` Rotation TTL: ${a.rotationTTL} min`))}async function ni(t,e){let r=e[0]||void 0,n=_(t);y||console.log("Rotating key...");let i=await n.keys.rotate(r);y?v(i):(console.log(`
|
|
93
|
+
${k("Key rotated")}`),console.log(` ID: ${m(i.id)}`),console.log(` Fingerprint: ${i.fingerprint}`),console.log(` Stale at: ${x(i.staleAt)} (${Ye(i.staleAt)})`))}async function ii(t,e){let r=e[0];r||f("Usage: botparty keys delete <keyId>");let n=_(t);if(t.yes!==!0&&t.y!==!0){y&&f("--yes flag required to confirm deletion"),console.log(`${C("WARNING")}: This will delete key ${m(r)} and all sub-keys.`),console.log(`Re-run with ${p("--yes")} to confirm.`);return}await n.keys.delete(r),y?v({keyId:r,deleted:!0}):console.log(`${k("Deleted")} key ${m(r)}`)}async function si(t,e){let r=e[0];r||f("Usage: botparty keys invalidate <keyId>");let n=typeof t.reason=="string"?t.reason:void 0,i=_(t);if(t.yes!==!0&&t.y!==!0){y&&f("--yes flag required to confirm invalidation"),console.log(`${b("DANGER")}: This will invalidate key ${m(r)} and ${b("LOCK THE ENTIRE NAMESPACE")}.`),console.log(`All JWTs will be rejected until a human unlocks it.
|
|
94
|
+
`),console.log(`Re-run with ${p("--yes")} to confirm.`);return}await i.keys.invalidate(r,n),y?v({keyId:r,invalidated:!0,namespaceLocked:!0}):(console.log(`${b("Key invalidated")} \u2014 namespace is now ${b("LOCKED")}.`),console.log("A human must unlock it at the BotParty web UI."))}async function oi(t){let e=_(t);e.isRegistered()||f("Not registered. Run: botparty init");let r=await e.generateToken(),n=typeof t.scopes=="string"?t.scopes.split(","):void 0,i=typeof t.expires=="string"?t.expires:void 0,s=await fetch(`${e.serverUrl}/api/v1/namespaces/invites`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({scopes:n,expiresIn:i})});if(!s.ok){let a=await s.json().catch(()=>({error:s.statusText}));f(a.error||`HTTP ${s.status}`)}let o=await s.json();y?v(o):(console.log(`${k("Invite created")}`),console.log(` Token ID: ${m(o.tokenId)}`),console.log(` Token: ${o.inviteToken}`),console.log(`
|
|
95
|
+
Share the token or set ${p("BOTPARTY_INVITE_TOKEN")} env var.`))}async function ai(t){let e=_(t);e.isRegistered()||f("Not registered. Run: botparty init");let r=await e.generateToken(),n=typeof t.status=="string"?`?status=${t.status}`:"",i=await fetch(`${e.serverUrl}/api/v1/namespaces/invites${n}`,{headers:{Authorization:`Bearer ${r}`}});if(!i.ok){let o=await i.json().catch(()=>({error:i.statusText}));f(o.error||`HTTP ${i.status}`)}let{invites:s}=await i.json();if(y){v({invites:s});return}if(s.length===0){console.log(E("No invites found."));return}console.log(`
|
|
96
96
|
${m("Invites")} (${s.length})
|
|
97
|
-
`);for(let o of s){let a=o.status==="active"?k(o.status):o.status==="pending"?C(o.status):b(o.status);console.log(` ${m(o.tokenId)} ${a}`),console.log(` Scopes: ${o.scopes.join(", ")}`),o.childNamespace&&console.log(` Child: ${p(o.childNamespace)}`),console.log(` Created: ${x(o.createdAt)}`),console.log("")}}async function
|
|
97
|
+
`);for(let o of s){let a=o.status==="active"?k(o.status):o.status==="pending"?C(o.status):b(o.status);console.log(` ${m(o.tokenId)} ${a}`),console.log(` Scopes: ${o.scopes.join(", ")}`),o.childNamespace&&console.log(` Child: ${p(o.childNamespace)}`),console.log(` Created: ${x(o.createdAt)}`),console.log("")}}async function ci(t){let e=_(t);e.isRegistered()||f("Not registered. Run: botparty init");let r=await e.generateToken(),n=await fetch(`${e.serverUrl}/api/v1/namespaces/dependents`,{headers:{Authorization:`Bearer ${r}`}});if(!n.ok){let s=await n.json().catch(()=>({error:n.statusText}));f(s.error||`HTTP ${n.status}`)}let{dependents:i}=await n.json();if(y){v({dependents:i});return}if(i.length===0){console.log(E("No dependents found."));return}console.log(`
|
|
98
98
|
${m("Dependents")} (${i.length})
|
|
99
|
-
`);for(let s of i){let o=s.status==="active"?k(s.status):s.status==="pending"?C(s.status):b(s.status);console.log(` ${m(s.tokenId)} ${o}`),s.childNamespace&&console.log(` Namespace: ${p(s.childNamespace)}`),console.log(` Scopes: ${s.scopes.join(", ")}`),console.log(` Created: ${x(s.createdAt)}`),s.revokedAt&&console.log(` Revoked: ${b(x(s.revokedAt))}`),console.log("")}}async function
|
|
100
|
-
Re-run with ${p("--yes")} to confirm.`);return}let i=await n.generateToken(),s=await fetch(`${n.serverUrl}/api/v1/namespaces/dependents?tokenId=${encodeURIComponent(r)}`,{method:"DELETE",headers:{Authorization:`Bearer ${i}`}});if(!s.ok){let a=await s.json().catch(()=>({error:s.statusText}));f(a.error||`HTTP ${s.status}`)}let o=await s.json();y?v({revoked:!0,tokenId:r,childNamespace:o.childNamespace}):(console.log(`${k("Revoked")} token ${m(r)}`),o.childNamespace&&console.log(` Child namespace ${m(o.childNamespace)} is now ${b("LOCKED")}.`))}async function
|
|
99
|
+
`);for(let s of i){let o=s.status==="active"?k(s.status):s.status==="pending"?C(s.status):b(s.status);console.log(` ${m(s.tokenId)} ${o}`),s.childNamespace&&console.log(` Namespace: ${p(s.childNamespace)}`),console.log(` Scopes: ${s.scopes.join(", ")}`),console.log(` Created: ${x(s.createdAt)}`),s.revokedAt&&console.log(` Revoked: ${b(x(s.revokedAt))}`),console.log("")}}async function li(t,e){let r=e[0];r||f("Usage: botparty dependents revoke <tokenId>");let n=_(t);if(n.isRegistered()||f("Not registered. Run: botparty init"),t.yes!==!0&&t.y!==!0){y&&f("--yes flag required to confirm revocation"),console.log(`${C("WARNING")}: This will revoke access for the child namespace linked to token ${m(r)}.`),console.log(`The child namespace will be ${b("LOCKED")}.`),console.log(`
|
|
100
|
+
Re-run with ${p("--yes")} to confirm.`);return}let i=await n.generateToken(),s=await fetch(`${n.serverUrl}/api/v1/namespaces/dependents?tokenId=${encodeURIComponent(r)}`,{method:"DELETE",headers:{Authorization:`Bearer ${i}`}});if(!s.ok){let a=await s.json().catch(()=>({error:s.statusText}));f(a.error||`HTTP ${s.status}`)}let o=await s.json();y?v({revoked:!0,tokenId:r,childNamespace:o.childNamespace}):(console.log(`${k("Revoked")} token ${m(r)}`),o.childNamespace&&console.log(` Child namespace ${m(o.childNamespace)} is now ${b("LOCKED")}.`))}async function Je(t,e,r){let n=await e.generateToken(),i=new Headers(r?.headers);return i.set("Authorization",`Bearer ${n}`),fetch(`${e.proxyUrl}${t}`,{...r,headers:i})}async function ui(t){let e=_(t),r=new URLSearchParams;typeof t.provider=="string"&&r.set("provider",t.provider),typeof t.status=="string"&&r.set("status",t.status);let n=r.toString(),i=await Je(`/api/botparty/connections${n?`?${n}`:""}`,e);if(!i.ok){let a=await i.json().catch(()=>({error:i.statusText}));f(a.error||`HTTP ${i.status}`)}let o=(await i.json()).connections;if(y){v({connections:o});return}if(o.length===0){console.log(E("No connections found."));return}console.log(`
|
|
101
101
|
${m("Connections")} (${o.length})
|
|
102
|
-
`);for(let a of o){let c=a.status==="active"?k("active"):C(a.status),l=a.type==="api_key"?E("[api_key]"):E("[oauth]"),u=a.accountLabel&&a.accountLabel!=="default"?E(` (${a.accountLabel})`):"",d=a.accountIdentifier?E(` \u2014 ${a.accountIdentifier}`):"";console.log(` ${m(a.displayName||a.provider)} ${l} ${c}${u}${d}`),console.log(` ${E("id:")} ${a.id}`),a.keyNames?.length&&console.log(` ${E("keys:")} ${a.keyNames.join(", ")}`),a.scopes?.length&&console.log(` ${E("scopes:")} ${a.scopes.join(", ")}`)}console.log("")}function
|
|
102
|
+
`);for(let a of o){let c=a.status==="active"?k("active"):C(a.status),l=a.type==="api_key"?E("[api_key]"):E("[oauth]"),u=a.accountLabel&&a.accountLabel!=="default"?E(` (${a.accountLabel})`):"",d=a.accountIdentifier?E(` \u2014 ${a.accountIdentifier}`):"";console.log(` ${m(a.displayName||a.provider)} ${l} ${c}${u}${d}`),console.log(` ${E("id:")} ${a.id}`),a.keyNames?.length&&console.log(` ${E("keys:")} ${a.keyNames.join(", ")}`),a.scopes?.length&&console.log(` ${E("scopes:")} ${a.scopes.join(", ")}`)}console.log("")}function di(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 n=t.domain?.toLowerCase().replace(/\.(com|io|dev|org|net|ai|club)$/,"");return!!(n&&n===r)}async function hi(t,e){let r=e[0];r||f("Usage: botparty connections delete <name|provider|id> [--yes]");let n=_(t),i=await Je("/api/botparty/connections",n);if(!i.ok){let l=await i.json().catch(()=>({error:i.statusText}));f(l.error||`HTTP ${i.status}`)}let{connections:s}=await i.json(),o=s.filter(l=>di(l,r));if(o.length===0&&f(`No connection found matching "${r}". Run: botparty connections list`),o.length>1){console.error(`${C("Multiple connections match")} "${r}":
|
|
103
103
|
`);for(let l of o){let u=l.accountLabel&&l.accountLabel!=="default"?E(` (${l.accountLabel})`):"";console.error(` ${m(l.displayName||l.provider)}${u} ${E(l.id)}`)}console.error(`
|
|
104
|
-
Specify the exact connection ID to delete.`),process.exit(1)}let a=o[0];t.yes!==!0&&t.y!==!0&&f(`This will permanently delete ${m(a.displayName||a.provider)} (${a.id}). Pass --yes to confirm.`);let c=await
|
|
104
|
+
Specify the exact connection ID to delete.`),process.exit(1)}let a=o[0];t.yes!==!0&&t.y!==!0&&f(`This will permanently delete ${m(a.displayName||a.provider)} (${a.id}). Pass --yes to confirm.`);let c=await Je(`/api/botparty/connections?id=${encodeURIComponent(a.id)}`,n,{method:"DELETE"});if(!c.ok){let l=await c.json().catch(()=>({error:c.statusText}));f(l.error||`HTTP ${c.status}`)}y?v({deleted:!0,connectionId:a.id,provider:a.provider}):console.log(`${k("Deleted")} ${m(a.displayName||a.provider)} (${a.id})`)}function pi(){console.log(`
|
|
105
105
|
${m("botparty")} \u2014 federated bot identity, authentication, and payments
|
|
106
106
|
|
|
107
107
|
${m("USAGE")}
|
|
@@ -173,4 +173,4 @@ ${m("EXAMPLES")}
|
|
|
173
173
|
botparty connections list # Show credential connections
|
|
174
174
|
botparty connections delete <id> --yes # Remove a connection
|
|
175
175
|
botparty link # Get link URL for human
|
|
176
|
-
`)}async function
|
|
176
|
+
`)}async function mi(){let{command:t,subcommand:e,positional:r,flags:n}=Bn(process.argv);if(n.json===!0&&(y=!0),n.version===!0||n.v===!0&&t!=="curl"&&t!=="fetch"||t==="version"){y?v({version:"0.0.1"}):console.log("botparty 0.0.1");return}if((n.help===!0||n.h===!0||t==="help")&&t!=="curl"&&t!=="fetch"){pi();return}try{switch(t){case"init":case"join":await Gn(n,r);break;case"whoami":await Jn(n);break;case"info":await Yn(n,r);break;case"link":await zn(n);break;case"destroy":await Xn(n);break;case"reset":await Qn(n);break;case"token":await Zn(n);break;case"curl":case"fetch":await ei(n);break;case"keys":switch(e){case"list":case"ls":await ti(n);break;case"add":await ri(n);break;case"rotate":await ni(n,r);break;case"delete":case"rm":await ii(n,r);break;case"invalidate":case"panic":await si(n,r);break;default:f(`Unknown keys subcommand: ${e||"(none)"}. Run: botparty keys list`)}break;case"invites":switch(e){case"create":await oi(n);break;case"list":case"ls":case"":await ai(n);break;default:f(`Unknown invites subcommand: ${e}. Try: botparty invites list`)}break;case"dependents":case"deps":switch(e){case"list":case"ls":case"":await ci(n);break;case"revoke":await li(n,r);break;default:f(`Unknown dependents subcommand: ${e}. Try: botparty dependents list`)}break;case"connections":case"conn":switch(e){case"list":case"ls":case"":await ui(n);break;case"delete":case"rm":await hi(n,r);break;default:f(`Unknown connections subcommand: ${e}. Run: botparty connections list`)}break;default:f(`Unknown command: ${t}. Run: botparty --help`)}}catch(i){Fn(i)}}mi();
|