@bayoudhi/moose-lib-serverless 0.7.6 → 0.7.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/moose-runner.js +3301 -1
  2. package/package.json +1 -1
@@ -260,6 +260,3306 @@ var require_workflow = __commonJS({
260
260
  }
261
261
  });
262
262
 
263
+ // ../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/error.js
264
+ var require_error = __commonJS({
265
+ "../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/error.js"(exports2) {
266
+ "use strict";
267
+ var CommanderError = class extends Error {
268
+ /**
269
+ * Constructs the CommanderError class
270
+ * @param {number} exitCode suggested exit code which could be used with process.exit
271
+ * @param {string} code an id string representing the error
272
+ * @param {string} message human-readable description of the error
273
+ */
274
+ constructor(exitCode, code, message) {
275
+ super(message);
276
+ Error.captureStackTrace(this, this.constructor);
277
+ this.name = this.constructor.name;
278
+ this.code = code;
279
+ this.exitCode = exitCode;
280
+ this.nestedError = void 0;
281
+ }
282
+ };
283
+ var InvalidArgumentError = class extends CommanderError {
284
+ /**
285
+ * Constructs the InvalidArgumentError class
286
+ * @param {string} [message] explanation of why argument is invalid
287
+ */
288
+ constructor(message) {
289
+ super(1, "commander.invalidArgument", message);
290
+ Error.captureStackTrace(this, this.constructor);
291
+ this.name = this.constructor.name;
292
+ }
293
+ };
294
+ exports2.CommanderError = CommanderError;
295
+ exports2.InvalidArgumentError = InvalidArgumentError;
296
+ }
297
+ });
298
+
299
+ // ../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/argument.js
300
+ var require_argument = __commonJS({
301
+ "../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/argument.js"(exports2) {
302
+ "use strict";
303
+ var { InvalidArgumentError } = require_error();
304
+ var Argument = class {
305
+ /**
306
+ * Initialize a new command argument with the given name and description.
307
+ * The default is that the argument is required, and you can explicitly
308
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
309
+ *
310
+ * @param {string} name
311
+ * @param {string} [description]
312
+ */
313
+ constructor(name, description) {
314
+ this.description = description || "";
315
+ this.variadic = false;
316
+ this.parseArg = void 0;
317
+ this.defaultValue = void 0;
318
+ this.defaultValueDescription = void 0;
319
+ this.argChoices = void 0;
320
+ switch (name[0]) {
321
+ case "<":
322
+ this.required = true;
323
+ this._name = name.slice(1, -1);
324
+ break;
325
+ case "[":
326
+ this.required = false;
327
+ this._name = name.slice(1, -1);
328
+ break;
329
+ default:
330
+ this.required = true;
331
+ this._name = name;
332
+ break;
333
+ }
334
+ if (this._name.length > 3 && this._name.slice(-3) === "...") {
335
+ this.variadic = true;
336
+ this._name = this._name.slice(0, -3);
337
+ }
338
+ }
339
+ /**
340
+ * Return argument name.
341
+ *
342
+ * @return {string}
343
+ */
344
+ name() {
345
+ return this._name;
346
+ }
347
+ /**
348
+ * @package
349
+ */
350
+ _concatValue(value, previous) {
351
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
352
+ return [value];
353
+ }
354
+ return previous.concat(value);
355
+ }
356
+ /**
357
+ * Set the default value, and optionally supply the description to be displayed in the help.
358
+ *
359
+ * @param {*} value
360
+ * @param {string} [description]
361
+ * @return {Argument}
362
+ */
363
+ default(value, description) {
364
+ this.defaultValue = value;
365
+ this.defaultValueDescription = description;
366
+ return this;
367
+ }
368
+ /**
369
+ * Set the custom handler for processing CLI command arguments into argument values.
370
+ *
371
+ * @param {Function} [fn]
372
+ * @return {Argument}
373
+ */
374
+ argParser(fn) {
375
+ this.parseArg = fn;
376
+ return this;
377
+ }
378
+ /**
379
+ * Only allow argument value to be one of choices.
380
+ *
381
+ * @param {string[]} values
382
+ * @return {Argument}
383
+ */
384
+ choices(values) {
385
+ this.argChoices = values.slice();
386
+ this.parseArg = (arg, previous) => {
387
+ if (!this.argChoices.includes(arg)) {
388
+ throw new InvalidArgumentError(
389
+ `Allowed choices are ${this.argChoices.join(", ")}.`
390
+ );
391
+ }
392
+ if (this.variadic) {
393
+ return this._concatValue(arg, previous);
394
+ }
395
+ return arg;
396
+ };
397
+ return this;
398
+ }
399
+ /**
400
+ * Make argument required.
401
+ *
402
+ * @returns {Argument}
403
+ */
404
+ argRequired() {
405
+ this.required = true;
406
+ return this;
407
+ }
408
+ /**
409
+ * Make argument optional.
410
+ *
411
+ * @returns {Argument}
412
+ */
413
+ argOptional() {
414
+ this.required = false;
415
+ return this;
416
+ }
417
+ };
418
+ function humanReadableArgName(arg) {
419
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
420
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
421
+ }
422
+ exports2.Argument = Argument;
423
+ exports2.humanReadableArgName = humanReadableArgName;
424
+ }
425
+ });
426
+
427
+ // ../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/help.js
428
+ var require_help = __commonJS({
429
+ "../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/help.js"(exports2) {
430
+ "use strict";
431
+ var { humanReadableArgName } = require_argument();
432
+ var Help = class {
433
+ constructor() {
434
+ this.helpWidth = void 0;
435
+ this.minWidthToWrap = 40;
436
+ this.sortSubcommands = false;
437
+ this.sortOptions = false;
438
+ this.showGlobalOptions = false;
439
+ }
440
+ /**
441
+ * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
442
+ * and just before calling `formatHelp()`.
443
+ *
444
+ * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
445
+ *
446
+ * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
447
+ */
448
+ prepareContext(contextOptions) {
449
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
450
+ }
451
+ /**
452
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
453
+ *
454
+ * @param {Command} cmd
455
+ * @returns {Command[]}
456
+ */
457
+ visibleCommands(cmd) {
458
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
459
+ const helpCommand = cmd._getHelpCommand();
460
+ if (helpCommand && !helpCommand._hidden) {
461
+ visibleCommands.push(helpCommand);
462
+ }
463
+ if (this.sortSubcommands) {
464
+ visibleCommands.sort((a, b) => {
465
+ return a.name().localeCompare(b.name());
466
+ });
467
+ }
468
+ return visibleCommands;
469
+ }
470
+ /**
471
+ * Compare options for sort.
472
+ *
473
+ * @param {Option} a
474
+ * @param {Option} b
475
+ * @returns {number}
476
+ */
477
+ compareOptions(a, b) {
478
+ const getSortKey = (option) => {
479
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
480
+ };
481
+ return getSortKey(a).localeCompare(getSortKey(b));
482
+ }
483
+ /**
484
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
485
+ *
486
+ * @param {Command} cmd
487
+ * @returns {Option[]}
488
+ */
489
+ visibleOptions(cmd) {
490
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
491
+ const helpOption = cmd._getHelpOption();
492
+ if (helpOption && !helpOption.hidden) {
493
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
494
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
495
+ if (!removeShort && !removeLong) {
496
+ visibleOptions.push(helpOption);
497
+ } else if (helpOption.long && !removeLong) {
498
+ visibleOptions.push(
499
+ cmd.createOption(helpOption.long, helpOption.description)
500
+ );
501
+ } else if (helpOption.short && !removeShort) {
502
+ visibleOptions.push(
503
+ cmd.createOption(helpOption.short, helpOption.description)
504
+ );
505
+ }
506
+ }
507
+ if (this.sortOptions) {
508
+ visibleOptions.sort(this.compareOptions);
509
+ }
510
+ return visibleOptions;
511
+ }
512
+ /**
513
+ * Get an array of the visible global options. (Not including help.)
514
+ *
515
+ * @param {Command} cmd
516
+ * @returns {Option[]}
517
+ */
518
+ visibleGlobalOptions(cmd) {
519
+ if (!this.showGlobalOptions) return [];
520
+ const globalOptions = [];
521
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
522
+ const visibleOptions = ancestorCmd.options.filter(
523
+ (option) => !option.hidden
524
+ );
525
+ globalOptions.push(...visibleOptions);
526
+ }
527
+ if (this.sortOptions) {
528
+ globalOptions.sort(this.compareOptions);
529
+ }
530
+ return globalOptions;
531
+ }
532
+ /**
533
+ * Get an array of the arguments if any have a description.
534
+ *
535
+ * @param {Command} cmd
536
+ * @returns {Argument[]}
537
+ */
538
+ visibleArguments(cmd) {
539
+ if (cmd._argsDescription) {
540
+ cmd.registeredArguments.forEach((argument) => {
541
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
542
+ });
543
+ }
544
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
545
+ return cmd.registeredArguments;
546
+ }
547
+ return [];
548
+ }
549
+ /**
550
+ * Get the command term to show in the list of subcommands.
551
+ *
552
+ * @param {Command} cmd
553
+ * @returns {string}
554
+ */
555
+ subcommandTerm(cmd) {
556
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
557
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
558
+ (args ? " " + args : "");
559
+ }
560
+ /**
561
+ * Get the option term to show in the list of options.
562
+ *
563
+ * @param {Option} option
564
+ * @returns {string}
565
+ */
566
+ optionTerm(option) {
567
+ return option.flags;
568
+ }
569
+ /**
570
+ * Get the argument term to show in the list of arguments.
571
+ *
572
+ * @param {Argument} argument
573
+ * @returns {string}
574
+ */
575
+ argumentTerm(argument) {
576
+ return argument.name();
577
+ }
578
+ /**
579
+ * Get the longest command term length.
580
+ *
581
+ * @param {Command} cmd
582
+ * @param {Help} helper
583
+ * @returns {number}
584
+ */
585
+ longestSubcommandTermLength(cmd, helper) {
586
+ return helper.visibleCommands(cmd).reduce((max, command) => {
587
+ return Math.max(
588
+ max,
589
+ this.displayWidth(
590
+ helper.styleSubcommandTerm(helper.subcommandTerm(command))
591
+ )
592
+ );
593
+ }, 0);
594
+ }
595
+ /**
596
+ * Get the longest option term length.
597
+ *
598
+ * @param {Command} cmd
599
+ * @param {Help} helper
600
+ * @returns {number}
601
+ */
602
+ longestOptionTermLength(cmd, helper) {
603
+ return helper.visibleOptions(cmd).reduce((max, option) => {
604
+ return Math.max(
605
+ max,
606
+ this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
607
+ );
608
+ }, 0);
609
+ }
610
+ /**
611
+ * Get the longest global option term length.
612
+ *
613
+ * @param {Command} cmd
614
+ * @param {Help} helper
615
+ * @returns {number}
616
+ */
617
+ longestGlobalOptionTermLength(cmd, helper) {
618
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
619
+ return Math.max(
620
+ max,
621
+ this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
622
+ );
623
+ }, 0);
624
+ }
625
+ /**
626
+ * Get the longest argument term length.
627
+ *
628
+ * @param {Command} cmd
629
+ * @param {Help} helper
630
+ * @returns {number}
631
+ */
632
+ longestArgumentTermLength(cmd, helper) {
633
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
634
+ return Math.max(
635
+ max,
636
+ this.displayWidth(
637
+ helper.styleArgumentTerm(helper.argumentTerm(argument))
638
+ )
639
+ );
640
+ }, 0);
641
+ }
642
+ /**
643
+ * Get the command usage to be displayed at the top of the built-in help.
644
+ *
645
+ * @param {Command} cmd
646
+ * @returns {string}
647
+ */
648
+ commandUsage(cmd) {
649
+ let cmdName = cmd._name;
650
+ if (cmd._aliases[0]) {
651
+ cmdName = cmdName + "|" + cmd._aliases[0];
652
+ }
653
+ let ancestorCmdNames = "";
654
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
655
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
656
+ }
657
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
658
+ }
659
+ /**
660
+ * Get the description for the command.
661
+ *
662
+ * @param {Command} cmd
663
+ * @returns {string}
664
+ */
665
+ commandDescription(cmd) {
666
+ return cmd.description();
667
+ }
668
+ /**
669
+ * Get the subcommand summary to show in the list of subcommands.
670
+ * (Fallback to description for backwards compatibility.)
671
+ *
672
+ * @param {Command} cmd
673
+ * @returns {string}
674
+ */
675
+ subcommandDescription(cmd) {
676
+ return cmd.summary() || cmd.description();
677
+ }
678
+ /**
679
+ * Get the option description to show in the list of options.
680
+ *
681
+ * @param {Option} option
682
+ * @return {string}
683
+ */
684
+ optionDescription(option) {
685
+ const extraInfo = [];
686
+ if (option.argChoices) {
687
+ extraInfo.push(
688
+ // use stringify to match the display of the default value
689
+ `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
690
+ );
691
+ }
692
+ if (option.defaultValue !== void 0) {
693
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
694
+ if (showDefault) {
695
+ extraInfo.push(
696
+ `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`
697
+ );
698
+ }
699
+ }
700
+ if (option.presetArg !== void 0 && option.optional) {
701
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
702
+ }
703
+ if (option.envVar !== void 0) {
704
+ extraInfo.push(`env: ${option.envVar}`);
705
+ }
706
+ if (extraInfo.length > 0) {
707
+ return `${option.description} (${extraInfo.join(", ")})`;
708
+ }
709
+ return option.description;
710
+ }
711
+ /**
712
+ * Get the argument description to show in the list of arguments.
713
+ *
714
+ * @param {Argument} argument
715
+ * @return {string}
716
+ */
717
+ argumentDescription(argument) {
718
+ const extraInfo = [];
719
+ if (argument.argChoices) {
720
+ extraInfo.push(
721
+ // use stringify to match the display of the default value
722
+ `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
723
+ );
724
+ }
725
+ if (argument.defaultValue !== void 0) {
726
+ extraInfo.push(
727
+ `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`
728
+ );
729
+ }
730
+ if (extraInfo.length > 0) {
731
+ const extraDescription = `(${extraInfo.join(", ")})`;
732
+ if (argument.description) {
733
+ return `${argument.description} ${extraDescription}`;
734
+ }
735
+ return extraDescription;
736
+ }
737
+ return argument.description;
738
+ }
739
+ /**
740
+ * Generate the built-in help text.
741
+ *
742
+ * @param {Command} cmd
743
+ * @param {Help} helper
744
+ * @returns {string}
745
+ */
746
+ formatHelp(cmd, helper) {
747
+ const termWidth = helper.padWidth(cmd, helper);
748
+ const helpWidth = helper.helpWidth ?? 80;
749
+ function callFormatItem(term, description) {
750
+ return helper.formatItem(term, termWidth, description, helper);
751
+ }
752
+ let output = [
753
+ `${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
754
+ ""
755
+ ];
756
+ const commandDescription = helper.commandDescription(cmd);
757
+ if (commandDescription.length > 0) {
758
+ output = output.concat([
759
+ helper.boxWrap(
760
+ helper.styleCommandDescription(commandDescription),
761
+ helpWidth
762
+ ),
763
+ ""
764
+ ]);
765
+ }
766
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
767
+ return callFormatItem(
768
+ helper.styleArgumentTerm(helper.argumentTerm(argument)),
769
+ helper.styleArgumentDescription(helper.argumentDescription(argument))
770
+ );
771
+ });
772
+ if (argumentList.length > 0) {
773
+ output = output.concat([
774
+ helper.styleTitle("Arguments:"),
775
+ ...argumentList,
776
+ ""
777
+ ]);
778
+ }
779
+ const optionList = helper.visibleOptions(cmd).map((option) => {
780
+ return callFormatItem(
781
+ helper.styleOptionTerm(helper.optionTerm(option)),
782
+ helper.styleOptionDescription(helper.optionDescription(option))
783
+ );
784
+ });
785
+ if (optionList.length > 0) {
786
+ output = output.concat([
787
+ helper.styleTitle("Options:"),
788
+ ...optionList,
789
+ ""
790
+ ]);
791
+ }
792
+ if (helper.showGlobalOptions) {
793
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
794
+ return callFormatItem(
795
+ helper.styleOptionTerm(helper.optionTerm(option)),
796
+ helper.styleOptionDescription(helper.optionDescription(option))
797
+ );
798
+ });
799
+ if (globalOptionList.length > 0) {
800
+ output = output.concat([
801
+ helper.styleTitle("Global Options:"),
802
+ ...globalOptionList,
803
+ ""
804
+ ]);
805
+ }
806
+ }
807
+ const commandList = helper.visibleCommands(cmd).map((cmd2) => {
808
+ return callFormatItem(
809
+ helper.styleSubcommandTerm(helper.subcommandTerm(cmd2)),
810
+ helper.styleSubcommandDescription(helper.subcommandDescription(cmd2))
811
+ );
812
+ });
813
+ if (commandList.length > 0) {
814
+ output = output.concat([
815
+ helper.styleTitle("Commands:"),
816
+ ...commandList,
817
+ ""
818
+ ]);
819
+ }
820
+ return output.join("\n");
821
+ }
822
+ /**
823
+ * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
824
+ *
825
+ * @param {string} str
826
+ * @returns {number}
827
+ */
828
+ displayWidth(str) {
829
+ return stripColor(str).length;
830
+ }
831
+ /**
832
+ * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
833
+ *
834
+ * @param {string} str
835
+ * @returns {string}
836
+ */
837
+ styleTitle(str) {
838
+ return str;
839
+ }
840
+ styleUsage(str) {
841
+ return str.split(" ").map((word) => {
842
+ if (word === "[options]") return this.styleOptionText(word);
843
+ if (word === "[command]") return this.styleSubcommandText(word);
844
+ if (word[0] === "[" || word[0] === "<")
845
+ return this.styleArgumentText(word);
846
+ return this.styleCommandText(word);
847
+ }).join(" ");
848
+ }
849
+ styleCommandDescription(str) {
850
+ return this.styleDescriptionText(str);
851
+ }
852
+ styleOptionDescription(str) {
853
+ return this.styleDescriptionText(str);
854
+ }
855
+ styleSubcommandDescription(str) {
856
+ return this.styleDescriptionText(str);
857
+ }
858
+ styleArgumentDescription(str) {
859
+ return this.styleDescriptionText(str);
860
+ }
861
+ styleDescriptionText(str) {
862
+ return str;
863
+ }
864
+ styleOptionTerm(str) {
865
+ return this.styleOptionText(str);
866
+ }
867
+ styleSubcommandTerm(str) {
868
+ return str.split(" ").map((word) => {
869
+ if (word === "[options]") return this.styleOptionText(word);
870
+ if (word[0] === "[" || word[0] === "<")
871
+ return this.styleArgumentText(word);
872
+ return this.styleSubcommandText(word);
873
+ }).join(" ");
874
+ }
875
+ styleArgumentTerm(str) {
876
+ return this.styleArgumentText(str);
877
+ }
878
+ styleOptionText(str) {
879
+ return str;
880
+ }
881
+ styleArgumentText(str) {
882
+ return str;
883
+ }
884
+ styleSubcommandText(str) {
885
+ return str;
886
+ }
887
+ styleCommandText(str) {
888
+ return str;
889
+ }
890
+ /**
891
+ * Calculate the pad width from the maximum term length.
892
+ *
893
+ * @param {Command} cmd
894
+ * @param {Help} helper
895
+ * @returns {number}
896
+ */
897
+ padWidth(cmd, helper) {
898
+ return Math.max(
899
+ helper.longestOptionTermLength(cmd, helper),
900
+ helper.longestGlobalOptionTermLength(cmd, helper),
901
+ helper.longestSubcommandTermLength(cmd, helper),
902
+ helper.longestArgumentTermLength(cmd, helper)
903
+ );
904
+ }
905
+ /**
906
+ * Detect manually wrapped and indented strings by checking for line break followed by whitespace.
907
+ *
908
+ * @param {string} str
909
+ * @returns {boolean}
910
+ */
911
+ preformatted(str) {
912
+ return /\n[^\S\r\n]/.test(str);
913
+ }
914
+ /**
915
+ * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
916
+ *
917
+ * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
918
+ * TTT DDD DDDD
919
+ * DD DDD
920
+ *
921
+ * @param {string} term
922
+ * @param {number} termWidth
923
+ * @param {string} description
924
+ * @param {Help} helper
925
+ * @returns {string}
926
+ */
927
+ formatItem(term, termWidth, description, helper) {
928
+ const itemIndent = 2;
929
+ const itemIndentStr = " ".repeat(itemIndent);
930
+ if (!description) return itemIndentStr + term;
931
+ const paddedTerm = term.padEnd(
932
+ termWidth + term.length - helper.displayWidth(term)
933
+ );
934
+ const spacerWidth = 2;
935
+ const helpWidth = this.helpWidth ?? 80;
936
+ const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
937
+ let formattedDescription;
938
+ if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
939
+ formattedDescription = description;
940
+ } else {
941
+ const wrappedDescription = helper.boxWrap(description, remainingWidth);
942
+ formattedDescription = wrappedDescription.replace(
943
+ /\n/g,
944
+ "\n" + " ".repeat(termWidth + spacerWidth)
945
+ );
946
+ }
947
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
948
+ ${itemIndentStr}`);
949
+ }
950
+ /**
951
+ * Wrap a string at whitespace, preserving existing line breaks.
952
+ * Wrapping is skipped if the width is less than `minWidthToWrap`.
953
+ *
954
+ * @param {string} str
955
+ * @param {number} width
956
+ * @returns {string}
957
+ */
958
+ boxWrap(str, width) {
959
+ if (width < this.minWidthToWrap) return str;
960
+ const rawLines = str.split(/\r\n|\n/);
961
+ const chunkPattern = /[\s]*[^\s]+/g;
962
+ const wrappedLines = [];
963
+ rawLines.forEach((line) => {
964
+ const chunks = line.match(chunkPattern);
965
+ if (chunks === null) {
966
+ wrappedLines.push("");
967
+ return;
968
+ }
969
+ let sumChunks = [chunks.shift()];
970
+ let sumWidth = this.displayWidth(sumChunks[0]);
971
+ chunks.forEach((chunk) => {
972
+ const visibleWidth = this.displayWidth(chunk);
973
+ if (sumWidth + visibleWidth <= width) {
974
+ sumChunks.push(chunk);
975
+ sumWidth += visibleWidth;
976
+ return;
977
+ }
978
+ wrappedLines.push(sumChunks.join(""));
979
+ const nextChunk = chunk.trimStart();
980
+ sumChunks = [nextChunk];
981
+ sumWidth = this.displayWidth(nextChunk);
982
+ });
983
+ wrappedLines.push(sumChunks.join(""));
984
+ });
985
+ return wrappedLines.join("\n");
986
+ }
987
+ };
988
+ function stripColor(str) {
989
+ const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
990
+ return str.replace(sgrPattern, "");
991
+ }
992
+ exports2.Help = Help;
993
+ exports2.stripColor = stripColor;
994
+ }
995
+ });
996
+
997
+ // ../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/option.js
998
+ var require_option = __commonJS({
999
+ "../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/option.js"(exports2) {
1000
+ "use strict";
1001
+ var { InvalidArgumentError } = require_error();
1002
+ var Option = class {
1003
+ /**
1004
+ * Initialize a new `Option` with the given `flags` and `description`.
1005
+ *
1006
+ * @param {string} flags
1007
+ * @param {string} [description]
1008
+ */
1009
+ constructor(flags, description) {
1010
+ this.flags = flags;
1011
+ this.description = description || "";
1012
+ this.required = flags.includes("<");
1013
+ this.optional = flags.includes("[");
1014
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
1015
+ this.mandatory = false;
1016
+ const optionFlags = splitOptionFlags(flags);
1017
+ this.short = optionFlags.shortFlag;
1018
+ this.long = optionFlags.longFlag;
1019
+ this.negate = false;
1020
+ if (this.long) {
1021
+ this.negate = this.long.startsWith("--no-");
1022
+ }
1023
+ this.defaultValue = void 0;
1024
+ this.defaultValueDescription = void 0;
1025
+ this.presetArg = void 0;
1026
+ this.envVar = void 0;
1027
+ this.parseArg = void 0;
1028
+ this.hidden = false;
1029
+ this.argChoices = void 0;
1030
+ this.conflictsWith = [];
1031
+ this.implied = void 0;
1032
+ }
1033
+ /**
1034
+ * Set the default value, and optionally supply the description to be displayed in the help.
1035
+ *
1036
+ * @param {*} value
1037
+ * @param {string} [description]
1038
+ * @return {Option}
1039
+ */
1040
+ default(value, description) {
1041
+ this.defaultValue = value;
1042
+ this.defaultValueDescription = description;
1043
+ return this;
1044
+ }
1045
+ /**
1046
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
1047
+ * The custom processing (parseArg) is called.
1048
+ *
1049
+ * @example
1050
+ * new Option('--color').default('GREYSCALE').preset('RGB');
1051
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
1052
+ *
1053
+ * @param {*} arg
1054
+ * @return {Option}
1055
+ */
1056
+ preset(arg) {
1057
+ this.presetArg = arg;
1058
+ return this;
1059
+ }
1060
+ /**
1061
+ * Add option name(s) that conflict with this option.
1062
+ * An error will be displayed if conflicting options are found during parsing.
1063
+ *
1064
+ * @example
1065
+ * new Option('--rgb').conflicts('cmyk');
1066
+ * new Option('--js').conflicts(['ts', 'jsx']);
1067
+ *
1068
+ * @param {(string | string[])} names
1069
+ * @return {Option}
1070
+ */
1071
+ conflicts(names) {
1072
+ this.conflictsWith = this.conflictsWith.concat(names);
1073
+ return this;
1074
+ }
1075
+ /**
1076
+ * Specify implied option values for when this option is set and the implied options are not.
1077
+ *
1078
+ * The custom processing (parseArg) is not called on the implied values.
1079
+ *
1080
+ * @example
1081
+ * program
1082
+ * .addOption(new Option('--log', 'write logging information to file'))
1083
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
1084
+ *
1085
+ * @param {object} impliedOptionValues
1086
+ * @return {Option}
1087
+ */
1088
+ implies(impliedOptionValues) {
1089
+ let newImplied = impliedOptionValues;
1090
+ if (typeof impliedOptionValues === "string") {
1091
+ newImplied = { [impliedOptionValues]: true };
1092
+ }
1093
+ this.implied = Object.assign(this.implied || {}, newImplied);
1094
+ return this;
1095
+ }
1096
+ /**
1097
+ * Set environment variable to check for option value.
1098
+ *
1099
+ * An environment variable is only used if when processed the current option value is
1100
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
1101
+ *
1102
+ * @param {string} name
1103
+ * @return {Option}
1104
+ */
1105
+ env(name) {
1106
+ this.envVar = name;
1107
+ return this;
1108
+ }
1109
+ /**
1110
+ * Set the custom handler for processing CLI option arguments into option values.
1111
+ *
1112
+ * @param {Function} [fn]
1113
+ * @return {Option}
1114
+ */
1115
+ argParser(fn) {
1116
+ this.parseArg = fn;
1117
+ return this;
1118
+ }
1119
+ /**
1120
+ * Whether the option is mandatory and must have a value after parsing.
1121
+ *
1122
+ * @param {boolean} [mandatory=true]
1123
+ * @return {Option}
1124
+ */
1125
+ makeOptionMandatory(mandatory = true) {
1126
+ this.mandatory = !!mandatory;
1127
+ return this;
1128
+ }
1129
+ /**
1130
+ * Hide option in help.
1131
+ *
1132
+ * @param {boolean} [hide=true]
1133
+ * @return {Option}
1134
+ */
1135
+ hideHelp(hide = true) {
1136
+ this.hidden = !!hide;
1137
+ return this;
1138
+ }
1139
+ /**
1140
+ * @package
1141
+ */
1142
+ _concatValue(value, previous) {
1143
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
1144
+ return [value];
1145
+ }
1146
+ return previous.concat(value);
1147
+ }
1148
+ /**
1149
+ * Only allow option value to be one of choices.
1150
+ *
1151
+ * @param {string[]} values
1152
+ * @return {Option}
1153
+ */
1154
+ choices(values) {
1155
+ this.argChoices = values.slice();
1156
+ this.parseArg = (arg, previous) => {
1157
+ if (!this.argChoices.includes(arg)) {
1158
+ throw new InvalidArgumentError(
1159
+ `Allowed choices are ${this.argChoices.join(", ")}.`
1160
+ );
1161
+ }
1162
+ if (this.variadic) {
1163
+ return this._concatValue(arg, previous);
1164
+ }
1165
+ return arg;
1166
+ };
1167
+ return this;
1168
+ }
1169
+ /**
1170
+ * Return option name.
1171
+ *
1172
+ * @return {string}
1173
+ */
1174
+ name() {
1175
+ if (this.long) {
1176
+ return this.long.replace(/^--/, "");
1177
+ }
1178
+ return this.short.replace(/^-/, "");
1179
+ }
1180
+ /**
1181
+ * Return option name, in a camelcase format that can be used
1182
+ * as an object attribute key.
1183
+ *
1184
+ * @return {string}
1185
+ */
1186
+ attributeName() {
1187
+ if (this.negate) {
1188
+ return camelcase(this.name().replace(/^no-/, ""));
1189
+ }
1190
+ return camelcase(this.name());
1191
+ }
1192
+ /**
1193
+ * Check if `arg` matches the short or long flag.
1194
+ *
1195
+ * @param {string} arg
1196
+ * @return {boolean}
1197
+ * @package
1198
+ */
1199
+ is(arg) {
1200
+ return this.short === arg || this.long === arg;
1201
+ }
1202
+ /**
1203
+ * Return whether a boolean option.
1204
+ *
1205
+ * Options are one of boolean, negated, required argument, or optional argument.
1206
+ *
1207
+ * @return {boolean}
1208
+ * @package
1209
+ */
1210
+ isBoolean() {
1211
+ return !this.required && !this.optional && !this.negate;
1212
+ }
1213
+ };
1214
+ var DualOptions = class {
1215
+ /**
1216
+ * @param {Option[]} options
1217
+ */
1218
+ constructor(options) {
1219
+ this.positiveOptions = /* @__PURE__ */ new Map();
1220
+ this.negativeOptions = /* @__PURE__ */ new Map();
1221
+ this.dualOptions = /* @__PURE__ */ new Set();
1222
+ options.forEach((option) => {
1223
+ if (option.negate) {
1224
+ this.negativeOptions.set(option.attributeName(), option);
1225
+ } else {
1226
+ this.positiveOptions.set(option.attributeName(), option);
1227
+ }
1228
+ });
1229
+ this.negativeOptions.forEach((value, key) => {
1230
+ if (this.positiveOptions.has(key)) {
1231
+ this.dualOptions.add(key);
1232
+ }
1233
+ });
1234
+ }
1235
+ /**
1236
+ * Did the value come from the option, and not from possible matching dual option?
1237
+ *
1238
+ * @param {*} value
1239
+ * @param {Option} option
1240
+ * @returns {boolean}
1241
+ */
1242
+ valueFromOption(value, option) {
1243
+ const optionKey = option.attributeName();
1244
+ if (!this.dualOptions.has(optionKey)) return true;
1245
+ const preset = this.negativeOptions.get(optionKey).presetArg;
1246
+ const negativeValue = preset !== void 0 ? preset : false;
1247
+ return option.negate === (negativeValue === value);
1248
+ }
1249
+ };
1250
+ function camelcase(str) {
1251
+ return str.split("-").reduce((str2, word) => {
1252
+ return str2 + word[0].toUpperCase() + word.slice(1);
1253
+ });
1254
+ }
1255
+ function splitOptionFlags(flags) {
1256
+ let shortFlag;
1257
+ let longFlag;
1258
+ const shortFlagExp = /^-[^-]$/;
1259
+ const longFlagExp = /^--[^-]/;
1260
+ const flagParts = flags.split(/[ |,]+/).concat("guard");
1261
+ if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
1262
+ if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
1263
+ if (!shortFlag && shortFlagExp.test(flagParts[0]))
1264
+ shortFlag = flagParts.shift();
1265
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
1266
+ shortFlag = longFlag;
1267
+ longFlag = flagParts.shift();
1268
+ }
1269
+ if (flagParts[0].startsWith("-")) {
1270
+ const unsupportedFlag = flagParts[0];
1271
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
1272
+ if (/^-[^-][^-]/.test(unsupportedFlag))
1273
+ throw new Error(
1274
+ `${baseError}
1275
+ - a short flag is a single dash and a single character
1276
+ - either use a single dash and a single character (for a short flag)
1277
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`
1278
+ );
1279
+ if (shortFlagExp.test(unsupportedFlag))
1280
+ throw new Error(`${baseError}
1281
+ - too many short flags`);
1282
+ if (longFlagExp.test(unsupportedFlag))
1283
+ throw new Error(`${baseError}
1284
+ - too many long flags`);
1285
+ throw new Error(`${baseError}
1286
+ - unrecognised flag format`);
1287
+ }
1288
+ if (shortFlag === void 0 && longFlag === void 0)
1289
+ throw new Error(
1290
+ `option creation failed due to no flags found in '${flags}'.`
1291
+ );
1292
+ return { shortFlag, longFlag };
1293
+ }
1294
+ exports2.Option = Option;
1295
+ exports2.DualOptions = DualOptions;
1296
+ }
1297
+ });
1298
+
1299
+ // ../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/suggestSimilar.js
1300
+ var require_suggestSimilar = __commonJS({
1301
+ "../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/suggestSimilar.js"(exports2) {
1302
+ "use strict";
1303
+ var maxDistance = 3;
1304
+ function editDistance(a, b) {
1305
+ if (Math.abs(a.length - b.length) > maxDistance)
1306
+ return Math.max(a.length, b.length);
1307
+ const d = [];
1308
+ for (let i = 0; i <= a.length; i++) {
1309
+ d[i] = [i];
1310
+ }
1311
+ for (let j = 0; j <= b.length; j++) {
1312
+ d[0][j] = j;
1313
+ }
1314
+ for (let j = 1; j <= b.length; j++) {
1315
+ for (let i = 1; i <= a.length; i++) {
1316
+ let cost = 1;
1317
+ if (a[i - 1] === b[j - 1]) {
1318
+ cost = 0;
1319
+ } else {
1320
+ cost = 1;
1321
+ }
1322
+ d[i][j] = Math.min(
1323
+ d[i - 1][j] + 1,
1324
+ // deletion
1325
+ d[i][j - 1] + 1,
1326
+ // insertion
1327
+ d[i - 1][j - 1] + cost
1328
+ // substitution
1329
+ );
1330
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
1331
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
1332
+ }
1333
+ }
1334
+ }
1335
+ return d[a.length][b.length];
1336
+ }
1337
+ function suggestSimilar(word, candidates) {
1338
+ if (!candidates || candidates.length === 0) return "";
1339
+ candidates = Array.from(new Set(candidates));
1340
+ const searchingOptions = word.startsWith("--");
1341
+ if (searchingOptions) {
1342
+ word = word.slice(2);
1343
+ candidates = candidates.map((candidate) => candidate.slice(2));
1344
+ }
1345
+ let similar = [];
1346
+ let bestDistance = maxDistance;
1347
+ const minSimilarity = 0.4;
1348
+ candidates.forEach((candidate) => {
1349
+ if (candidate.length <= 1) return;
1350
+ const distance = editDistance(word, candidate);
1351
+ const length = Math.max(word.length, candidate.length);
1352
+ const similarity = (length - distance) / length;
1353
+ if (similarity > minSimilarity) {
1354
+ if (distance < bestDistance) {
1355
+ bestDistance = distance;
1356
+ similar = [candidate];
1357
+ } else if (distance === bestDistance) {
1358
+ similar.push(candidate);
1359
+ }
1360
+ }
1361
+ });
1362
+ similar.sort((a, b) => a.localeCompare(b));
1363
+ if (searchingOptions) {
1364
+ similar = similar.map((candidate) => `--${candidate}`);
1365
+ }
1366
+ if (similar.length > 1) {
1367
+ return `
1368
+ (Did you mean one of ${similar.join(", ")}?)`;
1369
+ }
1370
+ if (similar.length === 1) {
1371
+ return `
1372
+ (Did you mean ${similar[0]}?)`;
1373
+ }
1374
+ return "";
1375
+ }
1376
+ exports2.suggestSimilar = suggestSimilar;
1377
+ }
1378
+ });
1379
+
1380
+ // ../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/command.js
1381
+ var require_command = __commonJS({
1382
+ "../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/command.js"(exports2) {
1383
+ "use strict";
1384
+ var EventEmitter = require("events").EventEmitter;
1385
+ var childProcess = require("child_process");
1386
+ var path = require("path");
1387
+ var fs4 = require("fs");
1388
+ var process2 = require("process");
1389
+ var { Argument, humanReadableArgName } = require_argument();
1390
+ var { CommanderError } = require_error();
1391
+ var { Help, stripColor } = require_help();
1392
+ var { Option, DualOptions } = require_option();
1393
+ var { suggestSimilar } = require_suggestSimilar();
1394
+ var Command = class _Command extends EventEmitter {
1395
+ /**
1396
+ * Initialize a new `Command`.
1397
+ *
1398
+ * @param {string} [name]
1399
+ */
1400
+ constructor(name) {
1401
+ super();
1402
+ this.commands = [];
1403
+ this.options = [];
1404
+ this.parent = null;
1405
+ this._allowUnknownOption = false;
1406
+ this._allowExcessArguments = false;
1407
+ this.registeredArguments = [];
1408
+ this._args = this.registeredArguments;
1409
+ this.args = [];
1410
+ this.rawArgs = [];
1411
+ this.processedArgs = [];
1412
+ this._scriptPath = null;
1413
+ this._name = name || "";
1414
+ this._optionValues = {};
1415
+ this._optionValueSources = {};
1416
+ this._storeOptionsAsProperties = false;
1417
+ this._actionHandler = null;
1418
+ this._executableHandler = false;
1419
+ this._executableFile = null;
1420
+ this._executableDir = null;
1421
+ this._defaultCommandName = null;
1422
+ this._exitCallback = null;
1423
+ this._aliases = [];
1424
+ this._combineFlagAndOptionalValue = true;
1425
+ this._description = "";
1426
+ this._summary = "";
1427
+ this._argsDescription = void 0;
1428
+ this._enablePositionalOptions = false;
1429
+ this._passThroughOptions = false;
1430
+ this._lifeCycleHooks = {};
1431
+ this._showHelpAfterError = false;
1432
+ this._showSuggestionAfterError = true;
1433
+ this._savedState = null;
1434
+ this._outputConfiguration = {
1435
+ writeOut: (str) => process2.stdout.write(str),
1436
+ writeErr: (str) => process2.stderr.write(str),
1437
+ outputError: (str, write) => write(str),
1438
+ getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : void 0,
1439
+ getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : void 0,
1440
+ getOutHasColors: () => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()),
1441
+ getErrHasColors: () => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()),
1442
+ stripColor: (str) => stripColor(str)
1443
+ };
1444
+ this._hidden = false;
1445
+ this._helpOption = void 0;
1446
+ this._addImplicitHelpCommand = void 0;
1447
+ this._helpCommand = void 0;
1448
+ this._helpConfiguration = {};
1449
+ }
1450
+ /**
1451
+ * Copy settings that are useful to have in common across root command and subcommands.
1452
+ *
1453
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1454
+ *
1455
+ * @param {Command} sourceCommand
1456
+ * @return {Command} `this` command for chaining
1457
+ */
1458
+ copyInheritedSettings(sourceCommand) {
1459
+ this._outputConfiguration = sourceCommand._outputConfiguration;
1460
+ this._helpOption = sourceCommand._helpOption;
1461
+ this._helpCommand = sourceCommand._helpCommand;
1462
+ this._helpConfiguration = sourceCommand._helpConfiguration;
1463
+ this._exitCallback = sourceCommand._exitCallback;
1464
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1465
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1466
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
1467
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1468
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
1469
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1470
+ return this;
1471
+ }
1472
+ /**
1473
+ * @returns {Command[]}
1474
+ * @private
1475
+ */
1476
+ _getCommandAndAncestors() {
1477
+ const result = [];
1478
+ for (let command = this; command; command = command.parent) {
1479
+ result.push(command);
1480
+ }
1481
+ return result;
1482
+ }
1483
+ /**
1484
+ * Define a command.
1485
+ *
1486
+ * There are two styles of command: pay attention to where to put the description.
1487
+ *
1488
+ * @example
1489
+ * // Command implemented using action handler (description is supplied separately to `.command`)
1490
+ * program
1491
+ * .command('clone <source> [destination]')
1492
+ * .description('clone a repository into a newly created directory')
1493
+ * .action((source, destination) => {
1494
+ * console.log('clone command called');
1495
+ * });
1496
+ *
1497
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
1498
+ * program
1499
+ * .command('start <service>', 'start named service')
1500
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
1501
+ *
1502
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1503
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1504
+ * @param {object} [execOpts] - configuration options (for executable)
1505
+ * @return {Command} returns new command for action handler, or `this` for executable command
1506
+ */
1507
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1508
+ let desc = actionOptsOrExecDesc;
1509
+ let opts = execOpts;
1510
+ if (typeof desc === "object" && desc !== null) {
1511
+ opts = desc;
1512
+ desc = null;
1513
+ }
1514
+ opts = opts || {};
1515
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1516
+ const cmd = this.createCommand(name);
1517
+ if (desc) {
1518
+ cmd.description(desc);
1519
+ cmd._executableHandler = true;
1520
+ }
1521
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1522
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
1523
+ cmd._executableFile = opts.executableFile || null;
1524
+ if (args) cmd.arguments(args);
1525
+ this._registerCommand(cmd);
1526
+ cmd.parent = this;
1527
+ cmd.copyInheritedSettings(this);
1528
+ if (desc) return this;
1529
+ return cmd;
1530
+ }
1531
+ /**
1532
+ * Factory routine to create a new unattached command.
1533
+ *
1534
+ * See .command() for creating an attached subcommand, which uses this routine to
1535
+ * create the command. You can override createCommand to customise subcommands.
1536
+ *
1537
+ * @param {string} [name]
1538
+ * @return {Command} new command
1539
+ */
1540
+ createCommand(name) {
1541
+ return new _Command(name);
1542
+ }
1543
+ /**
1544
+ * You can customise the help with a subclass of Help by overriding createHelp,
1545
+ * or by overriding Help properties using configureHelp().
1546
+ *
1547
+ * @return {Help}
1548
+ */
1549
+ createHelp() {
1550
+ return Object.assign(new Help(), this.configureHelp());
1551
+ }
1552
+ /**
1553
+ * You can customise the help by overriding Help properties using configureHelp(),
1554
+ * or with a subclass of Help by overriding createHelp().
1555
+ *
1556
+ * @param {object} [configuration] - configuration options
1557
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1558
+ */
1559
+ configureHelp(configuration) {
1560
+ if (configuration === void 0) return this._helpConfiguration;
1561
+ this._helpConfiguration = configuration;
1562
+ return this;
1563
+ }
1564
+ /**
1565
+ * The default output goes to stdout and stderr. You can customise this for special
1566
+ * applications. You can also customise the display of errors by overriding outputError.
1567
+ *
1568
+ * The configuration properties are all functions:
1569
+ *
1570
+ * // change how output being written, defaults to stdout and stderr
1571
+ * writeOut(str)
1572
+ * writeErr(str)
1573
+ * // change how output being written for errors, defaults to writeErr
1574
+ * outputError(str, write) // used for displaying errors and not used for displaying help
1575
+ * // specify width for wrapping help
1576
+ * getOutHelpWidth()
1577
+ * getErrHelpWidth()
1578
+ * // color support, currently only used with Help
1579
+ * getOutHasColors()
1580
+ * getErrHasColors()
1581
+ * stripColor() // used to remove ANSI escape codes if output does not have colors
1582
+ *
1583
+ * @param {object} [configuration] - configuration options
1584
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1585
+ */
1586
+ configureOutput(configuration) {
1587
+ if (configuration === void 0) return this._outputConfiguration;
1588
+ Object.assign(this._outputConfiguration, configuration);
1589
+ return this;
1590
+ }
1591
+ /**
1592
+ * Display the help or a custom message after an error occurs.
1593
+ *
1594
+ * @param {(boolean|string)} [displayHelp]
1595
+ * @return {Command} `this` command for chaining
1596
+ */
1597
+ showHelpAfterError(displayHelp = true) {
1598
+ if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
1599
+ this._showHelpAfterError = displayHelp;
1600
+ return this;
1601
+ }
1602
+ /**
1603
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
1604
+ *
1605
+ * @param {boolean} [displaySuggestion]
1606
+ * @return {Command} `this` command for chaining
1607
+ */
1608
+ showSuggestionAfterError(displaySuggestion = true) {
1609
+ this._showSuggestionAfterError = !!displaySuggestion;
1610
+ return this;
1611
+ }
1612
+ /**
1613
+ * Add a prepared subcommand.
1614
+ *
1615
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
1616
+ *
1617
+ * @param {Command} cmd - new subcommand
1618
+ * @param {object} [opts] - configuration options
1619
+ * @return {Command} `this` command for chaining
1620
+ */
1621
+ addCommand(cmd, opts) {
1622
+ if (!cmd._name) {
1623
+ throw new Error(`Command passed to .addCommand() must have a name
1624
+ - specify the name in Command constructor or using .name()`);
1625
+ }
1626
+ opts = opts || {};
1627
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1628
+ if (opts.noHelp || opts.hidden) cmd._hidden = true;
1629
+ this._registerCommand(cmd);
1630
+ cmd.parent = this;
1631
+ cmd._checkForBrokenPassThrough();
1632
+ return this;
1633
+ }
1634
+ /**
1635
+ * Factory routine to create a new unattached argument.
1636
+ *
1637
+ * See .argument() for creating an attached argument, which uses this routine to
1638
+ * create the argument. You can override createArgument to return a custom argument.
1639
+ *
1640
+ * @param {string} name
1641
+ * @param {string} [description]
1642
+ * @return {Argument} new argument
1643
+ */
1644
+ createArgument(name, description) {
1645
+ return new Argument(name, description);
1646
+ }
1647
+ /**
1648
+ * Define argument syntax for command.
1649
+ *
1650
+ * The default is that the argument is required, and you can explicitly
1651
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
1652
+ *
1653
+ * @example
1654
+ * program.argument('<input-file>');
1655
+ * program.argument('[output-file]');
1656
+ *
1657
+ * @param {string} name
1658
+ * @param {string} [description]
1659
+ * @param {(Function|*)} [fn] - custom argument processing function
1660
+ * @param {*} [defaultValue]
1661
+ * @return {Command} `this` command for chaining
1662
+ */
1663
+ argument(name, description, fn, defaultValue) {
1664
+ const argument = this.createArgument(name, description);
1665
+ if (typeof fn === "function") {
1666
+ argument.default(defaultValue).argParser(fn);
1667
+ } else {
1668
+ argument.default(fn);
1669
+ }
1670
+ this.addArgument(argument);
1671
+ return this;
1672
+ }
1673
+ /**
1674
+ * Define argument syntax for command, adding multiple at once (without descriptions).
1675
+ *
1676
+ * See also .argument().
1677
+ *
1678
+ * @example
1679
+ * program.arguments('<cmd> [env]');
1680
+ *
1681
+ * @param {string} names
1682
+ * @return {Command} `this` command for chaining
1683
+ */
1684
+ arguments(names) {
1685
+ names.trim().split(/ +/).forEach((detail) => {
1686
+ this.argument(detail);
1687
+ });
1688
+ return this;
1689
+ }
1690
+ /**
1691
+ * Define argument syntax for command, adding a prepared argument.
1692
+ *
1693
+ * @param {Argument} argument
1694
+ * @return {Command} `this` command for chaining
1695
+ */
1696
+ addArgument(argument) {
1697
+ const previousArgument = this.registeredArguments.slice(-1)[0];
1698
+ if (previousArgument && previousArgument.variadic) {
1699
+ throw new Error(
1700
+ `only the last argument can be variadic '${previousArgument.name()}'`
1701
+ );
1702
+ }
1703
+ if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
1704
+ throw new Error(
1705
+ `a default value for a required argument is never used: '${argument.name()}'`
1706
+ );
1707
+ }
1708
+ this.registeredArguments.push(argument);
1709
+ return this;
1710
+ }
1711
+ /**
1712
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
1713
+ *
1714
+ * @example
1715
+ * program.helpCommand('help [cmd]');
1716
+ * program.helpCommand('help [cmd]', 'show help');
1717
+ * program.helpCommand(false); // suppress default help command
1718
+ * program.helpCommand(true); // add help command even if no subcommands
1719
+ *
1720
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
1721
+ * @param {string} [description] - custom description
1722
+ * @return {Command} `this` command for chaining
1723
+ */
1724
+ helpCommand(enableOrNameAndArgs, description) {
1725
+ if (typeof enableOrNameAndArgs === "boolean") {
1726
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
1727
+ return this;
1728
+ }
1729
+ enableOrNameAndArgs = enableOrNameAndArgs ?? "help [command]";
1730
+ const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);
1731
+ const helpDescription = description ?? "display help for command";
1732
+ const helpCommand = this.createCommand(helpName);
1733
+ helpCommand.helpOption(false);
1734
+ if (helpArgs) helpCommand.arguments(helpArgs);
1735
+ if (helpDescription) helpCommand.description(helpDescription);
1736
+ this._addImplicitHelpCommand = true;
1737
+ this._helpCommand = helpCommand;
1738
+ return this;
1739
+ }
1740
+ /**
1741
+ * Add prepared custom help command.
1742
+ *
1743
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
1744
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
1745
+ * @return {Command} `this` command for chaining
1746
+ */
1747
+ addHelpCommand(helpCommand, deprecatedDescription) {
1748
+ if (typeof helpCommand !== "object") {
1749
+ this.helpCommand(helpCommand, deprecatedDescription);
1750
+ return this;
1751
+ }
1752
+ this._addImplicitHelpCommand = true;
1753
+ this._helpCommand = helpCommand;
1754
+ return this;
1755
+ }
1756
+ /**
1757
+ * Lazy create help command.
1758
+ *
1759
+ * @return {(Command|null)}
1760
+ * @package
1761
+ */
1762
+ _getHelpCommand() {
1763
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
1764
+ if (hasImplicitHelpCommand) {
1765
+ if (this._helpCommand === void 0) {
1766
+ this.helpCommand(void 0, void 0);
1767
+ }
1768
+ return this._helpCommand;
1769
+ }
1770
+ return null;
1771
+ }
1772
+ /**
1773
+ * Add hook for life cycle event.
1774
+ *
1775
+ * @param {string} event
1776
+ * @param {Function} listener
1777
+ * @return {Command} `this` command for chaining
1778
+ */
1779
+ hook(event, listener) {
1780
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
1781
+ if (!allowedValues.includes(event)) {
1782
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
1783
+ Expecting one of '${allowedValues.join("', '")}'`);
1784
+ }
1785
+ if (this._lifeCycleHooks[event]) {
1786
+ this._lifeCycleHooks[event].push(listener);
1787
+ } else {
1788
+ this._lifeCycleHooks[event] = [listener];
1789
+ }
1790
+ return this;
1791
+ }
1792
+ /**
1793
+ * Register callback to use as replacement for calling process.exit.
1794
+ *
1795
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
1796
+ * @return {Command} `this` command for chaining
1797
+ */
1798
+ exitOverride(fn) {
1799
+ if (fn) {
1800
+ this._exitCallback = fn;
1801
+ } else {
1802
+ this._exitCallback = (err) => {
1803
+ if (err.code !== "commander.executeSubCommandAsync") {
1804
+ throw err;
1805
+ } else {
1806
+ }
1807
+ };
1808
+ }
1809
+ return this;
1810
+ }
1811
+ /**
1812
+ * Call process.exit, and _exitCallback if defined.
1813
+ *
1814
+ * @param {number} exitCode exit code for using with process.exit
1815
+ * @param {string} code an id string representing the error
1816
+ * @param {string} message human-readable description of the error
1817
+ * @return never
1818
+ * @private
1819
+ */
1820
+ _exit(exitCode, code, message) {
1821
+ if (this._exitCallback) {
1822
+ this._exitCallback(new CommanderError(exitCode, code, message));
1823
+ }
1824
+ process2.exit(exitCode);
1825
+ }
1826
+ /**
1827
+ * Register callback `fn` for the command.
1828
+ *
1829
+ * @example
1830
+ * program
1831
+ * .command('serve')
1832
+ * .description('start service')
1833
+ * .action(function() {
1834
+ * // do work here
1835
+ * });
1836
+ *
1837
+ * @param {Function} fn
1838
+ * @return {Command} `this` command for chaining
1839
+ */
1840
+ action(fn) {
1841
+ const listener = (args) => {
1842
+ const expectedArgsCount = this.registeredArguments.length;
1843
+ const actionArgs = args.slice(0, expectedArgsCount);
1844
+ if (this._storeOptionsAsProperties) {
1845
+ actionArgs[expectedArgsCount] = this;
1846
+ } else {
1847
+ actionArgs[expectedArgsCount] = this.opts();
1848
+ }
1849
+ actionArgs.push(this);
1850
+ return fn.apply(this, actionArgs);
1851
+ };
1852
+ this._actionHandler = listener;
1853
+ return this;
1854
+ }
1855
+ /**
1856
+ * Factory routine to create a new unattached option.
1857
+ *
1858
+ * See .option() for creating an attached option, which uses this routine to
1859
+ * create the option. You can override createOption to return a custom option.
1860
+ *
1861
+ * @param {string} flags
1862
+ * @param {string} [description]
1863
+ * @return {Option} new option
1864
+ */
1865
+ createOption(flags, description) {
1866
+ return new Option(flags, description);
1867
+ }
1868
+ /**
1869
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
1870
+ *
1871
+ * @param {(Option | Argument)} target
1872
+ * @param {string} value
1873
+ * @param {*} previous
1874
+ * @param {string} invalidArgumentMessage
1875
+ * @private
1876
+ */
1877
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
1878
+ try {
1879
+ return target.parseArg(value, previous);
1880
+ } catch (err) {
1881
+ if (err.code === "commander.invalidArgument") {
1882
+ const message = `${invalidArgumentMessage} ${err.message}`;
1883
+ this.error(message, { exitCode: err.exitCode, code: err.code });
1884
+ }
1885
+ throw err;
1886
+ }
1887
+ }
1888
+ /**
1889
+ * Check for option flag conflicts.
1890
+ * Register option if no conflicts found, or throw on conflict.
1891
+ *
1892
+ * @param {Option} option
1893
+ * @private
1894
+ */
1895
+ _registerOption(option) {
1896
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1897
+ if (matchingOption) {
1898
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1899
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1900
+ - already used by option '${matchingOption.flags}'`);
1901
+ }
1902
+ this.options.push(option);
1903
+ }
1904
+ /**
1905
+ * Check for command name and alias conflicts with existing commands.
1906
+ * Register command if no conflicts found, or throw on conflict.
1907
+ *
1908
+ * @param {Command} command
1909
+ * @private
1910
+ */
1911
+ _registerCommand(command) {
1912
+ const knownBy = (cmd) => {
1913
+ return [cmd.name()].concat(cmd.aliases());
1914
+ };
1915
+ const alreadyUsed = knownBy(command).find(
1916
+ (name) => this._findCommand(name)
1917
+ );
1918
+ if (alreadyUsed) {
1919
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1920
+ const newCmd = knownBy(command).join("|");
1921
+ throw new Error(
1922
+ `cannot add command '${newCmd}' as already have command '${existingCmd}'`
1923
+ );
1924
+ }
1925
+ this.commands.push(command);
1926
+ }
1927
+ /**
1928
+ * Add an option.
1929
+ *
1930
+ * @param {Option} option
1931
+ * @return {Command} `this` command for chaining
1932
+ */
1933
+ addOption(option) {
1934
+ this._registerOption(option);
1935
+ const oname = option.name();
1936
+ const name = option.attributeName();
1937
+ if (option.negate) {
1938
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1939
+ if (!this._findOption(positiveLongFlag)) {
1940
+ this.setOptionValueWithSource(
1941
+ name,
1942
+ option.defaultValue === void 0 ? true : option.defaultValue,
1943
+ "default"
1944
+ );
1945
+ }
1946
+ } else if (option.defaultValue !== void 0) {
1947
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
1948
+ }
1949
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1950
+ if (val == null && option.presetArg !== void 0) {
1951
+ val = option.presetArg;
1952
+ }
1953
+ const oldValue = this.getOptionValue(name);
1954
+ if (val !== null && option.parseArg) {
1955
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1956
+ } else if (val !== null && option.variadic) {
1957
+ val = option._concatValue(val, oldValue);
1958
+ }
1959
+ if (val == null) {
1960
+ if (option.negate) {
1961
+ val = false;
1962
+ } else if (option.isBoolean() || option.optional) {
1963
+ val = true;
1964
+ } else {
1965
+ val = "";
1966
+ }
1967
+ }
1968
+ this.setOptionValueWithSource(name, val, valueSource);
1969
+ };
1970
+ this.on("option:" + oname, (val) => {
1971
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1972
+ handleOptionValue(val, invalidValueMessage, "cli");
1973
+ });
1974
+ if (option.envVar) {
1975
+ this.on("optionEnv:" + oname, (val) => {
1976
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1977
+ handleOptionValue(val, invalidValueMessage, "env");
1978
+ });
1979
+ }
1980
+ return this;
1981
+ }
1982
+ /**
1983
+ * Internal implementation shared by .option() and .requiredOption()
1984
+ *
1985
+ * @return {Command} `this` command for chaining
1986
+ * @private
1987
+ */
1988
+ _optionEx(config, flags, description, fn, defaultValue) {
1989
+ if (typeof flags === "object" && flags instanceof Option) {
1990
+ throw new Error(
1991
+ "To add an Option object use addOption() instead of option() or requiredOption()"
1992
+ );
1993
+ }
1994
+ const option = this.createOption(flags, description);
1995
+ option.makeOptionMandatory(!!config.mandatory);
1996
+ if (typeof fn === "function") {
1997
+ option.default(defaultValue).argParser(fn);
1998
+ } else if (fn instanceof RegExp) {
1999
+ const regex = fn;
2000
+ fn = (val, def) => {
2001
+ const m = regex.exec(val);
2002
+ return m ? m[0] : def;
2003
+ };
2004
+ option.default(defaultValue).argParser(fn);
2005
+ } else {
2006
+ option.default(fn);
2007
+ }
2008
+ return this.addOption(option);
2009
+ }
2010
+ /**
2011
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
2012
+ *
2013
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
2014
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
2015
+ *
2016
+ * See the README for more details, and see also addOption() and requiredOption().
2017
+ *
2018
+ * @example
2019
+ * program
2020
+ * .option('-p, --pepper', 'add pepper')
2021
+ * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
2022
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
2023
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
2024
+ *
2025
+ * @param {string} flags
2026
+ * @param {string} [description]
2027
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
2028
+ * @param {*} [defaultValue]
2029
+ * @return {Command} `this` command for chaining
2030
+ */
2031
+ option(flags, description, parseArg, defaultValue) {
2032
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
2033
+ }
2034
+ /**
2035
+ * Add a required option which must have a value after parsing. This usually means
2036
+ * the option must be specified on the command line. (Otherwise the same as .option().)
2037
+ *
2038
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
2039
+ *
2040
+ * @param {string} flags
2041
+ * @param {string} [description]
2042
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
2043
+ * @param {*} [defaultValue]
2044
+ * @return {Command} `this` command for chaining
2045
+ */
2046
+ requiredOption(flags, description, parseArg, defaultValue) {
2047
+ return this._optionEx(
2048
+ { mandatory: true },
2049
+ flags,
2050
+ description,
2051
+ parseArg,
2052
+ defaultValue
2053
+ );
2054
+ }
2055
+ /**
2056
+ * Alter parsing of short flags with optional values.
2057
+ *
2058
+ * @example
2059
+ * // for `.option('-f,--flag [value]'):
2060
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
2061
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
2062
+ *
2063
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
2064
+ * @return {Command} `this` command for chaining
2065
+ */
2066
+ combineFlagAndOptionalValue(combine = true) {
2067
+ this._combineFlagAndOptionalValue = !!combine;
2068
+ return this;
2069
+ }
2070
+ /**
2071
+ * Allow unknown options on the command line.
2072
+ *
2073
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
2074
+ * @return {Command} `this` command for chaining
2075
+ */
2076
+ allowUnknownOption(allowUnknown = true) {
2077
+ this._allowUnknownOption = !!allowUnknown;
2078
+ return this;
2079
+ }
2080
+ /**
2081
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
2082
+ *
2083
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
2084
+ * @return {Command} `this` command for chaining
2085
+ */
2086
+ allowExcessArguments(allowExcess = true) {
2087
+ this._allowExcessArguments = !!allowExcess;
2088
+ return this;
2089
+ }
2090
+ /**
2091
+ * Enable positional options. Positional means global options are specified before subcommands which lets
2092
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
2093
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
2094
+ *
2095
+ * @param {boolean} [positional]
2096
+ * @return {Command} `this` command for chaining
2097
+ */
2098
+ enablePositionalOptions(positional = true) {
2099
+ this._enablePositionalOptions = !!positional;
2100
+ return this;
2101
+ }
2102
+ /**
2103
+ * Pass through options that come after command-arguments rather than treat them as command-options,
2104
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
2105
+ * positional options to have been enabled on the program (parent commands).
2106
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
2107
+ *
2108
+ * @param {boolean} [passThrough] for unknown options.
2109
+ * @return {Command} `this` command for chaining
2110
+ */
2111
+ passThroughOptions(passThrough = true) {
2112
+ this._passThroughOptions = !!passThrough;
2113
+ this._checkForBrokenPassThrough();
2114
+ return this;
2115
+ }
2116
+ /**
2117
+ * @private
2118
+ */
2119
+ _checkForBrokenPassThrough() {
2120
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
2121
+ throw new Error(
2122
+ `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`
2123
+ );
2124
+ }
2125
+ }
2126
+ /**
2127
+ * Whether to store option values as properties on command object,
2128
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
2129
+ *
2130
+ * @param {boolean} [storeAsProperties=true]
2131
+ * @return {Command} `this` command for chaining
2132
+ */
2133
+ storeOptionsAsProperties(storeAsProperties = true) {
2134
+ if (this.options.length) {
2135
+ throw new Error("call .storeOptionsAsProperties() before adding options");
2136
+ }
2137
+ if (Object.keys(this._optionValues).length) {
2138
+ throw new Error(
2139
+ "call .storeOptionsAsProperties() before setting option values"
2140
+ );
2141
+ }
2142
+ this._storeOptionsAsProperties = !!storeAsProperties;
2143
+ return this;
2144
+ }
2145
+ /**
2146
+ * Retrieve option value.
2147
+ *
2148
+ * @param {string} key
2149
+ * @return {object} value
2150
+ */
2151
+ getOptionValue(key) {
2152
+ if (this._storeOptionsAsProperties) {
2153
+ return this[key];
2154
+ }
2155
+ return this._optionValues[key];
2156
+ }
2157
+ /**
2158
+ * Store option value.
2159
+ *
2160
+ * @param {string} key
2161
+ * @param {object} value
2162
+ * @return {Command} `this` command for chaining
2163
+ */
2164
+ setOptionValue(key, value) {
2165
+ return this.setOptionValueWithSource(key, value, void 0);
2166
+ }
2167
+ /**
2168
+ * Store option value and where the value came from.
2169
+ *
2170
+ * @param {string} key
2171
+ * @param {object} value
2172
+ * @param {string} source - expected values are default/config/env/cli/implied
2173
+ * @return {Command} `this` command for chaining
2174
+ */
2175
+ setOptionValueWithSource(key, value, source) {
2176
+ if (this._storeOptionsAsProperties) {
2177
+ this[key] = value;
2178
+ } else {
2179
+ this._optionValues[key] = value;
2180
+ }
2181
+ this._optionValueSources[key] = source;
2182
+ return this;
2183
+ }
2184
+ /**
2185
+ * Get source of option value.
2186
+ * Expected values are default | config | env | cli | implied
2187
+ *
2188
+ * @param {string} key
2189
+ * @return {string}
2190
+ */
2191
+ getOptionValueSource(key) {
2192
+ return this._optionValueSources[key];
2193
+ }
2194
+ /**
2195
+ * Get source of option value. See also .optsWithGlobals().
2196
+ * Expected values are default | config | env | cli | implied
2197
+ *
2198
+ * @param {string} key
2199
+ * @return {string}
2200
+ */
2201
+ getOptionValueSourceWithGlobals(key) {
2202
+ let source;
2203
+ this._getCommandAndAncestors().forEach((cmd) => {
2204
+ if (cmd.getOptionValueSource(key) !== void 0) {
2205
+ source = cmd.getOptionValueSource(key);
2206
+ }
2207
+ });
2208
+ return source;
2209
+ }
2210
+ /**
2211
+ * Get user arguments from implied or explicit arguments.
2212
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
2213
+ *
2214
+ * @private
2215
+ */
2216
+ _prepareUserArgs(argv, parseOptions) {
2217
+ if (argv !== void 0 && !Array.isArray(argv)) {
2218
+ throw new Error("first parameter to parse must be array or undefined");
2219
+ }
2220
+ parseOptions = parseOptions || {};
2221
+ if (argv === void 0 && parseOptions.from === void 0) {
2222
+ if (process2.versions?.electron) {
2223
+ parseOptions.from = "electron";
2224
+ }
2225
+ const execArgv = process2.execArgv ?? [];
2226
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
2227
+ parseOptions.from = "eval";
2228
+ }
2229
+ }
2230
+ if (argv === void 0) {
2231
+ argv = process2.argv;
2232
+ }
2233
+ this.rawArgs = argv.slice();
2234
+ let userArgs;
2235
+ switch (parseOptions.from) {
2236
+ case void 0:
2237
+ case "node":
2238
+ this._scriptPath = argv[1];
2239
+ userArgs = argv.slice(2);
2240
+ break;
2241
+ case "electron":
2242
+ if (process2.defaultApp) {
2243
+ this._scriptPath = argv[1];
2244
+ userArgs = argv.slice(2);
2245
+ } else {
2246
+ userArgs = argv.slice(1);
2247
+ }
2248
+ break;
2249
+ case "user":
2250
+ userArgs = argv.slice(0);
2251
+ break;
2252
+ case "eval":
2253
+ userArgs = argv.slice(1);
2254
+ break;
2255
+ default:
2256
+ throw new Error(
2257
+ `unexpected parse option { from: '${parseOptions.from}' }`
2258
+ );
2259
+ }
2260
+ if (!this._name && this._scriptPath)
2261
+ this.nameFromFilename(this._scriptPath);
2262
+ this._name = this._name || "program";
2263
+ return userArgs;
2264
+ }
2265
+ /**
2266
+ * Parse `argv`, setting options and invoking commands when defined.
2267
+ *
2268
+ * Use parseAsync instead of parse if any of your action handlers are async.
2269
+ *
2270
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
2271
+ *
2272
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
2273
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
2274
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
2275
+ * - `'user'`: just user arguments
2276
+ *
2277
+ * @example
2278
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
2279
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
2280
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2281
+ *
2282
+ * @param {string[]} [argv] - optional, defaults to process.argv
2283
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
2284
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
2285
+ * @return {Command} `this` command for chaining
2286
+ */
2287
+ parse(argv, parseOptions) {
2288
+ this._prepareForParse();
2289
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
2290
+ this._parseCommand([], userArgs);
2291
+ return this;
2292
+ }
2293
+ /**
2294
+ * Parse `argv`, setting options and invoking commands when defined.
2295
+ *
2296
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
2297
+ *
2298
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
2299
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
2300
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
2301
+ * - `'user'`: just user arguments
2302
+ *
2303
+ * @example
2304
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
2305
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
2306
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2307
+ *
2308
+ * @param {string[]} [argv]
2309
+ * @param {object} [parseOptions]
2310
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
2311
+ * @return {Promise}
2312
+ */
2313
+ async parseAsync(argv, parseOptions) {
2314
+ this._prepareForParse();
2315
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
2316
+ await this._parseCommand([], userArgs);
2317
+ return this;
2318
+ }
2319
+ _prepareForParse() {
2320
+ if (this._savedState === null) {
2321
+ this.saveStateBeforeParse();
2322
+ } else {
2323
+ this.restoreStateBeforeParse();
2324
+ }
2325
+ }
2326
+ /**
2327
+ * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
2328
+ * Not usually called directly, but available for subclasses to save their custom state.
2329
+ *
2330
+ * This is called in a lazy way. Only commands used in parsing chain will have state saved.
2331
+ */
2332
+ saveStateBeforeParse() {
2333
+ this._savedState = {
2334
+ // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing
2335
+ _name: this._name,
2336
+ // option values before parse have default values (including false for negated options)
2337
+ // shallow clones
2338
+ _optionValues: { ...this._optionValues },
2339
+ _optionValueSources: { ...this._optionValueSources }
2340
+ };
2341
+ }
2342
+ /**
2343
+ * Restore state before parse for calls after the first.
2344
+ * Not usually called directly, but available for subclasses to save their custom state.
2345
+ *
2346
+ * This is called in a lazy way. Only commands used in parsing chain will have state restored.
2347
+ */
2348
+ restoreStateBeforeParse() {
2349
+ if (this._storeOptionsAsProperties)
2350
+ throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
2351
+ - either make a new Command for each call to parse, or stop storing options as properties`);
2352
+ this._name = this._savedState._name;
2353
+ this._scriptPath = null;
2354
+ this.rawArgs = [];
2355
+ this._optionValues = { ...this._savedState._optionValues };
2356
+ this._optionValueSources = { ...this._savedState._optionValueSources };
2357
+ this.args = [];
2358
+ this.processedArgs = [];
2359
+ }
2360
+ /**
2361
+ * Throw if expected executable is missing. Add lots of help for author.
2362
+ *
2363
+ * @param {string} executableFile
2364
+ * @param {string} executableDir
2365
+ * @param {string} subcommandName
2366
+ */
2367
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
2368
+ if (fs4.existsSync(executableFile)) return;
2369
+ 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";
2370
+ const executableMissing = `'${executableFile}' does not exist
2371
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
2372
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
2373
+ - ${executableDirMessage}`;
2374
+ throw new Error(executableMissing);
2375
+ }
2376
+ /**
2377
+ * Execute a sub-command executable.
2378
+ *
2379
+ * @private
2380
+ */
2381
+ _executeSubCommand(subcommand, args) {
2382
+ args = args.slice();
2383
+ let launchWithNode = false;
2384
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
2385
+ function findFile(baseDir, baseName) {
2386
+ const localBin = path.resolve(baseDir, baseName);
2387
+ if (fs4.existsSync(localBin)) return localBin;
2388
+ if (sourceExt.includes(path.extname(baseName))) return void 0;
2389
+ const foundExt = sourceExt.find(
2390
+ (ext) => fs4.existsSync(`${localBin}${ext}`)
2391
+ );
2392
+ if (foundExt) return `${localBin}${foundExt}`;
2393
+ return void 0;
2394
+ }
2395
+ this._checkForMissingMandatoryOptions();
2396
+ this._checkForConflictingOptions();
2397
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
2398
+ let executableDir = this._executableDir || "";
2399
+ if (this._scriptPath) {
2400
+ let resolvedScriptPath;
2401
+ try {
2402
+ resolvedScriptPath = fs4.realpathSync(this._scriptPath);
2403
+ } catch {
2404
+ resolvedScriptPath = this._scriptPath;
2405
+ }
2406
+ executableDir = path.resolve(
2407
+ path.dirname(resolvedScriptPath),
2408
+ executableDir
2409
+ );
2410
+ }
2411
+ if (executableDir) {
2412
+ let localFile = findFile(executableDir, executableFile);
2413
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
2414
+ const legacyName = path.basename(
2415
+ this._scriptPath,
2416
+ path.extname(this._scriptPath)
2417
+ );
2418
+ if (legacyName !== this._name) {
2419
+ localFile = findFile(
2420
+ executableDir,
2421
+ `${legacyName}-${subcommand._name}`
2422
+ );
2423
+ }
2424
+ }
2425
+ executableFile = localFile || executableFile;
2426
+ }
2427
+ launchWithNode = sourceExt.includes(path.extname(executableFile));
2428
+ let proc;
2429
+ if (process2.platform !== "win32") {
2430
+ if (launchWithNode) {
2431
+ args.unshift(executableFile);
2432
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
2433
+ proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
2434
+ } else {
2435
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
2436
+ }
2437
+ } else {
2438
+ this._checkForMissingExecutable(
2439
+ executableFile,
2440
+ executableDir,
2441
+ subcommand._name
2442
+ );
2443
+ args.unshift(executableFile);
2444
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
2445
+ proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
2446
+ }
2447
+ if (!proc.killed) {
2448
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
2449
+ signals.forEach((signal) => {
2450
+ process2.on(signal, () => {
2451
+ if (proc.killed === false && proc.exitCode === null) {
2452
+ proc.kill(signal);
2453
+ }
2454
+ });
2455
+ });
2456
+ }
2457
+ const exitCallback = this._exitCallback;
2458
+ proc.on("close", (code) => {
2459
+ code = code ?? 1;
2460
+ if (!exitCallback) {
2461
+ process2.exit(code);
2462
+ } else {
2463
+ exitCallback(
2464
+ new CommanderError(
2465
+ code,
2466
+ "commander.executeSubCommandAsync",
2467
+ "(close)"
2468
+ )
2469
+ );
2470
+ }
2471
+ });
2472
+ proc.on("error", (err) => {
2473
+ if (err.code === "ENOENT") {
2474
+ this._checkForMissingExecutable(
2475
+ executableFile,
2476
+ executableDir,
2477
+ subcommand._name
2478
+ );
2479
+ } else if (err.code === "EACCES") {
2480
+ throw new Error(`'${executableFile}' not executable`);
2481
+ }
2482
+ if (!exitCallback) {
2483
+ process2.exit(1);
2484
+ } else {
2485
+ const wrappedError = new CommanderError(
2486
+ 1,
2487
+ "commander.executeSubCommandAsync",
2488
+ "(error)"
2489
+ );
2490
+ wrappedError.nestedError = err;
2491
+ exitCallback(wrappedError);
2492
+ }
2493
+ });
2494
+ this.runningCommand = proc;
2495
+ }
2496
+ /**
2497
+ * @private
2498
+ */
2499
+ _dispatchSubcommand(commandName, operands, unknown) {
2500
+ const subCommand = this._findCommand(commandName);
2501
+ if (!subCommand) this.help({ error: true });
2502
+ subCommand._prepareForParse();
2503
+ let promiseChain;
2504
+ promiseChain = this._chainOrCallSubCommandHook(
2505
+ promiseChain,
2506
+ subCommand,
2507
+ "preSubcommand"
2508
+ );
2509
+ promiseChain = this._chainOrCall(promiseChain, () => {
2510
+ if (subCommand._executableHandler) {
2511
+ this._executeSubCommand(subCommand, operands.concat(unknown));
2512
+ } else {
2513
+ return subCommand._parseCommand(operands, unknown);
2514
+ }
2515
+ });
2516
+ return promiseChain;
2517
+ }
2518
+ /**
2519
+ * Invoke help directly if possible, or dispatch if necessary.
2520
+ * e.g. help foo
2521
+ *
2522
+ * @private
2523
+ */
2524
+ _dispatchHelpCommand(subcommandName) {
2525
+ if (!subcommandName) {
2526
+ this.help();
2527
+ }
2528
+ const subCommand = this._findCommand(subcommandName);
2529
+ if (subCommand && !subCommand._executableHandler) {
2530
+ subCommand.help();
2531
+ }
2532
+ return this._dispatchSubcommand(
2533
+ subcommandName,
2534
+ [],
2535
+ [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]
2536
+ );
2537
+ }
2538
+ /**
2539
+ * Check this.args against expected this.registeredArguments.
2540
+ *
2541
+ * @private
2542
+ */
2543
+ _checkNumberOfArguments() {
2544
+ this.registeredArguments.forEach((arg, i) => {
2545
+ if (arg.required && this.args[i] == null) {
2546
+ this.missingArgument(arg.name());
2547
+ }
2548
+ });
2549
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
2550
+ return;
2551
+ }
2552
+ if (this.args.length > this.registeredArguments.length) {
2553
+ this._excessArguments(this.args);
2554
+ }
2555
+ }
2556
+ /**
2557
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
2558
+ *
2559
+ * @private
2560
+ */
2561
+ _processArguments() {
2562
+ const myParseArg = (argument, value, previous) => {
2563
+ let parsedValue = value;
2564
+ if (value !== null && argument.parseArg) {
2565
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
2566
+ parsedValue = this._callParseArg(
2567
+ argument,
2568
+ value,
2569
+ previous,
2570
+ invalidValueMessage
2571
+ );
2572
+ }
2573
+ return parsedValue;
2574
+ };
2575
+ this._checkNumberOfArguments();
2576
+ const processedArgs = [];
2577
+ this.registeredArguments.forEach((declaredArg, index) => {
2578
+ let value = declaredArg.defaultValue;
2579
+ if (declaredArg.variadic) {
2580
+ if (index < this.args.length) {
2581
+ value = this.args.slice(index);
2582
+ if (declaredArg.parseArg) {
2583
+ value = value.reduce((processed, v) => {
2584
+ return myParseArg(declaredArg, v, processed);
2585
+ }, declaredArg.defaultValue);
2586
+ }
2587
+ } else if (value === void 0) {
2588
+ value = [];
2589
+ }
2590
+ } else if (index < this.args.length) {
2591
+ value = this.args[index];
2592
+ if (declaredArg.parseArg) {
2593
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
2594
+ }
2595
+ }
2596
+ processedArgs[index] = value;
2597
+ });
2598
+ this.processedArgs = processedArgs;
2599
+ }
2600
+ /**
2601
+ * Once we have a promise we chain, but call synchronously until then.
2602
+ *
2603
+ * @param {(Promise|undefined)} promise
2604
+ * @param {Function} fn
2605
+ * @return {(Promise|undefined)}
2606
+ * @private
2607
+ */
2608
+ _chainOrCall(promise, fn) {
2609
+ if (promise && promise.then && typeof promise.then === "function") {
2610
+ return promise.then(() => fn());
2611
+ }
2612
+ return fn();
2613
+ }
2614
+ /**
2615
+ *
2616
+ * @param {(Promise|undefined)} promise
2617
+ * @param {string} event
2618
+ * @return {(Promise|undefined)}
2619
+ * @private
2620
+ */
2621
+ _chainOrCallHooks(promise, event) {
2622
+ let result = promise;
2623
+ const hooks = [];
2624
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
2625
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
2626
+ hooks.push({ hookedCommand, callback });
2627
+ });
2628
+ });
2629
+ if (event === "postAction") {
2630
+ hooks.reverse();
2631
+ }
2632
+ hooks.forEach((hookDetail) => {
2633
+ result = this._chainOrCall(result, () => {
2634
+ return hookDetail.callback(hookDetail.hookedCommand, this);
2635
+ });
2636
+ });
2637
+ return result;
2638
+ }
2639
+ /**
2640
+ *
2641
+ * @param {(Promise|undefined)} promise
2642
+ * @param {Command} subCommand
2643
+ * @param {string} event
2644
+ * @return {(Promise|undefined)}
2645
+ * @private
2646
+ */
2647
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
2648
+ let result = promise;
2649
+ if (this._lifeCycleHooks[event] !== void 0) {
2650
+ this._lifeCycleHooks[event].forEach((hook) => {
2651
+ result = this._chainOrCall(result, () => {
2652
+ return hook(this, subCommand);
2653
+ });
2654
+ });
2655
+ }
2656
+ return result;
2657
+ }
2658
+ /**
2659
+ * Process arguments in context of this command.
2660
+ * Returns action result, in case it is a promise.
2661
+ *
2662
+ * @private
2663
+ */
2664
+ _parseCommand(operands, unknown) {
2665
+ const parsed = this.parseOptions(unknown);
2666
+ this._parseOptionsEnv();
2667
+ this._parseOptionsImplied();
2668
+ operands = operands.concat(parsed.operands);
2669
+ unknown = parsed.unknown;
2670
+ this.args = operands.concat(unknown);
2671
+ if (operands && this._findCommand(operands[0])) {
2672
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2673
+ }
2674
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
2675
+ return this._dispatchHelpCommand(operands[1]);
2676
+ }
2677
+ if (this._defaultCommandName) {
2678
+ this._outputHelpIfRequested(unknown);
2679
+ return this._dispatchSubcommand(
2680
+ this._defaultCommandName,
2681
+ operands,
2682
+ unknown
2683
+ );
2684
+ }
2685
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
2686
+ this.help({ error: true });
2687
+ }
2688
+ this._outputHelpIfRequested(parsed.unknown);
2689
+ this._checkForMissingMandatoryOptions();
2690
+ this._checkForConflictingOptions();
2691
+ const checkForUnknownOptions = () => {
2692
+ if (parsed.unknown.length > 0) {
2693
+ this.unknownOption(parsed.unknown[0]);
2694
+ }
2695
+ };
2696
+ const commandEvent = `command:${this.name()}`;
2697
+ if (this._actionHandler) {
2698
+ checkForUnknownOptions();
2699
+ this._processArguments();
2700
+ let promiseChain;
2701
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
2702
+ promiseChain = this._chainOrCall(
2703
+ promiseChain,
2704
+ () => this._actionHandler(this.processedArgs)
2705
+ );
2706
+ if (this.parent) {
2707
+ promiseChain = this._chainOrCall(promiseChain, () => {
2708
+ this.parent.emit(commandEvent, operands, unknown);
2709
+ });
2710
+ }
2711
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
2712
+ return promiseChain;
2713
+ }
2714
+ if (this.parent && this.parent.listenerCount(commandEvent)) {
2715
+ checkForUnknownOptions();
2716
+ this._processArguments();
2717
+ this.parent.emit(commandEvent, operands, unknown);
2718
+ } else if (operands.length) {
2719
+ if (this._findCommand("*")) {
2720
+ return this._dispatchSubcommand("*", operands, unknown);
2721
+ }
2722
+ if (this.listenerCount("command:*")) {
2723
+ this.emit("command:*", operands, unknown);
2724
+ } else if (this.commands.length) {
2725
+ this.unknownCommand();
2726
+ } else {
2727
+ checkForUnknownOptions();
2728
+ this._processArguments();
2729
+ }
2730
+ } else if (this.commands.length) {
2731
+ checkForUnknownOptions();
2732
+ this.help({ error: true });
2733
+ } else {
2734
+ checkForUnknownOptions();
2735
+ this._processArguments();
2736
+ }
2737
+ }
2738
+ /**
2739
+ * Find matching command.
2740
+ *
2741
+ * @private
2742
+ * @return {Command | undefined}
2743
+ */
2744
+ _findCommand(name) {
2745
+ if (!name) return void 0;
2746
+ return this.commands.find(
2747
+ (cmd) => cmd._name === name || cmd._aliases.includes(name)
2748
+ );
2749
+ }
2750
+ /**
2751
+ * Return an option matching `arg` if any.
2752
+ *
2753
+ * @param {string} arg
2754
+ * @return {Option}
2755
+ * @package
2756
+ */
2757
+ _findOption(arg) {
2758
+ return this.options.find((option) => option.is(arg));
2759
+ }
2760
+ /**
2761
+ * Display an error message if a mandatory option does not have a value.
2762
+ * Called after checking for help flags in leaf subcommand.
2763
+ *
2764
+ * @private
2765
+ */
2766
+ _checkForMissingMandatoryOptions() {
2767
+ this._getCommandAndAncestors().forEach((cmd) => {
2768
+ cmd.options.forEach((anOption) => {
2769
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
2770
+ cmd.missingMandatoryOptionValue(anOption);
2771
+ }
2772
+ });
2773
+ });
2774
+ }
2775
+ /**
2776
+ * Display an error message if conflicting options are used together in this.
2777
+ *
2778
+ * @private
2779
+ */
2780
+ _checkForConflictingLocalOptions() {
2781
+ const definedNonDefaultOptions = this.options.filter((option) => {
2782
+ const optionKey = option.attributeName();
2783
+ if (this.getOptionValue(optionKey) === void 0) {
2784
+ return false;
2785
+ }
2786
+ return this.getOptionValueSource(optionKey) !== "default";
2787
+ });
2788
+ const optionsWithConflicting = definedNonDefaultOptions.filter(
2789
+ (option) => option.conflictsWith.length > 0
2790
+ );
2791
+ optionsWithConflicting.forEach((option) => {
2792
+ const conflictingAndDefined = definedNonDefaultOptions.find(
2793
+ (defined) => option.conflictsWith.includes(defined.attributeName())
2794
+ );
2795
+ if (conflictingAndDefined) {
2796
+ this._conflictingOption(option, conflictingAndDefined);
2797
+ }
2798
+ });
2799
+ }
2800
+ /**
2801
+ * Display an error message if conflicting options are used together.
2802
+ * Called after checking for help flags in leaf subcommand.
2803
+ *
2804
+ * @private
2805
+ */
2806
+ _checkForConflictingOptions() {
2807
+ this._getCommandAndAncestors().forEach((cmd) => {
2808
+ cmd._checkForConflictingLocalOptions();
2809
+ });
2810
+ }
2811
+ /**
2812
+ * Parse options from `argv` removing known options,
2813
+ * and return argv split into operands and unknown arguments.
2814
+ *
2815
+ * Side effects: modifies command by storing options. Does not reset state if called again.
2816
+ *
2817
+ * Examples:
2818
+ *
2819
+ * argv => operands, unknown
2820
+ * --known kkk op => [op], []
2821
+ * op --known kkk => [op], []
2822
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
2823
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
2824
+ *
2825
+ * @param {string[]} argv
2826
+ * @return {{operands: string[], unknown: string[]}}
2827
+ */
2828
+ parseOptions(argv) {
2829
+ const operands = [];
2830
+ const unknown = [];
2831
+ let dest = operands;
2832
+ const args = argv.slice();
2833
+ function maybeOption(arg) {
2834
+ return arg.length > 1 && arg[0] === "-";
2835
+ }
2836
+ let activeVariadicOption = null;
2837
+ while (args.length) {
2838
+ const arg = args.shift();
2839
+ if (arg === "--") {
2840
+ if (dest === unknown) dest.push(arg);
2841
+ dest.push(...args);
2842
+ break;
2843
+ }
2844
+ if (activeVariadicOption && !maybeOption(arg)) {
2845
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
2846
+ continue;
2847
+ }
2848
+ activeVariadicOption = null;
2849
+ if (maybeOption(arg)) {
2850
+ const option = this._findOption(arg);
2851
+ if (option) {
2852
+ if (option.required) {
2853
+ const value = args.shift();
2854
+ if (value === void 0) this.optionMissingArgument(option);
2855
+ this.emit(`option:${option.name()}`, value);
2856
+ } else if (option.optional) {
2857
+ let value = null;
2858
+ if (args.length > 0 && !maybeOption(args[0])) {
2859
+ value = args.shift();
2860
+ }
2861
+ this.emit(`option:${option.name()}`, value);
2862
+ } else {
2863
+ this.emit(`option:${option.name()}`);
2864
+ }
2865
+ activeVariadicOption = option.variadic ? option : null;
2866
+ continue;
2867
+ }
2868
+ }
2869
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
2870
+ const option = this._findOption(`-${arg[1]}`);
2871
+ if (option) {
2872
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
2873
+ this.emit(`option:${option.name()}`, arg.slice(2));
2874
+ } else {
2875
+ this.emit(`option:${option.name()}`);
2876
+ args.unshift(`-${arg.slice(2)}`);
2877
+ }
2878
+ continue;
2879
+ }
2880
+ }
2881
+ if (/^--[^=]+=/.test(arg)) {
2882
+ const index = arg.indexOf("=");
2883
+ const option = this._findOption(arg.slice(0, index));
2884
+ if (option && (option.required || option.optional)) {
2885
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
2886
+ continue;
2887
+ }
2888
+ }
2889
+ if (maybeOption(arg)) {
2890
+ dest = unknown;
2891
+ }
2892
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
2893
+ if (this._findCommand(arg)) {
2894
+ operands.push(arg);
2895
+ if (args.length > 0) unknown.push(...args);
2896
+ break;
2897
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
2898
+ operands.push(arg);
2899
+ if (args.length > 0) operands.push(...args);
2900
+ break;
2901
+ } else if (this._defaultCommandName) {
2902
+ unknown.push(arg);
2903
+ if (args.length > 0) unknown.push(...args);
2904
+ break;
2905
+ }
2906
+ }
2907
+ if (this._passThroughOptions) {
2908
+ dest.push(arg);
2909
+ if (args.length > 0) dest.push(...args);
2910
+ break;
2911
+ }
2912
+ dest.push(arg);
2913
+ }
2914
+ return { operands, unknown };
2915
+ }
2916
+ /**
2917
+ * Return an object containing local option values as key-value pairs.
2918
+ *
2919
+ * @return {object}
2920
+ */
2921
+ opts() {
2922
+ if (this._storeOptionsAsProperties) {
2923
+ const result = {};
2924
+ const len = this.options.length;
2925
+ for (let i = 0; i < len; i++) {
2926
+ const key = this.options[i].attributeName();
2927
+ result[key] = key === this._versionOptionName ? this._version : this[key];
2928
+ }
2929
+ return result;
2930
+ }
2931
+ return this._optionValues;
2932
+ }
2933
+ /**
2934
+ * Return an object containing merged local and global option values as key-value pairs.
2935
+ *
2936
+ * @return {object}
2937
+ */
2938
+ optsWithGlobals() {
2939
+ return this._getCommandAndAncestors().reduce(
2940
+ (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
2941
+ {}
2942
+ );
2943
+ }
2944
+ /**
2945
+ * Display error message and exit (or call exitOverride).
2946
+ *
2947
+ * @param {string} message
2948
+ * @param {object} [errorOptions]
2949
+ * @param {string} [errorOptions.code] - an id string representing the error
2950
+ * @param {number} [errorOptions.exitCode] - used with process.exit
2951
+ */
2952
+ error(message, errorOptions) {
2953
+ this._outputConfiguration.outputError(
2954
+ `${message}
2955
+ `,
2956
+ this._outputConfiguration.writeErr
2957
+ );
2958
+ if (typeof this._showHelpAfterError === "string") {
2959
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
2960
+ `);
2961
+ } else if (this._showHelpAfterError) {
2962
+ this._outputConfiguration.writeErr("\n");
2963
+ this.outputHelp({ error: true });
2964
+ }
2965
+ const config = errorOptions || {};
2966
+ const exitCode = config.exitCode || 1;
2967
+ const code = config.code || "commander.error";
2968
+ this._exit(exitCode, code, message);
2969
+ }
2970
+ /**
2971
+ * Apply any option related environment variables, if option does
2972
+ * not have a value from cli or client code.
2973
+ *
2974
+ * @private
2975
+ */
2976
+ _parseOptionsEnv() {
2977
+ this.options.forEach((option) => {
2978
+ if (option.envVar && option.envVar in process2.env) {
2979
+ const optionKey = option.attributeName();
2980
+ if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(
2981
+ this.getOptionValueSource(optionKey)
2982
+ )) {
2983
+ if (option.required || option.optional) {
2984
+ this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
2985
+ } else {
2986
+ this.emit(`optionEnv:${option.name()}`);
2987
+ }
2988
+ }
2989
+ }
2990
+ });
2991
+ }
2992
+ /**
2993
+ * Apply any implied option values, if option is undefined or default value.
2994
+ *
2995
+ * @private
2996
+ */
2997
+ _parseOptionsImplied() {
2998
+ const dualHelper = new DualOptions(this.options);
2999
+ const hasCustomOptionValue = (optionKey) => {
3000
+ return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
3001
+ };
3002
+ this.options.filter(
3003
+ (option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(
3004
+ this.getOptionValue(option.attributeName()),
3005
+ option
3006
+ )
3007
+ ).forEach((option) => {
3008
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
3009
+ this.setOptionValueWithSource(
3010
+ impliedKey,
3011
+ option.implied[impliedKey],
3012
+ "implied"
3013
+ );
3014
+ });
3015
+ });
3016
+ }
3017
+ /**
3018
+ * Argument `name` is missing.
3019
+ *
3020
+ * @param {string} name
3021
+ * @private
3022
+ */
3023
+ missingArgument(name) {
3024
+ const message = `error: missing required argument '${name}'`;
3025
+ this.error(message, { code: "commander.missingArgument" });
3026
+ }
3027
+ /**
3028
+ * `Option` is missing an argument.
3029
+ *
3030
+ * @param {Option} option
3031
+ * @private
3032
+ */
3033
+ optionMissingArgument(option) {
3034
+ const message = `error: option '${option.flags}' argument missing`;
3035
+ this.error(message, { code: "commander.optionMissingArgument" });
3036
+ }
3037
+ /**
3038
+ * `Option` does not have a value, and is a mandatory option.
3039
+ *
3040
+ * @param {Option} option
3041
+ * @private
3042
+ */
3043
+ missingMandatoryOptionValue(option) {
3044
+ const message = `error: required option '${option.flags}' not specified`;
3045
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
3046
+ }
3047
+ /**
3048
+ * `Option` conflicts with another option.
3049
+ *
3050
+ * @param {Option} option
3051
+ * @param {Option} conflictingOption
3052
+ * @private
3053
+ */
3054
+ _conflictingOption(option, conflictingOption) {
3055
+ const findBestOptionFromValue = (option2) => {
3056
+ const optionKey = option2.attributeName();
3057
+ const optionValue = this.getOptionValue(optionKey);
3058
+ const negativeOption = this.options.find(
3059
+ (target) => target.negate && optionKey === target.attributeName()
3060
+ );
3061
+ const positiveOption = this.options.find(
3062
+ (target) => !target.negate && optionKey === target.attributeName()
3063
+ );
3064
+ if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
3065
+ return negativeOption;
3066
+ }
3067
+ return positiveOption || option2;
3068
+ };
3069
+ const getErrorMessage = (option2) => {
3070
+ const bestOption = findBestOptionFromValue(option2);
3071
+ const optionKey = bestOption.attributeName();
3072
+ const source = this.getOptionValueSource(optionKey);
3073
+ if (source === "env") {
3074
+ return `environment variable '${bestOption.envVar}'`;
3075
+ }
3076
+ return `option '${bestOption.flags}'`;
3077
+ };
3078
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
3079
+ this.error(message, { code: "commander.conflictingOption" });
3080
+ }
3081
+ /**
3082
+ * Unknown option `flag`.
3083
+ *
3084
+ * @param {string} flag
3085
+ * @private
3086
+ */
3087
+ unknownOption(flag) {
3088
+ if (this._allowUnknownOption) return;
3089
+ let suggestion = "";
3090
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
3091
+ let candidateFlags = [];
3092
+ let command = this;
3093
+ do {
3094
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
3095
+ candidateFlags = candidateFlags.concat(moreFlags);
3096
+ command = command.parent;
3097
+ } while (command && !command._enablePositionalOptions);
3098
+ suggestion = suggestSimilar(flag, candidateFlags);
3099
+ }
3100
+ const message = `error: unknown option '${flag}'${suggestion}`;
3101
+ this.error(message, { code: "commander.unknownOption" });
3102
+ }
3103
+ /**
3104
+ * Excess arguments, more than expected.
3105
+ *
3106
+ * @param {string[]} receivedArgs
3107
+ * @private
3108
+ */
3109
+ _excessArguments(receivedArgs) {
3110
+ if (this._allowExcessArguments) return;
3111
+ const expected = this.registeredArguments.length;
3112
+ const s = expected === 1 ? "" : "s";
3113
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
3114
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
3115
+ this.error(message, { code: "commander.excessArguments" });
3116
+ }
3117
+ /**
3118
+ * Unknown command.
3119
+ *
3120
+ * @private
3121
+ */
3122
+ unknownCommand() {
3123
+ const unknownName = this.args[0];
3124
+ let suggestion = "";
3125
+ if (this._showSuggestionAfterError) {
3126
+ const candidateNames = [];
3127
+ this.createHelp().visibleCommands(this).forEach((command) => {
3128
+ candidateNames.push(command.name());
3129
+ if (command.alias()) candidateNames.push(command.alias());
3130
+ });
3131
+ suggestion = suggestSimilar(unknownName, candidateNames);
3132
+ }
3133
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
3134
+ this.error(message, { code: "commander.unknownCommand" });
3135
+ }
3136
+ /**
3137
+ * Get or set the program version.
3138
+ *
3139
+ * This method auto-registers the "-V, --version" option which will print the version number.
3140
+ *
3141
+ * You can optionally supply the flags and description to override the defaults.
3142
+ *
3143
+ * @param {string} [str]
3144
+ * @param {string} [flags]
3145
+ * @param {string} [description]
3146
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
3147
+ */
3148
+ version(str, flags, description) {
3149
+ if (str === void 0) return this._version;
3150
+ this._version = str;
3151
+ flags = flags || "-V, --version";
3152
+ description = description || "output the version number";
3153
+ const versionOption = this.createOption(flags, description);
3154
+ this._versionOptionName = versionOption.attributeName();
3155
+ this._registerOption(versionOption);
3156
+ this.on("option:" + versionOption.name(), () => {
3157
+ this._outputConfiguration.writeOut(`${str}
3158
+ `);
3159
+ this._exit(0, "commander.version", str);
3160
+ });
3161
+ return this;
3162
+ }
3163
+ /**
3164
+ * Set the description.
3165
+ *
3166
+ * @param {string} [str]
3167
+ * @param {object} [argsDescription]
3168
+ * @return {(string|Command)}
3169
+ */
3170
+ description(str, argsDescription) {
3171
+ if (str === void 0 && argsDescription === void 0)
3172
+ return this._description;
3173
+ this._description = str;
3174
+ if (argsDescription) {
3175
+ this._argsDescription = argsDescription;
3176
+ }
3177
+ return this;
3178
+ }
3179
+ /**
3180
+ * Set the summary. Used when listed as subcommand of parent.
3181
+ *
3182
+ * @param {string} [str]
3183
+ * @return {(string|Command)}
3184
+ */
3185
+ summary(str) {
3186
+ if (str === void 0) return this._summary;
3187
+ this._summary = str;
3188
+ return this;
3189
+ }
3190
+ /**
3191
+ * Set an alias for the command.
3192
+ *
3193
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
3194
+ *
3195
+ * @param {string} [alias]
3196
+ * @return {(string|Command)}
3197
+ */
3198
+ alias(alias) {
3199
+ if (alias === void 0) return this._aliases[0];
3200
+ let command = this;
3201
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
3202
+ command = this.commands[this.commands.length - 1];
3203
+ }
3204
+ if (alias === command._name)
3205
+ throw new Error("Command alias can't be the same as its name");
3206
+ const matchingCommand = this.parent?._findCommand(alias);
3207
+ if (matchingCommand) {
3208
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
3209
+ throw new Error(
3210
+ `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`
3211
+ );
3212
+ }
3213
+ command._aliases.push(alias);
3214
+ return this;
3215
+ }
3216
+ /**
3217
+ * Set aliases for the command.
3218
+ *
3219
+ * Only the first alias is shown in the auto-generated help.
3220
+ *
3221
+ * @param {string[]} [aliases]
3222
+ * @return {(string[]|Command)}
3223
+ */
3224
+ aliases(aliases) {
3225
+ if (aliases === void 0) return this._aliases;
3226
+ aliases.forEach((alias) => this.alias(alias));
3227
+ return this;
3228
+ }
3229
+ /**
3230
+ * Set / get the command usage `str`.
3231
+ *
3232
+ * @param {string} [str]
3233
+ * @return {(string|Command)}
3234
+ */
3235
+ usage(str) {
3236
+ if (str === void 0) {
3237
+ if (this._usage) return this._usage;
3238
+ const args = this.registeredArguments.map((arg) => {
3239
+ return humanReadableArgName(arg);
3240
+ });
3241
+ return [].concat(
3242
+ this.options.length || this._helpOption !== null ? "[options]" : [],
3243
+ this.commands.length ? "[command]" : [],
3244
+ this.registeredArguments.length ? args : []
3245
+ ).join(" ");
3246
+ }
3247
+ this._usage = str;
3248
+ return this;
3249
+ }
3250
+ /**
3251
+ * Get or set the name of the command.
3252
+ *
3253
+ * @param {string} [str]
3254
+ * @return {(string|Command)}
3255
+ */
3256
+ name(str) {
3257
+ if (str === void 0) return this._name;
3258
+ this._name = str;
3259
+ return this;
3260
+ }
3261
+ /**
3262
+ * Set the name of the command from script filename, such as process.argv[1],
3263
+ * or require.main.filename, or __filename.
3264
+ *
3265
+ * (Used internally and public although not documented in README.)
3266
+ *
3267
+ * @example
3268
+ * program.nameFromFilename(require.main.filename);
3269
+ *
3270
+ * @param {string} filename
3271
+ * @return {Command}
3272
+ */
3273
+ nameFromFilename(filename) {
3274
+ this._name = path.basename(filename, path.extname(filename));
3275
+ return this;
3276
+ }
3277
+ /**
3278
+ * Get or set the directory for searching for executable subcommands of this command.
3279
+ *
3280
+ * @example
3281
+ * program.executableDir(__dirname);
3282
+ * // or
3283
+ * program.executableDir('subcommands');
3284
+ *
3285
+ * @param {string} [path]
3286
+ * @return {(string|null|Command)}
3287
+ */
3288
+ executableDir(path2) {
3289
+ if (path2 === void 0) return this._executableDir;
3290
+ this._executableDir = path2;
3291
+ return this;
3292
+ }
3293
+ /**
3294
+ * Return program help documentation.
3295
+ *
3296
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
3297
+ * @return {string}
3298
+ */
3299
+ helpInformation(contextOptions) {
3300
+ const helper = this.createHelp();
3301
+ const context = this._getOutputContext(contextOptions);
3302
+ helper.prepareContext({
3303
+ error: context.error,
3304
+ helpWidth: context.helpWidth,
3305
+ outputHasColors: context.hasColors
3306
+ });
3307
+ const text = helper.formatHelp(this, helper);
3308
+ if (context.hasColors) return text;
3309
+ return this._outputConfiguration.stripColor(text);
3310
+ }
3311
+ /**
3312
+ * @typedef HelpContext
3313
+ * @type {object}
3314
+ * @property {boolean} error
3315
+ * @property {number} helpWidth
3316
+ * @property {boolean} hasColors
3317
+ * @property {function} write - includes stripColor if needed
3318
+ *
3319
+ * @returns {HelpContext}
3320
+ * @private
3321
+ */
3322
+ _getOutputContext(contextOptions) {
3323
+ contextOptions = contextOptions || {};
3324
+ const error = !!contextOptions.error;
3325
+ let baseWrite;
3326
+ let hasColors;
3327
+ let helpWidth;
3328
+ if (error) {
3329
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
3330
+ hasColors = this._outputConfiguration.getErrHasColors();
3331
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
3332
+ } else {
3333
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
3334
+ hasColors = this._outputConfiguration.getOutHasColors();
3335
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
3336
+ }
3337
+ const write = (str) => {
3338
+ if (!hasColors) str = this._outputConfiguration.stripColor(str);
3339
+ return baseWrite(str);
3340
+ };
3341
+ return { error, write, hasColors, helpWidth };
3342
+ }
3343
+ /**
3344
+ * Output help information for this command.
3345
+ *
3346
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
3347
+ *
3348
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
3349
+ */
3350
+ outputHelp(contextOptions) {
3351
+ let deprecatedCallback;
3352
+ if (typeof contextOptions === "function") {
3353
+ deprecatedCallback = contextOptions;
3354
+ contextOptions = void 0;
3355
+ }
3356
+ const outputContext = this._getOutputContext(contextOptions);
3357
+ const eventContext = {
3358
+ error: outputContext.error,
3359
+ write: outputContext.write,
3360
+ command: this
3361
+ };
3362
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
3363
+ this.emit("beforeHelp", eventContext);
3364
+ let helpInformation = this.helpInformation({ error: outputContext.error });
3365
+ if (deprecatedCallback) {
3366
+ helpInformation = deprecatedCallback(helpInformation);
3367
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
3368
+ throw new Error("outputHelp callback must return a string or a Buffer");
3369
+ }
3370
+ }
3371
+ outputContext.write(helpInformation);
3372
+ if (this._getHelpOption()?.long) {
3373
+ this.emit(this._getHelpOption().long);
3374
+ }
3375
+ this.emit("afterHelp", eventContext);
3376
+ this._getCommandAndAncestors().forEach(
3377
+ (command) => command.emit("afterAllHelp", eventContext)
3378
+ );
3379
+ }
3380
+ /**
3381
+ * You can pass in flags and a description to customise the built-in help option.
3382
+ * Pass in false to disable the built-in help option.
3383
+ *
3384
+ * @example
3385
+ * program.helpOption('-?, --help' 'show help'); // customise
3386
+ * program.helpOption(false); // disable
3387
+ *
3388
+ * @param {(string | boolean)} flags
3389
+ * @param {string} [description]
3390
+ * @return {Command} `this` command for chaining
3391
+ */
3392
+ helpOption(flags, description) {
3393
+ if (typeof flags === "boolean") {
3394
+ if (flags) {
3395
+ this._helpOption = this._helpOption ?? void 0;
3396
+ } else {
3397
+ this._helpOption = null;
3398
+ }
3399
+ return this;
3400
+ }
3401
+ flags = flags ?? "-h, --help";
3402
+ description = description ?? "display help for command";
3403
+ this._helpOption = this.createOption(flags, description);
3404
+ return this;
3405
+ }
3406
+ /**
3407
+ * Lazy create help option.
3408
+ * Returns null if has been disabled with .helpOption(false).
3409
+ *
3410
+ * @returns {(Option | null)} the help option
3411
+ * @package
3412
+ */
3413
+ _getHelpOption() {
3414
+ if (this._helpOption === void 0) {
3415
+ this.helpOption(void 0, void 0);
3416
+ }
3417
+ return this._helpOption;
3418
+ }
3419
+ /**
3420
+ * Supply your own option to use for the built-in help option.
3421
+ * This is an alternative to using helpOption() to customise the flags and description etc.
3422
+ *
3423
+ * @param {Option} option
3424
+ * @return {Command} `this` command for chaining
3425
+ */
3426
+ addHelpOption(option) {
3427
+ this._helpOption = option;
3428
+ return this;
3429
+ }
3430
+ /**
3431
+ * Output help information and exit.
3432
+ *
3433
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
3434
+ *
3435
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
3436
+ */
3437
+ help(contextOptions) {
3438
+ this.outputHelp(contextOptions);
3439
+ let exitCode = Number(process2.exitCode ?? 0);
3440
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
3441
+ exitCode = 1;
3442
+ }
3443
+ this._exit(exitCode, "commander.help", "(outputHelp)");
3444
+ }
3445
+ /**
3446
+ * // Do a little typing to coordinate emit and listener for the help text events.
3447
+ * @typedef HelpTextEventContext
3448
+ * @type {object}
3449
+ * @property {boolean} error
3450
+ * @property {Command} command
3451
+ * @property {function} write
3452
+ */
3453
+ /**
3454
+ * Add additional text to be displayed with the built-in help.
3455
+ *
3456
+ * Position is 'before' or 'after' to affect just this command,
3457
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
3458
+ *
3459
+ * @param {string} position - before or after built-in help
3460
+ * @param {(string | Function)} text - string to add, or a function returning a string
3461
+ * @return {Command} `this` command for chaining
3462
+ */
3463
+ addHelpText(position, text) {
3464
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
3465
+ if (!allowedValues.includes(position)) {
3466
+ throw new Error(`Unexpected value for position to addHelpText.
3467
+ Expecting one of '${allowedValues.join("', '")}'`);
3468
+ }
3469
+ const helpEvent = `${position}Help`;
3470
+ this.on(helpEvent, (context) => {
3471
+ let helpStr;
3472
+ if (typeof text === "function") {
3473
+ helpStr = text({ error: context.error, command: context.command });
3474
+ } else {
3475
+ helpStr = text;
3476
+ }
3477
+ if (helpStr) {
3478
+ context.write(`${helpStr}
3479
+ `);
3480
+ }
3481
+ });
3482
+ return this;
3483
+ }
3484
+ /**
3485
+ * Output help information if help flags specified
3486
+ *
3487
+ * @param {Array} args - array of options to search for help flags
3488
+ * @private
3489
+ */
3490
+ _outputHelpIfRequested(args) {
3491
+ const helpOption = this._getHelpOption();
3492
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
3493
+ if (helpRequested) {
3494
+ this.outputHelp();
3495
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
3496
+ }
3497
+ }
3498
+ };
3499
+ function incrementNodeInspectorPort(args) {
3500
+ return args.map((arg) => {
3501
+ if (!arg.startsWith("--inspect")) {
3502
+ return arg;
3503
+ }
3504
+ let debugOption;
3505
+ let debugHost = "127.0.0.1";
3506
+ let debugPort = "9229";
3507
+ let match;
3508
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
3509
+ debugOption = match[1];
3510
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
3511
+ debugOption = match[1];
3512
+ if (/^\d+$/.test(match[3])) {
3513
+ debugPort = match[3];
3514
+ } else {
3515
+ debugHost = match[3];
3516
+ }
3517
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
3518
+ debugOption = match[1];
3519
+ debugHost = match[3];
3520
+ debugPort = match[4];
3521
+ }
3522
+ if (debugOption && debugPort !== "0") {
3523
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
3524
+ }
3525
+ return arg;
3526
+ });
3527
+ }
3528
+ function useColor() {
3529
+ if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
3530
+ return false;
3531
+ if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== void 0)
3532
+ return true;
3533
+ return void 0;
3534
+ }
3535
+ exports2.Command = Command;
3536
+ exports2.useColor = useColor;
3537
+ }
3538
+ });
3539
+
3540
+ // ../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/index.js
3541
+ var require_commander = __commonJS({
3542
+ "../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/index.js"(exports2) {
3543
+ "use strict";
3544
+ var { Argument } = require_argument();
3545
+ var { Command } = require_command();
3546
+ var { CommanderError, InvalidArgumentError } = require_error();
3547
+ var { Help } = require_help();
3548
+ var { Option } = require_option();
3549
+ exports2.program = new Command();
3550
+ exports2.createCommand = (name) => new Command(name);
3551
+ exports2.createOption = (flags, description) => new Option(flags, description);
3552
+ exports2.createArgument = (name, description) => new Argument(name, description);
3553
+ exports2.Command = Command;
3554
+ exports2.Option = Option;
3555
+ exports2.Argument = Argument;
3556
+ exports2.Help = Help;
3557
+ exports2.CommanderError = CommanderError;
3558
+ exports2.InvalidArgumentError = InvalidArgumentError;
3559
+ exports2.InvalidOptionArgumentError = InvalidArgumentError;
3560
+ }
3561
+ });
3562
+
263
3563
  // src/moose-runner.ts
264
3564
  var __create = Object.create;
265
3565
  var __defProp = Object.defineProperty;
@@ -3907,7 +7207,7 @@ async function runScripts(config) {
3907
7207
  }
3908
7208
  return worker;
3909
7209
  }
3910
- var import_commander = require("commander");
7210
+ var import_commander = require_commander();
3911
7211
  var packageJson = { version: "0.6.417" };
3912
7212
  var program = new import_commander.Command();
3913
7213
  program.name("moose-runner").description("Moose runner for various operations").version(packageJson.version);