cdk-booster 1.0.1

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 (53) hide show
  1. package/LICENSE +353 -0
  2. package/LICENSE.md +350 -0
  3. package/README.md +114 -0
  4. package/dist/cdk-booster.d.ts +29 -0
  5. package/dist/cdk-booster.mjs +733 -0
  6. package/dist/cdkFrameworkWorker.mjs +50 -0
  7. package/dist/configuration.d.ts +16 -0
  8. package/dist/configuration.mjs +29 -0
  9. package/dist/constants.d.ts +1 -0
  10. package/dist/constants.mjs +3 -0
  11. package/dist/getConfigFromCliArgs.d.ts +7 -0
  12. package/dist/getConfigFromCliArgs.mjs +23 -0
  13. package/dist/getDirname.d.ts +10 -0
  14. package/dist/getDirname.mjs +19 -0
  15. package/dist/logger.d.ts +51 -0
  16. package/dist/logger.mjs +83 -0
  17. package/dist/types/bundleSettings.d.ts +6 -0
  18. package/dist/types/bundleSettings.mjs +1 -0
  19. package/dist/types/cbConfig.d.ts +8 -0
  20. package/dist/types/cbConfig.mjs +1 -0
  21. package/dist/types/lambdaBundle.d.ts +11 -0
  22. package/dist/types/lambdaBundle.mjs +1 -0
  23. package/dist/utils/findPackageJson.d.ts +6 -0
  24. package/dist/utils/findPackageJson.mjs +33 -0
  25. package/dist/version.d.ts +5 -0
  26. package/dist/version.mjs +25 -0
  27. package/node_modules/chalk/license +9 -0
  28. package/node_modules/chalk/package.json +83 -0
  29. package/node_modules/chalk/readme.md +297 -0
  30. package/node_modules/chalk/source/index.d.ts +325 -0
  31. package/node_modules/chalk/source/index.js +225 -0
  32. package/node_modules/chalk/source/utilities.js +33 -0
  33. package/node_modules/chalk/source/vendor/ansi-styles/index.d.ts +236 -0
  34. package/node_modules/chalk/source/vendor/ansi-styles/index.js +223 -0
  35. package/node_modules/chalk/source/vendor/supports-color/browser.d.ts +1 -0
  36. package/node_modules/chalk/source/vendor/supports-color/browser.js +34 -0
  37. package/node_modules/chalk/source/vendor/supports-color/index.d.ts +55 -0
  38. package/node_modules/chalk/source/vendor/supports-color/index.js +190 -0
  39. package/node_modules/commander/LICENSE +22 -0
  40. package/node_modules/commander/Readme.md +1159 -0
  41. package/node_modules/commander/esm.mjs +16 -0
  42. package/node_modules/commander/index.js +24 -0
  43. package/node_modules/commander/lib/argument.js +149 -0
  44. package/node_modules/commander/lib/command.js +2778 -0
  45. package/node_modules/commander/lib/error.js +39 -0
  46. package/node_modules/commander/lib/help.js +747 -0
  47. package/node_modules/commander/lib/option.js +379 -0
  48. package/node_modules/commander/lib/suggestSimilar.js +101 -0
  49. package/node_modules/commander/package-support.json +16 -0
  50. package/node_modules/commander/package.json +82 -0
  51. package/node_modules/commander/typings/esm.d.mts +3 -0
  52. package/node_modules/commander/typings/index.d.ts +1113 -0
  53. package/package.json +100 -0
@@ -0,0 +1,2778 @@
1
+ const EventEmitter = require('node:events').EventEmitter;
2
+ const childProcess = require('node:child_process');
3
+ const path = require('node:path');
4
+ const fs = require('node:fs');
5
+ const process = require('node:process');
6
+
7
+ const { Argument, humanReadableArgName } = require('./argument.js');
8
+ const { CommanderError } = require('./error.js');
9
+ const { Help, stripColor } = require('./help.js');
10
+ const { Option, DualOptions } = require('./option.js');
11
+ const { suggestSimilar } = require('./suggestSimilar');
12
+
13
+ class Command extends EventEmitter {
14
+ /**
15
+ * Initialize a new `Command`.
16
+ *
17
+ * @param {string} [name]
18
+ */
19
+
20
+ constructor(name) {
21
+ super();
22
+ /** @type {Command[]} */
23
+ this.commands = [];
24
+ /** @type {Option[]} */
25
+ this.options = [];
26
+ this.parent = null;
27
+ this._allowUnknownOption = false;
28
+ this._allowExcessArguments = false;
29
+ /** @type {Argument[]} */
30
+ this.registeredArguments = [];
31
+ this._args = this.registeredArguments; // deprecated old name
32
+ /** @type {string[]} */
33
+ this.args = []; // cli args with options removed
34
+ this.rawArgs = [];
35
+ this.processedArgs = []; // like .args but after custom processing and collecting variadic
36
+ this._scriptPath = null;
37
+ this._name = name || '';
38
+ this._optionValues = {};
39
+ this._optionValueSources = {}; // default, env, cli etc
40
+ this._storeOptionsAsProperties = false;
41
+ this._actionHandler = null;
42
+ this._executableHandler = false;
43
+ this._executableFile = null; // custom name for executable
44
+ this._executableDir = null; // custom search directory for subcommands
45
+ this._defaultCommandName = null;
46
+ this._exitCallback = null;
47
+ this._aliases = [];
48
+ this._combineFlagAndOptionalValue = true;
49
+ this._description = '';
50
+ this._summary = '';
51
+ this._argsDescription = undefined; // legacy
52
+ this._enablePositionalOptions = false;
53
+ this._passThroughOptions = false;
54
+ this._lifeCycleHooks = {}; // a hash of arrays
55
+ /** @type {(boolean | string)} */
56
+ this._showHelpAfterError = false;
57
+ this._showSuggestionAfterError = true;
58
+ this._savedState = null; // used in save/restoreStateBeforeParse
59
+
60
+ // see configureOutput() for docs
61
+ this._outputConfiguration = {
62
+ writeOut: (str) => process.stdout.write(str),
63
+ writeErr: (str) => process.stderr.write(str),
64
+ outputError: (str, write) => write(str),
65
+ getOutHelpWidth: () =>
66
+ process.stdout.isTTY ? process.stdout.columns : undefined,
67
+ getErrHelpWidth: () =>
68
+ process.stderr.isTTY ? process.stderr.columns : undefined,
69
+ getOutHasColors: () =>
70
+ useColor() ?? (process.stdout.isTTY && process.stdout.hasColors?.()),
71
+ getErrHasColors: () =>
72
+ useColor() ?? (process.stderr.isTTY && process.stderr.hasColors?.()),
73
+ stripColor: (str) => stripColor(str),
74
+ };
75
+
76
+ this._hidden = false;
77
+ /** @type {(Option | null | undefined)} */
78
+ this._helpOption = undefined; // Lazy created on demand. May be null if help option is disabled.
79
+ this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited
80
+ /** @type {Command} */
81
+ this._helpCommand = undefined; // lazy initialised, inherited
82
+ this._helpConfiguration = {};
83
+ /** @type {string | undefined} */
84
+ this._helpGroupHeading = undefined; // soft initialised when added to parent
85
+ /** @type {string | undefined} */
86
+ this._defaultCommandGroup = undefined;
87
+ /** @type {string | undefined} */
88
+ this._defaultOptionGroup = undefined;
89
+ }
90
+
91
+ /**
92
+ * Copy settings that are useful to have in common across root command and subcommands.
93
+ *
94
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
95
+ *
96
+ * @param {Command} sourceCommand
97
+ * @return {Command} `this` command for chaining
98
+ */
99
+ copyInheritedSettings(sourceCommand) {
100
+ this._outputConfiguration = sourceCommand._outputConfiguration;
101
+ this._helpOption = sourceCommand._helpOption;
102
+ this._helpCommand = sourceCommand._helpCommand;
103
+ this._helpConfiguration = sourceCommand._helpConfiguration;
104
+ this._exitCallback = sourceCommand._exitCallback;
105
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
106
+ this._combineFlagAndOptionalValue =
107
+ sourceCommand._combineFlagAndOptionalValue;
108
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
109
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
110
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
111
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
112
+
113
+ return this;
114
+ }
115
+
116
+ /**
117
+ * @returns {Command[]}
118
+ * @private
119
+ */
120
+
121
+ _getCommandAndAncestors() {
122
+ const result = [];
123
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
124
+ for (let command = this; command; command = command.parent) {
125
+ result.push(command);
126
+ }
127
+ return result;
128
+ }
129
+
130
+ /**
131
+ * Define a command.
132
+ *
133
+ * There are two styles of command: pay attention to where to put the description.
134
+ *
135
+ * @example
136
+ * // Command implemented using action handler (description is supplied separately to `.command`)
137
+ * program
138
+ * .command('clone <source> [destination]')
139
+ * .description('clone a repository into a newly created directory')
140
+ * .action((source, destination) => {
141
+ * console.log('clone command called');
142
+ * });
143
+ *
144
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
145
+ * program
146
+ * .command('start <service>', 'start named service')
147
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
148
+ *
149
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
150
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
151
+ * @param {object} [execOpts] - configuration options (for executable)
152
+ * @return {Command} returns new command for action handler, or `this` for executable command
153
+ */
154
+
155
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
156
+ let desc = actionOptsOrExecDesc;
157
+ let opts = execOpts;
158
+ if (typeof desc === 'object' && desc !== null) {
159
+ opts = desc;
160
+ desc = null;
161
+ }
162
+ opts = opts || {};
163
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
164
+
165
+ const cmd = this.createCommand(name);
166
+ if (desc) {
167
+ cmd.description(desc);
168
+ cmd._executableHandler = true;
169
+ }
170
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
171
+ cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden
172
+ cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor
173
+ if (args) cmd.arguments(args);
174
+ this._registerCommand(cmd);
175
+ cmd.parent = this;
176
+ cmd.copyInheritedSettings(this);
177
+
178
+ if (desc) return this;
179
+ return cmd;
180
+ }
181
+
182
+ /**
183
+ * Factory routine to create a new unattached command.
184
+ *
185
+ * See .command() for creating an attached subcommand, which uses this routine to
186
+ * create the command. You can override createCommand to customise subcommands.
187
+ *
188
+ * @param {string} [name]
189
+ * @return {Command} new command
190
+ */
191
+
192
+ createCommand(name) {
193
+ return new Command(name);
194
+ }
195
+
196
+ /**
197
+ * You can customise the help with a subclass of Help by overriding createHelp,
198
+ * or by overriding Help properties using configureHelp().
199
+ *
200
+ * @return {Help}
201
+ */
202
+
203
+ createHelp() {
204
+ return Object.assign(new Help(), this.configureHelp());
205
+ }
206
+
207
+ /**
208
+ * You can customise the help by overriding Help properties using configureHelp(),
209
+ * or with a subclass of Help by overriding createHelp().
210
+ *
211
+ * @param {object} [configuration] - configuration options
212
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
213
+ */
214
+
215
+ configureHelp(configuration) {
216
+ if (configuration === undefined) return this._helpConfiguration;
217
+
218
+ this._helpConfiguration = configuration;
219
+ return this;
220
+ }
221
+
222
+ /**
223
+ * The default output goes to stdout and stderr. You can customise this for special
224
+ * applications. You can also customise the display of errors by overriding outputError.
225
+ *
226
+ * The configuration properties are all functions:
227
+ *
228
+ * // change how output being written, defaults to stdout and stderr
229
+ * writeOut(str)
230
+ * writeErr(str)
231
+ * // change how output being written for errors, defaults to writeErr
232
+ * outputError(str, write) // used for displaying errors and not used for displaying help
233
+ * // specify width for wrapping help
234
+ * getOutHelpWidth()
235
+ * getErrHelpWidth()
236
+ * // color support, currently only used with Help
237
+ * getOutHasColors()
238
+ * getErrHasColors()
239
+ * stripColor() // used to remove ANSI escape codes if output does not have colors
240
+ *
241
+ * @param {object} [configuration] - configuration options
242
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
243
+ */
244
+
245
+ configureOutput(configuration) {
246
+ if (configuration === undefined) return this._outputConfiguration;
247
+
248
+ this._outputConfiguration = Object.assign(
249
+ {},
250
+ this._outputConfiguration,
251
+ configuration,
252
+ );
253
+ return this;
254
+ }
255
+
256
+ /**
257
+ * Display the help or a custom message after an error occurs.
258
+ *
259
+ * @param {(boolean|string)} [displayHelp]
260
+ * @return {Command} `this` command for chaining
261
+ */
262
+ showHelpAfterError(displayHelp = true) {
263
+ if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;
264
+ this._showHelpAfterError = displayHelp;
265
+ return this;
266
+ }
267
+
268
+ /**
269
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
270
+ *
271
+ * @param {boolean} [displaySuggestion]
272
+ * @return {Command} `this` command for chaining
273
+ */
274
+ showSuggestionAfterError(displaySuggestion = true) {
275
+ this._showSuggestionAfterError = !!displaySuggestion;
276
+ return this;
277
+ }
278
+
279
+ /**
280
+ * Add a prepared subcommand.
281
+ *
282
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
283
+ *
284
+ * @param {Command} cmd - new subcommand
285
+ * @param {object} [opts] - configuration options
286
+ * @return {Command} `this` command for chaining
287
+ */
288
+
289
+ addCommand(cmd, opts) {
290
+ if (!cmd._name) {
291
+ throw new Error(`Command passed to .addCommand() must have a name
292
+ - specify the name in Command constructor or using .name()`);
293
+ }
294
+
295
+ opts = opts || {};
296
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
297
+ if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation
298
+
299
+ this._registerCommand(cmd);
300
+ cmd.parent = this;
301
+ cmd._checkForBrokenPassThrough();
302
+
303
+ return this;
304
+ }
305
+
306
+ /**
307
+ * Factory routine to create a new unattached argument.
308
+ *
309
+ * See .argument() for creating an attached argument, which uses this routine to
310
+ * create the argument. You can override createArgument to return a custom argument.
311
+ *
312
+ * @param {string} name
313
+ * @param {string} [description]
314
+ * @return {Argument} new argument
315
+ */
316
+
317
+ createArgument(name, description) {
318
+ return new Argument(name, description);
319
+ }
320
+
321
+ /**
322
+ * Define argument syntax for command.
323
+ *
324
+ * The default is that the argument is required, and you can explicitly
325
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
326
+ *
327
+ * @example
328
+ * program.argument('<input-file>');
329
+ * program.argument('[output-file]');
330
+ *
331
+ * @param {string} name
332
+ * @param {string} [description]
333
+ * @param {(Function|*)} [parseArg] - custom argument processing function or default value
334
+ * @param {*} [defaultValue]
335
+ * @return {Command} `this` command for chaining
336
+ */
337
+ argument(name, description, parseArg, defaultValue) {
338
+ const argument = this.createArgument(name, description);
339
+ if (typeof parseArg === 'function') {
340
+ argument.default(defaultValue).argParser(parseArg);
341
+ } else {
342
+ argument.default(parseArg);
343
+ }
344
+ this.addArgument(argument);
345
+ return this;
346
+ }
347
+
348
+ /**
349
+ * Define argument syntax for command, adding multiple at once (without descriptions).
350
+ *
351
+ * See also .argument().
352
+ *
353
+ * @example
354
+ * program.arguments('<cmd> [env]');
355
+ *
356
+ * @param {string} names
357
+ * @return {Command} `this` command for chaining
358
+ */
359
+
360
+ arguments(names) {
361
+ names
362
+ .trim()
363
+ .split(/ +/)
364
+ .forEach((detail) => {
365
+ this.argument(detail);
366
+ });
367
+ return this;
368
+ }
369
+
370
+ /**
371
+ * Define argument syntax for command, adding a prepared argument.
372
+ *
373
+ * @param {Argument} argument
374
+ * @return {Command} `this` command for chaining
375
+ */
376
+ addArgument(argument) {
377
+ const previousArgument = this.registeredArguments.slice(-1)[0];
378
+ if (previousArgument && previousArgument.variadic) {
379
+ throw new Error(
380
+ `only the last argument can be variadic '${previousArgument.name()}'`,
381
+ );
382
+ }
383
+ if (
384
+ argument.required &&
385
+ argument.defaultValue !== undefined &&
386
+ argument.parseArg === undefined
387
+ ) {
388
+ throw new Error(
389
+ `a default value for a required argument is never used: '${argument.name()}'`,
390
+ );
391
+ }
392
+ this.registeredArguments.push(argument);
393
+ return this;
394
+ }
395
+
396
+ /**
397
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
398
+ *
399
+ * @example
400
+ * program.helpCommand('help [cmd]');
401
+ * program.helpCommand('help [cmd]', 'show help');
402
+ * program.helpCommand(false); // suppress default help command
403
+ * program.helpCommand(true); // add help command even if no subcommands
404
+ *
405
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
406
+ * @param {string} [description] - custom description
407
+ * @return {Command} `this` command for chaining
408
+ */
409
+
410
+ helpCommand(enableOrNameAndArgs, description) {
411
+ if (typeof enableOrNameAndArgs === 'boolean') {
412
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
413
+ if (enableOrNameAndArgs && this._defaultCommandGroup) {
414
+ // make the command to store the group
415
+ this._initCommandGroup(this._getHelpCommand());
416
+ }
417
+ return this;
418
+ }
419
+
420
+ const nameAndArgs = enableOrNameAndArgs ?? 'help [command]';
421
+ const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);
422
+ const helpDescription = description ?? 'display help for command';
423
+
424
+ const helpCommand = this.createCommand(helpName);
425
+ helpCommand.helpOption(false);
426
+ if (helpArgs) helpCommand.arguments(helpArgs);
427
+ if (helpDescription) helpCommand.description(helpDescription);
428
+
429
+ this._addImplicitHelpCommand = true;
430
+ this._helpCommand = helpCommand;
431
+ // init group unless lazy create
432
+ if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);
433
+
434
+ return this;
435
+ }
436
+
437
+ /**
438
+ * Add prepared custom help command.
439
+ *
440
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
441
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
442
+ * @return {Command} `this` command for chaining
443
+ */
444
+ addHelpCommand(helpCommand, deprecatedDescription) {
445
+ // If not passed an object, call through to helpCommand for backwards compatibility,
446
+ // as addHelpCommand was originally used like helpCommand is now.
447
+ if (typeof helpCommand !== 'object') {
448
+ this.helpCommand(helpCommand, deprecatedDescription);
449
+ return this;
450
+ }
451
+
452
+ this._addImplicitHelpCommand = true;
453
+ this._helpCommand = helpCommand;
454
+ this._initCommandGroup(helpCommand);
455
+ return this;
456
+ }
457
+
458
+ /**
459
+ * Lazy create help command.
460
+ *
461
+ * @return {(Command|null)}
462
+ * @package
463
+ */
464
+ _getHelpCommand() {
465
+ const hasImplicitHelpCommand =
466
+ this._addImplicitHelpCommand ??
467
+ (this.commands.length &&
468
+ !this._actionHandler &&
469
+ !this._findCommand('help'));
470
+
471
+ if (hasImplicitHelpCommand) {
472
+ if (this._helpCommand === undefined) {
473
+ this.helpCommand(undefined, undefined); // use default name and description
474
+ }
475
+ return this._helpCommand;
476
+ }
477
+ return null;
478
+ }
479
+
480
+ /**
481
+ * Add hook for life cycle event.
482
+ *
483
+ * @param {string} event
484
+ * @param {Function} listener
485
+ * @return {Command} `this` command for chaining
486
+ */
487
+
488
+ hook(event, listener) {
489
+ const allowedValues = ['preSubcommand', 'preAction', 'postAction'];
490
+ if (!allowedValues.includes(event)) {
491
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
492
+ Expecting one of '${allowedValues.join("', '")}'`);
493
+ }
494
+ if (this._lifeCycleHooks[event]) {
495
+ this._lifeCycleHooks[event].push(listener);
496
+ } else {
497
+ this._lifeCycleHooks[event] = [listener];
498
+ }
499
+ return this;
500
+ }
501
+
502
+ /**
503
+ * Register callback to use as replacement for calling process.exit.
504
+ *
505
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
506
+ * @return {Command} `this` command for chaining
507
+ */
508
+
509
+ exitOverride(fn) {
510
+ if (fn) {
511
+ this._exitCallback = fn;
512
+ } else {
513
+ this._exitCallback = (err) => {
514
+ if (err.code !== 'commander.executeSubCommandAsync') {
515
+ throw err;
516
+ } else {
517
+ // Async callback from spawn events, not useful to throw.
518
+ }
519
+ };
520
+ }
521
+ return this;
522
+ }
523
+
524
+ /**
525
+ * Call process.exit, and _exitCallback if defined.
526
+ *
527
+ * @param {number} exitCode exit code for using with process.exit
528
+ * @param {string} code an id string representing the error
529
+ * @param {string} message human-readable description of the error
530
+ * @return never
531
+ * @private
532
+ */
533
+
534
+ _exit(exitCode, code, message) {
535
+ if (this._exitCallback) {
536
+ this._exitCallback(new CommanderError(exitCode, code, message));
537
+ // Expecting this line is not reached.
538
+ }
539
+ process.exit(exitCode);
540
+ }
541
+
542
+ /**
543
+ * Register callback `fn` for the command.
544
+ *
545
+ * @example
546
+ * program
547
+ * .command('serve')
548
+ * .description('start service')
549
+ * .action(function() {
550
+ * // do work here
551
+ * });
552
+ *
553
+ * @param {Function} fn
554
+ * @return {Command} `this` command for chaining
555
+ */
556
+
557
+ action(fn) {
558
+ const listener = (args) => {
559
+ // The .action callback takes an extra parameter which is the command or options.
560
+ const expectedArgsCount = this.registeredArguments.length;
561
+ const actionArgs = args.slice(0, expectedArgsCount);
562
+ if (this._storeOptionsAsProperties) {
563
+ actionArgs[expectedArgsCount] = this; // backwards compatible "options"
564
+ } else {
565
+ actionArgs[expectedArgsCount] = this.opts();
566
+ }
567
+ actionArgs.push(this);
568
+
569
+ return fn.apply(this, actionArgs);
570
+ };
571
+ this._actionHandler = listener;
572
+ return this;
573
+ }
574
+
575
+ /**
576
+ * Factory routine to create a new unattached option.
577
+ *
578
+ * See .option() for creating an attached option, which uses this routine to
579
+ * create the option. You can override createOption to return a custom option.
580
+ *
581
+ * @param {string} flags
582
+ * @param {string} [description]
583
+ * @return {Option} new option
584
+ */
585
+
586
+ createOption(flags, description) {
587
+ return new Option(flags, description);
588
+ }
589
+
590
+ /**
591
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
592
+ *
593
+ * @param {(Option | Argument)} target
594
+ * @param {string} value
595
+ * @param {*} previous
596
+ * @param {string} invalidArgumentMessage
597
+ * @private
598
+ */
599
+
600
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
601
+ try {
602
+ return target.parseArg(value, previous);
603
+ } catch (err) {
604
+ if (err.code === 'commander.invalidArgument') {
605
+ const message = `${invalidArgumentMessage} ${err.message}`;
606
+ this.error(message, { exitCode: err.exitCode, code: err.code });
607
+ }
608
+ throw err;
609
+ }
610
+ }
611
+
612
+ /**
613
+ * Check for option flag conflicts.
614
+ * Register option if no conflicts found, or throw on conflict.
615
+ *
616
+ * @param {Option} option
617
+ * @private
618
+ */
619
+
620
+ _registerOption(option) {
621
+ const matchingOption =
622
+ (option.short && this._findOption(option.short)) ||
623
+ (option.long && this._findOption(option.long));
624
+ if (matchingOption) {
625
+ const matchingFlag =
626
+ option.long && this._findOption(option.long)
627
+ ? option.long
628
+ : option.short;
629
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
630
+ - already used by option '${matchingOption.flags}'`);
631
+ }
632
+
633
+ this._initOptionGroup(option);
634
+ this.options.push(option);
635
+ }
636
+
637
+ /**
638
+ * Check for command name and alias conflicts with existing commands.
639
+ * Register command if no conflicts found, or throw on conflict.
640
+ *
641
+ * @param {Command} command
642
+ * @private
643
+ */
644
+
645
+ _registerCommand(command) {
646
+ const knownBy = (cmd) => {
647
+ return [cmd.name()].concat(cmd.aliases());
648
+ };
649
+
650
+ const alreadyUsed = knownBy(command).find((name) =>
651
+ this._findCommand(name),
652
+ );
653
+ if (alreadyUsed) {
654
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');
655
+ const newCmd = knownBy(command).join('|');
656
+ throw new Error(
657
+ `cannot add command '${newCmd}' as already have command '${existingCmd}'`,
658
+ );
659
+ }
660
+
661
+ this._initCommandGroup(command);
662
+ this.commands.push(command);
663
+ }
664
+
665
+ /**
666
+ * Add an option.
667
+ *
668
+ * @param {Option} option
669
+ * @return {Command} `this` command for chaining
670
+ */
671
+ addOption(option) {
672
+ this._registerOption(option);
673
+
674
+ const oname = option.name();
675
+ const name = option.attributeName();
676
+
677
+ // store default value
678
+ if (option.negate) {
679
+ // --no-foo is special and defaults foo to true, unless a --foo option is already defined
680
+ const positiveLongFlag = option.long.replace(/^--no-/, '--');
681
+ if (!this._findOption(positiveLongFlag)) {
682
+ this.setOptionValueWithSource(
683
+ name,
684
+ option.defaultValue === undefined ? true : option.defaultValue,
685
+ 'default',
686
+ );
687
+ }
688
+ } else if (option.defaultValue !== undefined) {
689
+ this.setOptionValueWithSource(name, option.defaultValue, 'default');
690
+ }
691
+
692
+ // handler for cli and env supplied values
693
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
694
+ // val is null for optional option used without an optional-argument.
695
+ // val is undefined for boolean and negated option.
696
+ if (val == null && option.presetArg !== undefined) {
697
+ val = option.presetArg;
698
+ }
699
+
700
+ // custom processing
701
+ const oldValue = this.getOptionValue(name);
702
+ if (val !== null && option.parseArg) {
703
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
704
+ } else if (val !== null && option.variadic) {
705
+ val = option._concatValue(val, oldValue);
706
+ }
707
+
708
+ // Fill-in appropriate missing values. Long winded but easy to follow.
709
+ if (val == null) {
710
+ if (option.negate) {
711
+ val = false;
712
+ } else if (option.isBoolean() || option.optional) {
713
+ val = true;
714
+ } else {
715
+ val = ''; // not normal, parseArg might have failed or be a mock function for testing
716
+ }
717
+ }
718
+ this.setOptionValueWithSource(name, val, valueSource);
719
+ };
720
+
721
+ this.on('option:' + oname, (val) => {
722
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
723
+ handleOptionValue(val, invalidValueMessage, 'cli');
724
+ });
725
+
726
+ if (option.envVar) {
727
+ this.on('optionEnv:' + oname, (val) => {
728
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
729
+ handleOptionValue(val, invalidValueMessage, 'env');
730
+ });
731
+ }
732
+
733
+ return this;
734
+ }
735
+
736
+ /**
737
+ * Internal implementation shared by .option() and .requiredOption()
738
+ *
739
+ * @return {Command} `this` command for chaining
740
+ * @private
741
+ */
742
+ _optionEx(config, flags, description, fn, defaultValue) {
743
+ if (typeof flags === 'object' && flags instanceof Option) {
744
+ throw new Error(
745
+ 'To add an Option object use addOption() instead of option() or requiredOption()',
746
+ );
747
+ }
748
+ const option = this.createOption(flags, description);
749
+ option.makeOptionMandatory(!!config.mandatory);
750
+ if (typeof fn === 'function') {
751
+ option.default(defaultValue).argParser(fn);
752
+ } else if (fn instanceof RegExp) {
753
+ // deprecated
754
+ const regex = fn;
755
+ fn = (val, def) => {
756
+ const m = regex.exec(val);
757
+ return m ? m[0] : def;
758
+ };
759
+ option.default(defaultValue).argParser(fn);
760
+ } else {
761
+ option.default(fn);
762
+ }
763
+
764
+ return this.addOption(option);
765
+ }
766
+
767
+ /**
768
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
769
+ *
770
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
771
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
772
+ *
773
+ * See the README for more details, and see also addOption() and requiredOption().
774
+ *
775
+ * @example
776
+ * program
777
+ * .option('-p, --pepper', 'add pepper')
778
+ * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
779
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
780
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
781
+ *
782
+ * @param {string} flags
783
+ * @param {string} [description]
784
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
785
+ * @param {*} [defaultValue]
786
+ * @return {Command} `this` command for chaining
787
+ */
788
+
789
+ option(flags, description, parseArg, defaultValue) {
790
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
791
+ }
792
+
793
+ /**
794
+ * Add a required option which must have a value after parsing. This usually means
795
+ * the option must be specified on the command line. (Otherwise the same as .option().)
796
+ *
797
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
798
+ *
799
+ * @param {string} flags
800
+ * @param {string} [description]
801
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
802
+ * @param {*} [defaultValue]
803
+ * @return {Command} `this` command for chaining
804
+ */
805
+
806
+ requiredOption(flags, description, parseArg, defaultValue) {
807
+ return this._optionEx(
808
+ { mandatory: true },
809
+ flags,
810
+ description,
811
+ parseArg,
812
+ defaultValue,
813
+ );
814
+ }
815
+
816
+ /**
817
+ * Alter parsing of short flags with optional values.
818
+ *
819
+ * @example
820
+ * // for `.option('-f,--flag [value]'):
821
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
822
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
823
+ *
824
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
825
+ * @return {Command} `this` command for chaining
826
+ */
827
+ combineFlagAndOptionalValue(combine = true) {
828
+ this._combineFlagAndOptionalValue = !!combine;
829
+ return this;
830
+ }
831
+
832
+ /**
833
+ * Allow unknown options on the command line.
834
+ *
835
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
836
+ * @return {Command} `this` command for chaining
837
+ */
838
+ allowUnknownOption(allowUnknown = true) {
839
+ this._allowUnknownOption = !!allowUnknown;
840
+ return this;
841
+ }
842
+
843
+ /**
844
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
845
+ *
846
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
847
+ * @return {Command} `this` command for chaining
848
+ */
849
+ allowExcessArguments(allowExcess = true) {
850
+ this._allowExcessArguments = !!allowExcess;
851
+ return this;
852
+ }
853
+
854
+ /**
855
+ * Enable positional options. Positional means global options are specified before subcommands which lets
856
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
857
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
858
+ *
859
+ * @param {boolean} [positional]
860
+ * @return {Command} `this` command for chaining
861
+ */
862
+ enablePositionalOptions(positional = true) {
863
+ this._enablePositionalOptions = !!positional;
864
+ return this;
865
+ }
866
+
867
+ /**
868
+ * Pass through options that come after command-arguments rather than treat them as command-options,
869
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
870
+ * positional options to have been enabled on the program (parent commands).
871
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
872
+ *
873
+ * @param {boolean} [passThrough] for unknown options.
874
+ * @return {Command} `this` command for chaining
875
+ */
876
+ passThroughOptions(passThrough = true) {
877
+ this._passThroughOptions = !!passThrough;
878
+ this._checkForBrokenPassThrough();
879
+ return this;
880
+ }
881
+
882
+ /**
883
+ * @private
884
+ */
885
+
886
+ _checkForBrokenPassThrough() {
887
+ if (
888
+ this.parent &&
889
+ this._passThroughOptions &&
890
+ !this.parent._enablePositionalOptions
891
+ ) {
892
+ throw new Error(
893
+ `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`,
894
+ );
895
+ }
896
+ }
897
+
898
+ /**
899
+ * Whether to store option values as properties on command object,
900
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
901
+ *
902
+ * @param {boolean} [storeAsProperties=true]
903
+ * @return {Command} `this` command for chaining
904
+ */
905
+
906
+ storeOptionsAsProperties(storeAsProperties = true) {
907
+ if (this.options.length) {
908
+ throw new Error('call .storeOptionsAsProperties() before adding options');
909
+ }
910
+ if (Object.keys(this._optionValues).length) {
911
+ throw new Error(
912
+ 'call .storeOptionsAsProperties() before setting option values',
913
+ );
914
+ }
915
+ this._storeOptionsAsProperties = !!storeAsProperties;
916
+ return this;
917
+ }
918
+
919
+ /**
920
+ * Retrieve option value.
921
+ *
922
+ * @param {string} key
923
+ * @return {object} value
924
+ */
925
+
926
+ getOptionValue(key) {
927
+ if (this._storeOptionsAsProperties) {
928
+ return this[key];
929
+ }
930
+ return this._optionValues[key];
931
+ }
932
+
933
+ /**
934
+ * Store option value.
935
+ *
936
+ * @param {string} key
937
+ * @param {object} value
938
+ * @return {Command} `this` command for chaining
939
+ */
940
+
941
+ setOptionValue(key, value) {
942
+ return this.setOptionValueWithSource(key, value, undefined);
943
+ }
944
+
945
+ /**
946
+ * Store option value and where the value came from.
947
+ *
948
+ * @param {string} key
949
+ * @param {object} value
950
+ * @param {string} source - expected values are default/config/env/cli/implied
951
+ * @return {Command} `this` command for chaining
952
+ */
953
+
954
+ setOptionValueWithSource(key, value, source) {
955
+ if (this._storeOptionsAsProperties) {
956
+ this[key] = value;
957
+ } else {
958
+ this._optionValues[key] = value;
959
+ }
960
+ this._optionValueSources[key] = source;
961
+ return this;
962
+ }
963
+
964
+ /**
965
+ * Get source of option value.
966
+ * Expected values are default | config | env | cli | implied
967
+ *
968
+ * @param {string} key
969
+ * @return {string}
970
+ */
971
+
972
+ getOptionValueSource(key) {
973
+ return this._optionValueSources[key];
974
+ }
975
+
976
+ /**
977
+ * Get source of option value. See also .optsWithGlobals().
978
+ * Expected values are default | config | env | cli | implied
979
+ *
980
+ * @param {string} key
981
+ * @return {string}
982
+ */
983
+
984
+ getOptionValueSourceWithGlobals(key) {
985
+ // global overwrites local, like optsWithGlobals
986
+ let source;
987
+ this._getCommandAndAncestors().forEach((cmd) => {
988
+ if (cmd.getOptionValueSource(key) !== undefined) {
989
+ source = cmd.getOptionValueSource(key);
990
+ }
991
+ });
992
+ return source;
993
+ }
994
+
995
+ /**
996
+ * Get user arguments from implied or explicit arguments.
997
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
998
+ *
999
+ * @private
1000
+ */
1001
+
1002
+ _prepareUserArgs(argv, parseOptions) {
1003
+ if (argv !== undefined && !Array.isArray(argv)) {
1004
+ throw new Error('first parameter to parse must be array or undefined');
1005
+ }
1006
+ parseOptions = parseOptions || {};
1007
+
1008
+ // auto-detect argument conventions if nothing supplied
1009
+ if (argv === undefined && parseOptions.from === undefined) {
1010
+ if (process.versions?.electron) {
1011
+ parseOptions.from = 'electron';
1012
+ }
1013
+ // check node specific options for scenarios where user CLI args follow executable without scriptname
1014
+ const execArgv = process.execArgv ?? [];
1015
+ if (
1016
+ execArgv.includes('-e') ||
1017
+ execArgv.includes('--eval') ||
1018
+ execArgv.includes('-p') ||
1019
+ execArgv.includes('--print')
1020
+ ) {
1021
+ parseOptions.from = 'eval'; // internal usage, not documented
1022
+ }
1023
+ }
1024
+
1025
+ // default to using process.argv
1026
+ if (argv === undefined) {
1027
+ argv = process.argv;
1028
+ }
1029
+ this.rawArgs = argv.slice();
1030
+
1031
+ // extract the user args and scriptPath
1032
+ let userArgs;
1033
+ switch (parseOptions.from) {
1034
+ case undefined:
1035
+ case 'node':
1036
+ this._scriptPath = argv[1];
1037
+ userArgs = argv.slice(2);
1038
+ break;
1039
+ case 'electron':
1040
+ // @ts-ignore: because defaultApp is an unknown property
1041
+ if (process.defaultApp) {
1042
+ this._scriptPath = argv[1];
1043
+ userArgs = argv.slice(2);
1044
+ } else {
1045
+ userArgs = argv.slice(1);
1046
+ }
1047
+ break;
1048
+ case 'user':
1049
+ userArgs = argv.slice(0);
1050
+ break;
1051
+ case 'eval':
1052
+ userArgs = argv.slice(1);
1053
+ break;
1054
+ default:
1055
+ throw new Error(
1056
+ `unexpected parse option { from: '${parseOptions.from}' }`,
1057
+ );
1058
+ }
1059
+
1060
+ // Find default name for program from arguments.
1061
+ if (!this._name && this._scriptPath)
1062
+ this.nameFromFilename(this._scriptPath);
1063
+ this._name = this._name || 'program';
1064
+
1065
+ return userArgs;
1066
+ }
1067
+
1068
+ /**
1069
+ * Parse `argv`, setting options and invoking commands when defined.
1070
+ *
1071
+ * Use parseAsync instead of parse if any of your action handlers are async.
1072
+ *
1073
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1074
+ *
1075
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1076
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1077
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1078
+ * - `'user'`: just user arguments
1079
+ *
1080
+ * @example
1081
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
1082
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
1083
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1084
+ *
1085
+ * @param {string[]} [argv] - optional, defaults to process.argv
1086
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
1087
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
1088
+ * @return {Command} `this` command for chaining
1089
+ */
1090
+
1091
+ parse(argv, parseOptions) {
1092
+ this._prepareForParse();
1093
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1094
+ this._parseCommand([], userArgs);
1095
+
1096
+ return this;
1097
+ }
1098
+
1099
+ /**
1100
+ * Parse `argv`, setting options and invoking commands when defined.
1101
+ *
1102
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1103
+ *
1104
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1105
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1106
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1107
+ * - `'user'`: just user arguments
1108
+ *
1109
+ * @example
1110
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
1111
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
1112
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1113
+ *
1114
+ * @param {string[]} [argv]
1115
+ * @param {object} [parseOptions]
1116
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
1117
+ * @return {Promise}
1118
+ */
1119
+
1120
+ async parseAsync(argv, parseOptions) {
1121
+ this._prepareForParse();
1122
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1123
+ await this._parseCommand([], userArgs);
1124
+
1125
+ return this;
1126
+ }
1127
+
1128
+ _prepareForParse() {
1129
+ if (this._savedState === null) {
1130
+ this.saveStateBeforeParse();
1131
+ } else {
1132
+ this.restoreStateBeforeParse();
1133
+ }
1134
+ }
1135
+
1136
+ /**
1137
+ * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
1138
+ * Not usually called directly, but available for subclasses to save their custom state.
1139
+ *
1140
+ * This is called in a lazy way. Only commands used in parsing chain will have state saved.
1141
+ */
1142
+ saveStateBeforeParse() {
1143
+ this._savedState = {
1144
+ // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing
1145
+ _name: this._name,
1146
+ // option values before parse have default values (including false for negated options)
1147
+ // shallow clones
1148
+ _optionValues: { ...this._optionValues },
1149
+ _optionValueSources: { ...this._optionValueSources },
1150
+ };
1151
+ }
1152
+
1153
+ /**
1154
+ * Restore state before parse for calls after the first.
1155
+ * Not usually called directly, but available for subclasses to save their custom state.
1156
+ *
1157
+ * This is called in a lazy way. Only commands used in parsing chain will have state restored.
1158
+ */
1159
+ restoreStateBeforeParse() {
1160
+ if (this._storeOptionsAsProperties)
1161
+ throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
1162
+ - either make a new Command for each call to parse, or stop storing options as properties`);
1163
+
1164
+ // clear state from _prepareUserArgs
1165
+ this._name = this._savedState._name;
1166
+ this._scriptPath = null;
1167
+ this.rawArgs = [];
1168
+ // clear state from setOptionValueWithSource
1169
+ this._optionValues = { ...this._savedState._optionValues };
1170
+ this._optionValueSources = { ...this._savedState._optionValueSources };
1171
+ // clear state from _parseCommand
1172
+ this.args = [];
1173
+ // clear state from _processArguments
1174
+ this.processedArgs = [];
1175
+ }
1176
+
1177
+ /**
1178
+ * Throw if expected executable is missing. Add lots of help for author.
1179
+ *
1180
+ * @param {string} executableFile
1181
+ * @param {string} executableDir
1182
+ * @param {string} subcommandName
1183
+ */
1184
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
1185
+ if (fs.existsSync(executableFile)) return;
1186
+
1187
+ const executableDirMessage = executableDir
1188
+ ? `searched for local subcommand relative to directory '${executableDir}'`
1189
+ : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';
1190
+ const executableMissing = `'${executableFile}' does not exist
1191
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1192
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1193
+ - ${executableDirMessage}`;
1194
+ throw new Error(executableMissing);
1195
+ }
1196
+
1197
+ /**
1198
+ * Execute a sub-command executable.
1199
+ *
1200
+ * @private
1201
+ */
1202
+
1203
+ _executeSubCommand(subcommand, args) {
1204
+ args = args.slice();
1205
+ let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.
1206
+ const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];
1207
+
1208
+ function findFile(baseDir, baseName) {
1209
+ // Look for specified file
1210
+ const localBin = path.resolve(baseDir, baseName);
1211
+ if (fs.existsSync(localBin)) return localBin;
1212
+
1213
+ // Stop looking if candidate already has an expected extension.
1214
+ if (sourceExt.includes(path.extname(baseName))) return undefined;
1215
+
1216
+ // Try all the extensions.
1217
+ const foundExt = sourceExt.find((ext) =>
1218
+ fs.existsSync(`${localBin}${ext}`),
1219
+ );
1220
+ if (foundExt) return `${localBin}${foundExt}`;
1221
+
1222
+ return undefined;
1223
+ }
1224
+
1225
+ // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.
1226
+ this._checkForMissingMandatoryOptions();
1227
+ this._checkForConflictingOptions();
1228
+
1229
+ // executableFile and executableDir might be full path, or just a name
1230
+ let executableFile =
1231
+ subcommand._executableFile || `${this._name}-${subcommand._name}`;
1232
+ let executableDir = this._executableDir || '';
1233
+ if (this._scriptPath) {
1234
+ let resolvedScriptPath; // resolve possible symlink for installed npm binary
1235
+ try {
1236
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
1237
+ } catch {
1238
+ resolvedScriptPath = this._scriptPath;
1239
+ }
1240
+ executableDir = path.resolve(
1241
+ path.dirname(resolvedScriptPath),
1242
+ executableDir,
1243
+ );
1244
+ }
1245
+
1246
+ // Look for a local file in preference to a command in PATH.
1247
+ if (executableDir) {
1248
+ let localFile = findFile(executableDir, executableFile);
1249
+
1250
+ // Legacy search using prefix of script name instead of command name
1251
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1252
+ const legacyName = path.basename(
1253
+ this._scriptPath,
1254
+ path.extname(this._scriptPath),
1255
+ );
1256
+ if (legacyName !== this._name) {
1257
+ localFile = findFile(
1258
+ executableDir,
1259
+ `${legacyName}-${subcommand._name}`,
1260
+ );
1261
+ }
1262
+ }
1263
+ executableFile = localFile || executableFile;
1264
+ }
1265
+
1266
+ launchWithNode = sourceExt.includes(path.extname(executableFile));
1267
+
1268
+ let proc;
1269
+ if (process.platform !== 'win32') {
1270
+ if (launchWithNode) {
1271
+ args.unshift(executableFile);
1272
+ // add executable arguments to spawn
1273
+ args = incrementNodeInspectorPort(process.execArgv).concat(args);
1274
+
1275
+ proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });
1276
+ } else {
1277
+ proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });
1278
+ }
1279
+ } else {
1280
+ this._checkForMissingExecutable(
1281
+ executableFile,
1282
+ executableDir,
1283
+ subcommand._name,
1284
+ );
1285
+ args.unshift(executableFile);
1286
+ // add executable arguments to spawn
1287
+ args = incrementNodeInspectorPort(process.execArgv).concat(args);
1288
+ proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });
1289
+ }
1290
+
1291
+ if (!proc.killed) {
1292
+ // testing mainly to avoid leak warnings during unit tests with mocked spawn
1293
+ const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];
1294
+ signals.forEach((signal) => {
1295
+ process.on(signal, () => {
1296
+ if (proc.killed === false && proc.exitCode === null) {
1297
+ // @ts-ignore because signals not typed to known strings
1298
+ proc.kill(signal);
1299
+ }
1300
+ });
1301
+ });
1302
+ }
1303
+
1304
+ // By default terminate process when spawned process terminates.
1305
+ const exitCallback = this._exitCallback;
1306
+ proc.on('close', (code) => {
1307
+ code = code ?? 1; // code is null if spawned process terminated due to a signal
1308
+ if (!exitCallback) {
1309
+ process.exit(code);
1310
+ } else {
1311
+ exitCallback(
1312
+ new CommanderError(
1313
+ code,
1314
+ 'commander.executeSubCommandAsync',
1315
+ '(close)',
1316
+ ),
1317
+ );
1318
+ }
1319
+ });
1320
+ proc.on('error', (err) => {
1321
+ // @ts-ignore: because err.code is an unknown property
1322
+ if (err.code === 'ENOENT') {
1323
+ this._checkForMissingExecutable(
1324
+ executableFile,
1325
+ executableDir,
1326
+ subcommand._name,
1327
+ );
1328
+ // @ts-ignore: because err.code is an unknown property
1329
+ } else if (err.code === 'EACCES') {
1330
+ throw new Error(`'${executableFile}' not executable`);
1331
+ }
1332
+ if (!exitCallback) {
1333
+ process.exit(1);
1334
+ } else {
1335
+ const wrappedError = new CommanderError(
1336
+ 1,
1337
+ 'commander.executeSubCommandAsync',
1338
+ '(error)',
1339
+ );
1340
+ wrappedError.nestedError = err;
1341
+ exitCallback(wrappedError);
1342
+ }
1343
+ });
1344
+
1345
+ // Store the reference to the child process
1346
+ this.runningCommand = proc;
1347
+ }
1348
+
1349
+ /**
1350
+ * @private
1351
+ */
1352
+
1353
+ _dispatchSubcommand(commandName, operands, unknown) {
1354
+ const subCommand = this._findCommand(commandName);
1355
+ if (!subCommand) this.help({ error: true });
1356
+
1357
+ subCommand._prepareForParse();
1358
+ let promiseChain;
1359
+ promiseChain = this._chainOrCallSubCommandHook(
1360
+ promiseChain,
1361
+ subCommand,
1362
+ 'preSubcommand',
1363
+ );
1364
+ promiseChain = this._chainOrCall(promiseChain, () => {
1365
+ if (subCommand._executableHandler) {
1366
+ this._executeSubCommand(subCommand, operands.concat(unknown));
1367
+ } else {
1368
+ return subCommand._parseCommand(operands, unknown);
1369
+ }
1370
+ });
1371
+ return promiseChain;
1372
+ }
1373
+
1374
+ /**
1375
+ * Invoke help directly if possible, or dispatch if necessary.
1376
+ * e.g. help foo
1377
+ *
1378
+ * @private
1379
+ */
1380
+
1381
+ _dispatchHelpCommand(subcommandName) {
1382
+ if (!subcommandName) {
1383
+ this.help();
1384
+ }
1385
+ const subCommand = this._findCommand(subcommandName);
1386
+ if (subCommand && !subCommand._executableHandler) {
1387
+ subCommand.help();
1388
+ }
1389
+
1390
+ // Fallback to parsing the help flag to invoke the help.
1391
+ return this._dispatchSubcommand(
1392
+ subcommandName,
1393
+ [],
1394
+ [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'],
1395
+ );
1396
+ }
1397
+
1398
+ /**
1399
+ * Check this.args against expected this.registeredArguments.
1400
+ *
1401
+ * @private
1402
+ */
1403
+
1404
+ _checkNumberOfArguments() {
1405
+ // too few
1406
+ this.registeredArguments.forEach((arg, i) => {
1407
+ if (arg.required && this.args[i] == null) {
1408
+ this.missingArgument(arg.name());
1409
+ }
1410
+ });
1411
+ // too many
1412
+ if (
1413
+ this.registeredArguments.length > 0 &&
1414
+ this.registeredArguments[this.registeredArguments.length - 1].variadic
1415
+ ) {
1416
+ return;
1417
+ }
1418
+ if (this.args.length > this.registeredArguments.length) {
1419
+ this._excessArguments(this.args);
1420
+ }
1421
+ }
1422
+
1423
+ /**
1424
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
1425
+ *
1426
+ * @private
1427
+ */
1428
+
1429
+ _processArguments() {
1430
+ const myParseArg = (argument, value, previous) => {
1431
+ // Extra processing for nice error message on parsing failure.
1432
+ let parsedValue = value;
1433
+ if (value !== null && argument.parseArg) {
1434
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
1435
+ parsedValue = this._callParseArg(
1436
+ argument,
1437
+ value,
1438
+ previous,
1439
+ invalidValueMessage,
1440
+ );
1441
+ }
1442
+ return parsedValue;
1443
+ };
1444
+
1445
+ this._checkNumberOfArguments();
1446
+
1447
+ const processedArgs = [];
1448
+ this.registeredArguments.forEach((declaredArg, index) => {
1449
+ let value = declaredArg.defaultValue;
1450
+ if (declaredArg.variadic) {
1451
+ // Collect together remaining arguments for passing together as an array.
1452
+ if (index < this.args.length) {
1453
+ value = this.args.slice(index);
1454
+ if (declaredArg.parseArg) {
1455
+ value = value.reduce((processed, v) => {
1456
+ return myParseArg(declaredArg, v, processed);
1457
+ }, declaredArg.defaultValue);
1458
+ }
1459
+ } else if (value === undefined) {
1460
+ value = [];
1461
+ }
1462
+ } else if (index < this.args.length) {
1463
+ value = this.args[index];
1464
+ if (declaredArg.parseArg) {
1465
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
1466
+ }
1467
+ }
1468
+ processedArgs[index] = value;
1469
+ });
1470
+ this.processedArgs = processedArgs;
1471
+ }
1472
+
1473
+ /**
1474
+ * Once we have a promise we chain, but call synchronously until then.
1475
+ *
1476
+ * @param {(Promise|undefined)} promise
1477
+ * @param {Function} fn
1478
+ * @return {(Promise|undefined)}
1479
+ * @private
1480
+ */
1481
+
1482
+ _chainOrCall(promise, fn) {
1483
+ // thenable
1484
+ if (promise && promise.then && typeof promise.then === 'function') {
1485
+ // already have a promise, chain callback
1486
+ return promise.then(() => fn());
1487
+ }
1488
+ // callback might return a promise
1489
+ return fn();
1490
+ }
1491
+
1492
+ /**
1493
+ *
1494
+ * @param {(Promise|undefined)} promise
1495
+ * @param {string} event
1496
+ * @return {(Promise|undefined)}
1497
+ * @private
1498
+ */
1499
+
1500
+ _chainOrCallHooks(promise, event) {
1501
+ let result = promise;
1502
+ const hooks = [];
1503
+ this._getCommandAndAncestors()
1504
+ .reverse()
1505
+ .filter((cmd) => cmd._lifeCycleHooks[event] !== undefined)
1506
+ .forEach((hookedCommand) => {
1507
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
1508
+ hooks.push({ hookedCommand, callback });
1509
+ });
1510
+ });
1511
+ if (event === 'postAction') {
1512
+ hooks.reverse();
1513
+ }
1514
+
1515
+ hooks.forEach((hookDetail) => {
1516
+ result = this._chainOrCall(result, () => {
1517
+ return hookDetail.callback(hookDetail.hookedCommand, this);
1518
+ });
1519
+ });
1520
+ return result;
1521
+ }
1522
+
1523
+ /**
1524
+ *
1525
+ * @param {(Promise|undefined)} promise
1526
+ * @param {Command} subCommand
1527
+ * @param {string} event
1528
+ * @return {(Promise|undefined)}
1529
+ * @private
1530
+ */
1531
+
1532
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
1533
+ let result = promise;
1534
+ if (this._lifeCycleHooks[event] !== undefined) {
1535
+ this._lifeCycleHooks[event].forEach((hook) => {
1536
+ result = this._chainOrCall(result, () => {
1537
+ return hook(this, subCommand);
1538
+ });
1539
+ });
1540
+ }
1541
+ return result;
1542
+ }
1543
+
1544
+ /**
1545
+ * Process arguments in context of this command.
1546
+ * Returns action result, in case it is a promise.
1547
+ *
1548
+ * @private
1549
+ */
1550
+
1551
+ _parseCommand(operands, unknown) {
1552
+ const parsed = this.parseOptions(unknown);
1553
+ this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env
1554
+ this._parseOptionsImplied();
1555
+ operands = operands.concat(parsed.operands);
1556
+ unknown = parsed.unknown;
1557
+ this.args = operands.concat(unknown);
1558
+
1559
+ if (operands && this._findCommand(operands[0])) {
1560
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
1561
+ }
1562
+ if (
1563
+ this._getHelpCommand() &&
1564
+ operands[0] === this._getHelpCommand().name()
1565
+ ) {
1566
+ return this._dispatchHelpCommand(operands[1]);
1567
+ }
1568
+ if (this._defaultCommandName) {
1569
+ this._outputHelpIfRequested(unknown); // Run the help for default command from parent rather than passing to default command
1570
+ return this._dispatchSubcommand(
1571
+ this._defaultCommandName,
1572
+ operands,
1573
+ unknown,
1574
+ );
1575
+ }
1576
+ if (
1577
+ this.commands.length &&
1578
+ this.args.length === 0 &&
1579
+ !this._actionHandler &&
1580
+ !this._defaultCommandName
1581
+ ) {
1582
+ // probably missing subcommand and no handler, user needs help (and exit)
1583
+ this.help({ error: true });
1584
+ }
1585
+
1586
+ this._outputHelpIfRequested(parsed.unknown);
1587
+ this._checkForMissingMandatoryOptions();
1588
+ this._checkForConflictingOptions();
1589
+
1590
+ // We do not always call this check to avoid masking a "better" error, like unknown command.
1591
+ const checkForUnknownOptions = () => {
1592
+ if (parsed.unknown.length > 0) {
1593
+ this.unknownOption(parsed.unknown[0]);
1594
+ }
1595
+ };
1596
+
1597
+ const commandEvent = `command:${this.name()}`;
1598
+ if (this._actionHandler) {
1599
+ checkForUnknownOptions();
1600
+ this._processArguments();
1601
+
1602
+ let promiseChain;
1603
+ promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');
1604
+ promiseChain = this._chainOrCall(promiseChain, () =>
1605
+ this._actionHandler(this.processedArgs),
1606
+ );
1607
+ if (this.parent) {
1608
+ promiseChain = this._chainOrCall(promiseChain, () => {
1609
+ this.parent.emit(commandEvent, operands, unknown); // legacy
1610
+ });
1611
+ }
1612
+ promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');
1613
+ return promiseChain;
1614
+ }
1615
+ if (this.parent && this.parent.listenerCount(commandEvent)) {
1616
+ checkForUnknownOptions();
1617
+ this._processArguments();
1618
+ this.parent.emit(commandEvent, operands, unknown); // legacy
1619
+ } else if (operands.length) {
1620
+ if (this._findCommand('*')) {
1621
+ // legacy default command
1622
+ return this._dispatchSubcommand('*', operands, unknown);
1623
+ }
1624
+ if (this.listenerCount('command:*')) {
1625
+ // skip option check, emit event for possible misspelling suggestion
1626
+ this.emit('command:*', operands, unknown);
1627
+ } else if (this.commands.length) {
1628
+ this.unknownCommand();
1629
+ } else {
1630
+ checkForUnknownOptions();
1631
+ this._processArguments();
1632
+ }
1633
+ } else if (this.commands.length) {
1634
+ checkForUnknownOptions();
1635
+ // This command has subcommands and nothing hooked up at this level, so display help (and exit).
1636
+ this.help({ error: true });
1637
+ } else {
1638
+ checkForUnknownOptions();
1639
+ this._processArguments();
1640
+ // fall through for caller to handle after calling .parse()
1641
+ }
1642
+ }
1643
+
1644
+ /**
1645
+ * Find matching command.
1646
+ *
1647
+ * @private
1648
+ * @return {Command | undefined}
1649
+ */
1650
+ _findCommand(name) {
1651
+ if (!name) return undefined;
1652
+ return this.commands.find(
1653
+ (cmd) => cmd._name === name || cmd._aliases.includes(name),
1654
+ );
1655
+ }
1656
+
1657
+ /**
1658
+ * Return an option matching `arg` if any.
1659
+ *
1660
+ * @param {string} arg
1661
+ * @return {Option}
1662
+ * @package
1663
+ */
1664
+
1665
+ _findOption(arg) {
1666
+ return this.options.find((option) => option.is(arg));
1667
+ }
1668
+
1669
+ /**
1670
+ * Display an error message if a mandatory option does not have a value.
1671
+ * Called after checking for help flags in leaf subcommand.
1672
+ *
1673
+ * @private
1674
+ */
1675
+
1676
+ _checkForMissingMandatoryOptions() {
1677
+ // Walk up hierarchy so can call in subcommand after checking for displaying help.
1678
+ this._getCommandAndAncestors().forEach((cmd) => {
1679
+ cmd.options.forEach((anOption) => {
1680
+ if (
1681
+ anOption.mandatory &&
1682
+ cmd.getOptionValue(anOption.attributeName()) === undefined
1683
+ ) {
1684
+ cmd.missingMandatoryOptionValue(anOption);
1685
+ }
1686
+ });
1687
+ });
1688
+ }
1689
+
1690
+ /**
1691
+ * Display an error message if conflicting options are used together in this.
1692
+ *
1693
+ * @private
1694
+ */
1695
+ _checkForConflictingLocalOptions() {
1696
+ const definedNonDefaultOptions = this.options.filter((option) => {
1697
+ const optionKey = option.attributeName();
1698
+ if (this.getOptionValue(optionKey) === undefined) {
1699
+ return false;
1700
+ }
1701
+ return this.getOptionValueSource(optionKey) !== 'default';
1702
+ });
1703
+
1704
+ const optionsWithConflicting = definedNonDefaultOptions.filter(
1705
+ (option) => option.conflictsWith.length > 0,
1706
+ );
1707
+
1708
+ optionsWithConflicting.forEach((option) => {
1709
+ const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>
1710
+ option.conflictsWith.includes(defined.attributeName()),
1711
+ );
1712
+ if (conflictingAndDefined) {
1713
+ this._conflictingOption(option, conflictingAndDefined);
1714
+ }
1715
+ });
1716
+ }
1717
+
1718
+ /**
1719
+ * Display an error message if conflicting options are used together.
1720
+ * Called after checking for help flags in leaf subcommand.
1721
+ *
1722
+ * @private
1723
+ */
1724
+ _checkForConflictingOptions() {
1725
+ // Walk up hierarchy so can call in subcommand after checking for displaying help.
1726
+ this._getCommandAndAncestors().forEach((cmd) => {
1727
+ cmd._checkForConflictingLocalOptions();
1728
+ });
1729
+ }
1730
+
1731
+ /**
1732
+ * Parse options from `argv` removing known options,
1733
+ * and return argv split into operands and unknown arguments.
1734
+ *
1735
+ * Side effects: modifies command by storing options. Does not reset state if called again.
1736
+ *
1737
+ * Examples:
1738
+ *
1739
+ * argv => operands, unknown
1740
+ * --known kkk op => [op], []
1741
+ * op --known kkk => [op], []
1742
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
1743
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
1744
+ *
1745
+ * @param {string[]} argv
1746
+ * @return {{operands: string[], unknown: string[]}}
1747
+ */
1748
+
1749
+ parseOptions(argv) {
1750
+ const operands = []; // operands, not options or values
1751
+ const unknown = []; // first unknown option and remaining unknown args
1752
+ let dest = operands;
1753
+ const args = argv.slice();
1754
+
1755
+ function maybeOption(arg) {
1756
+ return arg.length > 1 && arg[0] === '-';
1757
+ }
1758
+
1759
+ const negativeNumberArg = (arg) => {
1760
+ // return false if not a negative number
1761
+ if (!/^-\d*\.?\d+(e[+-]?\d+)?$/.test(arg)) return false;
1762
+ // negative number is ok unless digit used as an option in command hierarchy
1763
+ return !this._getCommandAndAncestors().some((cmd) =>
1764
+ cmd.options
1765
+ .map((opt) => opt.short)
1766
+ .some((short) => /^-\d$/.test(short)),
1767
+ );
1768
+ };
1769
+
1770
+ // parse options
1771
+ let activeVariadicOption = null;
1772
+ while (args.length) {
1773
+ const arg = args.shift();
1774
+
1775
+ // literal
1776
+ if (arg === '--') {
1777
+ if (dest === unknown) dest.push(arg);
1778
+ dest.push(...args);
1779
+ break;
1780
+ }
1781
+
1782
+ if (
1783
+ activeVariadicOption &&
1784
+ (!maybeOption(arg) || negativeNumberArg(arg))
1785
+ ) {
1786
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
1787
+ continue;
1788
+ }
1789
+ activeVariadicOption = null;
1790
+
1791
+ if (maybeOption(arg)) {
1792
+ const option = this._findOption(arg);
1793
+ // recognised option, call listener to assign value with possible custom processing
1794
+ if (option) {
1795
+ if (option.required) {
1796
+ const value = args.shift();
1797
+ if (value === undefined) this.optionMissingArgument(option);
1798
+ this.emit(`option:${option.name()}`, value);
1799
+ } else if (option.optional) {
1800
+ let value = null;
1801
+ // historical behaviour is optional value is following arg unless an option
1802
+ if (
1803
+ args.length > 0 &&
1804
+ (!maybeOption(args[0]) || negativeNumberArg(args[0]))
1805
+ ) {
1806
+ value = args.shift();
1807
+ }
1808
+ this.emit(`option:${option.name()}`, value);
1809
+ } else {
1810
+ // boolean flag
1811
+ this.emit(`option:${option.name()}`);
1812
+ }
1813
+ activeVariadicOption = option.variadic ? option : null;
1814
+ continue;
1815
+ }
1816
+ }
1817
+
1818
+ // Look for combo options following single dash, eat first one if known.
1819
+ if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {
1820
+ const option = this._findOption(`-${arg[1]}`);
1821
+ if (option) {
1822
+ if (
1823
+ option.required ||
1824
+ (option.optional && this._combineFlagAndOptionalValue)
1825
+ ) {
1826
+ // option with value following in same argument
1827
+ this.emit(`option:${option.name()}`, arg.slice(2));
1828
+ } else {
1829
+ // boolean option, emit and put back remainder of arg for further processing
1830
+ this.emit(`option:${option.name()}`);
1831
+ args.unshift(`-${arg.slice(2)}`);
1832
+ }
1833
+ continue;
1834
+ }
1835
+ }
1836
+
1837
+ // Look for known long flag with value, like --foo=bar
1838
+ if (/^--[^=]+=/.test(arg)) {
1839
+ const index = arg.indexOf('=');
1840
+ const option = this._findOption(arg.slice(0, index));
1841
+ if (option && (option.required || option.optional)) {
1842
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
1843
+ continue;
1844
+ }
1845
+ }
1846
+
1847
+ // Not a recognised option by this command.
1848
+ // Might be a command-argument, or subcommand option, or unknown option, or help command or option.
1849
+
1850
+ // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.
1851
+ // A negative number in a leaf command is not an unknown option.
1852
+ if (
1853
+ dest === operands &&
1854
+ maybeOption(arg) &&
1855
+ !(this.commands.length === 0 && negativeNumberArg(arg))
1856
+ ) {
1857
+ dest = unknown;
1858
+ }
1859
+
1860
+ // If using positionalOptions, stop processing our options at subcommand.
1861
+ if (
1862
+ (this._enablePositionalOptions || this._passThroughOptions) &&
1863
+ operands.length === 0 &&
1864
+ unknown.length === 0
1865
+ ) {
1866
+ if (this._findCommand(arg)) {
1867
+ operands.push(arg);
1868
+ if (args.length > 0) unknown.push(...args);
1869
+ break;
1870
+ } else if (
1871
+ this._getHelpCommand() &&
1872
+ arg === this._getHelpCommand().name()
1873
+ ) {
1874
+ operands.push(arg);
1875
+ if (args.length > 0) operands.push(...args);
1876
+ break;
1877
+ } else if (this._defaultCommandName) {
1878
+ unknown.push(arg);
1879
+ if (args.length > 0) unknown.push(...args);
1880
+ break;
1881
+ }
1882
+ }
1883
+
1884
+ // If using passThroughOptions, stop processing options at first command-argument.
1885
+ if (this._passThroughOptions) {
1886
+ dest.push(arg);
1887
+ if (args.length > 0) dest.push(...args);
1888
+ break;
1889
+ }
1890
+
1891
+ // add arg
1892
+ dest.push(arg);
1893
+ }
1894
+
1895
+ return { operands, unknown };
1896
+ }
1897
+
1898
+ /**
1899
+ * Return an object containing local option values as key-value pairs.
1900
+ *
1901
+ * @return {object}
1902
+ */
1903
+ opts() {
1904
+ if (this._storeOptionsAsProperties) {
1905
+ // Preserve original behaviour so backwards compatible when still using properties
1906
+ const result = {};
1907
+ const len = this.options.length;
1908
+
1909
+ for (let i = 0; i < len; i++) {
1910
+ const key = this.options[i].attributeName();
1911
+ result[key] =
1912
+ key === this._versionOptionName ? this._version : this[key];
1913
+ }
1914
+ return result;
1915
+ }
1916
+
1917
+ return this._optionValues;
1918
+ }
1919
+
1920
+ /**
1921
+ * Return an object containing merged local and global option values as key-value pairs.
1922
+ *
1923
+ * @return {object}
1924
+ */
1925
+ optsWithGlobals() {
1926
+ // globals overwrite locals
1927
+ return this._getCommandAndAncestors().reduce(
1928
+ (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
1929
+ {},
1930
+ );
1931
+ }
1932
+
1933
+ /**
1934
+ * Display error message and exit (or call exitOverride).
1935
+ *
1936
+ * @param {string} message
1937
+ * @param {object} [errorOptions]
1938
+ * @param {string} [errorOptions.code] - an id string representing the error
1939
+ * @param {number} [errorOptions.exitCode] - used with process.exit
1940
+ */
1941
+ error(message, errorOptions) {
1942
+ // output handling
1943
+ this._outputConfiguration.outputError(
1944
+ `${message}\n`,
1945
+ this._outputConfiguration.writeErr,
1946
+ );
1947
+ if (typeof this._showHelpAfterError === 'string') {
1948
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);
1949
+ } else if (this._showHelpAfterError) {
1950
+ this._outputConfiguration.writeErr('\n');
1951
+ this.outputHelp({ error: true });
1952
+ }
1953
+
1954
+ // exit handling
1955
+ const config = errorOptions || {};
1956
+ const exitCode = config.exitCode || 1;
1957
+ const code = config.code || 'commander.error';
1958
+ this._exit(exitCode, code, message);
1959
+ }
1960
+
1961
+ /**
1962
+ * Apply any option related environment variables, if option does
1963
+ * not have a value from cli or client code.
1964
+ *
1965
+ * @private
1966
+ */
1967
+ _parseOptionsEnv() {
1968
+ this.options.forEach((option) => {
1969
+ if (option.envVar && option.envVar in process.env) {
1970
+ const optionKey = option.attributeName();
1971
+ // Priority check. Do not overwrite cli or options from unknown source (client-code).
1972
+ if (
1973
+ this.getOptionValue(optionKey) === undefined ||
1974
+ ['default', 'config', 'env'].includes(
1975
+ this.getOptionValueSource(optionKey),
1976
+ )
1977
+ ) {
1978
+ if (option.required || option.optional) {
1979
+ // option can take a value
1980
+ // keep very simple, optional always takes value
1981
+ this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);
1982
+ } else {
1983
+ // boolean
1984
+ // keep very simple, only care that envVar defined and not the value
1985
+ this.emit(`optionEnv:${option.name()}`);
1986
+ }
1987
+ }
1988
+ }
1989
+ });
1990
+ }
1991
+
1992
+ /**
1993
+ * Apply any implied option values, if option is undefined or default value.
1994
+ *
1995
+ * @private
1996
+ */
1997
+ _parseOptionsImplied() {
1998
+ const dualHelper = new DualOptions(this.options);
1999
+ const hasCustomOptionValue = (optionKey) => {
2000
+ return (
2001
+ this.getOptionValue(optionKey) !== undefined &&
2002
+ !['default', 'implied'].includes(this.getOptionValueSource(optionKey))
2003
+ );
2004
+ };
2005
+ this.options
2006
+ .filter(
2007
+ (option) =>
2008
+ option.implied !== undefined &&
2009
+ hasCustomOptionValue(option.attributeName()) &&
2010
+ dualHelper.valueFromOption(
2011
+ this.getOptionValue(option.attributeName()),
2012
+ option,
2013
+ ),
2014
+ )
2015
+ .forEach((option) => {
2016
+ Object.keys(option.implied)
2017
+ .filter((impliedKey) => !hasCustomOptionValue(impliedKey))
2018
+ .forEach((impliedKey) => {
2019
+ this.setOptionValueWithSource(
2020
+ impliedKey,
2021
+ option.implied[impliedKey],
2022
+ 'implied',
2023
+ );
2024
+ });
2025
+ });
2026
+ }
2027
+
2028
+ /**
2029
+ * Argument `name` is missing.
2030
+ *
2031
+ * @param {string} name
2032
+ * @private
2033
+ */
2034
+
2035
+ missingArgument(name) {
2036
+ const message = `error: missing required argument '${name}'`;
2037
+ this.error(message, { code: 'commander.missingArgument' });
2038
+ }
2039
+
2040
+ /**
2041
+ * `Option` is missing an argument.
2042
+ *
2043
+ * @param {Option} option
2044
+ * @private
2045
+ */
2046
+
2047
+ optionMissingArgument(option) {
2048
+ const message = `error: option '${option.flags}' argument missing`;
2049
+ this.error(message, { code: 'commander.optionMissingArgument' });
2050
+ }
2051
+
2052
+ /**
2053
+ * `Option` does not have a value, and is a mandatory option.
2054
+ *
2055
+ * @param {Option} option
2056
+ * @private
2057
+ */
2058
+
2059
+ missingMandatoryOptionValue(option) {
2060
+ const message = `error: required option '${option.flags}' not specified`;
2061
+ this.error(message, { code: 'commander.missingMandatoryOptionValue' });
2062
+ }
2063
+
2064
+ /**
2065
+ * `Option` conflicts with another option.
2066
+ *
2067
+ * @param {Option} option
2068
+ * @param {Option} conflictingOption
2069
+ * @private
2070
+ */
2071
+ _conflictingOption(option, conflictingOption) {
2072
+ // The calling code does not know whether a negated option is the source of the
2073
+ // value, so do some work to take an educated guess.
2074
+ const findBestOptionFromValue = (option) => {
2075
+ const optionKey = option.attributeName();
2076
+ const optionValue = this.getOptionValue(optionKey);
2077
+ const negativeOption = this.options.find(
2078
+ (target) => target.negate && optionKey === target.attributeName(),
2079
+ );
2080
+ const positiveOption = this.options.find(
2081
+ (target) => !target.negate && optionKey === target.attributeName(),
2082
+ );
2083
+ if (
2084
+ negativeOption &&
2085
+ ((negativeOption.presetArg === undefined && optionValue === false) ||
2086
+ (negativeOption.presetArg !== undefined &&
2087
+ optionValue === negativeOption.presetArg))
2088
+ ) {
2089
+ return negativeOption;
2090
+ }
2091
+ return positiveOption || option;
2092
+ };
2093
+
2094
+ const getErrorMessage = (option) => {
2095
+ const bestOption = findBestOptionFromValue(option);
2096
+ const optionKey = bestOption.attributeName();
2097
+ const source = this.getOptionValueSource(optionKey);
2098
+ if (source === 'env') {
2099
+ return `environment variable '${bestOption.envVar}'`;
2100
+ }
2101
+ return `option '${bestOption.flags}'`;
2102
+ };
2103
+
2104
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2105
+ this.error(message, { code: 'commander.conflictingOption' });
2106
+ }
2107
+
2108
+ /**
2109
+ * Unknown option `flag`.
2110
+ *
2111
+ * @param {string} flag
2112
+ * @private
2113
+ */
2114
+
2115
+ unknownOption(flag) {
2116
+ if (this._allowUnknownOption) return;
2117
+ let suggestion = '';
2118
+
2119
+ if (flag.startsWith('--') && this._showSuggestionAfterError) {
2120
+ // Looping to pick up the global options too
2121
+ let candidateFlags = [];
2122
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
2123
+ let command = this;
2124
+ do {
2125
+ const moreFlags = command
2126
+ .createHelp()
2127
+ .visibleOptions(command)
2128
+ .filter((option) => option.long)
2129
+ .map((option) => option.long);
2130
+ candidateFlags = candidateFlags.concat(moreFlags);
2131
+ command = command.parent;
2132
+ } while (command && !command._enablePositionalOptions);
2133
+ suggestion = suggestSimilar(flag, candidateFlags);
2134
+ }
2135
+
2136
+ const message = `error: unknown option '${flag}'${suggestion}`;
2137
+ this.error(message, { code: 'commander.unknownOption' });
2138
+ }
2139
+
2140
+ /**
2141
+ * Excess arguments, more than expected.
2142
+ *
2143
+ * @param {string[]} receivedArgs
2144
+ * @private
2145
+ */
2146
+
2147
+ _excessArguments(receivedArgs) {
2148
+ if (this._allowExcessArguments) return;
2149
+
2150
+ const expected = this.registeredArguments.length;
2151
+ const s = expected === 1 ? '' : 's';
2152
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : '';
2153
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
2154
+ this.error(message, { code: 'commander.excessArguments' });
2155
+ }
2156
+
2157
+ /**
2158
+ * Unknown command.
2159
+ *
2160
+ * @private
2161
+ */
2162
+
2163
+ unknownCommand() {
2164
+ const unknownName = this.args[0];
2165
+ let suggestion = '';
2166
+
2167
+ if (this._showSuggestionAfterError) {
2168
+ const candidateNames = [];
2169
+ this.createHelp()
2170
+ .visibleCommands(this)
2171
+ .forEach((command) => {
2172
+ candidateNames.push(command.name());
2173
+ // just visible alias
2174
+ if (command.alias()) candidateNames.push(command.alias());
2175
+ });
2176
+ suggestion = suggestSimilar(unknownName, candidateNames);
2177
+ }
2178
+
2179
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
2180
+ this.error(message, { code: 'commander.unknownCommand' });
2181
+ }
2182
+
2183
+ /**
2184
+ * Get or set the program version.
2185
+ *
2186
+ * This method auto-registers the "-V, --version" option which will print the version number.
2187
+ *
2188
+ * You can optionally supply the flags and description to override the defaults.
2189
+ *
2190
+ * @param {string} [str]
2191
+ * @param {string} [flags]
2192
+ * @param {string} [description]
2193
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
2194
+ */
2195
+
2196
+ version(str, flags, description) {
2197
+ if (str === undefined) return this._version;
2198
+ this._version = str;
2199
+ flags = flags || '-V, --version';
2200
+ description = description || 'output the version number';
2201
+ const versionOption = this.createOption(flags, description);
2202
+ this._versionOptionName = versionOption.attributeName();
2203
+ this._registerOption(versionOption);
2204
+
2205
+ this.on('option:' + versionOption.name(), () => {
2206
+ this._outputConfiguration.writeOut(`${str}\n`);
2207
+ this._exit(0, 'commander.version', str);
2208
+ });
2209
+ return this;
2210
+ }
2211
+
2212
+ /**
2213
+ * Set the description.
2214
+ *
2215
+ * @param {string} [str]
2216
+ * @param {object} [argsDescription]
2217
+ * @return {(string|Command)}
2218
+ */
2219
+ description(str, argsDescription) {
2220
+ if (str === undefined && argsDescription === undefined)
2221
+ return this._description;
2222
+ this._description = str;
2223
+ if (argsDescription) {
2224
+ this._argsDescription = argsDescription;
2225
+ }
2226
+ return this;
2227
+ }
2228
+
2229
+ /**
2230
+ * Set the summary. Used when listed as subcommand of parent.
2231
+ *
2232
+ * @param {string} [str]
2233
+ * @return {(string|Command)}
2234
+ */
2235
+ summary(str) {
2236
+ if (str === undefined) return this._summary;
2237
+ this._summary = str;
2238
+ return this;
2239
+ }
2240
+
2241
+ /**
2242
+ * Set an alias for the command.
2243
+ *
2244
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
2245
+ *
2246
+ * @param {string} [alias]
2247
+ * @return {(string|Command)}
2248
+ */
2249
+
2250
+ alias(alias) {
2251
+ if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility
2252
+
2253
+ /** @type {Command} */
2254
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
2255
+ let command = this;
2256
+ if (
2257
+ this.commands.length !== 0 &&
2258
+ this.commands[this.commands.length - 1]._executableHandler
2259
+ ) {
2260
+ // assume adding alias for last added executable subcommand, rather than this
2261
+ command = this.commands[this.commands.length - 1];
2262
+ }
2263
+
2264
+ if (alias === command._name)
2265
+ throw new Error("Command alias can't be the same as its name");
2266
+ const matchingCommand = this.parent?._findCommand(alias);
2267
+ if (matchingCommand) {
2268
+ // c.f. _registerCommand
2269
+ const existingCmd = [matchingCommand.name()]
2270
+ .concat(matchingCommand.aliases())
2271
+ .join('|');
2272
+ throw new Error(
2273
+ `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`,
2274
+ );
2275
+ }
2276
+
2277
+ command._aliases.push(alias);
2278
+ return this;
2279
+ }
2280
+
2281
+ /**
2282
+ * Set aliases for the command.
2283
+ *
2284
+ * Only the first alias is shown in the auto-generated help.
2285
+ *
2286
+ * @param {string[]} [aliases]
2287
+ * @return {(string[]|Command)}
2288
+ */
2289
+
2290
+ aliases(aliases) {
2291
+ // Getter for the array of aliases is the main reason for having aliases() in addition to alias().
2292
+ if (aliases === undefined) return this._aliases;
2293
+
2294
+ aliases.forEach((alias) => this.alias(alias));
2295
+ return this;
2296
+ }
2297
+
2298
+ /**
2299
+ * Set / get the command usage `str`.
2300
+ *
2301
+ * @param {string} [str]
2302
+ * @return {(string|Command)}
2303
+ */
2304
+
2305
+ usage(str) {
2306
+ if (str === undefined) {
2307
+ if (this._usage) return this._usage;
2308
+
2309
+ const args = this.registeredArguments.map((arg) => {
2310
+ return humanReadableArgName(arg);
2311
+ });
2312
+ return []
2313
+ .concat(
2314
+ this.options.length || this._helpOption !== null ? '[options]' : [],
2315
+ this.commands.length ? '[command]' : [],
2316
+ this.registeredArguments.length ? args : [],
2317
+ )
2318
+ .join(' ');
2319
+ }
2320
+
2321
+ this._usage = str;
2322
+ return this;
2323
+ }
2324
+
2325
+ /**
2326
+ * Get or set the name of the command.
2327
+ *
2328
+ * @param {string} [str]
2329
+ * @return {(string|Command)}
2330
+ */
2331
+
2332
+ name(str) {
2333
+ if (str === undefined) return this._name;
2334
+ this._name = str;
2335
+ return this;
2336
+ }
2337
+
2338
+ /**
2339
+ * Set/get the help group heading for this subcommand in parent command's help.
2340
+ *
2341
+ * @param {string} [heading]
2342
+ * @return {Command | string}
2343
+ */
2344
+
2345
+ helpGroup(heading) {
2346
+ if (heading === undefined) return this._helpGroupHeading ?? '';
2347
+ this._helpGroupHeading = heading;
2348
+ return this;
2349
+ }
2350
+
2351
+ /**
2352
+ * Set/get the default help group heading for subcommands added to this command.
2353
+ * (This does not override a group set directly on the subcommand using .helpGroup().)
2354
+ *
2355
+ * @example
2356
+ * program.commandsGroup('Development Commands:);
2357
+ * program.command('watch')...
2358
+ * program.command('lint')...
2359
+ * ...
2360
+ *
2361
+ * @param {string} [heading]
2362
+ * @returns {Command | string}
2363
+ */
2364
+ commandsGroup(heading) {
2365
+ if (heading === undefined) return this._defaultCommandGroup ?? '';
2366
+ this._defaultCommandGroup = heading;
2367
+ return this;
2368
+ }
2369
+
2370
+ /**
2371
+ * Set/get the default help group heading for options added to this command.
2372
+ * (This does not override a group set directly on the option using .helpGroup().)
2373
+ *
2374
+ * @example
2375
+ * program
2376
+ * .optionsGroup('Development Options:')
2377
+ * .option('-d, --debug', 'output extra debugging')
2378
+ * .option('-p, --profile', 'output profiling information')
2379
+ *
2380
+ * @param {string} [heading]
2381
+ * @returns {Command | string}
2382
+ */
2383
+ optionsGroup(heading) {
2384
+ if (heading === undefined) return this._defaultOptionGroup ?? '';
2385
+ this._defaultOptionGroup = heading;
2386
+ return this;
2387
+ }
2388
+
2389
+ /**
2390
+ * @param {Option} option
2391
+ * @private
2392
+ */
2393
+ _initOptionGroup(option) {
2394
+ if (this._defaultOptionGroup && !option.helpGroupHeading)
2395
+ option.helpGroup(this._defaultOptionGroup);
2396
+ }
2397
+
2398
+ /**
2399
+ * @param {Command} cmd
2400
+ * @private
2401
+ */
2402
+ _initCommandGroup(cmd) {
2403
+ if (this._defaultCommandGroup && !cmd.helpGroup())
2404
+ cmd.helpGroup(this._defaultCommandGroup);
2405
+ }
2406
+
2407
+ /**
2408
+ * Set the name of the command from script filename, such as process.argv[1],
2409
+ * or require.main.filename, or __filename.
2410
+ *
2411
+ * (Used internally and public although not documented in README.)
2412
+ *
2413
+ * @example
2414
+ * program.nameFromFilename(require.main.filename);
2415
+ *
2416
+ * @param {string} filename
2417
+ * @return {Command}
2418
+ */
2419
+
2420
+ nameFromFilename(filename) {
2421
+ this._name = path.basename(filename, path.extname(filename));
2422
+
2423
+ return this;
2424
+ }
2425
+
2426
+ /**
2427
+ * Get or set the directory for searching for executable subcommands of this command.
2428
+ *
2429
+ * @example
2430
+ * program.executableDir(__dirname);
2431
+ * // or
2432
+ * program.executableDir('subcommands');
2433
+ *
2434
+ * @param {string} [path]
2435
+ * @return {(string|null|Command)}
2436
+ */
2437
+
2438
+ executableDir(path) {
2439
+ if (path === undefined) return this._executableDir;
2440
+ this._executableDir = path;
2441
+ return this;
2442
+ }
2443
+
2444
+ /**
2445
+ * Return program help documentation.
2446
+ *
2447
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
2448
+ * @return {string}
2449
+ */
2450
+
2451
+ helpInformation(contextOptions) {
2452
+ const helper = this.createHelp();
2453
+ const context = this._getOutputContext(contextOptions);
2454
+ helper.prepareContext({
2455
+ error: context.error,
2456
+ helpWidth: context.helpWidth,
2457
+ outputHasColors: context.hasColors,
2458
+ });
2459
+ const text = helper.formatHelp(this, helper);
2460
+ if (context.hasColors) return text;
2461
+ return this._outputConfiguration.stripColor(text);
2462
+ }
2463
+
2464
+ /**
2465
+ * @typedef HelpContext
2466
+ * @type {object}
2467
+ * @property {boolean} error
2468
+ * @property {number} helpWidth
2469
+ * @property {boolean} hasColors
2470
+ * @property {function} write - includes stripColor if needed
2471
+ *
2472
+ * @returns {HelpContext}
2473
+ * @private
2474
+ */
2475
+
2476
+ _getOutputContext(contextOptions) {
2477
+ contextOptions = contextOptions || {};
2478
+ const error = !!contextOptions.error;
2479
+ let baseWrite;
2480
+ let hasColors;
2481
+ let helpWidth;
2482
+ if (error) {
2483
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
2484
+ hasColors = this._outputConfiguration.getErrHasColors();
2485
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
2486
+ } else {
2487
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
2488
+ hasColors = this._outputConfiguration.getOutHasColors();
2489
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
2490
+ }
2491
+ const write = (str) => {
2492
+ if (!hasColors) str = this._outputConfiguration.stripColor(str);
2493
+ return baseWrite(str);
2494
+ };
2495
+ return { error, write, hasColors, helpWidth };
2496
+ }
2497
+
2498
+ /**
2499
+ * Output help information for this command.
2500
+ *
2501
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2502
+ *
2503
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2504
+ */
2505
+
2506
+ outputHelp(contextOptions) {
2507
+ let deprecatedCallback;
2508
+ if (typeof contextOptions === 'function') {
2509
+ deprecatedCallback = contextOptions;
2510
+ contextOptions = undefined;
2511
+ }
2512
+
2513
+ const outputContext = this._getOutputContext(contextOptions);
2514
+ /** @type {HelpTextEventContext} */
2515
+ const eventContext = {
2516
+ error: outputContext.error,
2517
+ write: outputContext.write,
2518
+ command: this,
2519
+ };
2520
+
2521
+ this._getCommandAndAncestors()
2522
+ .reverse()
2523
+ .forEach((command) => command.emit('beforeAllHelp', eventContext));
2524
+ this.emit('beforeHelp', eventContext);
2525
+
2526
+ let helpInformation = this.helpInformation({ error: outputContext.error });
2527
+ if (deprecatedCallback) {
2528
+ helpInformation = deprecatedCallback(helpInformation);
2529
+ if (
2530
+ typeof helpInformation !== 'string' &&
2531
+ !Buffer.isBuffer(helpInformation)
2532
+ ) {
2533
+ throw new Error('outputHelp callback must return a string or a Buffer');
2534
+ }
2535
+ }
2536
+ outputContext.write(helpInformation);
2537
+
2538
+ if (this._getHelpOption()?.long) {
2539
+ this.emit(this._getHelpOption().long); // deprecated
2540
+ }
2541
+ this.emit('afterHelp', eventContext);
2542
+ this._getCommandAndAncestors().forEach((command) =>
2543
+ command.emit('afterAllHelp', eventContext),
2544
+ );
2545
+ }
2546
+
2547
+ /**
2548
+ * You can pass in flags and a description to customise the built-in help option.
2549
+ * Pass in false to disable the built-in help option.
2550
+ *
2551
+ * @example
2552
+ * program.helpOption('-?, --help' 'show help'); // customise
2553
+ * program.helpOption(false); // disable
2554
+ *
2555
+ * @param {(string | boolean)} flags
2556
+ * @param {string} [description]
2557
+ * @return {Command} `this` command for chaining
2558
+ */
2559
+
2560
+ helpOption(flags, description) {
2561
+ // Support enabling/disabling built-in help option.
2562
+ if (typeof flags === 'boolean') {
2563
+ if (flags) {
2564
+ if (this._helpOption === null) this._helpOption = undefined; // reenable
2565
+ if (this._defaultOptionGroup) {
2566
+ // make the option to store the group
2567
+ this._initOptionGroup(this._getHelpOption());
2568
+ }
2569
+ } else {
2570
+ this._helpOption = null; // disable
2571
+ }
2572
+ return this;
2573
+ }
2574
+
2575
+ // Customise flags and description.
2576
+ this._helpOption = this.createOption(
2577
+ flags ?? '-h, --help',
2578
+ description ?? 'display help for command',
2579
+ );
2580
+ // init group unless lazy create
2581
+ if (flags || description) this._initOptionGroup(this._helpOption);
2582
+
2583
+ return this;
2584
+ }
2585
+
2586
+ /**
2587
+ * Lazy create help option.
2588
+ * Returns null if has been disabled with .helpOption(false).
2589
+ *
2590
+ * @returns {(Option | null)} the help option
2591
+ * @package
2592
+ */
2593
+ _getHelpOption() {
2594
+ // Lazy create help option on demand.
2595
+ if (this._helpOption === undefined) {
2596
+ this.helpOption(undefined, undefined);
2597
+ }
2598
+ return this._helpOption;
2599
+ }
2600
+
2601
+ /**
2602
+ * Supply your own option to use for the built-in help option.
2603
+ * This is an alternative to using helpOption() to customise the flags and description etc.
2604
+ *
2605
+ * @param {Option} option
2606
+ * @return {Command} `this` command for chaining
2607
+ */
2608
+ addHelpOption(option) {
2609
+ this._helpOption = option;
2610
+ this._initOptionGroup(option);
2611
+ return this;
2612
+ }
2613
+
2614
+ /**
2615
+ * Output help information and exit.
2616
+ *
2617
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2618
+ *
2619
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2620
+ */
2621
+
2622
+ help(contextOptions) {
2623
+ this.outputHelp(contextOptions);
2624
+ let exitCode = Number(process.exitCode ?? 0); // process.exitCode does allow a string or an integer, but we prefer just a number
2625
+ if (
2626
+ exitCode === 0 &&
2627
+ contextOptions &&
2628
+ typeof contextOptions !== 'function' &&
2629
+ contextOptions.error
2630
+ ) {
2631
+ exitCode = 1;
2632
+ }
2633
+ // message: do not have all displayed text available so only passing placeholder.
2634
+ this._exit(exitCode, 'commander.help', '(outputHelp)');
2635
+ }
2636
+
2637
+ /**
2638
+ * // Do a little typing to coordinate emit and listener for the help text events.
2639
+ * @typedef HelpTextEventContext
2640
+ * @type {object}
2641
+ * @property {boolean} error
2642
+ * @property {Command} command
2643
+ * @property {function} write
2644
+ */
2645
+
2646
+ /**
2647
+ * Add additional text to be displayed with the built-in help.
2648
+ *
2649
+ * Position is 'before' or 'after' to affect just this command,
2650
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
2651
+ *
2652
+ * @param {string} position - before or after built-in help
2653
+ * @param {(string | Function)} text - string to add, or a function returning a string
2654
+ * @return {Command} `this` command for chaining
2655
+ */
2656
+
2657
+ addHelpText(position, text) {
2658
+ const allowedValues = ['beforeAll', 'before', 'after', 'afterAll'];
2659
+ if (!allowedValues.includes(position)) {
2660
+ throw new Error(`Unexpected value for position to addHelpText.
2661
+ Expecting one of '${allowedValues.join("', '")}'`);
2662
+ }
2663
+
2664
+ const helpEvent = `${position}Help`;
2665
+ this.on(helpEvent, (/** @type {HelpTextEventContext} */ context) => {
2666
+ let helpStr;
2667
+ if (typeof text === 'function') {
2668
+ helpStr = text({ error: context.error, command: context.command });
2669
+ } else {
2670
+ helpStr = text;
2671
+ }
2672
+ // Ignore falsy value when nothing to output.
2673
+ if (helpStr) {
2674
+ context.write(`${helpStr}\n`);
2675
+ }
2676
+ });
2677
+ return this;
2678
+ }
2679
+
2680
+ /**
2681
+ * Output help information if help flags specified
2682
+ *
2683
+ * @param {Array} args - array of options to search for help flags
2684
+ * @private
2685
+ */
2686
+
2687
+ _outputHelpIfRequested(args) {
2688
+ const helpOption = this._getHelpOption();
2689
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
2690
+ if (helpRequested) {
2691
+ this.outputHelp();
2692
+ // (Do not have all displayed text available so only passing placeholder.)
2693
+ this._exit(0, 'commander.helpDisplayed', '(outputHelp)');
2694
+ }
2695
+ }
2696
+ }
2697
+
2698
+ /**
2699
+ * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).
2700
+ *
2701
+ * @param {string[]} args - array of arguments from node.execArgv
2702
+ * @returns {string[]}
2703
+ * @private
2704
+ */
2705
+
2706
+ function incrementNodeInspectorPort(args) {
2707
+ // Testing for these options:
2708
+ // --inspect[=[host:]port]
2709
+ // --inspect-brk[=[host:]port]
2710
+ // --inspect-port=[host:]port
2711
+ return args.map((arg) => {
2712
+ if (!arg.startsWith('--inspect')) {
2713
+ return arg;
2714
+ }
2715
+ let debugOption;
2716
+ let debugHost = '127.0.0.1';
2717
+ let debugPort = '9229';
2718
+ let match;
2719
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
2720
+ // e.g. --inspect
2721
+ debugOption = match[1];
2722
+ } else if (
2723
+ (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null
2724
+ ) {
2725
+ debugOption = match[1];
2726
+ if (/^\d+$/.test(match[3])) {
2727
+ // e.g. --inspect=1234
2728
+ debugPort = match[3];
2729
+ } else {
2730
+ // e.g. --inspect=localhost
2731
+ debugHost = match[3];
2732
+ }
2733
+ } else if (
2734
+ (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null
2735
+ ) {
2736
+ // e.g. --inspect=localhost:1234
2737
+ debugOption = match[1];
2738
+ debugHost = match[3];
2739
+ debugPort = match[4];
2740
+ }
2741
+
2742
+ if (debugOption && debugPort !== '0') {
2743
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
2744
+ }
2745
+ return arg;
2746
+ });
2747
+ }
2748
+
2749
+ /**
2750
+ * @returns {boolean | undefined}
2751
+ * @package
2752
+ */
2753
+ function useColor() {
2754
+ // Test for common conventions.
2755
+ // NB: the observed behaviour is in combination with how author adds color! For example:
2756
+ // - we do not test NODE_DISABLE_COLORS, but util:styletext does
2757
+ // - we do test NO_COLOR, but Chalk does not
2758
+ //
2759
+ // References:
2760
+ // https://no-color.org
2761
+ // https://bixense.com/clicolors/
2762
+ // https://github.com/nodejs/node/blob/0a00217a5f67ef4a22384cfc80eb6dd9a917fdc1/lib/internal/tty.js#L109
2763
+ // https://github.com/chalk/supports-color/blob/c214314a14bcb174b12b3014b2b0a8de375029ae/index.js#L33
2764
+ // (https://force-color.org recent web page from 2023, does not match major javascript implementations)
2765
+
2766
+ if (
2767
+ process.env.NO_COLOR ||
2768
+ process.env.FORCE_COLOR === '0' ||
2769
+ process.env.FORCE_COLOR === 'false'
2770
+ )
2771
+ return false;
2772
+ if (process.env.FORCE_COLOR || process.env.CLICOLOR_FORCE !== undefined)
2773
+ return true;
2774
+ return undefined;
2775
+ }
2776
+
2777
+ exports.Command = Command;
2778
+ exports.useColor = useColor; // exporting for tests