engagelab-email-cli 1.0.0 → 1.0.1
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.cjs +13 -13
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var Yt=Object.create;var Ue=Object.defineProperty;var Xt=Object.getOwnPropertyDescriptor;var Zt=Object.getOwnPropertyNames;var Qt=Object.getPrototypeOf,er=Object.prototype.hasOwnProperty;var
|
|
3
|
-
`).replace(/^/gm," ".repeat(n))}let c=[`Usage: ${t.commandUsage(e)}`,""],l=t.commandDescription(e);l.length>0&&(c=c.concat([t.wrap(l,s,0),""]));let h=t.visibleArguments(e).map(f=>u(t.argumentTerm(f),t.argumentDescription(f)));h.length>0&&(c=c.concat(["Arguments:",a(h),""]));let d=t.visibleOptions(e).map(f=>u(t.optionTerm(f),t.optionDescription(f)));if(d.length>0&&(c=c.concat(["Options:",a(d),""])),this.showGlobalOptions){let f=t.visibleGlobalOptions(e).map(
|
|
2
|
+
var Yt=Object.create;var Ue=Object.defineProperty;var Xt=Object.getOwnPropertyDescriptor;var Zt=Object.getOwnPropertyNames;var Qt=Object.getPrototypeOf,er=Object.prototype.hasOwnProperty;var k=(r,e)=>()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}};var tr=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Zt(e))!er.call(r,s)&&s!==t&&Ue(r,s,{get:()=>e[s],enumerable:!(i=Xt(e,s))||i.enumerable});return r};var de=(r,e,t)=>(t=r!=null?Yt(Qt(r)):{},tr(e||!r||!r.__esModule?Ue(t,"default",{value:r,enumerable:!0}):t,r));var D=k(me=>{var Q=class extends Error{constructor(e,t,i){super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},fe=class extends Q{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};me.CommanderError=Q;me.InvalidArgumentError=fe});var ee=k(ge=>{var{InvalidArgumentError:rr}=D(),pe=class{constructor(e,t){switch(this.description=t||"",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.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,i)=>{if(!this.argChoices.includes(t))throw new rr(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,i):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function ir(r){let e=r.name()+(r.variadic===!0?"...":"");return r.required?"<"+e+">":"["+e+"]"}ge.Argument=pe;ge.humanReadableArgName=ir});var be=k(Je=>{var{humanReadableArgName:sr}=ee(),ye=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let t=e.commands.filter(s=>!s._hidden),i=e._getHelpCommand();return i&&!i._hidden&&t.push(i),this.sortSubcommands&&t.sort((s,n)=>s.name().localeCompare(n.name())),t}compareOptions(e,t){let i=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return i(e).localeCompare(i(t))}visibleOptions(e){let t=e.options.filter(s=>!s.hidden),i=e._getHelpOption();if(i&&!i.hidden){let s=i.short&&e._findOption(i.short),n=i.long&&e._findOption(i.long);!s&&!n?t.push(i):i.long&&!n?t.push(e.createOption(i.long,i.description)):i.short&&!s&&t.push(e.createOption(i.short,i.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let i=e.parent;i;i=i.parent){let s=i.options.filter(n=>!n.hidden);t.push(...s)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(i=>sr(i)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((i,s)=>Math.max(i,t.subcommandTerm(s).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((i,s)=>Math.max(i,t.optionTerm(s).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((i,s)=>Math.max(i,t.optionTerm(s).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((i,s)=>Math.max(i,t.argumentTerm(s).length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let i="";for(let s=e.parent;s;s=s.parent)i=s.name()+" "+i;return i+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let i=`(${t.join(", ")})`;return e.description?`${e.description} ${i}`:i}return e.description}formatHelp(e,t){let i=t.padWidth(e,t),s=t.helpWidth||80,n=2,o=2;function u(f,R){if(R){let he=`${f.padEnd(i+o)}${R}`;return t.wrap(he,s-n,i+o)}return f}function a(f){return f.join(`
|
|
3
|
+
`).replace(/^/gm," ".repeat(n))}let c=[`Usage: ${t.commandUsage(e)}`,""],l=t.commandDescription(e);l.length>0&&(c=c.concat([t.wrap(l,s,0),""]));let h=t.visibleArguments(e).map(f=>u(t.argumentTerm(f),t.argumentDescription(f)));h.length>0&&(c=c.concat(["Arguments:",a(h),""]));let d=t.visibleOptions(e).map(f=>u(t.optionTerm(f),t.optionDescription(f)));if(d.length>0&&(c=c.concat(["Options:",a(d),""])),this.showGlobalOptions){let f=t.visibleGlobalOptions(e).map(R=>u(t.optionTerm(R),t.optionDescription(R)));f.length>0&&(c=c.concat(["Global Options:",a(f),""]))}let g=t.visibleCommands(e).map(f=>u(t.subcommandTerm(f),t.subcommandDescription(f)));return g.length>0&&(c=c.concat(["Commands:",a(g),""])),c.join(`
|
|
4
4
|
`)}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,i,s=40){let n=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",o=new RegExp(`[\\n][${n}]+`);if(e.match(o))return e;let u=t-i;if(u<s)return e;let a=e.slice(0,i),c=e.slice(i).replace(`\r
|
|
5
5
|
`,`
|
|
6
6
|
`),l=" ".repeat(i),d="\\s\u200B",g=new RegExp(`
|
|
7
|
-
|.{1,${u-1}}([${d}]|$)|[^${d}]+?([${d}]|$)`,"g"),f=c.match(g)||[];return a+f.map((
|
|
8
|
-
`?"":(he>0?l:"")+
|
|
9
|
-
`)}};Je.Help=ye});var xe
|
|
7
|
+
|.{1,${u-1}}([${d}]|$)|[^${d}]+?([${d}]|$)`,"g"),f=c.match(g)||[];return a+f.map((R,he)=>R===`
|
|
8
|
+
`?"":(he>0?l:"")+R.trimEnd()).join(`
|
|
9
|
+
`)}};Je.Help=ye});var xe=k(Oe=>{var{InvalidArgumentError:nr}=D(),we=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let i=ar(e);this.short=i.shortFlag,this.long=i.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}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),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}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,i)=>{if(!this.argChoices.includes(t))throw new nr(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,i):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return or(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},_e=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,i)=>{this.positiveOptions.has(i)&&this.dualOptions.add(i)})}valueFromOption(e,t){let i=t.attributeName();if(!this.dualOptions.has(i))return!0;let s=this.negativeOptions.get(i).presetArg,n=s!==void 0?s:!1;return t.negate===(n===e)}};function or(r){return r.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function ar(r){let e,t,i=r.split(/[ |,]+/);return i.length>1&&!/^[[<]/.test(i[1])&&(e=i.shift()),t=i.shift(),!e&&/^-[^-]$/.test(t)&&(e=t,t=void 0),{shortFlag:e,longFlag:t}}Oe.Option=we;Oe.DualOptions=_e});var Be=k(We=>{function ur(r,e){if(Math.abs(r.length-e.length)>3)return Math.max(r.length,e.length);let t=[];for(let i=0;i<=r.length;i++)t[i]=[i];for(let i=0;i<=e.length;i++)t[0][i]=i;for(let i=1;i<=e.length;i++)for(let s=1;s<=r.length;s++){let n=1;r[s-1]===e[i-1]?n=0:n=1,t[s][i]=Math.min(t[s-1][i]+1,t[s][i-1]+1,t[s-1][i-1]+n),s>1&&i>1&&r[s-1]===e[i-2]&&r[s-2]===e[i-1]&&(t[s][i]=Math.min(t[s][i],t[s-2][i-2]+1))}return t[r.length][e.length]}function cr(r,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=r.startsWith("--");t&&(r=r.slice(2),e=e.map(o=>o.slice(2)));let i=[],s=3,n=.4;return e.forEach(o=>{if(o.length<=1)return;let u=ur(r,o),a=Math.max(r.length,o.length);(a-u)/a>n&&(u<s?(s=u,i=[o]):u===s&&i.push(o))}),i.sort((o,u)=>o.localeCompare(u)),t&&(i=i.map(o=>`--${o}`)),i.length>1?`
|
|
10
10
|
(Did you mean one of ${i.join(", ")}?)`:i.length===1?`
|
|
11
|
-
(Did you mean ${i[0]}?)`:""}We.suggestSimilar=cr});var Xe
|
|
11
|
+
(Did you mean ${i[0]}?)`:""}We.suggestSimilar=cr});var Xe=k(Ye=>{var lr=require("node:events").EventEmitter,Ee=require("node:child_process"),S=require("node:path"),Ce=require("node:fs"),m=require("node:process"),{Argument:hr,humanReadableArgName:dr}=ee(),{CommanderError:Ae}=D(),{Help:fr}=be(),{Option:Ge,DualOptions:mr}=xe(),{suggestSimilar:ze}=Be(),Se=class r extends lr{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,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._outputConfiguration={writeOut:t=>m.stdout.write(t),writeErr:t=>m.stderr.write(t),getOutHelpWidth:()=>m.stdout.isTTY?m.stdout.columns:void 0,getErrHelpWidth:()=>m.stderr.isTTY?m.stderr.columns:void 0,outputError:(t,i)=>i(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}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 t=this;t;t=t.parent)e.push(t);return e}command(e,t,i){let s=t,n=i;typeof s=="object"&&s!==null&&(n=s,s=null),n=n||{};let[,o,u]=e.match(/([^ ]+) *(.*)/),a=this.createCommand(o);return s&&(a.description(s),a._executableHandler=!0),n.isDefault&&(this._defaultCommandName=a._name),a._hidden=!!(n.noHelp||n.hidden),a._executableFile=n.executableFile||null,u&&a.arguments(u),this._registerCommand(a),a.parent=this,a.copyInheritedSettings(this),s?this:a}createCommand(e){return new r(e)}createHelp(){return Object.assign(new fr,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(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,t){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
|
|
12
12
|
- specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new hr(e,t)}argument(e,t,i,s){let n=this.createArgument(e,t);return typeof i=="function"?n.default(s).argParser(i):n.default(i),this.addArgument(n),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw new Error(`only the last argument can be variadic '${t.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,t){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,i,s]=e.match(/([^ ]+) *(.*)/),n=t??"display help for command",o=this.createCommand(i);return o.helpOption(!1),s&&o.arguments(s),n&&o.description(n),this._addImplicitHelpCommand=!0,this._helpCommand=o,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=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,t){let i=["preSubcommand","preAction","postAction"];if(!i.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
|
|
13
13
|
Expecting one of '${i.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,i){this._exitCallback&&this._exitCallback(new Ae(e,t,i)),m.exit(e)}action(e){let t=i=>{let s=this.registeredArguments.length,n=i.slice(0,s);return this._storeOptionsAsProperties?n[s]=this:n[s]=this.opts(),n.push(this),e.apply(this,n)};return this._actionHandler=t,this}createOption(e,t){return new Ge(e,t)}_callParseArg(e,t,i,s){try{return e.parseArg(t,i)}catch(n){if(n.code==="commander.invalidArgument"){let o=`${s} ${n.message}`;this.error(o,{exitCode:n.exitCode,code:n.code})}throw n}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let i=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 '${i}'
|
|
14
14
|
- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=s=>[s.name()].concat(s.aliases()),i=t(e).find(s=>this._findCommand(s));if(i){let s=t(this._findCommand(i)).join("|"),n=t(e).join("|");throw new Error(`cannot add command '${n}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),i=e.attributeName();if(e.negate){let n=e.long.replace(/^--no-/,"--");this._findOption(n)||this.setOptionValueWithSource(i,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(i,e.defaultValue,"default");let s=(n,o,u)=>{n==null&&e.presetArg!==void 0&&(n=e.presetArg);let a=this.getOptionValue(i);n!==null&&e.parseArg?n=this._callParseArg(e,n,a,o):n!==null&&e.variadic&&(n=e._concatValue(n,a)),n==null&&(e.negate?n=!1:e.isBoolean()||e.optional?n=!0:n=""),this.setOptionValueWithSource(i,n,u)};return this.on("option:"+t,n=>{let o=`error: option '${e.flags}' argument '${n}' is invalid.`;s(n,o,"cli")}),e.envVar&&this.on("optionEnv:"+t,n=>{let o=`error: option '${e.flags}' value '${n}' from env '${e.envVar}' is invalid.`;s(n,o,"env")}),this}_optionEx(e,t,i,s,n){if(typeof t=="object"&&t instanceof Ge)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(t,i);if(o.makeOptionMandatory(!!e.mandatory),typeof s=="function")o.default(n).argParser(s);else if(s instanceof RegExp){let u=s;s=(a,c)=>{let l=u.exec(a);return l?l[0]:c},o.default(n).argParser(s)}else o.default(s);return this.addOption(o)}option(e,t,i,s){return this._optionEx({},e,t,i,s)}requiredOption(e,t,i,s){return this._optionEx({mandatory:!0},e,t,i,s)}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,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,i){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=i,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(i=>{i.getOptionValueSource(e)!==void 0&&(t=i.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){m.versions?.electron&&(t.from="electron");let s=m.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(t.from="eval")}e===void 0&&(e=m.argv),this.rawArgs=e.slice();let i;switch(t.from){case void 0:case"node":this._scriptPath=e[1],i=e.slice(2);break;case"electron":m.defaultApp?(this._scriptPath=e[1],i=e.slice(2)):i=e.slice(1);break;case"user":i=e.slice(0);break;case"eval":i=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",i}parse(e,t){let i=this._prepareUserArgs(e,t);return this._parseCommand([],i),this}async parseAsync(e,t){let i=this._prepareUserArgs(e,t);return await this._parseCommand([],i),this}_executeSubCommand(e,t){t=t.slice();let i=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function n(l,h){let d=S.resolve(l,h);if(Ce.existsSync(d))return d;if(s.includes(S.extname(h)))return;let g=s.find(f=>Ce.existsSync(`${d}${f}`));if(g)return`${d}${g}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,u=this._executableDir||"";if(this._scriptPath){let l;try{l=Ce.realpathSync(this._scriptPath)}catch{l=this._scriptPath}u=S.resolve(S.dirname(l),u)}if(u){let l=n(u,o);if(!l&&!e._executableFile&&this._scriptPath){let h=S.basename(this._scriptPath,S.extname(this._scriptPath));h!==this._name&&(l=n(u,`${h}-${e._name}`))}o=l||o}i=s.includes(S.extname(o));let a;m.platform!=="win32"?i?(t.unshift(o),t=Ke(m.execArgv).concat(t),a=Ee.spawn(m.argv[0],t,{stdio:"inherit"})):a=Ee.spawn(o,t,{stdio:"inherit"}):(t.unshift(o),t=Ke(m.execArgv).concat(t),a=Ee.spawn(m.execPath,t,{stdio:"inherit"})),a.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(h=>{m.on(h,()=>{a.killed===!1&&a.exitCode===null&&a.kill(h)})});let c=this._exitCallback;a.on("close",l=>{l=l??1,c?c(new Ae(l,"commander.executeSubCommandAsync","(close)")):m.exit(l)}),a.on("error",l=>{if(l.code==="ENOENT"){let h=u?`searched for local subcommand relative to directory '${u}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",d=`'${o}' does not exist
|
|
@@ -20,15 +20,15 @@ Expecting one of '${i.join("', '")}'`);return this._lifeCycleHooks[e]?this._life
|
|
|
20
20
|
`),this.outputHelp({error:!0}));let i=t||{},s=i.exitCode||1,n=i.code||"commander.error";this._exit(s,n,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in m.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,m.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new mr(this.options),t=i=>this.getOptionValue(i)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(i));this.options.filter(i=>i.implied!==void 0&&t(i.attributeName())&&e.valueFromOption(this.getOptionValue(i.attributeName()),i)).forEach(i=>{Object.keys(i.implied).filter(s=>!t(s)).forEach(s=>{this.setOptionValueWithSource(s,i.implied[s],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let i=o=>{let u=o.attributeName(),a=this.getOptionValue(u),c=this.options.find(h=>h.negate&&u===h.attributeName()),l=this.options.find(h=>!h.negate&&u===h.attributeName());return c&&(c.presetArg===void 0&&a===!1||c.presetArg!==void 0&&a===c.presetArg)?c:l||o},s=o=>{let u=i(o),a=u.attributeName();return this.getOptionValueSource(a)==="env"?`environment variable '${u.envVar}'`:`option '${u.flags}'`},n=`error: ${s(e)} cannot be used with ${s(t)}`;this.error(n,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let s=[],n=this;do{let o=n.createHelp().visibleOptions(n).filter(u=>u.long).map(u=>u.long);s=s.concat(o),n=n.parent}while(n&&!n._enablePositionalOptions);t=ze(e,s)}let i=`error: unknown option '${e}'${t}`;this.error(i,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,i=t===1?"":"s",n=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${i} but got ${e.length}.`;this.error(n,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(n=>{s.push(n.name()),n.alias()&&s.push(n.alias())}),t=ze(e,s)}let i=`error: unknown command '${e}'${t}`;this.error(i,{code:"commander.unknownCommand"})}version(e,t,i){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",i=i||"output the version number";let s=this.createOption(t,i);return this._versionOptionName=s.attributeName(),this._registerOption(s),this.on("option:"+s.name(),()=>{this._outputConfiguration.writeOut(`${e}
|
|
21
21
|
`),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let i=this.parent?._findCommand(e);if(i){let s=[i.name()].concat(i.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${s}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(i=>dr(i));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=S.basename(e,S.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp();return t.helpWidth===void 0&&(t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),t.formatHelp(this,t)}_getHelpContext(e){e=e||{};let t={error:!!e.error},i;return t.error?i=s=>this._outputConfiguration.writeErr(s):i=s=>this._outputConfiguration.writeOut(s),t.write=e.write||i,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let i=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(n=>n.emit("beforeAllHelp",i)),this.emit("beforeHelp",i);let s=this.helpInformation(i);if(t&&(s=t(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");i.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",i),this._getCommandAndAncestors().forEach(n=>n.emit("afterAllHelp",i))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=m.exitCode||0;t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let i=["beforeAll","before","after","afterAll"];if(!i.includes(e))throw new Error(`Unexpected value for position to addHelpText.
|
|
22
22
|
Expecting one of '${i.join("', '")}'`);let s=`${e}Help`;return this.on(s,n=>{let o;typeof t=="function"?o=t({error:n.error,command:n.command}):o=t,o&&n.write(`${o}
|
|
23
|
-
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(s=>t.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Ke(r){return r.map(e=>{if(!e.startsWith("--inspect"))return e;let t,i="127.0.0.1",s="9229",n;return(n=e.match(/^(--inspect(-brk)?)$/))!==null?t=n[1]:(n=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=n[1],/^\d+$/.test(n[3])?s=n[3]:i=n[3]):(n=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=n[1],i=n[3],s=n[4]),t&&s!=="0"?`${t}=${i}:${parseInt(s)+1}`:e})}Ye.Command=Se});var tt
|
|
24
|
-
`,{encoding:"utf8",mode:384})}function nt(r=process.env,e=process.platform){if(r.ENGAGELAB_EMAIL_CONFIG)return r.ENGAGELAB_EMAIL_CONFIG;let t=r.XDG_CONFIG_HOME||(e==="win32"?r.APPDATA||
|
|
25
|
-
`)}),e.command("list").description("Show local CLI configuration").action(async()=>{let t=await
|
|
23
|
+
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(s=>t.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Ke(r){return r.map(e=>{if(!e.startsWith("--inspect"))return e;let t,i="127.0.0.1",s="9229",n;return(n=e.match(/^(--inspect(-brk)?)$/))!==null?t=n[1]:(n=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=n[1],/^\d+$/.test(n[3])?s=n[3]:i=n[3]):(n=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=n[1],i=n[3],s=n[4]),t&&s!=="0"?`${t}=${i}:${parseInt(s)+1}`:e})}Ye.Command=Se});var tt=k(y=>{var{Argument:Ze}=ee(),{Command:Re}=Xe(),{CommanderError:pr,InvalidArgumentError:Qe}=D(),{Help:gr}=be(),{Option:et}=xe();y.program=new Re;y.createCommand=r=>new Re(r);y.createOption=(r,e)=>new et(r,e);y.createArgument=(r,e)=>new Ze(r,e);y.Command=Re;y.Option=et;y.Argument=Ze;y.Help=gr;y.CommanderError=pr;y.InvalidArgumentError=Qe;y.InvalidOptionArgumentError=Qe});var rt=de(tt(),1),{program:ti,createCommand:ri,createArgument:ii,createOption:si,CommanderError:ni,InvalidArgumentError:oi,InvalidOptionArgumentError:ai,Command:it,Argument:ui,Option:ci,Help:li}=rt.default;var q=require("node:fs/promises"),U=de(require("node:path"),1),Te=de(require("node:os"),1);async function J({configPath:r=nt()}={}){try{return JSON.parse(await(0,q.readFile)(r,"utf8"))}catch(e){if(e.code==="ENOENT")return{};throw e}}async function st(r,{configPath:e=nt()}={}){await(0,q.mkdir)(U.default.dirname(e),{recursive:!0}),await(0,q.writeFile)(e,`${JSON.stringify(r,null,2)}
|
|
24
|
+
`,{encoding:"utf8",mode:384})}function nt(r=process.env,e=process.platform){if(r.ENGAGELAB_EMAIL_CONFIG)return r.ENGAGELAB_EMAIL_CONFIG;let t=r.XDG_CONFIG_HOME||(e==="win32"?r.APPDATA||U.default.join(Te.default.homedir(),"AppData","Roaming"):U.default.join(Te.default.homedir(),".config"));return U.default.join(t,"engagelab-email-cli","config.json")}function ot(r){return r?`${r.slice(0,7)}****`:""}var w=class extends Error{constructor(e,{code:t="cli_error",exitCode:i=1,status:s,data:n,cause:o}={}){super(e,{cause:o}),this.name="CliError",this.code=t,this.exitCode=i,this.status=s,this.data=n}};function ke(r){return r===401||r===403?2:r===404?3:r===409?4:5}function at(r){return r instanceof w?r:new w(r?.message||"Command failed",{code:"unknown_error",exitCode:5,cause:r})}function p(r){return new w(r,{code:"validation_error",exitCode:1})}function te(r){return new w(r,{code:"config_error",exitCode:1})}function ut(r){let e=r.command("config").description("Manage local EngageLab Email CLI config");e.command("set").description("Save local CLI configuration").option("--base-url <url>","EngageLab Email API base URL").option("--secret-key <key>","EngageLab Email Secret Key").action(async(t,i)=>{if(t={...i.optsWithGlobals(),...t},!t.baseUrl&&!t.secretKey)throw p("Provide at least one of --base-url or --secret-key");if(t.secretKey&&!t.secretKey.startsWith("sk_"))throw p("Secret Key must start with sk_");let s=await J();await st({...s,...yr(t)}),process.stdout.write(`Config saved
|
|
25
|
+
`)}),e.command("list").description("Show local CLI configuration").action(async()=>{let t=await J();process.stdout.write(`baseUrl: ${t.baseUrl||""}
|
|
26
26
|
`),process.stdout.write(`secretKey: ${ot(t.secretKey)}
|
|
27
|
-
`)})}function yr(r){return Object.fromEntries(Object.entries(r).filter(([,e])=>e!==void 0))}var ht=require("node:fs/promises");var dt=new Set(["bodyFile","bodyJson"]),ft=[["text","textFile"],["html","htmlFile"]];async function ve(r={},{readFile:e=ht.readFile}={}){if(br(r),r.bodyFile)return ct(await e(r.bodyFile,"utf8"),`Invalid JSON in ${r.bodyFile}`);if(r.bodyJson)return ct(r.bodyJson,"Invalid JSON in --body-json");let t={};for(let[i,s]of Object.entries(r))dt.has(i)||i.endsWith("File")||s===void 0||(t[i]=s);for(let[i,s]of ft)r[s]&&(t[i]=await e(r[s],"utf8"));return t}function br(r){if(r.bodyFile&&r.bodyJson)throw p("--body-file and --body-json are mutually exclusive");if((r.bodyFile||r.bodyJson)&&Object.entries(r).filter(([t,i])=>i!==void 0&&!dt.has(t)).length>0)throw p("--body-file/--body-json cannot be combined with field-level body options");for(let[e,t]of ft)if(r[e]&&r[t])throw p(`--${lt(e)} and --${lt(t)} are mutually exclusive`)}function ct(r,e){try{let t=JSON.parse(r);if(!t||typeof t!="object"||Array.isArray(t))throw new Error("JSON body must be an object");return t}catch(t){throw p(`${e}: ${t.message}`)}}function lt(r){return r.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}function
|
|
28
|
-
`)}function wr(r){return Array.isArray(r)?r.join(", "):r==null?"":String(r)}function pt(r,e){return r.padEnd(e," ")}function gt(r){return{0:"received",1:"parsing",2:"parsed",3:"parse_failed",4:"replied"}[r]??r}function yt(r){return{0:"pending",1:"processing",2:"done",3:"failed"}[r]??r}function bt(r){return
|
|
29
|
-
`)}function _r(r,{httpStatus:e}={}){if(!r||typeof r!="object"||typeof r.code!="number")throw new E("Invalid server response format",{code:"invalid_response",exitCode:5,status:e,data:r});if(r.code!==200)throw new E(r.message||"Request failed",{code:wt(r.code),exitCode:ke(r.code),status:r.code,data:r});return r}async function b(r){let e;try{e=await r.json()}catch(t){throw new E("Invalid server response format",{code:"invalid_response",exitCode:5,status:r.status,cause:t})}if(r.status<200||r.status>=300)throw new E(e?.message||`Request failed with status code ${r.status}`,{code:wt(r.status),exitCode:ke(r.status),status:r.status,data:e});return _r(e,{httpStatus:r.status})}function wt(r){return r===401||r===403?"auth_error":r===404?"not_found":r===409?"state_conflict":r===400?"validation_error":"server_error"}var R=class{constructor(e){this.client=e}listMessages(e={}){return this.client.get("v1/message",{searchParams:e}).then(b)}getMessage(e){return this.client.get(`v1/message/${encodeURIComponent(e)}`).then(b)}listenMessages(e={}){return this.client.get("v1/message/listen",{searchParams:e}).then(b)}ackMessage(e){return this.client.post(`v1/message/${encodeURIComponent(e)}/ack`).then(b)}failMessage(e){return this.client.post(`v1/message/${encodeURIComponent(e)}/fail`).then(b)}replyMessage(e,t){return this.client.post(`v1/message/${encodeURIComponent(e)}/reply`,{json:t}).then(b)}};var ie=class{constructor(e){this.client=e}sendEmail(e){return this.client.post("v1/mail/send",{json:e}).then(b)}};var C=class extends Error{name="KyError";get isKyError(){return!0}};var N=class extends C{name="HTTPError";response;request;options;data;constructor(e,t,i){let s=e.status||e.status===0?e.status:"",n=e.statusText??"",o=`${s} ${n}`.trim(),u=o?`status code ${o}`:"an unknown error";super(`Request failed with ${u}: ${t.method} ${t.url}`),this.response=e,this.request=t,this.options=i}};var M=class extends C{name="NetworkError";request;constructor(e,t){super(`Request failed due to a network error: ${e.method} ${e.url}`,t),this.request=e}};var V=class extends Error{name="NonError";value;constructor(e){let t="Non-error value was thrown";try{typeof e=="string"?t=e:e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"&&(t=e.message)}catch{}super(t),this.value=e}};var j=class extends C{name="ForceRetryError";customDelay;code;customRequest;constructor(e){let t=e?.cause?e.cause instanceof Error?e.cause:new V(e.cause):void 0;super(e?.code?`Forced retry: ${e.code}`:"Forced retry",t?{cause:t}:void 0),this.customDelay=e?.delay,this.code=e?.code,this.customRequest=e?.request}};var se=class extends Error{name="SchemaValidationError";issues;constructor(e){super("Response schema validation failed"),this.issues=e}};var _=class extends C{name="TimeoutError";request;constructor(e){super(`Request timed out: ${e.method} ${e.url}`),this.request=e}};var qe=(()=>{let r=!1,e=!1,t=typeof globalThis.ReadableStream=="function",i=typeof globalThis.Request=="function";if(t&&i)try{e=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return r=!0,"half"}}).headers.has("Content-Type")}catch(s){if(s instanceof Error&&s.message==="unsupported BodyInit type")return!1;throw s}return r&&!e})(),_t=typeof globalThis.AbortController=="function",ne=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",Ot=typeof globalThis.ReadableStream=="function",xt=typeof globalThis.FormData=="function",oe=["get","post","put","patch","head","delete"],Or=()=>{};Or();var Et={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},L=2147483647,Ct=40,ae=Symbol("stop"),z=class{options;constructor(e){this.options=e}},At=r=>new z(r),St={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,baseUrl:!0,prefix:!0,retry:!0,timeout:!0,totalTimeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0,context:!0},Rt={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,duplex:!0};var ue=new TextEncoder,xr=r=>{if(!r)return 0;if(r instanceof FormData){let e=0;for(let[t,i]of r)e+=Ct,e+=ue.encode(`Content-Disposition: form-data; name="${t}"`).byteLength,e+=typeof i=="string"?ue.encode(i).byteLength:i.size;return e}return r instanceof Blob?r.size:r instanceof ArrayBuffer||ArrayBuffer.isView(r)?r.byteLength:typeof r=="string"?ue.encode(r).byteLength:r instanceof URLSearchParams?ue.encode(r.toString()).byteLength:0},Tt=(r,e,t)=>{let i,s=0;return r.pipeThrough(new TransformStream({transform(n,o){if(o.enqueue(n),i){s+=i.byteLength;let u=e===0?0:s/e;u>=1&&(u=1-Number.EPSILON),t?.({percent:u,totalBytes:Math.max(e,s),transferredBytes:s},i)}i=n},flush(){i&&(s+=i.byteLength,t?.({percent:1,totalBytes:Math.max(e,s),transferredBytes:s},i))}}))},kt=(r,e)=>{if(!r.body)return r;let t={status:r.status,statusText:r.statusText,headers:r.headers};if(r.status===204)return new Response(null,t);let i=Math.max(0,Number(r.headers.get("content-length"))||0);return new Response(Tt(r.body,i,e),t)},vt=(r,e,t)=>{if(!r.body)return r;let i=xr(t??r.body);return new Request(r,{duplex:"half",body:Tt(r.body,i,e)})};var A=r=>r!==null&&typeof r=="object";var Er=Symbol("replaceOption"),Pe=r=>A(r)&&r[Er]===!0?{isReplace:!0,value:r.value}:{isReplace:!1,value:r};var Y=(...r)=>{for(let e of r)if((!A(e)||Array.isArray(e))&&e!==void 0)throw new TypeError("The `options` argument must be an object");return Ne({},...r)},Ie=(r={},e={})=>{let t=new globalThis.Headers(r),i=e instanceof globalThis.Headers,s=new globalThis.Headers(e);for(let[n,o]of s.entries())i&&o==="undefined"||o===void 0?t.delete(n):t.set(n,o);return t},He=r=>{if(!A(r)||Array.isArray(r))return!1;let e=Object.getPrototypeOf(r);return e===Object.prototype||e===null},F=r=>{if(r instanceof URLSearchParams){let e=new URLSearchParams(r),t=r[v];return t&&(e[v]=new Set(t)),e}return r instanceof globalThis.Headers?new globalThis.Headers(r):Array.isArray(r)?[...r]:He(r)?{...r}:r},Cr=r=>Object.fromEntries(Object.entries(r).filter(e=>e[1]!==void 0)),Ar=(r,e)=>He(r)&&He(e)?Cr({...r,...e}):Ie(r,e);function K(r,e,t){return Object.hasOwn(e,t)&&e[t]===void 0?[]:Ne(r[t]??[],e[t]??[])}var ce=(r={},e={})=>({init:K(r,e,"init"),beforeRequest:K(r,e,"beforeRequest"),beforeRetry:K(r,e,"beforeRetry"),beforeError:K(r,e,"beforeError"),afterResponse:K(r,e,"afterResponse")}),v=Symbol("deletedParameters"),Sr=(r,e)=>{let t=new URLSearchParams,i=new Set;for(let s of[r,e])if(s!==void 0)if(s instanceof URLSearchParams){for(let[o,u]of s.entries())t.append(o,u),i.delete(o);let n=s[v];if(n)for(let o of n)t.delete(o),i.add(o)}else if(Array.isArray(s))for(let n of s){if(!Array.isArray(n)||n.length!==2)throw new TypeError("Array search parameters must be provided in [[key, value], ...] format");t.append(String(n[0]),String(n[1])),i.delete(String(n[0]))}else if(A(s))for(let[n,o]of Object.entries(s))o===void 0?(t.delete(n),i.add(n)):(t.append(n,String(o)),i.delete(n));else{let n=new URLSearchParams(s);for(let[o,u]of n.entries())t.append(o,u),i.delete(o)}return i.size>0&&(t[v]=i),t},Ne=(...r)=>{let e={},t={},i={},s,n=[];for(let o of r)if(Array.isArray(o))Array.isArray(e)||(e=[]),e=[...e,...o];else if(A(o)){for(let[u,a]of Object.entries(o)){if(u==="signal"&&a instanceof globalThis.AbortSignal){n.push(a);continue}let c=Pe(a),{isReplace:l}=c;if(a=c.value,u==="context"){if(a!=null&&(!A(a)||Array.isArray(a)))throw new TypeError("The `context` option must be an object");e={...e,context:a==null?{}:l?{...a}:{...e.context,...a}};continue}if(u==="searchParams"){a==null?s=void 0:l?s=a:s=s===void 0?a:Sr(s,a);continue}A(a)&&!l&&u in e&&(a=Ne(e[u],a)),e={...e,[u]:a}}if(A(o.hooks)){let{value:u,isReplace:a}=Pe(o.hooks);i=ce(a?{}:i,u),e.hooks=i}if(A(o.headers)){let{value:u,isReplace:a}=Pe(o.headers);t=a?F(u):Ar(t,u),e.headers=t}}return s!==void 0&&(e.searchParams=s),n.length>0&&(n.length===1?e.signal=n[0]:ne?e.signal=AbortSignal.any(n):e.signal=n.at(-1)),e};var jt=r=>oe.includes(r)?r.toUpperCase():r,Rr=["get","put","head","delete","options","trace"],Tr=[408,413,429,500,502,503,504],kr=[413,429,503],$t={limit:2,methods:Rr,statusCodes:Tr,afterStatusCodes:kr,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:r=>.3*2**(r-1)*1e3,jitter:void 0,retryOnTimeout:!1},qt=(r={})=>{if(typeof r=="number")return{...$t,limit:r};if(r.methods&&!Array.isArray(r.methods))throw new Error("retry.methods must be an array");if(r.statusCodes&&!Array.isArray(r.statusCodes))throw new Error("retry.statusCodes must be an array");let e=Object.fromEntries(Object.entries({...r,methods:r.methods?.map(t=>t.toLowerCase())}).filter(([,t])=>t!==void 0));return{...$t,...e}};async function Me(r,e,t,i){return new Promise((s,n)=>{let o=setTimeout(()=>{t&&t.abort(),n(new _(r))},i.timeout);i.fetch(r,e).then(s).catch(n).then(()=>{clearTimeout(o)})})}async function le(r,{signal:e}){return new Promise((t,i)=>{e&&(e.throwIfAborted(),e.addEventListener("abort",s,{once:!0}));function s(){clearTimeout(n),i(e.reason)}let n=setTimeout(()=>{e?.removeEventListener("abort",s),t()},r)})}var Pt=r=>{let e={};for(let t in r)Object.hasOwn(r,t)&&!(t in Rt)&&!(t in St)&&(e[t]=r[t]);return e},Ht=r=>r===void 0?!1:Array.isArray(r)?r.length>0:r instanceof URLSearchParams?r.size>0||!!r[v]?.size:typeof r=="object"?Object.keys(r).length>0:typeof r=="string"?r.trim().length>0:!!r;var vr=Object.prototype.toString,$r=r=>vr.call(r)==="[object Error]",jr=new Set(["network error","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function Ve(r){if(!(r&&$r(r)&&r.name==="TypeError"&&typeof r.message=="string"))return!1;let{message:t,stack:i}=r;return t==="Load failed"?i===void 0||"__sentry_captured__"in r:t.startsWith("error sending request for url")||t==="Failed to fetch"||t.startsWith("Failed to fetch (")&&t.endsWith(")")?!0:jr.has(t)}var Le=(r,e)=>r instanceof e||r?.name===e.name;function It(r){return Le(r,N)}function Nt(r){return Le(r,M)}function Mt(r){return Le(r,_)}var qr=10*1024*1024,Pr="The `prefixUrl` option has been renamed `prefix` in v2 and enhanced to allow slashes in input. See also the new `baseUrl` option for improved flexibility with standard URL resolution: https://github.com/sindresorhus/ky#baseurl",X=Symbol("timedOutResponseData"),Hr=r=>{let e=/;\s*charset\s*=\s*(?:"([^"]+)"|([^;,\s]+))/i.exec(r),t=e?.[1]??e?.[2];if(t)try{return new TextDecoder(t)}catch{}return new TextDecoder},Vt="The `schema` argument must follow the Standard Schema specification",Ir=r=>typeof r!="object"?r:{...r,...r.methods&&{methods:[...r.methods]},...r.statusCodes&&{statusCodes:[...r.statusCodes]},...r.afterStatusCodes&&{afterStatusCodes:[...r.afterStatusCodes]}},Dt=Object.prototype.toString,Lt=r=>r instanceof globalThis.Request||Dt.call(r)==="[object Request]",Z=r=>r instanceof globalThis.Response||Dt.call(r)==="[object Response]",Nr=r=>Array.isArray(r)?r.map(e=>[...e]):F(r);function Mr(r){let e={...r,json:F(r.json),context:F(r.context),headers:F(r.headers),searchParams:Nr(r.searchParams)};return r.retry!==void 0&&(e.retry=Ir(r.retry)),e}var Ft=async(r,e)=>{if(typeof e!="object"&&typeof e!="function"||e===null)throw new TypeError(Vt);let t=e["~standard"];if(typeof t!="object"||t===null||typeof t.validate!="function")throw new TypeError(Vt);let i=await t.validate(r);if(i.issues)throw new se(i.issues);return i.value},Q=class r{static create(e,t){let i=t.hooks?.init??[],s=i.length>0?Mr(t):t;for(let a of i)a(s);let n=new r(e,s),o=async()=>{if(typeof n.#e.timeout=="number"&&n.#e.timeout>L)throw new RangeError(`The \`timeout\` option cannot be greater than ${L}`);if(typeof n.#e.totalTimeout=="number"&&n.#e.totalTimeout>L)throw new RangeError(`The \`totalTimeout\` option cannot be greater than ${L}`);await Promise.resolve();let a=await n.#P(),c=a??await n.#S(async()=>n.#y()),l=a!==void 0||n.#g();for(;;){if(c===void 0)return c;if(Z(c))try{c=await n.#H(c)}catch(d){if(!(d instanceof j))throw d;let g=await n.#p(d,async()=>n.#y());if(g===void 0)return g;c=g,l=n.#g();continue}let h=c;if(!h.ok&&h.type!=="opaque"&&(typeof n.#e.throwHttpErrors=="function"?n.#e.throwHttpErrors(h.status):n.#e.throwHttpErrors)){let d=new N(h,n.#a(h),n.#o()),g=d;if(d.data=await n.#v(h),l)throw g;let f=await n.#p(d,async()=>n.#y());if(f===void 0)return f;c=f,l=n.#g();continue}break}if(!Z(c))return c;if(n.#E(c),n.#e.onDownloadProgress){if(typeof n.#e.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!Ot)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");let h=c.clone();return n.#i(c),kt(h,n.#e.onDownloadProgress)}return c},u=(async()=>{try{return await o()}catch(a){if(!(a instanceof Error)||n.#O.has(a))throw a;let c=a;for(let l of n.#e.hooks.beforeError){let h=await l({request:n.request,options:n.#o(),error:c,retryCount:n.#r});h instanceof Error&&(c=h)}throw c}finally{let a=n.#_;n.#m(a?.body??void 0),n.request!==a&&n.#m(n.request.body??void 0)}})();for(let[a,c]of Object.entries(Et))a==="bytes"&&typeof globalThis.Response?.prototype?.bytes!="function"||(u[a]=async l=>{n.request.headers.set("accept",n.request.headers.get("accept")||c);let h=await u;if(a!=="json")return h[a]();let d=await h.text();if(d==="")return l!==void 0?Ft(void 0,l):JSON.parse(d);let g=s.parseJson?await s.parseJson(d,{request:n.#a(h),response:h}):JSON.parse(d);return l===void 0?g:Ft(g,l)});return u}static#T(e){return e&&typeof e=="object"&&!Array.isArray(e)&&!(e instanceof URLSearchParams)?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0)):e}request;#s;#r=0;#t;#e;#_;#u;#O=new WeakSet;#c;#f;#l=!1;#x=new WeakMap;constructor(e,t={}){if(this.#t=e,Object.hasOwn(t,"prefixUrl"))throw new Error(Pr);if(this.#e={...t,headers:Ie(this.#t.headers,t.headers),hooks:ce({},t.hooks),method:jt(t.method??this.#t.method??"GET"),prefix:String(t.prefix||""),retry:qt(t.retry),throwHttpErrors:t.throwHttpErrors??!0,timeout:t.timeout??1e4,totalTimeout:t.totalTimeout??!1,fetch:t.fetch??globalThis.fetch.bind(globalThis),context:t.context??{}},typeof this.#t!="string"&&!(this.#t instanceof URL||this.#t instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(typeof this.#t=="string"){if(this.#e.prefix){let s=this.#e.prefix.replace(/\/+$/,""),n=this.#t.replace(/^\/+/,"");this.#t=`${s}/${n}`}if(this.#e.baseUrl){let s;try{s=new URL(this.#t)}catch{}s||(this.#t=new URL(this.#t,new Request(this.#e.baseUrl).url))}}_t&&ne&&(this.#u=this.#e.signal??this.#t.signal,this.#s=new globalThis.AbortController,this.#e.signal=this.#A()),qe&&(this.#e.duplex="half"),this.#e.json!==void 0&&(this.#e.body=this.#e.stringifyJson?.(this.#e.json)??JSON.stringify(this.#e.json),this.#e.headers.set("content-type",this.#e.headers.get("content-type")??"application/json"));let i=t.headers&&new globalThis.Headers(t.headers).has("content-type");if(this.#t instanceof globalThis.Request&&(xt&&this.#e.body instanceof globalThis.FormData||this.#e.body instanceof URLSearchParams)&&!i&&this.#e.headers.delete("content-type"),this.request=new globalThis.Request(this.#t,this.#e),Ht(this.#e.searchParams)){let s=new URL(this.request.url),n=this.#e.searchParams?.[v];if(n)for(let o of n)s.searchParams.delete(o);if(typeof this.#e.searchParams=="string"){let o=this.#e.searchParams.replace(/^\?/,"");o!==""&&(s.search=s.search?`${s.search}&${o}`:`?${o}`)}else{let o=new URLSearchParams(r.#T(this.#e.searchParams));for(let[u,a]of o.entries())s.searchParams.append(u,a)}if(this.#e.searchParams&&typeof this.#e.searchParams=="object"&&!Array.isArray(this.#e.searchParams)&&!(this.#e.searchParams instanceof URLSearchParams))for(let[o,u]of Object.entries(this.#e.searchParams))u===void 0&&s.searchParams.delete(o);this.request=new globalThis.Request(s,this.#e)}if(this.#e.onUploadProgress&&typeof this.#e.onUploadProgress!="function")throw new TypeError("The `onUploadProgress` option must be a function");this.#f=typeof this.#e.totalTimeout=="number"?this.#R():void 0}#n(){let e=this.#e.retry.delay(this.#r+1),t=e;return this.#e.retry.jitter===!0?t=Math.random()*e:typeof this.#e.retry.jitter=="function"&&(t=this.#e.retry.jitter(e),(!Number.isFinite(t)||t<0)&&(t=e)),Math.min(this.#e.retry.backoffLimit,t)}async#k(e){if(this.#r>=this.#e.retry.limit)throw e;let t=e instanceof Error?e:new V(e);if(t instanceof j)return t.customDelay??this.#n();if(!this.#e.retry.methods.includes(this.request.method.toLowerCase()))throw e;if(this.#e.retry.shouldRetry!==void 0){let i=await this.#e.retry.shouldRetry({error:t,retryCount:this.#r+1});if(i===!1)throw e;if(i===!0)return this.#n()}if(Mt(e)){if(!this.#e.retry.retryOnTimeout)throw e;return this.#n()}if(It(e)){if(!this.#e.retry.statusCodes.includes(e.response.status))throw e;let i=e.response.headers.get("Retry-After")??e.response.headers.get("RateLimit-Reset")??e.response.headers.get("X-RateLimit-Retry-After")??e.response.headers.get("X-RateLimit-Reset")??e.response.headers.get("X-Rate-Limit-Reset");if(i&&this.#e.retry.afterStatusCodes.includes(e.response.status)){let s=Number(i)*1e3;return Number.isNaN(s)?s=Date.parse(i)-Date.now():s>=Date.parse("2024-01-01")&&(s-=Date.now()),Number.isFinite(s)?(s=Math.max(0,s),Math.min(this.#e.retry.maxRetryAfter,s)):Math.min(this.#e.retry.maxRetryAfter,this.#n())}if(e.response.status===413)throw e;return this.#n()}if(!Nt(e))throw e;return this.#n()}#E(e){let t=this.#a(e);return this.#e.parseJson&&(e.json=async()=>{let i=await e.text();return i===""?JSON.parse(i):this.#e.parseJson(i,{request:t,response:e})}),e}async#v(e){let t=await this.#j(e,this.#C());if(t===X){this.#h();return}if(!t)return;if(!this.#$(e.headers.get("content-type")??""))return t;let i=await this.#q(t,e,this.#C(),this.#a(e));if(i===X){this.#h();return}return i}#C(){let e=this.#e.timeout===!1?1e4:this.#e.timeout,t=this.#d();if(t===void 0)return e;if(t<=0)throw new _(this.request);return Math.min(e,t)}#$(e){let t=(e.split(";",1)[0]??"").trim().toLowerCase();return/\/(?:.*[.+-])?json$/.test(t)}async#j(e,t){let{body:i}=e;if(!i)try{return await e.text()}catch{return}let s;try{s=i.getReader()}catch{return}let n=Hr(e.headers.get("content-type")??""),o=[],u=0,a=(async()=>{try{for(;;){let{done:h,value:d}=await s.read();if(h)break;if(u+=d.byteLength,u>qr){s.cancel().catch(()=>{});return}o.push(n.decode(d,{stream:!0}))}}catch{return}return o.push(n.decode()),o.join("")})(),c=new Promise(h=>{let d=setTimeout(()=>{h(X)},t);a.finally(()=>{clearTimeout(d)})}),l=await Promise.race([a,c]);return l===X&&s.cancel().catch(()=>{}),l}async#q(e,t,i,s){let n;try{return await Promise.race([Promise.resolve().then(()=>this.#e.parseJson?this.#e.parseJson(e,{request:s,response:t}):JSON.parse(e)),new Promise(o=>{n=setTimeout(()=>{o(X)},i)})])}catch{return}finally{clearTimeout(n)}}#m(e){e&&e.cancel().catch(()=>{})}#i(e){this.#m(e.body??void 0)}#A(){return this.#u?AbortSignal.any([this.#u,this.#s.signal]):this.#s.signal}#h(){let e=this.#d();if(e!==void 0&&e<=0)throw new _(this.request)}async#P(){for(let e of this.#e.hooks.beforeRequest){let t=await e({request:this.request,options:this.#o(),retryCount:0});if(Lt(t))this.#b(t);else if(Z(t))return t}}async#H(e){let t=this.#a(e);for(let i of this.#e.hooks.afterResponse){let s=this.#w(e.clone(),t);this.#E(s);let n;try{n=await i({request:this.request,options:this.#o(),response:s,retryCount:this.#r})}catch(u){throw s!==e&&this.#i(s),this.#i(e),u}if(n instanceof z)throw s!==e&&this.#i(s),this.#i(e),new j(n.options);let o=Z(n)?this.#w(n,t):e;s!==e&&s!==o&&s.body!==o.body&&this.#i(s),e!==o&&e.body!==o.body&&this.#i(e),e=o}return e}async#S(e){try{return await e()}catch(t){return this.#p(t,e)}}async#p(e,t){this.#l=!1;let i=Math.min(await this.#k(e),L),s={signal:this.#u},n=this.#d();if(n!==void 0){if(n<=0)throw new _(this.request);if(i>=n)throw await le(n,s),new _(this.request)}if(await le(i,s),this.#h(),e instanceof j&&e.customRequest){let o=new globalThis.Request(e.customRequest,this.#e.signal?{signal:this.#e.signal}:void 0);this.#b(o)}for(let o of this.#e.hooks.beforeRetry){let u;try{u=await o({request:this.request,options:this.#o(),error:e,retryCount:this.#r+1})}catch(a){throw a instanceof Error&&a!==e&&this.#O.add(a),a}if(Lt(u)){this.#b(u);break}if(Z(u))return this.#l=!0,this.#r++,u;if(u===ae)return}return this.#h(),this.#r++,this.#S(t)}#g(){let e=this.#l;return this.#l=!1,e}async#y(){this.#s?.signal.aborted&&(this.#s=new globalThis.AbortController,this.#e.signal=this.#A(),this.request=new globalThis.Request(this.request,{signal:this.#e.signal}));let e=Pt(this.#e),t=this.#e.retry.limit>0?this.request.clone():void 0,i=this.#I(this.request,this.#e.body??void 0);this.#_=i,t&&(this.request=t);try{let s=this.#d();if(s!==void 0&&s<=0)throw new _(this.request);let n=this.#e.timeout===!1?s:s===void 0?this.#e.timeout:Math.min(this.#e.timeout,s),o=n===void 0?await this.#e.fetch(i,e):await Me(i,e,this.#s,{timeout:n,fetch:this.#e.fetch});return this.#w(o,i)}catch(s){throw Ve(s)?new M(this.request,{cause:s}):s}}#d(){if(this.#f===void 0)return;let e=this.#R()-this.#f;return Math.max(0,this.#e.totalTimeout-e)}#R(){return globalThis.performance?.now()??Date.now()}#o(){if(!this.#c){let{hooks:e,json:t,parseJson:i,stringifyJson:s,searchParams:n,timeout:o,totalTimeout:u,throwHttpErrors:a,fetch:c,...l}=this.#e;this.#c=Object.freeze(l)}return this.#c}#b(e){this.#c=void 0,this.request=e}#a(e){return this.#x.get(e)??this.request}#w(e,t){return this.#x.set(e,t),e}#I(e,t){return!this.#e.onUploadProgress||!e.body||!qe?e:vt(e,this.#e.onUploadProgress,t??this.#e.body??void 0)}};var Fe=r=>{let e=(t,i)=>Q.create(t,Y(r,i));for(let t of oe)e[t]=(i,s)=>Q.create(i,Y(r,s,{method:t}));return e.create=t=>Fe(Y(t)),e.extend=t=>(typeof t=="function"&&(t=t(r??{})),Fe(Y(r,t))),e.stop=ae,e.retry=At,e},Vr=Fe(),Ut=Vr;async function Jt({cliOptions:r={},env:e=process.env,readConfig:t=B,requireSecretKey:i=!0}={}){let s=await t(),n=r.baseUrl||e.ENGAGELAB_EMAIL_BASE_URL||s.baseUrl,o=r.secretKey||e.ENGAGELAB_EMAIL_SECRET_KEY||s.secretKey;if(!n)throw re("Missing base URL. Set --base-url, ENGAGELAB_EMAIL_BASE_URL, or config set.");if(i&&!o)throw re("Missing Secret Key. Set --secret-key, ENGAGELAB_EMAIL_SECRET_KEY, or config set.");if(i&&!o.startsWith("sk_"))throw re("Secret Key must start with sk_");return{baseUrl:n,secretKey:o}}async function O(r){let e=await Jt({cliOptions:r.optsWithGlobals()});return Ut.extend({prefix:Lr(e.baseUrl),headers:{Authorization:`Bearer ${e.secretKey}`},timeout:3e4,throwHttpErrors:!1})}function x(r,e,t){r.opts().json&&r.parent?.parent?.stdout?.write?.("");let i=r.programOutput?.stdout||process.stdout;if(r.opts().json){i.write(`${JSON.stringify(e,null,2)}
|
|
27
|
+
`)})}function yr(r){return Object.fromEntries(Object.entries(r).filter(([,e])=>e!==void 0))}var ht=require("node:fs/promises");var dt=new Set(["bodyFile","bodyJson"]),ft=[["text","textFile"],["html","htmlFile"]];async function ve(r={},{readFile:e=ht.readFile}={}){if(br(r),r.bodyFile)return ct(await e(r.bodyFile,"utf8"),`Invalid JSON in ${r.bodyFile}`);if(r.bodyJson)return ct(r.bodyJson,"Invalid JSON in --body-json");let t={};for(let[i,s]of Object.entries(r))dt.has(i)||i.endsWith("File")||s===void 0||(t[i]=s);for(let[i,s]of ft)r[s]&&(t[i]=await e(r[s],"utf8"));return t}function br(r){if(r.bodyFile&&r.bodyJson)throw p("--body-file and --body-json are mutually exclusive");if((r.bodyFile||r.bodyJson)&&Object.entries(r).filter(([t,i])=>i!==void 0&&!dt.has(t)).length>0)throw p("--body-file/--body-json cannot be combined with field-level body options");for(let[e,t]of ft)if(r[e]&&r[t])throw p(`--${lt(e)} and --${lt(t)} are mutually exclusive`)}function ct(r,e){try{let t=JSON.parse(r);if(!t||typeof t!="object"||Array.isArray(t))throw new Error("JSON body must be an object");return t}catch(t){throw p(`${e}: ${t.message}`)}}function lt(r){return r.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}function _(r){let e=Number.parseInt(r,10);if(!Number.isInteger(e)||e<=0)throw p("Expected a positive integer");return e}function W(r){let e=Number.parseInt(r,10);if(!Number.isInteger(e)||e<0)throw p("Expected a non-negative integer");return e}function $(r,e=[]){return[...e,r]}function mt(r){return Object.fromEntries(Object.entries(r).filter(([,e])=>e!=null&&e!==""))}function P(r,e){if(r==null||r==="")throw p(e);return r}function je(r,e){if(!r||r.length===0)return"No results";let t=r.map(u=>e.map(a=>wr(a.value(u)))),i=e.map((u,a)=>Math.max(u.header.length,...t.map(c=>c[a].length))),s=e.map((u,a)=>pt(u.header,i[a])).join(" "),n=i.map(u=>"-".repeat(u)).join(" "),o=t.map(u=>u.map((a,c)=>pt(a,i[c])).join(" "));return[s,n,...o].join(`
|
|
28
|
+
`)}function wr(r){return Array.isArray(r)?r.join(", "):r==null?"":String(r)}function pt(r,e){return r.padEnd(e," ")}function gt(r){return{0:"received",1:"parsing",2:"parsed",3:"parse_failed",4:"replied"}[r]??r}function yt(r){return{0:"pending",1:"processing",2:"done",3:"failed"}[r]??r}function bt(r){return je(r.data?.list||[],[{header:"Thread ID",value:e=>e.threadId},{header:"Subject",value:e=>e.subject},{header:"Participants",value:e=>e.participants},{header:"Last Message",value:e=>e.lastMessageAt},{header:"Count",value:e=>e.messageCount},{header:"Status",value:e=>e.status}])}function B(r){return je(r.data?.list||r.data||[],[{header:"Message UID",value:e=>e.messageUid},{header:"Thread ID",value:e=>e.threadId},{header:"From",value:e=>e.fromEmail||e.envelopeFrom},{header:"Subject",value:e=>e.subject},{header:"Status",value:e=>gt(e.status)},{header:"Agent",value:e=>yt(e.agentConsumeStatus)},{header:"Received",value:e=>e.receivedAt}])}function re(r){return JSON.stringify(r.data??r,null,2)}function qe(r){let e=r.data||{};return["Sent",e.messageUid?`messageUid: ${e.messageUid}`:null,e.requestId?`requestId: ${e.requestId}`:null,e.emailIds?`emailIds: ${e.emailIds.join(", ")}`:null].filter(Boolean).join(`
|
|
29
|
+
`)}function _r(r,{httpStatus:e}={}){if(!r||typeof r!="object"||typeof r.code!="number")throw new w("Invalid server response format",{code:"invalid_response",exitCode:5,status:e,data:r});if(r.code!==200)throw new w(r.message||"Request failed",{code:wt(r.code),exitCode:ke(r.code),status:r.code,data:r});return r}async function O(r){let e;try{e=await r.json()}catch(t){throw new w("Invalid server response format",{code:"invalid_response",exitCode:5,status:r.status,cause:t})}if(r.status<200||r.status>=300)throw new w(e?.message||`Request failed with status code ${r.status}`,{code:wt(r.status),exitCode:ke(r.status),status:r.status,data:e});return _r(e,{httpStatus:r.status})}function wt(r){return r===401||r===403?"auth_error":r===404?"not_found":r===409?"state_conflict":r===400?"validation_error":"server_error"}var v=class{constructor(e){this.client=e}listMessages(e={}){return this.client.get("/v1/message/list",{searchParams:e}).then(O)}getMessage(e){return this.client.get("/v1/message/get",{searchParams:{messageUid:e}}).then(O)}listenMessages(e={}){return this.client.get("/v1/message/listen",{searchParams:e}).then(O)}replyMessage(e,t){return this.client.post("/v1/message/reply",{searchParams:{messageUid:e},json:t}).then(O)}};var ie=class{constructor(e){this.client=e}sendEmail(e){return this.client.post("/v1/mail/send",{json:e}).then(O)}};var x=class extends Error{name="KyError";get isKyError(){return!0}};var H=class extends x{name="HTTPError";response;request;options;data;constructor(e,t,i){let s=e.status||e.status===0?e.status:"",n=e.statusText??"",o=`${s} ${n}`.trim(),u=o?`status code ${o}`:"an unknown error";super(`Request failed with ${u}: ${t.method} ${t.url}`),this.response=e,this.request=t,this.options=i}};var N=class extends x{name="NetworkError";request;constructor(e,t){super(`Request failed due to a network error: ${e.method} ${e.url}`,t),this.request=e}};var I=class extends Error{name="NonError";value;constructor(e){let t="Non-error value was thrown";try{typeof e=="string"?t=e:e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"&&(t=e.message)}catch{}super(t),this.value=e}};var j=class extends x{name="ForceRetryError";customDelay;code;customRequest;constructor(e){let t=e?.cause?e.cause instanceof Error?e.cause:new I(e.cause):void 0;super(e?.code?`Forced retry: ${e.code}`:"Forced retry",t?{cause:t}:void 0),this.customDelay=e?.delay,this.code=e?.code,this.customRequest=e?.request}};var se=class extends Error{name="SchemaValidationError";issues;constructor(e){super("Response schema validation failed"),this.issues=e}};var b=class extends x{name="TimeoutError";request;constructor(e){super(`Request timed out: ${e.method} ${e.url}`),this.request=e}};var $e=(()=>{let r=!1,e=!1,t=typeof globalThis.ReadableStream=="function",i=typeof globalThis.Request=="function";if(t&&i)try{e=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return r=!0,"half"}}).headers.has("Content-Type")}catch(s){if(s instanceof Error&&s.message==="unsupported BodyInit type")return!1;throw s}return r&&!e})(),_t=typeof globalThis.AbortController=="function",ne=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",Ot=typeof globalThis.ReadableStream=="function",xt=typeof globalThis.FormData=="function",oe=["get","post","put","patch","head","delete"],Or=()=>{};Or();var Et={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},V=2147483647,Ct=40,ae=Symbol("stop"),G=class{options;constructor(e){this.options=e}},At=r=>new G(r),St={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,baseUrl:!0,prefix:!0,retry:!0,timeout:!0,totalTimeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0,context:!0},Rt={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,duplex:!0};var ue=new TextEncoder,xr=r=>{if(!r)return 0;if(r instanceof FormData){let e=0;for(let[t,i]of r)e+=Ct,e+=ue.encode(`Content-Disposition: form-data; name="${t}"`).byteLength,e+=typeof i=="string"?ue.encode(i).byteLength:i.size;return e}return r instanceof Blob?r.size:r instanceof ArrayBuffer||ArrayBuffer.isView(r)?r.byteLength:typeof r=="string"?ue.encode(r).byteLength:r instanceof URLSearchParams?ue.encode(r.toString()).byteLength:0},Tt=(r,e,t)=>{let i,s=0;return r.pipeThrough(new TransformStream({transform(n,o){if(o.enqueue(n),i){s+=i.byteLength;let u=e===0?0:s/e;u>=1&&(u=1-Number.EPSILON),t?.({percent:u,totalBytes:Math.max(e,s),transferredBytes:s},i)}i=n},flush(){i&&(s+=i.byteLength,t?.({percent:1,totalBytes:Math.max(e,s),transferredBytes:s},i))}}))},kt=(r,e)=>{if(!r.body)return r;let t={status:r.status,statusText:r.statusText,headers:r.headers};if(r.status===204)return new Response(null,t);let i=Math.max(0,Number(r.headers.get("content-length"))||0);return new Response(Tt(r.body,i,e),t)},vt=(r,e,t)=>{if(!r.body)return r;let i=xr(t??r.body);return new Request(r,{duplex:"half",body:Tt(r.body,i,e)})};var E=r=>r!==null&&typeof r=="object";var Er=Symbol("replaceOption"),Pe=r=>E(r)&&r[Er]===!0?{isReplace:!0,value:r.value}:{isReplace:!1,value:r};var K=(...r)=>{for(let e of r)if((!E(e)||Array.isArray(e))&&e!==void 0)throw new TypeError("The `options` argument must be an object");return Ie({},...r)},Ne=(r={},e={})=>{let t=new globalThis.Headers(r),i=e instanceof globalThis.Headers,s=new globalThis.Headers(e);for(let[n,o]of s.entries())i&&o==="undefined"||o===void 0?t.delete(n):t.set(n,o);return t},He=r=>{if(!E(r)||Array.isArray(r))return!1;let e=Object.getPrototypeOf(r);return e===Object.prototype||e===null},L=r=>{if(r instanceof URLSearchParams){let e=new URLSearchParams(r),t=r[T];return t&&(e[T]=new Set(t)),e}return r instanceof globalThis.Headers?new globalThis.Headers(r):Array.isArray(r)?[...r]:He(r)?{...r}:r},Cr=r=>Object.fromEntries(Object.entries(r).filter(e=>e[1]!==void 0)),Ar=(r,e)=>He(r)&&He(e)?Cr({...r,...e}):Ne(r,e);function z(r,e,t){return Object.hasOwn(e,t)&&e[t]===void 0?[]:Ie(r[t]??[],e[t]??[])}var ce=(r={},e={})=>({init:z(r,e,"init"),beforeRequest:z(r,e,"beforeRequest"),beforeRetry:z(r,e,"beforeRetry"),beforeError:z(r,e,"beforeError"),afterResponse:z(r,e,"afterResponse")}),T=Symbol("deletedParameters"),Sr=(r,e)=>{let t=new URLSearchParams,i=new Set;for(let s of[r,e])if(s!==void 0)if(s instanceof URLSearchParams){for(let[o,u]of s.entries())t.append(o,u),i.delete(o);let n=s[T];if(n)for(let o of n)t.delete(o),i.add(o)}else if(Array.isArray(s))for(let n of s){if(!Array.isArray(n)||n.length!==2)throw new TypeError("Array search parameters must be provided in [[key, value], ...] format");t.append(String(n[0]),String(n[1])),i.delete(String(n[0]))}else if(E(s))for(let[n,o]of Object.entries(s))o===void 0?(t.delete(n),i.add(n)):(t.append(n,String(o)),i.delete(n));else{let n=new URLSearchParams(s);for(let[o,u]of n.entries())t.append(o,u),i.delete(o)}return i.size>0&&(t[T]=i),t},Ie=(...r)=>{let e={},t={},i={},s,n=[];for(let o of r)if(Array.isArray(o))Array.isArray(e)||(e=[]),e=[...e,...o];else if(E(o)){for(let[u,a]of Object.entries(o)){if(u==="signal"&&a instanceof globalThis.AbortSignal){n.push(a);continue}let c=Pe(a),{isReplace:l}=c;if(a=c.value,u==="context"){if(a!=null&&(!E(a)||Array.isArray(a)))throw new TypeError("The `context` option must be an object");e={...e,context:a==null?{}:l?{...a}:{...e.context,...a}};continue}if(u==="searchParams"){a==null?s=void 0:l?s=a:s=s===void 0?a:Sr(s,a);continue}E(a)&&!l&&u in e&&(a=Ie(e[u],a)),e={...e,[u]:a}}if(E(o.hooks)){let{value:u,isReplace:a}=Pe(o.hooks);i=ce(a?{}:i,u),e.hooks=i}if(E(o.headers)){let{value:u,isReplace:a}=Pe(o.headers);t=a?L(u):Ar(t,u),e.headers=t}}return s!==void 0&&(e.searchParams=s),n.length>0&&(n.length===1?e.signal=n[0]:ne?e.signal=AbortSignal.any(n):e.signal=n.at(-1)),e};var qt=r=>oe.includes(r)?r.toUpperCase():r,Rr=["get","put","head","delete","options","trace"],Tr=[408,413,429,500,502,503,504],kr=[413,429,503],jt={limit:2,methods:Rr,statusCodes:Tr,afterStatusCodes:kr,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:r=>.3*2**(r-1)*1e3,jitter:void 0,retryOnTimeout:!1},$t=(r={})=>{if(typeof r=="number")return{...jt,limit:r};if(r.methods&&!Array.isArray(r.methods))throw new Error("retry.methods must be an array");if(r.statusCodes&&!Array.isArray(r.statusCodes))throw new Error("retry.statusCodes must be an array");let e=Object.fromEntries(Object.entries({...r,methods:r.methods?.map(t=>t.toLowerCase())}).filter(([,t])=>t!==void 0));return{...jt,...e}};async function Ve(r,e,t,i){return new Promise((s,n)=>{let o=setTimeout(()=>{t&&t.abort(),n(new b(r))},i.timeout);i.fetch(r,e).then(s).catch(n).then(()=>{clearTimeout(o)})})}async function le(r,{signal:e}){return new Promise((t,i)=>{e&&(e.throwIfAborted(),e.addEventListener("abort",s,{once:!0}));function s(){clearTimeout(n),i(e.reason)}let n=setTimeout(()=>{e?.removeEventListener("abort",s),t()},r)})}var Pt=r=>{let e={};for(let t in r)Object.hasOwn(r,t)&&!(t in Rt)&&!(t in St)&&(e[t]=r[t]);return e},Ht=r=>r===void 0?!1:Array.isArray(r)?r.length>0:r instanceof URLSearchParams?r.size>0||!!r[T]?.size:typeof r=="object"?Object.keys(r).length>0:typeof r=="string"?r.trim().length>0:!!r;var vr=Object.prototype.toString,jr=r=>vr.call(r)==="[object Error]",qr=new Set(["network error","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function Le(r){if(!(r&&jr(r)&&r.name==="TypeError"&&typeof r.message=="string"))return!1;let{message:t,stack:i}=r;return t==="Load failed"?i===void 0||"__sentry_captured__"in r:t.startsWith("error sending request for url")||t==="Failed to fetch"||t.startsWith("Failed to fetch (")&&t.endsWith(")")?!0:qr.has(t)}var Me=(r,e)=>r instanceof e||r?.name===e.name;function Nt(r){return Me(r,H)}function It(r){return Me(r,N)}function Vt(r){return Me(r,b)}var $r=10*1024*1024,Pr="The `prefixUrl` option has been renamed `prefix` in v2 and enhanced to allow slashes in input. See also the new `baseUrl` option for improved flexibility with standard URL resolution: https://github.com/sindresorhus/ky#baseurl",Y=Symbol("timedOutResponseData"),Hr=r=>{let e=/;\s*charset\s*=\s*(?:"([^"]+)"|([^;,\s]+))/i.exec(r),t=e?.[1]??e?.[2];if(t)try{return new TextDecoder(t)}catch{}return new TextDecoder},Lt="The `schema` argument must follow the Standard Schema specification",Nr=r=>typeof r!="object"?r:{...r,...r.methods&&{methods:[...r.methods]},...r.statusCodes&&{statusCodes:[...r.statusCodes]},...r.afterStatusCodes&&{afterStatusCodes:[...r.afterStatusCodes]}},Dt=Object.prototype.toString,Mt=r=>r instanceof globalThis.Request||Dt.call(r)==="[object Request]",X=r=>r instanceof globalThis.Response||Dt.call(r)==="[object Response]",Ir=r=>Array.isArray(r)?r.map(e=>[...e]):L(r);function Vr(r){let e={...r,json:L(r.json),context:L(r.context),headers:L(r.headers),searchParams:Ir(r.searchParams)};return r.retry!==void 0&&(e.retry=Nr(r.retry)),e}var Ft=async(r,e)=>{if(typeof e!="object"&&typeof e!="function"||e===null)throw new TypeError(Lt);let t=e["~standard"];if(typeof t!="object"||t===null||typeof t.validate!="function")throw new TypeError(Lt);let i=await t.validate(r);if(i.issues)throw new se(i.issues);return i.value},Z=class r{static create(e,t){let i=t.hooks?.init??[],s=i.length>0?Vr(t):t;for(let a of i)a(s);let n=new r(e,s),o=async()=>{if(typeof n.#e.timeout=="number"&&n.#e.timeout>V)throw new RangeError(`The \`timeout\` option cannot be greater than ${V}`);if(typeof n.#e.totalTimeout=="number"&&n.#e.totalTimeout>V)throw new RangeError(`The \`totalTimeout\` option cannot be greater than ${V}`);await Promise.resolve();let a=await n.#P(),c=a??await n.#S(async()=>n.#y()),l=a!==void 0||n.#g();for(;;){if(c===void 0)return c;if(X(c))try{c=await n.#H(c)}catch(d){if(!(d instanceof j))throw d;let g=await n.#p(d,async()=>n.#y());if(g===void 0)return g;c=g,l=n.#g();continue}let h=c;if(!h.ok&&h.type!=="opaque"&&(typeof n.#e.throwHttpErrors=="function"?n.#e.throwHttpErrors(h.status):n.#e.throwHttpErrors)){let d=new H(h,n.#a(h),n.#o()),g=d;if(d.data=await n.#v(h),l)throw g;let f=await n.#p(d,async()=>n.#y());if(f===void 0)return f;c=f,l=n.#g();continue}break}if(!X(c))return c;if(n.#E(c),n.#e.onDownloadProgress){if(typeof n.#e.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!Ot)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");let h=c.clone();return n.#i(c),kt(h,n.#e.onDownloadProgress)}return c},u=(async()=>{try{return await o()}catch(a){if(!(a instanceof Error)||n.#O.has(a))throw a;let c=a;for(let l of n.#e.hooks.beforeError){let h=await l({request:n.request,options:n.#o(),error:c,retryCount:n.#r});h instanceof Error&&(c=h)}throw c}finally{let a=n.#_;n.#m(a?.body??void 0),n.request!==a&&n.#m(n.request.body??void 0)}})();for(let[a,c]of Object.entries(Et))a==="bytes"&&typeof globalThis.Response?.prototype?.bytes!="function"||(u[a]=async l=>{n.request.headers.set("accept",n.request.headers.get("accept")||c);let h=await u;if(a!=="json")return h[a]();let d=await h.text();if(d==="")return l!==void 0?Ft(void 0,l):JSON.parse(d);let g=s.parseJson?await s.parseJson(d,{request:n.#a(h),response:h}):JSON.parse(d);return l===void 0?g:Ft(g,l)});return u}static#T(e){return e&&typeof e=="object"&&!Array.isArray(e)&&!(e instanceof URLSearchParams)?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0)):e}request;#s;#r=0;#t;#e;#_;#u;#O=new WeakSet;#c;#f;#l=!1;#x=new WeakMap;constructor(e,t={}){if(this.#t=e,Object.hasOwn(t,"prefixUrl"))throw new Error(Pr);if(this.#e={...t,headers:Ne(this.#t.headers,t.headers),hooks:ce({},t.hooks),method:qt(t.method??this.#t.method??"GET"),prefix:String(t.prefix||""),retry:$t(t.retry),throwHttpErrors:t.throwHttpErrors??!0,timeout:t.timeout??1e4,totalTimeout:t.totalTimeout??!1,fetch:t.fetch??globalThis.fetch.bind(globalThis),context:t.context??{}},typeof this.#t!="string"&&!(this.#t instanceof URL||this.#t instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(typeof this.#t=="string"){if(this.#e.prefix){let s=this.#e.prefix.replace(/\/+$/,""),n=this.#t.replace(/^\/+/,"");this.#t=`${s}/${n}`}if(this.#e.baseUrl){let s;try{s=new URL(this.#t)}catch{}s||(this.#t=new URL(this.#t,new Request(this.#e.baseUrl).url))}}_t&&ne&&(this.#u=this.#e.signal??this.#t.signal,this.#s=new globalThis.AbortController,this.#e.signal=this.#A()),$e&&(this.#e.duplex="half"),this.#e.json!==void 0&&(this.#e.body=this.#e.stringifyJson?.(this.#e.json)??JSON.stringify(this.#e.json),this.#e.headers.set("content-type",this.#e.headers.get("content-type")??"application/json"));let i=t.headers&&new globalThis.Headers(t.headers).has("content-type");if(this.#t instanceof globalThis.Request&&(xt&&this.#e.body instanceof globalThis.FormData||this.#e.body instanceof URLSearchParams)&&!i&&this.#e.headers.delete("content-type"),this.request=new globalThis.Request(this.#t,this.#e),Ht(this.#e.searchParams)){let s=new URL(this.request.url),n=this.#e.searchParams?.[T];if(n)for(let o of n)s.searchParams.delete(o);if(typeof this.#e.searchParams=="string"){let o=this.#e.searchParams.replace(/^\?/,"");o!==""&&(s.search=s.search?`${s.search}&${o}`:`?${o}`)}else{let o=new URLSearchParams(r.#T(this.#e.searchParams));for(let[u,a]of o.entries())s.searchParams.append(u,a)}if(this.#e.searchParams&&typeof this.#e.searchParams=="object"&&!Array.isArray(this.#e.searchParams)&&!(this.#e.searchParams instanceof URLSearchParams))for(let[o,u]of Object.entries(this.#e.searchParams))u===void 0&&s.searchParams.delete(o);this.request=new globalThis.Request(s,this.#e)}if(this.#e.onUploadProgress&&typeof this.#e.onUploadProgress!="function")throw new TypeError("The `onUploadProgress` option must be a function");this.#f=typeof this.#e.totalTimeout=="number"?this.#R():void 0}#n(){let e=this.#e.retry.delay(this.#r+1),t=e;return this.#e.retry.jitter===!0?t=Math.random()*e:typeof this.#e.retry.jitter=="function"&&(t=this.#e.retry.jitter(e),(!Number.isFinite(t)||t<0)&&(t=e)),Math.min(this.#e.retry.backoffLimit,t)}async#k(e){if(this.#r>=this.#e.retry.limit)throw e;let t=e instanceof Error?e:new I(e);if(t instanceof j)return t.customDelay??this.#n();if(!this.#e.retry.methods.includes(this.request.method.toLowerCase()))throw e;if(this.#e.retry.shouldRetry!==void 0){let i=await this.#e.retry.shouldRetry({error:t,retryCount:this.#r+1});if(i===!1)throw e;if(i===!0)return this.#n()}if(Vt(e)){if(!this.#e.retry.retryOnTimeout)throw e;return this.#n()}if(Nt(e)){if(!this.#e.retry.statusCodes.includes(e.response.status))throw e;let i=e.response.headers.get("Retry-After")??e.response.headers.get("RateLimit-Reset")??e.response.headers.get("X-RateLimit-Retry-After")??e.response.headers.get("X-RateLimit-Reset")??e.response.headers.get("X-Rate-Limit-Reset");if(i&&this.#e.retry.afterStatusCodes.includes(e.response.status)){let s=Number(i)*1e3;return Number.isNaN(s)?s=Date.parse(i)-Date.now():s>=Date.parse("2024-01-01")&&(s-=Date.now()),Number.isFinite(s)?(s=Math.max(0,s),Math.min(this.#e.retry.maxRetryAfter,s)):Math.min(this.#e.retry.maxRetryAfter,this.#n())}if(e.response.status===413)throw e;return this.#n()}if(!It(e))throw e;return this.#n()}#E(e){let t=this.#a(e);return this.#e.parseJson&&(e.json=async()=>{let i=await e.text();return i===""?JSON.parse(i):this.#e.parseJson(i,{request:t,response:e})}),e}async#v(e){let t=await this.#q(e,this.#C());if(t===Y){this.#h();return}if(!t)return;if(!this.#j(e.headers.get("content-type")??""))return t;let i=await this.#$(t,e,this.#C(),this.#a(e));if(i===Y){this.#h();return}return i}#C(){let e=this.#e.timeout===!1?1e4:this.#e.timeout,t=this.#d();if(t===void 0)return e;if(t<=0)throw new b(this.request);return Math.min(e,t)}#j(e){let t=(e.split(";",1)[0]??"").trim().toLowerCase();return/\/(?:.*[.+-])?json$/.test(t)}async#q(e,t){let{body:i}=e;if(!i)try{return await e.text()}catch{return}let s;try{s=i.getReader()}catch{return}let n=Hr(e.headers.get("content-type")??""),o=[],u=0,a=(async()=>{try{for(;;){let{done:h,value:d}=await s.read();if(h)break;if(u+=d.byteLength,u>$r){s.cancel().catch(()=>{});return}o.push(n.decode(d,{stream:!0}))}}catch{return}return o.push(n.decode()),o.join("")})(),c=new Promise(h=>{let d=setTimeout(()=>{h(Y)},t);a.finally(()=>{clearTimeout(d)})}),l=await Promise.race([a,c]);return l===Y&&s.cancel().catch(()=>{}),l}async#$(e,t,i,s){let n;try{return await Promise.race([Promise.resolve().then(()=>this.#e.parseJson?this.#e.parseJson(e,{request:s,response:t}):JSON.parse(e)),new Promise(o=>{n=setTimeout(()=>{o(Y)},i)})])}catch{return}finally{clearTimeout(n)}}#m(e){e&&e.cancel().catch(()=>{})}#i(e){this.#m(e.body??void 0)}#A(){return this.#u?AbortSignal.any([this.#u,this.#s.signal]):this.#s.signal}#h(){let e=this.#d();if(e!==void 0&&e<=0)throw new b(this.request)}async#P(){for(let e of this.#e.hooks.beforeRequest){let t=await e({request:this.request,options:this.#o(),retryCount:0});if(Mt(t))this.#b(t);else if(X(t))return t}}async#H(e){let t=this.#a(e);for(let i of this.#e.hooks.afterResponse){let s=this.#w(e.clone(),t);this.#E(s);let n;try{n=await i({request:this.request,options:this.#o(),response:s,retryCount:this.#r})}catch(u){throw s!==e&&this.#i(s),this.#i(e),u}if(n instanceof G)throw s!==e&&this.#i(s),this.#i(e),new j(n.options);let o=X(n)?this.#w(n,t):e;s!==e&&s!==o&&s.body!==o.body&&this.#i(s),e!==o&&e.body!==o.body&&this.#i(e),e=o}return e}async#S(e){try{return await e()}catch(t){return this.#p(t,e)}}async#p(e,t){this.#l=!1;let i=Math.min(await this.#k(e),V),s={signal:this.#u},n=this.#d();if(n!==void 0){if(n<=0)throw new b(this.request);if(i>=n)throw await le(n,s),new b(this.request)}if(await le(i,s),this.#h(),e instanceof j&&e.customRequest){let o=new globalThis.Request(e.customRequest,this.#e.signal?{signal:this.#e.signal}:void 0);this.#b(o)}for(let o of this.#e.hooks.beforeRetry){let u;try{u=await o({request:this.request,options:this.#o(),error:e,retryCount:this.#r+1})}catch(a){throw a instanceof Error&&a!==e&&this.#O.add(a),a}if(Mt(u)){this.#b(u);break}if(X(u))return this.#l=!0,this.#r++,u;if(u===ae)return}return this.#h(),this.#r++,this.#S(t)}#g(){let e=this.#l;return this.#l=!1,e}async#y(){this.#s?.signal.aborted&&(this.#s=new globalThis.AbortController,this.#e.signal=this.#A(),this.request=new globalThis.Request(this.request,{signal:this.#e.signal}));let e=Pt(this.#e),t=this.#e.retry.limit>0?this.request.clone():void 0,i=this.#N(this.request,this.#e.body??void 0);this.#_=i,t&&(this.request=t);try{let s=this.#d();if(s!==void 0&&s<=0)throw new b(this.request);let n=this.#e.timeout===!1?s:s===void 0?this.#e.timeout:Math.min(this.#e.timeout,s),o=n===void 0?await this.#e.fetch(i,e):await Ve(i,e,this.#s,{timeout:n,fetch:this.#e.fetch});return this.#w(o,i)}catch(s){throw Le(s)?new N(this.request,{cause:s}):s}}#d(){if(this.#f===void 0)return;let e=this.#R()-this.#f;return Math.max(0,this.#e.totalTimeout-e)}#R(){return globalThis.performance?.now()??Date.now()}#o(){if(!this.#c){let{hooks:e,json:t,parseJson:i,stringifyJson:s,searchParams:n,timeout:o,totalTimeout:u,throwHttpErrors:a,fetch:c,...l}=this.#e;this.#c=Object.freeze(l)}return this.#c}#b(e){this.#c=void 0,this.request=e}#a(e){return this.#x.get(e)??this.request}#w(e,t){return this.#x.set(e,t),e}#N(e,t){return!this.#e.onUploadProgress||!e.body||!$e?e:vt(e,this.#e.onUploadProgress,t??this.#e.body??void 0)}};var Fe=r=>{let e=(t,i)=>Z.create(t,K(r,i));for(let t of oe)e[t]=(i,s)=>Z.create(i,K(r,s,{method:t}));return e.create=t=>Fe(K(t)),e.extend=t=>(typeof t=="function"&&(t=t(r??{})),Fe(K(r,t))),e.stop=ae,e.retry=At,e},Lr=Fe(),Ut=Lr;async function Jt({cliOptions:r={},env:e=process.env,readConfig:t=J,requireSecretKey:i=!0}={}){let s=await t(),n=r.baseUrl||e.ENGAGELAB_EMAIL_BASE_URL||s.baseUrl,o=r.secretKey||e.ENGAGELAB_EMAIL_SECRET_KEY||s.secretKey;if(!n)throw te("Missing base URL. Set --base-url, ENGAGELAB_EMAIL_BASE_URL, or config set.");if(i&&!o)throw te("Missing Secret Key. Set --secret-key, ENGAGELAB_EMAIL_SECRET_KEY, or config set.");if(i&&!o.startsWith("sk_"))throw te("Secret Key must start with sk_");return{baseUrl:n,secretKey:o}}async function C(r){let e=await Jt({cliOptions:r.optsWithGlobals()});return Ut.extend({prefix:Mr(e.baseUrl),headers:{Authorization:`Bearer ${e.secretKey}`},timeout:3e4,throwHttpErrors:!1})}function A(r,e,t){r.opts().json&&r.parent?.parent?.stdout?.write?.("");let i=r.programOutput?.stdout||process.stdout;if(r.opts().json){i.write(`${JSON.stringify(e,null,2)}
|
|
30
30
|
`);return}i.write(`${t(e)}
|
|
31
|
-
`)}function
|
|
31
|
+
`)}function M(r,e){let t={};for(let[i,s=i]of Object.entries(e))t[s]=r[i];return mt(t)}function De(r,e){let t={};for(let i of e)r[i]!==void 0&&(t[i]=r[i]);return t}function Mr(r){return r.endsWith("/")?r.slice(0,-1):r}var Fr=["bodyFile","bodyJson","mailboxId","to","subject","text","html","textFile","htmlFile","cc","bcc"];function Wt(r){let e=r.command("emails").description("Work with email messages");Dr(e),Ur(e)}function Dr(r){r.command("send").description("Send a new email").option("--body-file <path>","Read full JSON request body from file").option("--body-json <json>","Read full JSON request body from inline JSON").option("--mailbox-id <id>","Mailbox ID",_).option("--to <email>","Recipient email address",$).option("--subject <text>","Email subject").option("--text <text>","Plain text body").option("--html <html>","HTML body").option("--text-file <path>","Read plain text body from file").option("--html-file <path>","Read HTML body from file").option("--cc <email>","CC address",$).option("--bcc <email>","BCC address",$).option("--json","Output raw JSON").action(async(e,t)=>{let i=await ve(De(e,Fr));Jr(i);let s=new ie(await C(t));A(t,await s.sendEmail(i),qe)})}function Ur(r){let e=r.command("receiving").description("Work with inbound email");e.command("list").description("List inbound messages").option("--mailbox-id <id>","Filter by mailbox ID",_).option("--keyword <text>","Search keyword").option("--page-no <number>","Page number",_).option("--page-size <number>","Page size",_).option("--json","Output raw JSON").action(async(t,i)=>{let n=await new v(await C(i)).listMessages(M(t,{mailboxId:"mailboxId",keyword:"keyword",pageNo:"pageNo",pageSize:"pageSize"}));A(i,n,B)}),e.command("get").description("Get inbound message details").argument("<message-uid>","Message UID").option("--json","Output raw JSON").action(async(t,i,s)=>{P(t,"Message UID is required");let n=new v(await C(s));A(s,await n.getMessage(t),re)}),e.command("listen").description("Poll new inbound messages for Agent processing").option("--after <id>","Cursor ID from the previous result",W).option("--limit <number>","Message limit",_).option("--json","Output raw JSON").action(async(t,i)=>{let n=await new v(await C(i)).listenMessages(M(t,{after:"after",limit:"limit"}));A(i,n,B)}),e.command("reply").description("Reply to an inbound message").argument("<message-uid>","Message UID").option("--body-file <path>","Read full JSON request body from file").option("--body-json <json>","Read full JSON request body from inline JSON").option("--subject <text>","Reply subject").option("--text <text>","Plain text body").option("--html <html>","HTML body").option("--text-file <path>","Read plain text body from file").option("--html-file <path>","Read HTML body from file").option("--cc <email>","CC address",$).option("--bcc <email>","BCC address",$).option("--json","Output raw JSON").action(async(t,i,s)=>{P(t,"Message UID is required");let n=await ve(De(i,["bodyFile","bodyJson","subject","text","html","textFile","htmlFile","cc","bcc"]));Wr(n);let o=new v(await C(s));A(s,await o.replyMessage(t,n),qe)})}function Jr(r){if(!r.mailboxId)throw p("mailboxId is required");if(!Array.isArray(r.to)||r.to.length===0)throw p("At least one recipient is required");if(!r.subject)throw p("subject is required");Bt(r)}function Wr(r){Bt(r)}function Bt(r){if(!r.text&&!r.html)throw p("At least one of text or html is required")}var F=class{constructor(e){this.client=e}listThreads(e={}){return this.client.get("/v1/thread/list",{searchParams:e}).then(O)}getThread(e){return this.client.get("/v1/thread/get",{searchParams:{threadId:e}}).then(O)}listThreadMessages(e,t={}){return this.client.get("/v1/thread/messages",{searchParams:{threadId:e,...t}}).then(O)}};function Gt(r){let e=r.command("threads").description("Work with email threads");e.command("list").description("List threads").option("--mailbox-id <id>","Filter by mailbox ID",_).option("--subject <text>","Search normalized subject").option("--participant <email>","Search participant").option("--start-time <timestamp>","Latest message start timestamp in milliseconds",W).option("--end-time <timestamp>","Latest message end timestamp in milliseconds",W).option("--page-no <number>","Page number",_).option("--page-size <number>","Page size",_).option("--json","Output raw JSON").action(async(t,i)=>{let n=await new F(await C(i)).listThreads(M(t,{mailboxId:"mailboxId",subject:"subject",participant:"participant",startTime:"startTime",endTime:"endTime",pageNo:"pageNo",pageSize:"pageSize"}));A(i,n,bt)}),e.command("get").description("Get thread details").argument("<thread-id>","Thread ID").option("--json","Output raw JSON").action(async(t,i,s)=>{P(t,"Thread ID is required");let n=new F(await C(s));A(s,await n.getThread(t),re)}),e.command("messages").description("List messages in a thread").argument("<thread-id>","Thread ID").option("--limit <number>","Message limit",_).option("--include-content","Include text/html/headers/attachments").option("--json","Output raw JSON").action(async(t,i,s)=>{P(t,"Thread ID is required");let o=await new F(await C(s)).listThreadMessages(t,M(i,{limit:"limit",includeContent:"includeContent"}));A(s,o,B)})}function zt(r,e){r.write(`${JSON.stringify({error:{code:e.code||"unknown_error",message:e.message||"Command failed"}},null,2)}
|
|
32
32
|
`)}function Br(r=new it){return r.name("engagelab-email-cli").description("CLI for EngageLab Email Agent workflows").version("0.1.0").option("-u, --base-url <url>","EngageLab Email API base URL",process.env.ENGAGELAB_EMAIL_BASE_URL).option("--secret-key <key>","EngageLab Email Secret Key",process.env.ENGAGELAB_EMAIL_SECRET_KEY),ut(r),Gt(r),Wt(r),r}async function Kt(r=process.argv){let e=Br();try{await e.parseAsync(r)}catch(t){let i=at(t);r.includes("--json")?zt(process.stderr,i):process.stderr.write(`${i.message}
|
|
33
33
|
`),process.exitCode=i.exitCode}}Kt().catch(r=>{process.stderr.write(`${r instanceof Error?r.message:String(r)}
|
|
34
34
|
`),process.exitCode=1});
|