@xaendar/cli 0.5.3 → 0.5.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +46 -37
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,44 +1,53 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire } from 'node:module';
|
|
3
3
|
const require = createRequire(import.meta.url);
|
|
4
|
-
var
|
|
5
|
-
`)}displayWidth(t){return
|
|
6
|
-
`+" ".repeat(e+h)),
|
|
7
|
-
${
|
|
8
|
-
`)}};
|
|
4
|
+
var f=class extends Error{constructor(t,e,i){super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=e,this.exitCode=t,this.nestedError=void 0}},C=class extends f{constructor(t){super(1,"commander.invalidArgument",t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};var x=class{constructor(t,e){switch(this.description=e||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,t[0]){case"<":this.required=!0,this._name=t.slice(1,-1);break;case"[":this.required=!1,this._name=t.slice(1,-1);break;default:this.required=!0,this._name=t;break}this._name.endsWith("...")&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(t,e){return e===this.defaultValue||!Array.isArray(e)?[t]:(e.push(t),e)}default(t,e){return this.defaultValue=t,this.defaultValueDescription=e,this}argParser(t){return this.parseArg=t,this}choices(t){return this.argChoices=t.slice(),this.parseArg=(e,i)=>{if(!this.argChoices.includes(e))throw new C(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(e,i):e},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function $(o){let t=o.name()+(o.variadic===!0?"...":"");return o.required?"<"+t+">":"["+t+"]"}import{EventEmitter as tt}from"events";import H from"child_process";import d from"path";import E from"fs";import m from"process";import{stripVTControlCharacters as et}from"util";import{stripVTControlCharacters as z}from"util";var y=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(t){this.helpWidth=this.helpWidth??t.helpWidth??80}visibleCommands(t){let e=t.commands.filter(n=>!n._hidden),i=t._getHelpCommand();return i&&!i._hidden&&e.push(i),this.sortSubcommands&&e.sort((n,r)=>n.name().localeCompare(r.name())),e}compareOptions(t,e){let i=n=>n.short?n.short.replace(/^-/,""):n.long.replace(/^--/,"");return i(t).localeCompare(i(e))}visibleOptions(t){let e=t.options.filter(n=>!n.hidden),i=t._getHelpOption();if(i&&!i.hidden){let n=i.short&&t._findOption(i.short),r=i.long&&t._findOption(i.long);!n&&!r?e.push(i):i.long&&!r?e.push(t.createOption(i.long,i.description)):i.short&&!n&&e.push(t.createOption(i.short,i.description))}return this.sortOptions&&e.sort(this.compareOptions),e}visibleGlobalOptions(t){if(!this.showGlobalOptions)return[];let e=[];for(let i=t.parent;i;i=i.parent){let n=i.options.filter(r=>!r.hidden);e.push(...n)}return this.sortOptions&&e.sort(this.compareOptions),e}visibleArguments(t){return t._argsDescription&&t.registeredArguments.forEach(e=>{e.description=e.description||t._argsDescription[e.name()]||""}),t.registeredArguments.find(e=>e.description)?t.registeredArguments:[]}subcommandTerm(t){let e=t.registeredArguments.map(i=>$(i)).join(" ");return t._name+(t._aliases[0]?"|"+t._aliases[0]:"")+(t.options.length?" [options]":"")+(e?" "+e:"")}optionTerm(t){return t.flags}argumentTerm(t){return t.name()}longestSubcommandTermLength(t,e){return e.visibleCommands(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleSubcommandTerm(e.subcommandTerm(n)))),0)}longestOptionTermLength(t,e){return e.visibleOptions(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleOptionTerm(e.optionTerm(n)))),0)}longestGlobalOptionTermLength(t,e){return e.visibleGlobalOptions(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleOptionTerm(e.optionTerm(n)))),0)}longestArgumentTermLength(t,e){return e.visibleArguments(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleArgumentTerm(e.argumentTerm(n)))),0)}commandUsage(t){let e=t._name;t._aliases[0]&&(e=e+"|"+t._aliases[0]);let i="";for(let n=t.parent;n;n=n.parent)i=n.name()+" "+i;return i+e+" "+t.usage()}commandDescription(t){return t.description()}subcommandDescription(t){return t.summary()||t.description()}optionDescription(t){let e=[];if(t.argChoices&&e.push(`choices: ${t.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),t.defaultValue!==void 0&&(t.required||t.optional||t.isBoolean()&&typeof t.defaultValue=="boolean")&&e.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),t.presetArg!==void 0&&t.optional&&e.push(`preset: ${JSON.stringify(t.presetArg)}`),t.envVar!==void 0&&e.push(`env: ${t.envVar}`),e.length>0){let i=`(${e.join(", ")})`;return t.description?`${t.description} ${i}`:i}return t.description}argumentDescription(t){let e=[];if(t.argChoices&&e.push(`choices: ${t.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),t.defaultValue!==void 0&&e.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),e.length>0){let i=`(${e.join(", ")})`;return t.description?`${t.description} ${i}`:i}return t.description}formatItemList(t,e,i){return e.length===0?[]:[i.styleTitle(t),...e,""]}groupItems(t,e,i){let n=new Map;return t.forEach(r=>{let s=i(r);n.has(s)||n.set(s,[])}),e.forEach(r=>{let s=i(r);n.has(s)||n.set(s,[]),n.get(s).push(r)}),n}formatHelp(t,e){let i=e.padWidth(t,e),n=e.helpWidth??80;function r(u,p){return e.formatItem(u,i,p,e)}let s=[`${e.styleTitle("Usage:")} ${e.styleUsage(e.commandUsage(t))}`,""],a=e.commandDescription(t);a.length>0&&(s=s.concat([e.boxWrap(e.styleCommandDescription(a),n),""]));let h=e.visibleArguments(t).map(u=>r(e.styleArgumentTerm(e.argumentTerm(u)),e.styleArgumentDescription(e.argumentDescription(u))));if(s=s.concat(this.formatItemList("Arguments:",h,e)),this.groupItems(t.options,e.visibleOptions(t),u=>u.helpGroupHeading??"Options:").forEach((u,p)=>{let O=u.map(_=>r(e.styleOptionTerm(e.optionTerm(_)),e.styleOptionDescription(e.optionDescription(_))));s=s.concat(this.formatItemList(p,O,e))}),e.showGlobalOptions){let u=e.visibleGlobalOptions(t).map(p=>r(e.styleOptionTerm(e.optionTerm(p)),e.styleOptionDescription(e.optionDescription(p))));s=s.concat(this.formatItemList("Global Options:",u,e))}return this.groupItems(t.commands,e.visibleCommands(t),u=>u.helpGroup()||"Commands:").forEach((u,p)=>{let O=u.map(_=>r(e.styleSubcommandTerm(e.subcommandTerm(_)),e.styleSubcommandDescription(e.subcommandDescription(_))));s=s.concat(this.formatItemList(p,O,e))}),s.join(`
|
|
5
|
+
`)}displayWidth(t){return z(t).length}styleTitle(t){return t}styleUsage(t){return t.split(" ").map(e=>e==="[options]"?this.styleOptionText(e):e==="[command]"?this.styleSubcommandText(e):e[0]==="["||e[0]==="<"?this.styleArgumentText(e):this.styleCommandText(e)).join(" ")}styleCommandDescription(t){return this.styleDescriptionText(t)}styleOptionDescription(t){return this.styleDescriptionText(t)}styleSubcommandDescription(t){return this.styleDescriptionText(t)}styleArgumentDescription(t){return this.styleDescriptionText(t)}styleDescriptionText(t){return t}styleOptionTerm(t){return this.styleOptionText(t)}styleSubcommandTerm(t){return t.split(" ").map(e=>e==="[options]"?this.styleOptionText(e):e[0]==="["||e[0]==="<"?this.styleArgumentText(e):this.styleSubcommandText(e)).join(" ")}styleArgumentTerm(t){return this.styleArgumentText(t)}styleOptionText(t){return t}styleArgumentText(t){return t}styleSubcommandText(t){return t}styleCommandText(t){return t}padWidth(t,e){return Math.max(e.longestOptionTermLength(t,e),e.longestGlobalOptionTermLength(t,e),e.longestSubcommandTermLength(t,e),e.longestArgumentTermLength(t,e))}preformatted(t){return/\n[^\S\r\n]/.test(t)}formatItem(t,e,i,n){let s=" ".repeat(2);if(!i)return s+t;let a=t.padEnd(e+t.length-n.displayWidth(t)),h=2,l=(this.helpWidth??80)-e-h-2,u;return l<this.minWidthToWrap||n.preformatted(i)?u=i:u=n.boxWrap(i,l).replace(/\n/g,`
|
|
6
|
+
`+" ".repeat(e+h)),s+a+" ".repeat(h)+u.replace(/\n/g,`
|
|
7
|
+
${s}`)}boxWrap(t,e){if(e<this.minWidthToWrap)return t;let i=t.split(/\r\n|\n/),n=/[\s]*[^\s]+/g,r=[];return i.forEach(s=>{let a=s.match(n);if(a===null){r.push("");return}let h=[a.shift()],c=this.displayWidth(h[0]);a.forEach(l=>{let u=this.displayWidth(l);if(c+u<=e){h.push(l),c+=u;return}r.push(h.join(""));let p=l.trimStart();h=[p],c=this.displayWidth(p)}),r.push(h.join(""))}),r.join(`
|
|
8
|
+
`)}};var b=class{constructor(t,e){this.flags=t,this.description=e||"",this.required=t.includes("<"),this.optional=t.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(t),this.mandatory=!1;let i=Z(t);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,this.helpGroupHeading=void 0}default(t,e){return this.defaultValue=t,this.defaultValueDescription=e,this}preset(t){return this.presetArg=t,this}conflicts(t){return this.conflictsWith=this.conflictsWith.concat(t),this}implies(t){let e=t;return typeof t=="string"&&(e={[t]:!0}),this.implied=Object.assign(this.implied||{},e),this}env(t){return this.envVar=t,this}argParser(t){return this.parseArg=t,this}makeOptionMandatory(t=!0){return this.mandatory=!!t,this}hideHelp(t=!0){return this.hidden=!!t,this}_collectValue(t,e){return e===this.defaultValue||!Array.isArray(e)?[t]:(e.push(t),e)}choices(t){return this.argChoices=t.slice(),this.parseArg=(e,i)=>{if(!this.argChoices.includes(e))throw new C(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(e,i):e},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?D(this.name().replace(/^no-/,"")):D(this.name())}helpGroup(t){return this.helpGroupHeading=t,this}is(t){return this.short===t||this.long===t}isBoolean(){return!this.required&&!this.optional&&!this.negate}},v=class{constructor(t){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,t.forEach(e=>{e.negate?this.negativeOptions.set(e.attributeName(),e):this.positiveOptions.set(e.attributeName(),e)}),this.negativeOptions.forEach((e,i)=>{this.positiveOptions.has(i)&&this.dualOptions.add(i)})}valueFromOption(t,e){let i=e.attributeName();if(!this.dualOptions.has(i))return!0;let n=this.negativeOptions.get(i).presetArg,r=n!==void 0?n:!1;return e.negate===(r===t)}};function D(o){return o.split("-").reduce((t,e)=>t+e[0].toUpperCase()+e.slice(1))}function Z(o){let t,e,i=/^-[^-]$/,n=/^--[^-]/,r=o.split(/[ |,]+/).concat("guard");if(i.test(r[0])&&(t=r.shift()),n.test(r[0])&&(e=r.shift()),!t&&i.test(r[0])&&(t=r.shift()),!t&&n.test(r[0])&&(t=e,e=r.shift()),r[0].startsWith("-")){let s=r[0],a=`option creation failed due to '${s}' in option flags '${o}'`;throw/^-[^-][^-]/.test(s)?new Error(`${a}
|
|
9
9
|
- a short flag is a single dash and a single character
|
|
10
10
|
- either use a single dash and a single character (for a short flag)
|
|
11
|
-
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`):i.test(
|
|
12
|
-
- too many short flags`):n.test(
|
|
11
|
+
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`):i.test(s)?new Error(`${a}
|
|
12
|
+
- too many short flags`):n.test(s)?new Error(`${a}
|
|
13
13
|
- too many long flags`):new Error(`${a}
|
|
14
|
-
- unrecognised flag format`)}if(t===void 0&&e===void 0)throw new Error(`option creation failed due to no flags found in '${
|
|
14
|
+
- unrecognised flag format`)}if(t===void 0&&e===void 0)throw new Error(`option creation failed due to no flags found in '${o}'.`);return{shortFlag:t,longFlag:e}}function Q(o,t){if(Math.abs(o.length-t.length)>3)return Math.max(o.length,t.length);let e=[];for(let i=0;i<=o.length;i++)e[i]=[i];for(let i=0;i<=t.length;i++)e[0][i]=i;for(let i=1;i<=t.length;i++)for(let n=1;n<=o.length;n++){let r;o[n-1]===t[i-1]?r=0:r=1,e[n][i]=Math.min(e[n-1][i]+1,e[n][i-1]+1,e[n-1][i-1]+r),n>1&&i>1&&o[n-1]===t[i-2]&&o[n-2]===t[i-1]&&(e[n][i]=Math.min(e[n][i],e[n-2][i-2]+1))}return e[o.length][t.length]}function T(o,t){if(!t||t.length===0)return"";t=Array.from(new Set(t));let e=o.startsWith("--");e&&(o=o.slice(2),t=t.map(s=>s.slice(2)));let i=[],n=3,r=.4;return t.forEach(s=>{if(s.length<=1)return;let a=Q(o,s),h=Math.max(o.length,s.length);(h-a)/h>r&&(a<n?(n=a,i=[s]):a===n&&i.push(s))}),i.sort((s,a)=>s.localeCompare(a)),e&&(i=i.map(s=>`--${s}`)),i.length>1?`
|
|
15
15
|
(Did you mean one of ${i.join(", ")}?)`:i.length===1?`
|
|
16
|
-
(Did you mean ${i[0]}?)`:""}
|
|
17
|
-
- specify the name in Command constructor or using .name()`);return e=e||{},e.isDefault&&(this._defaultCommandName=t._name),(e.noHelp||e.hidden)&&(t._hidden=!0),this._registerCommand(t),t.parent=this,t._checkForBrokenPassThrough(),this}createArgument(t,e){return new
|
|
18
|
-
Expecting one of '${i.join("', '")}'`);return this._lifeCycleHooks[t]?this._lifeCycleHooks[t].push(e):this._lifeCycleHooks[t]=[e],this}exitOverride(t){return t?this._exitCallback=t:this._exitCallback=e=>{if(e.code!=="commander.executeSubCommandAsync")throw e},this}_exit(t,e,i){this._exitCallback&&this._exitCallback(new
|
|
19
|
-
- already used by option '${e.flags}'`)}this._initOptionGroup(t),this.options.push(t)}_registerCommand(t){let e=n=>[n.name()].concat(n.aliases()),i=e(t).find(n=>this._findCommand(n));if(i){let n=e(this._findCommand(i)).join("|"),
|
|
20
|
-
- either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(t,e,i){if(E.existsSync(t))return;let n=e?`searched for local subcommand relative to directory '${e}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",
|
|
16
|
+
(Did you mean ${i[0]}?)`:""}var g=class o extends tt{constructor(t){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=t||"",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._savedState=null,this._outputConfiguration={writeOut:e=>m.stdout.write(e),writeErr:e=>m.stderr.write(e),outputError:(e,i)=>i(e),getOutHelpWidth:()=>m.stdout.isTTY?m.stdout.columns:void 0,getErrHelpWidth:()=>m.stderr.isTTY?m.stderr.columns:void 0,getOutHasColors:()=>W()??(m.stdout.isTTY&&m.stdout.hasColors?.()),getErrHasColors:()=>W()??(m.stderr.isTTY&&m.stderr.hasColors?.()),stripColor:e=>et(e)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(t){return this._outputConfiguration=t._outputConfiguration,this._helpOption=t._helpOption,this._helpCommand=t._helpCommand,this._helpConfiguration=t._helpConfiguration,this._exitCallback=t._exitCallback,this._storeOptionsAsProperties=t._storeOptionsAsProperties,this._combineFlagAndOptionalValue=t._combineFlagAndOptionalValue,this._allowExcessArguments=t._allowExcessArguments,this._enablePositionalOptions=t._enablePositionalOptions,this._showHelpAfterError=t._showHelpAfterError,this._showSuggestionAfterError=t._showSuggestionAfterError,this}_getCommandAndAncestors(){let t=[];for(let e=this;e;e=e.parent)t.push(e);return t}command(t,e,i){let n=e,r=i;typeof n=="object"&&n!==null&&(r=n,n=null),r=r||{};let[,s,a]=t.match(/([^ ]+) *(.*)/),h=this.createCommand(s);return n&&(h.description(n),h._executableHandler=!0),r.isDefault&&(this._defaultCommandName=h._name),h._hidden=!!(r.noHelp||r.hidden),h._executableFile=r.executableFile||null,a&&h.arguments(a),this._registerCommand(h),h.parent=this,h.copyInheritedSettings(this),n?this:h}createCommand(t){return new o(t)}createHelp(){return Object.assign(new y,this.configureHelp())}configureHelp(t){return t===void 0?this._helpConfiguration:(this._helpConfiguration=t,this)}configureOutput(t){return t===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...t},this)}showHelpAfterError(t=!0){return typeof t!="string"&&(t=!!t),this._showHelpAfterError=t,this}showSuggestionAfterError(t=!0){return this._showSuggestionAfterError=!!t,this}addCommand(t,e){if(!t._name)throw new Error(`Command passed to .addCommand() must have a name
|
|
17
|
+
- specify the name in Command constructor or using .name()`);return e=e||{},e.isDefault&&(this._defaultCommandName=t._name),(e.noHelp||e.hidden)&&(t._hidden=!0),this._registerCommand(t),t.parent=this,t._checkForBrokenPassThrough(),this}createArgument(t,e){return new x(t,e)}argument(t,e,i,n){let r=this.createArgument(t,e);return typeof i=="function"?r.default(n).argParser(i):r.default(i),this.addArgument(r),this}arguments(t){return t.trim().split(/ +/).forEach(e=>{this.argument(e)}),this}addArgument(t){let e=this.registeredArguments.slice(-1)[0];if(e?.variadic)throw new Error(`only the last argument can be variadic '${e.name()}'`);if(t.required&&t.defaultValue!==void 0&&t.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${t.name()}'`);return this.registeredArguments.push(t),this}helpCommand(t,e){if(typeof t=="boolean")return this._addImplicitHelpCommand=t,t&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;let i=t??"help [command]",[,n,r]=i.match(/([^ ]+) *(.*)/),s=e??"display help for command",a=this.createCommand(n);return a.helpOption(!1),r&&a.arguments(r),s&&a.description(s),this._addImplicitHelpCommand=!0,this._helpCommand=a,(t||e)&&this._initCommandGroup(a),this}addHelpCommand(t,e){return typeof t!="object"?(this.helpCommand(t,e),this):(this._addImplicitHelpCommand=!0,this._helpCommand=t,this._initCommandGroup(t),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(t,e){let i=["preSubcommand","preAction","postAction"];if(!i.includes(t))throw new Error(`Unexpected value for event passed to hook : '${t}'.
|
|
18
|
+
Expecting one of '${i.join("', '")}'`);return this._lifeCycleHooks[t]?this._lifeCycleHooks[t].push(e):this._lifeCycleHooks[t]=[e],this}exitOverride(t){return t?this._exitCallback=t:this._exitCallback=e=>{if(e.code!=="commander.executeSubCommandAsync")throw e},this}_exit(t,e,i){this._exitCallback&&this._exitCallback(new f(t,e,i)),m.exit(t)}action(t){let e=i=>{let n=this.registeredArguments.length,r=i.slice(0,n);return this._storeOptionsAsProperties?r[n]=this:r[n]=this.opts(),r.push(this),t.apply(this,r)};return this._actionHandler=e,this}createOption(t,e){return new b(t,e)}_callParseArg(t,e,i,n){try{return t.parseArg(e,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(t){let e=t.short&&this._findOption(t.short)||t.long&&this._findOption(t.long);if(e){let i=t.long&&this._findOption(t.long)?t.long:t.short;throw new Error(`Cannot add option '${t.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${i}'
|
|
19
|
+
- already used by option '${e.flags}'`)}this._initOptionGroup(t),this.options.push(t)}_registerCommand(t){let e=n=>[n.name()].concat(n.aliases()),i=e(t).find(n=>this._findCommand(n));if(i){let n=e(this._findCommand(i)).join("|"),r=e(t).join("|");throw new Error(`cannot add command '${r}' as already have command '${n}'`)}this._initCommandGroup(t),this.commands.push(t)}addOption(t){this._registerOption(t);let e=t.name(),i=t.attributeName();t.defaultValue!==void 0&&this.setOptionValueWithSource(i,t.defaultValue,"default");let n=(r,s,a)=>{r==null&&t.presetArg!==void 0&&(r=t.presetArg);let h=this.getOptionValue(i);r!==null&&t.parseArg?r=this._callParseArg(t,r,h,s):r!==null&&t.variadic&&(r=t._collectValue(r,h)),r==null&&(t.negate?r=!1:t.isBoolean()||t.optional?r=!0:r=""),this.setOptionValueWithSource(i,r,a)};return this.on("option:"+e,r=>{let s=`error: option '${t.flags}' argument '${r}' is invalid.`;n(r,s,"cli")}),t.envVar&&this.on("optionEnv:"+e,r=>{let s=`error: option '${t.flags}' value '${r}' from env '${t.envVar}' is invalid.`;n(r,s,"env")}),this}_optionEx(t,e,i,n,r){if(typeof e=="object"&&e instanceof b)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let s=this.createOption(e,i);if(s.makeOptionMandatory(!!t.mandatory),typeof n=="function")s.default(r).argParser(n);else if(n instanceof RegExp){let a=n;n=(h,c)=>{let l=a.exec(h);return l?l[0]:c},s.default(r).argParser(n)}else s.default(n);return this.addOption(s)}option(t,e,i,n){return this._optionEx({},t,e,i,n)}requiredOption(t,e,i,n){return this._optionEx({mandatory:!0},t,e,i,n)}combineFlagAndOptionalValue(t=!0){return this._combineFlagAndOptionalValue=!!t,this}allowUnknownOption(t=!0){return this._allowUnknownOption=!!t,this}allowExcessArguments(t=!0){return this._allowExcessArguments=!!t,this}enablePositionalOptions(t=!0){return this._enablePositionalOptions=!!t,this}passThroughOptions(t=!0){return this._passThroughOptions=!!t,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(t=!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=!!t,this}getOptionValue(t){return this._storeOptionsAsProperties?this[t]:this._optionValues[t]}setOptionValue(t,e){return this.setOptionValueWithSource(t,e,void 0)}setOptionValueWithSource(t,e,i){return this._storeOptionsAsProperties?this[t]=e:this._optionValues[t]=e,this._optionValueSources[t]=i,this}getOptionValueSource(t){return this._optionValueSources[t]}getOptionValueSourceWithGlobals(t){let e;return this._getCommandAndAncestors().forEach(i=>{i.getOptionValueSource(t)!==void 0&&(e=i.getOptionValueSource(t))}),e}_prepareUserArgs(t,e){if(t!==void 0&&!Array.isArray(t))throw new Error("first parameter to parse must be array or undefined");if(e=e||{},t===void 0&&e.from===void 0){m.versions?.electron&&(e.from="electron");let n=m.execArgv??[];(n.includes("-e")||n.includes("--eval")||n.includes("-p")||n.includes("--print"))&&(e.from="eval")}t===void 0&&(t=m.argv),this.rawArgs=t.slice();let i;switch(e.from){case void 0:case"node":this._scriptPath=t[1],i=t.slice(2);break;case"electron":m.defaultApp?(this._scriptPath=t[1],i=t.slice(2)):i=t.slice(1);break;case"user":i=t.slice(0);break;case"eval":i=t.slice(1);break;default:throw new Error(`unexpected parse option { from: '${e.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",i}parse(t,e){this._prepareForParse();let i=this._prepareUserArgs(t,e);return this._parseCommand([],i),this}async parseAsync(t,e){this._prepareForParse();let i=this._prepareUserArgs(t,e);return await this._parseCommand([],i),this}_prepareForParse(){this._savedState===null?(this.options.filter(t=>t.negate&&t.defaultValue===void 0&&this.getOptionValue(t.attributeName())===void 0).forEach(t=>{let e=t.long.replace(/^--no-/,"--");this._findOption(e)||this.setOptionValueWithSource(t.attributeName(),!0,"default")}),this.saveStateBeforeParse()):this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
20
|
+
- either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(t,e,i){if(E.existsSync(t))return;let n=e?`searched for local subcommand relative to directory '${e}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",r=`'${t}' does not exist
|
|
21
21
|
- if '${i}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
22
22
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
23
|
-
- ${n}`;throw new Error(
|
|
23
|
+
- ${n}`;throw new Error(r)}_executeSubCommand(t,e){e=e.slice();let i=[".js",".ts",".tsx",".mjs",".cjs"];function n(l,u){let p=d.resolve(l,u);if(E.existsSync(p))return p;if(i.includes(d.extname(u)))return;let O=i.find(_=>E.existsSync(`${p}${_}`));if(O)return`${p}${O}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=t._executableFile||`${this._name}-${t._name}`,s=this._executableDir||"";if(this._scriptPath){let l;try{l=E.realpathSync(this._scriptPath)}catch{l=this._scriptPath}s=d.resolve(d.dirname(l),s)}if(s){let l=n(s,r);if(!l&&!t._executableFile&&this._scriptPath){let u=d.basename(this._scriptPath,d.extname(this._scriptPath));u!==this._name&&(l=n(s,`${u}-${t._name}`))}r=l||r}let a=i.includes(d.extname(r)),h;m.platform!=="win32"?a?(e.unshift(r),e=P(m.execArgv).concat(e),h=H.spawn(m.argv[0],e,{stdio:"inherit"})):h=H.spawn(r,e,{stdio:"inherit"}):(this._checkForMissingExecutable(r,s,t._name),e.unshift(r),e=P(m.execArgv).concat(e),h=H.spawn(m.execPath,e,{stdio:"inherit"})),h.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(u=>{m.on(u,()=>{h.killed===!1&&h.exitCode===null&&h.kill(u)})});let c=this._exitCallback;h.on("close",l=>{l=l??1,c?c(new f(l,"commander.executeSubCommandAsync","(close)")):m.exit(l)}),h.on("error",l=>{if(l.code==="ENOENT")this._checkForMissingExecutable(r,s,t._name);else if(l.code==="EACCES")throw new Error(`'${r}' not executable`);if(!c)m.exit(1);else{let u=new f(1,"commander.executeSubCommandAsync","(error)");u.nestedError=l,c(u)}}),this.runningCommand=h}_dispatchSubcommand(t,e,i){let n=this._findCommand(t);n||this.help({error:!0}),n._prepareForParse();let r;return r=this._chainOrCallSubCommandHook(r,n,"preSubcommand"),r=this._chainOrCall(r,()=>{if(n._executableHandler)this._executeSubCommand(n,e.concat(i));else return n._parseCommand(e,i)}),r}_dispatchHelpCommand(t){t||this.help();let e=this._findCommand(t);return e&&!e._executableHandler&&e.help(),this._dispatchSubcommand(t,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((t,e)=>{t.required&&this.args[e]==null&&this.missingArgument(t.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let t=(i,n,r)=>{let s=n;if(n!==null&&i.parseArg){let a=`error: command-argument value '${n}' is invalid for argument '${i.name()}'.`;s=this._callParseArg(i,n,r,a)}return s};this._checkNumberOfArguments();let e=[];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,a)=>t(i,a,s),i.defaultValue))):r===void 0&&(r=[]):n<this.args.length&&(r=this.args[n],i.parseArg&&(r=t(i,r,i.defaultValue))),e[n]=r}),this.processedArgs=e}_chainOrCall(t,e){return t?.then&&typeof t.then=="function"?t.then(()=>e()):e()}_chainOrCallHooks(t,e){let i=t,n=[];return this._getCommandAndAncestors().reverse().filter(r=>r._lifeCycleHooks[e]!==void 0).forEach(r=>{r._lifeCycleHooks[e].forEach(s=>{n.push({hookedCommand:r,callback:s})})}),e==="postAction"&&n.reverse(),n.forEach(r=>{i=this._chainOrCall(i,()=>r.callback(r.hookedCommand,this))}),i}_chainOrCallSubCommandHook(t,e,i){let n=t;return this._lifeCycleHooks[i]!==void 0&&this._lifeCycleHooks[i].forEach(r=>{n=this._chainOrCall(n,()=>r(this,e))}),n}_parseCommand(t,e){let i=this.parseOptions(e);if(this._parseOptionsEnv(),this._parseOptionsImplied(),t=t.concat(i.operands),e=i.unknown,this.args=t.concat(e),t&&this._findCommand(t[0]))return this._dispatchSubcommand(t[0],t.slice(1),e);if(this._getHelpCommand()&&t[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(t[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(e),this._dispatchSubcommand(this._defaultCommandName,t,e);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,t,e)})),s=this._chainOrCallHooks(s,"postAction"),s}if(this.parent?.listenerCount(r))n(),this._processArguments(),this.parent.emit(r,t,e);else if(t.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",t,e);this.listenerCount("command:*")?this.emit("command:*",t,e):this.commands.length?this.unknownCommand():(n(),this._processArguments())}else this.commands.length?(n(),this.help({error:!0})):(n(),this._processArguments())}_findCommand(t){if(t)return this.commands.find(e=>e._name===t||e._aliases.includes(t))}_findOption(t){return this.options.find(e=>e.is(t))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(t=>{t.options.forEach(e=>{e.mandatory&&t.getOptionValue(e.attributeName())===void 0&&t.missingMandatoryOptionValue(e)})})}_checkForConflictingLocalOptions(){let t=this.options.filter(i=>{let n=i.attributeName();return this.getOptionValue(n)===void 0?!1:this.getOptionValueSource(n)!=="default"});t.filter(i=>i.conflictsWith.length>0).forEach(i=>{let n=t.find(r=>i.conflictsWith.includes(r.attributeName()));n&&this._conflictingOption(i,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(t=>{t._checkForConflictingLocalOptions()})}parseOptions(t){let e=[],i=[],n=e;function r(l){return l.length>1&&l[0]==="-"}let s=l=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(l)?!this._getCommandAndAncestors().some(u=>u.options.map(p=>p.short).some(p=>/^-\d$/.test(p))):!1,a=null,h=null,c=0;for(;c<t.length||h;){let l=h??t[c++];if(h=null,l==="--"){n===i&&n.push(l),n.push(...t.slice(c));break}if(a&&(!r(l)||s(l))){this.emit(`option:${a.name()}`,l);continue}if(a=null,r(l)){let u=this._findOption(l);if(u){if(u.required){let p=t[c++];p===void 0&&this.optionMissingArgument(u),this.emit(`option:${u.name()}`,p)}else if(u.optional){let p=null;c<t.length&&(!r(t[c])||s(t[c]))&&(p=t[c++]),this.emit(`option:${u.name()}`,p)}else this.emit(`option:${u.name()}`);a=u.variadic?u:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let u=this._findOption(`-${l[1]}`);if(u){u.required||u.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${u.name()}`,l.slice(2)):(this.emit(`option:${u.name()}`),h=`-${l.slice(2)}`);continue}}if(/^--[^=]+=/.test(l)){let u=l.indexOf("="),p=this._findOption(l.slice(0,u));if(p&&(p.required||p.optional)){this.emit(`option:${p.name()}`,l.slice(u+1));continue}}if(n===e&&r(l)&&!(this.commands.length===0&&s(l))&&(n=i),(this._enablePositionalOptions||this._passThroughOptions)&&e.length===0&&i.length===0){if(this._findCommand(l)){e.push(l),i.push(...t.slice(c));break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){e.push(l,...t.slice(c));break}else if(this._defaultCommandName){i.push(l,...t.slice(c));break}}if(this._passThroughOptions){n.push(l,...t.slice(c));break}n.push(l)}return{operands:e,unknown:i}}opts(){if(this._storeOptionsAsProperties){let t={},e=this.options.length;for(let i=0;i<e;i++){let n=this.options[i].attributeName();t[n]=n===this._versionOptionName?this._version:this[n]}return t}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((t,e)=>Object.assign(t,e.opts()),{})}error(t,e){this._outputConfiguration.outputError(`${t}
|
|
24
24
|
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
25
25
|
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
26
|
-
`),this.outputHelp({error:!0}));let i=e||{},n=i.exitCode||1,
|
|
27
|
-
`),this._exit(0,"commander.version",t)}),this}description(t,e){return t===void 0&&e===void 0?this._description:(this._description=t,e&&(this._argsDescription=e),this)}summary(t){return t===void 0?this._summary:(this._summary=t,this)}alias(t){if(t===void 0)return this._aliases[0];let e=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(e=this.commands[this.commands.length-1]),t===e._name)throw new Error("Command alias can't be the same as its name");let i=this.parent?._findCommand(t);if(i){let n=[i.name()].concat(i.aliases()).join("|");throw new Error(`cannot add alias '${t}' to command '${this.name()}' as already have command '${n}'`)}return e._aliases.push(t),this}aliases(t){return t===void 0?this._aliases:(t.forEach(e=>this.alias(e)),this)}usage(t){if(t===void 0){if(this._usage)return this._usage;let e=this.registeredArguments.map(i
|
|
28
|
-
Expecting one of '${i.join("', '")}'`);let n=`${t}Help`;return this.on(n,
|
|
29
|
-
`)}),this}_outputHelpIfRequested(t){let e=this._getHelpOption();e&&t.find(n=>e.is(n))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function
|
|
26
|
+
`),this.outputHelp({error:!0}));let i=e||{},n=i.exitCode||1,r=i.code||"commander.error";this._exit(n,r,t)}_parseOptionsEnv(){this.options.forEach(t=>{if(t.envVar&&t.envVar in m.env){let e=t.attributeName();(this.getOptionValue(e)===void 0||["default","config","env"].includes(this.getOptionValueSource(e)))&&(t.required||t.optional?this.emit(`optionEnv:${t.name()}`,m.env[t.envVar]):this.emit(`optionEnv:${t.name()}`))}})}_parseOptionsImplied(){let t=new v(this.options),e=i=>this.getOptionValue(i)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(i));this.options.filter(i=>i.implied!==void 0&&e(i.attributeName())&&t.valueFromOption(this.getOptionValue(i.attributeName()),i)).forEach(i=>{Object.keys(i.implied).filter(n=>!e(n)).forEach(n=>{this.setOptionValueWithSource(n,i.implied[n],"implied")})})}missingArgument(t){let e=`error: missing required argument '${t}'`;this.error(e,{code:"commander.missingArgument"})}optionMissingArgument(t){let e=`error: option '${t.flags}' argument missing`;this.error(e,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(t){let e=`error: required option '${t.flags}' not specified`;this.error(e,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(t,e){let i=s=>{let a=s.attributeName(),h=this.getOptionValue(a),c=this.options.find(u=>u.negate&&a===u.attributeName()),l=this.options.find(u=>!u.negate&&a===u.attributeName());return c&&(c.presetArg===void 0&&h===!1||c.presetArg!==void 0&&h===c.presetArg)?c:l||s},n=s=>{let a=i(s),h=a.attributeName();return this.getOptionValueSource(h)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},r=`error: ${n(t)} cannot be used with ${n(e)}`;this.error(r,{code:"commander.conflictingOption"})}unknownOption(t){if(this._allowUnknownOption)return;let e="";if(t.startsWith("--")&&this._showSuggestionAfterError){let n=[],r=this;do{let s=r.createHelp().visibleOptions(r).filter(a=>a.long).map(a=>a.long);n=n.concat(s),r=r.parent}while(r&&!r._enablePositionalOptions);e=T(t,n)}let i=`error: unknown option '${t}'${e}`;this.error(i,{code:"commander.unknownOption"})}_excessArguments(t){if(this._allowExcessArguments)return;let e=this.registeredArguments.length,i=e===1?"":"s",n=t.length,r=this.parent?` for '${this.name()}'`:"",s=t.join(", "),a=`error: too many arguments${r}. Expected ${e} argument${i} but got ${n}: ${s}.`;this.error(a,{code:"commander.excessArguments"})}unknownCommand(){let t=this.args[0],e="";if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(r=>{n.push(r.name()),r.alias()&&n.push(r.alias())}),e=T(t,n)}let i=`error: unknown command '${t}'${e}`;this.error(i,{code:"commander.unknownCommand"})}version(t,e,i){if(t===void 0)return this._version;this._version=t,e=e||"-V, --version",i=i||"output the version number";let n=this.createOption(e,i);return this._versionOptionName=n.attributeName(),this._registerOption(n),this.on("option:"+n.name(),()=>{this._outputConfiguration.writeOut(`${t}
|
|
27
|
+
`),this._exit(0,"commander.version",t)}),this}description(t,e){return t===void 0&&e===void 0?this._description:(this._description=t,e&&(this._argsDescription=e),this)}summary(t){return t===void 0?this._summary:(this._summary=t,this)}alias(t){if(t===void 0)return this._aliases[0];let e=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(e=this.commands[this.commands.length-1]),t===e._name)throw new Error("Command alias can't be the same as its name");let i=this.parent?._findCommand(t);if(i){let n=[i.name()].concat(i.aliases()).join("|");throw new Error(`cannot add alias '${t}' to command '${this.name()}' as already have command '${n}'`)}return e._aliases.push(t),this}aliases(t){return t===void 0?this._aliases:(t.forEach(e=>this.alias(e)),this)}usage(t){if(t===void 0){if(this._usage)return this._usage;let e=this.registeredArguments.map(i=>$(i));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?e:[]).join(" ")}return this._usage=t,this}name(t){return t===void 0?this._name:(this._name=t,this)}helpGroup(t){return t===void 0?this._helpGroupHeading??"":(this._helpGroupHeading=t,this)}commandsGroup(t){return t===void 0?this._defaultCommandGroup??"":(this._defaultCommandGroup=t,this)}optionsGroup(t){return t===void 0?this._defaultOptionGroup??"":(this._defaultOptionGroup=t,this)}_initOptionGroup(t){this._defaultOptionGroup&&!t.helpGroupHeading&&t.helpGroup(this._defaultOptionGroup)}_initCommandGroup(t){this._defaultCommandGroup&&!t.helpGroup()&&t.helpGroup(this._defaultCommandGroup)}nameFromFilename(t){return this._name=d.basename(t,d.extname(t)),this}executableDir(t){return t===void 0?this._executableDir:(this._executableDir=t,this)}helpInformation(t){let e=this.createHelp(),i=this._getOutputContext(t);e.prepareContext({error:i.error,helpWidth:i.helpWidth,outputHasColors:i.hasColors});let n=e.formatHelp(this,e);return i.hasColors?n:this._outputConfiguration.stripColor(n)}_getOutputContext(t){t=t||{};let e=!!t.error,i,n,r;return e?(i=a=>this._outputConfiguration.writeErr(a),n=this._outputConfiguration.getErrHasColors(),r=this._outputConfiguration.getErrHelpWidth()):(i=a=>this._outputConfiguration.writeOut(a),n=this._outputConfiguration.getOutHasColors(),r=this._outputConfiguration.getOutHelpWidth()),{error:e,write:a=>(n||(a=this._outputConfiguration.stripColor(a)),i(a)),hasColors:n,helpWidth:r}}outputHelp(t){let e;typeof t=="function"&&(e=t,t=void 0);let i=this._getOutputContext(t),n={error:i.error,write:i.write,command:this};this._getCommandAndAncestors().reverse().forEach(s=>s.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let r=this.helpInformation({error:i.error});if(e&&(r=e(r),typeof r!="string"&&!Buffer.isBuffer(r)))throw new Error("outputHelp callback must return a string or a Buffer");i.write(r),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(s=>s.emit("afterAllHelp",n))}helpOption(t,e){return typeof t=="boolean"?(t?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(t??"-h, --help",e??"display help for command"),(t||e)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(t){return this._helpOption=t,this._initOptionGroup(t),this}help(t){this.outputHelp(t);let e=Number(m.exitCode??0);e===0&&t&&typeof t!="function"&&t.error&&(e=1),this._exit(e,"commander.help","(outputHelp)")}addHelpText(t,e){let i=["beforeAll","before","after","afterAll"];if(!i.includes(t))throw new Error(`Unexpected value for position to addHelpText.
|
|
28
|
+
Expecting one of '${i.join("', '")}'`);let n=`${t}Help`;return this.on(n,r=>{let s;typeof e=="function"?s=e({error:r.error,command:r.command}):s=e,s&&r.write(`${s}
|
|
29
|
+
`)}),this}_outputHelpIfRequested(t){let e=this._getHelpOption();e&&t.find(n=>e.is(n))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function P(o){return o.map(t=>{if(!t.startsWith("--inspect"))return t;let e,i="127.0.0.1",n="9229",r;return(r=t.match(/^(--inspect(-brk)?)$/))!==null?e=r[1]:(r=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(e=r[1],/^\d+$/.test(r[3])?n=r[3]:i=r[3]):(r=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(e=r[1],i=r[3],n=r[4]),e&&n!=="0"?`${e}=${i}:${parseInt(n)+1}`:t})}function W(){if(m.env.NO_COLOR||m.env.FORCE_COLOR==="0"||m.env.FORCE_COLOR==="false")return!1;if(m.env.FORCE_COLOR||m.env.CLICOLOR_FORCE!==void 0)return!0}var A=new g;import{readFileSync as xt}from"fs";import{resolve as yt}from"path";var F=["section","article","aside","nav","header","footer","address","h1","h2","h3","h4","h5","h6","p","hr","pre","blockquote","ol","ul","li","dl","dt","dd","figure","figcaption","div","a","span","br","wbr","b","strong","i","em","u","s","mark","small","sub","sup","abbr","cite","code","var","kbd","samp","time","data","dfn","q","ruby","rt","rp","bdi","bdo","ins","del","img","iframe","embed","object","param","picture","source","track","video","audio","map","area","table","caption","colgroup","col","tbody","thead","tfoot","tr","td","th","form","label","input","button","select","datalist","optgroup","option","textarea","output","progress","meter","fieldset","legend","details","summary","dialog","template","slot","canvas"];var k=["annotation-xml","color-profile","font-face","font-face-src","font-face-uri","font-face-format","font-face-name","missing-glyph"];function G(o){if(!/^[a-z][a-z0-9._\-]*-[a-z0-9._\-]*$/.test(o))throw new Error(`Tag <${o}> is not a valid custom element name. Custom element names must:
|
|
30
|
+
- contain a hyphen
|
|
31
|
+
- no spaces.
|
|
32
|
+
- start with a lowercase letter.
|
|
33
|
+
- not contain uppercase letters.
|
|
34
|
+
- not contain the following chars: '@', '#', '$', '%', '&', '*', '!', '?', '/', '\\', '|', "'", '"', '<', '>', '='
|
|
35
|
+
`);if(it(o))throw new Error(`Tag <${o}> is a native HTML tag and cannot be used as a custom element name.`);if(nt(o))throw new Error(`Tag <${o}> is a reserved tag name and cannot be used as a custom element name.
|
|
36
|
+
Reserved names are:
|
|
37
|
+
- ${k.join(`
|
|
38
|
+
- `)}`)}function it(o){return F.includes(o)}function nt(o){return k.includes(o)}import{existsSync as rt,mkdirSync as st,rmSync as ot,writeFileSync as at}from"fs";import{join as N}from"path";function w(o){return o.replace(/[-_](.)/g,(t,e)=>e.toUpperCase()).replace(/^(.)/,(t,e)=>e.toUpperCase())}function S(o,t,e,i){let n=N(t,o);i??="css",rt(n)&&(e?(console.log(`Deleting "${o}"...`),ot(n,{recursive:!0,force:!0}),console.log("\u2714 Component Deleted.")):(console.error(`\u2716 Directory "${o}" already exists.`),process.exit(1))),st(n,{recursive:!0}),G(o);let r=[[`${o}.xd.component.ts`,lt(o,i)],[`${o}.xd.component.html`,ut(o)],[`${o}.xd.component.${i}`,ht(o)],[`${o}.xd.component.spec.ts`,ct(o)]];for(let[s,a]of r)at(N(n,s),a,"utf8");console.log(),console.log(`\u2714 Component "${o}" generated:`);for(let[s]of r)console.log(`${o}/${s}`)}function lt(o,t){let e=w(o);return`import { BaseWebComponent, WebComponent } from '@xaendar/core';
|
|
30
39
|
|
|
31
40
|
@WebComponent({
|
|
32
|
-
selector: '${
|
|
33
|
-
styleUrl: './${
|
|
34
|
-
templateUrl: './${
|
|
41
|
+
selector: '${o}',
|
|
42
|
+
styleUrl: './${o}.xd.component.${t}',
|
|
43
|
+
templateUrl: './${o}.xd.component.html'
|
|
35
44
|
})
|
|
36
45
|
export class ${e}Component extends BaseWebComponent {
|
|
37
46
|
|
|
38
|
-
}`}function
|
|
39
|
-
`}function
|
|
40
|
-
`}function
|
|
41
|
-
import { ${t}Component } from './${
|
|
47
|
+
}`}function ut(o){return`<p>${o} works!</p>
|
|
48
|
+
`}function ht(o){return`/* component styles */
|
|
49
|
+
`}function ct(o){let t=w(o);return`import { describe, expect, it } from "vitest";
|
|
50
|
+
import { ${t}Component } from './${o}.xd.component';
|
|
42
51
|
|
|
43
52
|
describe('${t}Component', () => {
|
|
44
53
|
it('should create', () => {
|
|
@@ -46,22 +55,22 @@ describe('${t}Component', () => {
|
|
|
46
55
|
expect(component).toBeTruthy();
|
|
47
56
|
});
|
|
48
57
|
});
|
|
49
|
-
`}function
|
|
58
|
+
`}function I(){let o=new g("generate").alias("g").description("Generate Xaendar building blocks");return o.command("component <name>").alias("c").option("-p, --path <path>","Custom path for the generated component (default: current directory)").option("-f, --force","Force generation deleting current component if already exists").description("Generate a new component (creates <name>/ folder with .ts, .html, .css, .spec.ts)").action((t,e)=>{let i=e.path||process.cwd();S(t,i,!!e.force)}),o}import{existsSync as ft,mkdirSync as K,readdirSync as gt,writeFileSync as _t}from"fs";import{resolve as V}from"path/win32";import{readFileSync as pt}from"fs";import{resolve as mt}from"path";function j(o){return`<!DOCTYPE html>
|
|
50
59
|
<html lang="en">
|
|
51
60
|
<head>
|
|
52
61
|
<meta charset="UTF-8" />
|
|
53
62
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
54
|
-
<title>${
|
|
63
|
+
<title>${o}</title>
|
|
55
64
|
<script type="module" src="./signals.ts"></script>
|
|
56
65
|
<script type="module" src="./main.ts"></script>
|
|
57
66
|
</head>
|
|
58
67
|
<body>
|
|
59
|
-
<${
|
|
68
|
+
<${o}></${o}>
|
|
60
69
|
</body>
|
|
61
|
-
</html>`}function
|
|
70
|
+
</html>`}function M(o){let t=`${w(o)}Component`;return`import { ${t} } from './${o}/${o}.xd.component';
|
|
62
71
|
|
|
63
|
-
console.log(${t});`}function
|
|
64
|
-
"name": "${
|
|
72
|
+
console.log(${t});`}function L(o,t){return`{
|
|
73
|
+
"name": "${o}",
|
|
65
74
|
"version": "0.0.1",
|
|
66
75
|
"private": true,
|
|
67
76
|
"scripts": {
|
|
@@ -86,9 +95,9 @@ console.log(${t});`}function ct(r,t){return`{
|
|
|
86
95
|
"vitest": "^4.1.8"
|
|
87
96
|
}
|
|
88
97
|
}
|
|
89
|
-
`}function
|
|
98
|
+
`}function q(){return`import { loadSignals } from "@xaendar/signals";
|
|
90
99
|
|
|
91
|
-
loadSignals();`}function
|
|
100
|
+
loadSignals();`}function U(){return`{
|
|
92
101
|
"compilerOptions": {
|
|
93
102
|
"target": "ESNext",
|
|
94
103
|
"module": "ESNext",
|
|
@@ -117,7 +126,7 @@ loadSignals();`}function mt(){return`{
|
|
|
117
126
|
"node_modules",
|
|
118
127
|
"**/*.spec.ts"
|
|
119
128
|
]
|
|
120
|
-
}`}function
|
|
129
|
+
}`}function R(){return`import babel from "@rolldown/plugin-babel";
|
|
121
130
|
import { xaendarPlugin } from "@xaendar/build-tools";
|
|
122
131
|
import { defineConfig } from 'vite';
|
|
123
132
|
|
|
@@ -149,8 +158,8 @@ export default defineConfig({
|
|
|
149
158
|
}),
|
|
150
159
|
xaendarPlugin()
|
|
151
160
|
]
|
|
152
|
-
});`}function
|
|
153
|
-
"name": "${
|
|
161
|
+
});`}function B(o,t){return`{
|
|
162
|
+
"name": "${o}",
|
|
154
163
|
"entry": "src/main.ts",
|
|
155
164
|
"outDir": "dist",
|
|
156
165
|
"assetsDir": "assets",
|
|
@@ -159,4 +168,4 @@ export default defineConfig({
|
|
|
159
168
|
"style": "${t}"
|
|
160
169
|
}
|
|
161
170
|
}
|
|
162
|
-
}`}function
|
|
171
|
+
}`}function dt(){try{let o=JSON.parse(pt(mt(import.meta.filename,"..","../package.json"),"utf8"));if(!o.version)throw new Error("Unable to determine Xaendar CLI version.");return o.version}catch(o){console.error("Error reading Xaendar CLI version:",o),process.exit(1)}}function J(o){let t=dt(),e=o.name,i=`${e}-root`;return[{type:"file",name:"package.json",content:L(e,t)},{type:"file",name:"xaendar.json",content:B(e,o.style)},{type:"file",name:"vite.config.ts",content:R()},{type:"file",name:"tsconfig.json",content:U()},{type:"directory",name:"src",children:[{type:"file",name:"index.html",content:j(i)},{type:"file",name:"signals.ts",content:q()},{type:"file",name:"main.ts",content:M(i)},{type:"generateComponent",name:i}]}]}import{execSync as Ct}from"child_process";function X(){return new g("new").description("Scaffold a new Xaendar project").argument("<name>","Name of the project to create").option("-p, --path <path>","Custom path for the generated project (default: current directory)").option("-s, --style <style>","CSS preprocessor to use (css, scss, less, styl)","css").action((o,t)=>{let e=Ot(t.style),i=t.path||process.cwd(),n=V(i,o);bt(n),Y(J({name:o,style:e}),n,e),Ct("npm i",{stdio:"inherit",cwd:n})})}function Ot(o){let t=["css","scss","less","styl"];return o?(t.includes(o)||(console.error(`\u2716 Invalid style option: ${o}`),process.exit(1)),o):"css"}function bt(o){let t=ft(o);t&>(o).length&&(console.error(`\u2716 Cannot create project: target directory is not empty: ${o}`),process.exit(1)),t||K(o)}function Y(o,t,e){o.forEach(i=>{switch(i.type){case"file":case void 0:let n=i.content;_t(V(t,i.name),n,"utf8");break;case"directory":let r=V(t,i.name);K(r),i.children&&Y(i.children,r,e);break;case"generateComponent":S(i.name,t,!1,e);break}})}var At=JSON.parse(xt(yt(import.meta.filename,"..","../package.json"),"utf-8")).version;A.name("xd").description("Xaendar CLI").version(At);A.addCommand(I());A.addCommand(X());A.parse();
|