@frontstackdev/cli 0.0.0-canary-20241011195213 → 0.0.0-canary-20241014172104

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