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