ortoni-report 2.0.8 → 2.0.9

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