ace-assistant-cli 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +50 -34
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,41 +1,57 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- import{createRequire as M$}from"node:module";var T$=Object.create;var{getPrototypeOf:Q$,defineProperty:zj,getOwnPropertyNames:U$}=Object;var Z$=Object.prototype.hasOwnProperty;var G$=(j,$,S)=>{S=j!=null?T$(Q$(j)):{};let y=$||!j||!j.__esModule?zj(S,"default",{value:j,enumerable:!0}):S;for(let q of U$(j))if(!Z$.call(y,q))zj(y,q,{get:()=>j[q],enumerable:!0});return y};var F=(j,$)=>()=>($||j(($={exports:{}}).exports,$),$.exports);var C=M$(import.meta.url);var k=F((X$)=>{class r extends Error{constructor(j,$,S){super(S);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=$,this.exitCode=j,this.nestedError=void 0}}class Wj extends r{constructor(j){super(1,"commander.invalidArgument",j);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}X$.CommanderError=r;X$.InvalidArgumentError=Wj});var O=F((L$)=>{var{InvalidArgumentError:W$}=k();class Hj{constructor(j,$){switch(this.description=$||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,j[0]){case"<":this.required=!0,this._name=j.slice(1,-1);break;case"[":this.required=!1,this._name=j.slice(1,-1);break;default:this.required=!0,this._name=j;break}if(this._name.length>3&&this._name.slice(-3)==="...")this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_concatValue(j,$){if($===this.defaultValue||!Array.isArray($))return[j];return $.concat(j)}default(j,$){return this.defaultValue=j,this.defaultValueDescription=$,this}argParser(j){return this.parseArg=j,this}choices(j){return this.argChoices=j.slice(),this.parseArg=($,S)=>{if(!this.argChoices.includes($))throw new W$(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue($,S);return $},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function H$(j){let $=j.name()+(j.variadic===!0?"...":"");return j.required?"<"+$+">":"["+$+"]"}L$.Argument=Hj;L$.humanReadableArgName=H$});var l=F((B$)=>{var{humanReadableArgName:F$}=O();class Lj{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(j){let $=j.commands.filter((y)=>!y._hidden),S=j._getHelpCommand();if(S&&!S._hidden)$.push(S);if(this.sortSubcommands)$.sort((y,q)=>{return y.name().localeCompare(q.name())});return $}compareOptions(j,$){let S=(y)=>{return y.short?y.short.replace(/^-/,""):y.long.replace(/^--/,"")};return S(j).localeCompare(S($))}visibleOptions(j){let $=j.options.filter((y)=>!y.hidden),S=j._getHelpOption();if(S&&!S.hidden){let y=S.short&&j._findOption(S.short),q=S.long&&j._findOption(S.long);if(!y&&!q)$.push(S);else if(S.long&&!q)$.push(j.createOption(S.long,S.description));else if(S.short&&!y)$.push(j.createOption(S.short,S.description))}if(this.sortOptions)$.sort(this.compareOptions);return $}visibleGlobalOptions(j){if(!this.showGlobalOptions)return[];let $=[];for(let S=j.parent;S;S=S.parent){let y=S.options.filter((q)=>!q.hidden);$.push(...y)}if(this.sortOptions)$.sort(this.compareOptions);return $}visibleArguments(j){if(j._argsDescription)j.registeredArguments.forEach(($)=>{$.description=$.description||j._argsDescription[$.name()]||""});if(j.registeredArguments.find(($)=>$.description))return j.registeredArguments;return[]}subcommandTerm(j){let $=j.registeredArguments.map((S)=>F$(S)).join(" ");return j._name+(j._aliases[0]?"|"+j._aliases[0]:"")+(j.options.length?" [options]":"")+($?" "+$:"")}optionTerm(j){return j.flags}argumentTerm(j){return j.name()}longestSubcommandTermLength(j,$){return $.visibleCommands(j).reduce((S,y)=>{return Math.max(S,$.subcommandTerm(y).length)},0)}longestOptionTermLength(j,$){return $.visibleOptions(j).reduce((S,y)=>{return Math.max(S,$.optionTerm(y).length)},0)}longestGlobalOptionTermLength(j,$){return $.visibleGlobalOptions(j).reduce((S,y)=>{return Math.max(S,$.optionTerm(y).length)},0)}longestArgumentTermLength(j,$){return $.visibleArguments(j).reduce((S,y)=>{return Math.max(S,$.argumentTerm(y).length)},0)}commandUsage(j){let $=j._name;if(j._aliases[0])$=$+"|"+j._aliases[0];let S="";for(let y=j.parent;y;y=y.parent)S=y.name()+" "+S;return S+$+" "+j.usage()}commandDescription(j){return j.description()}subcommandDescription(j){return j.summary()||j.description()}optionDescription(j){let $=[];if(j.argChoices)$.push(`choices: ${j.argChoices.map((S)=>JSON.stringify(S)).join(", ")}`);if(j.defaultValue!==void 0){if(j.required||j.optional||j.isBoolean()&&typeof j.defaultValue==="boolean")$.push(`default: ${j.defaultValueDescription||JSON.stringify(j.defaultValue)}`)}if(j.presetArg!==void 0&&j.optional)$.push(`preset: ${JSON.stringify(j.presetArg)}`);if(j.envVar!==void 0)$.push(`env: ${j.envVar}`);if($.length>0)return`${j.description} (${$.join(", ")})`;return j.description}argumentDescription(j){let $=[];if(j.argChoices)$.push(`choices: ${j.argChoices.map((S)=>JSON.stringify(S)).join(", ")}`);if(j.defaultValue!==void 0)$.push(`default: ${j.defaultValueDescription||JSON.stringify(j.defaultValue)}`);if($.length>0){let S=`(${$.join(", ")})`;if(j.description)return`${j.description} ${S}`;return S}return j.description}formatHelp(j,$){let S=$.padWidth(j,$),y=$.helpWidth||80,q=2,R=2;function I(G,H){if(H){let s=`${G.padEnd(S+2)}${H}`;return $.wrap(s,y-2,S+2)}return G}function E(G){return G.join(`
4
- `).replace(/^/gm," ".repeat(2))}let P=[`Usage: ${$.commandUsage(j)}`,""],J=$.commandDescription(j);if(J.length>0)P=P.concat([$.wrap(J,y,0),""]);let Y=$.visibleArguments(j).map((G)=>{return I($.argumentTerm(G),$.argumentDescription(G))});if(Y.length>0)P=P.concat(["Arguments:",E(Y),""]);let Z=$.visibleOptions(j).map((G)=>{return I($.optionTerm(G),$.optionDescription(G))});if(Z.length>0)P=P.concat(["Options:",E(Z),""]);if(this.showGlobalOptions){let G=$.visibleGlobalOptions(j).map((H)=>{return I($.optionTerm(H),$.optionDescription(H))});if(G.length>0)P=P.concat(["Global Options:",E(G),""])}let X=$.visibleCommands(j).map((G)=>{return I($.subcommandTerm(G),$.subcommandDescription(G))});if(X.length>0)P=P.concat(["Commands:",E(X),""]);return P.join(`
5
- `)}padWidth(j,$){return Math.max($.longestOptionTermLength(j,$),$.longestGlobalOptionTermLength(j,$),$.longestSubcommandTermLength(j,$),$.longestArgumentTermLength(j,$))}wrap(j,$,S,y=40){let R=new RegExp(`[\\n][${" \\f\\t\\v   -    \uFEFF"}]+`);if(j.match(R))return j;let I=$-S;if(I<y)return j;let E=j.slice(0,S),P=j.slice(S).replace(`\r
3
+ import{createRequire as p$}from"node:module";var i$=Object.create;var{getPrototypeOf:a$,defineProperty:Dy,getOwnPropertyNames:e$}=Object;var n$=Object.prototype.hasOwnProperty;var o$=(y,$,j)=>{j=y!=null?i$(a$(y)):{};let G=$||!y||!y.__esModule?Dy(j,"default",{value:y,enumerable:!0}):j;for(let P of e$(y))if(!n$.call(G,P))Dy(G,P,{get:()=>y[P],enumerable:!0});return G};var B=(y,$)=>()=>($||y(($={exports:{}}).exports,$),$.exports);var O=p$(import.meta.url);var u=B((yj)=>{class $y extends Error{constructor(y,$,j){super(j);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=$,this.exitCode=y,this.nestedError=void 0}}class ky extends $y{constructor(y){super(1,"commander.invalidArgument",y);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}yj.CommanderError=$y;yj.InvalidArgumentError=ky});var s=B((Rj)=>{var{InvalidArgumentError:Gj}=u();class by{constructor(y,$){switch(this.description=$||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,y[0]){case"<":this.required=!0,this._name=y.slice(1,-1);break;case"[":this.required=!1,this._name=y.slice(1,-1);break;default:this.required=!0,this._name=y;break}if(this._name.length>3&&this._name.slice(-3)==="...")this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_concatValue(y,$){if($===this.defaultValue||!Array.isArray($))return[y];return $.concat(y)}default(y,$){return this.defaultValue=y,this.defaultValueDescription=$,this}argParser(y){return this.parseArg=y,this}choices(y){return this.argChoices=y.slice(),this.parseArg=($,j)=>{if(!this.argChoices.includes($))throw new Gj(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue($,j);return $},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function Pj(y){let $=y.name()+(y.variadic===!0?"...":"");return y.required?"<"+$+">":"["+$+"]"}Rj.Argument=by;Rj.humanReadableArgName=Pj});var jy=B((Ej)=>{var{humanReadableArgName:Uj}=s();class vy{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(y){let $=y.commands.filter((G)=>!G._hidden),j=y._getHelpCommand();if(j&&!j._hidden)$.push(j);if(this.sortSubcommands)$.sort((G,P)=>{return G.name().localeCompare(P.name())});return $}compareOptions(y,$){let j=(G)=>{return G.short?G.short.replace(/^-/,""):G.long.replace(/^--/,"")};return j(y).localeCompare(j($))}visibleOptions(y){let $=y.options.filter((G)=>!G.hidden),j=y._getHelpOption();if(j&&!j.hidden){let G=j.short&&y._findOption(j.short),P=j.long&&y._findOption(j.long);if(!G&&!P)$.push(j);else if(j.long&&!P)$.push(y.createOption(j.long,j.description));else if(j.short&&!G)$.push(y.createOption(j.short,j.description))}if(this.sortOptions)$.sort(this.compareOptions);return $}visibleGlobalOptions(y){if(!this.showGlobalOptions)return[];let $=[];for(let j=y.parent;j;j=j.parent){let G=j.options.filter((P)=>!P.hidden);$.push(...G)}if(this.sortOptions)$.sort(this.compareOptions);return $}visibleArguments(y){if(y._argsDescription)y.registeredArguments.forEach(($)=>{$.description=$.description||y._argsDescription[$.name()]||""});if(y.registeredArguments.find(($)=>$.description))return y.registeredArguments;return[]}subcommandTerm(y){let $=y.registeredArguments.map((j)=>Uj(j)).join(" ");return y._name+(y._aliases[0]?"|"+y._aliases[0]:"")+(y.options.length?" [options]":"")+($?" "+$:"")}optionTerm(y){return y.flags}argumentTerm(y){return y.name()}longestSubcommandTermLength(y,$){return $.visibleCommands(y).reduce((j,G)=>{return Math.max(j,$.subcommandTerm(G).length)},0)}longestOptionTermLength(y,$){return $.visibleOptions(y).reduce((j,G)=>{return Math.max(j,$.optionTerm(G).length)},0)}longestGlobalOptionTermLength(y,$){return $.visibleGlobalOptions(y).reduce((j,G)=>{return Math.max(j,$.optionTerm(G).length)},0)}longestArgumentTermLength(y,$){return $.visibleArguments(y).reduce((j,G)=>{return Math.max(j,$.argumentTerm(G).length)},0)}commandUsage(y){let $=y._name;if(y._aliases[0])$=$+"|"+y._aliases[0];let j="";for(let G=y.parent;G;G=G.parent)j=G.name()+" "+j;return j+$+" "+y.usage()}commandDescription(y){return y.description()}subcommandDescription(y){return y.summary()||y.description()}optionDescription(y){let $=[];if(y.argChoices)$.push(`choices: ${y.argChoices.map((j)=>JSON.stringify(j)).join(", ")}`);if(y.defaultValue!==void 0){if(y.required||y.optional||y.isBoolean()&&typeof y.defaultValue==="boolean")$.push(`default: ${y.defaultValueDescription||JSON.stringify(y.defaultValue)}`)}if(y.presetArg!==void 0&&y.optional)$.push(`preset: ${JSON.stringify(y.presetArg)}`);if(y.envVar!==void 0)$.push(`env: ${y.envVar}`);if($.length>0)return`${y.description} (${$.join(", ")})`;return y.description}argumentDescription(y){let $=[];if(y.argChoices)$.push(`choices: ${y.argChoices.map((j)=>JSON.stringify(j)).join(", ")}`);if(y.defaultValue!==void 0)$.push(`default: ${y.defaultValueDescription||JSON.stringify(y.defaultValue)}`);if($.length>0){let j=`(${$.join(", ")})`;if(y.description)return`${y.description} ${j}`;return j}return y.description}formatHelp(y,$){let j=$.padWidth(y,$),G=$.helpWidth||80,P=2,R=2;function q(c,H){if(H){let yy=`${c.padEnd(j+2)}${H}`;return $.wrap(yy,G-2,j+2)}return c}function S(c){return c.join(`
4
+ `).replace(/^/gm," ".repeat(2))}let U=[`Usage: ${$.commandUsage(y)}`,""],I=$.commandDescription(y);if(I.length>0)U=U.concat([$.wrap(I,G,0),""]);let J=$.visibleArguments(y).map((c)=>{return q($.argumentTerm(c),$.argumentDescription(c))});if(J.length>0)U=U.concat(["Arguments:",S(J),""]);let Z=$.visibleOptions(y).map((c)=>{return q($.optionTerm(c),$.optionDescription(c))});if(Z.length>0)U=U.concat(["Options:",S(Z),""]);if(this.showGlobalOptions){let c=$.visibleGlobalOptions(y).map((H)=>{return q($.optionTerm(H),$.optionDescription(H))});if(c.length>0)U=U.concat(["Global Options:",S(c),""])}let X=$.visibleCommands(y).map((c)=>{return q($.subcommandTerm(c),$.subcommandDescription(c))});if(X.length>0)U=U.concat(["Commands:",S(X),""]);return U.join(`
5
+ `)}padWidth(y,$){return Math.max($.longestOptionTermLength(y,$),$.longestGlobalOptionTermLength(y,$),$.longestSubcommandTermLength(y,$),$.longestArgumentTermLength(y,$))}wrap(y,$,j,G=40){let R=new RegExp(`[\\n][${" \\f\\t\\v   -    \uFEFF"}]+`);if(y.match(R))return y;let q=$-j;if(q<G)return y;let S=y.slice(0,j),U=y.slice(j).replace(`\r
6
6
  `,`
7
- `),J=" ".repeat(S),Z=`\\s${"​"}`,X=new RegExp(`
8
- |.{1,${I-1}}([${Z}]|$)|[^${Z}]+?([${Z}]|$)`,"g"),G=P.match(X)||[];return E+G.map((H,s)=>{if(H===`
9
- `)return"";return(s>0?J:"")+H.trimEnd()}).join(`
10
- `)}}B$.Help=Lj});var d=F((w$)=>{var{InvalidArgumentError:V$}=k();class Dj{constructor(j,$){this.flags=j,this.description=$||"",this.required=j.includes("<"),this.optional=j.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(j),this.mandatory=!1;let S=f$(j);if(this.short=S.shortFlag,this.long=S.longFlag,this.negate=!1,this.long)this.negate=this.long.startsWith("--no-");this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(j,$){return this.defaultValue=j,this.defaultValueDescription=$,this}preset(j){return this.presetArg=j,this}conflicts(j){return this.conflictsWith=this.conflictsWith.concat(j),this}implies(j){let $=j;if(typeof j==="string")$={[j]:!0};return this.implied=Object.assign(this.implied||{},$),this}env(j){return this.envVar=j,this}argParser(j){return this.parseArg=j,this}makeOptionMandatory(j=!0){return this.mandatory=!!j,this}hideHelp(j=!0){return this.hidden=!!j,this}_concatValue(j,$){if($===this.defaultValue||!Array.isArray($))return[j];return $.concat(j)}choices(j){return this.argChoices=j.slice(),this.parseArg=($,S)=>{if(!this.argChoices.includes($))throw new V$(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue($,S);return $},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){return A$(this.name().replace(/^no-/,""))}is(j){return this.short===j||this.long===j}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class Kj{constructor(j){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,j.forEach(($)=>{if($.negate)this.negativeOptions.set($.attributeName(),$);else this.positiveOptions.set($.attributeName(),$)}),this.negativeOptions.forEach(($,S)=>{if(this.positiveOptions.has(S))this.dualOptions.add(S)})}valueFromOption(j,$){let S=$.attributeName();if(!this.dualOptions.has(S))return!0;let y=this.negativeOptions.get(S).presetArg,q=y!==void 0?y:!1;return $.negate===(q===j)}}function A$(j){return j.split("-").reduce(($,S)=>{return $+S[0].toUpperCase()+S.slice(1)})}function f$(j){let $,S,y=j.split(/[ |,]+/);if(y.length>1&&!/^[[<]/.test(y[1]))$=y.shift();if(S=y.shift(),!$&&/^-[^-]$/.test(S))$=S,S=void 0;return{shortFlag:$,longFlag:S}}w$.Option=Dj;w$.DualOptions=Kj});var Fj=F((u$)=>{function k$(j,$){if(Math.abs(j.length-$.length)>3)return Math.max(j.length,$.length);let S=[];for(let y=0;y<=j.length;y++)S[y]=[y];for(let y=0;y<=$.length;y++)S[0][y]=y;for(let y=1;y<=$.length;y++)for(let q=1;q<=j.length;q++){let R=1;if(j[q-1]===$[y-1])R=0;else R=1;if(S[q][y]=Math.min(S[q-1][y]+1,S[q][y-1]+1,S[q-1][y-1]+R),q>1&&y>1&&j[q-1]===$[y-2]&&j[q-2]===$[y-1])S[q][y]=Math.min(S[q][y],S[q-2][y-2]+1)}return S[j.length][$.length]}function b$(j,$){if(!$||$.length===0)return"";$=Array.from(new Set($));let S=j.startsWith("--");if(S)j=j.slice(2),$=$.map((I)=>I.slice(2));let y=[],q=3,R=0.4;if($.forEach((I)=>{if(I.length<=1)return;let E=k$(j,I),P=Math.max(j.length,I.length);if((P-E)/P>R){if(E<q)q=E,y=[I];else if(E===q)y.push(I)}}),y.sort((I,E)=>I.localeCompare(E)),S)y=y.map((I)=>`--${I}`);if(y.length>1)return`
11
- (Did you mean one of ${y.join(", ")}?)`;if(y.length===1)return`
12
- (Did you mean ${y[0]}?)`;return""}u$.suggestSimilar=b$});var Aj=F((m$)=>{var c$=C("node:events").EventEmitter,i=C("node:child_process"),z=C("node:path"),p=C("node:fs"),M=C("node:process"),{Argument:h$,humanReadableArgName:v$}=O(),{CommanderError:o}=k(),{Help:t$}=l(),{Option:Bj,DualOptions:g$}=d(),{suggestSimilar:Nj}=Fj();class n extends c${constructor(j){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=j||"",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:($)=>M.stdout.write($),writeErr:($)=>M.stderr.write($),getOutHelpWidth:()=>M.stdout.isTTY?M.stdout.columns:void 0,getErrHelpWidth:()=>M.stderr.isTTY?M.stderr.columns:void 0,outputError:($,S)=>S($)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(j){return this._outputConfiguration=j._outputConfiguration,this._helpOption=j._helpOption,this._helpCommand=j._helpCommand,this._helpConfiguration=j._helpConfiguration,this._exitCallback=j._exitCallback,this._storeOptionsAsProperties=j._storeOptionsAsProperties,this._combineFlagAndOptionalValue=j._combineFlagAndOptionalValue,this._allowExcessArguments=j._allowExcessArguments,this._enablePositionalOptions=j._enablePositionalOptions,this._showHelpAfterError=j._showHelpAfterError,this._showSuggestionAfterError=j._showSuggestionAfterError,this}_getCommandAndAncestors(){let j=[];for(let $=this;$;$=$.parent)j.push($);return j}command(j,$,S){let y=$,q=S;if(typeof y==="object"&&y!==null)q=y,y=null;q=q||{};let[,R,I]=j.match(/([^ ]+) *(.*)/),E=this.createCommand(R);if(y)E.description(y),E._executableHandler=!0;if(q.isDefault)this._defaultCommandName=E._name;if(E._hidden=!!(q.noHelp||q.hidden),E._executableFile=q.executableFile||null,I)E.arguments(I);if(this._registerCommand(E),E.parent=this,E.copyInheritedSettings(this),y)return this;return E}createCommand(j){return new n(j)}createHelp(){return Object.assign(new t$,this.configureHelp())}configureHelp(j){if(j===void 0)return this._helpConfiguration;return this._helpConfiguration=j,this}configureOutput(j){if(j===void 0)return this._outputConfiguration;return Object.assign(this._outputConfiguration,j),this}showHelpAfterError(j=!0){if(typeof j!=="string")j=!!j;return this._showHelpAfterError=j,this}showSuggestionAfterError(j=!0){return this._showSuggestionAfterError=!!j,this}addCommand(j,$){if(!j._name)throw Error(`Command passed to .addCommand() must have a name
13
- - specify the name in Command constructor or using .name()`);if($=$||{},$.isDefault)this._defaultCommandName=j._name;if($.noHelp||$.hidden)j._hidden=!0;return this._registerCommand(j),j.parent=this,j._checkForBrokenPassThrough(),this}createArgument(j,$){return new h$(j,$)}argument(j,$,S,y){let q=this.createArgument(j,$);if(typeof S==="function")q.default(y).argParser(S);else q.default(S);return this.addArgument(q),this}arguments(j){return j.trim().split(/ +/).forEach(($)=>{this.argument($)}),this}addArgument(j){let $=this.registeredArguments.slice(-1)[0];if($&&$.variadic)throw Error(`only the last argument can be variadic '${$.name()}'`);if(j.required&&j.defaultValue!==void 0&&j.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${j.name()}'`);return this.registeredArguments.push(j),this}helpCommand(j,$){if(typeof j==="boolean")return this._addImplicitHelpCommand=j,this;j=j??"help [command]";let[,S,y]=j.match(/([^ ]+) *(.*)/),q=$??"display help for command",R=this.createCommand(S);if(R.helpOption(!1),y)R.arguments(y);if(q)R.description(q);return this._addImplicitHelpCommand=!0,this._helpCommand=R,this}addHelpCommand(j,$){if(typeof j!=="object")return this.helpCommand(j,$),this;return this._addImplicitHelpCommand=!0,this._helpCommand=j,this}_getHelpCommand(){if(this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))){if(this._helpCommand===void 0)this.helpCommand(void 0,void 0);return this._helpCommand}return null}hook(j,$){let S=["preSubcommand","preAction","postAction"];if(!S.includes(j))throw Error(`Unexpected value for event passed to hook : '${j}'.
14
- Expecting one of '${S.join("', '")}'`);if(this._lifeCycleHooks[j])this._lifeCycleHooks[j].push($);else this._lifeCycleHooks[j]=[$];return this}exitOverride(j){if(j)this._exitCallback=j;else this._exitCallback=($)=>{if($.code!=="commander.executeSubCommandAsync")throw $};return this}_exit(j,$,S){if(this._exitCallback)this._exitCallback(new o(j,$,S));M.exit(j)}action(j){let $=(S)=>{let y=this.registeredArguments.length,q=S.slice(0,y);if(this._storeOptionsAsProperties)q[y]=this;else q[y]=this.opts();return q.push(this),j.apply(this,q)};return this._actionHandler=$,this}createOption(j,$){return new Bj(j,$)}_callParseArg(j,$,S,y){try{return j.parseArg($,S)}catch(q){if(q.code==="commander.invalidArgument"){let R=`${y} ${q.message}`;this.error(R,{exitCode:q.exitCode,code:q.code})}throw q}}_registerOption(j){let $=j.short&&this._findOption(j.short)||j.long&&this._findOption(j.long);if($){let S=j.long&&this._findOption(j.long)?j.long:j.short;throw Error(`Cannot add option '${j.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${S}'
15
- - already used by option '${$.flags}'`)}this.options.push(j)}_registerCommand(j){let $=(y)=>{return[y.name()].concat(y.aliases())},S=$(j).find((y)=>this._findCommand(y));if(S){let y=$(this._findCommand(S)).join("|"),q=$(j).join("|");throw Error(`cannot add command '${q}' as already have command '${y}'`)}this.commands.push(j)}addOption(j){this._registerOption(j);let $=j.name(),S=j.attributeName();if(j.negate){let q=j.long.replace(/^--no-/,"--");if(!this._findOption(q))this.setOptionValueWithSource(S,j.defaultValue===void 0?!0:j.defaultValue,"default")}else if(j.defaultValue!==void 0)this.setOptionValueWithSource(S,j.defaultValue,"default");let y=(q,R,I)=>{if(q==null&&j.presetArg!==void 0)q=j.presetArg;let E=this.getOptionValue(S);if(q!==null&&j.parseArg)q=this._callParseArg(j,q,E,R);else if(q!==null&&j.variadic)q=j._concatValue(q,E);if(q==null)if(j.negate)q=!1;else if(j.isBoolean()||j.optional)q=!0;else q="";this.setOptionValueWithSource(S,q,I)};if(this.on("option:"+$,(q)=>{let R=`error: option '${j.flags}' argument '${q}' is invalid.`;y(q,R,"cli")}),j.envVar)this.on("optionEnv:"+$,(q)=>{let R=`error: option '${j.flags}' value '${q}' from env '${j.envVar}' is invalid.`;y(q,R,"env")});return this}_optionEx(j,$,S,y,q){if(typeof $==="object"&&$ instanceof Bj)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let R=this.createOption($,S);if(R.makeOptionMandatory(!!j.mandatory),typeof y==="function")R.default(q).argParser(y);else if(y instanceof RegExp){let I=y;y=(E,P)=>{let J=I.exec(E);return J?J[0]:P},R.default(q).argParser(y)}else R.default(y);return this.addOption(R)}option(j,$,S,y){return this._optionEx({},j,$,S,y)}requiredOption(j,$,S,y){return this._optionEx({mandatory:!0},j,$,S,y)}combineFlagAndOptionalValue(j=!0){return this._combineFlagAndOptionalValue=!!j,this}allowUnknownOption(j=!0){return this._allowUnknownOption=!!j,this}allowExcessArguments(j=!0){return this._allowExcessArguments=!!j,this}enablePositionalOptions(j=!0){return this._enablePositionalOptions=!!j,this}passThroughOptions(j=!0){return this._passThroughOptions=!!j,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(j=!0){if(this.options.length)throw Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!j,this}getOptionValue(j){if(this._storeOptionsAsProperties)return this[j];return this._optionValues[j]}setOptionValue(j,$){return this.setOptionValueWithSource(j,$,void 0)}setOptionValueWithSource(j,$,S){if(this._storeOptionsAsProperties)this[j]=$;else this._optionValues[j]=$;return this._optionValueSources[j]=S,this}getOptionValueSource(j){return this._optionValueSources[j]}getOptionValueSourceWithGlobals(j){let $;return this._getCommandAndAncestors().forEach((S)=>{if(S.getOptionValueSource(j)!==void 0)$=S.getOptionValueSource(j)}),$}_prepareUserArgs(j,$){if(j!==void 0&&!Array.isArray(j))throw Error("first parameter to parse must be array or undefined");if($=$||{},j===void 0&&$.from===void 0){if(M.versions?.electron)$.from="electron";let y=M.execArgv??[];if(y.includes("-e")||y.includes("--eval")||y.includes("-p")||y.includes("--print"))$.from="eval"}if(j===void 0)j=M.argv;this.rawArgs=j.slice();let S;switch($.from){case void 0:case"node":this._scriptPath=j[1],S=j.slice(2);break;case"electron":if(M.defaultApp)this._scriptPath=j[1],S=j.slice(2);else S=j.slice(1);break;case"user":S=j.slice(0);break;case"eval":S=j.slice(1);break;default:throw Error(`unexpected parse option { from: '${$.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);return this._name=this._name||"program",S}parse(j,$){let S=this._prepareUserArgs(j,$);return this._parseCommand([],S),this}async parseAsync(j,$){let S=this._prepareUserArgs(j,$);return await this._parseCommand([],S),this}_executeSubCommand(j,$){$=$.slice();let S=!1,y=[".js",".ts",".tsx",".mjs",".cjs"];function q(J,Y){let Z=z.resolve(J,Y);if(p.existsSync(Z))return Z;if(y.includes(z.extname(Y)))return;let X=y.find((G)=>p.existsSync(`${Z}${G}`));if(X)return`${Z}${X}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let R=j._executableFile||`${this._name}-${j._name}`,I=this._executableDir||"";if(this._scriptPath){let J;try{J=p.realpathSync(this._scriptPath)}catch(Y){J=this._scriptPath}I=z.resolve(z.dirname(J),I)}if(I){let J=q(I,R);if(!J&&!j._executableFile&&this._scriptPath){let Y=z.basename(this._scriptPath,z.extname(this._scriptPath));if(Y!==this._name)J=q(I,`${Y}-${j._name}`)}R=J||R}S=y.includes(z.extname(R));let E;if(M.platform!=="win32")if(S)$.unshift(R),$=Vj(M.execArgv).concat($),E=i.spawn(M.argv[0],$,{stdio:"inherit"});else E=i.spawn(R,$,{stdio:"inherit"});else $.unshift(R),$=Vj(M.execArgv).concat($),E=i.spawn(M.execPath,$,{stdio:"inherit"});if(!E.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((Y)=>{M.on(Y,()=>{if(E.killed===!1&&E.exitCode===null)E.kill(Y)})});let P=this._exitCallback;E.on("close",(J)=>{if(J=J??1,!P)M.exit(J);else P(new o(J,"commander.executeSubCommandAsync","(close)"))}),E.on("error",(J)=>{if(J.code==="ENOENT"){let Y=I?`searched for local subcommand relative to directory '${I}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",Z=`'${R}' does not exist
16
- - if '${j._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
7
+ `),I=" ".repeat(j),Z=`\\s${"​"}`,X=new RegExp(`
8
+ |.{1,${q-1}}([${Z}]|$)|[^${Z}]+?([${Z}]|$)`,"g"),c=U.match(X)||[];return S+c.map((H,yy)=>{if(H===`
9
+ `)return"";return(yy>0?I:"")+H.trimEnd()}).join(`
10
+ `)}}Ej.Help=vy});var Gy=B((Zj)=>{var{InvalidArgumentError:Lj}=u();class hy{constructor(y,$){this.flags=y,this.description=$||"",this.required=y.includes("<"),this.optional=y.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(y),this.mandatory=!1;let j=Jj(y);if(this.short=j.shortFlag,this.long=j.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(y,$){return this.defaultValue=y,this.defaultValueDescription=$,this}preset(y){return this.presetArg=y,this}conflicts(y){return this.conflictsWith=this.conflictsWith.concat(y),this}implies(y){let $=y;if(typeof y==="string")$={[y]:!0};return this.implied=Object.assign(this.implied||{},$),this}env(y){return this.envVar=y,this}argParser(y){return this.parseArg=y,this}makeOptionMandatory(y=!0){return this.mandatory=!!y,this}hideHelp(y=!0){return this.hidden=!!y,this}_concatValue(y,$){if($===this.defaultValue||!Array.isArray($))return[y];return $.concat(y)}choices(y){return this.argChoices=y.slice(),this.parseArg=($,j)=>{if(!this.argChoices.includes($))throw new Lj(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue($,j);return $},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){return Qj(this.name().replace(/^no-/,""))}is(y){return this.short===y||this.long===y}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class Oy{constructor(y){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,y.forEach(($)=>{if($.negate)this.negativeOptions.set($.attributeName(),$);else this.positiveOptions.set($.attributeName(),$)}),this.negativeOptions.forEach(($,j)=>{if(this.positiveOptions.has(j))this.dualOptions.add(j)})}valueFromOption(y,$){let j=$.attributeName();if(!this.dualOptions.has(j))return!0;let G=this.negativeOptions.get(j).presetArg,P=G!==void 0?G:!1;return $.negate===(P===y)}}function Qj(y){return y.split("-").reduce(($,j)=>{return $+j[0].toUpperCase()+j.slice(1)})}function Jj(y){let $,j,G=y.split(/[ |,]+/);if(G.length>1&&!/^[[<]/.test(G[1]))$=G.shift();if(j=G.shift(),!$&&/^-[^-]$/.test(j))$=j,j=void 0;return{shortFlag:$,longFlag:j}}Zj.Option=hy;Zj.DualOptions=Oy});var uy=B((Fj)=>{function wj(y,$){if(Math.abs(y.length-$.length)>3)return Math.max(y.length,$.length);let j=[];for(let G=0;G<=y.length;G++)j[G]=[G];for(let G=0;G<=$.length;G++)j[0][G]=G;for(let G=1;G<=$.length;G++)for(let P=1;P<=y.length;P++){let R=1;if(y[P-1]===$[G-1])R=0;else R=1;if(j[P][G]=Math.min(j[P-1][G]+1,j[P][G-1]+1,j[P-1][G-1]+R),P>1&&G>1&&y[P-1]===$[G-2]&&y[P-2]===$[G-1])j[P][G]=Math.min(j[P][G],j[P-2][G-2]+1)}return j[y.length][$.length]}function Xj(y,$){if(!$||$.length===0)return"";$=Array.from(new Set($));let j=y.startsWith("--");if(j)y=y.slice(2),$=$.map((q)=>q.slice(2));let G=[],P=3,R=0.4;if($.forEach((q)=>{if(q.length<=1)return;let S=wj(y,q),U=Math.max(y.length,q.length);if((U-S)/U>R){if(S<P)P=S,G=[q];else if(S===P)G.push(q)}}),G.sort((q,S)=>q.localeCompare(S)),j)G=G.map((q)=>`--${q}`);if(G.length>1)return`
11
+ (Did you mean one of ${G.join(", ")}?)`;if(G.length===1)return`
12
+ (Did you mean ${G[0]}?)`;return""}Fj.suggestSimilar=Xj});var ly=B((Kj)=>{var zj=O("node:events").EventEmitter,Py=O("node:child_process"),z=O("node:path"),Ry=O("node:fs"),w=O("node:process"),{Argument:Hj,humanReadableArgName:Wj}=s(),{CommanderError:qy}=u(),{Help:Mj}=jy(),{Option:gy,DualOptions:fj}=Gy(),{suggestSimilar:ty}=uy();class Sy extends zj{constructor(y){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=y||"",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:($)=>w.stdout.write($),writeErr:($)=>w.stderr.write($),getOutHelpWidth:()=>w.stdout.isTTY?w.stdout.columns:void 0,getErrHelpWidth:()=>w.stderr.isTTY?w.stderr.columns:void 0,outputError:($,j)=>j($)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(y){return this._outputConfiguration=y._outputConfiguration,this._helpOption=y._helpOption,this._helpCommand=y._helpCommand,this._helpConfiguration=y._helpConfiguration,this._exitCallback=y._exitCallback,this._storeOptionsAsProperties=y._storeOptionsAsProperties,this._combineFlagAndOptionalValue=y._combineFlagAndOptionalValue,this._allowExcessArguments=y._allowExcessArguments,this._enablePositionalOptions=y._enablePositionalOptions,this._showHelpAfterError=y._showHelpAfterError,this._showSuggestionAfterError=y._showSuggestionAfterError,this}_getCommandAndAncestors(){let y=[];for(let $=this;$;$=$.parent)y.push($);return y}command(y,$,j){let G=$,P=j;if(typeof G==="object"&&G!==null)P=G,G=null;P=P||{};let[,R,q]=y.match(/([^ ]+) *(.*)/),S=this.createCommand(R);if(G)S.description(G),S._executableHandler=!0;if(P.isDefault)this._defaultCommandName=S._name;if(S._hidden=!!(P.noHelp||P.hidden),S._executableFile=P.executableFile||null,q)S.arguments(q);if(this._registerCommand(S),S.parent=this,S.copyInheritedSettings(this),G)return this;return S}createCommand(y){return new Sy(y)}createHelp(){return Object.assign(new Mj,this.configureHelp())}configureHelp(y){if(y===void 0)return this._helpConfiguration;return this._helpConfiguration=y,this}configureOutput(y){if(y===void 0)return this._outputConfiguration;return Object.assign(this._outputConfiguration,y),this}showHelpAfterError(y=!0){if(typeof y!=="string")y=!!y;return this._showHelpAfterError=y,this}showSuggestionAfterError(y=!0){return this._showSuggestionAfterError=!!y,this}addCommand(y,$){if(!y._name)throw Error(`Command passed to .addCommand() must have a name
13
+ - specify the name in Command constructor or using .name()`);if($=$||{},$.isDefault)this._defaultCommandName=y._name;if($.noHelp||$.hidden)y._hidden=!0;return this._registerCommand(y),y.parent=this,y._checkForBrokenPassThrough(),this}createArgument(y,$){return new Hj(y,$)}argument(y,$,j,G){let P=this.createArgument(y,$);if(typeof j==="function")P.default(G).argParser(j);else P.default(j);return this.addArgument(P),this}arguments(y){return y.trim().split(/ +/).forEach(($)=>{this.argument($)}),this}addArgument(y){let $=this.registeredArguments.slice(-1)[0];if($&&$.variadic)throw Error(`only the last argument can be variadic '${$.name()}'`);if(y.required&&y.defaultValue!==void 0&&y.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${y.name()}'`);return this.registeredArguments.push(y),this}helpCommand(y,$){if(typeof y==="boolean")return this._addImplicitHelpCommand=y,this;y=y??"help [command]";let[,j,G]=y.match(/([^ ]+) *(.*)/),P=$??"display help for command",R=this.createCommand(j);if(R.helpOption(!1),G)R.arguments(G);if(P)R.description(P);return this._addImplicitHelpCommand=!0,this._helpCommand=R,this}addHelpCommand(y,$){if(typeof y!=="object")return this.helpCommand(y,$),this;return this._addImplicitHelpCommand=!0,this._helpCommand=y,this}_getHelpCommand(){if(this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))){if(this._helpCommand===void 0)this.helpCommand(void 0,void 0);return this._helpCommand}return null}hook(y,$){let j=["preSubcommand","preAction","postAction"];if(!j.includes(y))throw Error(`Unexpected value for event passed to hook : '${y}'.
14
+ Expecting one of '${j.join("', '")}'`);if(this._lifeCycleHooks[y])this._lifeCycleHooks[y].push($);else this._lifeCycleHooks[y]=[$];return this}exitOverride(y){if(y)this._exitCallback=y;else this._exitCallback=($)=>{if($.code!=="commander.executeSubCommandAsync")throw $};return this}_exit(y,$,j){if(this._exitCallback)this._exitCallback(new qy(y,$,j));w.exit(y)}action(y){let $=(j)=>{let G=this.registeredArguments.length,P=j.slice(0,G);if(this._storeOptionsAsProperties)P[G]=this;else P[G]=this.opts();return P.push(this),y.apply(this,P)};return this._actionHandler=$,this}createOption(y,$){return new gy(y,$)}_callParseArg(y,$,j,G){try{return y.parseArg($,j)}catch(P){if(P.code==="commander.invalidArgument"){let R=`${G} ${P.message}`;this.error(R,{exitCode:P.exitCode,code:P.code})}throw P}}_registerOption(y){let $=y.short&&this._findOption(y.short)||y.long&&this._findOption(y.long);if($){let j=y.long&&this._findOption(y.long)?y.long:y.short;throw Error(`Cannot add option '${y.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${j}'
15
+ - already used by option '${$.flags}'`)}this.options.push(y)}_registerCommand(y){let $=(G)=>{return[G.name()].concat(G.aliases())},j=$(y).find((G)=>this._findCommand(G));if(j){let G=$(this._findCommand(j)).join("|"),P=$(y).join("|");throw Error(`cannot add command '${P}' as already have command '${G}'`)}this.commands.push(y)}addOption(y){this._registerOption(y);let $=y.name(),j=y.attributeName();if(y.negate){let P=y.long.replace(/^--no-/,"--");if(!this._findOption(P))this.setOptionValueWithSource(j,y.defaultValue===void 0?!0:y.defaultValue,"default")}else if(y.defaultValue!==void 0)this.setOptionValueWithSource(j,y.defaultValue,"default");let G=(P,R,q)=>{if(P==null&&y.presetArg!==void 0)P=y.presetArg;let S=this.getOptionValue(j);if(P!==null&&y.parseArg)P=this._callParseArg(y,P,S,R);else if(P!==null&&y.variadic)P=y._concatValue(P,S);if(P==null)if(y.negate)P=!1;else if(y.isBoolean()||y.optional)P=!0;else P="";this.setOptionValueWithSource(j,P,q)};if(this.on("option:"+$,(P)=>{let R=`error: option '${y.flags}' argument '${P}' is invalid.`;G(P,R,"cli")}),y.envVar)this.on("optionEnv:"+$,(P)=>{let R=`error: option '${y.flags}' value '${P}' from env '${y.envVar}' is invalid.`;G(P,R,"env")});return this}_optionEx(y,$,j,G,P){if(typeof $==="object"&&$ instanceof gy)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let R=this.createOption($,j);if(R.makeOptionMandatory(!!y.mandatory),typeof G==="function")R.default(P).argParser(G);else if(G instanceof RegExp){let q=G;G=(S,U)=>{let I=q.exec(S);return I?I[0]:U},R.default(P).argParser(G)}else R.default(G);return this.addOption(R)}option(y,$,j,G){return this._optionEx({},y,$,j,G)}requiredOption(y,$,j,G){return this._optionEx({mandatory:!0},y,$,j,G)}combineFlagAndOptionalValue(y=!0){return this._combineFlagAndOptionalValue=!!y,this}allowUnknownOption(y=!0){return this._allowUnknownOption=!!y,this}allowExcessArguments(y=!0){return this._allowExcessArguments=!!y,this}enablePositionalOptions(y=!0){return this._enablePositionalOptions=!!y,this}passThroughOptions(y=!0){return this._passThroughOptions=!!y,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(y=!0){if(this.options.length)throw Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!y,this}getOptionValue(y){if(this._storeOptionsAsProperties)return this[y];return this._optionValues[y]}setOptionValue(y,$){return this.setOptionValueWithSource(y,$,void 0)}setOptionValueWithSource(y,$,j){if(this._storeOptionsAsProperties)this[y]=$;else this._optionValues[y]=$;return this._optionValueSources[y]=j,this}getOptionValueSource(y){return this._optionValueSources[y]}getOptionValueSourceWithGlobals(y){let $;return this._getCommandAndAncestors().forEach((j)=>{if(j.getOptionValueSource(y)!==void 0)$=j.getOptionValueSource(y)}),$}_prepareUserArgs(y,$){if(y!==void 0&&!Array.isArray(y))throw Error("first parameter to parse must be array or undefined");if($=$||{},y===void 0&&$.from===void 0){if(w.versions?.electron)$.from="electron";let G=w.execArgv??[];if(G.includes("-e")||G.includes("--eval")||G.includes("-p")||G.includes("--print"))$.from="eval"}if(y===void 0)y=w.argv;this.rawArgs=y.slice();let j;switch($.from){case void 0:case"node":this._scriptPath=y[1],j=y.slice(2);break;case"electron":if(w.defaultApp)this._scriptPath=y[1],j=y.slice(2);else j=y.slice(1);break;case"user":j=y.slice(0);break;case"eval":j=y.slice(1);break;default:throw Error(`unexpected parse option { from: '${$.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);return this._name=this._name||"program",j}parse(y,$){let j=this._prepareUserArgs(y,$);return this._parseCommand([],j),this}async parseAsync(y,$){let j=this._prepareUserArgs(y,$);return await this._parseCommand([],j),this}_executeSubCommand(y,$){$=$.slice();let j=!1,G=[".js",".ts",".tsx",".mjs",".cjs"];function P(I,J){let Z=z.resolve(I,J);if(Ry.existsSync(Z))return Z;if(G.includes(z.extname(J)))return;let X=G.find((c)=>Ry.existsSync(`${Z}${c}`));if(X)return`${Z}${X}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let R=y._executableFile||`${this._name}-${y._name}`,q=this._executableDir||"";if(this._scriptPath){let I;try{I=Ry.realpathSync(this._scriptPath)}catch(J){I=this._scriptPath}q=z.resolve(z.dirname(I),q)}if(q){let I=P(q,R);if(!I&&!y._executableFile&&this._scriptPath){let J=z.basename(this._scriptPath,z.extname(this._scriptPath));if(J!==this._name)I=P(q,`${J}-${y._name}`)}R=I||R}j=G.includes(z.extname(R));let S;if(w.platform!=="win32")if(j)$.unshift(R),$=my(w.execArgv).concat($),S=Py.spawn(w.argv[0],$,{stdio:"inherit"});else S=Py.spawn(R,$,{stdio:"inherit"});else $.unshift(R),$=my(w.execArgv).concat($),S=Py.spawn(w.execPath,$,{stdio:"inherit"});if(!S.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((J)=>{w.on(J,()=>{if(S.killed===!1&&S.exitCode===null)S.kill(J)})});let U=this._exitCallback;S.on("close",(I)=>{if(I=I??1,!U)w.exit(I);else U(new qy(I,"commander.executeSubCommandAsync","(close)"))}),S.on("error",(I)=>{if(I.code==="ENOENT"){let J=q?`searched for local subcommand relative to directory '${q}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",Z=`'${R}' does not exist
16
+ - if '${y._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
17
17
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
18
- - ${Y}`;throw Error(Z)}else if(J.code==="EACCES")throw Error(`'${R}' not executable`);if(!P)M.exit(1);else{let Y=new o(1,"commander.executeSubCommandAsync","(error)");Y.nestedError=J,P(Y)}}),this.runningCommand=E}_dispatchSubcommand(j,$,S){let y=this._findCommand(j);if(!y)this.help({error:!0});let q;return q=this._chainOrCallSubCommandHook(q,y,"preSubcommand"),q=this._chainOrCall(q,()=>{if(y._executableHandler)this._executeSubCommand(y,$.concat(S));else return y._parseCommand($,S)}),q}_dispatchHelpCommand(j){if(!j)this.help();let $=this._findCommand(j);if($&&!$._executableHandler)$.help();return this._dispatchSubcommand(j,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){if(this.registeredArguments.forEach((j,$)=>{if(j.required&&this.args[$]==null)this.missingArgument(j.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)return;if(this.args.length>this.registeredArguments.length)this._excessArguments(this.args)}_processArguments(){let j=(S,y,q)=>{let R=y;if(y!==null&&S.parseArg){let I=`error: command-argument value '${y}' is invalid for argument '${S.name()}'.`;R=this._callParseArg(S,y,q,I)}return R};this._checkNumberOfArguments();let $=[];this.registeredArguments.forEach((S,y)=>{let q=S.defaultValue;if(S.variadic){if(y<this.args.length){if(q=this.args.slice(y),S.parseArg)q=q.reduce((R,I)=>{return j(S,I,R)},S.defaultValue)}else if(q===void 0)q=[]}else if(y<this.args.length){if(q=this.args[y],S.parseArg)q=j(S,q,S.defaultValue)}$[y]=q}),this.processedArgs=$}_chainOrCall(j,$){if(j&&j.then&&typeof j.then==="function")return j.then(()=>$());return $()}_chainOrCallHooks(j,$){let S=j,y=[];if(this._getCommandAndAncestors().reverse().filter((q)=>q._lifeCycleHooks[$]!==void 0).forEach((q)=>{q._lifeCycleHooks[$].forEach((R)=>{y.push({hookedCommand:q,callback:R})})}),$==="postAction")y.reverse();return y.forEach((q)=>{S=this._chainOrCall(S,()=>{return q.callback(q.hookedCommand,this)})}),S}_chainOrCallSubCommandHook(j,$,S){let y=j;if(this._lifeCycleHooks[S]!==void 0)this._lifeCycleHooks[S].forEach((q)=>{y=this._chainOrCall(y,()=>{return q(this,$)})});return y}_parseCommand(j,$){let S=this.parseOptions($);if(this._parseOptionsEnv(),this._parseOptionsImplied(),j=j.concat(S.operands),$=S.unknown,this.args=j.concat($),j&&this._findCommand(j[0]))return this._dispatchSubcommand(j[0],j.slice(1),$);if(this._getHelpCommand()&&j[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(j[1]);if(this._defaultCommandName)return this._outputHelpIfRequested($),this._dispatchSubcommand(this._defaultCommandName,j,$);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});this._outputHelpIfRequested(S.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let y=()=>{if(S.unknown.length>0)this.unknownOption(S.unknown[0])},q=`command:${this.name()}`;if(this._actionHandler){y(),this._processArguments();let R;if(R=this._chainOrCallHooks(R,"preAction"),R=this._chainOrCall(R,()=>this._actionHandler(this.processedArgs)),this.parent)R=this._chainOrCall(R,()=>{this.parent.emit(q,j,$)});return R=this._chainOrCallHooks(R,"postAction"),R}if(this.parent&&this.parent.listenerCount(q))y(),this._processArguments(),this.parent.emit(q,j,$);else if(j.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",j,$);if(this.listenerCount("command:*"))this.emit("command:*",j,$);else if(this.commands.length)this.unknownCommand();else y(),this._processArguments()}else if(this.commands.length)y(),this.help({error:!0});else y(),this._processArguments()}_findCommand(j){if(!j)return;return this.commands.find(($)=>$._name===j||$._aliases.includes(j))}_findOption(j){return this.options.find(($)=>$.is(j))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach((j)=>{j.options.forEach(($)=>{if($.mandatory&&j.getOptionValue($.attributeName())===void 0)j.missingMandatoryOptionValue($)})})}_checkForConflictingLocalOptions(){let j=this.options.filter((S)=>{let y=S.attributeName();if(this.getOptionValue(y)===void 0)return!1;return this.getOptionValueSource(y)!=="default"});j.filter((S)=>S.conflictsWith.length>0).forEach((S)=>{let y=j.find((q)=>S.conflictsWith.includes(q.attributeName()));if(y)this._conflictingOption(S,y)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach((j)=>{j._checkForConflictingLocalOptions()})}parseOptions(j){let $=[],S=[],y=$,q=j.slice();function R(E){return E.length>1&&E[0]==="-"}let I=null;while(q.length){let E=q.shift();if(E==="--"){if(y===S)y.push(E);y.push(...q);break}if(I&&!R(E)){this.emit(`option:${I.name()}`,E);continue}if(I=null,R(E)){let P=this._findOption(E);if(P){if(P.required){let J=q.shift();if(J===void 0)this.optionMissingArgument(P);this.emit(`option:${P.name()}`,J)}else if(P.optional){let J=null;if(q.length>0&&!R(q[0]))J=q.shift();this.emit(`option:${P.name()}`,J)}else this.emit(`option:${P.name()}`);I=P.variadic?P:null;continue}}if(E.length>2&&E[0]==="-"&&E[1]!=="-"){let P=this._findOption(`-${E[1]}`);if(P){if(P.required||P.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${P.name()}`,E.slice(2));else this.emit(`option:${P.name()}`),q.unshift(`-${E.slice(2)}`);continue}}if(/^--[^=]+=/.test(E)){let P=E.indexOf("="),J=this._findOption(E.slice(0,P));if(J&&(J.required||J.optional)){this.emit(`option:${J.name()}`,E.slice(P+1));continue}}if(R(E))y=S;if((this._enablePositionalOptions||this._passThroughOptions)&&$.length===0&&S.length===0){if(this._findCommand(E)){if($.push(E),q.length>0)S.push(...q);break}else if(this._getHelpCommand()&&E===this._getHelpCommand().name()){if($.push(E),q.length>0)$.push(...q);break}else if(this._defaultCommandName){if(S.push(E),q.length>0)S.push(...q);break}}if(this._passThroughOptions){if(y.push(E),q.length>0)y.push(...q);break}y.push(E)}return{operands:$,unknown:S}}opts(){if(this._storeOptionsAsProperties){let j={},$=this.options.length;for(let S=0;S<$;S++){let y=this.options[S].attributeName();j[y]=y===this._versionOptionName?this._version:this[y]}return j}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((j,$)=>Object.assign(j,$.opts()),{})}error(j,$){if(this._outputConfiguration.outputError(`${j}
18
+ - ${J}`;throw Error(Z)}else if(I.code==="EACCES")throw Error(`'${R}' not executable`);if(!U)w.exit(1);else{let J=new qy(1,"commander.executeSubCommandAsync","(error)");J.nestedError=I,U(J)}}),this.runningCommand=S}_dispatchSubcommand(y,$,j){let G=this._findCommand(y);if(!G)this.help({error:!0});let P;return P=this._chainOrCallSubCommandHook(P,G,"preSubcommand"),P=this._chainOrCall(P,()=>{if(G._executableHandler)this._executeSubCommand(G,$.concat(j));else return G._parseCommand($,j)}),P}_dispatchHelpCommand(y){if(!y)this.help();let $=this._findCommand(y);if($&&!$._executableHandler)$.help();return this._dispatchSubcommand(y,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){if(this.registeredArguments.forEach((y,$)=>{if(y.required&&this.args[$]==null)this.missingArgument(y.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)return;if(this.args.length>this.registeredArguments.length)this._excessArguments(this.args)}_processArguments(){let y=(j,G,P)=>{let R=G;if(G!==null&&j.parseArg){let q=`error: command-argument value '${G}' is invalid for argument '${j.name()}'.`;R=this._callParseArg(j,G,P,q)}return R};this._checkNumberOfArguments();let $=[];this.registeredArguments.forEach((j,G)=>{let P=j.defaultValue;if(j.variadic){if(G<this.args.length){if(P=this.args.slice(G),j.parseArg)P=P.reduce((R,q)=>{return y(j,q,R)},j.defaultValue)}else if(P===void 0)P=[]}else if(G<this.args.length){if(P=this.args[G],j.parseArg)P=y(j,P,j.defaultValue)}$[G]=P}),this.processedArgs=$}_chainOrCall(y,$){if(y&&y.then&&typeof y.then==="function")return y.then(()=>$());return $()}_chainOrCallHooks(y,$){let j=y,G=[];if(this._getCommandAndAncestors().reverse().filter((P)=>P._lifeCycleHooks[$]!==void 0).forEach((P)=>{P._lifeCycleHooks[$].forEach((R)=>{G.push({hookedCommand:P,callback:R})})}),$==="postAction")G.reverse();return G.forEach((P)=>{j=this._chainOrCall(j,()=>{return P.callback(P.hookedCommand,this)})}),j}_chainOrCallSubCommandHook(y,$,j){let G=y;if(this._lifeCycleHooks[j]!==void 0)this._lifeCycleHooks[j].forEach((P)=>{G=this._chainOrCall(G,()=>{return P(this,$)})});return G}_parseCommand(y,$){let j=this.parseOptions($);if(this._parseOptionsEnv(),this._parseOptionsImplied(),y=y.concat(j.operands),$=j.unknown,this.args=y.concat($),y&&this._findCommand(y[0]))return this._dispatchSubcommand(y[0],y.slice(1),$);if(this._getHelpCommand()&&y[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(y[1]);if(this._defaultCommandName)return this._outputHelpIfRequested($),this._dispatchSubcommand(this._defaultCommandName,y,$);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});this._outputHelpIfRequested(j.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let G=()=>{if(j.unknown.length>0)this.unknownOption(j.unknown[0])},P=`command:${this.name()}`;if(this._actionHandler){G(),this._processArguments();let R;if(R=this._chainOrCallHooks(R,"preAction"),R=this._chainOrCall(R,()=>this._actionHandler(this.processedArgs)),this.parent)R=this._chainOrCall(R,()=>{this.parent.emit(P,y,$)});return R=this._chainOrCallHooks(R,"postAction"),R}if(this.parent&&this.parent.listenerCount(P))G(),this._processArguments(),this.parent.emit(P,y,$);else if(y.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",y,$);if(this.listenerCount("command:*"))this.emit("command:*",y,$);else if(this.commands.length)this.unknownCommand();else G(),this._processArguments()}else if(this.commands.length)G(),this.help({error:!0});else G(),this._processArguments()}_findCommand(y){if(!y)return;return this.commands.find(($)=>$._name===y||$._aliases.includes(y))}_findOption(y){return this.options.find(($)=>$.is(y))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach((y)=>{y.options.forEach(($)=>{if($.mandatory&&y.getOptionValue($.attributeName())===void 0)y.missingMandatoryOptionValue($)})})}_checkForConflictingLocalOptions(){let y=this.options.filter((j)=>{let G=j.attributeName();if(this.getOptionValue(G)===void 0)return!1;return this.getOptionValueSource(G)!=="default"});y.filter((j)=>j.conflictsWith.length>0).forEach((j)=>{let G=y.find((P)=>j.conflictsWith.includes(P.attributeName()));if(G)this._conflictingOption(j,G)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach((y)=>{y._checkForConflictingLocalOptions()})}parseOptions(y){let $=[],j=[],G=$,P=y.slice();function R(S){return S.length>1&&S[0]==="-"}let q=null;while(P.length){let S=P.shift();if(S==="--"){if(G===j)G.push(S);G.push(...P);break}if(q&&!R(S)){this.emit(`option:${q.name()}`,S);continue}if(q=null,R(S)){let U=this._findOption(S);if(U){if(U.required){let I=P.shift();if(I===void 0)this.optionMissingArgument(U);this.emit(`option:${U.name()}`,I)}else if(U.optional){let I=null;if(P.length>0&&!R(P[0]))I=P.shift();this.emit(`option:${U.name()}`,I)}else this.emit(`option:${U.name()}`);q=U.variadic?U:null;continue}}if(S.length>2&&S[0]==="-"&&S[1]!=="-"){let U=this._findOption(`-${S[1]}`);if(U){if(U.required||U.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${U.name()}`,S.slice(2));else this.emit(`option:${U.name()}`),P.unshift(`-${S.slice(2)}`);continue}}if(/^--[^=]+=/.test(S)){let U=S.indexOf("="),I=this._findOption(S.slice(0,U));if(I&&(I.required||I.optional)){this.emit(`option:${I.name()}`,S.slice(U+1));continue}}if(R(S))G=j;if((this._enablePositionalOptions||this._passThroughOptions)&&$.length===0&&j.length===0){if(this._findCommand(S)){if($.push(S),P.length>0)j.push(...P);break}else if(this._getHelpCommand()&&S===this._getHelpCommand().name()){if($.push(S),P.length>0)$.push(...P);break}else if(this._defaultCommandName){if(j.push(S),P.length>0)j.push(...P);break}}if(this._passThroughOptions){if(G.push(S),P.length>0)G.push(...P);break}G.push(S)}return{operands:$,unknown:j}}opts(){if(this._storeOptionsAsProperties){let y={},$=this.options.length;for(let j=0;j<$;j++){let G=this.options[j].attributeName();y[G]=G===this._versionOptionName?this._version:this[G]}return y}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((y,$)=>Object.assign(y,$.opts()),{})}error(y,$){if(this._outputConfiguration.outputError(`${y}
19
19
  `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==="string")this._outputConfiguration.writeErr(`${this._showHelpAfterError}
20
20
  `);else if(this._showHelpAfterError)this._outputConfiguration.writeErr(`
21
- `),this.outputHelp({error:!0});let S=$||{},y=S.exitCode||1,q=S.code||"commander.error";this._exit(y,q,j)}_parseOptionsEnv(){this.options.forEach((j)=>{if(j.envVar&&j.envVar in M.env){let $=j.attributeName();if(this.getOptionValue($)===void 0||["default","config","env"].includes(this.getOptionValueSource($)))if(j.required||j.optional)this.emit(`optionEnv:${j.name()}`,M.env[j.envVar]);else this.emit(`optionEnv:${j.name()}`)}})}_parseOptionsImplied(){let j=new g$(this.options),$=(S)=>{return this.getOptionValue(S)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(S))};this.options.filter((S)=>S.implied!==void 0&&$(S.attributeName())&&j.valueFromOption(this.getOptionValue(S.attributeName()),S)).forEach((S)=>{Object.keys(S.implied).filter((y)=>!$(y)).forEach((y)=>{this.setOptionValueWithSource(y,S.implied[y],"implied")})})}missingArgument(j){let $=`error: missing required argument '${j}'`;this.error($,{code:"commander.missingArgument"})}optionMissingArgument(j){let $=`error: option '${j.flags}' argument missing`;this.error($,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(j){let $=`error: required option '${j.flags}' not specified`;this.error($,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(j,$){let S=(R)=>{let I=R.attributeName(),E=this.getOptionValue(I),P=this.options.find((Y)=>Y.negate&&I===Y.attributeName()),J=this.options.find((Y)=>!Y.negate&&I===Y.attributeName());if(P&&(P.presetArg===void 0&&E===!1||P.presetArg!==void 0&&E===P.presetArg))return P;return J||R},y=(R)=>{let I=S(R),E=I.attributeName();if(this.getOptionValueSource(E)==="env")return`environment variable '${I.envVar}'`;return`option '${I.flags}'`},q=`error: ${y(j)} cannot be used with ${y($)}`;this.error(q,{code:"commander.conflictingOption"})}unknownOption(j){if(this._allowUnknownOption)return;let $="";if(j.startsWith("--")&&this._showSuggestionAfterError){let y=[],q=this;do{let R=q.createHelp().visibleOptions(q).filter((I)=>I.long).map((I)=>I.long);y=y.concat(R),q=q.parent}while(q&&!q._enablePositionalOptions);$=Nj(j,y)}let S=`error: unknown option '${j}'${$}`;this.error(S,{code:"commander.unknownOption"})}_excessArguments(j){if(this._allowExcessArguments)return;let $=this.registeredArguments.length,S=$===1?"":"s",q=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${$} argument${S} but got ${j.length}.`;this.error(q,{code:"commander.excessArguments"})}unknownCommand(){let j=this.args[0],$="";if(this._showSuggestionAfterError){let y=[];this.createHelp().visibleCommands(this).forEach((q)=>{if(y.push(q.name()),q.alias())y.push(q.alias())}),$=Nj(j,y)}let S=`error: unknown command '${j}'${$}`;this.error(S,{code:"commander.unknownCommand"})}version(j,$,S){if(j===void 0)return this._version;this._version=j,$=$||"-V, --version",S=S||"output the version number";let y=this.createOption($,S);return this._versionOptionName=y.attributeName(),this._registerOption(y),this.on("option:"+y.name(),()=>{this._outputConfiguration.writeOut(`${j}
22
- `),this._exit(0,"commander.version",j)}),this}description(j,$){if(j===void 0&&$===void 0)return this._description;if(this._description=j,$)this._argsDescription=$;return this}summary(j){if(j===void 0)return this._summary;return this._summary=j,this}alias(j){if(j===void 0)return this._aliases[0];let $=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)$=this.commands[this.commands.length-1];if(j===$._name)throw Error("Command alias can't be the same as its name");let S=this.parent?._findCommand(j);if(S){let y=[S.name()].concat(S.aliases()).join("|");throw Error(`cannot add alias '${j}' to command '${this.name()}' as already have command '${y}'`)}return $._aliases.push(j),this}aliases(j){if(j===void 0)return this._aliases;return j.forEach(($)=>this.alias($)),this}usage(j){if(j===void 0){if(this._usage)return this._usage;let $=this.registeredArguments.map((S)=>{return v$(S)});return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?$:[]).join(" ")}return this._usage=j,this}name(j){if(j===void 0)return this._name;return this._name=j,this}nameFromFilename(j){return this._name=z.basename(j,z.extname(j)),this}executableDir(j){if(j===void 0)return this._executableDir;return this._executableDir=j,this}helpInformation(j){let $=this.createHelp();if($.helpWidth===void 0)$.helpWidth=j&&j.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth();return $.formatHelp(this,$)}_getHelpContext(j){j=j||{};let $={error:!!j.error},S;if($.error)S=(y)=>this._outputConfiguration.writeErr(y);else S=(y)=>this._outputConfiguration.writeOut(y);return $.write=j.write||S,$.command=this,$}outputHelp(j){let $;if(typeof j==="function")$=j,j=void 0;let S=this._getHelpContext(j);this._getCommandAndAncestors().reverse().forEach((q)=>q.emit("beforeAllHelp",S)),this.emit("beforeHelp",S);let y=this.helpInformation(S);if($){if(y=$(y),typeof y!=="string"&&!Buffer.isBuffer(y))throw Error("outputHelp callback must return a string or a Buffer")}if(S.write(y),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",S),this._getCommandAndAncestors().forEach((q)=>q.emit("afterAllHelp",S))}helpOption(j,$){if(typeof j==="boolean"){if(j)this._helpOption=this._helpOption??void 0;else this._helpOption=null;return this}return j=j??"-h, --help",$=$??"display help for command",this._helpOption=this.createOption(j,$),this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption(j){return this._helpOption=j,this}help(j){this.outputHelp(j);let $=M.exitCode||0;if($===0&&j&&typeof j!=="function"&&j.error)$=1;this._exit($,"commander.help","(outputHelp)")}addHelpText(j,$){let S=["beforeAll","before","after","afterAll"];if(!S.includes(j))throw Error(`Unexpected value for position to addHelpText.
23
- Expecting one of '${S.join("', '")}'`);let y=`${j}Help`;return this.on(y,(q)=>{let R;if(typeof $==="function")R=$({error:q.error,command:q.command});else R=$;if(R)q.write(`${R}
24
- `)}),this}_outputHelpIfRequested(j){let $=this._getHelpOption();if($&&j.find((y)=>$.is(y)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function Vj(j){return j.map(($)=>{if(!$.startsWith("--inspect"))return $;let S,y="127.0.0.1",q="9229",R;if((R=$.match(/^(--inspect(-brk)?)$/))!==null)S=R[1];else if((R=$.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(S=R[1],/^\d+$/.test(R[3]))q=R[3];else y=R[3];else if((R=$.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)S=R[1],y=R[3],q=R[4];if(S&&q!=="0")return`${S}=${y}:${parseInt(q)+1}`;return $})}m$.Command=n});var Cj=F((d$)=>{var{Argument:fj}=O(),{Command:a}=Aj(),{CommanderError:r$,InvalidArgumentError:wj}=k(),{Help:l$}=l(),{Option:xj}=d();d$.program=new a;d$.createCommand=(j)=>new a(j);d$.createOption=(j,$)=>new xj(j,$);d$.createArgument=(j,$)=>new fj(j,$);d$.Command=a;d$.Option=xj;d$.Argument=fj;d$.Help=l$;d$.CommanderError=r$;d$.InvalidArgumentError=wj;d$.InvalidOptionArgumentError=wj});var kj=G$(Cj(),1),{program:W,createCommand:SS,createArgument:yS,createOption:qS,CommanderError:RS,InvalidArgumentError:ES,InvalidOptionArgumentError:IS,Command:PS,Argument:JS,Option:YS,Help:TS}=kj.default;var bj="0.1.1";import{homedir as E1}from"os";import{join as uj}from"path";import{existsSync as e,mkdirSync as I1,readFileSync as P1,writeFileSync as J1,unlinkSync as Y1}from"fs";function Oj(){let j=process.env.ACE_TEST_HOME??E1();return uj(j,".ace")}function jj(){return uj(Oj(),"credentials.json")}var T1=process.env.DEBUG==="true"||process.env.ACE_DEBUG==="true";function A(j,...$){if(T1)console.error(`[ace-cli debug] ${j}`,...$)}function Q1(){let j=Oj();if(!e(j))I1(j,{recursive:!0,mode:448})}function B(){try{let j=jj();if(!e(j))return A("Credentials file does not exist:",j),null;let $=P1(j,"utf-8"),S=JSON.parse($);if(S.expiresAt&&new Date(S.expiresAt)<new Date)return A("Token expired at:",S.expiresAt),null;return S}catch(j){return A("Error reading credentials:",j),null}}function $j(j){Q1();let $=jj();J1($,JSON.stringify(j,null,2),{mode:384}),A("Credentials saved to:",$)}function Sj(){try{let j=jj();if(e(j))return Y1(j),A("Credentials cleared"),!0;return!1}catch(j){return A("Error clearing credentials:",j),!1}}function b(){return B()?.apiUrl??process.env.ACE_API_URL??"https://aceisyourassistant.com"}import Uj from"node:process";import{Buffer as pj}from"node:buffer";import oj from"node:path";import{fileURLToPath as O1}from"node:url";import{promisify as c1}from"node:util";import nj from"node:child_process";import h1,{constants as v1}from"node:fs/promises";import tj from"node:process";import gj,{constants as z1}from"node:fs/promises";import vj from"node:process";import X1 from"node:os";import _1 from"node:fs";import G1 from"node:fs";import cj from"node:fs";var yj;function U1(){try{return cj.statSync("/.dockerenv"),!0}catch{return!1}}function Z1(){try{return cj.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function qj(){if(yj===void 0)yj=U1()||Z1();return yj}var Rj,M1=()=>{try{return G1.statSync("/run/.containerenv"),!0}catch{return!1}};function f(){if(Rj===void 0)Rj=M1()||qj();return Rj}var hj=()=>{if(vj.platform!=="linux")return!1;if(X1.release().toLowerCase().includes("microsoft")){if(f())return!1;return!0}try{return _1.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")?!f():!1}catch{return!1}},L=vj.env.__IS_WSL_TEST__?hj:hj();var W1=(()=>{let $;return async function(){if($)return $;let S="/etc/wsl.conf",y=!1;try{await gj.access(S,z1.F_OK),y=!0}catch{}if(!y)return"/mnt/";let q=await gj.readFile(S,{encoding:"utf8"}),R=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(q);if(!R)return"/mnt/";return $=R.groups.mountPoint.trim(),$=$.endsWith("/")?$:`${$}/`,$}})(),H1=async()=>{return`${await W1()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`},Ej=async()=>{if(L)return H1();return`${tj.env.SYSTEMROOT||tj.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`};function D(j,$,S){let y=(q)=>Object.defineProperty(j,$,{value:q,enumerable:!0,writable:!0});return Object.defineProperty(j,$,{configurable:!0,enumerable:!0,get(){let q=S();return y(q),q},set(q){y(q)}}),j}import{promisify as C1}from"node:util";import Tj from"node:process";import{execFile as k1}from"node:child_process";import{promisify as L1}from"node:util";import D1 from"node:process";import{execFile as K1}from"node:child_process";var F1=L1(K1);async function Ij(){if(D1.platform!=="darwin")throw Error("macOS only");let{stdout:j}=await F1("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),S=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(j)?.groups.id??"com.apple.Safari";if(S==="com.apple.safari")return"com.apple.Safari";return S}import B1 from"node:process";import{promisify as N1}from"node:util";import{execFile as V1,execFileSync as tS}from"node:child_process";var A1=N1(V1);async function mj(j,{humanReadableOutput:$=!0,signal:S}={}){if(B1.platform!=="darwin")throw Error("macOS only");let y=$?[]:["-ss"],q={};if(S)q.signal=S;let{stdout:R}=await A1("osascript",["-e",j,y],q);return R.trim()}async function Pj(j){return mj(`tell application "Finder" to set app_path to application file id "${j}" as string
25
- tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}import{promisify as f1}from"node:util";import{execFile as w1}from"node:child_process";var x1=f1(w1),sj={MSEdgeHTM:{name:"Edge",id:"com.microsoft.edge"},MSEdgeBHTML:{name:"Edge Beta",id:"com.microsoft.edge.beta"},MSEdgeDHTML:{name:"Edge Dev",id:"com.microsoft.edge.dev"},AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:"Edge",id:"com.microsoft.edge.old"},ChromeHTML:{name:"Chrome",id:"com.google.chrome"},ChromeBHTML:{name:"Chrome Beta",id:"com.google.chrome.beta"},ChromeDHTML:{name:"Chrome Dev",id:"com.google.chrome.dev"},ChromiumHTM:{name:"Chromium",id:"org.chromium.Chromium"},BraveHTML:{name:"Brave",id:"com.brave.Browser"},BraveBHTML:{name:"Brave Beta",id:"com.brave.Browser.beta"},BraveDHTML:{name:"Brave Dev",id:"com.brave.Browser.dev"},BraveSSHTM:{name:"Brave Nightly",id:"com.brave.Browser.nightly"},FirefoxURL:{name:"Firefox",id:"org.mozilla.firefox"},OperaStable:{name:"Opera",id:"com.operasoftware.Opera"},VivaldiHTM:{name:"Vivaldi",id:"com.vivaldi.Vivaldi"},"IE.HTTP":{name:"Internet Explorer",id:"com.microsoft.ie"}},dS=new Map(Object.entries(sj));class Jj extends Error{}async function Yj(j=x1){let{stdout:$}=await j("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),S=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec($);if(!S)throw new Jj(`Cannot find Windows browser in stdout: ${JSON.stringify($)}`);let{id:y}=S.groups,q=sj[y];if(!q)throw new Jj(`Unknown browser ID: ${y}`);return q}var b1=C1(k1),u1=(j)=>j.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,($)=>$.toUpperCase());async function Qj(){if(Tj.platform==="darwin"){let j=await Ij();return{name:await Pj(j),id:j}}if(Tj.platform==="linux"){let{stdout:j}=await b1("xdg-mime",["query","default","x-scheme-handler/http"]),$=j.trim();return{name:u1($.replace(/.desktop$/,"").replace("-"," ")),id:$}}if(Tj.platform==="win32")return Yj();throw Error("Only macOS, Linux, and Windows are supported")}var t1=c1(nj.execFile),Zj=oj.dirname(O1(import.meta.url)),rj=oj.join(Zj,"xdg-open"),{platform:w,arch:lj}=Uj;async function g1(){let j=await Ej(),$=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,S=pj.from($,"utf16le").toString("base64"),{stdout:y}=await t1(j,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",S],{encoding:"utf8"}),q=y.trim(),R={ChromeHTML:"com.google.chrome",BraveHTML:"com.brave.Browser",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return R[q]?{id:R[q]}:{}}var dj=async(j,$)=>{let S;for(let y of j)try{return await $(y)}catch(q){S=q}throw S},c=async(j)=>{if(j={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...j},Array.isArray(j.app))return dj(j.app,(E)=>c({...j,app:E}));let{name:$,arguments:S=[]}=j.app??{};if(S=[...S],Array.isArray($))return dj($,(E)=>c({...j,app:{name:E,arguments:S}}));if($==="browser"||$==="browserPrivate"){let E={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","com.brave.Browser":"brave","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge"},P={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},J=L?await g1():await Qj();if(J.id in E){let Y=E[J.id];if($==="browserPrivate")S.push(P[Y]);return c({...j,app:{name:N[Y],arguments:S}})}throw Error(`${J.name} is not supported as a default browser`)}let y,q=[],R={};if(w==="darwin"){if(y="open",j.wait)q.push("--wait-apps");if(j.background)q.push("--background");if(j.newInstance)q.push("--new");if($)q.push("-a",$)}else if(w==="win32"||L&&!f()&&!$){if(y=await Ej(),q.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),!L)R.windowsVerbatimArguments=!0;let E=["Start"];if(j.wait)E.push("-Wait");if($){if(E.push(`"\`"${$}\`""`),j.target)S.push(j.target)}else if(j.target)E.push(`"${j.target}"`);if(S.length>0)S=S.map((P)=>`"\`"${P}\`""`),E.push("-ArgumentList",S.join(","));j.target=pj.from(E.join(" "),"utf16le").toString("base64")}else{if($)y=$;else{let E=!Zj||Zj==="/",P=!1;try{await h1.access(rj,v1.X_OK),P=!0}catch{}y=Uj.versions.electron??(w==="android"||E||!P)?"xdg-open":rj}if(S.length>0)q.push(...S);if(!j.wait)R.stdio="ignore",R.detached=!0}if(w==="darwin"&&S.length>0)q.push("--args",...S);if(j.target)q.push(j.target);let I=nj.spawn(y,q,R);if(j.wait)return new Promise((E,P)=>{I.once("error",P),I.once("close",(J)=>{if(!j.allowNonzeroExitCode&&J>0){P(Error(`Exited with code ${J}`));return}E(I)})});return I.unref(),I},m1=(j,$)=>{if(typeof j!=="string")throw TypeError("Expected a `target`");return c({...$,target:j})};function ij(j){if(typeof j==="string"||Array.isArray(j))return j;let{[lj]:$}=j;if(!$)throw Error(`${lj} is not supported`);return $}function h({[w]:j},{wsl:$}){if($&&L)return ij($);if(!j)throw Error(`${w} is not supported`);return ij(j)}var N={};D(N,"chrome",()=>h({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}}));D(N,"brave",()=>h({darwin:"brave browser",win32:"brave",linux:["brave-browser","brave"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",x64:["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe","/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]}}));D(N,"firefox",()=>h({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));D(N,"edge",()=>h({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));D(N,"browser",()=>"browser");D(N,"browserPrivate",()=>"browserPrivate");var aj=m1;var s1=2000,r1=600;async function Gj(j){let $=j??b();console.log(`Initiating authentication...
26
- `);let S=await fetch(`${$}/api/cli-auth/initiate`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!S.ok){let Z=await S.text();throw Error(`Failed to initiate auth: ${Z}`)}let{deviceCode:y,userCode:q,verificationUrl:R,interval:I,expiresIn:E}=await S.json(),P=(I||s1/1000)*1000,J=Math.ceil((E||r1)/(P/1000));console.log("Opening browser to authenticate..."),console.log(""),console.log(` Your code: ${q}`),console.log(""),console.log(` Or visit: ${R}`),console.log(""),await aj(R),console.log("Waiting for authorization...");let Y=0;while(Y<J){await l1(P),Y++;try{let Z=await fetch(`${$}/api/cli-auth/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:y})});if(!Z.ok){if(Z.status===400)continue;throw Error(`Poll failed: ${await Z.text()}`)}let X=await Z.json();if(X.status==="authorized"&&X.token){let G={apiUrl:$,token:X.token.token,expiresAt:X.token.expiresAt,userId:X.token.userId,userEmail:X.token.userEmail};$j(G),console.log(""),console.log(`Authenticated as ${X.token.userEmail}`),console.log(""),console.log("You can now use ace commands. Try:"),console.log(" ace orient"),console.log(' ace capture "My new task"');return}if(X.status==="expired")throw Error("Authentication code expired. Please try again.")}catch(Z){if(Z instanceof TypeError)continue;throw Z}}throw Error("Authentication timed out. Please try again.")}function l1(j){return new Promise(($)=>setTimeout($,j))}function T(){return process.argv.includes("--json")}function Q(j,$){if($?.json||T())console.log(JSON.stringify(j,null,2));else if(typeof j==="string")console.log(j);else console.log(JSON.stringify(j,null,2))}function U(j){if(T())console.log(JSON.stringify({error:j}));else console.error(`Error: ${j}`)}function K(j){let $=[`[${j.id.slice(0,8)}] ${j.name}`];if(j.project_name)$.push(`(${j.project_name})`);if(j.dueDate)$.push(`due: ${j.dueDate}`);if(j.status==="waiting"&&j.waitingFor)$.push(`waiting: ${j.waitingFor}`);return $.join(" ")}function V(j){let $=[`[${j.id.slice(0,8)}] ${j.name}`];if(j.category_name)$.push(`(${j.category_name})`);if(j.status!=="active")$.push(`[${j.status}]`);return $.join(" ")}function x(j,$){if(j.length===0)return $?`${$}: (none)`:"(no actions)";let S=j.map((y)=>` ${K(y)}`);if($)return`${$} (${j.length}):
27
- ${S.join(`
28
- `)}`;return S.join(`
29
- `)}function u(j,$){if(j.length===0)return $?`${$}: (none)`:"(no projects)";let S=j.map((y)=>` ${V(y)}`);if($)return`${$} (${j.length}):
30
- ${S.join(`
31
- `)}`;return S.join(`
32
- `)}function ej(j){let $=[];$.push(`Inbox: ${j.inboxCount} items`);let S=j.domains.map((y)=>` ${y.name}: ${y.active_count}/${y.activeProjectLimit} active`);if($.push(`Capacity:
33
- ${S.join(`
34
- `)}`),j.activeProjects.length>0)$.push(u(j.activeProjects,"Active Projects"));if(j.overdue.length>0)$.push(x(j.overdue,"Overdue"));if(j.dueToday.length>0)$.push(x(j.dueToday,"Due Today"));if(j.waiting.length>0)$.push(x(j.waiting,"Waiting"));return $.join(`
21
+ `),this.outputHelp({error:!0});let j=$||{},G=j.exitCode||1,P=j.code||"commander.error";this._exit(G,P,y)}_parseOptionsEnv(){this.options.forEach((y)=>{if(y.envVar&&y.envVar in w.env){let $=y.attributeName();if(this.getOptionValue($)===void 0||["default","config","env"].includes(this.getOptionValueSource($)))if(y.required||y.optional)this.emit(`optionEnv:${y.name()}`,w.env[y.envVar]);else this.emit(`optionEnv:${y.name()}`)}})}_parseOptionsImplied(){let y=new fj(this.options),$=(j)=>{return this.getOptionValue(j)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(j))};this.options.filter((j)=>j.implied!==void 0&&$(j.attributeName())&&y.valueFromOption(this.getOptionValue(j.attributeName()),j)).forEach((j)=>{Object.keys(j.implied).filter((G)=>!$(G)).forEach((G)=>{this.setOptionValueWithSource(G,j.implied[G],"implied")})})}missingArgument(y){let $=`error: missing required argument '${y}'`;this.error($,{code:"commander.missingArgument"})}optionMissingArgument(y){let $=`error: option '${y.flags}' argument missing`;this.error($,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(y){let $=`error: required option '${y.flags}' not specified`;this.error($,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(y,$){let j=(R)=>{let q=R.attributeName(),S=this.getOptionValue(q),U=this.options.find((J)=>J.negate&&q===J.attributeName()),I=this.options.find((J)=>!J.negate&&q===J.attributeName());if(U&&(U.presetArg===void 0&&S===!1||U.presetArg!==void 0&&S===U.presetArg))return U;return I||R},G=(R)=>{let q=j(R),S=q.attributeName();if(this.getOptionValueSource(S)==="env")return`environment variable '${q.envVar}'`;return`option '${q.flags}'`},P=`error: ${G(y)} cannot be used with ${G($)}`;this.error(P,{code:"commander.conflictingOption"})}unknownOption(y){if(this._allowUnknownOption)return;let $="";if(y.startsWith("--")&&this._showSuggestionAfterError){let G=[],P=this;do{let R=P.createHelp().visibleOptions(P).filter((q)=>q.long).map((q)=>q.long);G=G.concat(R),P=P.parent}while(P&&!P._enablePositionalOptions);$=ty(y,G)}let j=`error: unknown option '${y}'${$}`;this.error(j,{code:"commander.unknownOption"})}_excessArguments(y){if(this._allowExcessArguments)return;let $=this.registeredArguments.length,j=$===1?"":"s",P=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${$} argument${j} but got ${y.length}.`;this.error(P,{code:"commander.excessArguments"})}unknownCommand(){let y=this.args[0],$="";if(this._showSuggestionAfterError){let G=[];this.createHelp().visibleCommands(this).forEach((P)=>{if(G.push(P.name()),P.alias())G.push(P.alias())}),$=ty(y,G)}let j=`error: unknown command '${y}'${$}`;this.error(j,{code:"commander.unknownCommand"})}version(y,$,j){if(y===void 0)return this._version;this._version=y,$=$||"-V, --version",j=j||"output the version number";let G=this.createOption($,j);return this._versionOptionName=G.attributeName(),this._registerOption(G),this.on("option:"+G.name(),()=>{this._outputConfiguration.writeOut(`${y}
22
+ `),this._exit(0,"commander.version",y)}),this}description(y,$){if(y===void 0&&$===void 0)return this._description;if(this._description=y,$)this._argsDescription=$;return this}summary(y){if(y===void 0)return this._summary;return this._summary=y,this}alias(y){if(y===void 0)return this._aliases[0];let $=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)$=this.commands[this.commands.length-1];if(y===$._name)throw Error("Command alias can't be the same as its name");let j=this.parent?._findCommand(y);if(j){let G=[j.name()].concat(j.aliases()).join("|");throw Error(`cannot add alias '${y}' to command '${this.name()}' as already have command '${G}'`)}return $._aliases.push(y),this}aliases(y){if(y===void 0)return this._aliases;return y.forEach(($)=>this.alias($)),this}usage(y){if(y===void 0){if(this._usage)return this._usage;let $=this.registeredArguments.map((j)=>{return Wj(j)});return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?$:[]).join(" ")}return this._usage=y,this}name(y){if(y===void 0)return this._name;return this._name=y,this}nameFromFilename(y){return this._name=z.basename(y,z.extname(y)),this}executableDir(y){if(y===void 0)return this._executableDir;return this._executableDir=y,this}helpInformation(y){let $=this.createHelp();if($.helpWidth===void 0)$.helpWidth=y&&y.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth();return $.formatHelp(this,$)}_getHelpContext(y){y=y||{};let $={error:!!y.error},j;if($.error)j=(G)=>this._outputConfiguration.writeErr(G);else j=(G)=>this._outputConfiguration.writeOut(G);return $.write=y.write||j,$.command=this,$}outputHelp(y){let $;if(typeof y==="function")$=y,y=void 0;let j=this._getHelpContext(y);this._getCommandAndAncestors().reverse().forEach((P)=>P.emit("beforeAllHelp",j)),this.emit("beforeHelp",j);let G=this.helpInformation(j);if($){if(G=$(G),typeof G!=="string"&&!Buffer.isBuffer(G))throw Error("outputHelp callback must return a string or a Buffer")}if(j.write(G),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",j),this._getCommandAndAncestors().forEach((P)=>P.emit("afterAllHelp",j))}helpOption(y,$){if(typeof y==="boolean"){if(y)this._helpOption=this._helpOption??void 0;else this._helpOption=null;return this}return y=y??"-h, --help",$=$??"display help for command",this._helpOption=this.createOption(y,$),this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption(y){return this._helpOption=y,this}help(y){this.outputHelp(y);let $=w.exitCode||0;if($===0&&y&&typeof y!=="function"&&y.error)$=1;this._exit($,"commander.help","(outputHelp)")}addHelpText(y,$){let j=["beforeAll","before","after","afterAll"];if(!j.includes(y))throw Error(`Unexpected value for position to addHelpText.
23
+ Expecting one of '${j.join("', '")}'`);let G=`${y}Help`;return this.on(G,(P)=>{let R;if(typeof $==="function")R=$({error:P.error,command:P.command});else R=$;if(R)P.write(`${R}
24
+ `)}),this}_outputHelpIfRequested(y){let $=this._getHelpOption();if($&&y.find((G)=>$.is(G)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function my(y){return y.map(($)=>{if(!$.startsWith("--inspect"))return $;let j,G="127.0.0.1",P="9229",R;if((R=$.match(/^(--inspect(-brk)?)$/))!==null)j=R[1];else if((R=$.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(j=R[1],/^\d+$/.test(R[3]))P=R[3];else G=R[3];else if((R=$.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)j=R[1],G=R[3],P=R[4];if(j&&P!=="0")return`${j}=${G}:${parseInt(P)+1}`;return $})}Kj.Command=Sy});var iy=B((Nj)=>{var{Argument:sy}=s(),{Command:Uy}=ly(),{CommanderError:Bj,InvalidArgumentError:ry}=u(),{Help:Cj}=jy(),{Option:dy}=Gy();Nj.program=new Uy;Nj.createCommand=(y)=>new Uy(y);Nj.createOption=(y,$)=>new dy(y,$);Nj.createArgument=(y,$)=>new sy(y,$);Nj.Command=Uy;Nj.Option=dy;Nj.Argument=sy;Nj.Help=Cj;Nj.CommanderError=Bj;Nj.InvalidArgumentError=ry;Nj.InvalidOptionArgumentError=ry});var ay=o$(iy(),1),{program:F,createCommand:lG,createArgument:sG,createOption:rG,CommanderError:dG,InvalidArgumentError:iG,InvalidOptionArgumentError:aG,Command:eG,Argument:nG,Option:oG,Help:pG}=ay.default;var ey="0.2.0";import{homedir as mj}from"os";import{join as ny}from"path";import{existsSync as Ey,mkdirSync as lj,readFileSync as sj,writeFileSync as rj,unlinkSync as dj}from"fs";function oy(){let y=process.env.ACE_TEST_HOME??mj();return ny(y,".ace")}function Iy(){return ny(oy(),"credentials.json")}var ij=process.env.DEBUG==="true"||process.env.ACE_DEBUG==="true";function D(y,...$){if(ij)console.error(`[ace-cli debug] ${y}`,...$)}function aj(){let y=oy();if(!Ey(y))lj(y,{recursive:!0,mode:448})}function C(){try{let y=Iy();if(!Ey(y))return D("Credentials file does not exist:",y),null;let $=sj(y,"utf-8"),j=JSON.parse($);if(j.expiresAt&&new Date(j.expiresAt)<new Date)return D("Token expired at:",j.expiresAt),null;return j}catch(y){return D("Error reading credentials:",y),null}}function Ly(y){aj();let $=Iy();rj($,JSON.stringify(y,null,2),{mode:384}),D("Credentials saved to:",$)}function Qy(){try{let y=Iy();if(Ey(y))return dj(y),D("Credentials cleared"),!0;return!1}catch(y){return D("Error clearing credentials:",y),!1}}function g(){return C()?.apiUrl??process.env.ACE_API_URL??"https://aceisyourassistant.com"}import Wy from"node:process";import{Buffer as I$}from"node:buffer";import L$ from"node:path";import{fileURLToPath as _G}from"node:url";import{promisify as zG}from"node:util";import Q$ from"node:child_process";import HG,{constants as WG}from"node:fs/promises";import j$ from"node:process";import G$,{constants as jG}from"node:fs/promises";import $$ from"node:process";import yG from"node:os";import $G from"node:fs";import oj from"node:fs";import py from"node:fs";var Jy;function ej(){try{return py.statSync("/.dockerenv"),!0}catch{return!1}}function nj(){try{return py.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function Zy(){if(Jy===void 0)Jy=ej()||nj();return Jy}var Yy,pj=()=>{try{return oj.statSync("/run/.containerenv"),!0}catch{return!1}};function k(){if(Yy===void 0)Yy=pj()||Zy();return Yy}var y$=()=>{if($$.platform!=="linux")return!1;if(yG.release().toLowerCase().includes("microsoft")){if(k())return!1;return!0}try{return $G.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")?!k():!1}catch{return!1}},W=$$.env.__IS_WSL_TEST__?y$:y$();var GG=(()=>{let $;return async function(){if($)return $;let j="/etc/wsl.conf",G=!1;try{await G$.access(j,jG.F_OK),G=!0}catch{}if(!G)return"/mnt/";let P=await G$.readFile(j,{encoding:"utf8"}),R=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(P);if(!R)return"/mnt/";return $=R.groups.mountPoint.trim(),$=$.endsWith("/")?$:`${$}/`,$}})(),PG=async()=>{return`${await GG()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`},cy=async()=>{if(W)return PG();return`${j$.env.SYSTEMROOT||j$.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`};function M(y,$,j){let G=(P)=>Object.defineProperty(y,$,{value:P,enumerable:!0,writable:!0});return Object.defineProperty(y,$,{configurable:!0,enumerable:!0,get(){let P=j();return G(P),P},set(P){G(P)}}),y}import{promisify as cG}from"node:util";import zy from"node:process";import{execFile as wG}from"node:child_process";import{promisify as RG}from"node:util";import qG from"node:process";import{execFile as SG}from"node:child_process";var UG=RG(SG);async function wy(){if(qG.platform!=="darwin")throw Error("macOS only");let{stdout:y}=await UG("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),j=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(y)?.groups.id??"com.apple.Safari";if(j==="com.apple.safari")return"com.apple.Safari";return j}import EG from"node:process";import{promisify as IG}from"node:util";import{execFile as LG,execFileSync as CP}from"node:child_process";var QG=IG(LG);async function P$(y,{humanReadableOutput:$=!0,signal:j}={}){if(EG.platform!=="darwin")throw Error("macOS only");let G=$?[]:["-ss"],P={};if(j)P.signal=j;let{stdout:R}=await QG("osascript",["-e",y,G],P);return R.trim()}async function Xy(y){return P$(`tell application "Finder" to set app_path to application file id "${y}" as string
25
+ tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}import{promisify as JG}from"node:util";import{execFile as ZG}from"node:child_process";var YG=JG(ZG),R$={MSEdgeHTM:{name:"Edge",id:"com.microsoft.edge"},MSEdgeBHTML:{name:"Edge Beta",id:"com.microsoft.edge.beta"},MSEdgeDHTML:{name:"Edge Dev",id:"com.microsoft.edge.dev"},AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:"Edge",id:"com.microsoft.edge.old"},ChromeHTML:{name:"Chrome",id:"com.google.chrome"},ChromeBHTML:{name:"Chrome Beta",id:"com.google.chrome.beta"},ChromeDHTML:{name:"Chrome Dev",id:"com.google.chrome.dev"},ChromiumHTM:{name:"Chromium",id:"org.chromium.Chromium"},BraveHTML:{name:"Brave",id:"com.brave.Browser"},BraveBHTML:{name:"Brave Beta",id:"com.brave.Browser.beta"},BraveDHTML:{name:"Brave Dev",id:"com.brave.Browser.dev"},BraveSSHTM:{name:"Brave Nightly",id:"com.brave.Browser.nightly"},FirefoxURL:{name:"Firefox",id:"org.mozilla.firefox"},OperaStable:{name:"Opera",id:"com.operasoftware.Opera"},VivaldiHTM:{name:"Vivaldi",id:"com.vivaldi.Vivaldi"},"IE.HTTP":{name:"Internet Explorer",id:"com.microsoft.ie"}},kP=new Map(Object.entries(R$));class Fy extends Error{}async function _y(y=YG){let{stdout:$}=await y("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),j=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec($);if(!j)throw new Fy(`Cannot find Windows browser in stdout: ${JSON.stringify($)}`);let{id:G}=j.groups,P=R$[G];if(!P)throw new Fy(`Unknown browser ID: ${G}`);return P}var XG=cG(wG),FG=(y)=>y.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,($)=>$.toUpperCase());async function Hy(){if(zy.platform==="darwin"){let y=await wy();return{name:await Xy(y),id:y}}if(zy.platform==="linux"){let{stdout:y}=await XG("xdg-mime",["query","default","x-scheme-handler/http"]),$=y.trim();return{name:FG($.replace(/.desktop$/,"").replace("-"," ")),id:$}}if(zy.platform==="win32")return _y();throw Error("Only macOS, Linux, and Windows are supported")}var MG=zG(Q$.execFile),My=L$.dirname(_G(import.meta.url)),q$=L$.join(My,"xdg-open"),{platform:b,arch:S$}=Wy;async function fG(){let y=await cy(),$=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,j=I$.from($,"utf16le").toString("base64"),{stdout:G}=await MG(y,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",j],{encoding:"utf8"}),P=G.trim(),R={ChromeHTML:"com.google.chrome",BraveHTML:"com.brave.Browser",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return R[P]?{id:R[P]}:{}}var U$=async(y,$)=>{let j;for(let G of y)try{return await $(G)}catch(P){j=P}throw j},r=async(y)=>{if(y={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...y},Array.isArray(y.app))return U$(y.app,(S)=>r({...y,app:S}));let{name:$,arguments:j=[]}=y.app??{};if(j=[...j],Array.isArray($))return U$($,(S)=>r({...y,app:{name:S,arguments:j}}));if($==="browser"||$==="browserPrivate"){let S={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","com.brave.Browser":"brave","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge"},U={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},I=W?await fG():await Hy();if(I.id in S){let J=S[I.id];if($==="browserPrivate")j.push(U[J]);return r({...y,app:{name:N[J],arguments:j}})}throw Error(`${I.name} is not supported as a default browser`)}let G,P=[],R={};if(b==="darwin"){if(G="open",y.wait)P.push("--wait-apps");if(y.background)P.push("--background");if(y.newInstance)P.push("--new");if($)P.push("-a",$)}else if(b==="win32"||W&&!k()&&!$){if(G=await cy(),P.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),!W)R.windowsVerbatimArguments=!0;let S=["Start"];if(y.wait)S.push("-Wait");if($){if(S.push(`"\`"${$}\`""`),y.target)j.push(y.target)}else if(y.target)S.push(`"${y.target}"`);if(j.length>0)j=j.map((U)=>`"\`"${U}\`""`),S.push("-ArgumentList",j.join(","));y.target=I$.from(S.join(" "),"utf16le").toString("base64")}else{if($)G=$;else{let S=!My||My==="/",U=!1;try{await HG.access(q$,WG.X_OK),U=!0}catch{}G=Wy.versions.electron??(b==="android"||S||!U)?"xdg-open":q$}if(j.length>0)P.push(...j);if(!y.wait)R.stdio="ignore",R.detached=!0}if(b==="darwin"&&j.length>0)P.push("--args",...j);if(y.target)P.push(y.target);let q=Q$.spawn(G,P,R);if(y.wait)return new Promise((S,U)=>{q.once("error",U),q.once("close",(I)=>{if(!y.allowNonzeroExitCode&&I>0){U(Error(`Exited with code ${I}`));return}S(q)})});return q.unref(),q},KG=(y,$)=>{if(typeof y!=="string")throw TypeError("Expected a `target`");return r({...$,target:y})};function E$(y){if(typeof y==="string"||Array.isArray(y))return y;let{[S$]:$}=y;if(!$)throw Error(`${S$} is not supported`);return $}function d({[b]:y},{wsl:$}){if($&&W)return E$($);if(!y)throw Error(`${b} is not supported`);return E$(y)}var N={};M(N,"chrome",()=>d({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}}));M(N,"brave",()=>d({darwin:"brave browser",win32:"brave",linux:["brave-browser","brave"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",x64:["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe","/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]}}));M(N,"firefox",()=>d({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));M(N,"edge",()=>d({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));M(N,"browser",()=>"browser");M(N,"browserPrivate",()=>"browserPrivate");var J$=KG;var TG=2000,BG=600;async function fy(y){let $=y??g();console.log(`Initiating authentication...
26
+ `);let j=await fetch(`${$}/api/cli-auth/initiate`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!j.ok){let Z=await j.text();throw Error(`Failed to initiate auth: ${Z}`)}let{deviceCode:G,userCode:P,verificationUrl:R,interval:q,expiresIn:S}=await j.json(),U=(q||TG/1000)*1000,I=Math.ceil((S||BG)/(U/1000));console.log("Opening browser to authenticate..."),console.log(""),console.log(` Your code: ${P}`),console.log(""),console.log(` Or visit: ${R}`),console.log(""),await J$(R),console.log("Waiting for authorization...");let J=0;while(J<I){await CG(U),J++;try{let Z=await fetch(`${$}/api/cli-auth/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:G})});if(!Z.ok){if(Z.status===400)continue;throw Error(`Poll failed: ${await Z.text()}`)}let X=await Z.json();if(X.status==="authorized"&&X.token){let c={apiUrl:$,token:X.token.token,expiresAt:X.token.expiresAt,userId:X.token.userId,userEmail:X.token.userEmail};Ly(c),console.log(""),console.log(`Authenticated as ${X.token.userEmail}`),console.log(""),console.log("You can now use ace commands. Try:"),console.log(" ace orient"),console.log(' ace capture "My new task"');return}if(X.status==="expired")throw Error("Authentication code expired. Please try again.")}catch(Z){if(Z instanceof TypeError)continue;throw Z}}throw Error("Authentication timed out. Please try again.")}function CG(y){return new Promise(($)=>setTimeout($,y))}function Ky(y,$){let j=$?new Date($):new Date,G=y.toLowerCase().trim().replace(/\s+/g,""),P,R=0,q=G.match(/^(\d{1,2}):(\d{2})(?::\d{2})?$/);if(q)P=parseInt(q[1],10),R=parseInt(q[2],10);else{let S=G.match(/^(\d{1,2})(?::(\d{2}))?([ap]m?)$/);if(S){P=parseInt(S[1],10),R=S[2]?parseInt(S[2],10):0;let U=S[3].startsWith("p");if(U&&P!==12)P+=12;else if(!U&&P===12)P=0}else{let U=new Date(y);if(!isNaN(U.getTime()))return U.toISOString();throw Error(`Invalid time format: ${y}. Use "HH:MM", "H:MMam/pm", or ISO format.`)}}if(P<0||P>23)throw Error(`Invalid hours: ${P}. Must be between 0 and 23.`);if(R<0||R>59)throw Error(`Invalid minutes: ${R}. Must be between 0 and 59.`);return j.setHours(P,R,0,0),j.toISOString()}function Z$(y,$){let j=new Date(y);return new Date(j.getTime()+$*60*1000).toISOString()}function V(y){let j=new Date(new Date);if(j.setHours(0,0,0,0),y==="today"){let q=new Date(j);return q.setHours(23,59,59,999),{startDate:j.toISOString(),endDate:q.toISOString()}}if(y==="week"){let q=new Date(j);return q.setDate(q.getDate()+7),q.setHours(23,59,59,999),{startDate:j.toISOString(),endDate:q.toISOString()}}if(!/^\d{4}-\d{2}-\d{2}$/.test(y))throw Error(`Invalid date format: ${y}. Use YYYY-MM-DD format.`);let P=new Date(y);if(isNaN(P.getTime()))throw Error(`Invalid date: ${y}. Use YYYY-MM-DD format.`);P.setHours(0,0,0,0);let R=new Date(P);return R.setHours(23,59,59,999),{startDate:P.toISOString(),endDate:R.toISOString()}}function t(y){return new Date(y).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}function x(y){return new Date(y).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function Y$(y,$,j){if(j)return t(y);let G=new Date(y),P=new Date($);if(G.toDateString()===P.toDateString())return`${x(y)} - ${x($)}`;return`${t(y)} ${x(y)} - ${t($)} ${x($)}`}function m(){return new Date().toISOString().split("T")[0]}function L(){return process.argv.includes("--json")}function Q(y,$){if($?.json||L())console.log(JSON.stringify(y,null,2));else if(typeof y==="string")console.log(y);else console.log(JSON.stringify(y,null,2))}function E(y){if(L())console.log(JSON.stringify({error:y}));else console.error(`Error: ${y}`)}function f(y){let $=[`[${y.id.slice(0,8)}] ${y.name}`];if(y.project_name)$.push(`(${y.project_name})`);if(y.dueDate)$.push(`due: ${y.dueDate}`);if(y.status==="waiting"&&y.waitingFor)$.push(`waiting: ${y.waitingFor}`);return $.join(" ")}function K(y){let $=[`[${y.id.slice(0,8)}] ${y.name}`];if(y.category_name)$.push(`(${y.category_name})`);if(y.status!=="active")$.push(`[${y.status}]`);return $.join(" ")}function _(y,$){if(y.length===0)return $?`${$}: (none)`:"(no actions)";let j=y.map((G)=>` ${f(G)}`);if($)return`${$} (${y.length}):
27
+ ${j.join(`
28
+ `)}`;return j.join(`
29
+ `)}function v(y,$){if(y.length===0)return $?`${$}: (none)`:"(no projects)";let j=y.map((G)=>` ${K(G)}`);if($)return`${$} (${y.length}):
30
+ ${j.join(`
31
+ `)}`;return j.join(`
32
+ `)}function c$(y){let $=[];$.push(`Inbox: ${y.inboxCount} items`);let j=y.domains.map((G)=>` ${G.name}: ${G.active_count}/${G.activeProjectLimit} active`);if($.push(`Capacity:
33
+ ${j.join(`
34
+ `)}`),y.activeProjects.length>0)$.push(v(y.activeProjects,"Active Projects"));if(y.overdue.length>0)$.push(_(y.overdue,"Overdue"));if(y.dueToday.length>0)$.push(_(y.dueToday,"Due Today"));if(y.waiting.length>0)$.push(_(y.waiting,"Waiting"));return $.join(`
35
35
 
36
- `)}function j$(j){let $=j.command("auth").description("Manage authentication");$.command("login").description("Authenticate with Ace").option("--api-url <url>","Ace API URL (default: https://aceisyourassistant.com)").action(async(S)=>{try{await Gj(S.apiUrl)}catch(y){U(y instanceof Error?y.message:"Login failed"),process.exit(1)}}),$.command("logout").description("Remove stored credentials").action(()=>{let S=Sj();if(T())Q({success:S});else if(S)console.log("Logged out successfully");else console.log("No credentials to remove")}),$.command("status").description("Show current authentication status").action(()=>{let S=B();if(T())Q({authenticated:!!S,email:S?.userEmail??null,apiUrl:S?.apiUrl??null});else if(S)console.log(`Authenticated as ${S.userEmail}`),console.log(`API URL: ${S.apiUrl}`);else console.log("Not authenticated. Run: ace auth login")}),$.command("whoami").description("Show current user").action(()=>{let S=B();if(T())Q({authenticated:!!S,email:S?.userEmail??null,userId:S?.userId??null});else if(S)console.log(S.userEmail);else console.log("Not authenticated"),process.exit(1)})}class Xj extends Error{status;body;constructor(j,$,S){super(j);this.status=$;this.body=S;this.name="ApiError"}}class Mj extends Xj{constructor(j="Not authenticated. Run: ace auth login"){super(j,401);this.name="AuthError"}}async function _(j,$={},S){let y=B();if(!y)throw new Mj;let R=`${S??y.apiUrl??b()}/api${j}`,I=await fetch(R,{...$,headers:{Authorization:`Bearer ${y.token}`,"Content-Type":"application/json",...$.headers}});if(I.status===401)throw new Mj("Session expired. Run: ace auth login");if(!I.ok){let E=await I.json().catch(()=>({}));throw new Xj(E.error??`Request failed with status ${I.status}`,I.status,E)}return I.json()}async function $$(){return _("/dashboard")}async function v(j={}){let $=new URLSearchParams;if(j.status)$.set("status",j.status);if(j.projectId)$.set("project_id",j.projectId);if(j.contextId)$.set("context_id",j.contextId);if(j.search)$.set("search",j.search);if(j.limit)$.set("limit",String(j.limit));if(j.offset)$.set("offset",String(j.offset));let S=$.toString(),y=S?`/actions?${S}`:"/actions";return(await _(y)).actions}async function S$(j){return _(`/actions/${j}`)}async function t(j){return _("/actions",{method:"POST",body:JSON.stringify(j)})}async function _j(j,$){return _(`/actions/${j}`,{method:"PUT",body:JSON.stringify($)})}async function y$(j){return _j(j,{status:"completed"})}async function q$(j){await _(`/actions/${j}`,{method:"DELETE"})}async function g(j={}){let $=new URLSearchParams;if(j.status)$.set("status",j.status);if(j.domain)$.set("domain",j.domain);if(j.categoryId)$.set("category_id",j.categoryId);if(j.search)$.set("search",j.search);if(j.dueForReview)$.set("due_for_review","true");let S=$.toString(),y=S?`/projects?${S}`:"/projects";return(await _(y)).projects}async function R$(j){return _(`/projects/${j}`)}async function E$(j){return _("/projects",{method:"POST",body:JSON.stringify(j)})}async function m(j,$){return _(`/projects/${j}`,{method:"PUT",body:JSON.stringify($)})}function I$(j){j.command("capture").description("Quick capture an item to inbox").argument("<text>","The item to capture").option("-n, --notes <notes>","Additional notes").action(async($,S)=>{try{let y=await t({name:$,status:"inbox",notes:S.notes});if(T())Q(y);else console.log(`Captured: ${K(y)}`)}catch(y){U(y instanceof Error?y.message:"Capture failed"),process.exit(1)}})}function P$(j){j.command("orient").description("Daily orientation - see your current state").alias("dashboard").action(async()=>{try{let $=await $$();if(T())Q($);else console.log(ej($))}catch($){U($ instanceof Error?$.message:"Failed to load dashboard"),process.exit(1)}})}function J$(j){let $=j.command("actions").description("Manage actions");$.command("list").description("List actions").option("-s, --status <status>","Filter by status (inbox, active, waiting, someday)").option("-p, --project <id>","Filter by project ID").option("-c, --context <id>","Filter by context ID").option("-q, --search <query>","Search by name").option("-l, --limit <n>","Limit results","50").action(async(S)=>{try{let y=await v({status:S.status,projectId:S.project,contextId:S.context,search:S.search,limit:parseInt(S.limit)});if(T())Q({actions:y});else{let q=S.status?`${S.status} actions`:"Actions";console.log(x(y,q))}}catch(y){U(y instanceof Error?y.message:"Failed to list actions"),process.exit(1)}}),$.command("inbox").description("List inbox items").action(async()=>{try{let S=await v({status:"inbox"});if(T())Q({actions:S,count:S.length});else console.log(x(S,"Inbox"))}catch(S){U(S instanceof Error?S.message:"Failed to list inbox"),process.exit(1)}}),$.command("get <id>").description("Get action details").action(async(S)=>{try{let y=await S$(S);if(T())Q(y);else{if(console.log(K(y)),y.notes)console.log(`
37
- Notes: ${y.notes}`);if(y.contexts.length>0)console.log(`
38
- Contexts: ${y.contexts.map((q)=>q.name).join(", ")}`)}}catch(y){U(y instanceof Error?y.message:"Failed to get action"),process.exit(1)}}),$.command("add <name>").description("Create a new action").option("-s, --status <status>","Initial status (default: inbox)").option("-p, --project <id>","Assign to project").option("-d, --due <date>","Due date (YYYY-MM-DD)").option("-n, --notes <notes>","Additional notes").action(async(S,y)=>{try{let q=await t({name:S,status:y.status??"inbox",projectId:y.project,dueDate:y.due,notes:y.notes});if(T())Q(q);else console.log(`Created: ${K(q)}`)}catch(q){U(q instanceof Error?q.message:"Failed to create action"),process.exit(1)}}),$.command("update <id>").description("Update an action").option("-n, --name <name>","New name").option("-s, --status <status>","New status").option("-p, --project <id>",'Assign to project (use "none" to unassign)').option("-d, --due <date>",'Due date (YYYY-MM-DD, or "none" to clear)').option("--notes <notes>","Update notes").option("-w, --waiting <reason>","Set waiting reason").action(async(S,y)=>{try{let q={};if(y.name)q.name=y.name;if(y.status)q.status=y.status;if(y.project==="none")q.projectId=null;else if(y.project)q.projectId=y.project;if(y.due==="none")q.dueDate=null;else if(y.due)q.dueDate=y.due;if(y.notes)q.notes=y.notes;if(y.waiting)q.waitingFor=y.waiting,q.status="waiting";let R=await _j(S,q);if(T())Q(R);else console.log(`Updated: ${K(R)}`)}catch(q){U(q instanceof Error?q.message:"Failed to update action"),process.exit(1)}}),$.command("complete <id>").description("Mark an action as completed").action(async(S)=>{try{let y=await y$(S);if(T())Q(y);else console.log(`Completed: ${K(y)}`)}catch(y){U(y instanceof Error?y.message:"Failed to complete action"),process.exit(1)}}),$.command("delete <id>").description("Delete an action").action(async(S)=>{try{if(await q$(S),T())Q({success:!0,id:S});else console.log(`Deleted action ${S}`)}catch(y){U(y instanceof Error?y.message:"Failed to delete action"),process.exit(1)}}),$.command("count").description("Count actions by status").option("-s, --status <status>","Status to count (default: inbox)").action(async(S)=>{try{let y=S.status??"inbox",q=await v({status:y});if(T())Q({status:y,count:q.length});else console.log(`${y}: ${q.length}`)}catch(y){U(y instanceof Error?y.message:"Failed to count actions"),process.exit(1)}})}function Y$(j){let $=j.command("projects").description("Manage projects");$.command("list").description("List projects").option("-s, --status <status>","Filter by status").option("-d, --domain <domain>","Filter by domain (Work, Personal)").option("-c, --category <id>","Filter by category ID").option("-q, --search <query>","Search by name").option("-r, --review","Show only projects due for review").action(async(S)=>{try{let y=await g({status:S.status,domain:S.domain,categoryId:S.category,search:S.search,dueForReview:S.review});if(T())Q({projects:y});else{let q=S.status?`${S.status} projects`:"Projects";console.log(u(y,q))}}catch(y){U(y instanceof Error?y.message:"Failed to list projects"),process.exit(1)}}),$.command("active").description("List active projects").option("-d, --domain <domain>","Filter by domain (Work, Personal)").action(async(S)=>{try{let y=await g({status:"active",domain:S.domain});if(T())Q({projects:y,count:y.length});else console.log(u(y,"Active Projects"))}catch(y){U(y instanceof Error?y.message:"Failed to list active projects"),process.exit(1)}}),$.command("get <id>").description("Get project details").action(async(S)=>{try{let y=await R$(S);if(T())Q(y);else{if(console.log(V(y)),y.theOneThing)console.log(`
39
- The One Thing: ${y.theOneThing}`);if(y.notes)console.log(`
40
- Notes: ${y.notes}`);if(console.log(`
41
- Status: ${y.status}`),y.reviewAfter)console.log(`Review after: ${y.reviewAfter}`)}}catch(y){U(y instanceof Error?y.message:"Failed to get project"),process.exit(1)}}),$.command("add <name>").description("Create a new project").option("-s, --status <status>","Initial status (default: incubating)").option("-c, --category <id>","Assign to category").option("-t, --the-one-thing <text>","Set the one thing").option("-n, --notes <notes>","Additional notes").action(async(S,y)=>{try{let q=await E$({name:S,status:y.status??"incubating",categoryId:y.category,theOneThing:y.theOneThing,notes:y.notes});if(T())Q(q);else console.log(`Created: ${V(q)}`)}catch(q){U(q instanceof Error?q.message:"Failed to create project"),process.exit(1)}}),$.command("update <id>").description("Update a project").option("-n, --name <name>","New name").option("-s, --status <status>","New status").option("-c, --category <id>",'Assign to category (use "none" to unassign)').option("-t, --the-one-thing <text>","Set the one thing").option("--notes <notes>","Update notes").action(async(S,y)=>{try{let q={};if(y.name)q.name=y.name;if(y.status)q.status=y.status;if(y.category==="none")q.categoryId=null;else if(y.category)q.categoryId=y.category;if(y.theOneThing)q.theOneThing=y.theOneThing;if(y.notes)q.notes=y.notes;let R=await m(S,q);if(T())Q(R);else console.log(`Updated: ${V(R)}`)}catch(q){U(q instanceof Error?q.message:"Failed to update project"),process.exit(1)}}),$.command("activate <id>").description("Set project status to active").action(async(S)=>{try{let y=await m(S,{status:"active"});if(T())Q(y);else console.log(`Activated: ${V(y)}`)}catch(y){U(y instanceof Error?y.message:"Failed to activate project"),process.exit(1)}}),$.command("complete <id>").description("Mark a project as completed").action(async(S)=>{try{let y=await m(S,{status:"completed"});if(T())Q(y);else console.log(`Completed: ${V(y)}`)}catch(y){U(y instanceof Error?y.message:"Failed to complete project"),process.exit(1)}}),$.command("review").description("List projects due for review").action(async()=>{try{let S=await g({dueForReview:!0});if(T())Q({projects:S,count:S.length});else console.log(u(S,"Projects Due for Review"))}catch(S){U(S instanceof Error?S.message:"Failed to list projects for review"),process.exit(1)}})}W.name("ace").description("CLI for Ace productivity assistant").version(bj);j$(W);I$(W);P$(W);J$(W);Y$(W);W.option("--json","Output in JSON format for AI consumption").option("--api-url <url>","Override API URL");W.parse();
36
+ `)}function NG(y){let $=[`[${y.id.slice(0,8)}] ${y.name}`];if($.push(`(${y.accountEmail})`),!y.isEnabled)$.push("[disabled]");return $.join(" ")}function w$(y,$){if(y.length===0)return $?`${$}: (none)`:"(no calendars connected)";let j=y.map((G)=>` ${NG(G)}`);if($)return`${$} (${y.length}):
37
+ ${j.join(`
38
+ `)}`;return j.join(`
39
+ `)}function X$(y){let j=[`${Y$(y.startTime,y.endTime,y.isAllDay)} - ${y.summary}`];if(y.location)j.push(`@ ${y.location}`);return j.join(" ")}function Ty(y,$){if(y.length===0)return $?`${$}: (no events)`:"(no events)";let j=new Map;for(let P of y){let R=t(P.startTime),q=j.get(R)||[];q.push(P),j.set(R,q)}let G=[];if($)G.push(`${$} (${y.length}):`);for(let[P,R]of j){G.push(`
40
+ ${P}:`);for(let q of R){let U=` ${q.isAllDay?"All day":`${x(q.startTime)} - ${x(q.endTime)}`}: ${q.summary}`;if(q.location)U+=` @ ${q.location}`;G.push(U)}}return G.join(`
41
+ `)}function F$(y){let $=y.command("auth").description("Manage authentication");$.command("login").description("Authenticate with Ace").option("--api-url <url>","Ace API URL (default: https://aceisyourassistant.com)").action(async(j)=>{try{await fy(j.apiUrl)}catch(G){E(G instanceof Error?G.message:"Login failed"),process.exit(1)}}),$.command("logout").description("Remove stored credentials").action(()=>{let j=Qy();if(L())Q({success:j});else if(j)console.log("Logged out successfully");else console.log("No credentials to remove")}),$.command("status").description("Show current authentication status").action(()=>{let j=C();if(L())Q({authenticated:!!j,email:j?.userEmail??null,apiUrl:j?.apiUrl??null});else if(j)console.log(`Authenticated as ${j.userEmail}`),console.log(`API URL: ${j.apiUrl}`);else console.log("Not authenticated. Run: ace auth login")}),$.command("whoami").description("Show current user").action(()=>{let j=C();if(L())Q({authenticated:!!j,email:j?.userEmail??null,userId:j?.userId??null});else if(j)console.log(j.userEmail);else console.log("Not authenticated"),process.exit(1)})}class Cy extends Error{status;body;constructor(y,$,j){super(y);this.status=$;this.body=j;this.name="ApiError"}}class By extends Cy{constructor(y="Not authenticated. Run: ace auth login"){super(y,401);this.name="AuthError"}}async function Y(y,$={},j){let G=C();if(!G)throw new By;let R=`${j??G.apiUrl??g()}/api${y}`,q=await fetch(R,{...$,headers:{Authorization:`Bearer ${G.token}`,"Content-Type":"application/json",...$.headers}});if(q.status===401)throw new By("Session expired. Run: ace auth login");if(!q.ok){let S=await q.json().catch(()=>({}));throw new Cy(S.error??`Request failed with status ${q.status}`,q.status,S)}return q.json()}async function _$(){return Y("/dashboard")}async function T(y={}){let $=new URLSearchParams;if(y.status)$.set("status",y.status);if(y.projectId)$.set("project_id",y.projectId);if(y.contextId)$.set("context_id",y.contextId);if(y.search)$.set("search",y.search);if(y.limit)$.set("limit",String(y.limit));if(y.offset)$.set("offset",String(y.offset));if(y.dueBefore)$.set("due_before",y.dueBefore);if(y.dueAfter)$.set("due_after",y.dueAfter);if(y.completedAfter)$.set("completed_after",y.completedAfter);let j=$.toString(),G=j?`/actions?${j}`:"/actions";return(await Y(G)).actions}async function z$(y){return Y(`/actions/${y}`)}async function i(y){return Y("/actions",{method:"POST",body:JSON.stringify(y)})}async function Ny(y,$){return Y(`/actions/${y}`,{method:"PUT",body:JSON.stringify($)})}async function H$(y){return Ny(y,{status:"completed"})}async function W$(y){await Y(`/actions/${y}`,{method:"DELETE"})}async function l(y={}){let $=new URLSearchParams;if(y.status)$.set("status",y.status);if(y.domain)$.set("domain",y.domain);if(y.categoryId)$.set("category_id",y.categoryId);if(y.search)$.set("search",y.search);if(y.dueForReview)$.set("dueForReview","true");if(y.completedAfter)$.set("completed_after",y.completedAfter);let j=$.toString(),G=j?`/projects?${j}`:"/projects";return(await Y(G)).projects}async function M$(y){return Y(`/projects/${y}`)}async function f$(y){return Y("/projects",{method:"POST",body:JSON.stringify(y)})}async function a(y,$){return Y(`/projects/${y}`,{method:"PUT",body:JSON.stringify($)})}async function K$(y){return Y(`/projects/${y}`,{method:"PUT",body:JSON.stringify({action:"review"})})}async function T$(y){await Y(`/projects/${y}`,{method:"DELETE"})}async function B$(){return(await Y("/contexts")).contexts}async function e(y={}){let $=new URLSearchParams;if(y.status)$.set("status",y.status);if(y.domain)$.set("domain",y.domain);if(y.search)$.set("search",y.search);if(y.dueForReview)$.set("dueForReview","true");let j=$.toString(),G=j?`/goals?${j}`:"/goals";return(await Y(G)).goals}async function C$(y,$=!1){let j=$?`/goals/${y}?include=projects`:`/goals/${y}`;return Y(j)}async function N$(y){return Y("/goals",{method:"POST",body:JSON.stringify(y)})}async function n(y,$){return Y(`/goals/${y}`,{method:"PUT",body:JSON.stringify($)})}async function x$(y){return Y(`/goals/${y}`,{method:"PUT",body:JSON.stringify({action:"review"})})}async function V$(y){await Y(`/goals/${y}`,{method:"DELETE"})}async function A$(){return(await Y("/domains")).domains}async function D$(y={}){let $=new URLSearchParams;if(y.source)$.set("source",y.source);if(y.limit)$.set("limit",String(y.limit));let j=$.toString(),G=j?`/activity-log?${j}`:"/activity-log";return(await Y(G)).logs}async function k$(y){return Y("/activity-log",{method:"POST",body:JSON.stringify(y)})}async function xy(){return(await Y("/calendar/calendars")).calendars}async function Vy(y={}){let $=new URLSearchParams;if(y.calendarId)$.set("calendarId",y.calendarId);if(y.startDate)$.set("startDate",y.startDate);if(y.endDate)$.set("endDate",y.endDate);if(y.limit)$.set("limit",String(y.limit));if(y.pageToken)$.set("pageToken",y.pageToken);let j=$.toString(),G=j?`/calendar/events?${j}`:"/calendar/events";return Y(G)}async function b$(y){return(await Y("/calendar/events",{method:"POST",body:JSON.stringify(y)})).event}function v$(y){y.command("capture").description("Quick capture an item to inbox").argument("<text>","The item to capture").option("-n, --notes <notes>","Additional notes").action(async($,j)=>{try{let G=await i({name:$,status:"inbox",notes:j.notes});if(L())Q(G);else console.log(`Captured: ${f(G)}`)}catch(G){E(G instanceof Error?G.message:"Capture failed"),process.exit(1)}})}function h$(y){y.command("orient").description("Daily orientation - see your current state").alias("dashboard").action(async()=>{try{let $=await _$();if(L())Q($);else console.log(c$($))}catch($){E($ instanceof Error?$.message:"Failed to load dashboard"),process.exit(1)}})}function xG(){let y=new Date;return y.setHours(0,0,0,0),y}function o(y){return y.toISOString().split("T")[0]}function h(y){let $=xG();if(y==="overdue")return{dueBefore:o($)};if(y==="today"){let j=new Date($);return j.setDate(j.getDate()+1),{dueAfter:o($),dueBefore:o(j)}}if(y==="week"){let j=new Date($);return j.setDate(j.getDate()+7),{dueBefore:o(j)}}return{}}function O$(y){if(y==="today")return h("today");if(y==="week")return h("week");return{dueBefore:y}}function p(y){let $=new Date;return $.setDate($.getDate()-y),$.toISOString()}function u$(y){let $=y.command("actions").description("Manage actions");$.command("list").description("List actions").option("-s, --status <status>","Filter by status (inbox, active, waiting, someday)").option("-p, --project <id>","Filter by project ID").option("-c, --context <id>","Filter by context ID").option("-q, --search <query>","Search by name").option("-l, --limit <n>","Limit results","50").option("-d, --due <period>","Filter by due date (today, week, or YYYY-MM-DD)").option("--overdue","Show only overdue actions").action(async(j)=>{try{let G,P;if(j.overdue)G=h("overdue").dueBefore;else if(j.due){let q=O$(j.due);G=q.dueBefore,P=q.dueAfter}let R=await T({status:j.status,projectId:j.project,contextId:j.context,search:j.search,limit:parseInt(j.limit),dueBefore:G,dueAfter:P});if(L())Q({actions:R});else{let q=j.status?`${j.status} actions`:"Actions";console.log(_(R,q))}}catch(G){E(G instanceof Error?G.message:"Failed to list actions"),process.exit(1)}}),$.command("inbox").description("List inbox items").action(async()=>{try{let j=await T({status:"inbox"});if(L())Q({actions:j,count:j.length});else console.log(_(j,"Inbox"))}catch(j){E(j instanceof Error?j.message:"Failed to list inbox"),process.exit(1)}}),$.command("due").description("List actions due today").option("-w, --week","Show actions due this week").action(async(j)=>{try{let G=h(j.week?"week":"today"),P=await T({status:"active",dueBefore:G.dueBefore,dueAfter:G.dueAfter});if(L())Q({actions:P,count:P.length});else{let R=j.week?"Due This Week":"Due Today";console.log(_(P,R))}}catch(G){E(G instanceof Error?G.message:"Failed to list due actions"),process.exit(1)}}),$.command("overdue").description("List overdue actions").action(async()=>{try{let j=h("overdue"),G=await T({status:"active",dueBefore:j.dueBefore});if(L())Q({actions:G,count:G.length});else console.log(_(G,"Overdue"))}catch(j){E(j instanceof Error?j.message:"Failed to list overdue actions"),process.exit(1)}}),$.command("waiting").description("List actions waiting on someone/something").action(async()=>{try{let j=await T({status:"waiting"});if(L())Q({actions:j,count:j.length});else console.log(_(j,"Waiting"))}catch(j){E(j instanceof Error?j.message:"Failed to list waiting actions"),process.exit(1)}}),$.command("get <id>").description("Get action details").action(async(j)=>{try{let G=await z$(j);if(L())Q(G);else{if(console.log(f(G)),G.notes)console.log(`
42
+ Notes: ${G.notes}`);if(G.contexts.length>0)console.log(`
43
+ Contexts: ${G.contexts.map((P)=>P.name).join(", ")}`)}}catch(G){E(G instanceof Error?G.message:"Failed to get action"),process.exit(1)}}),$.command("add <name>").description("Create a new action").option("-s, --status <status>","Initial status (default: inbox)").option("-p, --project <id>","Assign to project").option("-d, --due <date>","Due date (YYYY-MM-DD)").option("-n, --notes <notes>","Additional notes").action(async(j,G)=>{try{let P=await i({name:j,status:G.status??"inbox",projectId:G.project,dueDate:G.due,notes:G.notes});if(L())Q(P);else console.log(`Created: ${f(P)}`)}catch(P){E(P instanceof Error?P.message:"Failed to create action"),process.exit(1)}}),$.command("update <id>").description("Update an action").option("-n, --name <name>","New name").option("-s, --status <status>","New status").option("-p, --project <id>",'Assign to project (use "none" to unassign)').option("-d, --due <date>",'Due date (YYYY-MM-DD, or "none" to clear)').option("--notes <notes>","Update notes").option("-w, --waiting <reason>","Set waiting reason").action(async(j,G)=>{try{let P={};if(G.name)P.name=G.name;if(G.status)P.status=G.status;if(G.project==="none")P.projectId=null;else if(G.project)P.projectId=G.project;if(G.due==="none")P.dueDate=null;else if(G.due)P.dueDate=G.due;if(G.notes)P.notes=G.notes;if(G.waiting)P.waitingFor=G.waiting,P.status="waiting";let R=await Ny(j,P);if(L())Q(R);else console.log(`Updated: ${f(R)}`)}catch(P){E(P instanceof Error?P.message:"Failed to update action"),process.exit(1)}}),$.command("complete <id>").description("Mark an action as completed").action(async(j)=>{try{let G=await H$(j);if(L())Q(G);else console.log(`Completed: ${f(G)}`)}catch(G){E(G instanceof Error?G.message:"Failed to complete action"),process.exit(1)}}),$.command("delete <id>").description("Delete an action").action(async(j)=>{try{if(await W$(j),L())Q({success:!0,id:j});else console.log(`Deleted action ${j}`)}catch(G){E(G instanceof Error?G.message:"Failed to delete action"),process.exit(1)}}),$.command("count").description("Count actions by status").option("-s, --status <status>","Status to count (default: inbox)").action(async(j)=>{try{let G=j.status??"inbox",P=await T({status:G});if(L())Q({status:G,count:P.length});else console.log(`${G}: ${P.length}`)}catch(G){E(G instanceof Error?G.message:"Failed to count actions"),process.exit(1)}}),$.command("completed").description("List recently completed actions").option("-d, --days <n>","Number of days to look back","7").option("-l, --limit <n>","Max items to return","50").action(async(j)=>{try{let G=parseInt(j.days),P=await T({status:"completed",completedAfter:p(G),limit:parseInt(j.limit)});if(L())Q({actions:P,count:P.length,days:G});else console.log(_(P,`Completed (last ${j.days} days)`))}catch(G){E(G instanceof Error?G.message:"Failed to list completed actions"),process.exit(1)}})}function g$(y){let $=y.command("projects").description("Manage projects");$.command("list").description("List projects").option("-s, --status <status>","Filter by status").option("-d, --domain <domain>","Filter by domain (Work, Personal)").option("-c, --category <id>","Filter by category ID").option("-q, --search <query>","Search by name").option("-r, --review","Show only projects due for review").action(async(j)=>{try{let G=await l({status:j.status,domain:j.domain,categoryId:j.category,search:j.search,dueForReview:j.review});if(L())Q({projects:G});else{let P=j.status?`${j.status} projects`:"Projects";console.log(v(G,P))}}catch(G){E(G instanceof Error?G.message:"Failed to list projects"),process.exit(1)}}),$.command("active").description("List active projects").option("-d, --domain <domain>","Filter by domain (Work, Personal)").action(async(j)=>{try{let G=await l({status:"active",domain:j.domain});if(L())Q({projects:G,count:G.length});else console.log(v(G,"Active Projects"))}catch(G){E(G instanceof Error?G.message:"Failed to list active projects"),process.exit(1)}}),$.command("get <id>").description("Get project details").action(async(j)=>{try{let G=await M$(j);if(L())Q(G);else{if(console.log(K(G)),G.theOneThing)console.log(`
44
+ The One Thing: ${G.theOneThing}`);if(G.notes)console.log(`
45
+ Notes: ${G.notes}`);if(console.log(`
46
+ Status: ${G.status}`),G.reviewAfter)console.log(`Review after: ${G.reviewAfter}`)}}catch(G){E(G instanceof Error?G.message:"Failed to get project"),process.exit(1)}}),$.command("add <name>").description("Create a new project").option("-s, --status <status>","Initial status (default: incubating)").option("-c, --category <id>","Assign to category").option("-t, --the-one-thing <text>","Set the one thing").option("-n, --notes <notes>","Additional notes").action(async(j,G)=>{try{let P=await f$({name:j,status:G.status??"incubating",categoryId:G.category,theOneThing:G.theOneThing,notes:G.notes});if(L())Q(P);else console.log(`Created: ${K(P)}`)}catch(P){E(P instanceof Error?P.message:"Failed to create project"),process.exit(1)}}),$.command("update <id>").description("Update a project").option("-n, --name <name>","New name").option("-s, --status <status>","New status").option("-c, --category <id>",'Assign to category (use "none" to unassign)').option("-t, --the-one-thing <text>","Set the one thing").option("--notes <notes>","Update notes").action(async(j,G)=>{try{let P={};if(G.name)P.name=G.name;if(G.status)P.status=G.status;if(G.category==="none")P.categoryId=null;else if(G.category)P.categoryId=G.category;if(G.theOneThing)P.theOneThing=G.theOneThing;if(G.notes)P.notes=G.notes;let R=await a(j,P);if(L())Q(R);else console.log(`Updated: ${K(R)}`)}catch(P){E(P instanceof Error?P.message:"Failed to update project"),process.exit(1)}}),$.command("activate <id>").description("Set project status to active").action(async(j)=>{try{let G=await a(j,{status:"active"});if(L())Q(G);else console.log(`Activated: ${K(G)}`)}catch(G){E(G instanceof Error?G.message:"Failed to activate project"),process.exit(1)}}),$.command("complete <id>").description("Mark a project as completed").action(async(j)=>{try{let G=await a(j,{status:"completed"});if(L())Q(G);else console.log(`Completed: ${K(G)}`)}catch(G){E(G instanceof Error?G.message:"Failed to complete project"),process.exit(1)}}),$.command("review").description("List projects due for review").action(async()=>{try{let j=await l({dueForReview:!0});if(L())Q({projects:j,count:j.length});else console.log(v(j,"Projects Due for Review"))}catch(j){E(j instanceof Error?j.message:"Failed to list projects for review"),process.exit(1)}}),$.command("mark-reviewed <id>").description("Mark a project as reviewed (resets review timer)").action(async(j)=>{try{let G=await K$(j);if(L())Q(G);else console.log(`Marked as reviewed: ${K(G)}`)}catch(G){E(G instanceof Error?G.message:"Failed to mark project as reviewed"),process.exit(1)}}),$.command("drop <id>").description("Drop a project (soft delete)").action(async(j)=>{try{if(await T$(j),L())Q({success:!0,id:j});else console.log(`Dropped project ${j}`)}catch(G){E(G instanceof Error?G.message:"Failed to drop project"),process.exit(1)}}),$.command("completed").description("List recently completed projects").option("-d, --days <n>","Number of days to look back","7").action(async(j)=>{try{let G=parseInt(j.days),P=await l({status:"completed",completedAfter:p(G)});if(L())Q({projects:P,count:P.length,days:G});else console.log(v(P,`Completed (last ${j.days} days)`))}catch(G){E(G instanceof Error?G.message:"Failed to list completed projects"),process.exit(1)}})}function A(y){let $=y.id.slice(0,8),j=y.domain_name?` (${y.domain_name})`:"";return`[${$}] ${y.name}${j}`}function Ay(y,$){if(y.length===0)return`${$}: (none)`;let j=[`${$} (${y.length}):`],G=y.reduce((P,R)=>{let q=R.domain_name||"Unknown";if(!P[q])P[q]=[];return P[q].push(R),P},{});for(let[P,R]of Object.entries(G)){j.push(`
47
+ ${P}:`);for(let q of R){let S=q.status!=="active"?` [${q.status}]`:"";if(j.push(` ${A(q)}${S}`),q.theOneThing)j.push(` Focus: ${q.theOneThing}`);if(q.project_count!==void 0)j.push(` Projects: ${q.project_count}`)}}return j.join(`
48
+ `)}function t$(y){let $=y.command("goals").description("Manage goals");$.command("list").description("List goals").option("-s, --status <status>","Filter by status (active, paused, completed, dropped)").option("-d, --domain <domain>","Filter by domain (Work, Personal)").option("-q, --search <query>","Search by name").option("-r, --review","Show only goals due for review").action(async(j)=>{try{let G=await e({status:j.status,domain:j.domain,search:j.search,dueForReview:j.review});if(L())Q({goals:G});else{let P=j.status?`${j.status} goals`:"Goals";console.log(Ay(G,P))}}catch(G){E(G instanceof Error?G.message:"Failed to list goals"),process.exit(1)}}),$.command("active").description("List active goals").option("-d, --domain <domain>","Filter by domain (Work, Personal)").action(async(j)=>{try{let G=await e({status:"active",domain:j.domain});if(L())Q({goals:G,count:G.length});else console.log(Ay(G,"Active Goals"))}catch(G){E(G instanceof Error?G.message:"Failed to list active goals"),process.exit(1)}}),$.command("get <id>").description("Get goal details").option("-p, --projects","Include linked projects").action(async(j,G)=>{try{let P=await C$(j,G.projects);if(L())Q(P);else{if(console.log(A(P)),console.log(`
49
+ Status: ${P.status}`),P.theOneThing)console.log(`Focus: ${P.theOneThing}`);if(P.notes)console.log(`
50
+ Notes: ${P.notes}`);if(P.reviewAfter)console.log(`
51
+ Review after: ${P.reviewAfter}`);if(P.projects&&P.projects.length>0){console.log(`
52
+ Linked Projects (${P.projects.length}):`);for(let R of P.projects)console.log(` - ${R.name} [${R.status}]`)}}}catch(P){E(P instanceof Error?P.message:"Failed to get goal"),process.exit(1)}}),$.command("add <name>").description("Create a new goal").option("-d, --domain <domain>","Domain (Work or Personal)","Personal").option("-s, --status <status>","Initial status (default: active)").option("-f, --focus <text>","Set the focus/one thing").option("-n, --notes <notes>","Additional notes").action(async(j,G)=>{try{let P=await A$();if(!P||P.length===0)E("No domains found. Please check your Ace configuration."),process.exit(1);let R=P.find((S)=>S.name.toLowerCase()===G.domain.toLowerCase());if(!R){let S=P.map((U)=>U.name).join(", ");E(`Invalid domain: ${G.domain}. Valid options: ${S}`),process.exit(1)}let q=await N$({name:j,domainId:R.id,status:G.status??"active",theOneThing:G.focus,notes:G.notes});if(L())Q(q);else console.log(`Created: ${A(q)}`)}catch(P){E(P instanceof Error?P.message:"Failed to create goal"),process.exit(1)}}),$.command("update <id>").description("Update a goal").option("-n, --name <name>","New name").option("-s, --status <status>","New status").option("-f, --focus <text>","Update the focus/one thing").option("--notes <notes>","Update notes").action(async(j,G)=>{try{let P={};if(G.name)P.name=G.name;if(G.status)P.status=G.status;if(G.focus)P.theOneThing=G.focus;if(G.notes)P.notes=G.notes;let R=await n(j,P);if(L())Q(R);else console.log(`Updated: ${A(R)}`)}catch(P){E(P instanceof Error?P.message:"Failed to update goal"),process.exit(1)}}),$.command("mark-reviewed <id>").description("Mark a goal as reviewed (resets review timer)").action(async(j)=>{try{let G=await x$(j);if(L())Q(G);else console.log(`Marked as reviewed: ${A(G)}`)}catch(G){E(G instanceof Error?G.message:"Failed to mark goal as reviewed"),process.exit(1)}}),$.command("complete <id>").description("Mark a goal as completed").action(async(j)=>{try{let G=await n(j,{status:"completed"});if(L())Q(G);else console.log(`Completed: ${A(G)}`)}catch(G){E(G instanceof Error?G.message:"Failed to complete goal"),process.exit(1)}}),$.command("pause <id>").description("Pause a goal").action(async(j)=>{try{let G=await n(j,{status:"paused"});if(L())Q(G);else console.log(`Paused: ${A(G)}`)}catch(G){E(G instanceof Error?G.message:"Failed to pause goal"),process.exit(1)}}),$.command("drop <id>").description("Drop a goal").action(async(j)=>{try{if(await V$(j),L())Q({success:!0,id:j});else console.log(`Dropped goal ${j}`)}catch(G){E(G instanceof Error?G.message:"Failed to drop goal"),process.exit(1)}}),$.command("review").description("List goals due for review").action(async()=>{try{let j=await e({dueForReview:!0});if(L())Q({goals:j,count:j.length});else console.log(Ay(j,"Goals Due for Review"))}catch(j){E(j instanceof Error?j.message:"Failed to list goals for review"),process.exit(1)}})}function VG(y,$){if(y.length===0)return`${$}: (none)`;let j=[`${$} (${y.length}):`],G=y.reduce((P,R)=>{let q=new Date(R.timestamp).toLocaleDateString();if(!P[q])P[q]=[];return P[q].push(R),P},{});for(let[P,R]of Object.entries(G)){j.push(`
53
+ ${P}:`);for(let q of R){let S=new Date(q.timestamp).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});j.push(` ${S} [${q.source}] ${q.summary}`)}}return j.join(`
54
+ `)}function m$(y){let $=y.command("activity").description("View and log activity");$.command("list").description("List activity log entries").option("-s, --source <source>","Filter by source (manual, git, calendar, etc.)").option("-l, --limit <n>","Limit results","50").action(async(j)=>{try{let G=await D$({source:j.source,limit:parseInt(j.limit)});if(L())Q({logs:G});else{let P=j.source?`Activity (${j.source})`:"Recent Activity";console.log(VG(G,P))}}catch(G){E(G instanceof Error?G.message:"Failed to list activity"),process.exit(1)}}),$.command("log <summary>").description("Log an activity").option("-s, --source <source>","Activity source","manual").option("-p, --project <id>","Link to project").option("-a, --action <id>","Link to action").action(async(j,G)=>{try{let P=await k$({source:G.source,summary:j,project_id:G.project,action_id:G.action});if(L())Q(P);else if(console.log(`Logged: ${j}`),G.project)console.log(` Linked to project: ${G.project}`)}catch(P){E(P instanceof Error?P.message:"Failed to log activity"),process.exit(1)}})}function l$(y){y.command("contexts").description("Manage contexts").command("list").description("List all contexts").action(async()=>{try{let j=await B$();if(L())Q({contexts:j});else if(j.length===0)console.log("No contexts found");else{console.log("Contexts:");for(let G of j){let P=G.type?` (${G.type})`:"";console.log(` [${G.id.slice(0,8)}] ${G.name}${P}`)}}}catch(j){E(j instanceof Error?j.message:"Failed to list contexts"),process.exit(1)}})}var AG=30,s$=1,r$=250,DG=50;function d$(y){let $=y.command("calendar").description("Manage calendar events");$.command("list").description("List connected calendars").action(async()=>{try{let j=await xy();if(L())Q({calendars:j});else console.log(w$(j,"Connected Calendars"))}catch(j){E(j instanceof Error?j.message:"Failed to list calendars"),process.exit(1)}}),$.command("events").description("List calendar events").option("-c, --calendar <id>","Filter by calendar ID").option("-d, --date <date>","Date to show events for (YYYY-MM-DD, default: today)").option("-w, --week","Show events for the next 7 days").option("--from <date>","Start date for range (YYYY-MM-DD)").option("--to <date>","End date for range (YYYY-MM-DD)").option("-l, --limit <n>","Maximum number of events",String(DG)).option("--page-token <token>","Page token for pagination (requires --calendar)").action(async(j)=>{try{if(j.pageToken&&!j.calendar)E("--page-token requires --calendar to be specified"),process.exit(1);let G,P;if(j.from&&j.to){let S=V(j.from),U=V(j.to);G=S.startDate,P=U.endDate}else if(j.week){let S=V("week");G=S.startDate,P=S.endDate}else if(j.date){let S=V(j.date);G=S.startDate,P=S.endDate}else{let S=V("today");G=S.startDate,P=S.endDate}let R=parseInt(j.limit);if(isNaN(R)||R<s$||R>r$)E(`Invalid limit. Must be between ${s$} and ${r$}.`),process.exit(1);let q=await Vy({calendarId:j.calendar,startDate:G,endDate:P,limit:R,pageToken:j.pageToken});if(L())Q({events:q.events,count:q.events.length,nextPageToken:q.nextPageToken});else{let S="Events";if(j.week)S="Events (next 7 days)";else if(j.date)S=`Events for ${j.date}`;else if(j.from&&j.to)S=`Events from ${j.from} to ${j.to}`;else S=`Events for ${m()}`;if(console.log(Ty(q.events,S)),q.nextPageToken)console.log(`
55
+ More events available. Use --page-token ${q.nextPageToken} to see next page.`)}}catch(G){E(G instanceof Error?G.message:"Failed to list events"),process.exit(1)}}),$.command("today").description("List today's calendar events").option("-c, --calendar <id>","Filter by calendar ID").action(async(j)=>{try{let G=V("today"),P=await Vy({calendarId:j.calendar,startDate:G.startDate,endDate:G.endDate});if(L())Q({events:P.events,count:P.events.length,date:m()});else console.log(Ty(P.events,`Today (${m()})`))}catch(G){E(G instanceof Error?G.message:"Failed to list today's events"),process.exit(1)}}),$.command("add <summary>").description("Create a new calendar event").option("-c, --calendar <id>","Calendar ID to create event on").option("-s, --start <time>","Start time (e.g., 14:00, 2pm)","").option("-e, --end <time>","End time (e.g., 15:00, 3pm)").option("--duration <minutes>","Duration in minutes (alternative to --end)",String(AG)).option("-d, --date <date>","Date for the event (YYYY-MM-DD, default: today)").option("-l, --location <location>","Event location").option("--description <text>","Event description").option("--timezone <tz>","Timezone for the event (e.g., America/New_York, default: calendar's timezone)").action(async(j,G)=>{try{if(!G.calendar){let I=(await xy()).filter((J)=>J.isEnabled);if(I.length===0)E("No calendars connected. Connect a calendar via the web app first."),process.exit(1);if(I.length===1)G.calendar=I[0].id;else{let J=I.map((Z)=>` ${Z.id.slice(0,8)} - ${Z.name} (${Z.accountEmail})`).join(`
56
+ `);E(`Multiple calendars available. Please specify --calendar <id>:
57
+ ${J}`),process.exit(1)}}if(!G.start)E("Start time is required. Use --start <time> (e.g., --start 14:00 or --start 2pm)"),process.exit(1);let P=G.date||m(),R;try{R=Ky(G.start,P)}catch(U){E(U instanceof Error?U.message:"Invalid start time"),process.exit(1)}let q;if(G.end)try{q=Ky(G.end,P)}catch(U){E(U instanceof Error?U.message:"Invalid end time"),process.exit(1)}else{let U=parseInt(G.duration);if(isNaN(U)||U<=0)E("Invalid duration. Must be a positive number of minutes."),process.exit(1);q=Z$(R,U)}let S=await b$({calendarId:G.calendar,summary:j,startTime:R,endTime:q,location:G.location,description:G.description,timeZone:G.timezone});if(L())Q(S);else console.log(`Created: ${X$(S)}`)}catch(P){E(P instanceof Error?P.message:"Failed to create event"),process.exit(1)}})}F.name("ace").description("CLI for Ace productivity assistant").version(ey);F$(F);v$(F);h$(F);u$(F);g$(F);t$(F);m$(F);l$(F);d$(F);F.option("--json","Output in JSON format for AI consumption").option("--api-url <url>","Override API URL");F.parse();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ace-assistant-cli",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "CLI for Ace productivity assistant - bring your own AI",
5
5
  "type": "module",
6
6
  "bin": {