@frontstackdev/cli 0.0.0-canary-20240907183730 → 0.0.0-canary-20240907200342

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -40,10 +40,10 @@ Provides information about the currently logged in user, their organization and
40
40
  Select current working project or display all projects
41
41
 
42
42
  ```bash
43
- # To List projects
44
- frontstack project --list
43
+ # List and select a project
44
+ frontstack project
45
45
 
46
- # To select a project
46
+ # Select a project by ID
47
47
  frontstack project -p a2dc8820-2e52-427a-8d58-0256f28d3db9
48
48
  ```
49
49
 
@@ -1,39 +1,39 @@
1
1
  #!/usr/bin/env node
2
- var Ce=Object.defineProperty;var l=(s,e)=>Ce(s,"name",{value:e,configurable:!0});var v,j,k,x,P,H,S;import Ae from"events";import Ee from"child_process";import g from"path";import y,{readFileSync as $e}from"fs";import Se from"process";import m from"chalk";import Te from"js-yaml";import ve from"http";import je from"open";import E from"handlebars";import ke from"openapi-typescript";var b={},R={},T={};let ee=(v=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},l(v,"CommanderError"),v),xe=(j=class extends ee{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}},l(j,"InvalidArgumentError"),j);T.CommanderError=ee,T.InvalidArgumentError=xe;const{InvalidArgumentError:Pe}=T;let He=(k=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new Pe(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}},l(k,"Argument"),k);function Re(s){const e=s.name()+(s.variadic===!0?"...":"");return s.required?"<"+e+">":"["+e+"]"}l(Re,"humanReadableArgName$2"),R.Argument=He,R.humanReadableArgName=Re;var te={},L={};const{humanReadableArgName:Ne}=R;let Ve=(x=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){const t=e.commands.filter(r=>!r._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((r,i)=>r.name().localeCompare(i.name())),t}compareOptions(e,t){const n=l(r=>r.short?r.short.replace(/^-/,""):r.long.replace(/^--/,""),"getSortKey");return n(e).localeCompare(n(t))}visibleOptions(e){const t=e.options.filter(r=>!r.hidden),n=e._getHelpOption();if(n&&!n.hidden){const r=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);!r&&!i?t.push(n):n.long&&!i?t.push(e.createOption(n.long,n.description)):n.short&&!r&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];const t=[];for(let n=e.parent;n;n=n.parent){const r=n.options.filter(i=>!i.hidden);t.push(...r)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){const t=e.registeredArguments.map(n=>Ne(n)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((n,r)=>Math.max(n,t.subcommandTerm(r).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((n,r)=>Math.max(n,t.optionTerm(r).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((n,r)=>Math.max(n,t.optionTerm(r).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((n,r)=>Math.max(n,t.argumentTerm(r).length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let n="";for(let r=e.parent;r;r=r.parent)n=r.name()+" "+n;return n+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){const t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){const t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){const n=`(${t.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatHelp(e,t){const n=t.padWidth(e,t),r=t.helpWidth||80,i=2,a=2;function u(f,w){if(w){const D=`${f.padEnd(n+a)}${w}`;return t.wrap(D,r-i,n+a)}return f}l(u,"formatItem");function c(f){return f.join(`
3
- `).replace(/^/gm," ".repeat(i))}l(c,"formatList");let p=[`Usage: ${t.commandUsage(e)}`,""];const o=t.commandDescription(e);o.length>0&&(p=p.concat([t.wrap(o,r,0),""]));const h=t.visibleArguments(e).map(f=>u(t.argumentTerm(f),t.argumentDescription(f)));h.length>0&&(p=p.concat(["Arguments:",c(h),""]));const d=t.visibleOptions(e).map(f=>u(t.optionTerm(f),t.optionDescription(f)));if(d.length>0&&(p=p.concat(["Options:",c(d),""])),this.showGlobalOptions){const f=t.visibleGlobalOptions(e).map(w=>u(t.optionTerm(w),t.optionDescription(w)));f.length>0&&(p=p.concat(["Global Options:",c(f),""]))}const O=t.visibleCommands(e).map(f=>u(t.subcommandTerm(f),t.subcommandDescription(f)));return O.length>0&&(p=p.concat(["Commands:",c(O),""])),p.join(`
4
- `)}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,n,r=40){const i=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",a=new RegExp(`[\\n][${i}]+`);if(e.match(a))return e;const u=t-n;if(u<r)return e;const c=e.slice(0,n),p=e.slice(n).replace(`\r
2
+ var we=Object.defineProperty;var l=(i,e)=>we(i,"name",{value:e,configurable:!0});var v,j,k,x,P,H,S;import Ae from"events";import Ee from"child_process";import g from"path";import y,{readFileSync as $e}from"fs";import Se from"process";import m from"chalk";import Te from"js-yaml";import ve from"http";import je from"open";import E from"handlebars";import ke from"openapi-typescript";import{createRequire as xe}from"module";var b={},R={},T={};let ee=(v=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},l(v,"CommanderError"),v),Pe=(j=class extends ee{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}},l(j,"InvalidArgumentError"),j);T.CommanderError=ee,T.InvalidArgumentError=Pe;const{InvalidArgumentError:He}=T;let Re=(k=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new He(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}},l(k,"Argument"),k);function Ie(i){const e=i.name()+(i.variadic===!0?"...":"");return i.required?"<"+e+">":"["+e+"]"}l(Ie,"humanReadableArgName$2"),R.Argument=Re,R.humanReadableArgName=Ie;var te={},L={};const{humanReadableArgName:Ne}=R;let Ve=(x=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){const t=e.commands.filter(r=>!r._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((r,s)=>r.name().localeCompare(s.name())),t}compareOptions(e,t){const n=l(r=>r.short?r.short.replace(/^-/,""):r.long.replace(/^--/,""),"getSortKey");return n(e).localeCompare(n(t))}visibleOptions(e){const t=e.options.filter(r=>!r.hidden),n=e._getHelpOption();if(n&&!n.hidden){const r=n.short&&e._findOption(n.short),s=n.long&&e._findOption(n.long);!r&&!s?t.push(n):n.long&&!s?t.push(e.createOption(n.long,n.description)):n.short&&!r&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];const t=[];for(let n=e.parent;n;n=n.parent){const r=n.options.filter(s=>!s.hidden);t.push(...r)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){const t=e.registeredArguments.map(n=>Ne(n)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((n,r)=>Math.max(n,t.subcommandTerm(r).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((n,r)=>Math.max(n,t.optionTerm(r).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((n,r)=>Math.max(n,t.optionTerm(r).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((n,r)=>Math.max(n,t.argumentTerm(r).length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let n="";for(let r=e.parent;r;r=r.parent)n=r.name()+" "+n;return n+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){const t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){const t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){const n=`(${t.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatHelp(e,t){const n=t.padWidth(e,t),r=t.helpWidth||80,s=2,a=2;function u(f,C){if(C){const D=`${f.padEnd(n+a)}${C}`;return t.wrap(D,r-s,n+a)}return f}l(u,"formatItem");function c(f){return f.join(`
3
+ `).replace(/^/gm," ".repeat(s))}l(c,"formatList");let p=[`Usage: ${t.commandUsage(e)}`,""];const o=t.commandDescription(e);o.length>0&&(p=p.concat([t.wrap(o,r,0),""]));const h=t.visibleArguments(e).map(f=>u(t.argumentTerm(f),t.argumentDescription(f)));h.length>0&&(p=p.concat(["Arguments:",c(h),""]));const d=t.visibleOptions(e).map(f=>u(t.optionTerm(f),t.optionDescription(f)));if(d.length>0&&(p=p.concat(["Options:",c(d),""])),this.showGlobalOptions){const f=t.visibleGlobalOptions(e).map(C=>u(t.optionTerm(C),t.optionDescription(C)));f.length>0&&(p=p.concat(["Global Options:",c(f),""]))}const O=t.visibleCommands(e).map(f=>u(t.subcommandTerm(f),t.subcommandDescription(f)));return O.length>0&&(p=p.concat(["Commands:",c(O),""])),p.join(`
4
+ `)}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,n,r=40){const s=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",a=new RegExp(`[\\n][${s}]+`);if(e.match(a))return e;const u=t-n;if(u<r)return e;const c=e.slice(0,n),p=e.slice(n).replace(`\r
5
5
  `,`
6
6
  `),o=" ".repeat(n),d="\\s\u200B",O=new RegExp(`
7
- |.{1,${u-1}}([${d}]|$)|[^${d}]+?([${d}]|$)`,"g"),f=p.match(O)||[];return c+f.map((w,D)=>w===`
8
- `?"":(D>0?o:"")+w.trimEnd()).join(`
9
- `)}},l(x,"Help"),x);L.Help=Ve;var I={};const{InvalidArgumentError:Ie}=T;let Fe=(P=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;const n=qe(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new Ie(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return Le(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},l(P,"Option"),P),De=(H=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,n)=>{this.positiveOptions.has(n)&&this.dualOptions.add(n)})}valueFromOption(e,t){const n=t.attributeName();if(!this.dualOptions.has(n))return!0;const r=this.negativeOptions.get(n).presetArg,i=r!==void 0?r:!1;return t.negate===(i===e)}},l(H,"DualOptions"),H);function Le(s){return s.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}l(Le,"camelcase");function qe(s){let e,t;const n=s.split(/[ |,]+/);return n.length>1&&!/^[[<]/.test(n[1])&&(e=n.shift()),t=n.shift(),!e&&/^-[^-]$/.test(t)&&(e=t,t=void 0),{shortFlag:e,longFlag:t}}l(qe,"splitOptionFlags"),I.Option=Fe,I.DualOptions=De;var ne={};const re=3;function Ue(s,e){if(Math.abs(s.length-e.length)>re)return Math.max(s.length,e.length);const t=[];for(let n=0;n<=s.length;n++)t[n]=[n];for(let n=0;n<=e.length;n++)t[0][n]=n;for(let n=1;n<=e.length;n++)for(let r=1;r<=s.length;r++){let i=1;s[r-1]===e[n-1]?i=0:i=1,t[r][n]=Math.min(t[r-1][n]+1,t[r][n-1]+1,t[r-1][n-1]+i),r>1&&n>1&&s[r-1]===e[n-2]&&s[r-2]===e[n-1]&&(t[r][n]=Math.min(t[r][n],t[r-2][n-2]+1))}return t[s.length][e.length]}l(Ue,"editDistance");function Me(s,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));const t=s.startsWith("--");t&&(s=s.slice(2),e=e.map(a=>a.slice(2)));let n=[],r=re;const i=.4;return e.forEach(a=>{if(a.length<=1)return;const u=Ue(s,a),c=Math.max(s.length,a.length);(c-u)/c>i&&(u<r?(r=u,n=[a]):u===r&&n.push(a))}),n.sort((a,u)=>a.localeCompare(u)),t&&(n=n.map(a=>`--${a}`)),n.length>1?`
7
+ |.{1,${u-1}}([${d}]|$)|[^${d}]+?([${d}]|$)`,"g"),f=p.match(O)||[];return c+f.map((C,D)=>C===`
8
+ `?"":(D>0?o:"")+C.trimEnd()).join(`
9
+ `)}},l(x,"Help"),x);L.Help=Ve;var V={};const{InvalidArgumentError:Fe}=T;let De=(P=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;const n=Ue(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new Fe(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return qe(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},l(P,"Option"),P),Le=(H=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,n)=>{this.positiveOptions.has(n)&&this.dualOptions.add(n)})}valueFromOption(e,t){const n=t.attributeName();if(!this.dualOptions.has(n))return!0;const r=this.negativeOptions.get(n).presetArg,s=r!==void 0?r:!1;return t.negate===(s===e)}},l(H,"DualOptions"),H);function qe(i){return i.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}l(qe,"camelcase");function Ue(i){let e,t;const n=i.split(/[ |,]+/);return n.length>1&&!/^[[<]/.test(n[1])&&(e=n.shift()),t=n.shift(),!e&&/^-[^-]$/.test(t)&&(e=t,t=void 0),{shortFlag:e,longFlag:t}}l(Ue,"splitOptionFlags"),V.Option=De,V.DualOptions=Le;var ne={};const re=3;function Me(i,e){if(Math.abs(i.length-e.length)>re)return Math.max(i.length,e.length);const t=[];for(let n=0;n<=i.length;n++)t[n]=[n];for(let n=0;n<=e.length;n++)t[0][n]=n;for(let n=1;n<=e.length;n++)for(let r=1;r<=i.length;r++){let s=1;i[r-1]===e[n-1]?s=0:s=1,t[r][n]=Math.min(t[r-1][n]+1,t[r][n-1]+1,t[r-1][n-1]+s),r>1&&n>1&&i[r-1]===e[n-2]&&i[r-2]===e[n-1]&&(t[r][n]=Math.min(t[r][n],t[r-2][n-2]+1))}return t[i.length][e.length]}l(Me,"editDistance");function We(i,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));const t=i.startsWith("--");t&&(i=i.slice(2),e=e.map(a=>a.slice(2)));let n=[],r=re;const s=.4;return e.forEach(a=>{if(a.length<=1)return;const u=Me(i,a),c=Math.max(i.length,a.length);(c-u)/c>s&&(u<r?(r=u,n=[a]):u===r&&n.push(a))}),n.sort((a,u)=>a.localeCompare(u)),t&&(n=n.map(a=>`--${a}`)),n.length>1?`
10
10
  (Did you mean one of ${n.join(", ")}?)`:n.length===1?`
11
- (Did you mean ${n[0]}?)`:""}l(Me,"suggestSimilar$1"),ne.suggestSimilar=Me;const We=Ae.EventEmitter,q=Ee,C=g,U=y,_=Se,{Argument:Ge,humanReadableArgName:Je}=R,{CommanderError:M}=T,{Help:Be}=L,{Option:se,DualOptions:Ke}=I,{suggestSimilar:ie}=ne;let ze=(S=class extends We{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:l(t=>_.stdout.write(t),"writeOut"),writeErr:l(t=>_.stderr.write(t),"writeErr"),getOutHelpWidth:l(()=>_.stdout.isTTY?_.stdout.columns:void 0,"getOutHelpWidth"),getErrHelpWidth:l(()=>_.stderr.isTTY?_.stderr.columns:void 0,"getErrHelpWidth"),outputError:l((t,n)=>n(t),"outputError")},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){const e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let r=t,i=n;typeof r=="object"&&r!==null&&(i=r,r=null),i=i||{};const[,a,u]=e.match(/([^ ]+) *(.*)/),c=this.createCommand(a);return r&&(c.description(r),c._executableHandler=!0),i.isDefault&&(this._defaultCommandName=c._name),c._hidden=!!(i.noHelp||i.hidden),c._executableFile=i.executableFile||null,u&&c.arguments(u),this._registerCommand(c),c.parent=this,c.copyInheritedSettings(this),r?this:c}createCommand(e){return new S(e)}createHelp(){return Object.assign(new Be,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
12
- - specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new Ge(e,t)}argument(e,t,n,r){const i=this.createArgument(e,t);return typeof n=="function"?i.default(r).argParser(n):i.default(n),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){const t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw new Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";const[,n,r]=e.match(/([^ ]+) *(.*)/),i=t??"display help for command",a=this.createCommand(n);return a.helpOption(!1),r&&a.arguments(r),i&&a.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=a,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){const n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
13
- Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new M(e,t,n)),_.exit(e)}action(e){const t=l(n=>{const r=this.registeredArguments.length,i=n.slice(0,r);return this._storeOptionsAsProperties?i[r]=this:i[r]=this.opts(),i.push(this),e.apply(this,i)},"listener");return this._actionHandler=t,this}createOption(e,t){return new se(e,t)}_callParseArg(e,t,n,r){try{return e.parseArg(t,n)}catch(i){if(i.code==="commander.invalidArgument"){const a=`${r} ${i.message}`;this.error(a,{exitCode:i.exitCode,code:i.code})}throw i}}_registerOption(e){const t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){const n=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
14
- - already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){const t=l(r=>[r.name()].concat(r.aliases()),"knownBy"),n=t(e).find(r=>this._findCommand(r));if(n){const r=t(this._findCommand(n)).join("|"),i=t(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${r}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);const t=e.name(),n=e.attributeName();if(e.negate){const i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");const r=l((i,a,u)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);const c=this.getOptionValue(n);i!==null&&e.parseArg?i=this._callParseArg(e,i,c,a):i!==null&&e.variadic&&(i=e._concatValue(i,c)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(n,i,u)},"handleOptionValue");return this.on("option:"+t,i=>{const a=`error: option '${e.flags}' argument '${i}' is invalid.`;r(i,a,"cli")}),e.envVar&&this.on("optionEnv:"+t,i=>{const a=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;r(i,a,"env")}),this}_optionEx(e,t,n,r,i){if(typeof t=="object"&&t instanceof se)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");const a=this.createOption(t,n);if(a.makeOptionMandatory(!!e.mandatory),typeof r=="function")a.default(i).argParser(r);else if(r instanceof RegExp){const u=r;r=l((c,p)=>{const o=u.exec(c);return o?o[0]:p},"fn"),a.default(i).argParser(r)}else a.default(r);return this.addOption(a)}option(e,t,n,r){return this._optionEx({},e,t,n,r)}requiredOption(e,t,n,r){return this._optionEx({mandatory:!0},e,t,n,r)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(t=n.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");t=t||{},e===void 0&&(e=_.argv,_.versions&&_.versions.electron&&(t.from="electron")),this.rawArgs=e.slice();let n;switch(t.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":_.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,t){const n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){const n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_executeSubCommand(e,t){t=t.slice();let n=!1;const r=[".js",".ts",".tsx",".mjs",".cjs"];function i(o,h){const d=C.resolve(o,h);if(U.existsSync(d))return d;if(r.includes(C.extname(h)))return;const O=r.find(f=>U.existsSync(`${d}${f}`));if(O)return`${d}${O}`}l(i,"findFile"),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let a=e._executableFile||`${this._name}-${e._name}`,u=this._executableDir||"";if(this._scriptPath){let o;try{o=U.realpathSync(this._scriptPath)}catch{o=this._scriptPath}u=C.resolve(C.dirname(o),u)}if(u){let o=i(u,a);if(!o&&!e._executableFile&&this._scriptPath){const h=C.basename(this._scriptPath,C.extname(this._scriptPath));h!==this._name&&(o=i(u,`${h}-${e._name}`))}a=o||a}n=r.includes(C.extname(a));let c;_.platform!=="win32"?n?(t.unshift(a),t=oe(_.execArgv).concat(t),c=q.spawn(_.argv[0],t,{stdio:"inherit"})):c=q.spawn(a,t,{stdio:"inherit"}):(t.unshift(a),t=oe(_.execArgv).concat(t),c=q.spawn(_.execPath,t,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(h=>{_.on(h,()=>{c.killed===!1&&c.exitCode===null&&c.kill(h)})});const p=this._exitCallback;c.on("close",(o,h)=>{o=o??1,p?p(new M(o,"commander.executeSubCommandAsync","(close)")):_.exit(o)}),c.on("error",o=>{if(o.code==="ENOENT"){const h=u?`searched for local subcommand relative to directory '${u}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",d=`'${a}' does not exist
11
+ (Did you mean ${n[0]}?)`:""}l(We,"suggestSimilar$1"),ne.suggestSimilar=We;const Ge=Ae.EventEmitter,q=Ee,w=g,U=y,_=Se,{Argument:Je,humanReadableArgName:Be}=R,{CommanderError:M}=T,{Help:Ke}=L,{Option:ie,DualOptions:ze}=V,{suggestSimilar:se}=ne;let Qe=(S=class extends Ge{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:l(t=>_.stdout.write(t),"writeOut"),writeErr:l(t=>_.stderr.write(t),"writeErr"),getOutHelpWidth:l(()=>_.stdout.isTTY?_.stdout.columns:void 0,"getOutHelpWidth"),getErrHelpWidth:l(()=>_.stderr.isTTY?_.stderr.columns:void 0,"getErrHelpWidth"),outputError:l((t,n)=>n(t),"outputError")},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){const e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let r=t,s=n;typeof r=="object"&&r!==null&&(s=r,r=null),s=s||{};const[,a,u]=e.match(/([^ ]+) *(.*)/),c=this.createCommand(a);return r&&(c.description(r),c._executableHandler=!0),s.isDefault&&(this._defaultCommandName=c._name),c._hidden=!!(s.noHelp||s.hidden),c._executableFile=s.executableFile||null,u&&c.arguments(u),this._registerCommand(c),c.parent=this,c.copyInheritedSettings(this),r?this:c}createCommand(e){return new S(e)}createHelp(){return Object.assign(new Ke,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
12
+ - specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new Je(e,t)}argument(e,t,n,r){const s=this.createArgument(e,t);return typeof n=="function"?s.default(r).argParser(n):s.default(n),this.addArgument(s),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){const t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw new Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";const[,n,r]=e.match(/([^ ]+) *(.*)/),s=t??"display help for command",a=this.createCommand(n);return a.helpOption(!1),r&&a.arguments(r),s&&a.description(s),this._addImplicitHelpCommand=!0,this._helpCommand=a,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){const n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
13
+ Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new M(e,t,n)),_.exit(e)}action(e){const t=l(n=>{const r=this.registeredArguments.length,s=n.slice(0,r);return this._storeOptionsAsProperties?s[r]=this:s[r]=this.opts(),s.push(this),e.apply(this,s)},"listener");return this._actionHandler=t,this}createOption(e,t){return new ie(e,t)}_callParseArg(e,t,n,r){try{return e.parseArg(t,n)}catch(s){if(s.code==="commander.invalidArgument"){const a=`${r} ${s.message}`;this.error(a,{exitCode:s.exitCode,code:s.code})}throw s}}_registerOption(e){const t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){const n=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
14
+ - already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){const t=l(r=>[r.name()].concat(r.aliases()),"knownBy"),n=t(e).find(r=>this._findCommand(r));if(n){const r=t(this._findCommand(n)).join("|"),s=t(e).join("|");throw new Error(`cannot add command '${s}' as already have command '${r}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);const t=e.name(),n=e.attributeName();if(e.negate){const s=e.long.replace(/^--no-/,"--");this._findOption(s)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");const r=l((s,a,u)=>{s==null&&e.presetArg!==void 0&&(s=e.presetArg);const c=this.getOptionValue(n);s!==null&&e.parseArg?s=this._callParseArg(e,s,c,a):s!==null&&e.variadic&&(s=e._concatValue(s,c)),s==null&&(e.negate?s=!1:e.isBoolean()||e.optional?s=!0:s=""),this.setOptionValueWithSource(n,s,u)},"handleOptionValue");return this.on("option:"+t,s=>{const a=`error: option '${e.flags}' argument '${s}' is invalid.`;r(s,a,"cli")}),e.envVar&&this.on("optionEnv:"+t,s=>{const a=`error: option '${e.flags}' value '${s}' from env '${e.envVar}' is invalid.`;r(s,a,"env")}),this}_optionEx(e,t,n,r,s){if(typeof t=="object"&&t instanceof ie)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");const a=this.createOption(t,n);if(a.makeOptionMandatory(!!e.mandatory),typeof r=="function")a.default(s).argParser(r);else if(r instanceof RegExp){const u=r;r=l((c,p)=>{const o=u.exec(c);return o?o[0]:p},"fn"),a.default(s).argParser(r)}else a.default(r);return this.addOption(a)}option(e,t,n,r){return this._optionEx({},e,t,n,r)}requiredOption(e,t,n,r){return this._optionEx({mandatory:!0},e,t,n,r)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(t=n.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");t=t||{},e===void 0&&(e=_.argv,_.versions&&_.versions.electron&&(t.from="electron")),this.rawArgs=e.slice();let n;switch(t.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":_.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,t){const n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){const n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_executeSubCommand(e,t){t=t.slice();let n=!1;const r=[".js",".ts",".tsx",".mjs",".cjs"];function s(o,h){const d=w.resolve(o,h);if(U.existsSync(d))return d;if(r.includes(w.extname(h)))return;const O=r.find(f=>U.existsSync(`${d}${f}`));if(O)return`${d}${O}`}l(s,"findFile"),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let a=e._executableFile||`${this._name}-${e._name}`,u=this._executableDir||"";if(this._scriptPath){let o;try{o=U.realpathSync(this._scriptPath)}catch{o=this._scriptPath}u=w.resolve(w.dirname(o),u)}if(u){let o=s(u,a);if(!o&&!e._executableFile&&this._scriptPath){const h=w.basename(this._scriptPath,w.extname(this._scriptPath));h!==this._name&&(o=s(u,`${h}-${e._name}`))}a=o||a}n=r.includes(w.extname(a));let c;_.platform!=="win32"?n?(t.unshift(a),t=oe(_.execArgv).concat(t),c=q.spawn(_.argv[0],t,{stdio:"inherit"})):c=q.spawn(a,t,{stdio:"inherit"}):(t.unshift(a),t=oe(_.execArgv).concat(t),c=q.spawn(_.execPath,t,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(h=>{_.on(h,()=>{c.killed===!1&&c.exitCode===null&&c.kill(h)})});const p=this._exitCallback;c.on("close",(o,h)=>{o=o??1,p?p(new M(o,"commander.executeSubCommandAsync","(close)")):_.exit(o)}),c.on("error",o=>{if(o.code==="ENOENT"){const h=u?`searched for local subcommand relative to directory '${u}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",d=`'${a}' does not exist
15
15
  - if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
16
16
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
17
- - ${h}`;throw new Error(d)}else if(o.code==="EACCES")throw new Error(`'${a}' not executable`);if(!p)_.exit(1);else{const h=new M(1,"commander.executeSubCommandAsync","(error)");h.nestedError=o,p(h)}}),this.runningCommand=c}_dispatchSubcommand(e,t,n){const r=this._findCommand(e);r||this.help({error:!0});let i;return i=this._chainOrCallSubCommandHook(i,r,"preSubcommand"),i=this._chainOrCall(i,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(n));else return r._parseCommand(t,n)}),i}_dispatchHelpCommand(e){e||this.help();const t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){const e=l((n,r,i)=>{let a=r;if(r!==null&&n.parseArg){const u=`error: command-argument value '${r}' is invalid for argument '${n.name()}'.`;a=this._callParseArg(n,r,i,u)}return a},"myParseArg");this._checkNumberOfArguments();const t=[];this.registeredArguments.forEach((n,r)=>{let i=n.defaultValue;n.variadic?r<this.args.length?(i=this.args.slice(r),n.parseArg&&(i=i.reduce((a,u)=>e(n,u,a),n.defaultValue))):i===void 0&&(i=[]):r<this.args.length&&(i=this.args[r],n.parseArg&&(i=e(n,i,n.defaultValue))),t[r]=i}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e;const r=[];return this._getCommandAndAncestors().reverse().filter(i=>i._lifeCycleHooks[t]!==void 0).forEach(i=>{i._lifeCycleHooks[t].forEach(a=>{r.push({hookedCommand:i,callback:a})})}),t==="postAction"&&r.reverse(),r.forEach(i=>{n=this._chainOrCall(n,()=>i.callback(i.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let r=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(i=>{r=this._chainOrCall(r,()=>i(this,t))}),r}_parseCommand(e,t){const n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();const r=l(()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},"checkForUnknownOptions"),i=`command:${this.name()}`;if(this._actionHandler){r(),this._processArguments();let a;return a=this._chainOrCallHooks(a,"preAction"),a=this._chainOrCall(a,()=>this._actionHandler(this.processedArgs)),this.parent&&(a=this._chainOrCall(a,()=>{this.parent.emit(i,e,t)})),a=this._chainOrCallHooks(a,"postAction"),a}if(this.parent&&this.parent.listenerCount(i))r(),this._processArguments(),this.parent.emit(i,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(r(),this._processArguments())}else this.commands.length?(r(),this.help({error:!0})):(r(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){const e=this.options.filter(n=>{const r=n.attributeName();return this.getOptionValue(r)===void 0?!1:this.getOptionValueSource(r)!=="default"});e.filter(n=>n.conflictsWith.length>0).forEach(n=>{const r=e.find(i=>n.conflictsWith.includes(i.attributeName()));r&&this._conflictingOption(n,r)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){const t=[],n=[];let r=t;const i=e.slice();function a(c){return c.length>1&&c[0]==="-"}l(a,"maybeOption");let u=null;for(;i.length;){const c=i.shift();if(c==="--"){r===n&&r.push(c),r.push(...i);break}if(u&&!a(c)){this.emit(`option:${u.name()}`,c);continue}if(u=null,a(c)){const p=this._findOption(c);if(p){if(p.required){const o=i.shift();o===void 0&&this.optionMissingArgument(p),this.emit(`option:${p.name()}`,o)}else if(p.optional){let o=null;i.length>0&&!a(i[0])&&(o=i.shift()),this.emit(`option:${p.name()}`,o)}else this.emit(`option:${p.name()}`);u=p.variadic?p:null;continue}}if(c.length>2&&c[0]==="-"&&c[1]!=="-"){const p=this._findOption(`-${c[1]}`);if(p){p.required||p.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${p.name()}`,c.slice(2)):(this.emit(`option:${p.name()}`),i.unshift(`-${c.slice(2)}`));continue}}if(/^--[^=]+=/.test(c)){const p=c.indexOf("="),o=this._findOption(c.slice(0,p));if(o&&(o.required||o.optional)){this.emit(`option:${o.name()}`,c.slice(p+1));continue}}if(a(c)&&(r=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(c)){t.push(c),i.length>0&&n.push(...i);break}else if(this._getHelpCommand()&&c===this._getHelpCommand().name()){t.push(c),i.length>0&&t.push(...i);break}else if(this._defaultCommandName){n.push(c),i.length>0&&n.push(...i);break}}if(this._passThroughOptions){r.push(c),i.length>0&&r.push(...i);break}r.push(c)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){const e={},t=this.options.length;for(let n=0;n<t;n++){const r=this.options[n].attributeName();e[r]=r===this._versionOptionName?this._version:this[r]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
17
+ - ${h}`;throw new Error(d)}else if(o.code==="EACCES")throw new Error(`'${a}' not executable`);if(!p)_.exit(1);else{const h=new M(1,"commander.executeSubCommandAsync","(error)");h.nestedError=o,p(h)}}),this.runningCommand=c}_dispatchSubcommand(e,t,n){const r=this._findCommand(e);r||this.help({error:!0});let s;return s=this._chainOrCallSubCommandHook(s,r,"preSubcommand"),s=this._chainOrCall(s,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(n));else return r._parseCommand(t,n)}),s}_dispatchHelpCommand(e){e||this.help();const t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){const e=l((n,r,s)=>{let a=r;if(r!==null&&n.parseArg){const u=`error: command-argument value '${r}' is invalid for argument '${n.name()}'.`;a=this._callParseArg(n,r,s,u)}return a},"myParseArg");this._checkNumberOfArguments();const t=[];this.registeredArguments.forEach((n,r)=>{let s=n.defaultValue;n.variadic?r<this.args.length?(s=this.args.slice(r),n.parseArg&&(s=s.reduce((a,u)=>e(n,u,a),n.defaultValue))):s===void 0&&(s=[]):r<this.args.length&&(s=this.args[r],n.parseArg&&(s=e(n,s,n.defaultValue))),t[r]=s}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e;const r=[];return this._getCommandAndAncestors().reverse().filter(s=>s._lifeCycleHooks[t]!==void 0).forEach(s=>{s._lifeCycleHooks[t].forEach(a=>{r.push({hookedCommand:s,callback:a})})}),t==="postAction"&&r.reverse(),r.forEach(s=>{n=this._chainOrCall(n,()=>s.callback(s.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let r=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(s=>{r=this._chainOrCall(r,()=>s(this,t))}),r}_parseCommand(e,t){const n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();const r=l(()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},"checkForUnknownOptions"),s=`command:${this.name()}`;if(this._actionHandler){r(),this._processArguments();let a;return a=this._chainOrCallHooks(a,"preAction"),a=this._chainOrCall(a,()=>this._actionHandler(this.processedArgs)),this.parent&&(a=this._chainOrCall(a,()=>{this.parent.emit(s,e,t)})),a=this._chainOrCallHooks(a,"postAction"),a}if(this.parent&&this.parent.listenerCount(s))r(),this._processArguments(),this.parent.emit(s,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(r(),this._processArguments())}else this.commands.length?(r(),this.help({error:!0})):(r(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){const e=this.options.filter(n=>{const r=n.attributeName();return this.getOptionValue(r)===void 0?!1:this.getOptionValueSource(r)!=="default"});e.filter(n=>n.conflictsWith.length>0).forEach(n=>{const r=e.find(s=>n.conflictsWith.includes(s.attributeName()));r&&this._conflictingOption(n,r)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){const t=[],n=[];let r=t;const s=e.slice();function a(c){return c.length>1&&c[0]==="-"}l(a,"maybeOption");let u=null;for(;s.length;){const c=s.shift();if(c==="--"){r===n&&r.push(c),r.push(...s);break}if(u&&!a(c)){this.emit(`option:${u.name()}`,c);continue}if(u=null,a(c)){const p=this._findOption(c);if(p){if(p.required){const o=s.shift();o===void 0&&this.optionMissingArgument(p),this.emit(`option:${p.name()}`,o)}else if(p.optional){let o=null;s.length>0&&!a(s[0])&&(o=s.shift()),this.emit(`option:${p.name()}`,o)}else this.emit(`option:${p.name()}`);u=p.variadic?p:null;continue}}if(c.length>2&&c[0]==="-"&&c[1]!=="-"){const p=this._findOption(`-${c[1]}`);if(p){p.required||p.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${p.name()}`,c.slice(2)):(this.emit(`option:${p.name()}`),s.unshift(`-${c.slice(2)}`));continue}}if(/^--[^=]+=/.test(c)){const p=c.indexOf("="),o=this._findOption(c.slice(0,p));if(o&&(o.required||o.optional)){this.emit(`option:${o.name()}`,c.slice(p+1));continue}}if(a(c)&&(r=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(c)){t.push(c),s.length>0&&n.push(...s);break}else if(this._getHelpCommand()&&c===this._getHelpCommand().name()){t.push(c),s.length>0&&t.push(...s);break}else if(this._defaultCommandName){n.push(c),s.length>0&&n.push(...s);break}}if(this._passThroughOptions){r.push(c),s.length>0&&r.push(...s);break}r.push(c)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){const e={},t=this.options.length;for(let n=0;n<t;n++){const r=this.options[n].attributeName();e[r]=r===this._versionOptionName?this._version:this[r]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
18
18
  `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
19
19
  `):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
20
- `),this.outputHelp({error:!0}));const n=t||{},r=n.exitCode||1,i=n.code||"commander.error";this._exit(r,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in _.env){const t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,_.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){const e=new Ke(this.options),t=l(n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n)),"hasCustomOptionValue");this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(r=>!t(r)).forEach(r=>{this.setOptionValueWithSource(r,n.implied[r],"implied")})})}missingArgument(e){const t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){const t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){const t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){const n=l(a=>{const u=a.attributeName(),c=this.getOptionValue(u),p=this.options.find(h=>h.negate&&u===h.attributeName()),o=this.options.find(h=>!h.negate&&u===h.attributeName());return p&&(p.presetArg===void 0&&c===!1||p.presetArg!==void 0&&c===p.presetArg)?p:o||a},"findBestOptionFromValue"),r=l(a=>{const u=n(a),c=u.attributeName();return this.getOptionValueSource(c)==="env"?`environment variable '${u.envVar}'`:`option '${u.flags}'`},"getErrorMessage"),i=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let r=[],i=this;do{const a=i.createHelp().visibleOptions(i).filter(u=>u.long).map(u=>u.long);r=r.concat(a),i=i.parent}while(i&&!i._enablePositionalOptions);t=ie(e,r)}const n=`error: unknown option '${e}'${t}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;const t=this.registeredArguments.length,n=t===1?"":"s",i=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${n} but got ${e.length}.`;this.error(i,{code:"commander.excessArguments"})}unknownCommand(){const e=this.args[0];let t="";if(this._showSuggestionAfterError){const r=[];this.createHelp().visibleCommands(this).forEach(i=>{r.push(i.name()),i.alias()&&r.push(i.alias())}),t=ie(e,r)}const n=`error: unknown command '${e}'${t}`;this.error(n,{code:"commander.unknownCommand"})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",n=n||"output the version number";const r=this.createOption(t,n);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on("option:"+r.name(),()=>{this._outputConfiguration.writeOut(`${e}
21
- `),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");const n=this.parent?._findCommand(e);if(n){const r=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${r}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;const t=this.registeredArguments.map(n=>Je(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=C.basename(e,C.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){const t=this.createHelp();return t.helpWidth===void 0&&(t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),t.formatHelp(this,t)}_getHelpContext(e){e=e||{};const t={error:!!e.error};let n;return t.error?n=l(r=>this._outputConfiguration.writeErr(r),"write"):n=l(r=>this._outputConfiguration.writeOut(r),"write"),t.write=e.write||n,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);const n=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(i=>i.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let r=this.helpInformation(n);if(t&&(r=t(r),typeof r!="string"&&!Buffer.isBuffer(r)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(r),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(i=>i.emit("afterAllHelp",n))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=_.exitCode||0;t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){const n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
22
- Expecting one of '${n.join("', '")}'`);const r=`${e}Help`;return this.on(r,i=>{let a;typeof t=="function"?a=t({error:i.error,command:i.command}):a=t,a&&i.write(`${a}
23
- `)}),this}_outputHelpIfRequested(e){const t=this._getHelpOption();t&&e.find(r=>t.is(r))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}},l(S,"Command"),S);function oe(s){return s.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n="127.0.0.1",r="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?t=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=i[1],/^\d+$/.test(i[3])?r=i[3]:n=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],r=i[4]),t&&r!=="0"?`${t}=${n}:${parseInt(r)+1}`:e})}l(oe,"incrementNodeInspectorPort"),te.Command=ze;const{Argument:ae}=R,{Command:W}=te,{CommanderError:Qe,InvalidArgumentError:ce}=T,{Help:Ye}=L,{Option:le}=I;b.program=new W,b.createCommand=s=>new W(s),b.createOption=(s,e)=>new le(s,e),b.createArgument=(s,e)=>new ae(s,e),b.Command=W,b.Option=le,b.Argument=ae,b.Help=Ye,b.CommanderError=Qe,b.InvalidArgumentError=ce,b.InvalidOptionArgumentError=ce;const{program:En,createCommand:$n,createArgument:Sn,createOption:Tn,CommanderError:vn,InvalidArgumentError:jn,InvalidOptionArgumentError:kn,Command:Ze,Argument:xn,Option:Pn,Help:Hn}=b,Xe=/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,et=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,tt=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function nt(s,e){if(s==="__proto__"||s==="constructor"&&e&&typeof e=="object"&&"prototype"in e){rt(s);return}return e}l(nt,"jsonParseTransform");function rt(s){console.warn(`[destr] Dropping "${s}" key to prevent prototype pollution.`)}l(rt,"warnKeyDropped");function st(s,e={}){if(typeof s!="string")return s;const t=s.trim();if(s[0]==='"'&&s.endsWith('"')&&!s.includes("\\"))return t.slice(1,-1);if(t.length<=9){const n=t.toLowerCase();if(n==="true")return!0;if(n==="false")return!1;if(n==="undefined")return;if(n==="null")return null;if(n==="nan")return Number.NaN;if(n==="infinity")return Number.POSITIVE_INFINITY;if(n==="-infinity")return Number.NEGATIVE_INFINITY}if(!tt.test(s)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return s}try{if(Xe.test(s)||et.test(s)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(s,nt)}return JSON.parse(s)}catch(n){if(e.strict)throw n;return s}}l(st,"destr");const it=/#/g,ot=/&/g,at=/\//g,ct=/=/g,G=/\+/g,lt=/%5e/gi,ut=/%60/gi,ht=/%7c/gi,pt=/%20/gi;function dt(s){return encodeURI(""+s).replace(ht,"|")}l(dt,"encode");function J(s){return dt(typeof s=="string"?s:JSON.stringify(s)).replace(G,"%2B").replace(pt,"+").replace(it,"%23").replace(ot,"%26").replace(ut,"`").replace(lt,"^").replace(at,"%2F")}l(J,"encodeQueryValue");function B(s){return J(s).replace(ct,"%3D")}l(B,"encodeQueryKey");function ue(s=""){try{return decodeURIComponent(""+s)}catch{return""+s}}l(ue,"decode");function ft(s){return ue(s.replace(G," "))}l(ft,"decodeQueryKey");function mt(s){return ue(s.replace(G," "))}l(mt,"decodeQueryValue");function gt(s=""){const e={};s[0]==="?"&&(s=s.slice(1));for(const t of s.split("&")){const n=t.match(/([^=]+)=?(.*)/)||[];if(n.length<2)continue;const r=ft(n[1]);if(r==="__proto__"||r==="constructor")continue;const i=mt(n[2]||"");e[r]===void 0?e[r]=i:Array.isArray(e[r])?e[r].push(i):e[r]=[e[r],i]}return e}l(gt,"parseQuery");function _t(s,e){return(typeof e=="number"||typeof e=="boolean")&&(e=String(e)),e?Array.isArray(e)?e.map(t=>`${B(s)}=${J(t)}`).join("&"):`${B(s)}=${J(e)}`:B(s)}l(_t,"encodeQueryItem");function yt(s){return Object.keys(s).filter(e=>s[e]!==void 0).map(e=>_t(e,s[e])).filter(Boolean).join("&")}l(yt,"stringifyQuery");const Ot=/^[\s\w\0+.-]{2,}:([/\\]{1,2})/,bt=/^[\s\w\0+.-]{2,}:([/\\]{2})?/,wt=/^([/\\]\s*){2,}[^/\\]/,Ct=/^\.?\//;function he(s,e={}){return typeof e=="boolean"&&(e={acceptRelative:e}),e.strict?Ot.test(s):bt.test(s)||(e.acceptRelative?wt.test(s):!1)}l(he,"hasProtocol");function At(s="",e){return s.endsWith("/")}l(At,"hasTrailingSlash");function Et(s="",e){return(At(s)?s.slice(0,-1):s)||"/"}l(Et,"withoutTrailingSlash");function $t(s="",e){return s.endsWith("/")?s:s+"/"}l($t,"withTrailingSlash");function St(s,e){if(vt(e)||he(s))return s;const t=Et(e);return s.startsWith(t)?s:kt(t,s)}l(St,"withBase");function Tt(s,e){const t=xt(s),n={...gt(t.search),...e};return t.search=yt(n),Pt(t)}l(Tt,"withQuery");function vt(s){return!s||s==="/"}l(vt,"isEmptyURL");function jt(s){return s&&s!=="/"}l(jt,"isNonEmptyURL");function kt(s,...e){let t=s||"";for(const n of e.filter(r=>jt(r)))if(t){const r=n.replace(Ct,"");t=$t(t)+r}else t=n;return t}l(kt,"joinURL");const pe=Symbol.for("ufo:protocolRelative");function xt(s="",e){const t=s.match(/^[\s\0]*(blob:|data:|javascript:|vbscript:)(.*)/i);if(t){const[,h,d=""]=t;return{protocol:h.toLowerCase(),pathname:d,href:h+d,auth:"",host:"",search:"",hash:""}}if(!he(s,{acceptRelative:!0}))return de(s);const[,n="",r,i=""]=s.replace(/\\/g,"/").match(/^[\s\0]*([\w+.-]{2,}:)?\/\/([^/@]+@)?(.*)/)||[],[,a="",u=""]=i.match(/([^#/?]*)(.*)?/)||[],{pathname:c,search:p,hash:o}=de(u.replace(/\/(?=[A-Za-z]:)/,""));return{protocol:n.toLowerCase(),auth:r?r.slice(0,Math.max(0,r.length-1)):"",host:a,pathname:c,search:p,hash:o,[pe]:!n}}l(xt,"parseURL");function de(s=""){const[e="",t="",n=""]=(s.match(/([^#?]*)(\?[^#]*)?(#.*)?/)||[]).splice(1);return{pathname:e,search:t,hash:n}}l(de,"parsePath");function Pt(s){const e=s.pathname||"",t=s.search?(s.search.startsWith("?")?"":"?")+s.search:"",n=s.hash||"",r=s.auth?s.auth+"@":"",i=s.host||"";return(s.protocol||s[pe]?(s.protocol||"")+"//":"")+r+i+e+t+n}l(Pt,"stringifyParsedURL");const X=class X extends Error{constructor(e,t){super(e,t),this.name="FetchError",t?.cause&&!this.cause&&(this.cause=t.cause)}};l(X,"FetchError");let K=X;function Ht(s){const e=s.error?.message||s.error?.toString()||"",t=s.request?.method||s.options?.method||"GET",n=s.request?.url||String(s.request)||"/",r=`[${t}] ${JSON.stringify(n)}`,i=s.response?`${s.response.status} ${s.response.statusText}`:"<no response>",a=`${r}: ${i}${e?` ${e}`:""}`,u=new K(a,s.error?{cause:s.error}:void 0);for(const c of["request","options","response"])Object.defineProperty(u,c,{get(){return s[c]}});for(const[c,p]of[["data","_data"],["status","status"],["statusCode","status"],["statusText","statusText"],["statusMessage","statusText"]])Object.defineProperty(u,c,{get(){return s.response&&s.response[p]}});return u}l(Ht,"createFetchError");const Rt=new Set(Object.freeze(["PATCH","POST","PUT","DELETE"]));function fe(s="GET"){return Rt.has(s.toUpperCase())}l(fe,"isPayloadMethod");function Nt(s){if(s===void 0)return!1;const e=typeof s;return e==="string"||e==="number"||e==="boolean"||e===null?!0:e!=="object"?!1:Array.isArray(s)?!0:s.buffer?!1:s.constructor&&s.constructor.name==="Object"||typeof s.toJSON=="function"}l(Nt,"isJSONSerializable");const Vt=new Set(["image/svg","application/xml","application/xhtml","application/html"]),It=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function Ft(s=""){if(!s)return"json";const e=s.split(";").shift()||"";return It.test(e)?"json":Vt.has(e)||e.startsWith("text/")?"text":"blob"}l(Ft,"detectResponseType");function Dt(s,e,t=globalThis.Headers){const n={...e,...s};if(e?.params&&s?.params&&(n.params={...e?.params,...s?.params}),e?.query&&s?.query&&(n.query={...e?.query,...s?.query}),e?.headers&&s?.headers){n.headers=new t(e?.headers||{});for(const[r,i]of new t(s?.headers||{}))n.headers.set(r,i)}return n}l(Dt,"mergeFetchOptions");const Lt=new Set([408,409,425,429,500,502,503,504]),qt=new Set([101,204,205,304]);function me(s={}){const{fetch:e=globalThis.fetch,Headers:t=globalThis.Headers,AbortController:n=globalThis.AbortController}=s;async function r(u){const c=u.error&&u.error.name==="AbortError"&&!u.options.timeout||!1;if(u.options.retry!==!1&&!c){let o;typeof u.options.retry=="number"?o=u.options.retry:o=fe(u.options.method)?0:1;const h=u.response&&u.response.status||500;if(o>0&&(Array.isArray(u.options.retryStatusCodes)?u.options.retryStatusCodes.includes(h):Lt.has(h))){const d=u.options.retryDelay||0;return d>0&&await new Promise(O=>setTimeout(O,d)),i(u.request,{...u.options,retry:o-1})}}const p=Ht(u);throw Error.captureStackTrace&&Error.captureStackTrace(p,i),p}l(r,"onError");const i=l(async function(c,p={}){const o={request:c,options:Dt(p,s.defaults,t),response:void 0,error:void 0};o.options.method=o.options.method?.toUpperCase(),o.options.onRequest&&await o.options.onRequest(o),typeof o.request=="string"&&(o.options.baseURL&&(o.request=St(o.request,o.options.baseURL)),(o.options.query||o.options.params)&&(o.request=Tt(o.request,{...o.options.params,...o.options.query}))),o.options.body&&fe(o.options.method)&&(Nt(o.options.body)?(o.options.body=typeof o.options.body=="string"?o.options.body:JSON.stringify(o.options.body),o.options.headers=new t(o.options.headers||{}),o.options.headers.has("content-type")||o.options.headers.set("content-type","application/json"),o.options.headers.has("accept")||o.options.headers.set("accept","application/json")):("pipeTo"in o.options.body&&typeof o.options.body.pipeTo=="function"||typeof o.options.body.pipe=="function")&&("duplex"in o.options||(o.options.duplex="half")));let h;if(!o.options.signal&&o.options.timeout){const O=new n;h=setTimeout(()=>O.abort(),o.options.timeout),o.options.signal=O.signal}try{o.response=await e(o.request,o.options)}catch(O){return o.error=O,o.options.onRequestError&&await o.options.onRequestError(o),await r(o)}finally{h&&clearTimeout(h)}if(o.response.body&&!qt.has(o.response.status)&&o.options.method!=="HEAD"){const O=(o.options.parseResponse?"json":o.options.responseType)||Ft(o.response.headers.get("content-type")||"");switch(O){case"json":{const f=await o.response.text(),w=o.options.parseResponse||st;o.response._data=w(f);break}case"stream":{o.response._data=o.response.body;break}default:o.response._data=await o.response[O]()}}return o.options.onResponse&&await o.options.onResponse(o),!o.options.ignoreResponseError&&o.response.status>=400&&o.response.status<600?(o.options.onResponseError&&await o.options.onResponseError(o),await r(o)):o.response},"$fetchRaw2"),a=l(async function(c,p){return(await i(c,p))._data},"$fetch2");return a.raw=i,a.native=(...u)=>e(...u),a.create=(u={})=>me({...s,defaults:{...s.defaults,...u}}),a}l(me,"createFetch");const z=function(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("unable to locate global object")}(),Ut=z.fetch||(()=>Promise.reject(new Error("[ofetch] global.fetch is not supported!"))),Mt=z.Headers,Wt=z.AbortController,F=me({fetch:Ut,Headers:Mt,AbortController:Wt}),Gt={apiRoot:process.env.FRONTSTACK_CLI_API_ROOT||(process.env.FRONTSTACK_CLI_DEV_MODE=="1"?"https://backend.frontstack.dev/":"https://backend.frontlab.dev/")},N=Gt.apiRoot,Jt=`${N}login`,Bt=`${N}api/fetch-api/spec.yaml`,ge=3008,_e=`http://localhost:${ge}`,ye=`${Jt}?redirectUrl=${_e}/callback`,Kt=".frontstack-local/",A=g.join(process.cwd(),Kt),Q="api_session.jwt",Oe="project.json",V=l(()=>{const s=l(()=>{console.info("Not auth.login implemented yet")},"login"),e=l(async()=>{try{return a(),0}catch(h){console.log(h)}},"logout"),t=l(async(h=void 0)=>{try{return process.env.NODE_TLS_REJECT_UNAUTHORIZED=process.env.DEV?"0":"1",await F(`${N}profile`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${h||r()}`}})}catch(d){return console.log(d),1}},"getProfile"),n=l(async(h=void 0)=>{try{const d=c();if(d==null)throw new Error(`You have no project selected
24
- Run ${m.hex("#7c3bed")("frontstack project")} to select a Frontstack project`);return process.env.NODE_TLS_REJECT_UNAUTHORIZED=process.env.FRONTSTACK_CLI_DEV_MODE?"0":"1",await F(Bt,{method:"GET",headers:{"Content-Type":"application/yaml",Authorization:`Bearer ${h||r()}`,"FS-Project":d},parseResponse:l(f=>{try{return Te.load(f)}catch{throw new Error("Invalid API specification. The API specification must be a valid YAML file.")}},"parseResponse")})}catch(d){throw"data"in d&&"message"in d.data?new Error(`Server error: ${d.data.message}`):d}},"getFetchApiSpec"),r=l(()=>{const h=g.join(A,Q);return y.existsSync(h)?y.readFileSync(h,"utf8"):null},"getToken"),i=l(h=>(y.existsSync(A)||y.mkdirSync(A),y.writeFileSync(g.join(A,Q),h),0),"writeToken"),a=l(()=>{const h=g.join(A,Q);y.existsSync(h)&&y.unlinkSync(h)},"deleteToken"),u=l(async()=>(process.env.NODE_TLS_REJECT_UNAUTHORIZED=process.env.DEV?"0":"1",await F(`${N}api/project`,{method:"GET",headers:{"Content-Type":"application/yaml",Authorization:`Bearer ${r()}`},parseResponse:l(h=>JSON.parse(h),"parseResponse")})),"getProjects"),c=l(()=>{const h=g.join(A,Oe);if(!y.existsSync(h))return null;try{return JSON.parse(y.readFileSync(h,"utf8")).projectId}catch{console.error("[Error] Corrupt project file - please run 'frontstack project'")}},"getProjectId");return{login:s,logout:e,getProfile:t,getFetchApiSpec:n,getToken:r,writeToken:i,deleteToken:a,getProjects:u,getProject:l(async()=>{try{const h=c();return h===void 0?void 0:(process.env.NODE_TLS_REJECT_UNAUTHORIZED=process.env.DEV?"0":"1",await F(`${N}api/project/${h}`,{method:"GET",headers:{"Content-Type":"application/yaml",Authorization:`Bearer ${r()}`},parseResponse:l(d=>JSON.parse(d),"parseResponse")}))}catch(h){return{error:h.message}}},"getProject"),getProjectId:c,writeProject:l(h=>(y.existsSync(A)||y.mkdirSync(A),y.writeFileSync(g.join(A,Oe),JSON.stringify({projectId:h})),0),"writeProject")}},"auth"),{writeToken:zt}=V(),Qt=l(async(s,e)=>{const t=new Set,n=ve.createServer((r,i)=>{const a=_e;if(r.url===void 0)return;const c=new URL(r.url,a).searchParams.get("token");c&&(i.writeHead(200,{"Content-Type":"text/html"}),i.end('<html><head><script>// window.close()<\/script></head><body style="font-family: sans-serif;"><div style="height: 100%; width: 100%; display: flex; justify-content: center; align-items: center;"><div style="text-align: center"><h1 style="color: #7c3bed;">Login Successful</h1><p>You can <a href="#" onClick="window.close()">close</a> this browser window and return to the terminal.<p style="font-size: .8rem; color: #666; text-align: left; margin-top: 20px;">&copy; 2024 frontstack</p></div></div></html>'),i.on("finish",async()=>{for(const o of t)o.destroy();zt(c)!==0&&(console.error("Login failed."),n.close(),process.exit(1)),console.log(`${m.hex("#008000")("[SUCCESS]")} Login successful`),n.close(),process.exit(0)}))}).listen(s,()=>{console.log(`Please continue login in your browser at ${m.hex("#7c3bed")(e)}`)});n.on("connection",r=>{t.add(r),r.on("close",()=>t.delete(r))}),setTimeout(()=>{n.close()},6e4)},"login$1"),Yt=l(async s=>{await je(ye),await Qt(ge,ye)},"login"),Zt=V(),Xt=l(async s=>{await Zt.logout()!==0&&(console.error("Logout failed."),process.exit(1)),console.log("Logout successful."),process.exit(0)},"logout"),{getFetchApiSpec:en}=V();E.registerHelper("eq",function(s,e,t){return s===e}),E.registerHelper("uc",function(s){return s.toUpperCase()}),E.registerHelper("contains",function(s,e,t){return s===void 0?!1:s.includes(e)}),E.registerHelper("endsWith",function(s,e,t){return s===void 0?!1:s.endsWith(e)}),E.registerHelper("blockNameFromOperationId",function(s){return s.replace("get","").replace("Block","")});const Y=l((s,e=!1)=>s.$ref?`components['schemas']['${s.$ref.split("/").pop()}']`:s.type==="array"?`Array<${Y(s.items,!0)}>`:s.type==="object"?`{ ${Object.keys(s.properties).map(n=>`${n}: ${Y(s.properties[n])}`).join("; ")} }`:s.type,"getSchemaType");E.registerHelper("getSchemaType",s=>Y(s));var tn=l(async()=>{const s=g.dirname(new URL(import.meta.url).pathname),e=g.join(s,"src/commands/generate/templates"),t=g.join(e,"types.js.hbs"),n=y.readFileSync(t,"utf8"),r=E.compile(n),i=g.join(e,"client.js.hbs"),a=y.readFileSync(i,"utf8"),u=E.compile(a),c=g.join(e,"query.js.hbs"),p=y.readFileSync(c,"utf8");let o;if(o=await en(),o.error)throw new Error(`Issue fetching API specification. Check more information below.
25
- `+o.error);let h="";try{h=await ke(o)}catch(f){throw new Error(`Invalid API Specification: ${f.message}`)}const d=r({paths:o.paths,components:o.components}),O=u({paths:o.paths,servers:o.servers});return{_schemaTypes:h,_types:d,_client:O,_query:p}},"generate");const nn=l(async s=>{const e=s.verbose||!1;let t,n,r,i;try{e&&console.log("Generating Javascript client"),{_schemaTypes:t,_types:n,_client:r,_query:i}=await tn()}catch(h){console.error(`${m.hex("#b90404")("[ERROR]")} frontstack generate`),console.error(`${m.hex("#b90404")("[ERROR]")} Failed to generate Javascript client`),e?console.error(`${m.hex("#b90404")("[ERROR]")} ${h.message}`):(console.error("Are you..."),console.error(` * logged in using the ${m.hex("#7c3bed")("frontstack login")} command?`),console.error(" * connected to the internet?"),console.error(`Alternatively, run ${m.hex("#7c3bed")("frontstack generate -v")} for additional output.`));return}let a=s.output||".frontstack";process.stdout.write("Generating Javascript client"),a.startsWith("/")||(a=g.join(process.cwd(),a)),a.endsWith("/")||(a+="/");const u=g.join(a,"fetch-api.d.ts"),c=g.join(a,"generated-types.d.ts"),p=g.join(a,"generated-client.ts"),o=g.join(a,"query-types.ts");e&&(console.log(`
26
- Schema types path: ${m.dim(u)}`),console.log(`Types path: ${m.dim(c)}`),console.log(`Client path: ${m.dim(p)}`),console.log(`Target directory: ${m.dim(a)}`)),y.mkdirSync(a,{recursive:!0}),y.writeFileSync(g.join(u),t),y.writeFileSync(g.join(c),n),y.writeFileSync(g.join(p),r),y.writeFileSync(g.join(o),i),e?console.log(`Javascript client generated
20
+ `),this.outputHelp({error:!0}));const n=t||{},r=n.exitCode||1,s=n.code||"commander.error";this._exit(r,s,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in _.env){const t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,_.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){const e=new ze(this.options),t=l(n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n)),"hasCustomOptionValue");this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(r=>!t(r)).forEach(r=>{this.setOptionValueWithSource(r,n.implied[r],"implied")})})}missingArgument(e){const t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){const t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){const t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){const n=l(a=>{const u=a.attributeName(),c=this.getOptionValue(u),p=this.options.find(h=>h.negate&&u===h.attributeName()),o=this.options.find(h=>!h.negate&&u===h.attributeName());return p&&(p.presetArg===void 0&&c===!1||p.presetArg!==void 0&&c===p.presetArg)?p:o||a},"findBestOptionFromValue"),r=l(a=>{const u=n(a),c=u.attributeName();return this.getOptionValueSource(c)==="env"?`environment variable '${u.envVar}'`:`option '${u.flags}'`},"getErrorMessage"),s=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(s,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let r=[],s=this;do{const a=s.createHelp().visibleOptions(s).filter(u=>u.long).map(u=>u.long);r=r.concat(a),s=s.parent}while(s&&!s._enablePositionalOptions);t=se(e,r)}const n=`error: unknown option '${e}'${t}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;const t=this.registeredArguments.length,n=t===1?"":"s",s=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${n} but got ${e.length}.`;this.error(s,{code:"commander.excessArguments"})}unknownCommand(){const e=this.args[0];let t="";if(this._showSuggestionAfterError){const r=[];this.createHelp().visibleCommands(this).forEach(s=>{r.push(s.name()),s.alias()&&r.push(s.alias())}),t=se(e,r)}const n=`error: unknown command '${e}'${t}`;this.error(n,{code:"commander.unknownCommand"})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",n=n||"output the version number";const r=this.createOption(t,n);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on("option:"+r.name(),()=>{this._outputConfiguration.writeOut(`${e}
21
+ `),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");const n=this.parent?._findCommand(e);if(n){const r=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${r}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;const t=this.registeredArguments.map(n=>Be(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=w.basename(e,w.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){const t=this.createHelp();return t.helpWidth===void 0&&(t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),t.formatHelp(this,t)}_getHelpContext(e){e=e||{};const t={error:!!e.error};let n;return t.error?n=l(r=>this._outputConfiguration.writeErr(r),"write"):n=l(r=>this._outputConfiguration.writeOut(r),"write"),t.write=e.write||n,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);const n=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(s=>s.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let r=this.helpInformation(n);if(t&&(r=t(r),typeof r!="string"&&!Buffer.isBuffer(r)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(r),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(s=>s.emit("afterAllHelp",n))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=_.exitCode||0;t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){const n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
22
+ Expecting one of '${n.join("', '")}'`);const r=`${e}Help`;return this.on(r,s=>{let a;typeof t=="function"?a=t({error:s.error,command:s.command}):a=t,a&&s.write(`${a}
23
+ `)}),this}_outputHelpIfRequested(e){const t=this._getHelpOption();t&&e.find(r=>t.is(r))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}},l(S,"Command"),S);function oe(i){return i.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n="127.0.0.1",r="9229",s;return(s=e.match(/^(--inspect(-brk)?)$/))!==null?t=s[1]:(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=s[1],/^\d+$/.test(s[3])?r=s[3]:n=s[3]):(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=s[1],n=s[3],r=s[4]),t&&r!=="0"?`${t}=${n}:${parseInt(r)+1}`:e})}l(oe,"incrementNodeInspectorPort"),te.Command=Qe;const{Argument:ae}=R,{Command:W}=te,{CommanderError:Ye,InvalidArgumentError:ce}=T,{Help:Ze}=L,{Option:le}=V;b.program=new W,b.createCommand=i=>new W(i),b.createOption=(i,e)=>new le(i,e),b.createArgument=(i,e)=>new ae(i,e),b.Command=W,b.Option=le,b.Argument=ae,b.Help=Ze,b.CommanderError=Ye,b.InvalidArgumentError=ce,b.InvalidOptionArgumentError=ce;const{program:jn,createCommand:kn,createArgument:xn,createOption:Pn,CommanderError:Hn,InvalidArgumentError:Rn,InvalidOptionArgumentError:In,Command:Xe,Argument:Nn,Option:Vn,Help:Fn}=b,et=/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,tt=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,nt=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function rt(i,e){if(i==="__proto__"||i==="constructor"&&e&&typeof e=="object"&&"prototype"in e){it(i);return}return e}l(rt,"jsonParseTransform");function it(i){console.warn(`[destr] Dropping "${i}" key to prevent prototype pollution.`)}l(it,"warnKeyDropped");function st(i,e={}){if(typeof i!="string")return i;const t=i.trim();if(i[0]==='"'&&i.endsWith('"')&&!i.includes("\\"))return t.slice(1,-1);if(t.length<=9){const n=t.toLowerCase();if(n==="true")return!0;if(n==="false")return!1;if(n==="undefined")return;if(n==="null")return null;if(n==="nan")return Number.NaN;if(n==="infinity")return Number.POSITIVE_INFINITY;if(n==="-infinity")return Number.NEGATIVE_INFINITY}if(!nt.test(i)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return i}try{if(et.test(i)||tt.test(i)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(i,rt)}return JSON.parse(i)}catch(n){if(e.strict)throw n;return i}}l(st,"destr");const ot=/#/g,at=/&/g,ct=/\//g,lt=/=/g,G=/\+/g,ut=/%5e/gi,ht=/%60/gi,pt=/%7c/gi,dt=/%20/gi;function ft(i){return encodeURI(""+i).replace(pt,"|")}l(ft,"encode");function J(i){return ft(typeof i=="string"?i:JSON.stringify(i)).replace(G,"%2B").replace(dt,"+").replace(ot,"%23").replace(at,"%26").replace(ht,"`").replace(ut,"^").replace(ct,"%2F")}l(J,"encodeQueryValue");function B(i){return J(i).replace(lt,"%3D")}l(B,"encodeQueryKey");function ue(i=""){try{return decodeURIComponent(""+i)}catch{return""+i}}l(ue,"decode");function mt(i){return ue(i.replace(G," "))}l(mt,"decodeQueryKey");function gt(i){return ue(i.replace(G," "))}l(gt,"decodeQueryValue");function _t(i=""){const e={};i[0]==="?"&&(i=i.slice(1));for(const t of i.split("&")){const n=t.match(/([^=]+)=?(.*)/)||[];if(n.length<2)continue;const r=mt(n[1]);if(r==="__proto__"||r==="constructor")continue;const s=gt(n[2]||"");e[r]===void 0?e[r]=s:Array.isArray(e[r])?e[r].push(s):e[r]=[e[r],s]}return e}l(_t,"parseQuery");function yt(i,e){return(typeof e=="number"||typeof e=="boolean")&&(e=String(e)),e?Array.isArray(e)?e.map(t=>`${B(i)}=${J(t)}`).join("&"):`${B(i)}=${J(e)}`:B(i)}l(yt,"encodeQueryItem");function Ot(i){return Object.keys(i).filter(e=>i[e]!==void 0).map(e=>yt(e,i[e])).filter(Boolean).join("&")}l(Ot,"stringifyQuery");const bt=/^[\s\w\0+.-]{2,}:([/\\]{1,2})/,Ct=/^[\s\w\0+.-]{2,}:([/\\]{2})?/,wt=/^([/\\]\s*){2,}[^/\\]/,At=/^\.?\//;function he(i,e={}){return typeof e=="boolean"&&(e={acceptRelative:e}),e.strict?bt.test(i):Ct.test(i)||(e.acceptRelative?wt.test(i):!1)}l(he,"hasProtocol");function Et(i="",e){return i.endsWith("/")}l(Et,"hasTrailingSlash");function $t(i="",e){return(Et(i)?i.slice(0,-1):i)||"/"}l($t,"withoutTrailingSlash");function St(i="",e){return i.endsWith("/")?i:i+"/"}l(St,"withTrailingSlash");function Tt(i,e){if(jt(e)||he(i))return i;const t=$t(e);return i.startsWith(t)?i:xt(t,i)}l(Tt,"withBase");function vt(i,e){const t=Pt(i),n={..._t(t.search),...e};return t.search=Ot(n),Ht(t)}l(vt,"withQuery");function jt(i){return!i||i==="/"}l(jt,"isEmptyURL");function kt(i){return i&&i!=="/"}l(kt,"isNonEmptyURL");function xt(i,...e){let t=i||"";for(const n of e.filter(r=>kt(r)))if(t){const r=n.replace(At,"");t=St(t)+r}else t=n;return t}l(xt,"joinURL");const pe=Symbol.for("ufo:protocolRelative");function Pt(i="",e){const t=i.match(/^[\s\0]*(blob:|data:|javascript:|vbscript:)(.*)/i);if(t){const[,h,d=""]=t;return{protocol:h.toLowerCase(),pathname:d,href:h+d,auth:"",host:"",search:"",hash:""}}if(!he(i,{acceptRelative:!0}))return de(i);const[,n="",r,s=""]=i.replace(/\\/g,"/").match(/^[\s\0]*([\w+.-]{2,}:)?\/\/([^/@]+@)?(.*)/)||[],[,a="",u=""]=s.match(/([^#/?]*)(.*)?/)||[],{pathname:c,search:p,hash:o}=de(u.replace(/\/(?=[A-Za-z]:)/,""));return{protocol:n.toLowerCase(),auth:r?r.slice(0,Math.max(0,r.length-1)):"",host:a,pathname:c,search:p,hash:o,[pe]:!n}}l(Pt,"parseURL");function de(i=""){const[e="",t="",n=""]=(i.match(/([^#?]*)(\?[^#]*)?(#.*)?/)||[]).splice(1);return{pathname:e,search:t,hash:n}}l(de,"parsePath");function Ht(i){const e=i.pathname||"",t=i.search?(i.search.startsWith("?")?"":"?")+i.search:"",n=i.hash||"",r=i.auth?i.auth+"@":"",s=i.host||"";return(i.protocol||i[pe]?(i.protocol||"")+"//":"")+r+s+e+t+n}l(Ht,"stringifyParsedURL");const X=class X extends Error{constructor(e,t){super(e,t),this.name="FetchError",t?.cause&&!this.cause&&(this.cause=t.cause)}};l(X,"FetchError");let K=X;function Rt(i){const e=i.error?.message||i.error?.toString()||"",t=i.request?.method||i.options?.method||"GET",n=i.request?.url||String(i.request)||"/",r=`[${t}] ${JSON.stringify(n)}`,s=i.response?`${i.response.status} ${i.response.statusText}`:"<no response>",a=`${r}: ${s}${e?` ${e}`:""}`,u=new K(a,i.error?{cause:i.error}:void 0);for(const c of["request","options","response"])Object.defineProperty(u,c,{get(){return i[c]}});for(const[c,p]of[["data","_data"],["status","status"],["statusCode","status"],["statusText","statusText"],["statusMessage","statusText"]])Object.defineProperty(u,c,{get(){return i.response&&i.response[p]}});return u}l(Rt,"createFetchError");const It=new Set(Object.freeze(["PATCH","POST","PUT","DELETE"]));function fe(i="GET"){return It.has(i.toUpperCase())}l(fe,"isPayloadMethod");function Nt(i){if(i===void 0)return!1;const e=typeof i;return e==="string"||e==="number"||e==="boolean"||e===null?!0:e!=="object"?!1:Array.isArray(i)?!0:i.buffer?!1:i.constructor&&i.constructor.name==="Object"||typeof i.toJSON=="function"}l(Nt,"isJSONSerializable");const Vt=new Set(["image/svg","application/xml","application/xhtml","application/html"]),Ft=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function Dt(i=""){if(!i)return"json";const e=i.split(";").shift()||"";return Ft.test(e)?"json":Vt.has(e)||e.startsWith("text/")?"text":"blob"}l(Dt,"detectResponseType");function Lt(i,e,t=globalThis.Headers){const n={...e,...i};if(e?.params&&i?.params&&(n.params={...e?.params,...i?.params}),e?.query&&i?.query&&(n.query={...e?.query,...i?.query}),e?.headers&&i?.headers){n.headers=new t(e?.headers||{});for(const[r,s]of new t(i?.headers||{}))n.headers.set(r,s)}return n}l(Lt,"mergeFetchOptions");const qt=new Set([408,409,425,429,500,502,503,504]),Ut=new Set([101,204,205,304]);function me(i={}){const{fetch:e=globalThis.fetch,Headers:t=globalThis.Headers,AbortController:n=globalThis.AbortController}=i;async function r(u){const c=u.error&&u.error.name==="AbortError"&&!u.options.timeout||!1;if(u.options.retry!==!1&&!c){let o;typeof u.options.retry=="number"?o=u.options.retry:o=fe(u.options.method)?0:1;const h=u.response&&u.response.status||500;if(o>0&&(Array.isArray(u.options.retryStatusCodes)?u.options.retryStatusCodes.includes(h):qt.has(h))){const d=u.options.retryDelay||0;return d>0&&await new Promise(O=>setTimeout(O,d)),s(u.request,{...u.options,retry:o-1})}}const p=Rt(u);throw Error.captureStackTrace&&Error.captureStackTrace(p,s),p}l(r,"onError");const s=l(async function(c,p={}){const o={request:c,options:Lt(p,i.defaults,t),response:void 0,error:void 0};o.options.method=o.options.method?.toUpperCase(),o.options.onRequest&&await o.options.onRequest(o),typeof o.request=="string"&&(o.options.baseURL&&(o.request=Tt(o.request,o.options.baseURL)),(o.options.query||o.options.params)&&(o.request=vt(o.request,{...o.options.params,...o.options.query}))),o.options.body&&fe(o.options.method)&&(Nt(o.options.body)?(o.options.body=typeof o.options.body=="string"?o.options.body:JSON.stringify(o.options.body),o.options.headers=new t(o.options.headers||{}),o.options.headers.has("content-type")||o.options.headers.set("content-type","application/json"),o.options.headers.has("accept")||o.options.headers.set("accept","application/json")):("pipeTo"in o.options.body&&typeof o.options.body.pipeTo=="function"||typeof o.options.body.pipe=="function")&&("duplex"in o.options||(o.options.duplex="half")));let h;if(!o.options.signal&&o.options.timeout){const O=new n;h=setTimeout(()=>O.abort(),o.options.timeout),o.options.signal=O.signal}try{o.response=await e(o.request,o.options)}catch(O){return o.error=O,o.options.onRequestError&&await o.options.onRequestError(o),await r(o)}finally{h&&clearTimeout(h)}if(o.response.body&&!Ut.has(o.response.status)&&o.options.method!=="HEAD"){const O=(o.options.parseResponse?"json":o.options.responseType)||Dt(o.response.headers.get("content-type")||"");switch(O){case"json":{const f=await o.response.text(),C=o.options.parseResponse||st;o.response._data=C(f);break}case"stream":{o.response._data=o.response.body;break}default:o.response._data=await o.response[O]()}}return o.options.onResponse&&await o.options.onResponse(o),!o.options.ignoreResponseError&&o.response.status>=400&&o.response.status<600?(o.options.onResponseError&&await o.options.onResponseError(o),await r(o)):o.response},"$fetchRaw2"),a=l(async function(c,p){return(await s(c,p))._data},"$fetch2");return a.raw=s,a.native=(...u)=>e(...u),a.create=(u={})=>me({...i,defaults:{...i.defaults,...u}}),a}l(me,"createFetch");const z=function(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("unable to locate global object")}(),Mt=z.fetch||(()=>Promise.reject(new Error("[ofetch] global.fetch is not supported!"))),Wt=z.Headers,Gt=z.AbortController,F=me({fetch:Mt,Headers:Wt,AbortController:Gt}),Jt={apiRoot:process.env.FRONTSTACK_CLI_API_ROOT||(process.env.FRONTSTACK_CLI_DEV_MODE=="1"?"https://backend.frontstack.dev/":"https://backend.frontlab.dev/")},I=Jt.apiRoot,Bt=`${I}login`,Kt=`${I}api/fetch-api/spec.yaml`,ge=3008,_e=`http://localhost:${ge}`,ye=`${Bt}?redirectUrl=${_e}/callback`,zt=".frontstack-local/",A=g.join(process.cwd(),zt),Q="api_session.jwt",Oe="project.json",N=l(()=>{const i=l(()=>{console.info("Not auth.login implemented yet")},"login"),e=l(async()=>{try{return a(),0}catch(h){console.log(h)}},"logout"),t=l(async(h=void 0)=>{try{return process.env.NODE_TLS_REJECT_UNAUTHORIZED=process.env.FRONTSTACK_CLI_DEV_MODE?"0":"1",await F(`${I}profile`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${h||r()}`}})}catch(d){return console.log(d),1}},"getProfile"),n=l(async(h=void 0)=>{try{const d=c();if(d==null)throw new Error(`You have no project selected
24
+ Run ${m.hex("#7c3bed")("frontstack project")} to select a Frontstack project`);return process.env.NODE_TLS_REJECT_UNAUTHORIZED=process.env.FRONTSTACK_CLI_DEV_MODE?"0":"1",await F(Kt,{method:"GET",headers:{"Content-Type":"application/yaml",Authorization:`Bearer ${h||r()}`,"FS-Project":d},parseResponse:l(f=>{try{return Te.load(f)}catch{throw new Error("Invalid API specification. The API specification must be a valid YAML file.")}},"parseResponse")})}catch(d){throw"data"in d&&"message"in d.data?new Error(`Server error: ${d.data.message}`):d}},"getFetchApiSpec"),r=l(()=>{const h=g.join(A,Q);return y.existsSync(h)?y.readFileSync(h,"utf8"):null},"getToken"),s=l(h=>(y.existsSync(A)||y.mkdirSync(A),y.writeFileSync(g.join(A,Q),h),0),"writeToken"),a=l(()=>{const h=g.join(A,Q);y.existsSync(h)&&y.unlinkSync(h)},"deleteToken"),u=l(async()=>(process.env.NODE_TLS_REJECT_UNAUTHORIZED=process.env.FRONTSTACK_CLI_DEV_MODE?"0":"1",await F(`${I}api/project`,{method:"GET",headers:{"Content-Type":"application/yaml",Authorization:`Bearer ${r()}`},parseResponse:l(h=>JSON.parse(h),"parseResponse")})),"getProjects"),c=l(()=>{const h=g.join(A,Oe);if(!y.existsSync(h))return null;try{return JSON.parse(y.readFileSync(h,"utf8")).projectId}catch{console.error("[Error] Corrupt project file - please run 'frontstack project'")}},"getProjectId");return{login:i,logout:e,getProfile:t,getFetchApiSpec:n,getToken:r,writeToken:s,deleteToken:a,getProjects:u,getProject:l(async()=>{try{const h=c();return h===void 0?void 0:(process.env.NODE_TLS_REJECT_UNAUTHORIZED=process.env.FRONTSTACK_CLI_DEV_MODE?"0":"1",await F(`${I}api/project/${h}`,{method:"GET",headers:{"Content-Type":"application/yaml",Authorization:`Bearer ${r()}`},parseResponse:l(d=>JSON.parse(d),"parseResponse")}))}catch(h){return{error:h.message}}},"getProject"),getProjectId:c,writeProject:l(h=>(y.existsSync(A)||y.mkdirSync(A),y.writeFileSync(g.join(A,Oe),JSON.stringify({projectId:h})),0),"writeProject")}},"auth"),{writeToken:Qt}=N(),Yt=l(async(i,e)=>{const t=new Set,n=ve.createServer((r,s)=>{const a=_e;if(r.url===void 0)return;const c=new URL(r.url,a).searchParams.get("token");c&&(s.writeHead(200,{"Content-Type":"text/html"}),s.end('<html><head><script>// window.close()<\/script></head><body style="font-family: sans-serif;"><div style="height: 100%; width: 100%; display: flex; justify-content: center; align-items: center;"><div style="text-align: center"><h1 style="color: #7c3bed;">Login Successful</h1><p>You can <a href="#" onClick="window.close()">close</a> this browser window and return to the terminal.<p style="font-size: .8rem; color: #666; text-align: left; margin-top: 20px;">&copy; 2024 frontstack</p></div></div></html>'),s.on("finish",async()=>{for(const o of t)o.destroy();Qt(c)!==0&&(console.error("Login failed."),n.close(),process.exit(1)),console.log(`${m.hex("#008000")("[SUCCESS]")} Login successful`),n.close(),process.exit(0)}))}).listen(i,()=>{console.log(`Please continue login in your browser at ${m.hex("#7c3bed")(e)}`)});n.on("connection",r=>{t.add(r),r.on("close",()=>t.delete(r))}),setTimeout(()=>{n.close()},6e4)},"login$1"),Zt=l(async()=>{await je(ye),await Yt(ge,ye)},"login"),Xt=N(),en=l(async i=>{await Xt.logout()!==0&&(console.error("Logout failed."),process.exit(1)),console.log("Logout successful."),process.exit(0)},"logout"),{getFetchApiSpec:tn}=N();E.registerHelper("eq",function(i,e,t){return i===e}),E.registerHelper("uc",function(i){return i.toUpperCase()}),E.registerHelper("contains",function(i,e,t){return i===void 0?!1:i.includes(e)}),E.registerHelper("endsWith",function(i,e,t){return i===void 0?!1:i.endsWith(e)}),E.registerHelper("blockNameFromOperationId",function(i){return i.replace("get","").replace("Block","")});const Y=l((i,e=!1)=>i.$ref?`components['schemas']['${i.$ref.split("/").pop()}']`:i.type==="array"?`Array<${Y(i.items,!0)}>`:i.type==="object"?`{ ${Object.keys(i.properties).map(n=>`${n}: ${Y(i.properties[n])}`).join("; ")} }`:i.type,"getSchemaType");E.registerHelper("getSchemaType",i=>Y(i));var nn=l(async()=>{const i=g.dirname(new URL(import.meta.url).pathname),e=g.join(i,"src/commands/generate/templates"),t=g.join(e,"types.js.hbs"),n=y.readFileSync(t,"utf8"),r=E.compile(n),s=g.join(e,"client.js.hbs"),a=y.readFileSync(s,"utf8"),u=E.compile(a),c=g.join(e,"query.js.hbs"),p=y.readFileSync(c,"utf8");let o;if(o=await tn(),o.error)throw new Error(`Issue fetching API specification. Check more information below.
25
+ `+o.error);let h="";try{h=await ke(o)}catch(f){throw new Error(`Invalid API Specification: ${f.message}`)}const d=r({paths:o.paths,components:o.components}),O=u({paths:o.paths,servers:o.servers});return{_schemaTypes:h,_types:d,_client:O,_query:p}},"generate");const rn=l(async i=>{const e=i.verbose||!1;let t,n,r,s;try{e&&console.log("Generating Javascript client"),{_schemaTypes:t,_types:n,_client:r,_query:s}=await nn()}catch(h){console.error(`${m.hex("#b90404")("[ERROR]")} frontstack generate`),console.error(`${m.hex("#b90404")("[ERROR]")} Failed to generate Javascript client`),e?console.error(`${m.hex("#b90404")("[ERROR]")} ${h.message}`):(console.error("Are you..."),console.error(` * logged in using the ${m.hex("#7c3bed")("frontstack login")} command?`),console.error(" * connected to the internet?"),console.error(`Alternatively, run ${m.hex("#7c3bed")("frontstack generate -v")} for additional output.`));return}let a=i.output||".frontstack";process.stdout.write("Generating Javascript client"),a.startsWith("/")||(a=g.join(process.cwd(),a)),a.endsWith("/")||(a+="/");const u=g.join(a,"fetch-api.d.ts"),c=g.join(a,"generated-types.d.ts"),p=g.join(a,"generated-client.ts"),o=g.join(a,"query-types.ts");e&&(console.log(`
26
+ Schema types path: ${m.dim(u)}`),console.log(`Types path: ${m.dim(c)}`),console.log(`Client path: ${m.dim(p)}`),console.log(`Target directory: ${m.dim(a)}`)),y.mkdirSync(a,{recursive:!0}),y.writeFileSync(g.join(u),t),y.writeFileSync(g.join(c),n),y.writeFileSync(g.join(p),r),y.writeFileSync(g.join(o),s),e?console.log(`Javascript client generated
27
27
  `):(process.stdout.clearLine(0),process.stdout.cursorTo(0),process.stdout.write(m.green(`Javascript client generated
28
28
  `))),console.log(`
29
29
  Use the following imports in your project:
30
30
  `),console.log(" "+m.hex("#7c3bed")("import client from '@frontstack/client';")),console.log(`
31
31
  and use the client like this:
32
32
  `),console.log(" "+m.hex("#7c3bed")("const productDetail = await client.blocks('DetailPage', { key: 'my-product-id' });")),console.log(`
33
- If you make changes to your schema, run ${m.hex("#7c3bed")("frontstack generate")} again to update the client.`)},"generateCommand"),{getToken:rn,getProfile:sn,getProject:on}=V(),an=l(async()=>{if(console.log(m.bgHex("#7c3bed")(`Frontstack User Profile
34
- `)),rn()===null){console.log(`Status: Not logged in.
35
- `),console.log("Run "+m.hex("#7c3bed")("frontstack login")+" to login.");return}try{const e=await sn(),t=await on();console.log(`Status: Logged in
36
- `),console.log(`Email: ${e.email}`),console.log(`Organization: ${e.organizationName}`),console.log(`Current Project: ${t.name??"[No active project selected]"}`)}catch(e){console.log(e)}},"info"),{getProjects:cn,writeProject:be}=V(),ln=l(async s=>{let e=s.project??void 0,t=s.list??!1;const n=await cn();if(t&&n.length>0){console.log(`${m.hex("#7c3bed")("Projects")}
37
- `),console.log("| Project ID | Project Name |");for(let r of n)console.log(`| ${r.id} | ${r.name} |`);console.log("")}else if(n.length>0&&e===void 0)console.log("You didn't specifiy a project ID, so we'll use the first project in your account"),console.log(`You can list projects, using ${m.hex("#7c3bed")("frontstack project --list")}`),console.log(`Select a project, using ${m.hex("#7c3bed")("frontstack project --project <project_id>")}`),e=n[0].id,be(e),console.log(`Project ${m.hex("#7c3bed")(n.find(r=>r.id===e).name)} selected`);else if(e!==void 0){const r=n.find(i=>i.id===e);if(r)be(e),console.log(`Project ${m.hex("#7c3bed")(r.name)} selected`);else throw Error("Project not found. Please select a valid project ID")}else throw Error("No projects found. Please create a new project in your Admin dashboard")},"project"),un=g.dirname(new URL(import.meta.url).pathname),we=$e(g.join(un,"version"),"utf8");let Z="0.0.1-dev";we&&(Z=we.trim());const $=new Ze;$.name("frontstack").description(`${m.bgHex("#7c3bed").bold("Frontstack CLI")}
33
+ If you make changes to your schema, run ${m.hex("#7c3bed")("frontstack generate")} again to update the client.`)},"generateCommand"),{getToken:sn,getProfile:on,getProject:an}=N(),cn=l(async()=>{if(sn()===null){console.log(`Status: Not logged in.
34
+ `),console.log("Run "+m.hex("#7c3bed")("frontstack login")+" to login.");return}try{const e=await on(),t=await an();if(t===void 0||"error"in t){console.log(`Status: No project selected.
35
+ `),console.log("Run "+m.hex("#7c3bed")("frontstack project")+" to select a Frontstack project");return}if(e===1){console.log(`Not logged in.
36
+ `),console.log("Run "+m.hex("#7c3bed")("frontstack login")+" to login.");return}console.log("Logged in as "+m.hex("#7c3bed")(e.email)+`
37
+ `),console.log(`Organization: ${e.organization.name}`),console.log(`Current Project: ${t.name??"[No active project selected]"}`)}catch(e){console.log(e)}},"info");var ln=xe(import.meta.url);const un=ln("prompts"),{getProjects:hn,writeProject:be}=N(),pn=l(async i=>{let e=i.project??void 0,t=[];try{t=await hn()}catch{console.log(`You are not logged in. Please run ${m.hex("#7c3bed")("frontstack login")} to login`);return}if(t.length<1){console.log("No projects found. Please create a new project in your Admin dashboard");return}if(e!==void 0){const r=t.find(s=>s.id===e);if(r){console.log(`Project ${m.hex("#7c3bed")(r.name)} selected`),be(r.id);return}else{console.log(`Project with ID "${e}" not found. Please select a valid project ID`);return}}const n={type:"select",name:"projectId",message:"Pick a project (Use arrow keys and Enter)",choices:t.map(r=>({title:`${r.name} (${r.id})`,value:r.id}))};(async()=>{const r=await un(n),s=t.find(a=>a.id===r.projectId);if(s===void 0){console.log(`Project with ID "${r.projectId}" not found. Please select a valid project ID`);return}console.log(`Project ${m.hex("#7c3bed")(s.name)} selected`),be(r.projectId)})()},"project"),dn=g.dirname(new URL(import.meta.url).pathname),Ce=$e(g.join(dn,"version"),"utf8");let Z="0.0.1-dev";Ce&&(Z=Ce.trim());const $=new Xe;$.name("frontstack").description(`${m.bgHex("#7c3bed").bold("Frontstack CLI")}
38
38
  Manage Frontstack projects from the command line.
39
- ${m.dim(`Version: ${Z}`)}`).version(Z),$.command("login").description("Login to Frontstack account").action(s=>{Yt()}),$.command("logout").description("Logout from Frontstack account").action(async s=>{await Xt()}),$.command("generate").description("Generate a JavaScript client for the current project").option("-o, --output <path>","Output path",".frontstack").option("-v, --verbose","Verbose output").action(async s=>{await nn(s)}),$.command("info").description("Display information about the current organization, project, and user").action(async()=>{await an()}),$.command("project").description("Select current working project which will be used for schema and client updates").option("-l --list","List all projects").option("-p --project <project-id>","Set current project ID").action(async s=>{await ln(s)});var hn=$.parse(process.argv);export{hn as default};
39
+ ${m.dim(`Version: ${Z}`)}`).version(Z),$.command("login").description("Login to Frontstack account").action(i=>{Zt()}),$.command("logout").description("Logout from Frontstack account").action(async i=>{await en()}),$.command("generate").description("Generate a JavaScript client for the current project").option("-o, --output <path>","Output path",".frontstack").option("-v, --verbose","Verbose output").action(async i=>{await rn(i)}),$.command("info").description("Display information about the current organization, project, and user").action(async()=>{await cn()}),$.command("project").description("Select current working project which will be used for schema and client updates").option("-p --project <project-id>","Set current project ID").action(async i=>{await pn(i)});const fn=l(()=>{try{$.parse(process.argv)}catch(i){console.log(i)}},"run");var mn=fn();export{mn as default};
package/dist/version CHANGED
@@ -1 +1 @@
1
- 0.0.0-canary-20240907183730
1
+ 0.0.0-canary-20240907200342
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@frontstackdev/cli",
3
- "version": "0.0.0-canary-20240907183730",
3
+ "version": "0.0.0-canary-20240907200342",
4
4
  "description": "Frontstack CLI for managing projects",
5
5
  "type": "module",
6
6
  "module": "dist/frontstack.mjs",
@@ -25,6 +25,7 @@
25
25
  "@types/node": "^22.5.0"
26
26
  },
27
27
  "devDependencies": {
28
+ "@types/prompts": "^2.4.9",
28
29
  "commander": "^12.0.0",
29
30
  "msw": "^2.2.14",
30
31
  "ofetch": "^1.3.4",
@@ -39,6 +40,7 @@
39
40
  "handlebars": "^4.7.8",
40
41
  "js-yaml": "^4.1.0",
41
42
  "open": "^10.1.0",
42
- "openapi-typescript": "^6.7.5"
43
+ "openapi-typescript": "^6.7.5",
44
+ "prompts": "^2.4.2"
43
45
  }
44
46
  }