@rokelamen/md2html 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/cli.cjs ADDED
@@ -0,0 +1,4386 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ var require$$0 = require('node:events');
5
+ var require$$1 = require('node:child_process');
6
+ var require$$2 = require('node:path');
7
+ var require$$3 = require('node:fs');
8
+ var require$$4 = require('node:process');
9
+ var fs = require('fs');
10
+
11
+ function _interopNamespaceDefault(e) {
12
+ var n = Object.create(null);
13
+ if (e) {
14
+ Object.keys(e).forEach(function (k) {
15
+ if (k !== 'default') {
16
+ var d = Object.getOwnPropertyDescriptor(e, k);
17
+ Object.defineProperty(n, k, d.get ? d : {
18
+ enumerable: true,
19
+ get: function () { return e[k]; }
20
+ });
21
+ }
22
+ });
23
+ }
24
+ n.default = e;
25
+ return Object.freeze(n);
26
+ }
27
+
28
+ var fs__namespace = /*#__PURE__*/_interopNamespaceDefault(fs);
29
+
30
+ function getDefaultExportFromCjs (x) {
31
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
32
+ }
33
+
34
+ var commander$1 = {};
35
+
36
+ var argument = {};
37
+
38
+ var error = {};
39
+
40
+ /**
41
+ * CommanderError class
42
+ */
43
+
44
+ var hasRequiredError;
45
+
46
+ function requireError () {
47
+ if (hasRequiredError) return error;
48
+ hasRequiredError = 1;
49
+ class CommanderError extends Error {
50
+ /**
51
+ * Constructs the CommanderError class
52
+ * @param {number} exitCode suggested exit code which could be used with process.exit
53
+ * @param {string} code an id string representing the error
54
+ * @param {string} message human-readable description of the error
55
+ */
56
+ constructor(exitCode, code, message) {
57
+ super(message);
58
+ // properly capture stack trace in Node.js
59
+ Error.captureStackTrace(this, this.constructor);
60
+ this.name = this.constructor.name;
61
+ this.code = code;
62
+ this.exitCode = exitCode;
63
+ this.nestedError = undefined;
64
+ }
65
+ }
66
+
67
+ /**
68
+ * InvalidArgumentError class
69
+ */
70
+ class InvalidArgumentError extends CommanderError {
71
+ /**
72
+ * Constructs the InvalidArgumentError class
73
+ * @param {string} [message] explanation of why argument is invalid
74
+ */
75
+ constructor(message) {
76
+ super(1, 'commander.invalidArgument', message);
77
+ // properly capture stack trace in Node.js
78
+ Error.captureStackTrace(this, this.constructor);
79
+ this.name = this.constructor.name;
80
+ }
81
+ }
82
+
83
+ error.CommanderError = CommanderError;
84
+ error.InvalidArgumentError = InvalidArgumentError;
85
+ return error;
86
+ }
87
+
88
+ var hasRequiredArgument;
89
+
90
+ function requireArgument () {
91
+ if (hasRequiredArgument) return argument;
92
+ hasRequiredArgument = 1;
93
+ const { InvalidArgumentError } = requireError();
94
+
95
+ class Argument {
96
+ /**
97
+ * Initialize a new command argument with the given name and description.
98
+ * The default is that the argument is required, and you can explicitly
99
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
100
+ *
101
+ * @param {string} name
102
+ * @param {string} [description]
103
+ */
104
+
105
+ constructor(name, description) {
106
+ this.description = description || '';
107
+ this.variadic = false;
108
+ this.parseArg = undefined;
109
+ this.defaultValue = undefined;
110
+ this.defaultValueDescription = undefined;
111
+ this.argChoices = undefined;
112
+
113
+ switch (name[0]) {
114
+ case '<': // e.g. <required>
115
+ this.required = true;
116
+ this._name = name.slice(1, -1);
117
+ break;
118
+ case '[': // e.g. [optional]
119
+ this.required = false;
120
+ this._name = name.slice(1, -1);
121
+ break;
122
+ default:
123
+ this.required = true;
124
+ this._name = name;
125
+ break;
126
+ }
127
+
128
+ if (this._name.endsWith('...')) {
129
+ this.variadic = true;
130
+ this._name = this._name.slice(0, -3);
131
+ }
132
+ }
133
+
134
+ /**
135
+ * Return argument name.
136
+ *
137
+ * @return {string}
138
+ */
139
+
140
+ name() {
141
+ return this._name;
142
+ }
143
+
144
+ /**
145
+ * @package
146
+ */
147
+
148
+ _collectValue(value, previous) {
149
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
150
+ return [value];
151
+ }
152
+
153
+ previous.push(value);
154
+ return previous;
155
+ }
156
+
157
+ /**
158
+ * Set the default value, and optionally supply the description to be displayed in the help.
159
+ *
160
+ * @param {*} value
161
+ * @param {string} [description]
162
+ * @return {Argument}
163
+ */
164
+
165
+ default(value, description) {
166
+ this.defaultValue = value;
167
+ this.defaultValueDescription = description;
168
+ return this;
169
+ }
170
+
171
+ /**
172
+ * Set the custom handler for processing CLI command arguments into argument values.
173
+ *
174
+ * @param {Function} [fn]
175
+ * @return {Argument}
176
+ */
177
+
178
+ argParser(fn) {
179
+ this.parseArg = fn;
180
+ return this;
181
+ }
182
+
183
+ /**
184
+ * Only allow argument value to be one of choices.
185
+ *
186
+ * @param {string[]} values
187
+ * @return {Argument}
188
+ */
189
+
190
+ choices(values) {
191
+ this.argChoices = values.slice();
192
+ this.parseArg = (arg, previous) => {
193
+ if (!this.argChoices.includes(arg)) {
194
+ throw new InvalidArgumentError(
195
+ `Allowed choices are ${this.argChoices.join(', ')}.`,
196
+ );
197
+ }
198
+ if (this.variadic) {
199
+ return this._collectValue(arg, previous);
200
+ }
201
+ return arg;
202
+ };
203
+ return this;
204
+ }
205
+
206
+ /**
207
+ * Make argument required.
208
+ *
209
+ * @returns {Argument}
210
+ */
211
+ argRequired() {
212
+ this.required = true;
213
+ return this;
214
+ }
215
+
216
+ /**
217
+ * Make argument optional.
218
+ *
219
+ * @returns {Argument}
220
+ */
221
+ argOptional() {
222
+ this.required = false;
223
+ return this;
224
+ }
225
+ }
226
+
227
+ /**
228
+ * Takes an argument and returns its human readable equivalent for help usage.
229
+ *
230
+ * @param {Argument} arg
231
+ * @return {string}
232
+ * @private
233
+ */
234
+
235
+ function humanReadableArgName(arg) {
236
+ const nameOutput = arg.name() + (arg.variadic === true ? '...' : '');
237
+
238
+ return arg.required ? '<' + nameOutput + '>' : '[' + nameOutput + ']';
239
+ }
240
+
241
+ argument.Argument = Argument;
242
+ argument.humanReadableArgName = humanReadableArgName;
243
+ return argument;
244
+ }
245
+
246
+ var command$1 = {};
247
+
248
+ var help = {};
249
+
250
+ var hasRequiredHelp;
251
+
252
+ function requireHelp () {
253
+ if (hasRequiredHelp) return help;
254
+ hasRequiredHelp = 1;
255
+ const { humanReadableArgName } = requireArgument();
256
+
257
+ /**
258
+ * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`
259
+ * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types
260
+ * @typedef { import("./argument.js").Argument } Argument
261
+ * @typedef { import("./command.js").Command } Command
262
+ * @typedef { import("./option.js").Option } Option
263
+ */
264
+
265
+ // Although this is a class, methods are static in style to allow override using subclass or just functions.
266
+ class Help {
267
+ constructor() {
268
+ this.helpWidth = undefined;
269
+ this.minWidthToWrap = 40;
270
+ this.sortSubcommands = false;
271
+ this.sortOptions = false;
272
+ this.showGlobalOptions = false;
273
+ }
274
+
275
+ /**
276
+ * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
277
+ * and just before calling `formatHelp()`.
278
+ *
279
+ * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
280
+ *
281
+ * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
282
+ */
283
+ prepareContext(contextOptions) {
284
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
285
+ }
286
+
287
+ /**
288
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
289
+ *
290
+ * @param {Command} cmd
291
+ * @returns {Command[]}
292
+ */
293
+
294
+ visibleCommands(cmd) {
295
+ const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);
296
+ const helpCommand = cmd._getHelpCommand();
297
+ if (helpCommand && !helpCommand._hidden) {
298
+ visibleCommands.push(helpCommand);
299
+ }
300
+ if (this.sortSubcommands) {
301
+ visibleCommands.sort((a, b) => {
302
+ // @ts-ignore: because overloaded return type
303
+ return a.name().localeCompare(b.name());
304
+ });
305
+ }
306
+ return visibleCommands;
307
+ }
308
+
309
+ /**
310
+ * Compare options for sort.
311
+ *
312
+ * @param {Option} a
313
+ * @param {Option} b
314
+ * @returns {number}
315
+ */
316
+ compareOptions(a, b) {
317
+ const getSortKey = (option) => {
318
+ // WYSIWYG for order displayed in help. Short used for comparison if present. No special handling for negated.
319
+ return option.short
320
+ ? option.short.replace(/^-/, '')
321
+ : option.long.replace(/^--/, '');
322
+ };
323
+ return getSortKey(a).localeCompare(getSortKey(b));
324
+ }
325
+
326
+ /**
327
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
328
+ *
329
+ * @param {Command} cmd
330
+ * @returns {Option[]}
331
+ */
332
+
333
+ visibleOptions(cmd) {
334
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
335
+ // Built-in help option.
336
+ const helpOption = cmd._getHelpOption();
337
+ if (helpOption && !helpOption.hidden) {
338
+ // Automatically hide conflicting flags. Bit dubious but a historical behaviour that is convenient for single-command programs.
339
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
340
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
341
+ if (!removeShort && !removeLong) {
342
+ visibleOptions.push(helpOption); // no changes needed
343
+ } else if (helpOption.long && !removeLong) {
344
+ visibleOptions.push(
345
+ cmd.createOption(helpOption.long, helpOption.description),
346
+ );
347
+ } else if (helpOption.short && !removeShort) {
348
+ visibleOptions.push(
349
+ cmd.createOption(helpOption.short, helpOption.description),
350
+ );
351
+ }
352
+ }
353
+ if (this.sortOptions) {
354
+ visibleOptions.sort(this.compareOptions);
355
+ }
356
+ return visibleOptions;
357
+ }
358
+
359
+ /**
360
+ * Get an array of the visible global options. (Not including help.)
361
+ *
362
+ * @param {Command} cmd
363
+ * @returns {Option[]}
364
+ */
365
+
366
+ visibleGlobalOptions(cmd) {
367
+ if (!this.showGlobalOptions) return [];
368
+
369
+ const globalOptions = [];
370
+ for (
371
+ let ancestorCmd = cmd.parent;
372
+ ancestorCmd;
373
+ ancestorCmd = ancestorCmd.parent
374
+ ) {
375
+ const visibleOptions = ancestorCmd.options.filter(
376
+ (option) => !option.hidden,
377
+ );
378
+ globalOptions.push(...visibleOptions);
379
+ }
380
+ if (this.sortOptions) {
381
+ globalOptions.sort(this.compareOptions);
382
+ }
383
+ return globalOptions;
384
+ }
385
+
386
+ /**
387
+ * Get an array of the arguments if any have a description.
388
+ *
389
+ * @param {Command} cmd
390
+ * @returns {Argument[]}
391
+ */
392
+
393
+ visibleArguments(cmd) {
394
+ // Side effect! Apply the legacy descriptions before the arguments are displayed.
395
+ if (cmd._argsDescription) {
396
+ cmd.registeredArguments.forEach((argument) => {
397
+ argument.description =
398
+ argument.description || cmd._argsDescription[argument.name()] || '';
399
+ });
400
+ }
401
+
402
+ // If there are any arguments with a description then return all the arguments.
403
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
404
+ return cmd.registeredArguments;
405
+ }
406
+ return [];
407
+ }
408
+
409
+ /**
410
+ * Get the command term to show in the list of subcommands.
411
+ *
412
+ * @param {Command} cmd
413
+ * @returns {string}
414
+ */
415
+
416
+ subcommandTerm(cmd) {
417
+ // Legacy. Ignores custom usage string, and nested commands.
418
+ const args = cmd.registeredArguments
419
+ .map((arg) => humanReadableArgName(arg))
420
+ .join(' ');
421
+ return (
422
+ cmd._name +
423
+ (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') +
424
+ (cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option
425
+ (args ? ' ' + args : '')
426
+ );
427
+ }
428
+
429
+ /**
430
+ * Get the option term to show in the list of options.
431
+ *
432
+ * @param {Option} option
433
+ * @returns {string}
434
+ */
435
+
436
+ optionTerm(option) {
437
+ return option.flags;
438
+ }
439
+
440
+ /**
441
+ * Get the argument term to show in the list of arguments.
442
+ *
443
+ * @param {Argument} argument
444
+ * @returns {string}
445
+ */
446
+
447
+ argumentTerm(argument) {
448
+ return argument.name();
449
+ }
450
+
451
+ /**
452
+ * Get the longest command term length.
453
+ *
454
+ * @param {Command} cmd
455
+ * @param {Help} helper
456
+ * @returns {number}
457
+ */
458
+
459
+ longestSubcommandTermLength(cmd, helper) {
460
+ return helper.visibleCommands(cmd).reduce((max, command) => {
461
+ return Math.max(
462
+ max,
463
+ this.displayWidth(
464
+ helper.styleSubcommandTerm(helper.subcommandTerm(command)),
465
+ ),
466
+ );
467
+ }, 0);
468
+ }
469
+
470
+ /**
471
+ * Get the longest option term length.
472
+ *
473
+ * @param {Command} cmd
474
+ * @param {Help} helper
475
+ * @returns {number}
476
+ */
477
+
478
+ longestOptionTermLength(cmd, helper) {
479
+ return helper.visibleOptions(cmd).reduce((max, option) => {
480
+ return Math.max(
481
+ max,
482
+ this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))),
483
+ );
484
+ }, 0);
485
+ }
486
+
487
+ /**
488
+ * Get the longest global option term length.
489
+ *
490
+ * @param {Command} cmd
491
+ * @param {Help} helper
492
+ * @returns {number}
493
+ */
494
+
495
+ longestGlobalOptionTermLength(cmd, helper) {
496
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
497
+ return Math.max(
498
+ max,
499
+ this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))),
500
+ );
501
+ }, 0);
502
+ }
503
+
504
+ /**
505
+ * Get the longest argument term length.
506
+ *
507
+ * @param {Command} cmd
508
+ * @param {Help} helper
509
+ * @returns {number}
510
+ */
511
+
512
+ longestArgumentTermLength(cmd, helper) {
513
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
514
+ return Math.max(
515
+ max,
516
+ this.displayWidth(
517
+ helper.styleArgumentTerm(helper.argumentTerm(argument)),
518
+ ),
519
+ );
520
+ }, 0);
521
+ }
522
+
523
+ /**
524
+ * Get the command usage to be displayed at the top of the built-in help.
525
+ *
526
+ * @param {Command} cmd
527
+ * @returns {string}
528
+ */
529
+
530
+ commandUsage(cmd) {
531
+ // Usage
532
+ let cmdName = cmd._name;
533
+ if (cmd._aliases[0]) {
534
+ cmdName = cmdName + '|' + cmd._aliases[0];
535
+ }
536
+ let ancestorCmdNames = '';
537
+ for (
538
+ let ancestorCmd = cmd.parent;
539
+ ancestorCmd;
540
+ ancestorCmd = ancestorCmd.parent
541
+ ) {
542
+ ancestorCmdNames = ancestorCmd.name() + ' ' + ancestorCmdNames;
543
+ }
544
+ return ancestorCmdNames + cmdName + ' ' + cmd.usage();
545
+ }
546
+
547
+ /**
548
+ * Get the description for the command.
549
+ *
550
+ * @param {Command} cmd
551
+ * @returns {string}
552
+ */
553
+
554
+ commandDescription(cmd) {
555
+ // @ts-ignore: because overloaded return type
556
+ return cmd.description();
557
+ }
558
+
559
+ /**
560
+ * Get the subcommand summary to show in the list of subcommands.
561
+ * (Fallback to description for backwards compatibility.)
562
+ *
563
+ * @param {Command} cmd
564
+ * @returns {string}
565
+ */
566
+
567
+ subcommandDescription(cmd) {
568
+ // @ts-ignore: because overloaded return type
569
+ return cmd.summary() || cmd.description();
570
+ }
571
+
572
+ /**
573
+ * Get the option description to show in the list of options.
574
+ *
575
+ * @param {Option} option
576
+ * @return {string}
577
+ */
578
+
579
+ optionDescription(option) {
580
+ const extraInfo = [];
581
+
582
+ if (option.argChoices) {
583
+ extraInfo.push(
584
+ // use stringify to match the display of the default value
585
+ `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,
586
+ );
587
+ }
588
+ if (option.defaultValue !== undefined) {
589
+ // default for boolean and negated more for programmer than end user,
590
+ // but show true/false for boolean option as may be for hand-rolled env or config processing.
591
+ const showDefault =
592
+ option.required ||
593
+ option.optional ||
594
+ (option.isBoolean() && typeof option.defaultValue === 'boolean');
595
+ if (showDefault) {
596
+ extraInfo.push(
597
+ `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`,
598
+ );
599
+ }
600
+ }
601
+ // preset for boolean and negated are more for programmer than end user
602
+ if (option.presetArg !== undefined && option.optional) {
603
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
604
+ }
605
+ if (option.envVar !== undefined) {
606
+ extraInfo.push(`env: ${option.envVar}`);
607
+ }
608
+ if (extraInfo.length > 0) {
609
+ const extraDescription = `(${extraInfo.join(', ')})`;
610
+ if (option.description) {
611
+ return `${option.description} ${extraDescription}`;
612
+ }
613
+ return extraDescription;
614
+ }
615
+
616
+ return option.description;
617
+ }
618
+
619
+ /**
620
+ * Get the argument description to show in the list of arguments.
621
+ *
622
+ * @param {Argument} argument
623
+ * @return {string}
624
+ */
625
+
626
+ argumentDescription(argument) {
627
+ const extraInfo = [];
628
+ if (argument.argChoices) {
629
+ extraInfo.push(
630
+ // use stringify to match the display of the default value
631
+ `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,
632
+ );
633
+ }
634
+ if (argument.defaultValue !== undefined) {
635
+ extraInfo.push(
636
+ `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`,
637
+ );
638
+ }
639
+ if (extraInfo.length > 0) {
640
+ const extraDescription = `(${extraInfo.join(', ')})`;
641
+ if (argument.description) {
642
+ return `${argument.description} ${extraDescription}`;
643
+ }
644
+ return extraDescription;
645
+ }
646
+ return argument.description;
647
+ }
648
+
649
+ /**
650
+ * Format a list of items, given a heading and an array of formatted items.
651
+ *
652
+ * @param {string} heading
653
+ * @param {string[]} items
654
+ * @param {Help} helper
655
+ * @returns string[]
656
+ */
657
+ formatItemList(heading, items, helper) {
658
+ if (items.length === 0) return [];
659
+
660
+ return [helper.styleTitle(heading), ...items, ''];
661
+ }
662
+
663
+ /**
664
+ * Group items by their help group heading.
665
+ *
666
+ * @param {Command[] | Option[]} unsortedItems
667
+ * @param {Command[] | Option[]} visibleItems
668
+ * @param {Function} getGroup
669
+ * @returns {Map<string, Command[] | Option[]>}
670
+ */
671
+ groupItems(unsortedItems, visibleItems, getGroup) {
672
+ const result = new Map();
673
+ // Add groups in order of appearance in unsortedItems.
674
+ unsortedItems.forEach((item) => {
675
+ const group = getGroup(item);
676
+ if (!result.has(group)) result.set(group, []);
677
+ });
678
+ // Add items in order of appearance in visibleItems.
679
+ visibleItems.forEach((item) => {
680
+ const group = getGroup(item);
681
+ if (!result.has(group)) {
682
+ result.set(group, []);
683
+ }
684
+ result.get(group).push(item);
685
+ });
686
+ return result;
687
+ }
688
+
689
+ /**
690
+ * Generate the built-in help text.
691
+ *
692
+ * @param {Command} cmd
693
+ * @param {Help} helper
694
+ * @returns {string}
695
+ */
696
+
697
+ formatHelp(cmd, helper) {
698
+ const termWidth = helper.padWidth(cmd, helper);
699
+ const helpWidth = helper.helpWidth ?? 80; // in case prepareContext() was not called
700
+
701
+ function callFormatItem(term, description) {
702
+ return helper.formatItem(term, termWidth, description, helper);
703
+ }
704
+
705
+ // Usage
706
+ let output = [
707
+ `${helper.styleTitle('Usage:')} ${helper.styleUsage(helper.commandUsage(cmd))}`,
708
+ '',
709
+ ];
710
+
711
+ // Description
712
+ const commandDescription = helper.commandDescription(cmd);
713
+ if (commandDescription.length > 0) {
714
+ output = output.concat([
715
+ helper.boxWrap(
716
+ helper.styleCommandDescription(commandDescription),
717
+ helpWidth,
718
+ ),
719
+ '',
720
+ ]);
721
+ }
722
+
723
+ // Arguments
724
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
725
+ return callFormatItem(
726
+ helper.styleArgumentTerm(helper.argumentTerm(argument)),
727
+ helper.styleArgumentDescription(helper.argumentDescription(argument)),
728
+ );
729
+ });
730
+ output = output.concat(
731
+ this.formatItemList('Arguments:', argumentList, helper),
732
+ );
733
+
734
+ // Options
735
+ const optionGroups = this.groupItems(
736
+ cmd.options,
737
+ helper.visibleOptions(cmd),
738
+ (option) => option.helpGroupHeading ?? 'Options:',
739
+ );
740
+ optionGroups.forEach((options, group) => {
741
+ const optionList = options.map((option) => {
742
+ return callFormatItem(
743
+ helper.styleOptionTerm(helper.optionTerm(option)),
744
+ helper.styleOptionDescription(helper.optionDescription(option)),
745
+ );
746
+ });
747
+ output = output.concat(this.formatItemList(group, optionList, helper));
748
+ });
749
+
750
+ if (helper.showGlobalOptions) {
751
+ const globalOptionList = helper
752
+ .visibleGlobalOptions(cmd)
753
+ .map((option) => {
754
+ return callFormatItem(
755
+ helper.styleOptionTerm(helper.optionTerm(option)),
756
+ helper.styleOptionDescription(helper.optionDescription(option)),
757
+ );
758
+ });
759
+ output = output.concat(
760
+ this.formatItemList('Global Options:', globalOptionList, helper),
761
+ );
762
+ }
763
+
764
+ // Commands
765
+ const commandGroups = this.groupItems(
766
+ cmd.commands,
767
+ helper.visibleCommands(cmd),
768
+ (sub) => sub.helpGroup() || 'Commands:',
769
+ );
770
+ commandGroups.forEach((commands, group) => {
771
+ const commandList = commands.map((sub) => {
772
+ return callFormatItem(
773
+ helper.styleSubcommandTerm(helper.subcommandTerm(sub)),
774
+ helper.styleSubcommandDescription(helper.subcommandDescription(sub)),
775
+ );
776
+ });
777
+ output = output.concat(this.formatItemList(group, commandList, helper));
778
+ });
779
+
780
+ return output.join('\n');
781
+ }
782
+
783
+ /**
784
+ * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
785
+ *
786
+ * @param {string} str
787
+ * @returns {number}
788
+ */
789
+ displayWidth(str) {
790
+ return stripColor(str).length;
791
+ }
792
+
793
+ /**
794
+ * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
795
+ *
796
+ * @param {string} str
797
+ * @returns {string}
798
+ */
799
+ styleTitle(str) {
800
+ return str;
801
+ }
802
+
803
+ styleUsage(str) {
804
+ // Usage has lots of parts the user might like to color separately! Assume default usage string which is formed like:
805
+ // command subcommand [options] [command] <foo> [bar]
806
+ return str
807
+ .split(' ')
808
+ .map((word) => {
809
+ if (word === '[options]') return this.styleOptionText(word);
810
+ if (word === '[command]') return this.styleSubcommandText(word);
811
+ if (word[0] === '[' || word[0] === '<')
812
+ return this.styleArgumentText(word);
813
+ return this.styleCommandText(word); // Restrict to initial words?
814
+ })
815
+ .join(' ');
816
+ }
817
+ styleCommandDescription(str) {
818
+ return this.styleDescriptionText(str);
819
+ }
820
+ styleOptionDescription(str) {
821
+ return this.styleDescriptionText(str);
822
+ }
823
+ styleSubcommandDescription(str) {
824
+ return this.styleDescriptionText(str);
825
+ }
826
+ styleArgumentDescription(str) {
827
+ return this.styleDescriptionText(str);
828
+ }
829
+ styleDescriptionText(str) {
830
+ return str;
831
+ }
832
+ styleOptionTerm(str) {
833
+ return this.styleOptionText(str);
834
+ }
835
+ styleSubcommandTerm(str) {
836
+ // This is very like usage with lots of parts! Assume default string which is formed like:
837
+ // subcommand [options] <foo> [bar]
838
+ return str
839
+ .split(' ')
840
+ .map((word) => {
841
+ if (word === '[options]') return this.styleOptionText(word);
842
+ if (word[0] === '[' || word[0] === '<')
843
+ return this.styleArgumentText(word);
844
+ return this.styleSubcommandText(word); // Restrict to initial words?
845
+ })
846
+ .join(' ');
847
+ }
848
+ styleArgumentTerm(str) {
849
+ return this.styleArgumentText(str);
850
+ }
851
+ styleOptionText(str) {
852
+ return str;
853
+ }
854
+ styleArgumentText(str) {
855
+ return str;
856
+ }
857
+ styleSubcommandText(str) {
858
+ return str;
859
+ }
860
+ styleCommandText(str) {
861
+ return str;
862
+ }
863
+
864
+ /**
865
+ * Calculate the pad width from the maximum term length.
866
+ *
867
+ * @param {Command} cmd
868
+ * @param {Help} helper
869
+ * @returns {number}
870
+ */
871
+
872
+ padWidth(cmd, helper) {
873
+ return Math.max(
874
+ helper.longestOptionTermLength(cmd, helper),
875
+ helper.longestGlobalOptionTermLength(cmd, helper),
876
+ helper.longestSubcommandTermLength(cmd, helper),
877
+ helper.longestArgumentTermLength(cmd, helper),
878
+ );
879
+ }
880
+
881
+ /**
882
+ * Detect manually wrapped and indented strings by checking for line break followed by whitespace.
883
+ *
884
+ * @param {string} str
885
+ * @returns {boolean}
886
+ */
887
+ preformatted(str) {
888
+ return /\n[^\S\r\n]/.test(str);
889
+ }
890
+
891
+ /**
892
+ * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
893
+ *
894
+ * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
895
+ * TTT DDD DDDD
896
+ * DD DDD
897
+ *
898
+ * @param {string} term
899
+ * @param {number} termWidth
900
+ * @param {string} description
901
+ * @param {Help} helper
902
+ * @returns {string}
903
+ */
904
+ formatItem(term, termWidth, description, helper) {
905
+ const itemIndent = 2;
906
+ const itemIndentStr = ' '.repeat(itemIndent);
907
+ if (!description) return itemIndentStr + term;
908
+
909
+ // Pad the term out to a consistent width, so descriptions are aligned.
910
+ const paddedTerm = term.padEnd(
911
+ termWidth + term.length - helper.displayWidth(term),
912
+ );
913
+
914
+ // Format the description.
915
+ const spacerWidth = 2; // between term and description
916
+ const helpWidth = this.helpWidth ?? 80; // in case prepareContext() was not called
917
+ const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
918
+ let formattedDescription;
919
+ if (
920
+ remainingWidth < this.minWidthToWrap ||
921
+ helper.preformatted(description)
922
+ ) {
923
+ formattedDescription = description;
924
+ } else {
925
+ const wrappedDescription = helper.boxWrap(description, remainingWidth);
926
+ formattedDescription = wrappedDescription.replace(
927
+ /\n/g,
928
+ '\n' + ' '.repeat(termWidth + spacerWidth),
929
+ );
930
+ }
931
+
932
+ // Construct and overall indent.
933
+ return (
934
+ itemIndentStr +
935
+ paddedTerm +
936
+ ' '.repeat(spacerWidth) +
937
+ formattedDescription.replace(/\n/g, `\n${itemIndentStr}`)
938
+ );
939
+ }
940
+
941
+ /**
942
+ * Wrap a string at whitespace, preserving existing line breaks.
943
+ * Wrapping is skipped if the width is less than `minWidthToWrap`.
944
+ *
945
+ * @param {string} str
946
+ * @param {number} width
947
+ * @returns {string}
948
+ */
949
+ boxWrap(str, width) {
950
+ if (width < this.minWidthToWrap) return str;
951
+
952
+ const rawLines = str.split(/\r\n|\n/);
953
+ // split up text by whitespace
954
+ const chunkPattern = /[\s]*[^\s]+/g;
955
+ const wrappedLines = [];
956
+ rawLines.forEach((line) => {
957
+ const chunks = line.match(chunkPattern);
958
+ if (chunks === null) {
959
+ wrappedLines.push('');
960
+ return;
961
+ }
962
+
963
+ let sumChunks = [chunks.shift()];
964
+ let sumWidth = this.displayWidth(sumChunks[0]);
965
+ chunks.forEach((chunk) => {
966
+ const visibleWidth = this.displayWidth(chunk);
967
+ // Accumulate chunks while they fit into width.
968
+ if (sumWidth + visibleWidth <= width) {
969
+ sumChunks.push(chunk);
970
+ sumWidth += visibleWidth;
971
+ return;
972
+ }
973
+ wrappedLines.push(sumChunks.join(''));
974
+
975
+ const nextChunk = chunk.trimStart(); // trim space at line break
976
+ sumChunks = [nextChunk];
977
+ sumWidth = this.displayWidth(nextChunk);
978
+ });
979
+ wrappedLines.push(sumChunks.join(''));
980
+ });
981
+
982
+ return wrappedLines.join('\n');
983
+ }
984
+ }
985
+
986
+ /**
987
+ * Strip style ANSI escape sequences from the string. In particular, SGR (Select Graphic Rendition) codes.
988
+ *
989
+ * @param {string} str
990
+ * @returns {string}
991
+ * @package
992
+ */
993
+
994
+ function stripColor(str) {
995
+ // eslint-disable-next-line no-control-regex
996
+ const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
997
+ return str.replace(sgrPattern, '');
998
+ }
999
+
1000
+ help.Help = Help;
1001
+ help.stripColor = stripColor;
1002
+ return help;
1003
+ }
1004
+
1005
+ var option = {};
1006
+
1007
+ var hasRequiredOption;
1008
+
1009
+ function requireOption () {
1010
+ if (hasRequiredOption) return option;
1011
+ hasRequiredOption = 1;
1012
+ const { InvalidArgumentError } = requireError();
1013
+
1014
+ class Option {
1015
+ /**
1016
+ * Initialize a new `Option` with the given `flags` and `description`.
1017
+ *
1018
+ * @param {string} flags
1019
+ * @param {string} [description]
1020
+ */
1021
+
1022
+ constructor(flags, description) {
1023
+ this.flags = flags;
1024
+ this.description = description || '';
1025
+
1026
+ this.required = flags.includes('<'); // A value must be supplied when the option is specified.
1027
+ this.optional = flags.includes('['); // A value is optional when the option is specified.
1028
+ // variadic test ignores <value,...> et al which might be used to describe custom splitting of single argument
1029
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags); // The option can take multiple values.
1030
+ this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line.
1031
+ const optionFlags = splitOptionFlags(flags);
1032
+ this.short = optionFlags.shortFlag; // May be a short flag, undefined, or even a long flag (if option has two long flags).
1033
+ this.long = optionFlags.longFlag;
1034
+ this.negate = false;
1035
+ if (this.long) {
1036
+ this.negate = this.long.startsWith('--no-');
1037
+ }
1038
+ this.defaultValue = undefined;
1039
+ this.defaultValueDescription = undefined;
1040
+ this.presetArg = undefined;
1041
+ this.envVar = undefined;
1042
+ this.parseArg = undefined;
1043
+ this.hidden = false;
1044
+ this.argChoices = undefined;
1045
+ this.conflictsWith = [];
1046
+ this.implied = undefined;
1047
+ this.helpGroupHeading = undefined; // soft initialised when option added to command
1048
+ }
1049
+
1050
+ /**
1051
+ * Set the default value, and optionally supply the description to be displayed in the help.
1052
+ *
1053
+ * @param {*} value
1054
+ * @param {string} [description]
1055
+ * @return {Option}
1056
+ */
1057
+
1058
+ default(value, description) {
1059
+ this.defaultValue = value;
1060
+ this.defaultValueDescription = description;
1061
+ return this;
1062
+ }
1063
+
1064
+ /**
1065
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
1066
+ * The custom processing (parseArg) is called.
1067
+ *
1068
+ * @example
1069
+ * new Option('--color').default('GREYSCALE').preset('RGB');
1070
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
1071
+ *
1072
+ * @param {*} arg
1073
+ * @return {Option}
1074
+ */
1075
+
1076
+ preset(arg) {
1077
+ this.presetArg = arg;
1078
+ return this;
1079
+ }
1080
+
1081
+ /**
1082
+ * Add option name(s) that conflict with this option.
1083
+ * An error will be displayed if conflicting options are found during parsing.
1084
+ *
1085
+ * @example
1086
+ * new Option('--rgb').conflicts('cmyk');
1087
+ * new Option('--js').conflicts(['ts', 'jsx']);
1088
+ *
1089
+ * @param {(string | string[])} names
1090
+ * @return {Option}
1091
+ */
1092
+
1093
+ conflicts(names) {
1094
+ this.conflictsWith = this.conflictsWith.concat(names);
1095
+ return this;
1096
+ }
1097
+
1098
+ /**
1099
+ * Specify implied option values for when this option is set and the implied options are not.
1100
+ *
1101
+ * The custom processing (parseArg) is not called on the implied values.
1102
+ *
1103
+ * @example
1104
+ * program
1105
+ * .addOption(new Option('--log', 'write logging information to file'))
1106
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
1107
+ *
1108
+ * @param {object} impliedOptionValues
1109
+ * @return {Option}
1110
+ */
1111
+ implies(impliedOptionValues) {
1112
+ let newImplied = impliedOptionValues;
1113
+ if (typeof impliedOptionValues === 'string') {
1114
+ // string is not documented, but easy mistake and we can do what user probably intended.
1115
+ newImplied = { [impliedOptionValues]: true };
1116
+ }
1117
+ this.implied = Object.assign(this.implied || {}, newImplied);
1118
+ return this;
1119
+ }
1120
+
1121
+ /**
1122
+ * Set environment variable to check for option value.
1123
+ *
1124
+ * An environment variable is only used if when processed the current option value is
1125
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
1126
+ *
1127
+ * @param {string} name
1128
+ * @return {Option}
1129
+ */
1130
+
1131
+ env(name) {
1132
+ this.envVar = name;
1133
+ return this;
1134
+ }
1135
+
1136
+ /**
1137
+ * Set the custom handler for processing CLI option arguments into option values.
1138
+ *
1139
+ * @param {Function} [fn]
1140
+ * @return {Option}
1141
+ */
1142
+
1143
+ argParser(fn) {
1144
+ this.parseArg = fn;
1145
+ return this;
1146
+ }
1147
+
1148
+ /**
1149
+ * Whether the option is mandatory and must have a value after parsing.
1150
+ *
1151
+ * @param {boolean} [mandatory=true]
1152
+ * @return {Option}
1153
+ */
1154
+
1155
+ makeOptionMandatory(mandatory = true) {
1156
+ this.mandatory = !!mandatory;
1157
+ return this;
1158
+ }
1159
+
1160
+ /**
1161
+ * Hide option in help.
1162
+ *
1163
+ * @param {boolean} [hide=true]
1164
+ * @return {Option}
1165
+ */
1166
+
1167
+ hideHelp(hide = true) {
1168
+ this.hidden = !!hide;
1169
+ return this;
1170
+ }
1171
+
1172
+ /**
1173
+ * @package
1174
+ */
1175
+
1176
+ _collectValue(value, previous) {
1177
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
1178
+ return [value];
1179
+ }
1180
+
1181
+ previous.push(value);
1182
+ return previous;
1183
+ }
1184
+
1185
+ /**
1186
+ * Only allow option value to be one of choices.
1187
+ *
1188
+ * @param {string[]} values
1189
+ * @return {Option}
1190
+ */
1191
+
1192
+ choices(values) {
1193
+ this.argChoices = values.slice();
1194
+ this.parseArg = (arg, previous) => {
1195
+ if (!this.argChoices.includes(arg)) {
1196
+ throw new InvalidArgumentError(
1197
+ `Allowed choices are ${this.argChoices.join(', ')}.`,
1198
+ );
1199
+ }
1200
+ if (this.variadic) {
1201
+ return this._collectValue(arg, previous);
1202
+ }
1203
+ return arg;
1204
+ };
1205
+ return this;
1206
+ }
1207
+
1208
+ /**
1209
+ * Return option name.
1210
+ *
1211
+ * @return {string}
1212
+ */
1213
+
1214
+ name() {
1215
+ if (this.long) {
1216
+ return this.long.replace(/^--/, '');
1217
+ }
1218
+ return this.short.replace(/^-/, '');
1219
+ }
1220
+
1221
+ /**
1222
+ * Return option name, in a camelcase format that can be used
1223
+ * as an object attribute key.
1224
+ *
1225
+ * @return {string}
1226
+ */
1227
+
1228
+ attributeName() {
1229
+ if (this.negate) {
1230
+ return camelcase(this.name().replace(/^no-/, ''));
1231
+ }
1232
+ return camelcase(this.name());
1233
+ }
1234
+
1235
+ /**
1236
+ * Set the help group heading.
1237
+ *
1238
+ * @param {string} heading
1239
+ * @return {Option}
1240
+ */
1241
+ helpGroup(heading) {
1242
+ this.helpGroupHeading = heading;
1243
+ return this;
1244
+ }
1245
+
1246
+ /**
1247
+ * Check if `arg` matches the short or long flag.
1248
+ *
1249
+ * @param {string} arg
1250
+ * @return {boolean}
1251
+ * @package
1252
+ */
1253
+
1254
+ is(arg) {
1255
+ return this.short === arg || this.long === arg;
1256
+ }
1257
+
1258
+ /**
1259
+ * Return whether a boolean option.
1260
+ *
1261
+ * Options are one of boolean, negated, required argument, or optional argument.
1262
+ *
1263
+ * @return {boolean}
1264
+ * @package
1265
+ */
1266
+
1267
+ isBoolean() {
1268
+ return !this.required && !this.optional && !this.negate;
1269
+ }
1270
+ }
1271
+
1272
+ /**
1273
+ * This class is to make it easier to work with dual options, without changing the existing
1274
+ * implementation. We support separate dual options for separate positive and negative options,
1275
+ * like `--build` and `--no-build`, which share a single option value. This works nicely for some
1276
+ * use cases, but is tricky for others where we want separate behaviours despite
1277
+ * the single shared option value.
1278
+ */
1279
+ class DualOptions {
1280
+ /**
1281
+ * @param {Option[]} options
1282
+ */
1283
+ constructor(options) {
1284
+ this.positiveOptions = new Map();
1285
+ this.negativeOptions = new Map();
1286
+ this.dualOptions = new Set();
1287
+ options.forEach((option) => {
1288
+ if (option.negate) {
1289
+ this.negativeOptions.set(option.attributeName(), option);
1290
+ } else {
1291
+ this.positiveOptions.set(option.attributeName(), option);
1292
+ }
1293
+ });
1294
+ this.negativeOptions.forEach((value, key) => {
1295
+ if (this.positiveOptions.has(key)) {
1296
+ this.dualOptions.add(key);
1297
+ }
1298
+ });
1299
+ }
1300
+
1301
+ /**
1302
+ * Did the value come from the option, and not from possible matching dual option?
1303
+ *
1304
+ * @param {*} value
1305
+ * @param {Option} option
1306
+ * @returns {boolean}
1307
+ */
1308
+ valueFromOption(value, option) {
1309
+ const optionKey = option.attributeName();
1310
+ if (!this.dualOptions.has(optionKey)) return true;
1311
+
1312
+ // Use the value to deduce if (probably) came from the option.
1313
+ const preset = this.negativeOptions.get(optionKey).presetArg;
1314
+ const negativeValue = preset !== undefined ? preset : false;
1315
+ return option.negate === (negativeValue === value);
1316
+ }
1317
+ }
1318
+
1319
+ /**
1320
+ * Convert string from kebab-case to camelCase.
1321
+ *
1322
+ * @param {string} str
1323
+ * @return {string}
1324
+ * @private
1325
+ */
1326
+
1327
+ function camelcase(str) {
1328
+ return str.split('-').reduce((str, word) => {
1329
+ return str + word[0].toUpperCase() + word.slice(1);
1330
+ });
1331
+ }
1332
+
1333
+ /**
1334
+ * Split the short and long flag out of something like '-m,--mixed <value>'
1335
+ *
1336
+ * @private
1337
+ */
1338
+
1339
+ function splitOptionFlags(flags) {
1340
+ let shortFlag;
1341
+ let longFlag;
1342
+ // short flag, single dash and single character
1343
+ const shortFlagExp = /^-[^-]$/;
1344
+ // long flag, double dash and at least one character
1345
+ const longFlagExp = /^--[^-]/;
1346
+
1347
+ const flagParts = flags.split(/[ |,]+/).concat('guard');
1348
+ // Normal is short and/or long.
1349
+ if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
1350
+ if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
1351
+ // Long then short. Rarely used but fine.
1352
+ if (!shortFlag && shortFlagExp.test(flagParts[0]))
1353
+ shortFlag = flagParts.shift();
1354
+ // Allow two long flags, like '--ws, --workspace'
1355
+ // This is the supported way to have a shortish option flag.
1356
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
1357
+ shortFlag = longFlag;
1358
+ longFlag = flagParts.shift();
1359
+ }
1360
+
1361
+ // Check for unprocessed flag. Fail noisily rather than silently ignore.
1362
+ if (flagParts[0].startsWith('-')) {
1363
+ const unsupportedFlag = flagParts[0];
1364
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
1365
+ if (/^-[^-][^-]/.test(unsupportedFlag))
1366
+ throw new Error(
1367
+ `${baseError}
1368
+ - a short flag is a single dash and a single character
1369
+ - either use a single dash and a single character (for a short flag)
1370
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`,
1371
+ );
1372
+ if (shortFlagExp.test(unsupportedFlag))
1373
+ throw new Error(`${baseError}
1374
+ - too many short flags`);
1375
+ if (longFlagExp.test(unsupportedFlag))
1376
+ throw new Error(`${baseError}
1377
+ - too many long flags`);
1378
+
1379
+ throw new Error(`${baseError}
1380
+ - unrecognised flag format`);
1381
+ }
1382
+ if (shortFlag === undefined && longFlag === undefined)
1383
+ throw new Error(
1384
+ `option creation failed due to no flags found in '${flags}'.`,
1385
+ );
1386
+
1387
+ return { shortFlag, longFlag };
1388
+ }
1389
+
1390
+ option.Option = Option;
1391
+ option.DualOptions = DualOptions;
1392
+ return option;
1393
+ }
1394
+
1395
+ var suggestSimilar = {};
1396
+
1397
+ var hasRequiredSuggestSimilar;
1398
+
1399
+ function requireSuggestSimilar () {
1400
+ if (hasRequiredSuggestSimilar) return suggestSimilar;
1401
+ hasRequiredSuggestSimilar = 1;
1402
+ const maxDistance = 3;
1403
+
1404
+ function editDistance(a, b) {
1405
+ // https://en.wikipedia.org/wiki/Damerau–Levenshtein_distance
1406
+ // Calculating optimal string alignment distance, no substring is edited more than once.
1407
+ // (Simple implementation.)
1408
+
1409
+ // Quick early exit, return worst case.
1410
+ if (Math.abs(a.length - b.length) > maxDistance)
1411
+ return Math.max(a.length, b.length);
1412
+
1413
+ // distance between prefix substrings of a and b
1414
+ const d = [];
1415
+
1416
+ // pure deletions turn a into empty string
1417
+ for (let i = 0; i <= a.length; i++) {
1418
+ d[i] = [i];
1419
+ }
1420
+ // pure insertions turn empty string into b
1421
+ for (let j = 0; j <= b.length; j++) {
1422
+ d[0][j] = j;
1423
+ }
1424
+
1425
+ // fill matrix
1426
+ for (let j = 1; j <= b.length; j++) {
1427
+ for (let i = 1; i <= a.length; i++) {
1428
+ let cost = 1;
1429
+ if (a[i - 1] === b[j - 1]) {
1430
+ cost = 0;
1431
+ } else {
1432
+ cost = 1;
1433
+ }
1434
+ d[i][j] = Math.min(
1435
+ d[i - 1][j] + 1, // deletion
1436
+ d[i][j - 1] + 1, // insertion
1437
+ d[i - 1][j - 1] + cost, // substitution
1438
+ );
1439
+ // transposition
1440
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
1441
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
1442
+ }
1443
+ }
1444
+ }
1445
+
1446
+ return d[a.length][b.length];
1447
+ }
1448
+
1449
+ /**
1450
+ * Find close matches, restricted to same number of edits.
1451
+ *
1452
+ * @param {string} word
1453
+ * @param {string[]} candidates
1454
+ * @returns {string}
1455
+ */
1456
+
1457
+ function suggestSimilar$1(word, candidates) {
1458
+ if (!candidates || candidates.length === 0) return '';
1459
+ // remove possible duplicates
1460
+ candidates = Array.from(new Set(candidates));
1461
+
1462
+ const searchingOptions = word.startsWith('--');
1463
+ if (searchingOptions) {
1464
+ word = word.slice(2);
1465
+ candidates = candidates.map((candidate) => candidate.slice(2));
1466
+ }
1467
+
1468
+ let similar = [];
1469
+ let bestDistance = maxDistance;
1470
+ const minSimilarity = 0.4;
1471
+ candidates.forEach((candidate) => {
1472
+ if (candidate.length <= 1) return; // no one character guesses
1473
+
1474
+ const distance = editDistance(word, candidate);
1475
+ const length = Math.max(word.length, candidate.length);
1476
+ const similarity = (length - distance) / length;
1477
+ if (similarity > minSimilarity) {
1478
+ if (distance < bestDistance) {
1479
+ // better edit distance, throw away previous worse matches
1480
+ bestDistance = distance;
1481
+ similar = [candidate];
1482
+ } else if (distance === bestDistance) {
1483
+ similar.push(candidate);
1484
+ }
1485
+ }
1486
+ });
1487
+
1488
+ similar.sort((a, b) => a.localeCompare(b));
1489
+ if (searchingOptions) {
1490
+ similar = similar.map((candidate) => `--${candidate}`);
1491
+ }
1492
+
1493
+ if (similar.length > 1) {
1494
+ return `\n(Did you mean one of ${similar.join(', ')}?)`;
1495
+ }
1496
+ if (similar.length === 1) {
1497
+ return `\n(Did you mean ${similar[0]}?)`;
1498
+ }
1499
+ return '';
1500
+ }
1501
+
1502
+ suggestSimilar.suggestSimilar = suggestSimilar$1;
1503
+ return suggestSimilar;
1504
+ }
1505
+
1506
+ var hasRequiredCommand;
1507
+
1508
+ function requireCommand () {
1509
+ if (hasRequiredCommand) return command$1;
1510
+ hasRequiredCommand = 1;
1511
+ const EventEmitter = require$$0.EventEmitter;
1512
+ const childProcess = require$$1;
1513
+ const path = require$$2;
1514
+ const fs = require$$3;
1515
+ const process = require$$4;
1516
+
1517
+ const { Argument, humanReadableArgName } = requireArgument();
1518
+ const { CommanderError } = requireError();
1519
+ const { Help, stripColor } = requireHelp();
1520
+ const { Option, DualOptions } = requireOption();
1521
+ const { suggestSimilar } = requireSuggestSimilar();
1522
+
1523
+ class Command extends EventEmitter {
1524
+ /**
1525
+ * Initialize a new `Command`.
1526
+ *
1527
+ * @param {string} [name]
1528
+ */
1529
+
1530
+ constructor(name) {
1531
+ super();
1532
+ /** @type {Command[]} */
1533
+ this.commands = [];
1534
+ /** @type {Option[]} */
1535
+ this.options = [];
1536
+ this.parent = null;
1537
+ this._allowUnknownOption = false;
1538
+ this._allowExcessArguments = false;
1539
+ /** @type {Argument[]} */
1540
+ this.registeredArguments = [];
1541
+ this._args = this.registeredArguments; // deprecated old name
1542
+ /** @type {string[]} */
1543
+ this.args = []; // cli args with options removed
1544
+ this.rawArgs = [];
1545
+ this.processedArgs = []; // like .args but after custom processing and collecting variadic
1546
+ this._scriptPath = null;
1547
+ this._name = name || '';
1548
+ this._optionValues = {};
1549
+ this._optionValueSources = {}; // default, env, cli etc
1550
+ this._storeOptionsAsProperties = false;
1551
+ this._actionHandler = null;
1552
+ this._executableHandler = false;
1553
+ this._executableFile = null; // custom name for executable
1554
+ this._executableDir = null; // custom search directory for subcommands
1555
+ this._defaultCommandName = null;
1556
+ this._exitCallback = null;
1557
+ this._aliases = [];
1558
+ this._combineFlagAndOptionalValue = true;
1559
+ this._description = '';
1560
+ this._summary = '';
1561
+ this._argsDescription = undefined; // legacy
1562
+ this._enablePositionalOptions = false;
1563
+ this._passThroughOptions = false;
1564
+ this._lifeCycleHooks = {}; // a hash of arrays
1565
+ /** @type {(boolean | string)} */
1566
+ this._showHelpAfterError = false;
1567
+ this._showSuggestionAfterError = true;
1568
+ this._savedState = null; // used in save/restoreStateBeforeParse
1569
+
1570
+ // see configureOutput() for docs
1571
+ this._outputConfiguration = {
1572
+ writeOut: (str) => process.stdout.write(str),
1573
+ writeErr: (str) => process.stderr.write(str),
1574
+ outputError: (str, write) => write(str),
1575
+ getOutHelpWidth: () =>
1576
+ process.stdout.isTTY ? process.stdout.columns : undefined,
1577
+ getErrHelpWidth: () =>
1578
+ process.stderr.isTTY ? process.stderr.columns : undefined,
1579
+ getOutHasColors: () =>
1580
+ useColor() ?? (process.stdout.isTTY && process.stdout.hasColors?.()),
1581
+ getErrHasColors: () =>
1582
+ useColor() ?? (process.stderr.isTTY && process.stderr.hasColors?.()),
1583
+ stripColor: (str) => stripColor(str),
1584
+ };
1585
+
1586
+ this._hidden = false;
1587
+ /** @type {(Option | null | undefined)} */
1588
+ this._helpOption = undefined; // Lazy created on demand. May be null if help option is disabled.
1589
+ this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited
1590
+ /** @type {Command} */
1591
+ this._helpCommand = undefined; // lazy initialised, inherited
1592
+ this._helpConfiguration = {};
1593
+ /** @type {string | undefined} */
1594
+ this._helpGroupHeading = undefined; // soft initialised when added to parent
1595
+ /** @type {string | undefined} */
1596
+ this._defaultCommandGroup = undefined;
1597
+ /** @type {string | undefined} */
1598
+ this._defaultOptionGroup = undefined;
1599
+ }
1600
+
1601
+ /**
1602
+ * Copy settings that are useful to have in common across root command and subcommands.
1603
+ *
1604
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1605
+ *
1606
+ * @param {Command} sourceCommand
1607
+ * @return {Command} `this` command for chaining
1608
+ */
1609
+ copyInheritedSettings(sourceCommand) {
1610
+ this._outputConfiguration = sourceCommand._outputConfiguration;
1611
+ this._helpOption = sourceCommand._helpOption;
1612
+ this._helpCommand = sourceCommand._helpCommand;
1613
+ this._helpConfiguration = sourceCommand._helpConfiguration;
1614
+ this._exitCallback = sourceCommand._exitCallback;
1615
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1616
+ this._combineFlagAndOptionalValue =
1617
+ sourceCommand._combineFlagAndOptionalValue;
1618
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
1619
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1620
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
1621
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1622
+
1623
+ return this;
1624
+ }
1625
+
1626
+ /**
1627
+ * @returns {Command[]}
1628
+ * @private
1629
+ */
1630
+
1631
+ _getCommandAndAncestors() {
1632
+ const result = [];
1633
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
1634
+ for (let command = this; command; command = command.parent) {
1635
+ result.push(command);
1636
+ }
1637
+ return result;
1638
+ }
1639
+
1640
+ /**
1641
+ * Define a command.
1642
+ *
1643
+ * There are two styles of command: pay attention to where to put the description.
1644
+ *
1645
+ * @example
1646
+ * // Command implemented using action handler (description is supplied separately to `.command`)
1647
+ * program
1648
+ * .command('clone <source> [destination]')
1649
+ * .description('clone a repository into a newly created directory')
1650
+ * .action((source, destination) => {
1651
+ * console.log('clone command called');
1652
+ * });
1653
+ *
1654
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
1655
+ * program
1656
+ * .command('start <service>', 'start named service')
1657
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
1658
+ *
1659
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1660
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1661
+ * @param {object} [execOpts] - configuration options (for executable)
1662
+ * @return {Command} returns new command for action handler, or `this` for executable command
1663
+ */
1664
+
1665
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1666
+ let desc = actionOptsOrExecDesc;
1667
+ let opts = execOpts;
1668
+ if (typeof desc === 'object' && desc !== null) {
1669
+ opts = desc;
1670
+ desc = null;
1671
+ }
1672
+ opts = opts || {};
1673
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1674
+
1675
+ const cmd = this.createCommand(name);
1676
+ if (desc) {
1677
+ cmd.description(desc);
1678
+ cmd._executableHandler = true;
1679
+ }
1680
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1681
+ cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden
1682
+ cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor
1683
+ if (args) cmd.arguments(args);
1684
+ this._registerCommand(cmd);
1685
+ cmd.parent = this;
1686
+ cmd.copyInheritedSettings(this);
1687
+
1688
+ if (desc) return this;
1689
+ return cmd;
1690
+ }
1691
+
1692
+ /**
1693
+ * Factory routine to create a new unattached command.
1694
+ *
1695
+ * See .command() for creating an attached subcommand, which uses this routine to
1696
+ * create the command. You can override createCommand to customise subcommands.
1697
+ *
1698
+ * @param {string} [name]
1699
+ * @return {Command} new command
1700
+ */
1701
+
1702
+ createCommand(name) {
1703
+ return new Command(name);
1704
+ }
1705
+
1706
+ /**
1707
+ * You can customise the help with a subclass of Help by overriding createHelp,
1708
+ * or by overriding Help properties using configureHelp().
1709
+ *
1710
+ * @return {Help}
1711
+ */
1712
+
1713
+ createHelp() {
1714
+ return Object.assign(new Help(), this.configureHelp());
1715
+ }
1716
+
1717
+ /**
1718
+ * You can customise the help by overriding Help properties using configureHelp(),
1719
+ * or with a subclass of Help by overriding createHelp().
1720
+ *
1721
+ * @param {object} [configuration] - configuration options
1722
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1723
+ */
1724
+
1725
+ configureHelp(configuration) {
1726
+ if (configuration === undefined) return this._helpConfiguration;
1727
+
1728
+ this._helpConfiguration = configuration;
1729
+ return this;
1730
+ }
1731
+
1732
+ /**
1733
+ * The default output goes to stdout and stderr. You can customise this for special
1734
+ * applications. You can also customise the display of errors by overriding outputError.
1735
+ *
1736
+ * The configuration properties are all functions:
1737
+ *
1738
+ * // change how output being written, defaults to stdout and stderr
1739
+ * writeOut(str)
1740
+ * writeErr(str)
1741
+ * // change how output being written for errors, defaults to writeErr
1742
+ * outputError(str, write) // used for displaying errors and not used for displaying help
1743
+ * // specify width for wrapping help
1744
+ * getOutHelpWidth()
1745
+ * getErrHelpWidth()
1746
+ * // color support, currently only used with Help
1747
+ * getOutHasColors()
1748
+ * getErrHasColors()
1749
+ * stripColor() // used to remove ANSI escape codes if output does not have colors
1750
+ *
1751
+ * @param {object} [configuration] - configuration options
1752
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1753
+ */
1754
+
1755
+ configureOutput(configuration) {
1756
+ if (configuration === undefined) return this._outputConfiguration;
1757
+
1758
+ this._outputConfiguration = {
1759
+ ...this._outputConfiguration,
1760
+ ...configuration,
1761
+ };
1762
+ return this;
1763
+ }
1764
+
1765
+ /**
1766
+ * Display the help or a custom message after an error occurs.
1767
+ *
1768
+ * @param {(boolean|string)} [displayHelp]
1769
+ * @return {Command} `this` command for chaining
1770
+ */
1771
+ showHelpAfterError(displayHelp = true) {
1772
+ if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;
1773
+ this._showHelpAfterError = displayHelp;
1774
+ return this;
1775
+ }
1776
+
1777
+ /**
1778
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
1779
+ *
1780
+ * @param {boolean} [displaySuggestion]
1781
+ * @return {Command} `this` command for chaining
1782
+ */
1783
+ showSuggestionAfterError(displaySuggestion = true) {
1784
+ this._showSuggestionAfterError = !!displaySuggestion;
1785
+ return this;
1786
+ }
1787
+
1788
+ /**
1789
+ * Add a prepared subcommand.
1790
+ *
1791
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
1792
+ *
1793
+ * @param {Command} cmd - new subcommand
1794
+ * @param {object} [opts] - configuration options
1795
+ * @return {Command} `this` command for chaining
1796
+ */
1797
+
1798
+ addCommand(cmd, opts) {
1799
+ if (!cmd._name) {
1800
+ throw new Error(`Command passed to .addCommand() must have a name
1801
+ - specify the name in Command constructor or using .name()`);
1802
+ }
1803
+
1804
+ opts = opts || {};
1805
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1806
+ if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation
1807
+
1808
+ this._registerCommand(cmd);
1809
+ cmd.parent = this;
1810
+ cmd._checkForBrokenPassThrough();
1811
+
1812
+ return this;
1813
+ }
1814
+
1815
+ /**
1816
+ * Factory routine to create a new unattached argument.
1817
+ *
1818
+ * See .argument() for creating an attached argument, which uses this routine to
1819
+ * create the argument. You can override createArgument to return a custom argument.
1820
+ *
1821
+ * @param {string} name
1822
+ * @param {string} [description]
1823
+ * @return {Argument} new argument
1824
+ */
1825
+
1826
+ createArgument(name, description) {
1827
+ return new Argument(name, description);
1828
+ }
1829
+
1830
+ /**
1831
+ * Define argument syntax for command.
1832
+ *
1833
+ * The default is that the argument is required, and you can explicitly
1834
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
1835
+ *
1836
+ * @example
1837
+ * program.argument('<input-file>');
1838
+ * program.argument('[output-file]');
1839
+ *
1840
+ * @param {string} name
1841
+ * @param {string} [description]
1842
+ * @param {(Function|*)} [parseArg] - custom argument processing function or default value
1843
+ * @param {*} [defaultValue]
1844
+ * @return {Command} `this` command for chaining
1845
+ */
1846
+ argument(name, description, parseArg, defaultValue) {
1847
+ const argument = this.createArgument(name, description);
1848
+ if (typeof parseArg === 'function') {
1849
+ argument.default(defaultValue).argParser(parseArg);
1850
+ } else {
1851
+ argument.default(parseArg);
1852
+ }
1853
+ this.addArgument(argument);
1854
+ return this;
1855
+ }
1856
+
1857
+ /**
1858
+ * Define argument syntax for command, adding multiple at once (without descriptions).
1859
+ *
1860
+ * See also .argument().
1861
+ *
1862
+ * @example
1863
+ * program.arguments('<cmd> [env]');
1864
+ *
1865
+ * @param {string} names
1866
+ * @return {Command} `this` command for chaining
1867
+ */
1868
+
1869
+ arguments(names) {
1870
+ names
1871
+ .trim()
1872
+ .split(/ +/)
1873
+ .forEach((detail) => {
1874
+ this.argument(detail);
1875
+ });
1876
+ return this;
1877
+ }
1878
+
1879
+ /**
1880
+ * Define argument syntax for command, adding a prepared argument.
1881
+ *
1882
+ * @param {Argument} argument
1883
+ * @return {Command} `this` command for chaining
1884
+ */
1885
+ addArgument(argument) {
1886
+ const previousArgument = this.registeredArguments.slice(-1)[0];
1887
+ if (previousArgument?.variadic) {
1888
+ throw new Error(
1889
+ `only the last argument can be variadic '${previousArgument.name()}'`,
1890
+ );
1891
+ }
1892
+ if (
1893
+ argument.required &&
1894
+ argument.defaultValue !== undefined &&
1895
+ argument.parseArg === undefined
1896
+ ) {
1897
+ throw new Error(
1898
+ `a default value for a required argument is never used: '${argument.name()}'`,
1899
+ );
1900
+ }
1901
+ this.registeredArguments.push(argument);
1902
+ return this;
1903
+ }
1904
+
1905
+ /**
1906
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
1907
+ *
1908
+ * @example
1909
+ * program.helpCommand('help [cmd]');
1910
+ * program.helpCommand('help [cmd]', 'show help');
1911
+ * program.helpCommand(false); // suppress default help command
1912
+ * program.helpCommand(true); // add help command even if no subcommands
1913
+ *
1914
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
1915
+ * @param {string} [description] - custom description
1916
+ * @return {Command} `this` command for chaining
1917
+ */
1918
+
1919
+ helpCommand(enableOrNameAndArgs, description) {
1920
+ if (typeof enableOrNameAndArgs === 'boolean') {
1921
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
1922
+ if (enableOrNameAndArgs && this._defaultCommandGroup) {
1923
+ // make the command to store the group
1924
+ this._initCommandGroup(this._getHelpCommand());
1925
+ }
1926
+ return this;
1927
+ }
1928
+
1929
+ const nameAndArgs = enableOrNameAndArgs ?? 'help [command]';
1930
+ const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);
1931
+ const helpDescription = description ?? 'display help for command';
1932
+
1933
+ const helpCommand = this.createCommand(helpName);
1934
+ helpCommand.helpOption(false);
1935
+ if (helpArgs) helpCommand.arguments(helpArgs);
1936
+ if (helpDescription) helpCommand.description(helpDescription);
1937
+
1938
+ this._addImplicitHelpCommand = true;
1939
+ this._helpCommand = helpCommand;
1940
+ // init group unless lazy create
1941
+ if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);
1942
+
1943
+ return this;
1944
+ }
1945
+
1946
+ /**
1947
+ * Add prepared custom help command.
1948
+ *
1949
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
1950
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
1951
+ * @return {Command} `this` command for chaining
1952
+ */
1953
+ addHelpCommand(helpCommand, deprecatedDescription) {
1954
+ // If not passed an object, call through to helpCommand for backwards compatibility,
1955
+ // as addHelpCommand was originally used like helpCommand is now.
1956
+ if (typeof helpCommand !== 'object') {
1957
+ this.helpCommand(helpCommand, deprecatedDescription);
1958
+ return this;
1959
+ }
1960
+
1961
+ this._addImplicitHelpCommand = true;
1962
+ this._helpCommand = helpCommand;
1963
+ this._initCommandGroup(helpCommand);
1964
+ return this;
1965
+ }
1966
+
1967
+ /**
1968
+ * Lazy create help command.
1969
+ *
1970
+ * @return {(Command|null)}
1971
+ * @package
1972
+ */
1973
+ _getHelpCommand() {
1974
+ const hasImplicitHelpCommand =
1975
+ this._addImplicitHelpCommand ??
1976
+ (this.commands.length &&
1977
+ !this._actionHandler &&
1978
+ !this._findCommand('help'));
1979
+
1980
+ if (hasImplicitHelpCommand) {
1981
+ if (this._helpCommand === undefined) {
1982
+ this.helpCommand(undefined, undefined); // use default name and description
1983
+ }
1984
+ return this._helpCommand;
1985
+ }
1986
+ return null;
1987
+ }
1988
+
1989
+ /**
1990
+ * Add hook for life cycle event.
1991
+ *
1992
+ * @param {string} event
1993
+ * @param {Function} listener
1994
+ * @return {Command} `this` command for chaining
1995
+ */
1996
+
1997
+ hook(event, listener) {
1998
+ const allowedValues = ['preSubcommand', 'preAction', 'postAction'];
1999
+ if (!allowedValues.includes(event)) {
2000
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
2001
+ Expecting one of '${allowedValues.join("', '")}'`);
2002
+ }
2003
+ if (this._lifeCycleHooks[event]) {
2004
+ this._lifeCycleHooks[event].push(listener);
2005
+ } else {
2006
+ this._lifeCycleHooks[event] = [listener];
2007
+ }
2008
+ return this;
2009
+ }
2010
+
2011
+ /**
2012
+ * Register callback to use as replacement for calling process.exit.
2013
+ *
2014
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
2015
+ * @return {Command} `this` command for chaining
2016
+ */
2017
+
2018
+ exitOverride(fn) {
2019
+ if (fn) {
2020
+ this._exitCallback = fn;
2021
+ } else {
2022
+ this._exitCallback = (err) => {
2023
+ if (err.code !== 'commander.executeSubCommandAsync') {
2024
+ throw err;
2025
+ }
2026
+ };
2027
+ }
2028
+ return this;
2029
+ }
2030
+
2031
+ /**
2032
+ * Call process.exit, and _exitCallback if defined.
2033
+ *
2034
+ * @param {number} exitCode exit code for using with process.exit
2035
+ * @param {string} code an id string representing the error
2036
+ * @param {string} message human-readable description of the error
2037
+ * @return never
2038
+ * @private
2039
+ */
2040
+
2041
+ _exit(exitCode, code, message) {
2042
+ if (this._exitCallback) {
2043
+ this._exitCallback(new CommanderError(exitCode, code, message));
2044
+ // Expecting this line is not reached.
2045
+ }
2046
+ process.exit(exitCode);
2047
+ }
2048
+
2049
+ /**
2050
+ * Register callback `fn` for the command.
2051
+ *
2052
+ * @example
2053
+ * program
2054
+ * .command('serve')
2055
+ * .description('start service')
2056
+ * .action(function() {
2057
+ * // do work here
2058
+ * });
2059
+ *
2060
+ * @param {Function} fn
2061
+ * @return {Command} `this` command for chaining
2062
+ */
2063
+
2064
+ action(fn) {
2065
+ const listener = (args) => {
2066
+ // The .action callback takes an extra parameter which is the command or options.
2067
+ const expectedArgsCount = this.registeredArguments.length;
2068
+ const actionArgs = args.slice(0, expectedArgsCount);
2069
+ if (this._storeOptionsAsProperties) {
2070
+ actionArgs[expectedArgsCount] = this; // backwards compatible "options"
2071
+ } else {
2072
+ actionArgs[expectedArgsCount] = this.opts();
2073
+ }
2074
+ actionArgs.push(this);
2075
+
2076
+ return fn.apply(this, actionArgs);
2077
+ };
2078
+ this._actionHandler = listener;
2079
+ return this;
2080
+ }
2081
+
2082
+ /**
2083
+ * Factory routine to create a new unattached option.
2084
+ *
2085
+ * See .option() for creating an attached option, which uses this routine to
2086
+ * create the option. You can override createOption to return a custom option.
2087
+ *
2088
+ * @param {string} flags
2089
+ * @param {string} [description]
2090
+ * @return {Option} new option
2091
+ */
2092
+
2093
+ createOption(flags, description) {
2094
+ return new Option(flags, description);
2095
+ }
2096
+
2097
+ /**
2098
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
2099
+ *
2100
+ * @param {(Option | Argument)} target
2101
+ * @param {string} value
2102
+ * @param {*} previous
2103
+ * @param {string} invalidArgumentMessage
2104
+ * @private
2105
+ */
2106
+
2107
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
2108
+ try {
2109
+ return target.parseArg(value, previous);
2110
+ } catch (err) {
2111
+ if (err.code === 'commander.invalidArgument') {
2112
+ const message = `${invalidArgumentMessage} ${err.message}`;
2113
+ this.error(message, { exitCode: err.exitCode, code: err.code });
2114
+ }
2115
+ throw err;
2116
+ }
2117
+ }
2118
+
2119
+ /**
2120
+ * Check for option flag conflicts.
2121
+ * Register option if no conflicts found, or throw on conflict.
2122
+ *
2123
+ * @param {Option} option
2124
+ * @private
2125
+ */
2126
+
2127
+ _registerOption(option) {
2128
+ const matchingOption =
2129
+ (option.short && this._findOption(option.short)) ||
2130
+ (option.long && this._findOption(option.long));
2131
+ if (matchingOption) {
2132
+ const matchingFlag =
2133
+ option.long && this._findOption(option.long)
2134
+ ? option.long
2135
+ : option.short;
2136
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
2137
+ - already used by option '${matchingOption.flags}'`);
2138
+ }
2139
+
2140
+ this._initOptionGroup(option);
2141
+ this.options.push(option);
2142
+ }
2143
+
2144
+ /**
2145
+ * Check for command name and alias conflicts with existing commands.
2146
+ * Register command if no conflicts found, or throw on conflict.
2147
+ *
2148
+ * @param {Command} command
2149
+ * @private
2150
+ */
2151
+
2152
+ _registerCommand(command) {
2153
+ const knownBy = (cmd) => {
2154
+ return [cmd.name()].concat(cmd.aliases());
2155
+ };
2156
+
2157
+ const alreadyUsed = knownBy(command).find((name) =>
2158
+ this._findCommand(name),
2159
+ );
2160
+ if (alreadyUsed) {
2161
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');
2162
+ const newCmd = knownBy(command).join('|');
2163
+ throw new Error(
2164
+ `cannot add command '${newCmd}' as already have command '${existingCmd}'`,
2165
+ );
2166
+ }
2167
+
2168
+ this._initCommandGroup(command);
2169
+ this.commands.push(command);
2170
+ }
2171
+
2172
+ /**
2173
+ * Add an option.
2174
+ *
2175
+ * @param {Option} option
2176
+ * @return {Command} `this` command for chaining
2177
+ */
2178
+ addOption(option) {
2179
+ this._registerOption(option);
2180
+
2181
+ const oname = option.name();
2182
+ const name = option.attributeName();
2183
+
2184
+ // store default value
2185
+ if (option.negate) {
2186
+ // --no-foo is special and defaults foo to true, unless a --foo option is already defined
2187
+ const positiveLongFlag = option.long.replace(/^--no-/, '--');
2188
+ if (!this._findOption(positiveLongFlag)) {
2189
+ this.setOptionValueWithSource(
2190
+ name,
2191
+ option.defaultValue === undefined ? true : option.defaultValue,
2192
+ 'default',
2193
+ );
2194
+ }
2195
+ } else if (option.defaultValue !== undefined) {
2196
+ this.setOptionValueWithSource(name, option.defaultValue, 'default');
2197
+ }
2198
+
2199
+ // handler for cli and env supplied values
2200
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
2201
+ // val is null for optional option used without an optional-argument.
2202
+ // val is undefined for boolean and negated option.
2203
+ if (val == null && option.presetArg !== undefined) {
2204
+ val = option.presetArg;
2205
+ }
2206
+
2207
+ // custom processing
2208
+ const oldValue = this.getOptionValue(name);
2209
+ if (val !== null && option.parseArg) {
2210
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
2211
+ } else if (val !== null && option.variadic) {
2212
+ val = option._collectValue(val, oldValue);
2213
+ }
2214
+
2215
+ // Fill-in appropriate missing values. Long winded but easy to follow.
2216
+ if (val == null) {
2217
+ if (option.negate) {
2218
+ val = false;
2219
+ } else if (option.isBoolean() || option.optional) {
2220
+ val = true;
2221
+ } else {
2222
+ val = ''; // not normal, parseArg might have failed or be a mock function for testing
2223
+ }
2224
+ }
2225
+ this.setOptionValueWithSource(name, val, valueSource);
2226
+ };
2227
+
2228
+ this.on('option:' + oname, (val) => {
2229
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
2230
+ handleOptionValue(val, invalidValueMessage, 'cli');
2231
+ });
2232
+
2233
+ if (option.envVar) {
2234
+ this.on('optionEnv:' + oname, (val) => {
2235
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
2236
+ handleOptionValue(val, invalidValueMessage, 'env');
2237
+ });
2238
+ }
2239
+
2240
+ return this;
2241
+ }
2242
+
2243
+ /**
2244
+ * Internal implementation shared by .option() and .requiredOption()
2245
+ *
2246
+ * @return {Command} `this` command for chaining
2247
+ * @private
2248
+ */
2249
+ _optionEx(config, flags, description, fn, defaultValue) {
2250
+ if (typeof flags === 'object' && flags instanceof Option) {
2251
+ throw new Error(
2252
+ 'To add an Option object use addOption() instead of option() or requiredOption()',
2253
+ );
2254
+ }
2255
+ const option = this.createOption(flags, description);
2256
+ option.makeOptionMandatory(!!config.mandatory);
2257
+ if (typeof fn === 'function') {
2258
+ option.default(defaultValue).argParser(fn);
2259
+ } else if (fn instanceof RegExp) {
2260
+ // deprecated
2261
+ const regex = fn;
2262
+ fn = (val, def) => {
2263
+ const m = regex.exec(val);
2264
+ return m ? m[0] : def;
2265
+ };
2266
+ option.default(defaultValue).argParser(fn);
2267
+ } else {
2268
+ option.default(fn);
2269
+ }
2270
+
2271
+ return this.addOption(option);
2272
+ }
2273
+
2274
+ /**
2275
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
2276
+ *
2277
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
2278
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
2279
+ *
2280
+ * See the README for more details, and see also addOption() and requiredOption().
2281
+ *
2282
+ * @example
2283
+ * program
2284
+ * .option('-p, --pepper', 'add pepper')
2285
+ * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
2286
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
2287
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
2288
+ *
2289
+ * @param {string} flags
2290
+ * @param {string} [description]
2291
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
2292
+ * @param {*} [defaultValue]
2293
+ * @return {Command} `this` command for chaining
2294
+ */
2295
+
2296
+ option(flags, description, parseArg, defaultValue) {
2297
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
2298
+ }
2299
+
2300
+ /**
2301
+ * Add a required option which must have a value after parsing. This usually means
2302
+ * the option must be specified on the command line. (Otherwise the same as .option().)
2303
+ *
2304
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
2305
+ *
2306
+ * @param {string} flags
2307
+ * @param {string} [description]
2308
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
2309
+ * @param {*} [defaultValue]
2310
+ * @return {Command} `this` command for chaining
2311
+ */
2312
+
2313
+ requiredOption(flags, description, parseArg, defaultValue) {
2314
+ return this._optionEx(
2315
+ { mandatory: true },
2316
+ flags,
2317
+ description,
2318
+ parseArg,
2319
+ defaultValue,
2320
+ );
2321
+ }
2322
+
2323
+ /**
2324
+ * Alter parsing of short flags with optional values.
2325
+ *
2326
+ * @example
2327
+ * // for `.option('-f,--flag [value]'):
2328
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
2329
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
2330
+ *
2331
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
2332
+ * @return {Command} `this` command for chaining
2333
+ */
2334
+ combineFlagAndOptionalValue(combine = true) {
2335
+ this._combineFlagAndOptionalValue = !!combine;
2336
+ return this;
2337
+ }
2338
+
2339
+ /**
2340
+ * Allow unknown options on the command line.
2341
+ *
2342
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
2343
+ * @return {Command} `this` command for chaining
2344
+ */
2345
+ allowUnknownOption(allowUnknown = true) {
2346
+ this._allowUnknownOption = !!allowUnknown;
2347
+ return this;
2348
+ }
2349
+
2350
+ /**
2351
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
2352
+ *
2353
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
2354
+ * @return {Command} `this` command for chaining
2355
+ */
2356
+ allowExcessArguments(allowExcess = true) {
2357
+ this._allowExcessArguments = !!allowExcess;
2358
+ return this;
2359
+ }
2360
+
2361
+ /**
2362
+ * Enable positional options. Positional means global options are specified before subcommands which lets
2363
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
2364
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
2365
+ *
2366
+ * @param {boolean} [positional]
2367
+ * @return {Command} `this` command for chaining
2368
+ */
2369
+ enablePositionalOptions(positional = true) {
2370
+ this._enablePositionalOptions = !!positional;
2371
+ return this;
2372
+ }
2373
+
2374
+ /**
2375
+ * Pass through options that come after command-arguments rather than treat them as command-options,
2376
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
2377
+ * positional options to have been enabled on the program (parent commands).
2378
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
2379
+ *
2380
+ * @param {boolean} [passThrough] for unknown options.
2381
+ * @return {Command} `this` command for chaining
2382
+ */
2383
+ passThroughOptions(passThrough = true) {
2384
+ this._passThroughOptions = !!passThrough;
2385
+ this._checkForBrokenPassThrough();
2386
+ return this;
2387
+ }
2388
+
2389
+ /**
2390
+ * @private
2391
+ */
2392
+
2393
+ _checkForBrokenPassThrough() {
2394
+ if (
2395
+ this.parent &&
2396
+ this._passThroughOptions &&
2397
+ !this.parent._enablePositionalOptions
2398
+ ) {
2399
+ throw new Error(
2400
+ `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`,
2401
+ );
2402
+ }
2403
+ }
2404
+
2405
+ /**
2406
+ * Whether to store option values as properties on command object,
2407
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
2408
+ *
2409
+ * @param {boolean} [storeAsProperties=true]
2410
+ * @return {Command} `this` command for chaining
2411
+ */
2412
+
2413
+ storeOptionsAsProperties(storeAsProperties = true) {
2414
+ if (this.options.length) {
2415
+ throw new Error('call .storeOptionsAsProperties() before adding options');
2416
+ }
2417
+ if (Object.keys(this._optionValues).length) {
2418
+ throw new Error(
2419
+ 'call .storeOptionsAsProperties() before setting option values',
2420
+ );
2421
+ }
2422
+ this._storeOptionsAsProperties = !!storeAsProperties;
2423
+ return this;
2424
+ }
2425
+
2426
+ /**
2427
+ * Retrieve option value.
2428
+ *
2429
+ * @param {string} key
2430
+ * @return {object} value
2431
+ */
2432
+
2433
+ getOptionValue(key) {
2434
+ if (this._storeOptionsAsProperties) {
2435
+ return this[key];
2436
+ }
2437
+ return this._optionValues[key];
2438
+ }
2439
+
2440
+ /**
2441
+ * Store option value.
2442
+ *
2443
+ * @param {string} key
2444
+ * @param {object} value
2445
+ * @return {Command} `this` command for chaining
2446
+ */
2447
+
2448
+ setOptionValue(key, value) {
2449
+ return this.setOptionValueWithSource(key, value, undefined);
2450
+ }
2451
+
2452
+ /**
2453
+ * Store option value and where the value came from.
2454
+ *
2455
+ * @param {string} key
2456
+ * @param {object} value
2457
+ * @param {string} source - expected values are default/config/env/cli/implied
2458
+ * @return {Command} `this` command for chaining
2459
+ */
2460
+
2461
+ setOptionValueWithSource(key, value, source) {
2462
+ if (this._storeOptionsAsProperties) {
2463
+ this[key] = value;
2464
+ } else {
2465
+ this._optionValues[key] = value;
2466
+ }
2467
+ this._optionValueSources[key] = source;
2468
+ return this;
2469
+ }
2470
+
2471
+ /**
2472
+ * Get source of option value.
2473
+ * Expected values are default | config | env | cli | implied
2474
+ *
2475
+ * @param {string} key
2476
+ * @return {string}
2477
+ */
2478
+
2479
+ getOptionValueSource(key) {
2480
+ return this._optionValueSources[key];
2481
+ }
2482
+
2483
+ /**
2484
+ * Get source of option value. See also .optsWithGlobals().
2485
+ * Expected values are default | config | env | cli | implied
2486
+ *
2487
+ * @param {string} key
2488
+ * @return {string}
2489
+ */
2490
+
2491
+ getOptionValueSourceWithGlobals(key) {
2492
+ // global overwrites local, like optsWithGlobals
2493
+ let source;
2494
+ this._getCommandAndAncestors().forEach((cmd) => {
2495
+ if (cmd.getOptionValueSource(key) !== undefined) {
2496
+ source = cmd.getOptionValueSource(key);
2497
+ }
2498
+ });
2499
+ return source;
2500
+ }
2501
+
2502
+ /**
2503
+ * Get user arguments from implied or explicit arguments.
2504
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
2505
+ *
2506
+ * @private
2507
+ */
2508
+
2509
+ _prepareUserArgs(argv, parseOptions) {
2510
+ if (argv !== undefined && !Array.isArray(argv)) {
2511
+ throw new Error('first parameter to parse must be array or undefined');
2512
+ }
2513
+ parseOptions = parseOptions || {};
2514
+
2515
+ // auto-detect argument conventions if nothing supplied
2516
+ if (argv === undefined && parseOptions.from === undefined) {
2517
+ if (process.versions?.electron) {
2518
+ parseOptions.from = 'electron';
2519
+ }
2520
+ // check node specific options for scenarios where user CLI args follow executable without scriptname
2521
+ const execArgv = process.execArgv ?? [];
2522
+ if (
2523
+ execArgv.includes('-e') ||
2524
+ execArgv.includes('--eval') ||
2525
+ execArgv.includes('-p') ||
2526
+ execArgv.includes('--print')
2527
+ ) {
2528
+ parseOptions.from = 'eval'; // internal usage, not documented
2529
+ }
2530
+ }
2531
+
2532
+ // default to using process.argv
2533
+ if (argv === undefined) {
2534
+ argv = process.argv;
2535
+ }
2536
+ this.rawArgs = argv.slice();
2537
+
2538
+ // extract the user args and scriptPath
2539
+ let userArgs;
2540
+ switch (parseOptions.from) {
2541
+ case undefined:
2542
+ case 'node':
2543
+ this._scriptPath = argv[1];
2544
+ userArgs = argv.slice(2);
2545
+ break;
2546
+ case 'electron':
2547
+ // @ts-ignore: because defaultApp is an unknown property
2548
+ if (process.defaultApp) {
2549
+ this._scriptPath = argv[1];
2550
+ userArgs = argv.slice(2);
2551
+ } else {
2552
+ userArgs = argv.slice(1);
2553
+ }
2554
+ break;
2555
+ case 'user':
2556
+ userArgs = argv.slice(0);
2557
+ break;
2558
+ case 'eval':
2559
+ userArgs = argv.slice(1);
2560
+ break;
2561
+ default:
2562
+ throw new Error(
2563
+ `unexpected parse option { from: '${parseOptions.from}' }`,
2564
+ );
2565
+ }
2566
+
2567
+ // Find default name for program from arguments.
2568
+ if (!this._name && this._scriptPath)
2569
+ this.nameFromFilename(this._scriptPath);
2570
+ this._name = this._name || 'program';
2571
+
2572
+ return userArgs;
2573
+ }
2574
+
2575
+ /**
2576
+ * Parse `argv`, setting options and invoking commands when defined.
2577
+ *
2578
+ * Use parseAsync instead of parse if any of your action handlers are async.
2579
+ *
2580
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
2581
+ *
2582
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
2583
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
2584
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
2585
+ * - `'user'`: just user arguments
2586
+ *
2587
+ * @example
2588
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
2589
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
2590
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2591
+ *
2592
+ * @param {string[]} [argv] - optional, defaults to process.argv
2593
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
2594
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
2595
+ * @return {Command} `this` command for chaining
2596
+ */
2597
+
2598
+ parse(argv, parseOptions) {
2599
+ this._prepareForParse();
2600
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
2601
+ this._parseCommand([], userArgs);
2602
+
2603
+ return this;
2604
+ }
2605
+
2606
+ /**
2607
+ * Parse `argv`, setting options and invoking commands when defined.
2608
+ *
2609
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
2610
+ *
2611
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
2612
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
2613
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
2614
+ * - `'user'`: just user arguments
2615
+ *
2616
+ * @example
2617
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
2618
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
2619
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2620
+ *
2621
+ * @param {string[]} [argv]
2622
+ * @param {object} [parseOptions]
2623
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
2624
+ * @return {Promise}
2625
+ */
2626
+
2627
+ async parseAsync(argv, parseOptions) {
2628
+ this._prepareForParse();
2629
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
2630
+ await this._parseCommand([], userArgs);
2631
+
2632
+ return this;
2633
+ }
2634
+
2635
+ _prepareForParse() {
2636
+ if (this._savedState === null) {
2637
+ this.saveStateBeforeParse();
2638
+ } else {
2639
+ this.restoreStateBeforeParse();
2640
+ }
2641
+ }
2642
+
2643
+ /**
2644
+ * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
2645
+ * Not usually called directly, but available for subclasses to save their custom state.
2646
+ *
2647
+ * This is called in a lazy way. Only commands used in parsing chain will have state saved.
2648
+ */
2649
+ saveStateBeforeParse() {
2650
+ this._savedState = {
2651
+ // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing
2652
+ _name: this._name,
2653
+ // option values before parse have default values (including false for negated options)
2654
+ // shallow clones
2655
+ _optionValues: { ...this._optionValues },
2656
+ _optionValueSources: { ...this._optionValueSources },
2657
+ };
2658
+ }
2659
+
2660
+ /**
2661
+ * Restore state before parse for calls after the first.
2662
+ * Not usually called directly, but available for subclasses to save their custom state.
2663
+ *
2664
+ * This is called in a lazy way. Only commands used in parsing chain will have state restored.
2665
+ */
2666
+ restoreStateBeforeParse() {
2667
+ if (this._storeOptionsAsProperties)
2668
+ throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
2669
+ - either make a new Command for each call to parse, or stop storing options as properties`);
2670
+
2671
+ // clear state from _prepareUserArgs
2672
+ this._name = this._savedState._name;
2673
+ this._scriptPath = null;
2674
+ this.rawArgs = [];
2675
+ // clear state from setOptionValueWithSource
2676
+ this._optionValues = { ...this._savedState._optionValues };
2677
+ this._optionValueSources = { ...this._savedState._optionValueSources };
2678
+ // clear state from _parseCommand
2679
+ this.args = [];
2680
+ // clear state from _processArguments
2681
+ this.processedArgs = [];
2682
+ }
2683
+
2684
+ /**
2685
+ * Throw if expected executable is missing. Add lots of help for author.
2686
+ *
2687
+ * @param {string} executableFile
2688
+ * @param {string} executableDir
2689
+ * @param {string} subcommandName
2690
+ */
2691
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
2692
+ if (fs.existsSync(executableFile)) return;
2693
+
2694
+ const executableDirMessage = executableDir
2695
+ ? `searched for local subcommand relative to directory '${executableDir}'`
2696
+ : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';
2697
+ const executableMissing = `'${executableFile}' does not exist
2698
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
2699
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
2700
+ - ${executableDirMessage}`;
2701
+ throw new Error(executableMissing);
2702
+ }
2703
+
2704
+ /**
2705
+ * Execute a sub-command executable.
2706
+ *
2707
+ * @private
2708
+ */
2709
+
2710
+ _executeSubCommand(subcommand, args) {
2711
+ args = args.slice();
2712
+ let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.
2713
+ const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];
2714
+
2715
+ function findFile(baseDir, baseName) {
2716
+ // Look for specified file
2717
+ const localBin = path.resolve(baseDir, baseName);
2718
+ if (fs.existsSync(localBin)) return localBin;
2719
+
2720
+ // Stop looking if candidate already has an expected extension.
2721
+ if (sourceExt.includes(path.extname(baseName))) return undefined;
2722
+
2723
+ // Try all the extensions.
2724
+ const foundExt = sourceExt.find((ext) =>
2725
+ fs.existsSync(`${localBin}${ext}`),
2726
+ );
2727
+ if (foundExt) return `${localBin}${foundExt}`;
2728
+
2729
+ return undefined;
2730
+ }
2731
+
2732
+ // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.
2733
+ this._checkForMissingMandatoryOptions();
2734
+ this._checkForConflictingOptions();
2735
+
2736
+ // executableFile and executableDir might be full path, or just a name
2737
+ let executableFile =
2738
+ subcommand._executableFile || `${this._name}-${subcommand._name}`;
2739
+ let executableDir = this._executableDir || '';
2740
+ if (this._scriptPath) {
2741
+ let resolvedScriptPath; // resolve possible symlink for installed npm binary
2742
+ try {
2743
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
2744
+ } catch {
2745
+ resolvedScriptPath = this._scriptPath;
2746
+ }
2747
+ executableDir = path.resolve(
2748
+ path.dirname(resolvedScriptPath),
2749
+ executableDir,
2750
+ );
2751
+ }
2752
+
2753
+ // Look for a local file in preference to a command in PATH.
2754
+ if (executableDir) {
2755
+ let localFile = findFile(executableDir, executableFile);
2756
+
2757
+ // Legacy search using prefix of script name instead of command name
2758
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
2759
+ const legacyName = path.basename(
2760
+ this._scriptPath,
2761
+ path.extname(this._scriptPath),
2762
+ );
2763
+ if (legacyName !== this._name) {
2764
+ localFile = findFile(
2765
+ executableDir,
2766
+ `${legacyName}-${subcommand._name}`,
2767
+ );
2768
+ }
2769
+ }
2770
+ executableFile = localFile || executableFile;
2771
+ }
2772
+
2773
+ launchWithNode = sourceExt.includes(path.extname(executableFile));
2774
+
2775
+ let proc;
2776
+ if (process.platform !== 'win32') {
2777
+ if (launchWithNode) {
2778
+ args.unshift(executableFile);
2779
+ // add executable arguments to spawn
2780
+ args = incrementNodeInspectorPort(process.execArgv).concat(args);
2781
+
2782
+ proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });
2783
+ } else {
2784
+ proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });
2785
+ }
2786
+ } else {
2787
+ this._checkForMissingExecutable(
2788
+ executableFile,
2789
+ executableDir,
2790
+ subcommand._name,
2791
+ );
2792
+ args.unshift(executableFile);
2793
+ // add executable arguments to spawn
2794
+ args = incrementNodeInspectorPort(process.execArgv).concat(args);
2795
+ proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });
2796
+ }
2797
+
2798
+ if (!proc.killed) {
2799
+ // testing mainly to avoid leak warnings during unit tests with mocked spawn
2800
+ const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];
2801
+ signals.forEach((signal) => {
2802
+ process.on(signal, () => {
2803
+ if (proc.killed === false && proc.exitCode === null) {
2804
+ // @ts-ignore because signals not typed to known strings
2805
+ proc.kill(signal);
2806
+ }
2807
+ });
2808
+ });
2809
+ }
2810
+
2811
+ // By default terminate process when spawned process terminates.
2812
+ const exitCallback = this._exitCallback;
2813
+ proc.on('close', (code) => {
2814
+ code = code ?? 1; // code is null if spawned process terminated due to a signal
2815
+ if (!exitCallback) {
2816
+ process.exit(code);
2817
+ } else {
2818
+ exitCallback(
2819
+ new CommanderError(
2820
+ code,
2821
+ 'commander.executeSubCommandAsync',
2822
+ '(close)',
2823
+ ),
2824
+ );
2825
+ }
2826
+ });
2827
+ proc.on('error', (err) => {
2828
+ // @ts-ignore: because err.code is an unknown property
2829
+ if (err.code === 'ENOENT') {
2830
+ this._checkForMissingExecutable(
2831
+ executableFile,
2832
+ executableDir,
2833
+ subcommand._name,
2834
+ );
2835
+ // @ts-ignore: because err.code is an unknown property
2836
+ } else if (err.code === 'EACCES') {
2837
+ throw new Error(`'${executableFile}' not executable`);
2838
+ }
2839
+ if (!exitCallback) {
2840
+ process.exit(1);
2841
+ } else {
2842
+ const wrappedError = new CommanderError(
2843
+ 1,
2844
+ 'commander.executeSubCommandAsync',
2845
+ '(error)',
2846
+ );
2847
+ wrappedError.nestedError = err;
2848
+ exitCallback(wrappedError);
2849
+ }
2850
+ });
2851
+
2852
+ // Store the reference to the child process
2853
+ this.runningCommand = proc;
2854
+ }
2855
+
2856
+ /**
2857
+ * @private
2858
+ */
2859
+
2860
+ _dispatchSubcommand(commandName, operands, unknown) {
2861
+ const subCommand = this._findCommand(commandName);
2862
+ if (!subCommand) this.help({ error: true });
2863
+
2864
+ subCommand._prepareForParse();
2865
+ let promiseChain;
2866
+ promiseChain = this._chainOrCallSubCommandHook(
2867
+ promiseChain,
2868
+ subCommand,
2869
+ 'preSubcommand',
2870
+ );
2871
+ promiseChain = this._chainOrCall(promiseChain, () => {
2872
+ if (subCommand._executableHandler) {
2873
+ this._executeSubCommand(subCommand, operands.concat(unknown));
2874
+ } else {
2875
+ return subCommand._parseCommand(operands, unknown);
2876
+ }
2877
+ });
2878
+ return promiseChain;
2879
+ }
2880
+
2881
+ /**
2882
+ * Invoke help directly if possible, or dispatch if necessary.
2883
+ * e.g. help foo
2884
+ *
2885
+ * @private
2886
+ */
2887
+
2888
+ _dispatchHelpCommand(subcommandName) {
2889
+ if (!subcommandName) {
2890
+ this.help();
2891
+ }
2892
+ const subCommand = this._findCommand(subcommandName);
2893
+ if (subCommand && !subCommand._executableHandler) {
2894
+ subCommand.help();
2895
+ }
2896
+
2897
+ // Fallback to parsing the help flag to invoke the help.
2898
+ return this._dispatchSubcommand(
2899
+ subcommandName,
2900
+ [],
2901
+ [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'],
2902
+ );
2903
+ }
2904
+
2905
+ /**
2906
+ * Check this.args against expected this.registeredArguments.
2907
+ *
2908
+ * @private
2909
+ */
2910
+
2911
+ _checkNumberOfArguments() {
2912
+ // too few
2913
+ this.registeredArguments.forEach((arg, i) => {
2914
+ if (arg.required && this.args[i] == null) {
2915
+ this.missingArgument(arg.name());
2916
+ }
2917
+ });
2918
+ // too many
2919
+ if (
2920
+ this.registeredArguments.length > 0 &&
2921
+ this.registeredArguments[this.registeredArguments.length - 1].variadic
2922
+ ) {
2923
+ return;
2924
+ }
2925
+ if (this.args.length > this.registeredArguments.length) {
2926
+ this._excessArguments(this.args);
2927
+ }
2928
+ }
2929
+
2930
+ /**
2931
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
2932
+ *
2933
+ * @private
2934
+ */
2935
+
2936
+ _processArguments() {
2937
+ const myParseArg = (argument, value, previous) => {
2938
+ // Extra processing for nice error message on parsing failure.
2939
+ let parsedValue = value;
2940
+ if (value !== null && argument.parseArg) {
2941
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
2942
+ parsedValue = this._callParseArg(
2943
+ argument,
2944
+ value,
2945
+ previous,
2946
+ invalidValueMessage,
2947
+ );
2948
+ }
2949
+ return parsedValue;
2950
+ };
2951
+
2952
+ this._checkNumberOfArguments();
2953
+
2954
+ const processedArgs = [];
2955
+ this.registeredArguments.forEach((declaredArg, index) => {
2956
+ let value = declaredArg.defaultValue;
2957
+ if (declaredArg.variadic) {
2958
+ // Collect together remaining arguments for passing together as an array.
2959
+ if (index < this.args.length) {
2960
+ value = this.args.slice(index);
2961
+ if (declaredArg.parseArg) {
2962
+ value = value.reduce((processed, v) => {
2963
+ return myParseArg(declaredArg, v, processed);
2964
+ }, declaredArg.defaultValue);
2965
+ }
2966
+ } else if (value === undefined) {
2967
+ value = [];
2968
+ }
2969
+ } else if (index < this.args.length) {
2970
+ value = this.args[index];
2971
+ if (declaredArg.parseArg) {
2972
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
2973
+ }
2974
+ }
2975
+ processedArgs[index] = value;
2976
+ });
2977
+ this.processedArgs = processedArgs;
2978
+ }
2979
+
2980
+ /**
2981
+ * Once we have a promise we chain, but call synchronously until then.
2982
+ *
2983
+ * @param {(Promise|undefined)} promise
2984
+ * @param {Function} fn
2985
+ * @return {(Promise|undefined)}
2986
+ * @private
2987
+ */
2988
+
2989
+ _chainOrCall(promise, fn) {
2990
+ // thenable
2991
+ if (promise?.then && typeof promise.then === 'function') {
2992
+ // already have a promise, chain callback
2993
+ return promise.then(() => fn());
2994
+ }
2995
+ // callback might return a promise
2996
+ return fn();
2997
+ }
2998
+
2999
+ /**
3000
+ *
3001
+ * @param {(Promise|undefined)} promise
3002
+ * @param {string} event
3003
+ * @return {(Promise|undefined)}
3004
+ * @private
3005
+ */
3006
+
3007
+ _chainOrCallHooks(promise, event) {
3008
+ let result = promise;
3009
+ const hooks = [];
3010
+ this._getCommandAndAncestors()
3011
+ .reverse()
3012
+ .filter((cmd) => cmd._lifeCycleHooks[event] !== undefined)
3013
+ .forEach((hookedCommand) => {
3014
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
3015
+ hooks.push({ hookedCommand, callback });
3016
+ });
3017
+ });
3018
+ if (event === 'postAction') {
3019
+ hooks.reverse();
3020
+ }
3021
+
3022
+ hooks.forEach((hookDetail) => {
3023
+ result = this._chainOrCall(result, () => {
3024
+ return hookDetail.callback(hookDetail.hookedCommand, this);
3025
+ });
3026
+ });
3027
+ return result;
3028
+ }
3029
+
3030
+ /**
3031
+ *
3032
+ * @param {(Promise|undefined)} promise
3033
+ * @param {Command} subCommand
3034
+ * @param {string} event
3035
+ * @return {(Promise|undefined)}
3036
+ * @private
3037
+ */
3038
+
3039
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
3040
+ let result = promise;
3041
+ if (this._lifeCycleHooks[event] !== undefined) {
3042
+ this._lifeCycleHooks[event].forEach((hook) => {
3043
+ result = this._chainOrCall(result, () => {
3044
+ return hook(this, subCommand);
3045
+ });
3046
+ });
3047
+ }
3048
+ return result;
3049
+ }
3050
+
3051
+ /**
3052
+ * Process arguments in context of this command.
3053
+ * Returns action result, in case it is a promise.
3054
+ *
3055
+ * @private
3056
+ */
3057
+
3058
+ _parseCommand(operands, unknown) {
3059
+ const parsed = this.parseOptions(unknown);
3060
+ this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env
3061
+ this._parseOptionsImplied();
3062
+ operands = operands.concat(parsed.operands);
3063
+ unknown = parsed.unknown;
3064
+ this.args = operands.concat(unknown);
3065
+
3066
+ if (operands && this._findCommand(operands[0])) {
3067
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
3068
+ }
3069
+ if (
3070
+ this._getHelpCommand() &&
3071
+ operands[0] === this._getHelpCommand().name()
3072
+ ) {
3073
+ return this._dispatchHelpCommand(operands[1]);
3074
+ }
3075
+ if (this._defaultCommandName) {
3076
+ this._outputHelpIfRequested(unknown); // Run the help for default command from parent rather than passing to default command
3077
+ return this._dispatchSubcommand(
3078
+ this._defaultCommandName,
3079
+ operands,
3080
+ unknown,
3081
+ );
3082
+ }
3083
+ if (
3084
+ this.commands.length &&
3085
+ this.args.length === 0 &&
3086
+ !this._actionHandler &&
3087
+ !this._defaultCommandName
3088
+ ) {
3089
+ // probably missing subcommand and no handler, user needs help (and exit)
3090
+ this.help({ error: true });
3091
+ }
3092
+
3093
+ this._outputHelpIfRequested(parsed.unknown);
3094
+ this._checkForMissingMandatoryOptions();
3095
+ this._checkForConflictingOptions();
3096
+
3097
+ // We do not always call this check to avoid masking a "better" error, like unknown command.
3098
+ const checkForUnknownOptions = () => {
3099
+ if (parsed.unknown.length > 0) {
3100
+ this.unknownOption(parsed.unknown[0]);
3101
+ }
3102
+ };
3103
+
3104
+ const commandEvent = `command:${this.name()}`;
3105
+ if (this._actionHandler) {
3106
+ checkForUnknownOptions();
3107
+ this._processArguments();
3108
+
3109
+ let promiseChain;
3110
+ promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');
3111
+ promiseChain = this._chainOrCall(promiseChain, () =>
3112
+ this._actionHandler(this.processedArgs),
3113
+ );
3114
+ if (this.parent) {
3115
+ promiseChain = this._chainOrCall(promiseChain, () => {
3116
+ this.parent.emit(commandEvent, operands, unknown); // legacy
3117
+ });
3118
+ }
3119
+ promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');
3120
+ return promiseChain;
3121
+ }
3122
+ if (this.parent?.listenerCount(commandEvent)) {
3123
+ checkForUnknownOptions();
3124
+ this._processArguments();
3125
+ this.parent.emit(commandEvent, operands, unknown); // legacy
3126
+ } else if (operands.length) {
3127
+ if (this._findCommand('*')) {
3128
+ // legacy default command
3129
+ return this._dispatchSubcommand('*', operands, unknown);
3130
+ }
3131
+ if (this.listenerCount('command:*')) {
3132
+ // skip option check, emit event for possible misspelling suggestion
3133
+ this.emit('command:*', operands, unknown);
3134
+ } else if (this.commands.length) {
3135
+ this.unknownCommand();
3136
+ } else {
3137
+ checkForUnknownOptions();
3138
+ this._processArguments();
3139
+ }
3140
+ } else if (this.commands.length) {
3141
+ checkForUnknownOptions();
3142
+ // This command has subcommands and nothing hooked up at this level, so display help (and exit).
3143
+ this.help({ error: true });
3144
+ } else {
3145
+ checkForUnknownOptions();
3146
+ this._processArguments();
3147
+ // fall through for caller to handle after calling .parse()
3148
+ }
3149
+ }
3150
+
3151
+ /**
3152
+ * Find matching command.
3153
+ *
3154
+ * @private
3155
+ * @return {Command | undefined}
3156
+ */
3157
+ _findCommand(name) {
3158
+ if (!name) return undefined;
3159
+ return this.commands.find(
3160
+ (cmd) => cmd._name === name || cmd._aliases.includes(name),
3161
+ );
3162
+ }
3163
+
3164
+ /**
3165
+ * Return an option matching `arg` if any.
3166
+ *
3167
+ * @param {string} arg
3168
+ * @return {Option}
3169
+ * @package
3170
+ */
3171
+
3172
+ _findOption(arg) {
3173
+ return this.options.find((option) => option.is(arg));
3174
+ }
3175
+
3176
+ /**
3177
+ * Display an error message if a mandatory option does not have a value.
3178
+ * Called after checking for help flags in leaf subcommand.
3179
+ *
3180
+ * @private
3181
+ */
3182
+
3183
+ _checkForMissingMandatoryOptions() {
3184
+ // Walk up hierarchy so can call in subcommand after checking for displaying help.
3185
+ this._getCommandAndAncestors().forEach((cmd) => {
3186
+ cmd.options.forEach((anOption) => {
3187
+ if (
3188
+ anOption.mandatory &&
3189
+ cmd.getOptionValue(anOption.attributeName()) === undefined
3190
+ ) {
3191
+ cmd.missingMandatoryOptionValue(anOption);
3192
+ }
3193
+ });
3194
+ });
3195
+ }
3196
+
3197
+ /**
3198
+ * Display an error message if conflicting options are used together in this.
3199
+ *
3200
+ * @private
3201
+ */
3202
+ _checkForConflictingLocalOptions() {
3203
+ const definedNonDefaultOptions = this.options.filter((option) => {
3204
+ const optionKey = option.attributeName();
3205
+ if (this.getOptionValue(optionKey) === undefined) {
3206
+ return false;
3207
+ }
3208
+ return this.getOptionValueSource(optionKey) !== 'default';
3209
+ });
3210
+
3211
+ const optionsWithConflicting = definedNonDefaultOptions.filter(
3212
+ (option) => option.conflictsWith.length > 0,
3213
+ );
3214
+
3215
+ optionsWithConflicting.forEach((option) => {
3216
+ const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>
3217
+ option.conflictsWith.includes(defined.attributeName()),
3218
+ );
3219
+ if (conflictingAndDefined) {
3220
+ this._conflictingOption(option, conflictingAndDefined);
3221
+ }
3222
+ });
3223
+ }
3224
+
3225
+ /**
3226
+ * Display an error message if conflicting options are used together.
3227
+ * Called after checking for help flags in leaf subcommand.
3228
+ *
3229
+ * @private
3230
+ */
3231
+ _checkForConflictingOptions() {
3232
+ // Walk up hierarchy so can call in subcommand after checking for displaying help.
3233
+ this._getCommandAndAncestors().forEach((cmd) => {
3234
+ cmd._checkForConflictingLocalOptions();
3235
+ });
3236
+ }
3237
+
3238
+ /**
3239
+ * Parse options from `argv` removing known options,
3240
+ * and return argv split into operands and unknown arguments.
3241
+ *
3242
+ * Side effects: modifies command by storing options. Does not reset state if called again.
3243
+ *
3244
+ * Examples:
3245
+ *
3246
+ * argv => operands, unknown
3247
+ * --known kkk op => [op], []
3248
+ * op --known kkk => [op], []
3249
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
3250
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
3251
+ *
3252
+ * @param {string[]} args
3253
+ * @return {{operands: string[], unknown: string[]}}
3254
+ */
3255
+
3256
+ parseOptions(args) {
3257
+ const operands = []; // operands, not options or values
3258
+ const unknown = []; // first unknown option and remaining unknown args
3259
+ let dest = operands;
3260
+
3261
+ function maybeOption(arg) {
3262
+ return arg.length > 1 && arg[0] === '-';
3263
+ }
3264
+
3265
+ const negativeNumberArg = (arg) => {
3266
+ // return false if not a negative number
3267
+ if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)) return false;
3268
+ // negative number is ok unless digit used as an option in command hierarchy
3269
+ return !this._getCommandAndAncestors().some((cmd) =>
3270
+ cmd.options
3271
+ .map((opt) => opt.short)
3272
+ .some((short) => /^-\d$/.test(short)),
3273
+ );
3274
+ };
3275
+
3276
+ // parse options
3277
+ let activeVariadicOption = null;
3278
+ let activeGroup = null; // working through group of short options, like -abc
3279
+ let i = 0;
3280
+ while (i < args.length || activeGroup) {
3281
+ const arg = activeGroup ?? args[i++];
3282
+ activeGroup = null;
3283
+
3284
+ // literal
3285
+ if (arg === '--') {
3286
+ if (dest === unknown) dest.push(arg);
3287
+ dest.push(...args.slice(i));
3288
+ break;
3289
+ }
3290
+
3291
+ if (
3292
+ activeVariadicOption &&
3293
+ (!maybeOption(arg) || negativeNumberArg(arg))
3294
+ ) {
3295
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
3296
+ continue;
3297
+ }
3298
+ activeVariadicOption = null;
3299
+
3300
+ if (maybeOption(arg)) {
3301
+ const option = this._findOption(arg);
3302
+ // recognised option, call listener to assign value with possible custom processing
3303
+ if (option) {
3304
+ if (option.required) {
3305
+ const value = args[i++];
3306
+ if (value === undefined) this.optionMissingArgument(option);
3307
+ this.emit(`option:${option.name()}`, value);
3308
+ } else if (option.optional) {
3309
+ let value = null;
3310
+ // historical behaviour is optional value is following arg unless an option
3311
+ if (
3312
+ i < args.length &&
3313
+ (!maybeOption(args[i]) || negativeNumberArg(args[i]))
3314
+ ) {
3315
+ value = args[i++];
3316
+ }
3317
+ this.emit(`option:${option.name()}`, value);
3318
+ } else {
3319
+ // boolean flag
3320
+ this.emit(`option:${option.name()}`);
3321
+ }
3322
+ activeVariadicOption = option.variadic ? option : null;
3323
+ continue;
3324
+ }
3325
+ }
3326
+
3327
+ // Look for combo options following single dash, eat first one if known.
3328
+ if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {
3329
+ const option = this._findOption(`-${arg[1]}`);
3330
+ if (option) {
3331
+ if (
3332
+ option.required ||
3333
+ (option.optional && this._combineFlagAndOptionalValue)
3334
+ ) {
3335
+ // option with value following in same argument
3336
+ this.emit(`option:${option.name()}`, arg.slice(2));
3337
+ } else {
3338
+ // boolean option
3339
+ this.emit(`option:${option.name()}`);
3340
+ // remove the processed option and keep processing group
3341
+ activeGroup = `-${arg.slice(2)}`;
3342
+ }
3343
+ continue;
3344
+ }
3345
+ }
3346
+
3347
+ // Look for known long flag with value, like --foo=bar
3348
+ if (/^--[^=]+=/.test(arg)) {
3349
+ const index = arg.indexOf('=');
3350
+ const option = this._findOption(arg.slice(0, index));
3351
+ if (option && (option.required || option.optional)) {
3352
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
3353
+ continue;
3354
+ }
3355
+ }
3356
+
3357
+ // Not a recognised option by this command.
3358
+ // Might be a command-argument, or subcommand option, or unknown option, or help command or option.
3359
+
3360
+ // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.
3361
+ // A negative number in a leaf command is not an unknown option.
3362
+ if (
3363
+ dest === operands &&
3364
+ maybeOption(arg) &&
3365
+ !(this.commands.length === 0 && negativeNumberArg(arg))
3366
+ ) {
3367
+ dest = unknown;
3368
+ }
3369
+
3370
+ // If using positionalOptions, stop processing our options at subcommand.
3371
+ if (
3372
+ (this._enablePositionalOptions || this._passThroughOptions) &&
3373
+ operands.length === 0 &&
3374
+ unknown.length === 0
3375
+ ) {
3376
+ if (this._findCommand(arg)) {
3377
+ operands.push(arg);
3378
+ unknown.push(...args.slice(i));
3379
+ break;
3380
+ } else if (
3381
+ this._getHelpCommand() &&
3382
+ arg === this._getHelpCommand().name()
3383
+ ) {
3384
+ operands.push(arg, ...args.slice(i));
3385
+ break;
3386
+ } else if (this._defaultCommandName) {
3387
+ unknown.push(arg, ...args.slice(i));
3388
+ break;
3389
+ }
3390
+ }
3391
+
3392
+ // If using passThroughOptions, stop processing options at first command-argument.
3393
+ if (this._passThroughOptions) {
3394
+ dest.push(arg, ...args.slice(i));
3395
+ break;
3396
+ }
3397
+
3398
+ // add arg
3399
+ dest.push(arg);
3400
+ }
3401
+
3402
+ return { operands, unknown };
3403
+ }
3404
+
3405
+ /**
3406
+ * Return an object containing local option values as key-value pairs.
3407
+ *
3408
+ * @return {object}
3409
+ */
3410
+ opts() {
3411
+ if (this._storeOptionsAsProperties) {
3412
+ // Preserve original behaviour so backwards compatible when still using properties
3413
+ const result = {};
3414
+ const len = this.options.length;
3415
+
3416
+ for (let i = 0; i < len; i++) {
3417
+ const key = this.options[i].attributeName();
3418
+ result[key] =
3419
+ key === this._versionOptionName ? this._version : this[key];
3420
+ }
3421
+ return result;
3422
+ }
3423
+
3424
+ return this._optionValues;
3425
+ }
3426
+
3427
+ /**
3428
+ * Return an object containing merged local and global option values as key-value pairs.
3429
+ *
3430
+ * @return {object}
3431
+ */
3432
+ optsWithGlobals() {
3433
+ // globals overwrite locals
3434
+ return this._getCommandAndAncestors().reduce(
3435
+ (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
3436
+ {},
3437
+ );
3438
+ }
3439
+
3440
+ /**
3441
+ * Display error message and exit (or call exitOverride).
3442
+ *
3443
+ * @param {string} message
3444
+ * @param {object} [errorOptions]
3445
+ * @param {string} [errorOptions.code] - an id string representing the error
3446
+ * @param {number} [errorOptions.exitCode] - used with process.exit
3447
+ */
3448
+ error(message, errorOptions) {
3449
+ // output handling
3450
+ this._outputConfiguration.outputError(
3451
+ `${message}\n`,
3452
+ this._outputConfiguration.writeErr,
3453
+ );
3454
+ if (typeof this._showHelpAfterError === 'string') {
3455
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);
3456
+ } else if (this._showHelpAfterError) {
3457
+ this._outputConfiguration.writeErr('\n');
3458
+ this.outputHelp({ error: true });
3459
+ }
3460
+
3461
+ // exit handling
3462
+ const config = errorOptions || {};
3463
+ const exitCode = config.exitCode || 1;
3464
+ const code = config.code || 'commander.error';
3465
+ this._exit(exitCode, code, message);
3466
+ }
3467
+
3468
+ /**
3469
+ * Apply any option related environment variables, if option does
3470
+ * not have a value from cli or client code.
3471
+ *
3472
+ * @private
3473
+ */
3474
+ _parseOptionsEnv() {
3475
+ this.options.forEach((option) => {
3476
+ if (option.envVar && option.envVar in process.env) {
3477
+ const optionKey = option.attributeName();
3478
+ // Priority check. Do not overwrite cli or options from unknown source (client-code).
3479
+ if (
3480
+ this.getOptionValue(optionKey) === undefined ||
3481
+ ['default', 'config', 'env'].includes(
3482
+ this.getOptionValueSource(optionKey),
3483
+ )
3484
+ ) {
3485
+ if (option.required || option.optional) {
3486
+ // option can take a value
3487
+ // keep very simple, optional always takes value
3488
+ this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);
3489
+ } else {
3490
+ // boolean
3491
+ // keep very simple, only care that envVar defined and not the value
3492
+ this.emit(`optionEnv:${option.name()}`);
3493
+ }
3494
+ }
3495
+ }
3496
+ });
3497
+ }
3498
+
3499
+ /**
3500
+ * Apply any implied option values, if option is undefined or default value.
3501
+ *
3502
+ * @private
3503
+ */
3504
+ _parseOptionsImplied() {
3505
+ const dualHelper = new DualOptions(this.options);
3506
+ const hasCustomOptionValue = (optionKey) => {
3507
+ return (
3508
+ this.getOptionValue(optionKey) !== undefined &&
3509
+ !['default', 'implied'].includes(this.getOptionValueSource(optionKey))
3510
+ );
3511
+ };
3512
+ this.options
3513
+ .filter(
3514
+ (option) =>
3515
+ option.implied !== undefined &&
3516
+ hasCustomOptionValue(option.attributeName()) &&
3517
+ dualHelper.valueFromOption(
3518
+ this.getOptionValue(option.attributeName()),
3519
+ option,
3520
+ ),
3521
+ )
3522
+ .forEach((option) => {
3523
+ Object.keys(option.implied)
3524
+ .filter((impliedKey) => !hasCustomOptionValue(impliedKey))
3525
+ .forEach((impliedKey) => {
3526
+ this.setOptionValueWithSource(
3527
+ impliedKey,
3528
+ option.implied[impliedKey],
3529
+ 'implied',
3530
+ );
3531
+ });
3532
+ });
3533
+ }
3534
+
3535
+ /**
3536
+ * Argument `name` is missing.
3537
+ *
3538
+ * @param {string} name
3539
+ * @private
3540
+ */
3541
+
3542
+ missingArgument(name) {
3543
+ const message = `error: missing required argument '${name}'`;
3544
+ this.error(message, { code: 'commander.missingArgument' });
3545
+ }
3546
+
3547
+ /**
3548
+ * `Option` is missing an argument.
3549
+ *
3550
+ * @param {Option} option
3551
+ * @private
3552
+ */
3553
+
3554
+ optionMissingArgument(option) {
3555
+ const message = `error: option '${option.flags}' argument missing`;
3556
+ this.error(message, { code: 'commander.optionMissingArgument' });
3557
+ }
3558
+
3559
+ /**
3560
+ * `Option` does not have a value, and is a mandatory option.
3561
+ *
3562
+ * @param {Option} option
3563
+ * @private
3564
+ */
3565
+
3566
+ missingMandatoryOptionValue(option) {
3567
+ const message = `error: required option '${option.flags}' not specified`;
3568
+ this.error(message, { code: 'commander.missingMandatoryOptionValue' });
3569
+ }
3570
+
3571
+ /**
3572
+ * `Option` conflicts with another option.
3573
+ *
3574
+ * @param {Option} option
3575
+ * @param {Option} conflictingOption
3576
+ * @private
3577
+ */
3578
+ _conflictingOption(option, conflictingOption) {
3579
+ // The calling code does not know whether a negated option is the source of the
3580
+ // value, so do some work to take an educated guess.
3581
+ const findBestOptionFromValue = (option) => {
3582
+ const optionKey = option.attributeName();
3583
+ const optionValue = this.getOptionValue(optionKey);
3584
+ const negativeOption = this.options.find(
3585
+ (target) => target.negate && optionKey === target.attributeName(),
3586
+ );
3587
+ const positiveOption = this.options.find(
3588
+ (target) => !target.negate && optionKey === target.attributeName(),
3589
+ );
3590
+ if (
3591
+ negativeOption &&
3592
+ ((negativeOption.presetArg === undefined && optionValue === false) ||
3593
+ (negativeOption.presetArg !== undefined &&
3594
+ optionValue === negativeOption.presetArg))
3595
+ ) {
3596
+ return negativeOption;
3597
+ }
3598
+ return positiveOption || option;
3599
+ };
3600
+
3601
+ const getErrorMessage = (option) => {
3602
+ const bestOption = findBestOptionFromValue(option);
3603
+ const optionKey = bestOption.attributeName();
3604
+ const source = this.getOptionValueSource(optionKey);
3605
+ if (source === 'env') {
3606
+ return `environment variable '${bestOption.envVar}'`;
3607
+ }
3608
+ return `option '${bestOption.flags}'`;
3609
+ };
3610
+
3611
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
3612
+ this.error(message, { code: 'commander.conflictingOption' });
3613
+ }
3614
+
3615
+ /**
3616
+ * Unknown option `flag`.
3617
+ *
3618
+ * @param {string} flag
3619
+ * @private
3620
+ */
3621
+
3622
+ unknownOption(flag) {
3623
+ if (this._allowUnknownOption) return;
3624
+ let suggestion = '';
3625
+
3626
+ if (flag.startsWith('--') && this._showSuggestionAfterError) {
3627
+ // Looping to pick up the global options too
3628
+ let candidateFlags = [];
3629
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
3630
+ let command = this;
3631
+ do {
3632
+ const moreFlags = command
3633
+ .createHelp()
3634
+ .visibleOptions(command)
3635
+ .filter((option) => option.long)
3636
+ .map((option) => option.long);
3637
+ candidateFlags = candidateFlags.concat(moreFlags);
3638
+ command = command.parent;
3639
+ } while (command && !command._enablePositionalOptions);
3640
+ suggestion = suggestSimilar(flag, candidateFlags);
3641
+ }
3642
+
3643
+ const message = `error: unknown option '${flag}'${suggestion}`;
3644
+ this.error(message, { code: 'commander.unknownOption' });
3645
+ }
3646
+
3647
+ /**
3648
+ * Excess arguments, more than expected.
3649
+ *
3650
+ * @param {string[]} receivedArgs
3651
+ * @private
3652
+ */
3653
+
3654
+ _excessArguments(receivedArgs) {
3655
+ if (this._allowExcessArguments) return;
3656
+
3657
+ const expected = this.registeredArguments.length;
3658
+ const s = expected === 1 ? '' : 's';
3659
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : '';
3660
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
3661
+ this.error(message, { code: 'commander.excessArguments' });
3662
+ }
3663
+
3664
+ /**
3665
+ * Unknown command.
3666
+ *
3667
+ * @private
3668
+ */
3669
+
3670
+ unknownCommand() {
3671
+ const unknownName = this.args[0];
3672
+ let suggestion = '';
3673
+
3674
+ if (this._showSuggestionAfterError) {
3675
+ const candidateNames = [];
3676
+ this.createHelp()
3677
+ .visibleCommands(this)
3678
+ .forEach((command) => {
3679
+ candidateNames.push(command.name());
3680
+ // just visible alias
3681
+ if (command.alias()) candidateNames.push(command.alias());
3682
+ });
3683
+ suggestion = suggestSimilar(unknownName, candidateNames);
3684
+ }
3685
+
3686
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
3687
+ this.error(message, { code: 'commander.unknownCommand' });
3688
+ }
3689
+
3690
+ /**
3691
+ * Get or set the program version.
3692
+ *
3693
+ * This method auto-registers the "-V, --version" option which will print the version number.
3694
+ *
3695
+ * You can optionally supply the flags and description to override the defaults.
3696
+ *
3697
+ * @param {string} [str]
3698
+ * @param {string} [flags]
3699
+ * @param {string} [description]
3700
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
3701
+ */
3702
+
3703
+ version(str, flags, description) {
3704
+ if (str === undefined) return this._version;
3705
+ this._version = str;
3706
+ flags = flags || '-V, --version';
3707
+ description = description || 'output the version number';
3708
+ const versionOption = this.createOption(flags, description);
3709
+ this._versionOptionName = versionOption.attributeName();
3710
+ this._registerOption(versionOption);
3711
+
3712
+ this.on('option:' + versionOption.name(), () => {
3713
+ this._outputConfiguration.writeOut(`${str}\n`);
3714
+ this._exit(0, 'commander.version', str);
3715
+ });
3716
+ return this;
3717
+ }
3718
+
3719
+ /**
3720
+ * Set the description.
3721
+ *
3722
+ * @param {string} [str]
3723
+ * @param {object} [argsDescription]
3724
+ * @return {(string|Command)}
3725
+ */
3726
+ description(str, argsDescription) {
3727
+ if (str === undefined && argsDescription === undefined)
3728
+ return this._description;
3729
+ this._description = str;
3730
+ if (argsDescription) {
3731
+ this._argsDescription = argsDescription;
3732
+ }
3733
+ return this;
3734
+ }
3735
+
3736
+ /**
3737
+ * Set the summary. Used when listed as subcommand of parent.
3738
+ *
3739
+ * @param {string} [str]
3740
+ * @return {(string|Command)}
3741
+ */
3742
+ summary(str) {
3743
+ if (str === undefined) return this._summary;
3744
+ this._summary = str;
3745
+ return this;
3746
+ }
3747
+
3748
+ /**
3749
+ * Set an alias for the command.
3750
+ *
3751
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
3752
+ *
3753
+ * @param {string} [alias]
3754
+ * @return {(string|Command)}
3755
+ */
3756
+
3757
+ alias(alias) {
3758
+ if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility
3759
+
3760
+ /** @type {Command} */
3761
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
3762
+ let command = this;
3763
+ if (
3764
+ this.commands.length !== 0 &&
3765
+ this.commands[this.commands.length - 1]._executableHandler
3766
+ ) {
3767
+ // assume adding alias for last added executable subcommand, rather than this
3768
+ command = this.commands[this.commands.length - 1];
3769
+ }
3770
+
3771
+ if (alias === command._name)
3772
+ throw new Error("Command alias can't be the same as its name");
3773
+ const matchingCommand = this.parent?._findCommand(alias);
3774
+ if (matchingCommand) {
3775
+ // c.f. _registerCommand
3776
+ const existingCmd = [matchingCommand.name()]
3777
+ .concat(matchingCommand.aliases())
3778
+ .join('|');
3779
+ throw new Error(
3780
+ `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`,
3781
+ );
3782
+ }
3783
+
3784
+ command._aliases.push(alias);
3785
+ return this;
3786
+ }
3787
+
3788
+ /**
3789
+ * Set aliases for the command.
3790
+ *
3791
+ * Only the first alias is shown in the auto-generated help.
3792
+ *
3793
+ * @param {string[]} [aliases]
3794
+ * @return {(string[]|Command)}
3795
+ */
3796
+
3797
+ aliases(aliases) {
3798
+ // Getter for the array of aliases is the main reason for having aliases() in addition to alias().
3799
+ if (aliases === undefined) return this._aliases;
3800
+
3801
+ aliases.forEach((alias) => this.alias(alias));
3802
+ return this;
3803
+ }
3804
+
3805
+ /**
3806
+ * Set / get the command usage `str`.
3807
+ *
3808
+ * @param {string} [str]
3809
+ * @return {(string|Command)}
3810
+ */
3811
+
3812
+ usage(str) {
3813
+ if (str === undefined) {
3814
+ if (this._usage) return this._usage;
3815
+
3816
+ const args = this.registeredArguments.map((arg) => {
3817
+ return humanReadableArgName(arg);
3818
+ });
3819
+ return []
3820
+ .concat(
3821
+ this.options.length || this._helpOption !== null ? '[options]' : [],
3822
+ this.commands.length ? '[command]' : [],
3823
+ this.registeredArguments.length ? args : [],
3824
+ )
3825
+ .join(' ');
3826
+ }
3827
+
3828
+ this._usage = str;
3829
+ return this;
3830
+ }
3831
+
3832
+ /**
3833
+ * Get or set the name of the command.
3834
+ *
3835
+ * @param {string} [str]
3836
+ * @return {(string|Command)}
3837
+ */
3838
+
3839
+ name(str) {
3840
+ if (str === undefined) return this._name;
3841
+ this._name = str;
3842
+ return this;
3843
+ }
3844
+
3845
+ /**
3846
+ * Set/get the help group heading for this subcommand in parent command's help.
3847
+ *
3848
+ * @param {string} [heading]
3849
+ * @return {Command | string}
3850
+ */
3851
+
3852
+ helpGroup(heading) {
3853
+ if (heading === undefined) return this._helpGroupHeading ?? '';
3854
+ this._helpGroupHeading = heading;
3855
+ return this;
3856
+ }
3857
+
3858
+ /**
3859
+ * Set/get the default help group heading for subcommands added to this command.
3860
+ * (This does not override a group set directly on the subcommand using .helpGroup().)
3861
+ *
3862
+ * @example
3863
+ * program.commandsGroup('Development Commands:);
3864
+ * program.command('watch')...
3865
+ * program.command('lint')...
3866
+ * ...
3867
+ *
3868
+ * @param {string} [heading]
3869
+ * @returns {Command | string}
3870
+ */
3871
+ commandsGroup(heading) {
3872
+ if (heading === undefined) return this._defaultCommandGroup ?? '';
3873
+ this._defaultCommandGroup = heading;
3874
+ return this;
3875
+ }
3876
+
3877
+ /**
3878
+ * Set/get the default help group heading for options added to this command.
3879
+ * (This does not override a group set directly on the option using .helpGroup().)
3880
+ *
3881
+ * @example
3882
+ * program
3883
+ * .optionsGroup('Development Options:')
3884
+ * .option('-d, --debug', 'output extra debugging')
3885
+ * .option('-p, --profile', 'output profiling information')
3886
+ *
3887
+ * @param {string} [heading]
3888
+ * @returns {Command | string}
3889
+ */
3890
+ optionsGroup(heading) {
3891
+ if (heading === undefined) return this._defaultOptionGroup ?? '';
3892
+ this._defaultOptionGroup = heading;
3893
+ return this;
3894
+ }
3895
+
3896
+ /**
3897
+ * @param {Option} option
3898
+ * @private
3899
+ */
3900
+ _initOptionGroup(option) {
3901
+ if (this._defaultOptionGroup && !option.helpGroupHeading)
3902
+ option.helpGroup(this._defaultOptionGroup);
3903
+ }
3904
+
3905
+ /**
3906
+ * @param {Command} cmd
3907
+ * @private
3908
+ */
3909
+ _initCommandGroup(cmd) {
3910
+ if (this._defaultCommandGroup && !cmd.helpGroup())
3911
+ cmd.helpGroup(this._defaultCommandGroup);
3912
+ }
3913
+
3914
+ /**
3915
+ * Set the name of the command from script filename, such as process.argv[1],
3916
+ * or require.main.filename, or __filename.
3917
+ *
3918
+ * (Used internally and public although not documented in README.)
3919
+ *
3920
+ * @example
3921
+ * program.nameFromFilename(require.main.filename);
3922
+ *
3923
+ * @param {string} filename
3924
+ * @return {Command}
3925
+ */
3926
+
3927
+ nameFromFilename(filename) {
3928
+ this._name = path.basename(filename, path.extname(filename));
3929
+
3930
+ return this;
3931
+ }
3932
+
3933
+ /**
3934
+ * Get or set the directory for searching for executable subcommands of this command.
3935
+ *
3936
+ * @example
3937
+ * program.executableDir(__dirname);
3938
+ * // or
3939
+ * program.executableDir('subcommands');
3940
+ *
3941
+ * @param {string} [path]
3942
+ * @return {(string|null|Command)}
3943
+ */
3944
+
3945
+ executableDir(path) {
3946
+ if (path === undefined) return this._executableDir;
3947
+ this._executableDir = path;
3948
+ return this;
3949
+ }
3950
+
3951
+ /**
3952
+ * Return program help documentation.
3953
+ *
3954
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
3955
+ * @return {string}
3956
+ */
3957
+
3958
+ helpInformation(contextOptions) {
3959
+ const helper = this.createHelp();
3960
+ const context = this._getOutputContext(contextOptions);
3961
+ helper.prepareContext({
3962
+ error: context.error,
3963
+ helpWidth: context.helpWidth,
3964
+ outputHasColors: context.hasColors,
3965
+ });
3966
+ const text = helper.formatHelp(this, helper);
3967
+ if (context.hasColors) return text;
3968
+ return this._outputConfiguration.stripColor(text);
3969
+ }
3970
+
3971
+ /**
3972
+ * @typedef HelpContext
3973
+ * @type {object}
3974
+ * @property {boolean} error
3975
+ * @property {number} helpWidth
3976
+ * @property {boolean} hasColors
3977
+ * @property {function} write - includes stripColor if needed
3978
+ *
3979
+ * @returns {HelpContext}
3980
+ * @private
3981
+ */
3982
+
3983
+ _getOutputContext(contextOptions) {
3984
+ contextOptions = contextOptions || {};
3985
+ const error = !!contextOptions.error;
3986
+ let baseWrite;
3987
+ let hasColors;
3988
+ let helpWidth;
3989
+ if (error) {
3990
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
3991
+ hasColors = this._outputConfiguration.getErrHasColors();
3992
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
3993
+ } else {
3994
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
3995
+ hasColors = this._outputConfiguration.getOutHasColors();
3996
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
3997
+ }
3998
+ const write = (str) => {
3999
+ if (!hasColors) str = this._outputConfiguration.stripColor(str);
4000
+ return baseWrite(str);
4001
+ };
4002
+ return { error, write, hasColors, helpWidth };
4003
+ }
4004
+
4005
+ /**
4006
+ * Output help information for this command.
4007
+ *
4008
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
4009
+ *
4010
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
4011
+ */
4012
+
4013
+ outputHelp(contextOptions) {
4014
+ let deprecatedCallback;
4015
+ if (typeof contextOptions === 'function') {
4016
+ deprecatedCallback = contextOptions;
4017
+ contextOptions = undefined;
4018
+ }
4019
+
4020
+ const outputContext = this._getOutputContext(contextOptions);
4021
+ /** @type {HelpTextEventContext} */
4022
+ const eventContext = {
4023
+ error: outputContext.error,
4024
+ write: outputContext.write,
4025
+ command: this,
4026
+ };
4027
+
4028
+ this._getCommandAndAncestors()
4029
+ .reverse()
4030
+ .forEach((command) => command.emit('beforeAllHelp', eventContext));
4031
+ this.emit('beforeHelp', eventContext);
4032
+
4033
+ let helpInformation = this.helpInformation({ error: outputContext.error });
4034
+ if (deprecatedCallback) {
4035
+ helpInformation = deprecatedCallback(helpInformation);
4036
+ if (
4037
+ typeof helpInformation !== 'string' &&
4038
+ !Buffer.isBuffer(helpInformation)
4039
+ ) {
4040
+ throw new Error('outputHelp callback must return a string or a Buffer');
4041
+ }
4042
+ }
4043
+ outputContext.write(helpInformation);
4044
+
4045
+ if (this._getHelpOption()?.long) {
4046
+ this.emit(this._getHelpOption().long); // deprecated
4047
+ }
4048
+ this.emit('afterHelp', eventContext);
4049
+ this._getCommandAndAncestors().forEach((command) =>
4050
+ command.emit('afterAllHelp', eventContext),
4051
+ );
4052
+ }
4053
+
4054
+ /**
4055
+ * You can pass in flags and a description to customise the built-in help option.
4056
+ * Pass in false to disable the built-in help option.
4057
+ *
4058
+ * @example
4059
+ * program.helpOption('-?, --help' 'show help'); // customise
4060
+ * program.helpOption(false); // disable
4061
+ *
4062
+ * @param {(string | boolean)} flags
4063
+ * @param {string} [description]
4064
+ * @return {Command} `this` command for chaining
4065
+ */
4066
+
4067
+ helpOption(flags, description) {
4068
+ // Support enabling/disabling built-in help option.
4069
+ if (typeof flags === 'boolean') {
4070
+ if (flags) {
4071
+ if (this._helpOption === null) this._helpOption = undefined; // reenable
4072
+ if (this._defaultOptionGroup) {
4073
+ // make the option to store the group
4074
+ this._initOptionGroup(this._getHelpOption());
4075
+ }
4076
+ } else {
4077
+ this._helpOption = null; // disable
4078
+ }
4079
+ return this;
4080
+ }
4081
+
4082
+ // Customise flags and description.
4083
+ this._helpOption = this.createOption(
4084
+ flags ?? '-h, --help',
4085
+ description ?? 'display help for command',
4086
+ );
4087
+ // init group unless lazy create
4088
+ if (flags || description) this._initOptionGroup(this._helpOption);
4089
+
4090
+ return this;
4091
+ }
4092
+
4093
+ /**
4094
+ * Lazy create help option.
4095
+ * Returns null if has been disabled with .helpOption(false).
4096
+ *
4097
+ * @returns {(Option | null)} the help option
4098
+ * @package
4099
+ */
4100
+ _getHelpOption() {
4101
+ // Lazy create help option on demand.
4102
+ if (this._helpOption === undefined) {
4103
+ this.helpOption(undefined, undefined);
4104
+ }
4105
+ return this._helpOption;
4106
+ }
4107
+
4108
+ /**
4109
+ * Supply your own option to use for the built-in help option.
4110
+ * This is an alternative to using helpOption() to customise the flags and description etc.
4111
+ *
4112
+ * @param {Option} option
4113
+ * @return {Command} `this` command for chaining
4114
+ */
4115
+ addHelpOption(option) {
4116
+ this._helpOption = option;
4117
+ this._initOptionGroup(option);
4118
+ return this;
4119
+ }
4120
+
4121
+ /**
4122
+ * Output help information and exit.
4123
+ *
4124
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
4125
+ *
4126
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
4127
+ */
4128
+
4129
+ help(contextOptions) {
4130
+ this.outputHelp(contextOptions);
4131
+ let exitCode = Number(process.exitCode ?? 0); // process.exitCode does allow a string or an integer, but we prefer just a number
4132
+ if (
4133
+ exitCode === 0 &&
4134
+ contextOptions &&
4135
+ typeof contextOptions !== 'function' &&
4136
+ contextOptions.error
4137
+ ) {
4138
+ exitCode = 1;
4139
+ }
4140
+ // message: do not have all displayed text available so only passing placeholder.
4141
+ this._exit(exitCode, 'commander.help', '(outputHelp)');
4142
+ }
4143
+
4144
+ /**
4145
+ * // Do a little typing to coordinate emit and listener for the help text events.
4146
+ * @typedef HelpTextEventContext
4147
+ * @type {object}
4148
+ * @property {boolean} error
4149
+ * @property {Command} command
4150
+ * @property {function} write
4151
+ */
4152
+
4153
+ /**
4154
+ * Add additional text to be displayed with the built-in help.
4155
+ *
4156
+ * Position is 'before' or 'after' to affect just this command,
4157
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
4158
+ *
4159
+ * @param {string} position - before or after built-in help
4160
+ * @param {(string | Function)} text - string to add, or a function returning a string
4161
+ * @return {Command} `this` command for chaining
4162
+ */
4163
+
4164
+ addHelpText(position, text) {
4165
+ const allowedValues = ['beforeAll', 'before', 'after', 'afterAll'];
4166
+ if (!allowedValues.includes(position)) {
4167
+ throw new Error(`Unexpected value for position to addHelpText.
4168
+ Expecting one of '${allowedValues.join("', '")}'`);
4169
+ }
4170
+
4171
+ const helpEvent = `${position}Help`;
4172
+ this.on(helpEvent, (/** @type {HelpTextEventContext} */ context) => {
4173
+ let helpStr;
4174
+ if (typeof text === 'function') {
4175
+ helpStr = text({ error: context.error, command: context.command });
4176
+ } else {
4177
+ helpStr = text;
4178
+ }
4179
+ // Ignore falsy value when nothing to output.
4180
+ if (helpStr) {
4181
+ context.write(`${helpStr}\n`);
4182
+ }
4183
+ });
4184
+ return this;
4185
+ }
4186
+
4187
+ /**
4188
+ * Output help information if help flags specified
4189
+ *
4190
+ * @param {Array} args - array of options to search for help flags
4191
+ * @private
4192
+ */
4193
+
4194
+ _outputHelpIfRequested(args) {
4195
+ const helpOption = this._getHelpOption();
4196
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
4197
+ if (helpRequested) {
4198
+ this.outputHelp();
4199
+ // (Do not have all displayed text available so only passing placeholder.)
4200
+ this._exit(0, 'commander.helpDisplayed', '(outputHelp)');
4201
+ }
4202
+ }
4203
+ }
4204
+
4205
+ /**
4206
+ * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).
4207
+ *
4208
+ * @param {string[]} args - array of arguments from node.execArgv
4209
+ * @returns {string[]}
4210
+ * @private
4211
+ */
4212
+
4213
+ function incrementNodeInspectorPort(args) {
4214
+ // Testing for these options:
4215
+ // --inspect[=[host:]port]
4216
+ // --inspect-brk[=[host:]port]
4217
+ // --inspect-port=[host:]port
4218
+ return args.map((arg) => {
4219
+ if (!arg.startsWith('--inspect')) {
4220
+ return arg;
4221
+ }
4222
+ let debugOption;
4223
+ let debugHost = '127.0.0.1';
4224
+ let debugPort = '9229';
4225
+ let match;
4226
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
4227
+ // e.g. --inspect
4228
+ debugOption = match[1];
4229
+ } else if (
4230
+ (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null
4231
+ ) {
4232
+ debugOption = match[1];
4233
+ if (/^\d+$/.test(match[3])) {
4234
+ // e.g. --inspect=1234
4235
+ debugPort = match[3];
4236
+ } else {
4237
+ // e.g. --inspect=localhost
4238
+ debugHost = match[3];
4239
+ }
4240
+ } else if (
4241
+ (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null
4242
+ ) {
4243
+ // e.g. --inspect=localhost:1234
4244
+ debugOption = match[1];
4245
+ debugHost = match[3];
4246
+ debugPort = match[4];
4247
+ }
4248
+
4249
+ if (debugOption && debugPort !== '0') {
4250
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
4251
+ }
4252
+ return arg;
4253
+ });
4254
+ }
4255
+
4256
+ /**
4257
+ * @returns {boolean | undefined}
4258
+ * @package
4259
+ */
4260
+ function useColor() {
4261
+ // Test for common conventions.
4262
+ // NB: the observed behaviour is in combination with how author adds color! For example:
4263
+ // - we do not test NODE_DISABLE_COLORS, but util:styletext does
4264
+ // - we do test NO_COLOR, but Chalk does not
4265
+ //
4266
+ // References:
4267
+ // https://no-color.org
4268
+ // https://bixense.com/clicolors/
4269
+ // https://github.com/nodejs/node/blob/0a00217a5f67ef4a22384cfc80eb6dd9a917fdc1/lib/internal/tty.js#L109
4270
+ // https://github.com/chalk/supports-color/blob/c214314a14bcb174b12b3014b2b0a8de375029ae/index.js#L33
4271
+ // (https://force-color.org recent web page from 2023, does not match major javascript implementations)
4272
+
4273
+ if (
4274
+ process.env.NO_COLOR ||
4275
+ process.env.FORCE_COLOR === '0' ||
4276
+ process.env.FORCE_COLOR === 'false'
4277
+ )
4278
+ return false;
4279
+ if (process.env.FORCE_COLOR || process.env.CLICOLOR_FORCE !== undefined)
4280
+ return true;
4281
+ return undefined;
4282
+ }
4283
+
4284
+ command$1.Command = Command;
4285
+ command$1.useColor = useColor; // exporting for tests
4286
+ return command$1;
4287
+ }
4288
+
4289
+ var hasRequiredCommander;
4290
+
4291
+ function requireCommander () {
4292
+ if (hasRequiredCommander) return commander$1;
4293
+ hasRequiredCommander = 1;
4294
+ const { Argument } = requireArgument();
4295
+ const { Command } = requireCommand();
4296
+ const { CommanderError, InvalidArgumentError } = requireError();
4297
+ const { Help } = requireHelp();
4298
+ const { Option } = requireOption();
4299
+
4300
+ commander$1.program = new Command();
4301
+
4302
+ commander$1.createCommand = (name) => new Command(name);
4303
+ commander$1.createOption = (flags, description) => new Option(flags, description);
4304
+ commander$1.createArgument = (name, description) => new Argument(name, description);
4305
+
4306
+ /**
4307
+ * Expose classes
4308
+ */
4309
+
4310
+ commander$1.Command = Command;
4311
+ commander$1.Option = Option;
4312
+ commander$1.Argument = Argument;
4313
+ commander$1.Help = Help;
4314
+
4315
+ commander$1.CommanderError = CommanderError;
4316
+ commander$1.InvalidArgumentError = InvalidArgumentError;
4317
+ commander$1.InvalidOptionArgumentError = InvalidArgumentError; // Deprecated
4318
+ return commander$1;
4319
+ }
4320
+
4321
+ var commanderExports = requireCommander();
4322
+ var commander = /*@__PURE__*/getDefaultExportFromCjs(commanderExports);
4323
+
4324
+ // wrapper to provide named exports for ESM.
4325
+ const {
4326
+ program,
4327
+ createCommand,
4328
+ createArgument,
4329
+ createOption,
4330
+ CommanderError,
4331
+ InvalidArgumentError,
4332
+ InvalidOptionArgumentError, // deprecated old name
4333
+ Command,
4334
+ Argument,
4335
+ Option,
4336
+ Help,
4337
+ } = commander;
4338
+
4339
+ /* The main parse logic */
4340
+ function parse(content) {
4341
+ const source = content.trim();
4342
+ return `<p>${source}</p>`;
4343
+ }
4344
+
4345
+ // Import these from package.json in the future
4346
+ const name = 'md2html';
4347
+ const version = '0.1.2';
4348
+ const description = 'A simple tool to convert markdown content to html';
4349
+ /* Command-line tool logic */
4350
+ function command() {
4351
+ /* Set basic info */
4352
+ program
4353
+ .name(name)
4354
+ .version(version)
4355
+ .description(description);
4356
+ /* Config arguments info */
4357
+ program
4358
+ .option('-f, --file <path>', 'source file path')
4359
+ .argument('[input]', 'input content');
4360
+ /* Parse the cli options */
4361
+ program.parse(process.argv);
4362
+ /* Validation check */
4363
+ const options = program.opts();
4364
+ const input = program.args[0];
4365
+ const hasFile = typeof options.file === 'string';
4366
+ const hasInput = typeof input === 'string';
4367
+ // XOR validation
4368
+ if (hasFile === hasInput) {
4369
+ console.error('error: exactly one content source must be provided (either <input> or -f, --file).');
4370
+ process.exit(1);
4371
+ }
4372
+ /* Define one-source content */
4373
+ const content = hasFile
4374
+ ? (() => {
4375
+ try {
4376
+ return fs__namespace.readFileSync(options.file, 'utf-8');
4377
+ }
4378
+ catch {
4379
+ console.error(`error: failed to read file "${options.file}"`);
4380
+ process.exit(1);
4381
+ }
4382
+ })()
4383
+ : input;
4384
+ console.log(parse(content));
4385
+ }
4386
+ command();