@wix/cli-app 1.1.55 → 1.1.57

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/build/CreateVersionCommand-AIXBHCYB.js +269 -0
  2. package/build/{CreateVersionCommand-XTZT5DED.js.map → CreateVersionCommand-AIXBHCYB.js.map} +1 -1
  3. package/build/DevCommand-TOFPM7DZ.js +1168 -0
  4. package/build/{DevCommand-Q5XLAGMG.js.map → DevCommand-TOFPM7DZ.js.map} +1 -1
  5. package/build/GenerateCommand-HB46FNMR.js +12392 -0
  6. package/build/GenerateCommand-HB46FNMR.js.map +1 -0
  7. package/build/LogsCommand-Q2HRBR6G.js +284 -0
  8. package/build/{LogsCommand-XJHE75L2.js.map → LogsCommand-Q2HRBR6G.js.map} +1 -1
  9. package/build/PreviewCommand-XBSTVGWT.js +23 -0
  10. package/build/ServeCommand-ZEXPLXTI.js +165 -0
  11. package/build/{ServeCommand-CPZOI7DC.js.map → ServeCommand-ZEXPLXTI.js.map} +1 -1
  12. package/build/build-3AJU7FWE.js +97 -0
  13. package/build/{build-3RXHADZD.js.map → build-3AJU7FWE.js.map} +1 -1
  14. package/build/build-EC7LZLAY.js +3596 -0
  15. package/build/{build-D3GVJS75.js.map → build-EC7LZLAY.js.map} +1 -1
  16. package/build/chunk-2BYVOUAH.js +46 -0
  17. package/build/{chunk-4BHNJVL2.js.map → chunk-2BYVOUAH.js.map} +1 -1
  18. package/build/chunk-2CUJME55.js +897 -0
  19. package/build/{chunk-7VOKCPZP.js.map → chunk-2CUJME55.js.map} +1 -1
  20. package/build/chunk-2GIVAXZY.js +32 -0
  21. package/build/{chunk-QOUZ6J7N.js.map → chunk-2GIVAXZY.js.map} +1 -1
  22. package/build/chunk-4JP2XRKG.js +39101 -0
  23. package/build/chunk-4JP2XRKG.js.map +1 -0
  24. package/build/chunk-6A37LXDJ.js +51 -0
  25. package/build/{chunk-HDXLQ34N.js.map → chunk-6A37LXDJ.js.map} +1 -1
  26. package/build/chunk-77XREOLU.js +183 -0
  27. package/build/{chunk-X4BLMM2K.js.map → chunk-77XREOLU.js.map} +1 -1
  28. package/build/chunk-BMVZ7QCF.js +104 -0
  29. package/build/{chunk-FKBCPMYK.js.map → chunk-BMVZ7QCF.js.map} +1 -1
  30. package/build/chunk-F2XRLYHS.js +635 -0
  31. package/build/{chunk-GWU77DPO.js.map → chunk-F2XRLYHS.js.map} +1 -1
  32. package/build/chunk-FH6U3Y37.js +19 -0
  33. package/build/chunk-FH6U3Y37.js.map +1 -0
  34. package/build/chunk-FOKCY5BR.js +38035 -0
  35. package/build/{chunk-N5D4TFKX.js.map → chunk-FOKCY5BR.js.map} +1 -1
  36. package/build/chunk-FTNALO4B.js +45 -0
  37. package/build/{chunk-B4SDDVMV.js.map → chunk-FTNALO4B.js.map} +1 -1
  38. package/build/chunk-HL4K6RV3.js +195 -0
  39. package/build/{chunk-C4SXZWXS.js.map → chunk-HL4K6RV3.js.map} +1 -1
  40. package/build/chunk-IJVKSYIY.js +222 -0
  41. package/build/chunk-IJVKSYIY.js.map +1 -0
  42. package/build/chunk-JZVNLHD3.js +151 -0
  43. package/build/{chunk-6HSUK2A2.js.map → chunk-JZVNLHD3.js.map} +1 -1
  44. package/build/chunk-MGPAOFO3.js +29231 -0
  45. package/build/chunk-MGPAOFO3.js.map +1 -0
  46. package/build/chunk-N6O7J2WO.js +1323 -0
  47. package/build/{chunk-LJEYXY4V.js.map → chunk-N6O7J2WO.js.map} +1 -1
  48. package/build/chunk-PYIAC2GK.js +66 -0
  49. package/build/{chunk-V4TR6DCM.js.map → chunk-PYIAC2GK.js.map} +1 -1
  50. package/build/chunk-QG2TLAMS.js +96 -0
  51. package/build/{chunk-K2A77MMN.js.map → chunk-QG2TLAMS.js.map} +1 -1
  52. package/build/chunk-QZOQAFHK.js +2197 -0
  53. package/build/chunk-QZOQAFHK.js.map +1 -0
  54. package/build/chunk-XQ2F7ZVH.js +23 -0
  55. package/build/{chunk-2FB5F5QF.js.map → chunk-XQ2F7ZVH.js.map} +1 -1
  56. package/build/chunk-Y6SGP7TM.js +29 -0
  57. package/build/{chunk-KG7BHEJG.js.map → chunk-Y6SGP7TM.js.map} +1 -1
  58. package/build/cloudflare-runtime/entry.js +1 -1
  59. package/build/cloudflare-runtime/getRegisteredExtensions.js +1 -1
  60. package/build/devtools-YPSDP32D.js +3702 -0
  61. package/build/{devtools-4JFNYU2B.js.map → devtools-YPSDP32D.js.map} +1 -1
  62. package/build/esm-YQVNLOAI.js +22083 -0
  63. package/build/{esm-HBMYQBEO.js.map → esm-YQVNLOAI.js.map} +1 -1
  64. package/build/index.js +3252 -21
  65. package/build/index.js.map +1 -1
  66. package/build/platform-sdk/chunk-DGX4CFXG.js +2 -0
  67. package/build/platform-sdk/chunk-DGX4CFXG.js.map +1 -0
  68. package/build/platform-sdk/chunk-TN6HYRXL.js +2 -0
  69. package/build/platform-sdk/chunk-TN6HYRXL.js.map +1 -0
  70. package/build/platform-sdk/dashboard.js +1 -1
  71. package/build/platform-sdk/dashboard.js.map +1 -1
  72. package/build/platform-sdk/editor.js +5 -5
  73. package/build/platform-sdk/editor.js.map +1 -1
  74. package/build/platform-sdk/site.js +1 -1
  75. package/build/preview-C7XYH7BB.js +138 -0
  76. package/build/{preview-TM7JAWFS.js.map → preview-C7XYH7BB.js.map} +1 -1
  77. package/build/render-command-BMSK4YLL.js +117 -0
  78. package/build/{render-command-QEQ3L7OX.js.map → render-command-BMSK4YLL.js.map} +1 -1
  79. package/build/types.impl-CD4WWRUK.js +10 -0
  80. package/package.json +10 -5
  81. package/templates/custom-element/dependencies.json +1 -1
  82. package/templates/dashboard-modal/dependencies.json +1 -1
  83. package/templates/site-plugin/dependencies.json +1 -1
  84. package/build/CreateVersionCommand-XTZT5DED.js +0 -4
  85. package/build/DevCommand-Q5XLAGMG.js +0 -4
  86. package/build/GenerateCommand-HNFICZJA.js +0 -128
  87. package/build/GenerateCommand-HNFICZJA.js.map +0 -1
  88. package/build/LogsCommand-XJHE75L2.js +0 -4
  89. package/build/PreviewCommand-JKPFMGWV.js +0 -4
  90. package/build/ServeCommand-CPZOI7DC.js +0 -4
  91. package/build/build-3RXHADZD.js +0 -4
  92. package/build/build-D3GVJS75.js +0 -5
  93. package/build/chunk-2FB5F5QF.js +0 -4
  94. package/build/chunk-4BHNJVL2.js +0 -4
  95. package/build/chunk-5OZZ7R6I.js +0 -11
  96. package/build/chunk-5OZZ7R6I.js.map +0 -1
  97. package/build/chunk-6HSUK2A2.js +0 -4
  98. package/build/chunk-7VOKCPZP.js +0 -5
  99. package/build/chunk-B4SDDVMV.js +0 -4
  100. package/build/chunk-C4SXZWXS.js +0 -4
  101. package/build/chunk-FKBCPMYK.js +0 -11
  102. package/build/chunk-FMIXY6J5.js +0 -115
  103. package/build/chunk-FMIXY6J5.js.map +0 -1
  104. package/build/chunk-GWU77DPO.js +0 -4
  105. package/build/chunk-HDXLQ34N.js +0 -4
  106. package/build/chunk-JXE3LQ2S.js +0 -100
  107. package/build/chunk-JXE3LQ2S.js.map +0 -1
  108. package/build/chunk-K2A77MMN.js +0 -4
  109. package/build/chunk-KG7BHEJG.js +0 -4
  110. package/build/chunk-LJEYXY4V.js +0 -4
  111. package/build/chunk-N5D4TFKX.js +0 -280
  112. package/build/chunk-PCBMS46R.js +0 -4
  113. package/build/chunk-PCBMS46R.js.map +0 -1
  114. package/build/chunk-QOUZ6J7N.js +0 -4
  115. package/build/chunk-V4TR6DCM.js +0 -4
  116. package/build/chunk-WJTPY35F.js +0 -9
  117. package/build/chunk-WJTPY35F.js.map +0 -1
  118. package/build/chunk-X4BLMM2K.js +0 -4
  119. package/build/devtools-4JFNYU2B.js +0 -10
  120. package/build/esm-HBMYQBEO.js +0 -466
  121. package/build/platform-sdk/chunk-GZP4Z76C.js +0 -2
  122. package/build/platform-sdk/chunk-GZP4Z76C.js.map +0 -1
  123. package/build/platform-sdk/chunk-KGLNBMRO.js +0 -2
  124. package/build/platform-sdk/chunk-KGLNBMRO.js.map +0 -1
  125. package/build/preview-TM7JAWFS.js +0 -4
  126. package/build/render-command-QEQ3L7OX.js +0 -4
  127. package/build/types.impl-L2DPGJ77.js +0 -4
  128. /package/build/{PreviewCommand-JKPFMGWV.js.map → PreviewCommand-XBSTVGWT.js.map} +0 -0
  129. /package/build/{types.impl-L2DPGJ77.js.map → types.impl-CD4WWRUK.js.map} +0 -0
package/build/index.js CHANGED
@@ -1,25 +1,3256 @@
1
1
  import { createRequire as _createRequire } from 'node:module';
2
2
  const require = _createRequire(import.meta.url);
3
- import{a as A}from"./chunk-2FB5F5QF.js";import"./chunk-5OZZ7R6I.js";import{a as Z,b as V,m as S}from"./chunk-JXE3LQ2S.js";import{a as H,c as E,e as $,h as m}from"./chunk-V4TR6DCM.js";var k=E(W=>{"use strict";m();var P=class extends Error{constructor(e,t,i){super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},N=class extends P{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};W.CommanderError=P;W.InvalidArgumentError=N});var T=E(j=>{"use strict";m();var{InvalidArgumentError:He}=k(),M=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,i)=>{if(!this.argChoices.includes(t))throw new He(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,i):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function ke(o){let e=o.name()+(o.variadic===!0?"...":"");return o.required?"<"+e+">":"["+e+"]"}j.Argument=M;j.humanReadableArgName=ke});var R=E(ee=>{"use strict";m();var{humanReadableArgName:Pe}=T(),U=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let t=e.commands.filter(n=>!n._hidden),i=e._getHelpCommand();return i&&!i._hidden&&t.push(i),this.sortSubcommands&&t.sort((n,r)=>n.name().localeCompare(r.name())),t}compareOptions(e,t){let i=n=>n.short?n.short.replace(/^-/,""):n.long.replace(/^--/,"");return i(e).localeCompare(i(t))}visibleOptions(e){let t=e.options.filter(n=>!n.hidden),i=e._getHelpOption();if(i&&!i.hidden){let n=i.short&&e._findOption(i.short),r=i.long&&e._findOption(i.long);!n&&!r?t.push(i):i.long&&!r?t.push(e.createOption(i.long,i.description)):i.short&&!n&&t.push(e.createOption(i.short,i.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let i=e.parent;i;i=i.parent){let n=i.options.filter(r=>!r.hidden);t.push(...n)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(i=>Pe(i)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((i,n)=>Math.max(i,t.subcommandTerm(n).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((i,n)=>Math.max(i,t.optionTerm(n).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((i,n)=>Math.max(i,t.optionTerm(n).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((i,n)=>Math.max(i,t.argumentTerm(n).length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let i="";for(let n=e.parent;n;n=n.parent)i=n.name()+" "+i;return i+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let i=`(${t.join(", ")})`;return e.description?`${e.description} ${i}`:i}return e.description}formatHelp(e,t){let i=t.padWidth(e,t),n=t.helpWidth||80,r=2,s=2;function u(p,x){if(x){let D=`${p.padEnd(i+s)}${x}`;return t.wrap(D,n-r,i+s)}return p}function a(p){return p.join(`
4
- `).replace(/^/gm," ".repeat(r))}let l=[`Usage: ${t.commandUsage(e)}`,""],h=t.commandDescription(e);h.length>0&&(l=l.concat([t.wrap(h,n,0),""]));let c=t.visibleArguments(e).map(p=>u(t.argumentTerm(p),t.argumentDescription(p)));c.length>0&&(l=l.concat(["Arguments:",a(c),""]));let C=t.visibleOptions(e).map(p=>u(t.optionTerm(p),t.optionDescription(p)));if(C.length>0&&(l=l.concat(["Options:",a(C),""])),this.showGlobalOptions){let p=t.visibleGlobalOptions(e).map(x=>u(t.optionTerm(x),t.optionDescription(x)));p.length>0&&(l=l.concat(["Global Options:",a(p),""]))}let y=t.visibleCommands(e).map(p=>u(t.subcommandTerm(p),t.subcommandDescription(p)));return y.length>0&&(l=l.concat(["Commands:",a(y),""])),l.join(`
5
- `)}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,i,n=40){let r=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",s=new RegExp(`[\\n][${r}]+`);if(e.match(s))return e;let u=t-i;if(u<n)return e;let a=e.slice(0,i),l=e.slice(i).replace(`\r
6
- `,`
7
- `),h=" ".repeat(i),C="\\s\u200B",y=new RegExp(`
8
- |.{1,${u-1}}([${C}]|$)|[^${C}]+?([${C}]|$)`,"g"),p=l.match(y)||[];return a+p.map((x,D)=>x===`
9
- `?"":(D>0?h:"")+x.trimEnd()).join(`
10
- `)}};ee.Help=U});var J=E(B=>{"use strict";m();var{InvalidArgumentError:Te}=k(),G=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let i=Fe(e);this.short=i.shortFlag,this.long=i.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,i)=>{if(!this.argChoices.includes(t))throw new Te(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,i):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return Ie(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},L=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,i)=>{this.positiveOptions.has(i)&&this.dualOptions.add(i)})}valueFromOption(e,t){let i=t.attributeName();if(!this.dualOptions.has(i))return!0;let n=this.negativeOptions.get(i).presetArg,r=n!==void 0?n:!1;return t.negate===(r===e)}};function Ie(o){return o.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function Fe(o){let e,t,i=o.split(/[ |,]+/);return i.length>1&&!/^[[<]/.test(i[1])&&(e=i.shift()),t=i.shift(),!e&&/^-[^-]$/.test(t)&&(e=t,t=void 0),{shortFlag:e,longFlag:t}}B.Option=G;B.DualOptions=L});var ie=E(te=>{"use strict";m();function qe(o,e){if(Math.abs(o.length-e.length)>3)return Math.max(o.length,e.length);let t=[];for(let i=0;i<=o.length;i++)t[i]=[i];for(let i=0;i<=e.length;i++)t[0][i]=i;for(let i=1;i<=e.length;i++)for(let n=1;n<=o.length;n++){let r=1;o[n-1]===e[i-1]?r=0:r=1,t[n][i]=Math.min(t[n-1][i]+1,t[n][i-1]+1,t[n-1][i-1]+r),n>1&&i>1&&o[n-1]===e[i-2]&&o[n-2]===e[i-1]&&(t[n][i]=Math.min(t[n][i],t[n-2][i-2]+1))}return t[o.length][e.length]}function De(o,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=o.startsWith("--");t&&(o=o.slice(2),e=e.map(s=>s.slice(2)));let i=[],n=3,r=.4;return e.forEach(s=>{if(s.length<=1)return;let u=qe(o,s),a=Math.max(o.length,s.length);(a-u)/a>r&&(u<n?(n=u,i=[s]):u===n&&i.push(s))}),i.sort((s,u)=>s.localeCompare(u)),t&&(i=i.map(s=>`--${s}`)),i.length>1?`
11
- (Did you mean one of ${i.join(", ")}?)`:i.length===1?`
12
- (Did you mean ${i[0]}?)`:""}te.suggestSimilar=De});var ae=E(oe=>{"use strict";m();var Ne=H("node:events").EventEmitter,K=H("node:child_process"),v=H("node:path"),z=H("node:fs"),d=H("node:process"),{Argument:We,humanReadableArgName:Me}=T(),{CommanderError:Y}=k(),{Help:je}=R(),{Option:ne,DualOptions:Ue}=J(),{suggestSimilar:re}=ie(),Q=class o extends Ne{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:t=>d.stdout.write(t),writeErr:t=>d.stderr.write(t),getOutHelpWidth:()=>d.stdout.isTTY?d.stdout.columns:void 0,getErrHelpWidth:()=>d.stderr.isTTY?d.stderr.columns:void 0,outputError:(t,i)=>i(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,i){let n=t,r=i;typeof n=="object"&&n!==null&&(r=n,n=null),r=r||{};let[,s,u]=e.match(/([^ ]+) *(.*)/),a=this.createCommand(s);return n&&(a.description(n),a._executableHandler=!0),r.isDefault&&(this._defaultCommandName=a._name),a._hidden=!!(r.noHelp||r.hidden),a._executableFile=r.executableFile||null,u&&a.arguments(u),this._registerCommand(a),a.parent=this,a.copyInheritedSettings(this),n?this:a}createCommand(e){return new o(e)}createHelp(){return Object.assign(new je,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
13
- - 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 We(e,t)}argument(e,t,i,n){let r=this.createArgument(e,t);return typeof i=="function"?r.default(n).argParser(i):r.default(i),this.addArgument(r),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw new Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,i,n]=e.match(/([^ ]+) *(.*)/),r=t??"display help for command",s=this.createCommand(i);return s.helpOption(!1),n&&s.arguments(n),r&&s.description(r),this._addImplicitHelpCommand=!0,this._helpCommand=s,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let i=["preSubcommand","preAction","postAction"];if(!i.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
14
- Expecting one of '${i.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,i){this._exitCallback&&this._exitCallback(new Y(e,t,i)),d.exit(e)}action(e){let t=i=>{let n=this.registeredArguments.length,r=i.slice(0,n);return this._storeOptionsAsProperties?r[n]=this:r[n]=this.opts(),r.push(this),e.apply(this,r)};return this._actionHandler=t,this}createOption(e,t){return new ne(e,t)}_callParseArg(e,t,i,n){try{return e.parseArg(t,i)}catch(r){if(r.code==="commander.invalidArgument"){let s=`${n} ${r.message}`;this.error(s,{exitCode:r.exitCode,code:r.code})}throw r}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let i=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${i}'
15
- - already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=n=>[n.name()].concat(n.aliases()),i=t(e).find(n=>this._findCommand(n));if(i){let n=t(this._findCommand(i)).join("|"),r=t(e).join("|");throw new Error(`cannot add command '${r}' as already have command '${n}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),i=e.attributeName();if(e.negate){let r=e.long.replace(/^--no-/,"--");this._findOption(r)||this.setOptionValueWithSource(i,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(i,e.defaultValue,"default");let n=(r,s,u)=>{r==null&&e.presetArg!==void 0&&(r=e.presetArg);let a=this.getOptionValue(i);r!==null&&e.parseArg?r=this._callParseArg(e,r,a,s):r!==null&&e.variadic&&(r=e._concatValue(r,a)),r==null&&(e.negate?r=!1:e.isBoolean()||e.optional?r=!0:r=""),this.setOptionValueWithSource(i,r,u)};return this.on("option:"+t,r=>{let s=`error: option '${e.flags}' argument '${r}' is invalid.`;n(r,s,"cli")}),e.envVar&&this.on("optionEnv:"+t,r=>{let s=`error: option '${e.flags}' value '${r}' from env '${e.envVar}' is invalid.`;n(r,s,"env")}),this}_optionEx(e,t,i,n,r){if(typeof t=="object"&&t instanceof ne)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let s=this.createOption(t,i);if(s.makeOptionMandatory(!!e.mandatory),typeof n=="function")s.default(r).argParser(n);else if(n instanceof RegExp){let u=n;n=(a,l)=>{let h=u.exec(a);return h?h[0]:l},s.default(r).argParser(n)}else s.default(n);return this.addOption(s)}option(e,t,i,n){return this._optionEx({},e,t,i,n)}requiredOption(e,t,i,n){return this._optionEx({mandatory:!0},e,t,i,n)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,i){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=i,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(i=>{i.getOptionValueSource(e)!==void 0&&(t=i.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){d.versions?.electron&&(t.from="electron");let n=d.execArgv??[];(n.includes("-e")||n.includes("--eval")||n.includes("-p")||n.includes("--print"))&&(t.from="eval")}e===void 0&&(e=d.argv),this.rawArgs=e.slice();let i;switch(t.from){case void 0:case"node":this._scriptPath=e[1],i=e.slice(2);break;case"electron":d.defaultApp?(this._scriptPath=e[1],i=e.slice(2)):i=e.slice(1);break;case"user":i=e.slice(0);break;case"eval":i=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",i}parse(e,t){let i=this._prepareUserArgs(e,t);return this._parseCommand([],i),this}async parseAsync(e,t){let i=this._prepareUserArgs(e,t);return await this._parseCommand([],i),this}_executeSubCommand(e,t){t=t.slice();let i=!1,n=[".js",".ts",".tsx",".mjs",".cjs"];function r(h,c){let C=v.resolve(h,c);if(z.existsSync(C))return C;if(n.includes(v.extname(c)))return;let y=n.find(p=>z.existsSync(`${C}${p}`));if(y)return`${C}${y}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=e._executableFile||`${this._name}-${e._name}`,u=this._executableDir||"";if(this._scriptPath){let h;try{h=z.realpathSync(this._scriptPath)}catch{h=this._scriptPath}u=v.resolve(v.dirname(h),u)}if(u){let h=r(u,s);if(!h&&!e._executableFile&&this._scriptPath){let c=v.basename(this._scriptPath,v.extname(this._scriptPath));c!==this._name&&(h=r(u,`${c}-${e._name}`))}s=h||s}i=n.includes(v.extname(s));let a;d.platform!=="win32"?i?(t.unshift(s),t=se(d.execArgv).concat(t),a=K.spawn(d.argv[0],t,{stdio:"inherit"})):a=K.spawn(s,t,{stdio:"inherit"}):(t.unshift(s),t=se(d.execArgv).concat(t),a=K.spawn(d.execPath,t,{stdio:"inherit"})),a.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(c=>{d.on(c,()=>{a.killed===!1&&a.exitCode===null&&a.kill(c)})});let l=this._exitCallback;a.on("close",h=>{h=h??1,l?l(new Y(h,"commander.executeSubCommandAsync","(close)")):d.exit(h)}),a.on("error",h=>{if(h.code==="ENOENT"){let c=u?`searched for local subcommand relative to directory '${u}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",C=`'${s}' does not exist
16
- - if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
3
+ import {
4
+ createI18nT
5
+ } from "./chunk-XQ2F7ZVH.js";
6
+ import "./chunk-IJVKSYIY.js";
7
+ import {
8
+ require_react,
9
+ version,
10
+ z
11
+ } from "./chunk-MGPAOFO3.js";
12
+ import {
13
+ __commonJS,
14
+ __require,
15
+ __toESM,
16
+ init_esm_shims
17
+ } from "./chunk-PYIAC2GK.js";
18
+
19
+ // ../../node_modules/commander/lib/error.js
20
+ var require_error = __commonJS({
21
+ "../../node_modules/commander/lib/error.js"(exports) {
22
+ "use strict";
23
+ init_esm_shims();
24
+ var CommanderError2 = class extends Error {
25
+ /**
26
+ * Constructs the CommanderError class
27
+ * @param {number} exitCode suggested exit code which could be used with process.exit
28
+ * @param {string} code an id string representing the error
29
+ * @param {string} message human-readable description of the error
30
+ */
31
+ constructor(exitCode, code, message) {
32
+ super(message);
33
+ Error.captureStackTrace(this, this.constructor);
34
+ this.name = this.constructor.name;
35
+ this.code = code;
36
+ this.exitCode = exitCode;
37
+ this.nestedError = void 0;
38
+ }
39
+ };
40
+ var InvalidArgumentError2 = class extends CommanderError2 {
41
+ /**
42
+ * Constructs the InvalidArgumentError class
43
+ * @param {string} [message] explanation of why argument is invalid
44
+ */
45
+ constructor(message) {
46
+ super(1, "commander.invalidArgument", message);
47
+ Error.captureStackTrace(this, this.constructor);
48
+ this.name = this.constructor.name;
49
+ }
50
+ };
51
+ exports.CommanderError = CommanderError2;
52
+ exports.InvalidArgumentError = InvalidArgumentError2;
53
+ }
54
+ });
55
+
56
+ // ../../node_modules/commander/lib/argument.js
57
+ var require_argument = __commonJS({
58
+ "../../node_modules/commander/lib/argument.js"(exports) {
59
+ "use strict";
60
+ init_esm_shims();
61
+ var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
62
+ var Argument2 = class {
63
+ /**
64
+ * Initialize a new command argument with the given name and description.
65
+ * The default is that the argument is required, and you can explicitly
66
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
67
+ *
68
+ * @param {string} name
69
+ * @param {string} [description]
70
+ */
71
+ constructor(name, description) {
72
+ this.description = description || "";
73
+ this.variadic = false;
74
+ this.parseArg = void 0;
75
+ this.defaultValue = void 0;
76
+ this.defaultValueDescription = void 0;
77
+ this.argChoices = void 0;
78
+ switch (name[0]) {
79
+ case "<":
80
+ this.required = true;
81
+ this._name = name.slice(1, -1);
82
+ break;
83
+ case "[":
84
+ this.required = false;
85
+ this._name = name.slice(1, -1);
86
+ break;
87
+ default:
88
+ this.required = true;
89
+ this._name = name;
90
+ break;
91
+ }
92
+ if (this._name.length > 3 && this._name.slice(-3) === "...") {
93
+ this.variadic = true;
94
+ this._name = this._name.slice(0, -3);
95
+ }
96
+ }
97
+ /**
98
+ * Return argument name.
99
+ *
100
+ * @return {string}
101
+ */
102
+ name() {
103
+ return this._name;
104
+ }
105
+ /**
106
+ * @package
107
+ */
108
+ _concatValue(value, previous) {
109
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
110
+ return [value];
111
+ }
112
+ return previous.concat(value);
113
+ }
114
+ /**
115
+ * Set the default value, and optionally supply the description to be displayed in the help.
116
+ *
117
+ * @param {*} value
118
+ * @param {string} [description]
119
+ * @return {Argument}
120
+ */
121
+ default(value, description) {
122
+ this.defaultValue = value;
123
+ this.defaultValueDescription = description;
124
+ return this;
125
+ }
126
+ /**
127
+ * Set the custom handler for processing CLI command arguments into argument values.
128
+ *
129
+ * @param {Function} [fn]
130
+ * @return {Argument}
131
+ */
132
+ argParser(fn) {
133
+ this.parseArg = fn;
134
+ return this;
135
+ }
136
+ /**
137
+ * Only allow argument value to be one of choices.
138
+ *
139
+ * @param {string[]} values
140
+ * @return {Argument}
141
+ */
142
+ choices(values) {
143
+ this.argChoices = values.slice();
144
+ this.parseArg = (arg, previous) => {
145
+ if (!this.argChoices.includes(arg)) {
146
+ throw new InvalidArgumentError2(
147
+ `Allowed choices are ${this.argChoices.join(", ")}.`
148
+ );
149
+ }
150
+ if (this.variadic) {
151
+ return this._concatValue(arg, previous);
152
+ }
153
+ return arg;
154
+ };
155
+ return this;
156
+ }
157
+ /**
158
+ * Make argument required.
159
+ *
160
+ * @returns {Argument}
161
+ */
162
+ argRequired() {
163
+ this.required = true;
164
+ return this;
165
+ }
166
+ /**
167
+ * Make argument optional.
168
+ *
169
+ * @returns {Argument}
170
+ */
171
+ argOptional() {
172
+ this.required = false;
173
+ return this;
174
+ }
175
+ };
176
+ function humanReadableArgName(arg) {
177
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
178
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
179
+ }
180
+ exports.Argument = Argument2;
181
+ exports.humanReadableArgName = humanReadableArgName;
182
+ }
183
+ });
184
+
185
+ // ../../node_modules/commander/lib/help.js
186
+ var require_help = __commonJS({
187
+ "../../node_modules/commander/lib/help.js"(exports) {
188
+ "use strict";
189
+ init_esm_shims();
190
+ var { humanReadableArgName } = require_argument();
191
+ var Help2 = class {
192
+ constructor() {
193
+ this.helpWidth = void 0;
194
+ this.sortSubcommands = false;
195
+ this.sortOptions = false;
196
+ this.showGlobalOptions = false;
197
+ }
198
+ /**
199
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
200
+ *
201
+ * @param {Command} cmd
202
+ * @returns {Command[]}
203
+ */
204
+ visibleCommands(cmd) {
205
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
206
+ const helpCommand = cmd._getHelpCommand();
207
+ if (helpCommand && !helpCommand._hidden) {
208
+ visibleCommands.push(helpCommand);
209
+ }
210
+ if (this.sortSubcommands) {
211
+ visibleCommands.sort((a, b) => {
212
+ return a.name().localeCompare(b.name());
213
+ });
214
+ }
215
+ return visibleCommands;
216
+ }
217
+ /**
218
+ * Compare options for sort.
219
+ *
220
+ * @param {Option} a
221
+ * @param {Option} b
222
+ * @returns {number}
223
+ */
224
+ compareOptions(a, b) {
225
+ const getSortKey = (option) => {
226
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
227
+ };
228
+ return getSortKey(a).localeCompare(getSortKey(b));
229
+ }
230
+ /**
231
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
232
+ *
233
+ * @param {Command} cmd
234
+ * @returns {Option[]}
235
+ */
236
+ visibleOptions(cmd) {
237
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
238
+ const helpOption = cmd._getHelpOption();
239
+ if (helpOption && !helpOption.hidden) {
240
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
241
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
242
+ if (!removeShort && !removeLong) {
243
+ visibleOptions.push(helpOption);
244
+ } else if (helpOption.long && !removeLong) {
245
+ visibleOptions.push(
246
+ cmd.createOption(helpOption.long, helpOption.description)
247
+ );
248
+ } else if (helpOption.short && !removeShort) {
249
+ visibleOptions.push(
250
+ cmd.createOption(helpOption.short, helpOption.description)
251
+ );
252
+ }
253
+ }
254
+ if (this.sortOptions) {
255
+ visibleOptions.sort(this.compareOptions);
256
+ }
257
+ return visibleOptions;
258
+ }
259
+ /**
260
+ * Get an array of the visible global options. (Not including help.)
261
+ *
262
+ * @param {Command} cmd
263
+ * @returns {Option[]}
264
+ */
265
+ visibleGlobalOptions(cmd) {
266
+ if (!this.showGlobalOptions) return [];
267
+ const globalOptions = [];
268
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
269
+ const visibleOptions = ancestorCmd.options.filter(
270
+ (option) => !option.hidden
271
+ );
272
+ globalOptions.push(...visibleOptions);
273
+ }
274
+ if (this.sortOptions) {
275
+ globalOptions.sort(this.compareOptions);
276
+ }
277
+ return globalOptions;
278
+ }
279
+ /**
280
+ * Get an array of the arguments if any have a description.
281
+ *
282
+ * @param {Command} cmd
283
+ * @returns {Argument[]}
284
+ */
285
+ visibleArguments(cmd) {
286
+ if (cmd._argsDescription) {
287
+ cmd.registeredArguments.forEach((argument) => {
288
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
289
+ });
290
+ }
291
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
292
+ return cmd.registeredArguments;
293
+ }
294
+ return [];
295
+ }
296
+ /**
297
+ * Get the command term to show in the list of subcommands.
298
+ *
299
+ * @param {Command} cmd
300
+ * @returns {string}
301
+ */
302
+ subcommandTerm(cmd) {
303
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
304
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
305
+ (args ? " " + args : "");
306
+ }
307
+ /**
308
+ * Get the option term to show in the list of options.
309
+ *
310
+ * @param {Option} option
311
+ * @returns {string}
312
+ */
313
+ optionTerm(option) {
314
+ return option.flags;
315
+ }
316
+ /**
317
+ * Get the argument term to show in the list of arguments.
318
+ *
319
+ * @param {Argument} argument
320
+ * @returns {string}
321
+ */
322
+ argumentTerm(argument) {
323
+ return argument.name();
324
+ }
325
+ /**
326
+ * Get the longest command term length.
327
+ *
328
+ * @param {Command} cmd
329
+ * @param {Help} helper
330
+ * @returns {number}
331
+ */
332
+ longestSubcommandTermLength(cmd, helper) {
333
+ return helper.visibleCommands(cmd).reduce((max, command) => {
334
+ return Math.max(max, helper.subcommandTerm(command).length);
335
+ }, 0);
336
+ }
337
+ /**
338
+ * Get the longest option term length.
339
+ *
340
+ * @param {Command} cmd
341
+ * @param {Help} helper
342
+ * @returns {number}
343
+ */
344
+ longestOptionTermLength(cmd, helper) {
345
+ return helper.visibleOptions(cmd).reduce((max, option) => {
346
+ return Math.max(max, helper.optionTerm(option).length);
347
+ }, 0);
348
+ }
349
+ /**
350
+ * Get the longest global option term length.
351
+ *
352
+ * @param {Command} cmd
353
+ * @param {Help} helper
354
+ * @returns {number}
355
+ */
356
+ longestGlobalOptionTermLength(cmd, helper) {
357
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
358
+ return Math.max(max, helper.optionTerm(option).length);
359
+ }, 0);
360
+ }
361
+ /**
362
+ * Get the longest argument term length.
363
+ *
364
+ * @param {Command} cmd
365
+ * @param {Help} helper
366
+ * @returns {number}
367
+ */
368
+ longestArgumentTermLength(cmd, helper) {
369
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
370
+ return Math.max(max, helper.argumentTerm(argument).length);
371
+ }, 0);
372
+ }
373
+ /**
374
+ * Get the command usage to be displayed at the top of the built-in help.
375
+ *
376
+ * @param {Command} cmd
377
+ * @returns {string}
378
+ */
379
+ commandUsage(cmd) {
380
+ let cmdName = cmd._name;
381
+ if (cmd._aliases[0]) {
382
+ cmdName = cmdName + "|" + cmd._aliases[0];
383
+ }
384
+ let ancestorCmdNames = "";
385
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
386
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
387
+ }
388
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
389
+ }
390
+ /**
391
+ * Get the description for the command.
392
+ *
393
+ * @param {Command} cmd
394
+ * @returns {string}
395
+ */
396
+ commandDescription(cmd) {
397
+ return cmd.description();
398
+ }
399
+ /**
400
+ * Get the subcommand summary to show in the list of subcommands.
401
+ * (Fallback to description for backwards compatibility.)
402
+ *
403
+ * @param {Command} cmd
404
+ * @returns {string}
405
+ */
406
+ subcommandDescription(cmd) {
407
+ return cmd.summary() || cmd.description();
408
+ }
409
+ /**
410
+ * Get the option description to show in the list of options.
411
+ *
412
+ * @param {Option} option
413
+ * @return {string}
414
+ */
415
+ optionDescription(option) {
416
+ const extraInfo = [];
417
+ if (option.argChoices) {
418
+ extraInfo.push(
419
+ // use stringify to match the display of the default value
420
+ `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
421
+ );
422
+ }
423
+ if (option.defaultValue !== void 0) {
424
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
425
+ if (showDefault) {
426
+ extraInfo.push(
427
+ `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`
428
+ );
429
+ }
430
+ }
431
+ if (option.presetArg !== void 0 && option.optional) {
432
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
433
+ }
434
+ if (option.envVar !== void 0) {
435
+ extraInfo.push(`env: ${option.envVar}`);
436
+ }
437
+ if (extraInfo.length > 0) {
438
+ return `${option.description} (${extraInfo.join(", ")})`;
439
+ }
440
+ return option.description;
441
+ }
442
+ /**
443
+ * Get the argument description to show in the list of arguments.
444
+ *
445
+ * @param {Argument} argument
446
+ * @return {string}
447
+ */
448
+ argumentDescription(argument) {
449
+ const extraInfo = [];
450
+ if (argument.argChoices) {
451
+ extraInfo.push(
452
+ // use stringify to match the display of the default value
453
+ `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
454
+ );
455
+ }
456
+ if (argument.defaultValue !== void 0) {
457
+ extraInfo.push(
458
+ `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`
459
+ );
460
+ }
461
+ if (extraInfo.length > 0) {
462
+ const extraDescripton = `(${extraInfo.join(", ")})`;
463
+ if (argument.description) {
464
+ return `${argument.description} ${extraDescripton}`;
465
+ }
466
+ return extraDescripton;
467
+ }
468
+ return argument.description;
469
+ }
470
+ /**
471
+ * Generate the built-in help text.
472
+ *
473
+ * @param {Command} cmd
474
+ * @param {Help} helper
475
+ * @returns {string}
476
+ */
477
+ formatHelp(cmd, helper) {
478
+ const termWidth = helper.padWidth(cmd, helper);
479
+ const helpWidth = helper.helpWidth || 80;
480
+ const itemIndentWidth = 2;
481
+ const itemSeparatorWidth = 2;
482
+ function formatItem(term, description) {
483
+ if (description) {
484
+ const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;
485
+ return helper.wrap(
486
+ fullText,
487
+ helpWidth - itemIndentWidth,
488
+ termWidth + itemSeparatorWidth
489
+ );
490
+ }
491
+ return term;
492
+ }
493
+ function formatList(textArray) {
494
+ return textArray.join("\n").replace(/^/gm, " ".repeat(itemIndentWidth));
495
+ }
496
+ let output = [`Usage: ${helper.commandUsage(cmd)}`, ""];
497
+ const commandDescription = helper.commandDescription(cmd);
498
+ if (commandDescription.length > 0) {
499
+ output = output.concat([
500
+ helper.wrap(commandDescription, helpWidth, 0),
501
+ ""
502
+ ]);
503
+ }
504
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
505
+ return formatItem(
506
+ helper.argumentTerm(argument),
507
+ helper.argumentDescription(argument)
508
+ );
509
+ });
510
+ if (argumentList.length > 0) {
511
+ output = output.concat(["Arguments:", formatList(argumentList), ""]);
512
+ }
513
+ const optionList = helper.visibleOptions(cmd).map((option) => {
514
+ return formatItem(
515
+ helper.optionTerm(option),
516
+ helper.optionDescription(option)
517
+ );
518
+ });
519
+ if (optionList.length > 0) {
520
+ output = output.concat(["Options:", formatList(optionList), ""]);
521
+ }
522
+ if (this.showGlobalOptions) {
523
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
524
+ return formatItem(
525
+ helper.optionTerm(option),
526
+ helper.optionDescription(option)
527
+ );
528
+ });
529
+ if (globalOptionList.length > 0) {
530
+ output = output.concat([
531
+ "Global Options:",
532
+ formatList(globalOptionList),
533
+ ""
534
+ ]);
535
+ }
536
+ }
537
+ const commandList = helper.visibleCommands(cmd).map((cmd2) => {
538
+ return formatItem(
539
+ helper.subcommandTerm(cmd2),
540
+ helper.subcommandDescription(cmd2)
541
+ );
542
+ });
543
+ if (commandList.length > 0) {
544
+ output = output.concat(["Commands:", formatList(commandList), ""]);
545
+ }
546
+ return output.join("\n");
547
+ }
548
+ /**
549
+ * Calculate the pad width from the maximum term length.
550
+ *
551
+ * @param {Command} cmd
552
+ * @param {Help} helper
553
+ * @returns {number}
554
+ */
555
+ padWidth(cmd, helper) {
556
+ return Math.max(
557
+ helper.longestOptionTermLength(cmd, helper),
558
+ helper.longestGlobalOptionTermLength(cmd, helper),
559
+ helper.longestSubcommandTermLength(cmd, helper),
560
+ helper.longestArgumentTermLength(cmd, helper)
561
+ );
562
+ }
563
+ /**
564
+ * Wrap the given string to width characters per line, with lines after the first indented.
565
+ * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.
566
+ *
567
+ * @param {string} str
568
+ * @param {number} width
569
+ * @param {number} indent
570
+ * @param {number} [minColumnWidth=40]
571
+ * @return {string}
572
+ *
573
+ */
574
+ wrap(str, width, indent, minColumnWidth = 40) {
575
+ const indents = " \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF";
576
+ const manualIndent = new RegExp(`[\\n][${indents}]+`);
577
+ if (str.match(manualIndent)) return str;
578
+ const columnWidth = width - indent;
579
+ if (columnWidth < minColumnWidth) return str;
580
+ const leadingStr = str.slice(0, indent);
581
+ const columnText = str.slice(indent).replace("\r\n", "\n");
582
+ const indentString = " ".repeat(indent);
583
+ const zeroWidthSpace = "\u200B";
584
+ const breaks = `\\s${zeroWidthSpace}`;
585
+ const regex = new RegExp(
586
+ `
587
+ |.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`,
588
+ "g"
589
+ );
590
+ const lines = columnText.match(regex) || [];
591
+ return leadingStr + lines.map((line, i) => {
592
+ if (line === "\n") return "";
593
+ return (i > 0 ? indentString : "") + line.trimEnd();
594
+ }).join("\n");
595
+ }
596
+ };
597
+ exports.Help = Help2;
598
+ }
599
+ });
600
+
601
+ // ../../node_modules/commander/lib/option.js
602
+ var require_option = __commonJS({
603
+ "../../node_modules/commander/lib/option.js"(exports) {
604
+ "use strict";
605
+ init_esm_shims();
606
+ var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
607
+ var Option2 = class {
608
+ /**
609
+ * Initialize a new `Option` with the given `flags` and `description`.
610
+ *
611
+ * @param {string} flags
612
+ * @param {string} [description]
613
+ */
614
+ constructor(flags, description) {
615
+ this.flags = flags;
616
+ this.description = description || "";
617
+ this.required = flags.includes("<");
618
+ this.optional = flags.includes("[");
619
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
620
+ this.mandatory = false;
621
+ const optionFlags = splitOptionFlags(flags);
622
+ this.short = optionFlags.shortFlag;
623
+ this.long = optionFlags.longFlag;
624
+ this.negate = false;
625
+ if (this.long) {
626
+ this.negate = this.long.startsWith("--no-");
627
+ }
628
+ this.defaultValue = void 0;
629
+ this.defaultValueDescription = void 0;
630
+ this.presetArg = void 0;
631
+ this.envVar = void 0;
632
+ this.parseArg = void 0;
633
+ this.hidden = false;
634
+ this.argChoices = void 0;
635
+ this.conflictsWith = [];
636
+ this.implied = void 0;
637
+ }
638
+ /**
639
+ * Set the default value, and optionally supply the description to be displayed in the help.
640
+ *
641
+ * @param {*} value
642
+ * @param {string} [description]
643
+ * @return {Option}
644
+ */
645
+ default(value, description) {
646
+ this.defaultValue = value;
647
+ this.defaultValueDescription = description;
648
+ return this;
649
+ }
650
+ /**
651
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
652
+ * The custom processing (parseArg) is called.
653
+ *
654
+ * @example
655
+ * new Option('--color').default('GREYSCALE').preset('RGB');
656
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
657
+ *
658
+ * @param {*} arg
659
+ * @return {Option}
660
+ */
661
+ preset(arg) {
662
+ this.presetArg = arg;
663
+ return this;
664
+ }
665
+ /**
666
+ * Add option name(s) that conflict with this option.
667
+ * An error will be displayed if conflicting options are found during parsing.
668
+ *
669
+ * @example
670
+ * new Option('--rgb').conflicts('cmyk');
671
+ * new Option('--js').conflicts(['ts', 'jsx']);
672
+ *
673
+ * @param {(string | string[])} names
674
+ * @return {Option}
675
+ */
676
+ conflicts(names) {
677
+ this.conflictsWith = this.conflictsWith.concat(names);
678
+ return this;
679
+ }
680
+ /**
681
+ * Specify implied option values for when this option is set and the implied options are not.
682
+ *
683
+ * The custom processing (parseArg) is not called on the implied values.
684
+ *
685
+ * @example
686
+ * program
687
+ * .addOption(new Option('--log', 'write logging information to file'))
688
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
689
+ *
690
+ * @param {object} impliedOptionValues
691
+ * @return {Option}
692
+ */
693
+ implies(impliedOptionValues) {
694
+ let newImplied = impliedOptionValues;
695
+ if (typeof impliedOptionValues === "string") {
696
+ newImplied = { [impliedOptionValues]: true };
697
+ }
698
+ this.implied = Object.assign(this.implied || {}, newImplied);
699
+ return this;
700
+ }
701
+ /**
702
+ * Set environment variable to check for option value.
703
+ *
704
+ * An environment variable is only used if when processed the current option value is
705
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
706
+ *
707
+ * @param {string} name
708
+ * @return {Option}
709
+ */
710
+ env(name) {
711
+ this.envVar = name;
712
+ return this;
713
+ }
714
+ /**
715
+ * Set the custom handler for processing CLI option arguments into option values.
716
+ *
717
+ * @param {Function} [fn]
718
+ * @return {Option}
719
+ */
720
+ argParser(fn) {
721
+ this.parseArg = fn;
722
+ return this;
723
+ }
724
+ /**
725
+ * Whether the option is mandatory and must have a value after parsing.
726
+ *
727
+ * @param {boolean} [mandatory=true]
728
+ * @return {Option}
729
+ */
730
+ makeOptionMandatory(mandatory = true) {
731
+ this.mandatory = !!mandatory;
732
+ return this;
733
+ }
734
+ /**
735
+ * Hide option in help.
736
+ *
737
+ * @param {boolean} [hide=true]
738
+ * @return {Option}
739
+ */
740
+ hideHelp(hide = true) {
741
+ this.hidden = !!hide;
742
+ return this;
743
+ }
744
+ /**
745
+ * @package
746
+ */
747
+ _concatValue(value, previous) {
748
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
749
+ return [value];
750
+ }
751
+ return previous.concat(value);
752
+ }
753
+ /**
754
+ * Only allow option value to be one of choices.
755
+ *
756
+ * @param {string[]} values
757
+ * @return {Option}
758
+ */
759
+ choices(values) {
760
+ this.argChoices = values.slice();
761
+ this.parseArg = (arg, previous) => {
762
+ if (!this.argChoices.includes(arg)) {
763
+ throw new InvalidArgumentError2(
764
+ `Allowed choices are ${this.argChoices.join(", ")}.`
765
+ );
766
+ }
767
+ if (this.variadic) {
768
+ return this._concatValue(arg, previous);
769
+ }
770
+ return arg;
771
+ };
772
+ return this;
773
+ }
774
+ /**
775
+ * Return option name.
776
+ *
777
+ * @return {string}
778
+ */
779
+ name() {
780
+ if (this.long) {
781
+ return this.long.replace(/^--/, "");
782
+ }
783
+ return this.short.replace(/^-/, "");
784
+ }
785
+ /**
786
+ * Return option name, in a camelcase format that can be used
787
+ * as a object attribute key.
788
+ *
789
+ * @return {string}
790
+ */
791
+ attributeName() {
792
+ return camelcase(this.name().replace(/^no-/, ""));
793
+ }
794
+ /**
795
+ * Check if `arg` matches the short or long flag.
796
+ *
797
+ * @param {string} arg
798
+ * @return {boolean}
799
+ * @package
800
+ */
801
+ is(arg) {
802
+ return this.short === arg || this.long === arg;
803
+ }
804
+ /**
805
+ * Return whether a boolean option.
806
+ *
807
+ * Options are one of boolean, negated, required argument, or optional argument.
808
+ *
809
+ * @return {boolean}
810
+ * @package
811
+ */
812
+ isBoolean() {
813
+ return !this.required && !this.optional && !this.negate;
814
+ }
815
+ };
816
+ var DualOptions = class {
817
+ /**
818
+ * @param {Option[]} options
819
+ */
820
+ constructor(options) {
821
+ this.positiveOptions = /* @__PURE__ */ new Map();
822
+ this.negativeOptions = /* @__PURE__ */ new Map();
823
+ this.dualOptions = /* @__PURE__ */ new Set();
824
+ options.forEach((option) => {
825
+ if (option.negate) {
826
+ this.negativeOptions.set(option.attributeName(), option);
827
+ } else {
828
+ this.positiveOptions.set(option.attributeName(), option);
829
+ }
830
+ });
831
+ this.negativeOptions.forEach((value, key) => {
832
+ if (this.positiveOptions.has(key)) {
833
+ this.dualOptions.add(key);
834
+ }
835
+ });
836
+ }
837
+ /**
838
+ * Did the value come from the option, and not from possible matching dual option?
839
+ *
840
+ * @param {*} value
841
+ * @param {Option} option
842
+ * @returns {boolean}
843
+ */
844
+ valueFromOption(value, option) {
845
+ const optionKey = option.attributeName();
846
+ if (!this.dualOptions.has(optionKey)) return true;
847
+ const preset = this.negativeOptions.get(optionKey).presetArg;
848
+ const negativeValue = preset !== void 0 ? preset : false;
849
+ return option.negate === (negativeValue === value);
850
+ }
851
+ };
852
+ function camelcase(str) {
853
+ return str.split("-").reduce((str2, word) => {
854
+ return str2 + word[0].toUpperCase() + word.slice(1);
855
+ });
856
+ }
857
+ function splitOptionFlags(flags) {
858
+ let shortFlag;
859
+ let longFlag;
860
+ const flagParts = flags.split(/[ |,]+/);
861
+ if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1]))
862
+ shortFlag = flagParts.shift();
863
+ longFlag = flagParts.shift();
864
+ if (!shortFlag && /^-[^-]$/.test(longFlag)) {
865
+ shortFlag = longFlag;
866
+ longFlag = void 0;
867
+ }
868
+ return { shortFlag, longFlag };
869
+ }
870
+ exports.Option = Option2;
871
+ exports.DualOptions = DualOptions;
872
+ }
873
+ });
874
+
875
+ // ../../node_modules/commander/lib/suggestSimilar.js
876
+ var require_suggestSimilar = __commonJS({
877
+ "../../node_modules/commander/lib/suggestSimilar.js"(exports) {
878
+ "use strict";
879
+ init_esm_shims();
880
+ var maxDistance = 3;
881
+ function editDistance(a, b) {
882
+ if (Math.abs(a.length - b.length) > maxDistance)
883
+ return Math.max(a.length, b.length);
884
+ const d = [];
885
+ for (let i = 0; i <= a.length; i++) {
886
+ d[i] = [i];
887
+ }
888
+ for (let j = 0; j <= b.length; j++) {
889
+ d[0][j] = j;
890
+ }
891
+ for (let j = 1; j <= b.length; j++) {
892
+ for (let i = 1; i <= a.length; i++) {
893
+ let cost = 1;
894
+ if (a[i - 1] === b[j - 1]) {
895
+ cost = 0;
896
+ } else {
897
+ cost = 1;
898
+ }
899
+ d[i][j] = Math.min(
900
+ d[i - 1][j] + 1,
901
+ // deletion
902
+ d[i][j - 1] + 1,
903
+ // insertion
904
+ d[i - 1][j - 1] + cost
905
+ // substitution
906
+ );
907
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
908
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
909
+ }
910
+ }
911
+ }
912
+ return d[a.length][b.length];
913
+ }
914
+ function suggestSimilar(word, candidates) {
915
+ if (!candidates || candidates.length === 0) return "";
916
+ candidates = Array.from(new Set(candidates));
917
+ const searchingOptions = word.startsWith("--");
918
+ if (searchingOptions) {
919
+ word = word.slice(2);
920
+ candidates = candidates.map((candidate) => candidate.slice(2));
921
+ }
922
+ let similar = [];
923
+ let bestDistance = maxDistance;
924
+ const minSimilarity = 0.4;
925
+ candidates.forEach((candidate) => {
926
+ if (candidate.length <= 1) return;
927
+ const distance = editDistance(word, candidate);
928
+ const length = Math.max(word.length, candidate.length);
929
+ const similarity = (length - distance) / length;
930
+ if (similarity > minSimilarity) {
931
+ if (distance < bestDistance) {
932
+ bestDistance = distance;
933
+ similar = [candidate];
934
+ } else if (distance === bestDistance) {
935
+ similar.push(candidate);
936
+ }
937
+ }
938
+ });
939
+ similar.sort((a, b) => a.localeCompare(b));
940
+ if (searchingOptions) {
941
+ similar = similar.map((candidate) => `--${candidate}`);
942
+ }
943
+ if (similar.length > 1) {
944
+ return `
945
+ (Did you mean one of ${similar.join(", ")}?)`;
946
+ }
947
+ if (similar.length === 1) {
948
+ return `
949
+ (Did you mean ${similar[0]}?)`;
950
+ }
951
+ return "";
952
+ }
953
+ exports.suggestSimilar = suggestSimilar;
954
+ }
955
+ });
956
+
957
+ // ../../node_modules/commander/lib/command.js
958
+ var require_command = __commonJS({
959
+ "../../node_modules/commander/lib/command.js"(exports) {
960
+ "use strict";
961
+ init_esm_shims();
962
+ var EventEmitter = __require("node:events").EventEmitter;
963
+ var childProcess = __require("node:child_process");
964
+ var path = __require("node:path");
965
+ var fs = __require("node:fs");
966
+ var process = __require("node:process");
967
+ var { Argument: Argument2, humanReadableArgName } = require_argument();
968
+ var { CommanderError: CommanderError2 } = require_error();
969
+ var { Help: Help2 } = require_help();
970
+ var { Option: Option2, DualOptions } = require_option();
971
+ var { suggestSimilar } = require_suggestSimilar();
972
+ var Command2 = class _Command extends EventEmitter {
973
+ /**
974
+ * Initialize a new `Command`.
975
+ *
976
+ * @param {string} [name]
977
+ */
978
+ constructor(name) {
979
+ super();
980
+ this.commands = [];
981
+ this.options = [];
982
+ this.parent = null;
983
+ this._allowUnknownOption = false;
984
+ this._allowExcessArguments = true;
985
+ this.registeredArguments = [];
986
+ this._args = this.registeredArguments;
987
+ this.args = [];
988
+ this.rawArgs = [];
989
+ this.processedArgs = [];
990
+ this._scriptPath = null;
991
+ this._name = name || "";
992
+ this._optionValues = {};
993
+ this._optionValueSources = {};
994
+ this._storeOptionsAsProperties = false;
995
+ this._actionHandler = null;
996
+ this._executableHandler = false;
997
+ this._executableFile = null;
998
+ this._executableDir = null;
999
+ this._defaultCommandName = null;
1000
+ this._exitCallback = null;
1001
+ this._aliases = [];
1002
+ this._combineFlagAndOptionalValue = true;
1003
+ this._description = "";
1004
+ this._summary = "";
1005
+ this._argsDescription = void 0;
1006
+ this._enablePositionalOptions = false;
1007
+ this._passThroughOptions = false;
1008
+ this._lifeCycleHooks = {};
1009
+ this._showHelpAfterError = false;
1010
+ this._showSuggestionAfterError = true;
1011
+ this._outputConfiguration = {
1012
+ writeOut: (str) => process.stdout.write(str),
1013
+ writeErr: (str) => process.stderr.write(str),
1014
+ getOutHelpWidth: () => process.stdout.isTTY ? process.stdout.columns : void 0,
1015
+ getErrHelpWidth: () => process.stderr.isTTY ? process.stderr.columns : void 0,
1016
+ outputError: (str, write) => write(str)
1017
+ };
1018
+ this._hidden = false;
1019
+ this._helpOption = void 0;
1020
+ this._addImplicitHelpCommand = void 0;
1021
+ this._helpCommand = void 0;
1022
+ this._helpConfiguration = {};
1023
+ }
1024
+ /**
1025
+ * Copy settings that are useful to have in common across root command and subcommands.
1026
+ *
1027
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1028
+ *
1029
+ * @param {Command} sourceCommand
1030
+ * @return {Command} `this` command for chaining
1031
+ */
1032
+ copyInheritedSettings(sourceCommand) {
1033
+ this._outputConfiguration = sourceCommand._outputConfiguration;
1034
+ this._helpOption = sourceCommand._helpOption;
1035
+ this._helpCommand = sourceCommand._helpCommand;
1036
+ this._helpConfiguration = sourceCommand._helpConfiguration;
1037
+ this._exitCallback = sourceCommand._exitCallback;
1038
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1039
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1040
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
1041
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1042
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
1043
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1044
+ return this;
1045
+ }
1046
+ /**
1047
+ * @returns {Command[]}
1048
+ * @private
1049
+ */
1050
+ _getCommandAndAncestors() {
1051
+ const result = [];
1052
+ for (let command = this; command; command = command.parent) {
1053
+ result.push(command);
1054
+ }
1055
+ return result;
1056
+ }
1057
+ /**
1058
+ * Define a command.
1059
+ *
1060
+ * There are two styles of command: pay attention to where to put the description.
1061
+ *
1062
+ * @example
1063
+ * // Command implemented using action handler (description is supplied separately to `.command`)
1064
+ * program
1065
+ * .command('clone <source> [destination]')
1066
+ * .description('clone a repository into a newly created directory')
1067
+ * .action((source, destination) => {
1068
+ * console.log('clone command called');
1069
+ * });
1070
+ *
1071
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
1072
+ * program
1073
+ * .command('start <service>', 'start named service')
1074
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
1075
+ *
1076
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1077
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1078
+ * @param {object} [execOpts] - configuration options (for executable)
1079
+ * @return {Command} returns new command for action handler, or `this` for executable command
1080
+ */
1081
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1082
+ let desc = actionOptsOrExecDesc;
1083
+ let opts = execOpts;
1084
+ if (typeof desc === "object" && desc !== null) {
1085
+ opts = desc;
1086
+ desc = null;
1087
+ }
1088
+ opts = opts || {};
1089
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1090
+ const cmd = this.createCommand(name);
1091
+ if (desc) {
1092
+ cmd.description(desc);
1093
+ cmd._executableHandler = true;
1094
+ }
1095
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1096
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
1097
+ cmd._executableFile = opts.executableFile || null;
1098
+ if (args) cmd.arguments(args);
1099
+ this._registerCommand(cmd);
1100
+ cmd.parent = this;
1101
+ cmd.copyInheritedSettings(this);
1102
+ if (desc) return this;
1103
+ return cmd;
1104
+ }
1105
+ /**
1106
+ * Factory routine to create a new unattached command.
1107
+ *
1108
+ * See .command() for creating an attached subcommand, which uses this routine to
1109
+ * create the command. You can override createCommand to customise subcommands.
1110
+ *
1111
+ * @param {string} [name]
1112
+ * @return {Command} new command
1113
+ */
1114
+ createCommand(name) {
1115
+ return new _Command(name);
1116
+ }
1117
+ /**
1118
+ * You can customise the help with a subclass of Help by overriding createHelp,
1119
+ * or by overriding Help properties using configureHelp().
1120
+ *
1121
+ * @return {Help}
1122
+ */
1123
+ createHelp() {
1124
+ return Object.assign(new Help2(), this.configureHelp());
1125
+ }
1126
+ /**
1127
+ * You can customise the help by overriding Help properties using configureHelp(),
1128
+ * or with a subclass of Help by overriding createHelp().
1129
+ *
1130
+ * @param {object} [configuration] - configuration options
1131
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1132
+ */
1133
+ configureHelp(configuration) {
1134
+ if (configuration === void 0) return this._helpConfiguration;
1135
+ this._helpConfiguration = configuration;
1136
+ return this;
1137
+ }
1138
+ /**
1139
+ * The default output goes to stdout and stderr. You can customise this for special
1140
+ * applications. You can also customise the display of errors by overriding outputError.
1141
+ *
1142
+ * The configuration properties are all functions:
1143
+ *
1144
+ * // functions to change where being written, stdout and stderr
1145
+ * writeOut(str)
1146
+ * writeErr(str)
1147
+ * // matching functions to specify width for wrapping help
1148
+ * getOutHelpWidth()
1149
+ * getErrHelpWidth()
1150
+ * // functions based on what is being written out
1151
+ * outputError(str, write) // used for displaying errors, and not used for displaying help
1152
+ *
1153
+ * @param {object} [configuration] - configuration options
1154
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1155
+ */
1156
+ configureOutput(configuration) {
1157
+ if (configuration === void 0) return this._outputConfiguration;
1158
+ Object.assign(this._outputConfiguration, configuration);
1159
+ return this;
1160
+ }
1161
+ /**
1162
+ * Display the help or a custom message after an error occurs.
1163
+ *
1164
+ * @param {(boolean|string)} [displayHelp]
1165
+ * @return {Command} `this` command for chaining
1166
+ */
1167
+ showHelpAfterError(displayHelp = true) {
1168
+ if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
1169
+ this._showHelpAfterError = displayHelp;
1170
+ return this;
1171
+ }
1172
+ /**
1173
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
1174
+ *
1175
+ * @param {boolean} [displaySuggestion]
1176
+ * @return {Command} `this` command for chaining
1177
+ */
1178
+ showSuggestionAfterError(displaySuggestion = true) {
1179
+ this._showSuggestionAfterError = !!displaySuggestion;
1180
+ return this;
1181
+ }
1182
+ /**
1183
+ * Add a prepared subcommand.
1184
+ *
1185
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
1186
+ *
1187
+ * @param {Command} cmd - new subcommand
1188
+ * @param {object} [opts] - configuration options
1189
+ * @return {Command} `this` command for chaining
1190
+ */
1191
+ addCommand(cmd, opts) {
1192
+ if (!cmd._name) {
1193
+ throw new Error(`Command passed to .addCommand() must have a name
1194
+ - specify the name in Command constructor or using .name()`);
1195
+ }
1196
+ opts = opts || {};
1197
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1198
+ if (opts.noHelp || opts.hidden) cmd._hidden = true;
1199
+ this._registerCommand(cmd);
1200
+ cmd.parent = this;
1201
+ cmd._checkForBrokenPassThrough();
1202
+ return this;
1203
+ }
1204
+ /**
1205
+ * Factory routine to create a new unattached argument.
1206
+ *
1207
+ * See .argument() for creating an attached argument, which uses this routine to
1208
+ * create the argument. You can override createArgument to return a custom argument.
1209
+ *
1210
+ * @param {string} name
1211
+ * @param {string} [description]
1212
+ * @return {Argument} new argument
1213
+ */
1214
+ createArgument(name, description) {
1215
+ return new Argument2(name, description);
1216
+ }
1217
+ /**
1218
+ * Define argument syntax for command.
1219
+ *
1220
+ * The default is that the argument is required, and you can explicitly
1221
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
1222
+ *
1223
+ * @example
1224
+ * program.argument('<input-file>');
1225
+ * program.argument('[output-file]');
1226
+ *
1227
+ * @param {string} name
1228
+ * @param {string} [description]
1229
+ * @param {(Function|*)} [fn] - custom argument processing function
1230
+ * @param {*} [defaultValue]
1231
+ * @return {Command} `this` command for chaining
1232
+ */
1233
+ argument(name, description, fn, defaultValue) {
1234
+ const argument = this.createArgument(name, description);
1235
+ if (typeof fn === "function") {
1236
+ argument.default(defaultValue).argParser(fn);
1237
+ } else {
1238
+ argument.default(fn);
1239
+ }
1240
+ this.addArgument(argument);
1241
+ return this;
1242
+ }
1243
+ /**
1244
+ * Define argument syntax for command, adding multiple at once (without descriptions).
1245
+ *
1246
+ * See also .argument().
1247
+ *
1248
+ * @example
1249
+ * program.arguments('<cmd> [env]');
1250
+ *
1251
+ * @param {string} names
1252
+ * @return {Command} `this` command for chaining
1253
+ */
1254
+ arguments(names) {
1255
+ names.trim().split(/ +/).forEach((detail) => {
1256
+ this.argument(detail);
1257
+ });
1258
+ return this;
1259
+ }
1260
+ /**
1261
+ * Define argument syntax for command, adding a prepared argument.
1262
+ *
1263
+ * @param {Argument} argument
1264
+ * @return {Command} `this` command for chaining
1265
+ */
1266
+ addArgument(argument) {
1267
+ const previousArgument = this.registeredArguments.slice(-1)[0];
1268
+ if (previousArgument && previousArgument.variadic) {
1269
+ throw new Error(
1270
+ `only the last argument can be variadic '${previousArgument.name()}'`
1271
+ );
1272
+ }
1273
+ if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
1274
+ throw new Error(
1275
+ `a default value for a required argument is never used: '${argument.name()}'`
1276
+ );
1277
+ }
1278
+ this.registeredArguments.push(argument);
1279
+ return this;
1280
+ }
1281
+ /**
1282
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
1283
+ *
1284
+ * @example
1285
+ * program.helpCommand('help [cmd]');
1286
+ * program.helpCommand('help [cmd]', 'show help');
1287
+ * program.helpCommand(false); // suppress default help command
1288
+ * program.helpCommand(true); // add help command even if no subcommands
1289
+ *
1290
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
1291
+ * @param {string} [description] - custom description
1292
+ * @return {Command} `this` command for chaining
1293
+ */
1294
+ helpCommand(enableOrNameAndArgs, description) {
1295
+ if (typeof enableOrNameAndArgs === "boolean") {
1296
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
1297
+ return this;
1298
+ }
1299
+ enableOrNameAndArgs = enableOrNameAndArgs ?? "help [command]";
1300
+ const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);
1301
+ const helpDescription = description ?? "display help for command";
1302
+ const helpCommand = this.createCommand(helpName);
1303
+ helpCommand.helpOption(false);
1304
+ if (helpArgs) helpCommand.arguments(helpArgs);
1305
+ if (helpDescription) helpCommand.description(helpDescription);
1306
+ this._addImplicitHelpCommand = true;
1307
+ this._helpCommand = helpCommand;
1308
+ return this;
1309
+ }
1310
+ /**
1311
+ * Add prepared custom help command.
1312
+ *
1313
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
1314
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
1315
+ * @return {Command} `this` command for chaining
1316
+ */
1317
+ addHelpCommand(helpCommand, deprecatedDescription) {
1318
+ if (typeof helpCommand !== "object") {
1319
+ this.helpCommand(helpCommand, deprecatedDescription);
1320
+ return this;
1321
+ }
1322
+ this._addImplicitHelpCommand = true;
1323
+ this._helpCommand = helpCommand;
1324
+ return this;
1325
+ }
1326
+ /**
1327
+ * Lazy create help command.
1328
+ *
1329
+ * @return {(Command|null)}
1330
+ * @package
1331
+ */
1332
+ _getHelpCommand() {
1333
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
1334
+ if (hasImplicitHelpCommand) {
1335
+ if (this._helpCommand === void 0) {
1336
+ this.helpCommand(void 0, void 0);
1337
+ }
1338
+ return this._helpCommand;
1339
+ }
1340
+ return null;
1341
+ }
1342
+ /**
1343
+ * Add hook for life cycle event.
1344
+ *
1345
+ * @param {string} event
1346
+ * @param {Function} listener
1347
+ * @return {Command} `this` command for chaining
1348
+ */
1349
+ hook(event, listener) {
1350
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
1351
+ if (!allowedValues.includes(event)) {
1352
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
1353
+ Expecting one of '${allowedValues.join("', '")}'`);
1354
+ }
1355
+ if (this._lifeCycleHooks[event]) {
1356
+ this._lifeCycleHooks[event].push(listener);
1357
+ } else {
1358
+ this._lifeCycleHooks[event] = [listener];
1359
+ }
1360
+ return this;
1361
+ }
1362
+ /**
1363
+ * Register callback to use as replacement for calling process.exit.
1364
+ *
1365
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
1366
+ * @return {Command} `this` command for chaining
1367
+ */
1368
+ exitOverride(fn) {
1369
+ if (fn) {
1370
+ this._exitCallback = fn;
1371
+ } else {
1372
+ this._exitCallback = (err) => {
1373
+ if (err.code !== "commander.executeSubCommandAsync") {
1374
+ throw err;
1375
+ } else {
1376
+ }
1377
+ };
1378
+ }
1379
+ return this;
1380
+ }
1381
+ /**
1382
+ * Call process.exit, and _exitCallback if defined.
1383
+ *
1384
+ * @param {number} exitCode exit code for using with process.exit
1385
+ * @param {string} code an id string representing the error
1386
+ * @param {string} message human-readable description of the error
1387
+ * @return never
1388
+ * @private
1389
+ */
1390
+ _exit(exitCode, code, message) {
1391
+ if (this._exitCallback) {
1392
+ this._exitCallback(new CommanderError2(exitCode, code, message));
1393
+ }
1394
+ process.exit(exitCode);
1395
+ }
1396
+ /**
1397
+ * Register callback `fn` for the command.
1398
+ *
1399
+ * @example
1400
+ * program
1401
+ * .command('serve')
1402
+ * .description('start service')
1403
+ * .action(function() {
1404
+ * // do work here
1405
+ * });
1406
+ *
1407
+ * @param {Function} fn
1408
+ * @return {Command} `this` command for chaining
1409
+ */
1410
+ action(fn) {
1411
+ const listener = (args) => {
1412
+ const expectedArgsCount = this.registeredArguments.length;
1413
+ const actionArgs = args.slice(0, expectedArgsCount);
1414
+ if (this._storeOptionsAsProperties) {
1415
+ actionArgs[expectedArgsCount] = this;
1416
+ } else {
1417
+ actionArgs[expectedArgsCount] = this.opts();
1418
+ }
1419
+ actionArgs.push(this);
1420
+ return fn.apply(this, actionArgs);
1421
+ };
1422
+ this._actionHandler = listener;
1423
+ return this;
1424
+ }
1425
+ /**
1426
+ * Factory routine to create a new unattached option.
1427
+ *
1428
+ * See .option() for creating an attached option, which uses this routine to
1429
+ * create the option. You can override createOption to return a custom option.
1430
+ *
1431
+ * @param {string} flags
1432
+ * @param {string} [description]
1433
+ * @return {Option} new option
1434
+ */
1435
+ createOption(flags, description) {
1436
+ return new Option2(flags, description);
1437
+ }
1438
+ /**
1439
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
1440
+ *
1441
+ * @param {(Option | Argument)} target
1442
+ * @param {string} value
1443
+ * @param {*} previous
1444
+ * @param {string} invalidArgumentMessage
1445
+ * @private
1446
+ */
1447
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
1448
+ try {
1449
+ return target.parseArg(value, previous);
1450
+ } catch (err) {
1451
+ if (err.code === "commander.invalidArgument") {
1452
+ const message = `${invalidArgumentMessage} ${err.message}`;
1453
+ this.error(message, { exitCode: err.exitCode, code: err.code });
1454
+ }
1455
+ throw err;
1456
+ }
1457
+ }
1458
+ /**
1459
+ * Check for option flag conflicts.
1460
+ * Register option if no conflicts found, or throw on conflict.
1461
+ *
1462
+ * @param {Option} option
1463
+ * @private
1464
+ */
1465
+ _registerOption(option) {
1466
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1467
+ if (matchingOption) {
1468
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1469
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1470
+ - already used by option '${matchingOption.flags}'`);
1471
+ }
1472
+ this.options.push(option);
1473
+ }
1474
+ /**
1475
+ * Check for command name and alias conflicts with existing commands.
1476
+ * Register command if no conflicts found, or throw on conflict.
1477
+ *
1478
+ * @param {Command} command
1479
+ * @private
1480
+ */
1481
+ _registerCommand(command) {
1482
+ const knownBy = (cmd) => {
1483
+ return [cmd.name()].concat(cmd.aliases());
1484
+ };
1485
+ const alreadyUsed = knownBy(command).find(
1486
+ (name) => this._findCommand(name)
1487
+ );
1488
+ if (alreadyUsed) {
1489
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1490
+ const newCmd = knownBy(command).join("|");
1491
+ throw new Error(
1492
+ `cannot add command '${newCmd}' as already have command '${existingCmd}'`
1493
+ );
1494
+ }
1495
+ this.commands.push(command);
1496
+ }
1497
+ /**
1498
+ * Add an option.
1499
+ *
1500
+ * @param {Option} option
1501
+ * @return {Command} `this` command for chaining
1502
+ */
1503
+ addOption(option) {
1504
+ this._registerOption(option);
1505
+ const oname = option.name();
1506
+ const name = option.attributeName();
1507
+ if (option.negate) {
1508
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1509
+ if (!this._findOption(positiveLongFlag)) {
1510
+ this.setOptionValueWithSource(
1511
+ name,
1512
+ option.defaultValue === void 0 ? true : option.defaultValue,
1513
+ "default"
1514
+ );
1515
+ }
1516
+ } else if (option.defaultValue !== void 0) {
1517
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
1518
+ }
1519
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1520
+ if (val == null && option.presetArg !== void 0) {
1521
+ val = option.presetArg;
1522
+ }
1523
+ const oldValue = this.getOptionValue(name);
1524
+ if (val !== null && option.parseArg) {
1525
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1526
+ } else if (val !== null && option.variadic) {
1527
+ val = option._concatValue(val, oldValue);
1528
+ }
1529
+ if (val == null) {
1530
+ if (option.negate) {
1531
+ val = false;
1532
+ } else if (option.isBoolean() || option.optional) {
1533
+ val = true;
1534
+ } else {
1535
+ val = "";
1536
+ }
1537
+ }
1538
+ this.setOptionValueWithSource(name, val, valueSource);
1539
+ };
1540
+ this.on("option:" + oname, (val) => {
1541
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1542
+ handleOptionValue(val, invalidValueMessage, "cli");
1543
+ });
1544
+ if (option.envVar) {
1545
+ this.on("optionEnv:" + oname, (val) => {
1546
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1547
+ handleOptionValue(val, invalidValueMessage, "env");
1548
+ });
1549
+ }
1550
+ return this;
1551
+ }
1552
+ /**
1553
+ * Internal implementation shared by .option() and .requiredOption()
1554
+ *
1555
+ * @return {Command} `this` command for chaining
1556
+ * @private
1557
+ */
1558
+ _optionEx(config, flags, description, fn, defaultValue) {
1559
+ if (typeof flags === "object" && flags instanceof Option2) {
1560
+ throw new Error(
1561
+ "To add an Option object use addOption() instead of option() or requiredOption()"
1562
+ );
1563
+ }
1564
+ const option = this.createOption(flags, description);
1565
+ option.makeOptionMandatory(!!config.mandatory);
1566
+ if (typeof fn === "function") {
1567
+ option.default(defaultValue).argParser(fn);
1568
+ } else if (fn instanceof RegExp) {
1569
+ const regex = fn;
1570
+ fn = (val, def) => {
1571
+ const m = regex.exec(val);
1572
+ return m ? m[0] : def;
1573
+ };
1574
+ option.default(defaultValue).argParser(fn);
1575
+ } else {
1576
+ option.default(fn);
1577
+ }
1578
+ return this.addOption(option);
1579
+ }
1580
+ /**
1581
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
1582
+ *
1583
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
1584
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
1585
+ *
1586
+ * See the README for more details, and see also addOption() and requiredOption().
1587
+ *
1588
+ * @example
1589
+ * program
1590
+ * .option('-p, --pepper', 'add pepper')
1591
+ * .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument
1592
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
1593
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
1594
+ *
1595
+ * @param {string} flags
1596
+ * @param {string} [description]
1597
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1598
+ * @param {*} [defaultValue]
1599
+ * @return {Command} `this` command for chaining
1600
+ */
1601
+ option(flags, description, parseArg, defaultValue) {
1602
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1603
+ }
1604
+ /**
1605
+ * Add a required option which must have a value after parsing. This usually means
1606
+ * the option must be specified on the command line. (Otherwise the same as .option().)
1607
+ *
1608
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1609
+ *
1610
+ * @param {string} flags
1611
+ * @param {string} [description]
1612
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1613
+ * @param {*} [defaultValue]
1614
+ * @return {Command} `this` command for chaining
1615
+ */
1616
+ requiredOption(flags, description, parseArg, defaultValue) {
1617
+ return this._optionEx(
1618
+ { mandatory: true },
1619
+ flags,
1620
+ description,
1621
+ parseArg,
1622
+ defaultValue
1623
+ );
1624
+ }
1625
+ /**
1626
+ * Alter parsing of short flags with optional values.
1627
+ *
1628
+ * @example
1629
+ * // for `.option('-f,--flag [value]'):
1630
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
1631
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
1632
+ *
1633
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
1634
+ * @return {Command} `this` command for chaining
1635
+ */
1636
+ combineFlagAndOptionalValue(combine = true) {
1637
+ this._combineFlagAndOptionalValue = !!combine;
1638
+ return this;
1639
+ }
1640
+ /**
1641
+ * Allow unknown options on the command line.
1642
+ *
1643
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
1644
+ * @return {Command} `this` command for chaining
1645
+ */
1646
+ allowUnknownOption(allowUnknown = true) {
1647
+ this._allowUnknownOption = !!allowUnknown;
1648
+ return this;
1649
+ }
1650
+ /**
1651
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1652
+ *
1653
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
1654
+ * @return {Command} `this` command for chaining
1655
+ */
1656
+ allowExcessArguments(allowExcess = true) {
1657
+ this._allowExcessArguments = !!allowExcess;
1658
+ return this;
1659
+ }
1660
+ /**
1661
+ * Enable positional options. Positional means global options are specified before subcommands which lets
1662
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1663
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
1664
+ *
1665
+ * @param {boolean} [positional]
1666
+ * @return {Command} `this` command for chaining
1667
+ */
1668
+ enablePositionalOptions(positional = true) {
1669
+ this._enablePositionalOptions = !!positional;
1670
+ return this;
1671
+ }
1672
+ /**
1673
+ * Pass through options that come after command-arguments rather than treat them as command-options,
1674
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
1675
+ * positional options to have been enabled on the program (parent commands).
1676
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
1677
+ *
1678
+ * @param {boolean} [passThrough] for unknown options.
1679
+ * @return {Command} `this` command for chaining
1680
+ */
1681
+ passThroughOptions(passThrough = true) {
1682
+ this._passThroughOptions = !!passThrough;
1683
+ this._checkForBrokenPassThrough();
1684
+ return this;
1685
+ }
1686
+ /**
1687
+ * @private
1688
+ */
1689
+ _checkForBrokenPassThrough() {
1690
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
1691
+ throw new Error(
1692
+ `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`
1693
+ );
1694
+ }
1695
+ }
1696
+ /**
1697
+ * Whether to store option values as properties on command object,
1698
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
1699
+ *
1700
+ * @param {boolean} [storeAsProperties=true]
1701
+ * @return {Command} `this` command for chaining
1702
+ */
1703
+ storeOptionsAsProperties(storeAsProperties = true) {
1704
+ if (this.options.length) {
1705
+ throw new Error("call .storeOptionsAsProperties() before adding options");
1706
+ }
1707
+ if (Object.keys(this._optionValues).length) {
1708
+ throw new Error(
1709
+ "call .storeOptionsAsProperties() before setting option values"
1710
+ );
1711
+ }
1712
+ this._storeOptionsAsProperties = !!storeAsProperties;
1713
+ return this;
1714
+ }
1715
+ /**
1716
+ * Retrieve option value.
1717
+ *
1718
+ * @param {string} key
1719
+ * @return {object} value
1720
+ */
1721
+ getOptionValue(key) {
1722
+ if (this._storeOptionsAsProperties) {
1723
+ return this[key];
1724
+ }
1725
+ return this._optionValues[key];
1726
+ }
1727
+ /**
1728
+ * Store option value.
1729
+ *
1730
+ * @param {string} key
1731
+ * @param {object} value
1732
+ * @return {Command} `this` command for chaining
1733
+ */
1734
+ setOptionValue(key, value) {
1735
+ return this.setOptionValueWithSource(key, value, void 0);
1736
+ }
1737
+ /**
1738
+ * Store option value and where the value came from.
1739
+ *
1740
+ * @param {string} key
1741
+ * @param {object} value
1742
+ * @param {string} source - expected values are default/config/env/cli/implied
1743
+ * @return {Command} `this` command for chaining
1744
+ */
1745
+ setOptionValueWithSource(key, value, source) {
1746
+ if (this._storeOptionsAsProperties) {
1747
+ this[key] = value;
1748
+ } else {
1749
+ this._optionValues[key] = value;
1750
+ }
1751
+ this._optionValueSources[key] = source;
1752
+ return this;
1753
+ }
1754
+ /**
1755
+ * Get source of option value.
1756
+ * Expected values are default | config | env | cli | implied
1757
+ *
1758
+ * @param {string} key
1759
+ * @return {string}
1760
+ */
1761
+ getOptionValueSource(key) {
1762
+ return this._optionValueSources[key];
1763
+ }
1764
+ /**
1765
+ * Get source of option value. See also .optsWithGlobals().
1766
+ * Expected values are default | config | env | cli | implied
1767
+ *
1768
+ * @param {string} key
1769
+ * @return {string}
1770
+ */
1771
+ getOptionValueSourceWithGlobals(key) {
1772
+ let source;
1773
+ this._getCommandAndAncestors().forEach((cmd) => {
1774
+ if (cmd.getOptionValueSource(key) !== void 0) {
1775
+ source = cmd.getOptionValueSource(key);
1776
+ }
1777
+ });
1778
+ return source;
1779
+ }
1780
+ /**
1781
+ * Get user arguments from implied or explicit arguments.
1782
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
1783
+ *
1784
+ * @private
1785
+ */
1786
+ _prepareUserArgs(argv, parseOptions) {
1787
+ if (argv !== void 0 && !Array.isArray(argv)) {
1788
+ throw new Error("first parameter to parse must be array or undefined");
1789
+ }
1790
+ parseOptions = parseOptions || {};
1791
+ if (argv === void 0 && parseOptions.from === void 0) {
1792
+ if (process.versions?.electron) {
1793
+ parseOptions.from = "electron";
1794
+ }
1795
+ const execArgv = process.execArgv ?? [];
1796
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
1797
+ parseOptions.from = "eval";
1798
+ }
1799
+ }
1800
+ if (argv === void 0) {
1801
+ argv = process.argv;
1802
+ }
1803
+ this.rawArgs = argv.slice();
1804
+ let userArgs;
1805
+ switch (parseOptions.from) {
1806
+ case void 0:
1807
+ case "node":
1808
+ this._scriptPath = argv[1];
1809
+ userArgs = argv.slice(2);
1810
+ break;
1811
+ case "electron":
1812
+ if (process.defaultApp) {
1813
+ this._scriptPath = argv[1];
1814
+ userArgs = argv.slice(2);
1815
+ } else {
1816
+ userArgs = argv.slice(1);
1817
+ }
1818
+ break;
1819
+ case "user":
1820
+ userArgs = argv.slice(0);
1821
+ break;
1822
+ case "eval":
1823
+ userArgs = argv.slice(1);
1824
+ break;
1825
+ default:
1826
+ throw new Error(
1827
+ `unexpected parse option { from: '${parseOptions.from}' }`
1828
+ );
1829
+ }
1830
+ if (!this._name && this._scriptPath)
1831
+ this.nameFromFilename(this._scriptPath);
1832
+ this._name = this._name || "program";
1833
+ return userArgs;
1834
+ }
1835
+ /**
1836
+ * Parse `argv`, setting options and invoking commands when defined.
1837
+ *
1838
+ * Use parseAsync instead of parse if any of your action handlers are async.
1839
+ *
1840
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1841
+ *
1842
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1843
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1844
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1845
+ * - `'user'`: just user arguments
1846
+ *
1847
+ * @example
1848
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
1849
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
1850
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1851
+ *
1852
+ * @param {string[]} [argv] - optional, defaults to process.argv
1853
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
1854
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
1855
+ * @return {Command} `this` command for chaining
1856
+ */
1857
+ parse(argv, parseOptions) {
1858
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1859
+ this._parseCommand([], userArgs);
1860
+ return this;
1861
+ }
1862
+ /**
1863
+ * Parse `argv`, setting options and invoking commands when defined.
1864
+ *
1865
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1866
+ *
1867
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1868
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1869
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1870
+ * - `'user'`: just user arguments
1871
+ *
1872
+ * @example
1873
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
1874
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
1875
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1876
+ *
1877
+ * @param {string[]} [argv]
1878
+ * @param {object} [parseOptions]
1879
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
1880
+ * @return {Promise}
1881
+ */
1882
+ async parseAsync(argv, parseOptions) {
1883
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1884
+ await this._parseCommand([], userArgs);
1885
+ return this;
1886
+ }
1887
+ /**
1888
+ * Execute a sub-command executable.
1889
+ *
1890
+ * @private
1891
+ */
1892
+ _executeSubCommand(subcommand, args) {
1893
+ args = args.slice();
1894
+ let launchWithNode = false;
1895
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
1896
+ function findFile(baseDir, baseName) {
1897
+ const localBin = path.resolve(baseDir, baseName);
1898
+ if (fs.existsSync(localBin)) return localBin;
1899
+ if (sourceExt.includes(path.extname(baseName))) return void 0;
1900
+ const foundExt = sourceExt.find(
1901
+ (ext) => fs.existsSync(`${localBin}${ext}`)
1902
+ );
1903
+ if (foundExt) return `${localBin}${foundExt}`;
1904
+ return void 0;
1905
+ }
1906
+ this._checkForMissingMandatoryOptions();
1907
+ this._checkForConflictingOptions();
1908
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1909
+ let executableDir = this._executableDir || "";
1910
+ if (this._scriptPath) {
1911
+ let resolvedScriptPath;
1912
+ try {
1913
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
1914
+ } catch (err) {
1915
+ resolvedScriptPath = this._scriptPath;
1916
+ }
1917
+ executableDir = path.resolve(
1918
+ path.dirname(resolvedScriptPath),
1919
+ executableDir
1920
+ );
1921
+ }
1922
+ if (executableDir) {
1923
+ let localFile = findFile(executableDir, executableFile);
1924
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1925
+ const legacyName = path.basename(
1926
+ this._scriptPath,
1927
+ path.extname(this._scriptPath)
1928
+ );
1929
+ if (legacyName !== this._name) {
1930
+ localFile = findFile(
1931
+ executableDir,
1932
+ `${legacyName}-${subcommand._name}`
1933
+ );
1934
+ }
1935
+ }
1936
+ executableFile = localFile || executableFile;
1937
+ }
1938
+ launchWithNode = sourceExt.includes(path.extname(executableFile));
1939
+ let proc;
1940
+ if (process.platform !== "win32") {
1941
+ if (launchWithNode) {
1942
+ args.unshift(executableFile);
1943
+ args = incrementNodeInspectorPort(process.execArgv).concat(args);
1944
+ proc = childProcess.spawn(process.argv[0], args, { stdio: "inherit" });
1945
+ } else {
1946
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1947
+ }
1948
+ } else {
1949
+ args.unshift(executableFile);
1950
+ args = incrementNodeInspectorPort(process.execArgv).concat(args);
1951
+ proc = childProcess.spawn(process.execPath, args, { stdio: "inherit" });
1952
+ }
1953
+ if (!proc.killed) {
1954
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
1955
+ signals.forEach((signal) => {
1956
+ process.on(signal, () => {
1957
+ if (proc.killed === false && proc.exitCode === null) {
1958
+ proc.kill(signal);
1959
+ }
1960
+ });
1961
+ });
1962
+ }
1963
+ const exitCallback = this._exitCallback;
1964
+ proc.on("close", (code) => {
1965
+ code = code ?? 1;
1966
+ if (!exitCallback) {
1967
+ process.exit(code);
1968
+ } else {
1969
+ exitCallback(
1970
+ new CommanderError2(
1971
+ code,
1972
+ "commander.executeSubCommandAsync",
1973
+ "(close)"
1974
+ )
1975
+ );
1976
+ }
1977
+ });
1978
+ proc.on("error", (err) => {
1979
+ if (err.code === "ENOENT") {
1980
+ const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory";
1981
+ const executableMissing = `'${executableFile}' does not exist
1982
+ - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
17
1983
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
18
- - ${c}`;throw new Error(C)}else if(h.code==="EACCES")throw new Error(`'${s}' not executable`);if(!l)d.exit(1);else{let c=new Y(1,"commander.executeSubCommandAsync","(error)");c.nestedError=h,l(c)}}),this.runningCommand=a}_dispatchSubcommand(e,t,i){let n=this._findCommand(e);n||this.help({error:!0});let r;return r=this._chainOrCallSubCommandHook(r,n,"preSubcommand"),r=this._chainOrCall(r,()=>{if(n._executableHandler)this._executeSubCommand(n,t.concat(i));else return n._parseCommand(t,i)}),r}_dispatchHelpCommand(e){e||this.help();let 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(){let e=(i,n,r)=>{let s=n;if(n!==null&&i.parseArg){let u=`error: command-argument value '${n}' is invalid for argument '${i.name()}'.`;s=this._callParseArg(i,n,r,u)}return s};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((i,n)=>{let r=i.defaultValue;i.variadic?n<this.args.length?(r=this.args.slice(n),i.parseArg&&(r=r.reduce((s,u)=>e(i,u,s),i.defaultValue))):r===void 0&&(r=[]):n<this.args.length&&(r=this.args[n],i.parseArg&&(r=e(i,r,i.defaultValue))),t[n]=r}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let i=e,n=[];return this._getCommandAndAncestors().reverse().filter(r=>r._lifeCycleHooks[t]!==void 0).forEach(r=>{r._lifeCycleHooks[t].forEach(s=>{n.push({hookedCommand:r,callback:s})})}),t==="postAction"&&n.reverse(),n.forEach(r=>{i=this._chainOrCall(i,()=>r.callback(r.hookedCommand,this))}),i}_chainOrCallSubCommandHook(e,t,i){let n=e;return this._lifeCycleHooks[i]!==void 0&&this._lifeCycleHooks[i].forEach(r=>{n=this._chainOrCall(n,()=>r(this,t))}),n}_parseCommand(e,t){let i=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(i.operands),t=i.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(i.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let n=()=>{i.unknown.length>0&&this.unknownOption(i.unknown[0])},r=`command:${this.name()}`;if(this._actionHandler){n(),this._processArguments();let s;return s=this._chainOrCallHooks(s,"preAction"),s=this._chainOrCall(s,()=>this._actionHandler(this.processedArgs)),this.parent&&(s=this._chainOrCall(s,()=>{this.parent.emit(r,e,t)})),s=this._chainOrCallHooks(s,"postAction"),s}if(this.parent&&this.parent.listenerCount(r))n(),this._processArguments(),this.parent.emit(r,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():(n(),this._processArguments())}else this.commands.length?(n(),this.help({error:!0})):(n(),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(){let e=this.options.filter(i=>{let n=i.attributeName();return this.getOptionValue(n)===void 0?!1:this.getOptionValueSource(n)!=="default"});e.filter(i=>i.conflictsWith.length>0).forEach(i=>{let n=e.find(r=>i.conflictsWith.includes(r.attributeName()));n&&this._conflictingOption(i,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],i=[],n=t,r=e.slice();function s(a){return a.length>1&&a[0]==="-"}let u=null;for(;r.length;){let a=r.shift();if(a==="--"){n===i&&n.push(a),n.push(...r);break}if(u&&!s(a)){this.emit(`option:${u.name()}`,a);continue}if(u=null,s(a)){let l=this._findOption(a);if(l){if(l.required){let h=r.shift();h===void 0&&this.optionMissingArgument(l),this.emit(`option:${l.name()}`,h)}else if(l.optional){let h=null;r.length>0&&!s(r[0])&&(h=r.shift()),this.emit(`option:${l.name()}`,h)}else this.emit(`option:${l.name()}`);u=l.variadic?l:null;continue}}if(a.length>2&&a[0]==="-"&&a[1]!=="-"){let l=this._findOption(`-${a[1]}`);if(l){l.required||l.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${l.name()}`,a.slice(2)):(this.emit(`option:${l.name()}`),r.unshift(`-${a.slice(2)}`));continue}}if(/^--[^=]+=/.test(a)){let l=a.indexOf("="),h=this._findOption(a.slice(0,l));if(h&&(h.required||h.optional)){this.emit(`option:${h.name()}`,a.slice(l+1));continue}}if(s(a)&&(n=i),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&i.length===0){if(this._findCommand(a)){t.push(a),r.length>0&&i.push(...r);break}else if(this._getHelpCommand()&&a===this._getHelpCommand().name()){t.push(a),r.length>0&&t.push(...r);break}else if(this._defaultCommandName){i.push(a),r.length>0&&i.push(...r);break}}if(this._passThroughOptions){n.push(a),r.length>0&&n.push(...r);break}n.push(a)}return{operands:t,unknown:i}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let i=0;i<t;i++){let n=this.options[i].attributeName();e[n]=n===this._versionOptionName?this._version:this[n]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
19
- `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
20
- `):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
21
- `),this.outputHelp({error:!0}));let i=t||{},n=i.exitCode||1,r=i.code||"commander.error";this._exit(n,r,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in d.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,d.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Ue(this.options),t=i=>this.getOptionValue(i)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(i));this.options.filter(i=>i.implied!==void 0&&t(i.attributeName())&&e.valueFromOption(this.getOptionValue(i.attributeName()),i)).forEach(i=>{Object.keys(i.implied).filter(n=>!t(n)).forEach(n=>{this.setOptionValueWithSource(n,i.implied[n],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let i=s=>{let u=s.attributeName(),a=this.getOptionValue(u),l=this.options.find(c=>c.negate&&u===c.attributeName()),h=this.options.find(c=>!c.negate&&u===c.attributeName());return l&&(l.presetArg===void 0&&a===!1||l.presetArg!==void 0&&a===l.presetArg)?l:h||s},n=s=>{let u=i(s),a=u.attributeName();return this.getOptionValueSource(a)==="env"?`environment variable '${u.envVar}'`:`option '${u.flags}'`},r=`error: ${n(e)} cannot be used with ${n(t)}`;this.error(r,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let n=[],r=this;do{let s=r.createHelp().visibleOptions(r).filter(u=>u.long).map(u=>u.long);n=n.concat(s),r=r.parent}while(r&&!r._enablePositionalOptions);t=re(e,n)}let i=`error: unknown option '${e}'${t}`;this.error(i,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,i=t===1?"":"s",r=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${i} but got ${e.length}.`;this.error(r,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(r=>{n.push(r.name()),r.alias()&&n.push(r.alias())}),t=re(e,n)}let i=`error: unknown command '${e}'${t}`;this.error(i,{code:"commander.unknownCommand"})}version(e,t,i){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",i=i||"output the version number";let n=this.createOption(t,i);return this._versionOptionName=n.attributeName(),this._registerOption(n),this.on("option:"+n.name(),()=>{this._outputConfiguration.writeOut(`${e}
22
- `),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let i=this.parent?._findCommand(e);if(i){let n=[i.name()].concat(i.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${n}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(i=>Me(i));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=v.basename(e,v.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp();return t.helpWidth===void 0&&(t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),t.formatHelp(this,t)}_getHelpContext(e){e=e||{};let t={error:!!e.error},i;return t.error?i=n=>this._outputConfiguration.writeErr(n):i=n=>this._outputConfiguration.writeOut(n),t.write=e.write||i,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let i=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(r=>r.emit("beforeAllHelp",i)),this.emit("beforeHelp",i);let n=this.helpInformation(i);if(t&&(n=t(n),typeof n!="string"&&!Buffer.isBuffer(n)))throw new Error("outputHelp callback must return a string or a Buffer");i.write(n),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",i),this._getCommandAndAncestors().forEach(r=>r.emit("afterAllHelp",i))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=d.exitCode||0;t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let i=["beforeAll","before","after","afterAll"];if(!i.includes(e))throw new Error(`Unexpected value for position to addHelpText.
23
- Expecting one of '${i.join("', '")}'`);let n=`${e}Help`;return this.on(n,r=>{let s;typeof t=="function"?s=t({error:r.error,command:r.command}):s=t,s&&r.write(`${s}
24
- `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(n=>t.is(n))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function se(o){return o.map(e=>{if(!e.startsWith("--inspect"))return e;let t,i="127.0.0.1",n="9229",r;return(r=e.match(/^(--inspect(-brk)?)$/))!==null?t=r[1]:(r=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=r[1],/^\d+$/.test(r[3])?n=r[3]:i=r[3]):(r=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=r[1],i=r[3],n=r[4]),t&&n!=="0"?`${t}=${i}:${parseInt(n)+1}`:e})}oe.Command=Q});var me=E(w=>{"use strict";m();var{Argument:ue}=T(),{Command:X}=ae(),{CommanderError:Re,InvalidArgumentError:le}=k(),{Help:Ge}=R(),{Option:he}=J();w.program=new X;w.createCommand=o=>new X(o);w.createOption=(o,e)=>new he(o,e);w.createArgument=(o,e)=>new ue(o,e);w.Command=X;w.Option=he;w.Argument=ue;w.Help=Ge;w.CommanderError=Re;w.InvalidArgumentError=le;w.InvalidOptionArgumentError=le});var de=E((O,ce)=>{"use strict";m();var b=me();O=ce.exports={};O.program=new b.Command;O.Argument=b.Argument;O.Command=b.Command;O.CommanderError=b.CommanderError;O.Help=b.Help;O.InvalidArgumentError=b.InvalidArgumentError;O.InvalidOptionArgumentError=b.InvalidArgumentError;O.Option=b.Option;O.createCommand=o=>new b.Command(o);O.createOption=(o,e)=>new b.Option(o,e);O.createArgument=(o,e)=>new b.Argument(o,e)});m();m();m();var pe=$(de(),1),{program:at,createCommand:_,createArgument:ut,createOption:lt,CommanderError:ht,InvalidArgumentError:I,InvalidOptionArgumentError:mt,Command:ct,Argument:dt,Option:fe,Help:pt}=pe.default;m();var ge=o=>_("build").action(async(e,t)=>{let{runCommand:i}=await import("./render-command-QEQ3L7OX.js"),{build:n}=await import("./build-3RXHADZD.js");await i(t,o,n)});m();var _e=$(V(),1);var Ce=o=>{let e=A();return _("dev").option("-s, --https",e("dev_command_def.option.https")).action(async(t,i)=>{let{DevCommand:n}=await import("./DevCommand-Q5XLAGMG.js"),{renderCommand:r}=await import("./render-command-QEQ3L7OX.js"),{https:s=!1}=t;await r(i,o,_e.default.createElement(n,{https:s}),{watchForModelChanges:!0})})};m();var we=$(V(),1);m();function F(o){let e=S.union([S.string().uuid(),S.literal("current")]).transform(t=>t==="current"?void 0:t).safeParse(o);if(e.success)return e.data;throw new I('Value must be a valid GUID or "current"')}function q(o){let e=S.string().url().safeParse(o);if(e.success)return e.data;throw new I("Value must be a valid URL")}function Oe(o){let e=S.string().regex(/^(0|[1-9]\d*)\.(0|[1-9]\d*)(\.(0|[1-9]\d*))?$/).safeParse(o);if(e.success)return e.data;throw new I("Version value should be in semver format `x.x.x`")}var be=o=>{let e=A();return _("preview").option("-s, --site <site-id>",e("app_preview_command_def.option.site"),F).option("--base-url <url>",e("app_preview_command_def.option.base_url"),q).option("--no-input",e("app_preview_command_def.option.no_input")).action(async(t,i)=>{let{site:n,baseUrl:r,input:s}=t,{renderCommand:u,runCommand:a}=await import("./render-command-QEQ3L7OX.js");if(!s)return a(i,o,async h=>{let{nonInteractivePreview:c}=await import("./preview-TM7JAWFS.js");return c({siteId:n,baseUrl:r},h,o)});let{PreviewCommand:l}=await import("./PreviewCommand-JKPFMGWV.js");await u(i,o,we.default.createElement(l,{baseUrl:r,siteIdOverride:n}))})};m();var Ae=$(V(),1);var ve=o=>{let e=A();return _("create-version").addOption(new fe("-t, --version-type <type>",e("create_version_command_def.option.version_type")).choices(["major","minor"])).option("-s, --site <site-id>",e("create_version_command_def.option.site"),F).option("-y, --approve-preview",e("create_version_command_def.option.approve_preview")).option("--base-url <url>",e("create_version_command_def.option.base_url"),q).action(async(t,i)=>{let{VersionType:n}=await import("./types.impl-L2DPGJ77.js"),{renderCommand:r}=await import("./render-command-QEQ3L7OX.js"),{CreateVersionCommand:s}=await import("./CreateVersionCommand-XTZT5DED.js"),{approvePreview:u=!1,versionType:a,baseUrl:l,site:h}=t,c={major:n.MAJOR,minor:n.MINOR},C=a?c[a]:void 0;await r(i,o,Ae.default.createElement(s,{baseUrl:l,siteIdOverride:h,preApprovePreview:u,versionType:C}))})};m();var xe=$(V(),1);var Ee=o=>_("serve").action(async(e,t)=>{let{renderCommand:i}=await import("./render-command-QEQ3L7OX.js"),{ServeCommand:n}=await import("./ServeCommand-CPZOI7DC.js");await i(t,o,xe.default.createElement(n,null))});m();var ye=$(V(),1);var $e=o=>{let e=A();return _("generate").description(e("generate_command.description")).action(async(t,i)=>{let{GenerateCommand:n}=await import("./GenerateCommand-HNFICZJA.js"),{renderCommand:r}=await import("./render-command-QEQ3L7OX.js");await r(i,o,ye.default.createElement(n,null),{skipProjectValidation:!0})})};m();var Ve=$(V(),1);var Se=o=>{let e=A();return _("logs").requiredOption("--version <version>",e("logs_command_def.option.version"),Oe).action(async(t,i)=>{let{version:n}=t,{renderCommand:r}=await import("./render-command-QEQ3L7OX.js"),{LogsCommand:s}=await import("./LogsCommand-XJHE75L2.js");await r(i,o,Ve.default.createElement(s,{version:n}))})};var Le=async o=>_("app").version(Z,"-v, --version","Output the version number").enablePositionalOptions(!0).helpOption("-h, --help","Display help for command").helpCommand(!1).addCommand(Ce(o)).addCommand(ge(o)).addCommand(Ee(o)).addCommand(be(o)).addCommand(ve(o)).addCommand($e(o)).addCommand(Se(o));export{Le as getRootCommand};
1984
+ - ${executableDirMessage}`;
1985
+ throw new Error(executableMissing);
1986
+ } else if (err.code === "EACCES") {
1987
+ throw new Error(`'${executableFile}' not executable`);
1988
+ }
1989
+ if (!exitCallback) {
1990
+ process.exit(1);
1991
+ } else {
1992
+ const wrappedError = new CommanderError2(
1993
+ 1,
1994
+ "commander.executeSubCommandAsync",
1995
+ "(error)"
1996
+ );
1997
+ wrappedError.nestedError = err;
1998
+ exitCallback(wrappedError);
1999
+ }
2000
+ });
2001
+ this.runningCommand = proc;
2002
+ }
2003
+ /**
2004
+ * @private
2005
+ */
2006
+ _dispatchSubcommand(commandName, operands, unknown) {
2007
+ const subCommand = this._findCommand(commandName);
2008
+ if (!subCommand) this.help({ error: true });
2009
+ let promiseChain;
2010
+ promiseChain = this._chainOrCallSubCommandHook(
2011
+ promiseChain,
2012
+ subCommand,
2013
+ "preSubcommand"
2014
+ );
2015
+ promiseChain = this._chainOrCall(promiseChain, () => {
2016
+ if (subCommand._executableHandler) {
2017
+ this._executeSubCommand(subCommand, operands.concat(unknown));
2018
+ } else {
2019
+ return subCommand._parseCommand(operands, unknown);
2020
+ }
2021
+ });
2022
+ return promiseChain;
2023
+ }
2024
+ /**
2025
+ * Invoke help directly if possible, or dispatch if necessary.
2026
+ * e.g. help foo
2027
+ *
2028
+ * @private
2029
+ */
2030
+ _dispatchHelpCommand(subcommandName) {
2031
+ if (!subcommandName) {
2032
+ this.help();
2033
+ }
2034
+ const subCommand = this._findCommand(subcommandName);
2035
+ if (subCommand && !subCommand._executableHandler) {
2036
+ subCommand.help();
2037
+ }
2038
+ return this._dispatchSubcommand(
2039
+ subcommandName,
2040
+ [],
2041
+ [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]
2042
+ );
2043
+ }
2044
+ /**
2045
+ * Check this.args against expected this.registeredArguments.
2046
+ *
2047
+ * @private
2048
+ */
2049
+ _checkNumberOfArguments() {
2050
+ this.registeredArguments.forEach((arg, i) => {
2051
+ if (arg.required && this.args[i] == null) {
2052
+ this.missingArgument(arg.name());
2053
+ }
2054
+ });
2055
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
2056
+ return;
2057
+ }
2058
+ if (this.args.length > this.registeredArguments.length) {
2059
+ this._excessArguments(this.args);
2060
+ }
2061
+ }
2062
+ /**
2063
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
2064
+ *
2065
+ * @private
2066
+ */
2067
+ _processArguments() {
2068
+ const myParseArg = (argument, value, previous) => {
2069
+ let parsedValue = value;
2070
+ if (value !== null && argument.parseArg) {
2071
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
2072
+ parsedValue = this._callParseArg(
2073
+ argument,
2074
+ value,
2075
+ previous,
2076
+ invalidValueMessage
2077
+ );
2078
+ }
2079
+ return parsedValue;
2080
+ };
2081
+ this._checkNumberOfArguments();
2082
+ const processedArgs = [];
2083
+ this.registeredArguments.forEach((declaredArg, index) => {
2084
+ let value = declaredArg.defaultValue;
2085
+ if (declaredArg.variadic) {
2086
+ if (index < this.args.length) {
2087
+ value = this.args.slice(index);
2088
+ if (declaredArg.parseArg) {
2089
+ value = value.reduce((processed, v) => {
2090
+ return myParseArg(declaredArg, v, processed);
2091
+ }, declaredArg.defaultValue);
2092
+ }
2093
+ } else if (value === void 0) {
2094
+ value = [];
2095
+ }
2096
+ } else if (index < this.args.length) {
2097
+ value = this.args[index];
2098
+ if (declaredArg.parseArg) {
2099
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
2100
+ }
2101
+ }
2102
+ processedArgs[index] = value;
2103
+ });
2104
+ this.processedArgs = processedArgs;
2105
+ }
2106
+ /**
2107
+ * Once we have a promise we chain, but call synchronously until then.
2108
+ *
2109
+ * @param {(Promise|undefined)} promise
2110
+ * @param {Function} fn
2111
+ * @return {(Promise|undefined)}
2112
+ * @private
2113
+ */
2114
+ _chainOrCall(promise, fn) {
2115
+ if (promise && promise.then && typeof promise.then === "function") {
2116
+ return promise.then(() => fn());
2117
+ }
2118
+ return fn();
2119
+ }
2120
+ /**
2121
+ *
2122
+ * @param {(Promise|undefined)} promise
2123
+ * @param {string} event
2124
+ * @return {(Promise|undefined)}
2125
+ * @private
2126
+ */
2127
+ _chainOrCallHooks(promise, event) {
2128
+ let result = promise;
2129
+ const hooks = [];
2130
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
2131
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
2132
+ hooks.push({ hookedCommand, callback });
2133
+ });
2134
+ });
2135
+ if (event === "postAction") {
2136
+ hooks.reverse();
2137
+ }
2138
+ hooks.forEach((hookDetail) => {
2139
+ result = this._chainOrCall(result, () => {
2140
+ return hookDetail.callback(hookDetail.hookedCommand, this);
2141
+ });
2142
+ });
2143
+ return result;
2144
+ }
2145
+ /**
2146
+ *
2147
+ * @param {(Promise|undefined)} promise
2148
+ * @param {Command} subCommand
2149
+ * @param {string} event
2150
+ * @return {(Promise|undefined)}
2151
+ * @private
2152
+ */
2153
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
2154
+ let result = promise;
2155
+ if (this._lifeCycleHooks[event] !== void 0) {
2156
+ this._lifeCycleHooks[event].forEach((hook) => {
2157
+ result = this._chainOrCall(result, () => {
2158
+ return hook(this, subCommand);
2159
+ });
2160
+ });
2161
+ }
2162
+ return result;
2163
+ }
2164
+ /**
2165
+ * Process arguments in context of this command.
2166
+ * Returns action result, in case it is a promise.
2167
+ *
2168
+ * @private
2169
+ */
2170
+ _parseCommand(operands, unknown) {
2171
+ const parsed = this.parseOptions(unknown);
2172
+ this._parseOptionsEnv();
2173
+ this._parseOptionsImplied();
2174
+ operands = operands.concat(parsed.operands);
2175
+ unknown = parsed.unknown;
2176
+ this.args = operands.concat(unknown);
2177
+ if (operands && this._findCommand(operands[0])) {
2178
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2179
+ }
2180
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
2181
+ return this._dispatchHelpCommand(operands[1]);
2182
+ }
2183
+ if (this._defaultCommandName) {
2184
+ this._outputHelpIfRequested(unknown);
2185
+ return this._dispatchSubcommand(
2186
+ this._defaultCommandName,
2187
+ operands,
2188
+ unknown
2189
+ );
2190
+ }
2191
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
2192
+ this.help({ error: true });
2193
+ }
2194
+ this._outputHelpIfRequested(parsed.unknown);
2195
+ this._checkForMissingMandatoryOptions();
2196
+ this._checkForConflictingOptions();
2197
+ const checkForUnknownOptions = () => {
2198
+ if (parsed.unknown.length > 0) {
2199
+ this.unknownOption(parsed.unknown[0]);
2200
+ }
2201
+ };
2202
+ const commandEvent = `command:${this.name()}`;
2203
+ if (this._actionHandler) {
2204
+ checkForUnknownOptions();
2205
+ this._processArguments();
2206
+ let promiseChain;
2207
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
2208
+ promiseChain = this._chainOrCall(
2209
+ promiseChain,
2210
+ () => this._actionHandler(this.processedArgs)
2211
+ );
2212
+ if (this.parent) {
2213
+ promiseChain = this._chainOrCall(promiseChain, () => {
2214
+ this.parent.emit(commandEvent, operands, unknown);
2215
+ });
2216
+ }
2217
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
2218
+ return promiseChain;
2219
+ }
2220
+ if (this.parent && this.parent.listenerCount(commandEvent)) {
2221
+ checkForUnknownOptions();
2222
+ this._processArguments();
2223
+ this.parent.emit(commandEvent, operands, unknown);
2224
+ } else if (operands.length) {
2225
+ if (this._findCommand("*")) {
2226
+ return this._dispatchSubcommand("*", operands, unknown);
2227
+ }
2228
+ if (this.listenerCount("command:*")) {
2229
+ this.emit("command:*", operands, unknown);
2230
+ } else if (this.commands.length) {
2231
+ this.unknownCommand();
2232
+ } else {
2233
+ checkForUnknownOptions();
2234
+ this._processArguments();
2235
+ }
2236
+ } else if (this.commands.length) {
2237
+ checkForUnknownOptions();
2238
+ this.help({ error: true });
2239
+ } else {
2240
+ checkForUnknownOptions();
2241
+ this._processArguments();
2242
+ }
2243
+ }
2244
+ /**
2245
+ * Find matching command.
2246
+ *
2247
+ * @private
2248
+ * @return {Command | undefined}
2249
+ */
2250
+ _findCommand(name) {
2251
+ if (!name) return void 0;
2252
+ return this.commands.find(
2253
+ (cmd) => cmd._name === name || cmd._aliases.includes(name)
2254
+ );
2255
+ }
2256
+ /**
2257
+ * Return an option matching `arg` if any.
2258
+ *
2259
+ * @param {string} arg
2260
+ * @return {Option}
2261
+ * @package
2262
+ */
2263
+ _findOption(arg) {
2264
+ return this.options.find((option) => option.is(arg));
2265
+ }
2266
+ /**
2267
+ * Display an error message if a mandatory option does not have a value.
2268
+ * Called after checking for help flags in leaf subcommand.
2269
+ *
2270
+ * @private
2271
+ */
2272
+ _checkForMissingMandatoryOptions() {
2273
+ this._getCommandAndAncestors().forEach((cmd) => {
2274
+ cmd.options.forEach((anOption) => {
2275
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
2276
+ cmd.missingMandatoryOptionValue(anOption);
2277
+ }
2278
+ });
2279
+ });
2280
+ }
2281
+ /**
2282
+ * Display an error message if conflicting options are used together in this.
2283
+ *
2284
+ * @private
2285
+ */
2286
+ _checkForConflictingLocalOptions() {
2287
+ const definedNonDefaultOptions = this.options.filter((option) => {
2288
+ const optionKey = option.attributeName();
2289
+ if (this.getOptionValue(optionKey) === void 0) {
2290
+ return false;
2291
+ }
2292
+ return this.getOptionValueSource(optionKey) !== "default";
2293
+ });
2294
+ const optionsWithConflicting = definedNonDefaultOptions.filter(
2295
+ (option) => option.conflictsWith.length > 0
2296
+ );
2297
+ optionsWithConflicting.forEach((option) => {
2298
+ const conflictingAndDefined = definedNonDefaultOptions.find(
2299
+ (defined) => option.conflictsWith.includes(defined.attributeName())
2300
+ );
2301
+ if (conflictingAndDefined) {
2302
+ this._conflictingOption(option, conflictingAndDefined);
2303
+ }
2304
+ });
2305
+ }
2306
+ /**
2307
+ * Display an error message if conflicting options are used together.
2308
+ * Called after checking for help flags in leaf subcommand.
2309
+ *
2310
+ * @private
2311
+ */
2312
+ _checkForConflictingOptions() {
2313
+ this._getCommandAndAncestors().forEach((cmd) => {
2314
+ cmd._checkForConflictingLocalOptions();
2315
+ });
2316
+ }
2317
+ /**
2318
+ * Parse options from `argv` removing known options,
2319
+ * and return argv split into operands and unknown arguments.
2320
+ *
2321
+ * Examples:
2322
+ *
2323
+ * argv => operands, unknown
2324
+ * --known kkk op => [op], []
2325
+ * op --known kkk => [op], []
2326
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
2327
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
2328
+ *
2329
+ * @param {string[]} argv
2330
+ * @return {{operands: string[], unknown: string[]}}
2331
+ */
2332
+ parseOptions(argv) {
2333
+ const operands = [];
2334
+ const unknown = [];
2335
+ let dest = operands;
2336
+ const args = argv.slice();
2337
+ function maybeOption(arg) {
2338
+ return arg.length > 1 && arg[0] === "-";
2339
+ }
2340
+ let activeVariadicOption = null;
2341
+ while (args.length) {
2342
+ const arg = args.shift();
2343
+ if (arg === "--") {
2344
+ if (dest === unknown) dest.push(arg);
2345
+ dest.push(...args);
2346
+ break;
2347
+ }
2348
+ if (activeVariadicOption && !maybeOption(arg)) {
2349
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
2350
+ continue;
2351
+ }
2352
+ activeVariadicOption = null;
2353
+ if (maybeOption(arg)) {
2354
+ const option = this._findOption(arg);
2355
+ if (option) {
2356
+ if (option.required) {
2357
+ const value = args.shift();
2358
+ if (value === void 0) this.optionMissingArgument(option);
2359
+ this.emit(`option:${option.name()}`, value);
2360
+ } else if (option.optional) {
2361
+ let value = null;
2362
+ if (args.length > 0 && !maybeOption(args[0])) {
2363
+ value = args.shift();
2364
+ }
2365
+ this.emit(`option:${option.name()}`, value);
2366
+ } else {
2367
+ this.emit(`option:${option.name()}`);
2368
+ }
2369
+ activeVariadicOption = option.variadic ? option : null;
2370
+ continue;
2371
+ }
2372
+ }
2373
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
2374
+ const option = this._findOption(`-${arg[1]}`);
2375
+ if (option) {
2376
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
2377
+ this.emit(`option:${option.name()}`, arg.slice(2));
2378
+ } else {
2379
+ this.emit(`option:${option.name()}`);
2380
+ args.unshift(`-${arg.slice(2)}`);
2381
+ }
2382
+ continue;
2383
+ }
2384
+ }
2385
+ if (/^--[^=]+=/.test(arg)) {
2386
+ const index = arg.indexOf("=");
2387
+ const option = this._findOption(arg.slice(0, index));
2388
+ if (option && (option.required || option.optional)) {
2389
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
2390
+ continue;
2391
+ }
2392
+ }
2393
+ if (maybeOption(arg)) {
2394
+ dest = unknown;
2395
+ }
2396
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
2397
+ if (this._findCommand(arg)) {
2398
+ operands.push(arg);
2399
+ if (args.length > 0) unknown.push(...args);
2400
+ break;
2401
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
2402
+ operands.push(arg);
2403
+ if (args.length > 0) operands.push(...args);
2404
+ break;
2405
+ } else if (this._defaultCommandName) {
2406
+ unknown.push(arg);
2407
+ if (args.length > 0) unknown.push(...args);
2408
+ break;
2409
+ }
2410
+ }
2411
+ if (this._passThroughOptions) {
2412
+ dest.push(arg);
2413
+ if (args.length > 0) dest.push(...args);
2414
+ break;
2415
+ }
2416
+ dest.push(arg);
2417
+ }
2418
+ return { operands, unknown };
2419
+ }
2420
+ /**
2421
+ * Return an object containing local option values as key-value pairs.
2422
+ *
2423
+ * @return {object}
2424
+ */
2425
+ opts() {
2426
+ if (this._storeOptionsAsProperties) {
2427
+ const result = {};
2428
+ const len = this.options.length;
2429
+ for (let i = 0; i < len; i++) {
2430
+ const key = this.options[i].attributeName();
2431
+ result[key] = key === this._versionOptionName ? this._version : this[key];
2432
+ }
2433
+ return result;
2434
+ }
2435
+ return this._optionValues;
2436
+ }
2437
+ /**
2438
+ * Return an object containing merged local and global option values as key-value pairs.
2439
+ *
2440
+ * @return {object}
2441
+ */
2442
+ optsWithGlobals() {
2443
+ return this._getCommandAndAncestors().reduce(
2444
+ (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
2445
+ {}
2446
+ );
2447
+ }
2448
+ /**
2449
+ * Display error message and exit (or call exitOverride).
2450
+ *
2451
+ * @param {string} message
2452
+ * @param {object} [errorOptions]
2453
+ * @param {string} [errorOptions.code] - an id string representing the error
2454
+ * @param {number} [errorOptions.exitCode] - used with process.exit
2455
+ */
2456
+ error(message, errorOptions) {
2457
+ this._outputConfiguration.outputError(
2458
+ `${message}
2459
+ `,
2460
+ this._outputConfiguration.writeErr
2461
+ );
2462
+ if (typeof this._showHelpAfterError === "string") {
2463
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
2464
+ `);
2465
+ } else if (this._showHelpAfterError) {
2466
+ this._outputConfiguration.writeErr("\n");
2467
+ this.outputHelp({ error: true });
2468
+ }
2469
+ const config = errorOptions || {};
2470
+ const exitCode = config.exitCode || 1;
2471
+ const code = config.code || "commander.error";
2472
+ this._exit(exitCode, code, message);
2473
+ }
2474
+ /**
2475
+ * Apply any option related environment variables, if option does
2476
+ * not have a value from cli or client code.
2477
+ *
2478
+ * @private
2479
+ */
2480
+ _parseOptionsEnv() {
2481
+ this.options.forEach((option) => {
2482
+ if (option.envVar && option.envVar in process.env) {
2483
+ const optionKey = option.attributeName();
2484
+ if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(
2485
+ this.getOptionValueSource(optionKey)
2486
+ )) {
2487
+ if (option.required || option.optional) {
2488
+ this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);
2489
+ } else {
2490
+ this.emit(`optionEnv:${option.name()}`);
2491
+ }
2492
+ }
2493
+ }
2494
+ });
2495
+ }
2496
+ /**
2497
+ * Apply any implied option values, if option is undefined or default value.
2498
+ *
2499
+ * @private
2500
+ */
2501
+ _parseOptionsImplied() {
2502
+ const dualHelper = new DualOptions(this.options);
2503
+ const hasCustomOptionValue = (optionKey) => {
2504
+ return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
2505
+ };
2506
+ this.options.filter(
2507
+ (option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(
2508
+ this.getOptionValue(option.attributeName()),
2509
+ option
2510
+ )
2511
+ ).forEach((option) => {
2512
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
2513
+ this.setOptionValueWithSource(
2514
+ impliedKey,
2515
+ option.implied[impliedKey],
2516
+ "implied"
2517
+ );
2518
+ });
2519
+ });
2520
+ }
2521
+ /**
2522
+ * Argument `name` is missing.
2523
+ *
2524
+ * @param {string} name
2525
+ * @private
2526
+ */
2527
+ missingArgument(name) {
2528
+ const message = `error: missing required argument '${name}'`;
2529
+ this.error(message, { code: "commander.missingArgument" });
2530
+ }
2531
+ /**
2532
+ * `Option` is missing an argument.
2533
+ *
2534
+ * @param {Option} option
2535
+ * @private
2536
+ */
2537
+ optionMissingArgument(option) {
2538
+ const message = `error: option '${option.flags}' argument missing`;
2539
+ this.error(message, { code: "commander.optionMissingArgument" });
2540
+ }
2541
+ /**
2542
+ * `Option` does not have a value, and is a mandatory option.
2543
+ *
2544
+ * @param {Option} option
2545
+ * @private
2546
+ */
2547
+ missingMandatoryOptionValue(option) {
2548
+ const message = `error: required option '${option.flags}' not specified`;
2549
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
2550
+ }
2551
+ /**
2552
+ * `Option` conflicts with another option.
2553
+ *
2554
+ * @param {Option} option
2555
+ * @param {Option} conflictingOption
2556
+ * @private
2557
+ */
2558
+ _conflictingOption(option, conflictingOption) {
2559
+ const findBestOptionFromValue = (option2) => {
2560
+ const optionKey = option2.attributeName();
2561
+ const optionValue = this.getOptionValue(optionKey);
2562
+ const negativeOption = this.options.find(
2563
+ (target) => target.negate && optionKey === target.attributeName()
2564
+ );
2565
+ const positiveOption = this.options.find(
2566
+ (target) => !target.negate && optionKey === target.attributeName()
2567
+ );
2568
+ if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
2569
+ return negativeOption;
2570
+ }
2571
+ return positiveOption || option2;
2572
+ };
2573
+ const getErrorMessage = (option2) => {
2574
+ const bestOption = findBestOptionFromValue(option2);
2575
+ const optionKey = bestOption.attributeName();
2576
+ const source = this.getOptionValueSource(optionKey);
2577
+ if (source === "env") {
2578
+ return `environment variable '${bestOption.envVar}'`;
2579
+ }
2580
+ return `option '${bestOption.flags}'`;
2581
+ };
2582
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2583
+ this.error(message, { code: "commander.conflictingOption" });
2584
+ }
2585
+ /**
2586
+ * Unknown option `flag`.
2587
+ *
2588
+ * @param {string} flag
2589
+ * @private
2590
+ */
2591
+ unknownOption(flag) {
2592
+ if (this._allowUnknownOption) return;
2593
+ let suggestion = "";
2594
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
2595
+ let candidateFlags = [];
2596
+ let command = this;
2597
+ do {
2598
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
2599
+ candidateFlags = candidateFlags.concat(moreFlags);
2600
+ command = command.parent;
2601
+ } while (command && !command._enablePositionalOptions);
2602
+ suggestion = suggestSimilar(flag, candidateFlags);
2603
+ }
2604
+ const message = `error: unknown option '${flag}'${suggestion}`;
2605
+ this.error(message, { code: "commander.unknownOption" });
2606
+ }
2607
+ /**
2608
+ * Excess arguments, more than expected.
2609
+ *
2610
+ * @param {string[]} receivedArgs
2611
+ * @private
2612
+ */
2613
+ _excessArguments(receivedArgs) {
2614
+ if (this._allowExcessArguments) return;
2615
+ const expected = this.registeredArguments.length;
2616
+ const s = expected === 1 ? "" : "s";
2617
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
2618
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
2619
+ this.error(message, { code: "commander.excessArguments" });
2620
+ }
2621
+ /**
2622
+ * Unknown command.
2623
+ *
2624
+ * @private
2625
+ */
2626
+ unknownCommand() {
2627
+ const unknownName = this.args[0];
2628
+ let suggestion = "";
2629
+ if (this._showSuggestionAfterError) {
2630
+ const candidateNames = [];
2631
+ this.createHelp().visibleCommands(this).forEach((command) => {
2632
+ candidateNames.push(command.name());
2633
+ if (command.alias()) candidateNames.push(command.alias());
2634
+ });
2635
+ suggestion = suggestSimilar(unknownName, candidateNames);
2636
+ }
2637
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
2638
+ this.error(message, { code: "commander.unknownCommand" });
2639
+ }
2640
+ /**
2641
+ * Get or set the program version.
2642
+ *
2643
+ * This method auto-registers the "-V, --version" option which will print the version number.
2644
+ *
2645
+ * You can optionally supply the flags and description to override the defaults.
2646
+ *
2647
+ * @param {string} [str]
2648
+ * @param {string} [flags]
2649
+ * @param {string} [description]
2650
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
2651
+ */
2652
+ version(str, flags, description) {
2653
+ if (str === void 0) return this._version;
2654
+ this._version = str;
2655
+ flags = flags || "-V, --version";
2656
+ description = description || "output the version number";
2657
+ const versionOption = this.createOption(flags, description);
2658
+ this._versionOptionName = versionOption.attributeName();
2659
+ this._registerOption(versionOption);
2660
+ this.on("option:" + versionOption.name(), () => {
2661
+ this._outputConfiguration.writeOut(`${str}
2662
+ `);
2663
+ this._exit(0, "commander.version", str);
2664
+ });
2665
+ return this;
2666
+ }
2667
+ /**
2668
+ * Set the description.
2669
+ *
2670
+ * @param {string} [str]
2671
+ * @param {object} [argsDescription]
2672
+ * @return {(string|Command)}
2673
+ */
2674
+ description(str, argsDescription) {
2675
+ if (str === void 0 && argsDescription === void 0)
2676
+ return this._description;
2677
+ this._description = str;
2678
+ if (argsDescription) {
2679
+ this._argsDescription = argsDescription;
2680
+ }
2681
+ return this;
2682
+ }
2683
+ /**
2684
+ * Set the summary. Used when listed as subcommand of parent.
2685
+ *
2686
+ * @param {string} [str]
2687
+ * @return {(string|Command)}
2688
+ */
2689
+ summary(str) {
2690
+ if (str === void 0) return this._summary;
2691
+ this._summary = str;
2692
+ return this;
2693
+ }
2694
+ /**
2695
+ * Set an alias for the command.
2696
+ *
2697
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
2698
+ *
2699
+ * @param {string} [alias]
2700
+ * @return {(string|Command)}
2701
+ */
2702
+ alias(alias) {
2703
+ if (alias === void 0) return this._aliases[0];
2704
+ let command = this;
2705
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
2706
+ command = this.commands[this.commands.length - 1];
2707
+ }
2708
+ if (alias === command._name)
2709
+ throw new Error("Command alias can't be the same as its name");
2710
+ const matchingCommand = this.parent?._findCommand(alias);
2711
+ if (matchingCommand) {
2712
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
2713
+ throw new Error(
2714
+ `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`
2715
+ );
2716
+ }
2717
+ command._aliases.push(alias);
2718
+ return this;
2719
+ }
2720
+ /**
2721
+ * Set aliases for the command.
2722
+ *
2723
+ * Only the first alias is shown in the auto-generated help.
2724
+ *
2725
+ * @param {string[]} [aliases]
2726
+ * @return {(string[]|Command)}
2727
+ */
2728
+ aliases(aliases) {
2729
+ if (aliases === void 0) return this._aliases;
2730
+ aliases.forEach((alias) => this.alias(alias));
2731
+ return this;
2732
+ }
2733
+ /**
2734
+ * Set / get the command usage `str`.
2735
+ *
2736
+ * @param {string} [str]
2737
+ * @return {(string|Command)}
2738
+ */
2739
+ usage(str) {
2740
+ if (str === void 0) {
2741
+ if (this._usage) return this._usage;
2742
+ const args = this.registeredArguments.map((arg) => {
2743
+ return humanReadableArgName(arg);
2744
+ });
2745
+ return [].concat(
2746
+ this.options.length || this._helpOption !== null ? "[options]" : [],
2747
+ this.commands.length ? "[command]" : [],
2748
+ this.registeredArguments.length ? args : []
2749
+ ).join(" ");
2750
+ }
2751
+ this._usage = str;
2752
+ return this;
2753
+ }
2754
+ /**
2755
+ * Get or set the name of the command.
2756
+ *
2757
+ * @param {string} [str]
2758
+ * @return {(string|Command)}
2759
+ */
2760
+ name(str) {
2761
+ if (str === void 0) return this._name;
2762
+ this._name = str;
2763
+ return this;
2764
+ }
2765
+ /**
2766
+ * Set the name of the command from script filename, such as process.argv[1],
2767
+ * or require.main.filename, or __filename.
2768
+ *
2769
+ * (Used internally and public although not documented in README.)
2770
+ *
2771
+ * @example
2772
+ * program.nameFromFilename(require.main.filename);
2773
+ *
2774
+ * @param {string} filename
2775
+ * @return {Command}
2776
+ */
2777
+ nameFromFilename(filename) {
2778
+ this._name = path.basename(filename, path.extname(filename));
2779
+ return this;
2780
+ }
2781
+ /**
2782
+ * Get or set the directory for searching for executable subcommands of this command.
2783
+ *
2784
+ * @example
2785
+ * program.executableDir(__dirname);
2786
+ * // or
2787
+ * program.executableDir('subcommands');
2788
+ *
2789
+ * @param {string} [path]
2790
+ * @return {(string|null|Command)}
2791
+ */
2792
+ executableDir(path2) {
2793
+ if (path2 === void 0) return this._executableDir;
2794
+ this._executableDir = path2;
2795
+ return this;
2796
+ }
2797
+ /**
2798
+ * Return program help documentation.
2799
+ *
2800
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
2801
+ * @return {string}
2802
+ */
2803
+ helpInformation(contextOptions) {
2804
+ const helper = this.createHelp();
2805
+ if (helper.helpWidth === void 0) {
2806
+ helper.helpWidth = contextOptions && contextOptions.error ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();
2807
+ }
2808
+ return helper.formatHelp(this, helper);
2809
+ }
2810
+ /**
2811
+ * @private
2812
+ */
2813
+ _getHelpContext(contextOptions) {
2814
+ contextOptions = contextOptions || {};
2815
+ const context = { error: !!contextOptions.error };
2816
+ let write;
2817
+ if (context.error) {
2818
+ write = (arg) => this._outputConfiguration.writeErr(arg);
2819
+ } else {
2820
+ write = (arg) => this._outputConfiguration.writeOut(arg);
2821
+ }
2822
+ context.write = contextOptions.write || write;
2823
+ context.command = this;
2824
+ return context;
2825
+ }
2826
+ /**
2827
+ * Output help information for this command.
2828
+ *
2829
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2830
+ *
2831
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2832
+ */
2833
+ outputHelp(contextOptions) {
2834
+ let deprecatedCallback;
2835
+ if (typeof contextOptions === "function") {
2836
+ deprecatedCallback = contextOptions;
2837
+ contextOptions = void 0;
2838
+ }
2839
+ const context = this._getHelpContext(contextOptions);
2840
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", context));
2841
+ this.emit("beforeHelp", context);
2842
+ let helpInformation = this.helpInformation(context);
2843
+ if (deprecatedCallback) {
2844
+ helpInformation = deprecatedCallback(helpInformation);
2845
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
2846
+ throw new Error("outputHelp callback must return a string or a Buffer");
2847
+ }
2848
+ }
2849
+ context.write(helpInformation);
2850
+ if (this._getHelpOption()?.long) {
2851
+ this.emit(this._getHelpOption().long);
2852
+ }
2853
+ this.emit("afterHelp", context);
2854
+ this._getCommandAndAncestors().forEach(
2855
+ (command) => command.emit("afterAllHelp", context)
2856
+ );
2857
+ }
2858
+ /**
2859
+ * You can pass in flags and a description to customise the built-in help option.
2860
+ * Pass in false to disable the built-in help option.
2861
+ *
2862
+ * @example
2863
+ * program.helpOption('-?, --help' 'show help'); // customise
2864
+ * program.helpOption(false); // disable
2865
+ *
2866
+ * @param {(string | boolean)} flags
2867
+ * @param {string} [description]
2868
+ * @return {Command} `this` command for chaining
2869
+ */
2870
+ helpOption(flags, description) {
2871
+ if (typeof flags === "boolean") {
2872
+ if (flags) {
2873
+ this._helpOption = this._helpOption ?? void 0;
2874
+ } else {
2875
+ this._helpOption = null;
2876
+ }
2877
+ return this;
2878
+ }
2879
+ flags = flags ?? "-h, --help";
2880
+ description = description ?? "display help for command";
2881
+ this._helpOption = this.createOption(flags, description);
2882
+ return this;
2883
+ }
2884
+ /**
2885
+ * Lazy create help option.
2886
+ * Returns null if has been disabled with .helpOption(false).
2887
+ *
2888
+ * @returns {(Option | null)} the help option
2889
+ * @package
2890
+ */
2891
+ _getHelpOption() {
2892
+ if (this._helpOption === void 0) {
2893
+ this.helpOption(void 0, void 0);
2894
+ }
2895
+ return this._helpOption;
2896
+ }
2897
+ /**
2898
+ * Supply your own option to use for the built-in help option.
2899
+ * This is an alternative to using helpOption() to customise the flags and description etc.
2900
+ *
2901
+ * @param {Option} option
2902
+ * @return {Command} `this` command for chaining
2903
+ */
2904
+ addHelpOption(option) {
2905
+ this._helpOption = option;
2906
+ return this;
2907
+ }
2908
+ /**
2909
+ * Output help information and exit.
2910
+ *
2911
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2912
+ *
2913
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2914
+ */
2915
+ help(contextOptions) {
2916
+ this.outputHelp(contextOptions);
2917
+ let exitCode = process.exitCode || 0;
2918
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
2919
+ exitCode = 1;
2920
+ }
2921
+ this._exit(exitCode, "commander.help", "(outputHelp)");
2922
+ }
2923
+ /**
2924
+ * Add additional text to be displayed with the built-in help.
2925
+ *
2926
+ * Position is 'before' or 'after' to affect just this command,
2927
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
2928
+ *
2929
+ * @param {string} position - before or after built-in help
2930
+ * @param {(string | Function)} text - string to add, or a function returning a string
2931
+ * @return {Command} `this` command for chaining
2932
+ */
2933
+ addHelpText(position, text) {
2934
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
2935
+ if (!allowedValues.includes(position)) {
2936
+ throw new Error(`Unexpected value for position to addHelpText.
2937
+ Expecting one of '${allowedValues.join("', '")}'`);
2938
+ }
2939
+ const helpEvent = `${position}Help`;
2940
+ this.on(helpEvent, (context) => {
2941
+ let helpStr;
2942
+ if (typeof text === "function") {
2943
+ helpStr = text({ error: context.error, command: context.command });
2944
+ } else {
2945
+ helpStr = text;
2946
+ }
2947
+ if (helpStr) {
2948
+ context.write(`${helpStr}
2949
+ `);
2950
+ }
2951
+ });
2952
+ return this;
2953
+ }
2954
+ /**
2955
+ * Output help information if help flags specified
2956
+ *
2957
+ * @param {Array} args - array of options to search for help flags
2958
+ * @private
2959
+ */
2960
+ _outputHelpIfRequested(args) {
2961
+ const helpOption = this._getHelpOption();
2962
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
2963
+ if (helpRequested) {
2964
+ this.outputHelp();
2965
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
2966
+ }
2967
+ }
2968
+ };
2969
+ function incrementNodeInspectorPort(args) {
2970
+ return args.map((arg) => {
2971
+ if (!arg.startsWith("--inspect")) {
2972
+ return arg;
2973
+ }
2974
+ let debugOption;
2975
+ let debugHost = "127.0.0.1";
2976
+ let debugPort = "9229";
2977
+ let match;
2978
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
2979
+ debugOption = match[1];
2980
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
2981
+ debugOption = match[1];
2982
+ if (/^\d+$/.test(match[3])) {
2983
+ debugPort = match[3];
2984
+ } else {
2985
+ debugHost = match[3];
2986
+ }
2987
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
2988
+ debugOption = match[1];
2989
+ debugHost = match[3];
2990
+ debugPort = match[4];
2991
+ }
2992
+ if (debugOption && debugPort !== "0") {
2993
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
2994
+ }
2995
+ return arg;
2996
+ });
2997
+ }
2998
+ exports.Command = Command2;
2999
+ }
3000
+ });
3001
+
3002
+ // ../../node_modules/commander/index.js
3003
+ var require_commander = __commonJS({
3004
+ "../../node_modules/commander/index.js"(exports) {
3005
+ "use strict";
3006
+ init_esm_shims();
3007
+ var { Argument: Argument2 } = require_argument();
3008
+ var { Command: Command2 } = require_command();
3009
+ var { CommanderError: CommanderError2, InvalidArgumentError: InvalidArgumentError2 } = require_error();
3010
+ var { Help: Help2 } = require_help();
3011
+ var { Option: Option2 } = require_option();
3012
+ exports.program = new Command2();
3013
+ exports.createCommand = (name) => new Command2(name);
3014
+ exports.createOption = (flags, description) => new Option2(flags, description);
3015
+ exports.createArgument = (name, description) => new Argument2(name, description);
3016
+ exports.Command = Command2;
3017
+ exports.Option = Option2;
3018
+ exports.Argument = Argument2;
3019
+ exports.Help = Help2;
3020
+ exports.CommanderError = CommanderError2;
3021
+ exports.InvalidArgumentError = InvalidArgumentError2;
3022
+ exports.InvalidOptionArgumentError = InvalidArgumentError2;
3023
+ }
3024
+ });
3025
+
3026
+ // ../../node_modules/@commander-js/extra-typings/index.js
3027
+ var require_extra_typings = __commonJS({
3028
+ "../../node_modules/@commander-js/extra-typings/index.js"(exports, module) {
3029
+ "use strict";
3030
+ init_esm_shims();
3031
+ var commander = require_commander();
3032
+ exports = module.exports = {};
3033
+ exports.program = new commander.Command();
3034
+ exports.Argument = commander.Argument;
3035
+ exports.Command = commander.Command;
3036
+ exports.CommanderError = commander.CommanderError;
3037
+ exports.Help = commander.Help;
3038
+ exports.InvalidArgumentError = commander.InvalidArgumentError;
3039
+ exports.InvalidOptionArgumentError = commander.InvalidArgumentError;
3040
+ exports.Option = commander.Option;
3041
+ exports.createCommand = (name) => new commander.Command(name);
3042
+ exports.createOption = (flags, description) => new commander.Option(flags, description);
3043
+ exports.createArgument = (name, description) => new commander.Argument(name, description);
3044
+ }
3045
+ });
3046
+
3047
+ // src/index.ts
3048
+ init_esm_shims();
3049
+
3050
+ // src/commands/root-command.ts
3051
+ init_esm_shims();
3052
+
3053
+ // ../../node_modules/@commander-js/extra-typings/esm.mjs
3054
+ init_esm_shims();
3055
+ var import_index = __toESM(require_extra_typings(), 1);
3056
+ var {
3057
+ program,
3058
+ createCommand,
3059
+ createArgument,
3060
+ createOption,
3061
+ CommanderError,
3062
+ InvalidArgumentError,
3063
+ InvalidOptionArgumentError,
3064
+ // deprecated old name
3065
+ Command,
3066
+ Argument,
3067
+ Option,
3068
+ Help
3069
+ } = import_index.default;
3070
+
3071
+ // src/commands/build.ts
3072
+ init_esm_shims();
3073
+ var buildCommand = (services) => createCommand("build").action(async (_, command) => {
3074
+ const { runCommand } = await import("./render-command-BMSK4YLL.js");
3075
+ const { build } = await import("./build-3AJU7FWE.js");
3076
+ await runCommand(command, services, build);
3077
+ });
3078
+
3079
+ // src/commands/dev.tsx
3080
+ init_esm_shims();
3081
+ var import_react = __toESM(require_react(), 1);
3082
+ var devCommand = (services) => {
3083
+ const t = createI18nT();
3084
+ return createCommand("dev").option("-s, --https", t("dev_command_def.option.https")).action(async (options, command) => {
3085
+ const { DevCommand } = await import("./DevCommand-TOFPM7DZ.js");
3086
+ const { renderCommand } = await import("./render-command-BMSK4YLL.js");
3087
+ const { https = false } = options;
3088
+ await renderCommand(command, services, /* @__PURE__ */ import_react.default.createElement(DevCommand, { https }), {
3089
+ watchForModelChanges: true
3090
+ });
3091
+ });
3092
+ };
3093
+
3094
+ // src/commands/preview.tsx
3095
+ init_esm_shims();
3096
+ var import_react2 = __toESM(require_react(), 1);
3097
+
3098
+ // src/commands/validations.ts
3099
+ init_esm_shims();
3100
+ function validateSite(value) {
3101
+ const parsed = z.union([z.string().uuid(), z.literal("current")]).transform((val) => val === "current" ? void 0 : val).safeParse(value);
3102
+ if (parsed.success) {
3103
+ return parsed.data;
3104
+ }
3105
+ throw new InvalidArgumentError('Value must be a valid GUID or "current"');
3106
+ }
3107
+ function validateBase(value) {
3108
+ const parsed = z.string().url().safeParse(value);
3109
+ if (parsed.success) {
3110
+ return parsed.data;
3111
+ }
3112
+ throw new InvalidArgumentError("Value must be a valid URL");
3113
+ }
3114
+ function validateVersion(value) {
3115
+ const parsed = z.string().regex(/^(0|[1-9]\d*)\.(0|[1-9]\d*)(\.(0|[1-9]\d*))?$/).safeParse(value);
3116
+ if (parsed.success) {
3117
+ return parsed.data;
3118
+ }
3119
+ throw new InvalidArgumentError(
3120
+ "Version value should be in semver format `x.x.x`"
3121
+ );
3122
+ }
3123
+
3124
+ // src/commands/preview.tsx
3125
+ var previewCommand = (services) => {
3126
+ const t = createI18nT();
3127
+ return createCommand("preview").option(
3128
+ "-s, --site <site-id>",
3129
+ t("app_preview_command_def.option.site"),
3130
+ validateSite
3131
+ ).option(
3132
+ "--base-url <url>",
3133
+ t("app_preview_command_def.option.base_url"),
3134
+ validateBase
3135
+ ).option("--no-input", t("app_preview_command_def.option.no_input")).action(async (options, command) => {
3136
+ const { site, baseUrl, input } = options;
3137
+ const { renderCommand, runCommand } = await import("./render-command-BMSK4YLL.js");
3138
+ if (!input) {
3139
+ return runCommand(command, services, async (model) => {
3140
+ const { nonInteractivePreview } = await import("./preview-C7XYH7BB.js");
3141
+ return nonInteractivePreview(
3142
+ { siteId: site, baseUrl },
3143
+ model,
3144
+ services
3145
+ );
3146
+ });
3147
+ }
3148
+ const { PreviewCommand } = await import("./PreviewCommand-XBSTVGWT.js");
3149
+ await renderCommand(
3150
+ command,
3151
+ services,
3152
+ /* @__PURE__ */ import_react2.default.createElement(PreviewCommand, { baseUrl, siteIdOverride: site })
3153
+ );
3154
+ });
3155
+ };
3156
+
3157
+ // src/commands/create-version.tsx
3158
+ init_esm_shims();
3159
+ var import_react3 = __toESM(require_react(), 1);
3160
+ var createVersionCommand = (services) => {
3161
+ const t = createI18nT();
3162
+ return createCommand("create-version").addOption(
3163
+ new Option(
3164
+ "-t, --version-type <type>",
3165
+ t("create_version_command_def.option.version_type")
3166
+ ).choices(["major", "minor"])
3167
+ ).option(
3168
+ "-s, --site <site-id>",
3169
+ t("create_version_command_def.option.site"),
3170
+ validateSite
3171
+ ).option(
3172
+ "-y, --approve-preview",
3173
+ t("create_version_command_def.option.approve_preview")
3174
+ ).option(
3175
+ "--base-url <url>",
3176
+ t("create_version_command_def.option.base_url"),
3177
+ validateBase
3178
+ ).action(async (options, command) => {
3179
+ const { VersionType } = await import("./types.impl-CD4WWRUK.js");
3180
+ const { renderCommand } = await import("./render-command-BMSK4YLL.js");
3181
+ const { CreateVersionCommand } = await import("./CreateVersionCommand-AIXBHCYB.js");
3182
+ const {
3183
+ approvePreview = false,
3184
+ versionType: versionTypeString,
3185
+ baseUrl,
3186
+ site
3187
+ } = options;
3188
+ const versionTypes = {
3189
+ major: VersionType.MAJOR,
3190
+ minor: VersionType.MINOR
3191
+ };
3192
+ const versionType = versionTypeString ? versionTypes[versionTypeString] : void 0;
3193
+ await renderCommand(
3194
+ command,
3195
+ services,
3196
+ /* @__PURE__ */ import_react3.default.createElement(
3197
+ CreateVersionCommand,
3198
+ {
3199
+ baseUrl,
3200
+ siteIdOverride: site,
3201
+ preApprovePreview: approvePreview,
3202
+ versionType
3203
+ }
3204
+ )
3205
+ );
3206
+ });
3207
+ };
3208
+
3209
+ // src/commands/serve.tsx
3210
+ init_esm_shims();
3211
+ var import_react4 = __toESM(require_react(), 1);
3212
+ var serveCommand = (services) => createCommand("serve").action(async (_, command) => {
3213
+ const { renderCommand } = await import("./render-command-BMSK4YLL.js");
3214
+ const { ServeCommand } = await import("./ServeCommand-ZEXPLXTI.js");
3215
+ await renderCommand(command, services, /* @__PURE__ */ import_react4.default.createElement(ServeCommand, null));
3216
+ });
3217
+
3218
+ // src/commands/generate.tsx
3219
+ init_esm_shims();
3220
+ var import_react5 = __toESM(require_react(), 1);
3221
+ var generateCommand = (services) => {
3222
+ const t = createI18nT();
3223
+ return createCommand("generate").description(t("generate_command.description")).action(async (options, command) => {
3224
+ const { GenerateCommand } = await import("./GenerateCommand-HB46FNMR.js");
3225
+ const { renderCommand } = await import("./render-command-BMSK4YLL.js");
3226
+ await renderCommand(command, services, /* @__PURE__ */ import_react5.default.createElement(GenerateCommand, null), {
3227
+ skipProjectValidation: true
3228
+ });
3229
+ });
3230
+ };
3231
+
3232
+ // src/commands/logs.tsx
3233
+ init_esm_shims();
3234
+ var import_react6 = __toESM(require_react(), 1);
3235
+ var logsCommand = (services) => {
3236
+ const t = createI18nT();
3237
+ return createCommand("logs").requiredOption(
3238
+ "--version <version>",
3239
+ t("logs_command_def.option.version"),
3240
+ validateVersion
3241
+ ).action(async (options, command) => {
3242
+ const { version: version2 } = options;
3243
+ const { renderCommand } = await import("./render-command-BMSK4YLL.js");
3244
+ const { LogsCommand } = await import("./LogsCommand-Q2HRBR6G.js");
3245
+ await renderCommand(command, services, /* @__PURE__ */ import_react6.default.createElement(LogsCommand, { version: version2 }));
3246
+ });
3247
+ };
3248
+
3249
+ // src/commands/root-command.ts
3250
+ var getRootCommand = async (services) => {
3251
+ return createCommand("app").version(version, "-v, --version", "Output the version number").enablePositionalOptions(true).helpOption("-h, --help", "Display help for command").helpCommand(false).addCommand(devCommand(services)).addCommand(buildCommand(services)).addCommand(serveCommand(services)).addCommand(previewCommand(services)).addCommand(createVersionCommand(services)).addCommand(generateCommand(services)).addCommand(logsCommand(services));
3252
+ };
3253
+ export {
3254
+ getRootCommand
3255
+ };
25
3256
  //# sourceMappingURL=index.js.map