@bugbug-io/cli 14.3.2 → 14.4.1

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