@frontstackdev/cli 0.0.0-canary-20250214153840 → 0.0.0-canary-20250218090244

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