blaze-performance-tester 3.2.41 → 3.2.43

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/cli.js +3577 -57
  2. package/package.json +6 -3
package/dist/cli.js CHANGED
@@ -858,7 +858,7 @@ function camelCase(str) {
858
858
  if (str.indexOf("-") === -1 && str.indexOf("_") === -1) {
859
859
  return str;
860
860
  } else {
861
- let camelcase = "";
861
+ let camelcase2 = "";
862
862
  let nextChrUpper = false;
863
863
  const leadingHyphens = str.match(/^-+/);
864
864
  for (let i = leadingHyphens ? leadingHyphens[0].length : 0; i < str.length; i++) {
@@ -870,10 +870,10 @@ function camelCase(str) {
870
870
  if (i !== 0 && (chr === "-" || chr === "_")) {
871
871
  nextChrUpper = true;
872
872
  } else if (chr !== "-" && chr !== "_") {
873
- camelcase += chr;
873
+ camelcase2 += chr;
874
874
  }
875
875
  }
876
- return camelcase;
876
+ return camelcase2;
877
877
  }
878
878
  }
879
879
  function decamelize(str, joinString) {
@@ -1808,11 +1808,11 @@ var parser = new YargsParser({
1808
1808
  format,
1809
1809
  normalize,
1810
1810
  resolve: resolve2,
1811
- require: (path2) => {
1811
+ require: (path3) => {
1812
1812
  if (typeof require2 !== "undefined") {
1813
- return require2(path2);
1814
- } else if (path2.match(/\.json$/)) {
1815
- return JSON.parse(readFileSync(path2, "utf8"));
1813
+ return require2(path3);
1814
+ } else if (path3.match(/\.json$/)) {
1815
+ return JSON.parse(readFileSync(path3, "utf8"));
1816
1816
  } else {
1817
1817
  throw Error("only .json config files are supported in ESM");
1818
1818
  }
@@ -5414,9 +5414,9 @@ var yargs_default = Yargs;
5414
5414
 
5415
5415
  // cli.ts
5416
5416
  import { createRequire as createRequire3 } from "module";
5417
- import * as path from "path";
5417
+ import * as path2 from "path";
5418
5418
  import { fileURLToPath as fileURLToPath2 } from "url";
5419
- import * as fs from "fs";
5419
+ import * as fs2 from "fs";
5420
5420
  import { GoogleGenAI } from "@google/genai";
5421
5421
 
5422
5422
  // src/LogAnalyzer.ts
@@ -5559,17 +5559,3436 @@ var LogAnalyzer = class {
5559
5559
  }
5560
5560
  };
5561
5561
 
5562
+ // node_modules/commander/lib/error.js
5563
+ var CommanderError = class extends Error {
5564
+ /**
5565
+ * Constructs the CommanderError class
5566
+ * @param {number} exitCode suggested exit code which could be used with process.exit
5567
+ * @param {string} code an id string representing the error
5568
+ * @param {string} message human-readable description of the error
5569
+ */
5570
+ constructor(exitCode, code, message) {
5571
+ super(message);
5572
+ Error.captureStackTrace(this, this.constructor);
5573
+ this.name = this.constructor.name;
5574
+ this.code = code;
5575
+ this.exitCode = exitCode;
5576
+ this.nestedError = void 0;
5577
+ }
5578
+ };
5579
+ var InvalidArgumentError = class extends CommanderError {
5580
+ /**
5581
+ * Constructs the InvalidArgumentError class
5582
+ * @param {string} [message] explanation of why argument is invalid
5583
+ */
5584
+ constructor(message) {
5585
+ super(1, "commander.invalidArgument", message);
5586
+ Error.captureStackTrace(this, this.constructor);
5587
+ this.name = this.constructor.name;
5588
+ }
5589
+ };
5590
+
5591
+ // node_modules/commander/lib/argument.js
5592
+ var Argument = class {
5593
+ /**
5594
+ * Initialize a new command argument with the given name and description.
5595
+ * The default is that the argument is required, and you can explicitly
5596
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
5597
+ *
5598
+ * @param {string} name
5599
+ * @param {string} [description]
5600
+ */
5601
+ constructor(name, description) {
5602
+ this.description = description || "";
5603
+ this.variadic = false;
5604
+ this.parseArg = void 0;
5605
+ this.defaultValue = void 0;
5606
+ this.defaultValueDescription = void 0;
5607
+ this.argChoices = void 0;
5608
+ switch (name[0]) {
5609
+ case "<":
5610
+ this.required = true;
5611
+ this._name = name.slice(1, -1);
5612
+ break;
5613
+ case "[":
5614
+ this.required = false;
5615
+ this._name = name.slice(1, -1);
5616
+ break;
5617
+ default:
5618
+ this.required = true;
5619
+ this._name = name;
5620
+ break;
5621
+ }
5622
+ if (this._name.endsWith("...")) {
5623
+ this.variadic = true;
5624
+ this._name = this._name.slice(0, -3);
5625
+ }
5626
+ }
5627
+ /**
5628
+ * Return argument name.
5629
+ *
5630
+ * @return {string}
5631
+ */
5632
+ name() {
5633
+ return this._name;
5634
+ }
5635
+ /**
5636
+ * @package
5637
+ */
5638
+ _collectValue(value, previous) {
5639
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
5640
+ return [value];
5641
+ }
5642
+ previous.push(value);
5643
+ return previous;
5644
+ }
5645
+ /**
5646
+ * Set the default value, and optionally supply the description to be displayed in the help.
5647
+ *
5648
+ * @param {*} value
5649
+ * @param {string} [description]
5650
+ * @return {Argument}
5651
+ */
5652
+ default(value, description) {
5653
+ this.defaultValue = value;
5654
+ this.defaultValueDescription = description;
5655
+ return this;
5656
+ }
5657
+ /**
5658
+ * Set the custom handler for processing CLI command arguments into argument values.
5659
+ *
5660
+ * @param {Function} [fn]
5661
+ * @return {Argument}
5662
+ */
5663
+ argParser(fn) {
5664
+ this.parseArg = fn;
5665
+ return this;
5666
+ }
5667
+ /**
5668
+ * Only allow argument value to be one of choices.
5669
+ *
5670
+ * @param {string[]} values
5671
+ * @return {Argument}
5672
+ */
5673
+ choices(values) {
5674
+ this.argChoices = values.slice();
5675
+ this.parseArg = (arg, previous) => {
5676
+ if (!this.argChoices.includes(arg)) {
5677
+ throw new InvalidArgumentError(
5678
+ `Allowed choices are ${this.argChoices.join(", ")}.`
5679
+ );
5680
+ }
5681
+ if (this.variadic) {
5682
+ return this._collectValue(arg, previous);
5683
+ }
5684
+ return arg;
5685
+ };
5686
+ return this;
5687
+ }
5688
+ /**
5689
+ * Make argument required.
5690
+ *
5691
+ * @returns {Argument}
5692
+ */
5693
+ argRequired() {
5694
+ this.required = true;
5695
+ return this;
5696
+ }
5697
+ /**
5698
+ * Make argument optional.
5699
+ *
5700
+ * @returns {Argument}
5701
+ */
5702
+ argOptional() {
5703
+ this.required = false;
5704
+ return this;
5705
+ }
5706
+ };
5707
+ function humanReadableArgName(arg) {
5708
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
5709
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
5710
+ }
5711
+
5712
+ // node_modules/commander/lib/command.js
5713
+ import { EventEmitter } from "node:events";
5714
+ import childProcess from "node:child_process";
5715
+ import path from "node:path";
5716
+ import fs from "node:fs";
5717
+ import process2 from "node:process";
5718
+ import { stripVTControlCharacters as stripVTControlCharacters2 } from "node:util";
5719
+
5720
+ // node_modules/commander/lib/help.js
5721
+ import { stripVTControlCharacters } from "node:util";
5722
+ var Help = class {
5723
+ constructor() {
5724
+ this.helpWidth = void 0;
5725
+ this.minWidthToWrap = 40;
5726
+ this.sortSubcommands = false;
5727
+ this.sortOptions = false;
5728
+ this.showGlobalOptions = false;
5729
+ }
5730
+ /**
5731
+ * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
5732
+ * and just before calling `formatHelp()`.
5733
+ *
5734
+ * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
5735
+ *
5736
+ * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
5737
+ */
5738
+ prepareContext(contextOptions) {
5739
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
5740
+ }
5741
+ /**
5742
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
5743
+ *
5744
+ * @param {Command} cmd
5745
+ * @returns {Command[]}
5746
+ */
5747
+ visibleCommands(cmd) {
5748
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
5749
+ const helpCommand = cmd._getHelpCommand();
5750
+ if (helpCommand && !helpCommand._hidden) {
5751
+ visibleCommands.push(helpCommand);
5752
+ }
5753
+ if (this.sortSubcommands) {
5754
+ visibleCommands.sort((a, b) => {
5755
+ return a.name().localeCompare(b.name());
5756
+ });
5757
+ }
5758
+ return visibleCommands;
5759
+ }
5760
+ /**
5761
+ * Compare options for sort.
5762
+ *
5763
+ * @param {Option} a
5764
+ * @param {Option} b
5765
+ * @returns {number}
5766
+ */
5767
+ compareOptions(a, b) {
5768
+ const getSortKey = (option) => {
5769
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
5770
+ };
5771
+ return getSortKey(a).localeCompare(getSortKey(b));
5772
+ }
5773
+ /**
5774
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
5775
+ *
5776
+ * @param {Command} cmd
5777
+ * @returns {Option[]}
5778
+ */
5779
+ visibleOptions(cmd) {
5780
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
5781
+ const helpOption = cmd._getHelpOption();
5782
+ if (helpOption && !helpOption.hidden) {
5783
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
5784
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
5785
+ if (!removeShort && !removeLong) {
5786
+ visibleOptions.push(helpOption);
5787
+ } else if (helpOption.long && !removeLong) {
5788
+ visibleOptions.push(
5789
+ cmd.createOption(helpOption.long, helpOption.description)
5790
+ );
5791
+ } else if (helpOption.short && !removeShort) {
5792
+ visibleOptions.push(
5793
+ cmd.createOption(helpOption.short, helpOption.description)
5794
+ );
5795
+ }
5796
+ }
5797
+ if (this.sortOptions) {
5798
+ visibleOptions.sort(this.compareOptions);
5799
+ }
5800
+ return visibleOptions;
5801
+ }
5802
+ /**
5803
+ * Get an array of the visible global options. (Not including help.)
5804
+ *
5805
+ * @param {Command} cmd
5806
+ * @returns {Option[]}
5807
+ */
5808
+ visibleGlobalOptions(cmd) {
5809
+ if (!this.showGlobalOptions)
5810
+ return [];
5811
+ const globalOptions = [];
5812
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
5813
+ const visibleOptions = ancestorCmd.options.filter(
5814
+ (option) => !option.hidden
5815
+ );
5816
+ globalOptions.push(...visibleOptions);
5817
+ }
5818
+ if (this.sortOptions) {
5819
+ globalOptions.sort(this.compareOptions);
5820
+ }
5821
+ return globalOptions;
5822
+ }
5823
+ /**
5824
+ * Get an array of the arguments if any have a description.
5825
+ *
5826
+ * @param {Command} cmd
5827
+ * @returns {Argument[]}
5828
+ */
5829
+ visibleArguments(cmd) {
5830
+ if (cmd._argsDescription) {
5831
+ cmd.registeredArguments.forEach((argument) => {
5832
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
5833
+ });
5834
+ }
5835
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
5836
+ return cmd.registeredArguments;
5837
+ }
5838
+ return [];
5839
+ }
5840
+ /**
5841
+ * Get the command term to show in the list of subcommands.
5842
+ *
5843
+ * @param {Command} cmd
5844
+ * @returns {string}
5845
+ */
5846
+ subcommandTerm(cmd) {
5847
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
5848
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
5849
+ (args ? " " + args : "");
5850
+ }
5851
+ /**
5852
+ * Get the option term to show in the list of options.
5853
+ *
5854
+ * @param {Option} option
5855
+ * @returns {string}
5856
+ */
5857
+ optionTerm(option) {
5858
+ return option.flags;
5859
+ }
5860
+ /**
5861
+ * Get the argument term to show in the list of arguments.
5862
+ *
5863
+ * @param {Argument} argument
5864
+ * @returns {string}
5865
+ */
5866
+ argumentTerm(argument) {
5867
+ return argument.name();
5868
+ }
5869
+ /**
5870
+ * Get the longest command term length.
5871
+ *
5872
+ * @param {Command} cmd
5873
+ * @param {Help} helper
5874
+ * @returns {number}
5875
+ */
5876
+ longestSubcommandTermLength(cmd, helper) {
5877
+ return helper.visibleCommands(cmd).reduce((max, command2) => {
5878
+ return Math.max(
5879
+ max,
5880
+ this.displayWidth(
5881
+ helper.styleSubcommandTerm(helper.subcommandTerm(command2))
5882
+ )
5883
+ );
5884
+ }, 0);
5885
+ }
5886
+ /**
5887
+ * Get the longest option term length.
5888
+ *
5889
+ * @param {Command} cmd
5890
+ * @param {Help} helper
5891
+ * @returns {number}
5892
+ */
5893
+ longestOptionTermLength(cmd, helper) {
5894
+ return helper.visibleOptions(cmd).reduce((max, option) => {
5895
+ return Math.max(
5896
+ max,
5897
+ this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
5898
+ );
5899
+ }, 0);
5900
+ }
5901
+ /**
5902
+ * Get the longest global option term length.
5903
+ *
5904
+ * @param {Command} cmd
5905
+ * @param {Help} helper
5906
+ * @returns {number}
5907
+ */
5908
+ longestGlobalOptionTermLength(cmd, helper) {
5909
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
5910
+ return Math.max(
5911
+ max,
5912
+ this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
5913
+ );
5914
+ }, 0);
5915
+ }
5916
+ /**
5917
+ * Get the longest argument term length.
5918
+ *
5919
+ * @param {Command} cmd
5920
+ * @param {Help} helper
5921
+ * @returns {number}
5922
+ */
5923
+ longestArgumentTermLength(cmd, helper) {
5924
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
5925
+ return Math.max(
5926
+ max,
5927
+ this.displayWidth(
5928
+ helper.styleArgumentTerm(helper.argumentTerm(argument))
5929
+ )
5930
+ );
5931
+ }, 0);
5932
+ }
5933
+ /**
5934
+ * Get the command usage to be displayed at the top of the built-in help.
5935
+ *
5936
+ * @param {Command} cmd
5937
+ * @returns {string}
5938
+ */
5939
+ commandUsage(cmd) {
5940
+ let cmdName = cmd._name;
5941
+ if (cmd._aliases[0]) {
5942
+ cmdName = cmdName + "|" + cmd._aliases[0];
5943
+ }
5944
+ let ancestorCmdNames = "";
5945
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
5946
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
5947
+ }
5948
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
5949
+ }
5950
+ /**
5951
+ * Get the description for the command.
5952
+ *
5953
+ * @param {Command} cmd
5954
+ * @returns {string}
5955
+ */
5956
+ commandDescription(cmd) {
5957
+ return cmd.description();
5958
+ }
5959
+ /**
5960
+ * Get the subcommand summary to show in the list of subcommands.
5961
+ * (Fallback to description for backwards compatibility.)
5962
+ *
5963
+ * @param {Command} cmd
5964
+ * @returns {string}
5965
+ */
5966
+ subcommandDescription(cmd) {
5967
+ return cmd.summary() || cmd.description();
5968
+ }
5969
+ /**
5970
+ * Get the option description to show in the list of options.
5971
+ *
5972
+ * @param {Option} option
5973
+ * @return {string}
5974
+ */
5975
+ optionDescription(option) {
5976
+ const extraInfo = [];
5977
+ if (option.argChoices) {
5978
+ extraInfo.push(
5979
+ // use stringify to match the display of the default value
5980
+ `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
5981
+ );
5982
+ }
5983
+ if (option.defaultValue !== void 0) {
5984
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
5985
+ if (showDefault) {
5986
+ extraInfo.push(
5987
+ `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`
5988
+ );
5989
+ }
5990
+ }
5991
+ if (option.presetArg !== void 0 && option.optional) {
5992
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
5993
+ }
5994
+ if (option.envVar !== void 0) {
5995
+ extraInfo.push(`env: ${option.envVar}`);
5996
+ }
5997
+ if (extraInfo.length > 0) {
5998
+ const extraDescription = `(${extraInfo.join(", ")})`;
5999
+ if (option.description) {
6000
+ return `${option.description} ${extraDescription}`;
6001
+ }
6002
+ return extraDescription;
6003
+ }
6004
+ return option.description;
6005
+ }
6006
+ /**
6007
+ * Get the argument description to show in the list of arguments.
6008
+ *
6009
+ * @param {Argument} argument
6010
+ * @return {string}
6011
+ */
6012
+ argumentDescription(argument) {
6013
+ const extraInfo = [];
6014
+ if (argument.argChoices) {
6015
+ extraInfo.push(
6016
+ // use stringify to match the display of the default value
6017
+ `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
6018
+ );
6019
+ }
6020
+ if (argument.defaultValue !== void 0) {
6021
+ extraInfo.push(
6022
+ `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`
6023
+ );
6024
+ }
6025
+ if (extraInfo.length > 0) {
6026
+ const extraDescription = `(${extraInfo.join(", ")})`;
6027
+ if (argument.description) {
6028
+ return `${argument.description} ${extraDescription}`;
6029
+ }
6030
+ return extraDescription;
6031
+ }
6032
+ return argument.description;
6033
+ }
6034
+ /**
6035
+ * Format a list of items, given a heading and an array of formatted items.
6036
+ *
6037
+ * @param {string} heading
6038
+ * @param {string[]} items
6039
+ * @param {Help} helper
6040
+ * @returns string[]
6041
+ */
6042
+ formatItemList(heading, items, helper) {
6043
+ if (items.length === 0)
6044
+ return [];
6045
+ return [helper.styleTitle(heading), ...items, ""];
6046
+ }
6047
+ /**
6048
+ * Group items by their help group heading.
6049
+ *
6050
+ * @param {Command[] | Option[]} unsortedItems
6051
+ * @param {Command[] | Option[]} visibleItems
6052
+ * @param {Function} getGroup
6053
+ * @returns {Map<string, Command[] | Option[]>}
6054
+ */
6055
+ groupItems(unsortedItems, visibleItems, getGroup) {
6056
+ const result = /* @__PURE__ */ new Map();
6057
+ unsortedItems.forEach((item) => {
6058
+ const group = getGroup(item);
6059
+ if (!result.has(group))
6060
+ result.set(group, []);
6061
+ });
6062
+ visibleItems.forEach((item) => {
6063
+ const group = getGroup(item);
6064
+ if (!result.has(group)) {
6065
+ result.set(group, []);
6066
+ }
6067
+ result.get(group).push(item);
6068
+ });
6069
+ return result;
6070
+ }
6071
+ /**
6072
+ * Generate the built-in help text.
6073
+ *
6074
+ * @param {Command} cmd
6075
+ * @param {Help} helper
6076
+ * @returns {string}
6077
+ */
6078
+ formatHelp(cmd, helper) {
6079
+ const termWidth = helper.padWidth(cmd, helper);
6080
+ const helpWidth = helper.helpWidth ?? 80;
6081
+ function callFormatItem(term, description) {
6082
+ return helper.formatItem(term, termWidth, description, helper);
6083
+ }
6084
+ let output = [
6085
+ `${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
6086
+ ""
6087
+ ];
6088
+ const commandDescription = helper.commandDescription(cmd);
6089
+ if (commandDescription.length > 0) {
6090
+ output = output.concat([
6091
+ helper.boxWrap(
6092
+ helper.styleCommandDescription(commandDescription),
6093
+ helpWidth
6094
+ ),
6095
+ ""
6096
+ ]);
6097
+ }
6098
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
6099
+ return callFormatItem(
6100
+ helper.styleArgumentTerm(helper.argumentTerm(argument)),
6101
+ helper.styleArgumentDescription(helper.argumentDescription(argument))
6102
+ );
6103
+ });
6104
+ output = output.concat(
6105
+ this.formatItemList("Arguments:", argumentList, helper)
6106
+ );
6107
+ const optionGroups = this.groupItems(
6108
+ cmd.options,
6109
+ helper.visibleOptions(cmd),
6110
+ (option) => option.helpGroupHeading ?? "Options:"
6111
+ );
6112
+ optionGroups.forEach((options, group) => {
6113
+ const optionList = options.map((option) => {
6114
+ return callFormatItem(
6115
+ helper.styleOptionTerm(helper.optionTerm(option)),
6116
+ helper.styleOptionDescription(helper.optionDescription(option))
6117
+ );
6118
+ });
6119
+ output = output.concat(this.formatItemList(group, optionList, helper));
6120
+ });
6121
+ if (helper.showGlobalOptions) {
6122
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
6123
+ return callFormatItem(
6124
+ helper.styleOptionTerm(helper.optionTerm(option)),
6125
+ helper.styleOptionDescription(helper.optionDescription(option))
6126
+ );
6127
+ });
6128
+ output = output.concat(
6129
+ this.formatItemList("Global Options:", globalOptionList, helper)
6130
+ );
6131
+ }
6132
+ const commandGroups = this.groupItems(
6133
+ cmd.commands,
6134
+ helper.visibleCommands(cmd),
6135
+ (sub) => sub.helpGroup() || "Commands:"
6136
+ );
6137
+ commandGroups.forEach((commands, group) => {
6138
+ const commandList = commands.map((sub) => {
6139
+ return callFormatItem(
6140
+ helper.styleSubcommandTerm(helper.subcommandTerm(sub)),
6141
+ helper.styleSubcommandDescription(helper.subcommandDescription(sub))
6142
+ );
6143
+ });
6144
+ output = output.concat(this.formatItemList(group, commandList, helper));
6145
+ });
6146
+ return output.join("\n");
6147
+ }
6148
+ /**
6149
+ * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
6150
+ *
6151
+ * @param {string} str
6152
+ * @returns {number}
6153
+ */
6154
+ displayWidth(str) {
6155
+ return stripVTControlCharacters(str).length;
6156
+ }
6157
+ /**
6158
+ * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
6159
+ *
6160
+ * @param {string} str
6161
+ * @returns {string}
6162
+ */
6163
+ styleTitle(str) {
6164
+ return str;
6165
+ }
6166
+ styleUsage(str) {
6167
+ return str.split(" ").map((word) => {
6168
+ if (word === "[options]")
6169
+ return this.styleOptionText(word);
6170
+ if (word === "[command]")
6171
+ return this.styleSubcommandText(word);
6172
+ if (word[0] === "[" || word[0] === "<")
6173
+ return this.styleArgumentText(word);
6174
+ return this.styleCommandText(word);
6175
+ }).join(" ");
6176
+ }
6177
+ styleCommandDescription(str) {
6178
+ return this.styleDescriptionText(str);
6179
+ }
6180
+ styleOptionDescription(str) {
6181
+ return this.styleDescriptionText(str);
6182
+ }
6183
+ styleSubcommandDescription(str) {
6184
+ return this.styleDescriptionText(str);
6185
+ }
6186
+ styleArgumentDescription(str) {
6187
+ return this.styleDescriptionText(str);
6188
+ }
6189
+ styleDescriptionText(str) {
6190
+ return str;
6191
+ }
6192
+ styleOptionTerm(str) {
6193
+ return this.styleOptionText(str);
6194
+ }
6195
+ styleSubcommandTerm(str) {
6196
+ return str.split(" ").map((word) => {
6197
+ if (word === "[options]")
6198
+ return this.styleOptionText(word);
6199
+ if (word[0] === "[" || word[0] === "<")
6200
+ return this.styleArgumentText(word);
6201
+ return this.styleSubcommandText(word);
6202
+ }).join(" ");
6203
+ }
6204
+ styleArgumentTerm(str) {
6205
+ return this.styleArgumentText(str);
6206
+ }
6207
+ styleOptionText(str) {
6208
+ return str;
6209
+ }
6210
+ styleArgumentText(str) {
6211
+ return str;
6212
+ }
6213
+ styleSubcommandText(str) {
6214
+ return str;
6215
+ }
6216
+ styleCommandText(str) {
6217
+ return str;
6218
+ }
6219
+ /**
6220
+ * Calculate the pad width from the maximum term length.
6221
+ *
6222
+ * @param {Command} cmd
6223
+ * @param {Help} helper
6224
+ * @returns {number}
6225
+ */
6226
+ padWidth(cmd, helper) {
6227
+ return Math.max(
6228
+ helper.longestOptionTermLength(cmd, helper),
6229
+ helper.longestGlobalOptionTermLength(cmd, helper),
6230
+ helper.longestSubcommandTermLength(cmd, helper),
6231
+ helper.longestArgumentTermLength(cmd, helper)
6232
+ );
6233
+ }
6234
+ /**
6235
+ * Detect manually wrapped and indented strings by checking for line break followed by whitespace.
6236
+ *
6237
+ * @param {string} str
6238
+ * @returns {boolean}
6239
+ */
6240
+ preformatted(str) {
6241
+ return /\n[^\S\r\n]/.test(str);
6242
+ }
6243
+ /**
6244
+ * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
6245
+ *
6246
+ * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
6247
+ * TTT DDD DDDD
6248
+ * DD DDD
6249
+ *
6250
+ * @param {string} term
6251
+ * @param {number} termWidth
6252
+ * @param {string} description
6253
+ * @param {Help} helper
6254
+ * @returns {string}
6255
+ */
6256
+ formatItem(term, termWidth, description, helper) {
6257
+ const itemIndent = 2;
6258
+ const itemIndentStr = " ".repeat(itemIndent);
6259
+ if (!description)
6260
+ return itemIndentStr + term;
6261
+ const paddedTerm = term.padEnd(
6262
+ termWidth + term.length - helper.displayWidth(term)
6263
+ );
6264
+ const spacerWidth = 2;
6265
+ const helpWidth = this.helpWidth ?? 80;
6266
+ const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
6267
+ let formattedDescription;
6268
+ if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
6269
+ formattedDescription = description;
6270
+ } else {
6271
+ const wrappedDescription = helper.boxWrap(description, remainingWidth);
6272
+ formattedDescription = wrappedDescription.replace(
6273
+ /\n/g,
6274
+ "\n" + " ".repeat(termWidth + spacerWidth)
6275
+ );
6276
+ }
6277
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
6278
+ ${itemIndentStr}`);
6279
+ }
6280
+ /**
6281
+ * Wrap a string at whitespace, preserving existing line breaks.
6282
+ * Wrapping is skipped if the width is less than `minWidthToWrap`.
6283
+ *
6284
+ * @param {string} str
6285
+ * @param {number} width
6286
+ * @returns {string}
6287
+ */
6288
+ boxWrap(str, width) {
6289
+ if (width < this.minWidthToWrap)
6290
+ return str;
6291
+ const rawLines = str.split(/\r\n|\n/);
6292
+ const chunkPattern = /[\s]*[^\s]+/g;
6293
+ const wrappedLines = [];
6294
+ rawLines.forEach((line) => {
6295
+ const chunks = line.match(chunkPattern);
6296
+ if (chunks === null) {
6297
+ wrappedLines.push("");
6298
+ return;
6299
+ }
6300
+ let sumChunks = [chunks.shift()];
6301
+ let sumWidth = this.displayWidth(sumChunks[0]);
6302
+ chunks.forEach((chunk) => {
6303
+ const visibleWidth = this.displayWidth(chunk);
6304
+ if (sumWidth + visibleWidth <= width) {
6305
+ sumChunks.push(chunk);
6306
+ sumWidth += visibleWidth;
6307
+ return;
6308
+ }
6309
+ wrappedLines.push(sumChunks.join(""));
6310
+ const nextChunk = chunk.trimStart();
6311
+ sumChunks = [nextChunk];
6312
+ sumWidth = this.displayWidth(nextChunk);
6313
+ });
6314
+ wrappedLines.push(sumChunks.join(""));
6315
+ });
6316
+ return wrappedLines.join("\n");
6317
+ }
6318
+ };
6319
+
6320
+ // node_modules/commander/lib/option.js
6321
+ var Option = class {
6322
+ /**
6323
+ * Initialize a new `Option` with the given `flags` and `description`.
6324
+ *
6325
+ * @param {string} flags
6326
+ * @param {string} [description]
6327
+ */
6328
+ constructor(flags, description) {
6329
+ this.flags = flags;
6330
+ this.description = description || "";
6331
+ this.required = flags.includes("<");
6332
+ this.optional = flags.includes("[");
6333
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
6334
+ this.mandatory = false;
6335
+ const optionFlags = splitOptionFlags(flags);
6336
+ this.short = optionFlags.shortFlag;
6337
+ this.long = optionFlags.longFlag;
6338
+ this.negate = false;
6339
+ if (this.long) {
6340
+ this.negate = this.long.startsWith("--no-");
6341
+ }
6342
+ this.defaultValue = void 0;
6343
+ this.defaultValueDescription = void 0;
6344
+ this.presetArg = void 0;
6345
+ this.envVar = void 0;
6346
+ this.parseArg = void 0;
6347
+ this.hidden = false;
6348
+ this.argChoices = void 0;
6349
+ this.conflictsWith = [];
6350
+ this.implied = void 0;
6351
+ this.helpGroupHeading = void 0;
6352
+ }
6353
+ /**
6354
+ * Set the default value, and optionally supply the description to be displayed in the help.
6355
+ *
6356
+ * @param {*} value
6357
+ * @param {string} [description]
6358
+ * @return {Option}
6359
+ */
6360
+ default(value, description) {
6361
+ this.defaultValue = value;
6362
+ this.defaultValueDescription = description;
6363
+ return this;
6364
+ }
6365
+ /**
6366
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
6367
+ * The custom processing (parseArg) is called.
6368
+ *
6369
+ * @example
6370
+ * new Option('--color').default('GREYSCALE').preset('RGB');
6371
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
6372
+ *
6373
+ * @param {*} arg
6374
+ * @return {Option}
6375
+ */
6376
+ preset(arg) {
6377
+ this.presetArg = arg;
6378
+ return this;
6379
+ }
6380
+ /**
6381
+ * Add option name(s) that conflict with this option.
6382
+ * An error will be displayed if conflicting options are found during parsing.
6383
+ *
6384
+ * @example
6385
+ * new Option('--rgb').conflicts('cmyk');
6386
+ * new Option('--js').conflicts(['ts', 'jsx']);
6387
+ *
6388
+ * @param {(string | string[])} names
6389
+ * @return {Option}
6390
+ */
6391
+ conflicts(names) {
6392
+ this.conflictsWith = this.conflictsWith.concat(names);
6393
+ return this;
6394
+ }
6395
+ /**
6396
+ * Specify implied option values for when this option is set and the implied options are not.
6397
+ *
6398
+ * The custom processing (parseArg) is not called on the implied values.
6399
+ *
6400
+ * @example
6401
+ * program
6402
+ * .addOption(new Option('--log', 'write logging information to file'))
6403
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
6404
+ *
6405
+ * @param {object} impliedOptionValues
6406
+ * @return {Option}
6407
+ */
6408
+ implies(impliedOptionValues) {
6409
+ let newImplied = impliedOptionValues;
6410
+ if (typeof impliedOptionValues === "string") {
6411
+ newImplied = { [impliedOptionValues]: true };
6412
+ }
6413
+ this.implied = Object.assign(this.implied || {}, newImplied);
6414
+ return this;
6415
+ }
6416
+ /**
6417
+ * Set environment variable to check for option value.
6418
+ *
6419
+ * An environment variable is only used if when processed the current option value is
6420
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
6421
+ *
6422
+ * @param {string} name
6423
+ * @return {Option}
6424
+ */
6425
+ env(name) {
6426
+ this.envVar = name;
6427
+ return this;
6428
+ }
6429
+ /**
6430
+ * Set the custom handler for processing CLI option arguments into option values.
6431
+ *
6432
+ * @param {Function} [fn]
6433
+ * @return {Option}
6434
+ */
6435
+ argParser(fn) {
6436
+ this.parseArg = fn;
6437
+ return this;
6438
+ }
6439
+ /**
6440
+ * Whether the option is mandatory and must have a value after parsing.
6441
+ *
6442
+ * @param {boolean} [mandatory=true]
6443
+ * @return {Option}
6444
+ */
6445
+ makeOptionMandatory(mandatory = true) {
6446
+ this.mandatory = !!mandatory;
6447
+ return this;
6448
+ }
6449
+ /**
6450
+ * Hide option in help.
6451
+ *
6452
+ * @param {boolean} [hide=true]
6453
+ * @return {Option}
6454
+ */
6455
+ hideHelp(hide = true) {
6456
+ this.hidden = !!hide;
6457
+ return this;
6458
+ }
6459
+ /**
6460
+ * @package
6461
+ */
6462
+ _collectValue(value, previous) {
6463
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
6464
+ return [value];
6465
+ }
6466
+ previous.push(value);
6467
+ return previous;
6468
+ }
6469
+ /**
6470
+ * Only allow option value to be one of choices.
6471
+ *
6472
+ * @param {string[]} values
6473
+ * @return {Option}
6474
+ */
6475
+ choices(values) {
6476
+ this.argChoices = values.slice();
6477
+ this.parseArg = (arg, previous) => {
6478
+ if (!this.argChoices.includes(arg)) {
6479
+ throw new InvalidArgumentError(
6480
+ `Allowed choices are ${this.argChoices.join(", ")}.`
6481
+ );
6482
+ }
6483
+ if (this.variadic) {
6484
+ return this._collectValue(arg, previous);
6485
+ }
6486
+ return arg;
6487
+ };
6488
+ return this;
6489
+ }
6490
+ /**
6491
+ * Return option name.
6492
+ *
6493
+ * @return {string}
6494
+ */
6495
+ name() {
6496
+ if (this.long) {
6497
+ return this.long.replace(/^--/, "");
6498
+ }
6499
+ return this.short.replace(/^-/, "");
6500
+ }
6501
+ /**
6502
+ * Return option name, in a camelcase format that can be used
6503
+ * as an object attribute key.
6504
+ *
6505
+ * @return {string}
6506
+ */
6507
+ attributeName() {
6508
+ if (this.negate) {
6509
+ return camelcase(this.name().replace(/^no-/, ""));
6510
+ }
6511
+ return camelcase(this.name());
6512
+ }
6513
+ /**
6514
+ * Set the help group heading.
6515
+ *
6516
+ * @param {string} heading
6517
+ * @return {Option}
6518
+ */
6519
+ helpGroup(heading) {
6520
+ this.helpGroupHeading = heading;
6521
+ return this;
6522
+ }
6523
+ /**
6524
+ * Check if `arg` matches the short or long flag.
6525
+ *
6526
+ * @param {string} arg
6527
+ * @return {boolean}
6528
+ * @package
6529
+ */
6530
+ is(arg) {
6531
+ return this.short === arg || this.long === arg;
6532
+ }
6533
+ /**
6534
+ * Return whether a boolean option.
6535
+ *
6536
+ * Options are one of boolean, negated, required argument, or optional argument.
6537
+ *
6538
+ * @return {boolean}
6539
+ * @package
6540
+ */
6541
+ isBoolean() {
6542
+ return !this.required && !this.optional && !this.negate;
6543
+ }
6544
+ };
6545
+ var DualOptions = class {
6546
+ /**
6547
+ * @param {Option[]} options
6548
+ */
6549
+ constructor(options) {
6550
+ this.positiveOptions = /* @__PURE__ */ new Map();
6551
+ this.negativeOptions = /* @__PURE__ */ new Map();
6552
+ this.dualOptions = /* @__PURE__ */ new Set();
6553
+ options.forEach((option) => {
6554
+ if (option.negate) {
6555
+ this.negativeOptions.set(option.attributeName(), option);
6556
+ } else {
6557
+ this.positiveOptions.set(option.attributeName(), option);
6558
+ }
6559
+ });
6560
+ this.negativeOptions.forEach((value, key) => {
6561
+ if (this.positiveOptions.has(key)) {
6562
+ this.dualOptions.add(key);
6563
+ }
6564
+ });
6565
+ }
6566
+ /**
6567
+ * Did the value come from the option, and not from possible matching dual option?
6568
+ *
6569
+ * @param {*} value
6570
+ * @param {Option} option
6571
+ * @returns {boolean}
6572
+ */
6573
+ valueFromOption(value, option) {
6574
+ const optionKey = option.attributeName();
6575
+ if (!this.dualOptions.has(optionKey))
6576
+ return true;
6577
+ const preset = this.negativeOptions.get(optionKey).presetArg;
6578
+ const negativeValue = preset !== void 0 ? preset : false;
6579
+ return option.negate === (negativeValue === value);
6580
+ }
6581
+ };
6582
+ function camelcase(str) {
6583
+ return str.split("-").reduce((str2, word) => {
6584
+ return str2 + word[0].toUpperCase() + word.slice(1);
6585
+ });
6586
+ }
6587
+ function splitOptionFlags(flags) {
6588
+ let shortFlag;
6589
+ let longFlag;
6590
+ const shortFlagExp = /^-[^-]$/;
6591
+ const longFlagExp = /^--[^-]/;
6592
+ const flagParts = flags.split(/[ |,]+/).concat("guard");
6593
+ if (shortFlagExp.test(flagParts[0]))
6594
+ shortFlag = flagParts.shift();
6595
+ if (longFlagExp.test(flagParts[0]))
6596
+ longFlag = flagParts.shift();
6597
+ if (!shortFlag && shortFlagExp.test(flagParts[0]))
6598
+ shortFlag = flagParts.shift();
6599
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
6600
+ shortFlag = longFlag;
6601
+ longFlag = flagParts.shift();
6602
+ }
6603
+ if (flagParts[0].startsWith("-")) {
6604
+ const unsupportedFlag = flagParts[0];
6605
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
6606
+ if (/^-[^-][^-]/.test(unsupportedFlag))
6607
+ throw new Error(
6608
+ `${baseError}
6609
+ - a short flag is a single dash and a single character
6610
+ - either use a single dash and a single character (for a short flag)
6611
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`
6612
+ );
6613
+ if (shortFlagExp.test(unsupportedFlag))
6614
+ throw new Error(`${baseError}
6615
+ - too many short flags`);
6616
+ if (longFlagExp.test(unsupportedFlag))
6617
+ throw new Error(`${baseError}
6618
+ - too many long flags`);
6619
+ throw new Error(`${baseError}
6620
+ - unrecognised flag format`);
6621
+ }
6622
+ if (shortFlag === void 0 && longFlag === void 0)
6623
+ throw new Error(
6624
+ `option creation failed due to no flags found in '${flags}'.`
6625
+ );
6626
+ return { shortFlag, longFlag };
6627
+ }
6628
+
6629
+ // node_modules/commander/lib/suggestSimilar.js
6630
+ var maxDistance = 3;
6631
+ function editDistance(a, b) {
6632
+ if (Math.abs(a.length - b.length) > maxDistance)
6633
+ return Math.max(a.length, b.length);
6634
+ const d = [];
6635
+ for (let i = 0; i <= a.length; i++) {
6636
+ d[i] = [i];
6637
+ }
6638
+ for (let j = 0; j <= b.length; j++) {
6639
+ d[0][j] = j;
6640
+ }
6641
+ for (let j = 1; j <= b.length; j++) {
6642
+ for (let i = 1; i <= a.length; i++) {
6643
+ let cost;
6644
+ if (a[i - 1] === b[j - 1]) {
6645
+ cost = 0;
6646
+ } else {
6647
+ cost = 1;
6648
+ }
6649
+ d[i][j] = Math.min(
6650
+ d[i - 1][j] + 1,
6651
+ // deletion
6652
+ d[i][j - 1] + 1,
6653
+ // insertion
6654
+ d[i - 1][j - 1] + cost
6655
+ // substitution
6656
+ );
6657
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
6658
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
6659
+ }
6660
+ }
6661
+ }
6662
+ return d[a.length][b.length];
6663
+ }
6664
+ function suggestSimilar(word, candidates) {
6665
+ if (!candidates || candidates.length === 0)
6666
+ return "";
6667
+ candidates = Array.from(new Set(candidates));
6668
+ const searchingOptions = word.startsWith("--");
6669
+ if (searchingOptions) {
6670
+ word = word.slice(2);
6671
+ candidates = candidates.map((candidate) => candidate.slice(2));
6672
+ }
6673
+ let similar = [];
6674
+ let bestDistance = maxDistance;
6675
+ const minSimilarity = 0.4;
6676
+ candidates.forEach((candidate) => {
6677
+ if (candidate.length <= 1)
6678
+ return;
6679
+ const distance = editDistance(word, candidate);
6680
+ const length = Math.max(word.length, candidate.length);
6681
+ const similarity = (length - distance) / length;
6682
+ if (similarity > minSimilarity) {
6683
+ if (distance < bestDistance) {
6684
+ bestDistance = distance;
6685
+ similar = [candidate];
6686
+ } else if (distance === bestDistance) {
6687
+ similar.push(candidate);
6688
+ }
6689
+ }
6690
+ });
6691
+ similar.sort((a, b) => a.localeCompare(b));
6692
+ if (searchingOptions) {
6693
+ similar = similar.map((candidate) => `--${candidate}`);
6694
+ }
6695
+ if (similar.length > 1) {
6696
+ return `
6697
+ (Did you mean one of ${similar.join(", ")}?)`;
6698
+ }
6699
+ if (similar.length === 1) {
6700
+ return `
6701
+ (Did you mean ${similar[0]}?)`;
6702
+ }
6703
+ return "";
6704
+ }
6705
+
6706
+ // node_modules/commander/lib/command.js
6707
+ var Command = class _Command extends EventEmitter {
6708
+ /**
6709
+ * Initialize a new `Command`.
6710
+ *
6711
+ * @param {string} [name]
6712
+ */
6713
+ constructor(name) {
6714
+ super();
6715
+ this.commands = [];
6716
+ this.options = [];
6717
+ this.parent = null;
6718
+ this._allowUnknownOption = false;
6719
+ this._allowExcessArguments = false;
6720
+ this.registeredArguments = [];
6721
+ this._args = this.registeredArguments;
6722
+ this.args = [];
6723
+ this.rawArgs = [];
6724
+ this.processedArgs = [];
6725
+ this._scriptPath = null;
6726
+ this._name = name || "";
6727
+ this._optionValues = {};
6728
+ this._optionValueSources = {};
6729
+ this._storeOptionsAsProperties = false;
6730
+ this._actionHandler = null;
6731
+ this._executableHandler = false;
6732
+ this._executableFile = null;
6733
+ this._executableDir = null;
6734
+ this._defaultCommandName = null;
6735
+ this._exitCallback = null;
6736
+ this._aliases = [];
6737
+ this._combineFlagAndOptionalValue = true;
6738
+ this._description = "";
6739
+ this._summary = "";
6740
+ this._argsDescription = void 0;
6741
+ this._enablePositionalOptions = false;
6742
+ this._passThroughOptions = false;
6743
+ this._lifeCycleHooks = {};
6744
+ this._showHelpAfterError = false;
6745
+ this._showSuggestionAfterError = true;
6746
+ this._savedState = null;
6747
+ this._outputConfiguration = {
6748
+ writeOut: (str) => process2.stdout.write(str),
6749
+ writeErr: (str) => process2.stderr.write(str),
6750
+ outputError: (str, write) => write(str),
6751
+ getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : void 0,
6752
+ getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : void 0,
6753
+ getOutHasColors: () => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()),
6754
+ getErrHasColors: () => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()),
6755
+ stripColor: (str) => stripVTControlCharacters2(str)
6756
+ };
6757
+ this._hidden = false;
6758
+ this._helpOption = void 0;
6759
+ this._addImplicitHelpCommand = void 0;
6760
+ this._helpCommand = void 0;
6761
+ this._helpConfiguration = {};
6762
+ this._helpGroupHeading = void 0;
6763
+ this._defaultCommandGroup = void 0;
6764
+ this._defaultOptionGroup = void 0;
6765
+ }
6766
+ /**
6767
+ * Copy settings that are useful to have in common across root command and subcommands.
6768
+ *
6769
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
6770
+ *
6771
+ * @param {Command} sourceCommand
6772
+ * @return {Command} `this` command for chaining
6773
+ */
6774
+ copyInheritedSettings(sourceCommand) {
6775
+ this._outputConfiguration = sourceCommand._outputConfiguration;
6776
+ this._helpOption = sourceCommand._helpOption;
6777
+ this._helpCommand = sourceCommand._helpCommand;
6778
+ this._helpConfiguration = sourceCommand._helpConfiguration;
6779
+ this._exitCallback = sourceCommand._exitCallback;
6780
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
6781
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
6782
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
6783
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
6784
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
6785
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
6786
+ return this;
6787
+ }
6788
+ /**
6789
+ * @returns {Command[]}
6790
+ * @private
6791
+ */
6792
+ _getCommandAndAncestors() {
6793
+ const result = [];
6794
+ for (let command2 = this; command2; command2 = command2.parent) {
6795
+ result.push(command2);
6796
+ }
6797
+ return result;
6798
+ }
6799
+ /**
6800
+ * Define a command.
6801
+ *
6802
+ * There are two styles of command: pay attention to where to put the description.
6803
+ *
6804
+ * @example
6805
+ * // Command implemented using action handler (description is supplied separately to `.command`)
6806
+ * program
6807
+ * .command('clone <source> [destination]')
6808
+ * .description('clone a repository into a newly created directory')
6809
+ * .action((source, destination) => {
6810
+ * console.log('clone command called');
6811
+ * });
6812
+ *
6813
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
6814
+ * program
6815
+ * .command('start <service>', 'start named service')
6816
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
6817
+ *
6818
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
6819
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
6820
+ * @param {object} [execOpts] - configuration options (for executable)
6821
+ * @return {Command} returns new command for action handler, or `this` for executable command
6822
+ */
6823
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
6824
+ let desc = actionOptsOrExecDesc;
6825
+ let opts = execOpts;
6826
+ if (typeof desc === "object" && desc !== null) {
6827
+ opts = desc;
6828
+ desc = null;
6829
+ }
6830
+ opts = opts || {};
6831
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
6832
+ const cmd = this.createCommand(name);
6833
+ if (desc) {
6834
+ cmd.description(desc);
6835
+ cmd._executableHandler = true;
6836
+ }
6837
+ if (opts.isDefault)
6838
+ this._defaultCommandName = cmd._name;
6839
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
6840
+ cmd._executableFile = opts.executableFile || null;
6841
+ if (args)
6842
+ cmd.arguments(args);
6843
+ this._registerCommand(cmd);
6844
+ cmd.parent = this;
6845
+ cmd.copyInheritedSettings(this);
6846
+ if (desc)
6847
+ return this;
6848
+ return cmd;
6849
+ }
6850
+ /**
6851
+ * Factory routine to create a new unattached command.
6852
+ *
6853
+ * See .command() for creating an attached subcommand, which uses this routine to
6854
+ * create the command. You can override createCommand to customise subcommands.
6855
+ *
6856
+ * @param {string} [name]
6857
+ * @return {Command} new command
6858
+ */
6859
+ createCommand(name) {
6860
+ return new _Command(name);
6861
+ }
6862
+ /**
6863
+ * You can customise the help with a subclass of Help by overriding createHelp,
6864
+ * or by overriding Help properties using configureHelp().
6865
+ *
6866
+ * @return {Help}
6867
+ */
6868
+ createHelp() {
6869
+ return Object.assign(new Help(), this.configureHelp());
6870
+ }
6871
+ /**
6872
+ * You can customise the help by overriding Help properties using configureHelp(),
6873
+ * or with a subclass of Help by overriding createHelp().
6874
+ *
6875
+ * @param {object} [configuration] - configuration options
6876
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
6877
+ */
6878
+ configureHelp(configuration) {
6879
+ if (configuration === void 0)
6880
+ return this._helpConfiguration;
6881
+ this._helpConfiguration = configuration;
6882
+ return this;
6883
+ }
6884
+ /**
6885
+ * The default output goes to stdout and stderr. You can customise this for special
6886
+ * applications. You can also customise the display of errors by overriding outputError.
6887
+ *
6888
+ * The configuration properties are all functions:
6889
+ *
6890
+ * // change how output being written, defaults to stdout and stderr
6891
+ * writeOut(str)
6892
+ * writeErr(str)
6893
+ * // change how output being written for errors, defaults to writeErr
6894
+ * outputError(str, write) // used for displaying errors and not used for displaying help
6895
+ * // specify width for wrapping help
6896
+ * getOutHelpWidth()
6897
+ * getErrHelpWidth()
6898
+ * // color support, currently only used with Help
6899
+ * getOutHasColors()
6900
+ * getErrHasColors()
6901
+ * stripColor() // used to remove ANSI escape codes if output does not have colors
6902
+ *
6903
+ * @param {object} [configuration] - configuration options
6904
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
6905
+ */
6906
+ configureOutput(configuration) {
6907
+ if (configuration === void 0)
6908
+ return this._outputConfiguration;
6909
+ this._outputConfiguration = {
6910
+ ...this._outputConfiguration,
6911
+ ...configuration
6912
+ };
6913
+ return this;
6914
+ }
6915
+ /**
6916
+ * Display the help or a custom message after an error occurs.
6917
+ *
6918
+ * @param {(boolean|string)} [displayHelp]
6919
+ * @return {Command} `this` command for chaining
6920
+ */
6921
+ showHelpAfterError(displayHelp = true) {
6922
+ if (typeof displayHelp !== "string")
6923
+ displayHelp = !!displayHelp;
6924
+ this._showHelpAfterError = displayHelp;
6925
+ return this;
6926
+ }
6927
+ /**
6928
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
6929
+ *
6930
+ * @param {boolean} [displaySuggestion]
6931
+ * @return {Command} `this` command for chaining
6932
+ */
6933
+ showSuggestionAfterError(displaySuggestion = true) {
6934
+ this._showSuggestionAfterError = !!displaySuggestion;
6935
+ return this;
6936
+ }
6937
+ /**
6938
+ * Add a prepared subcommand.
6939
+ *
6940
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
6941
+ *
6942
+ * @param {Command} cmd - new subcommand
6943
+ * @param {object} [opts] - configuration options
6944
+ * @return {Command} `this` command for chaining
6945
+ */
6946
+ addCommand(cmd, opts) {
6947
+ if (!cmd._name) {
6948
+ throw new Error(`Command passed to .addCommand() must have a name
6949
+ - specify the name in Command constructor or using .name()`);
6950
+ }
6951
+ opts = opts || {};
6952
+ if (opts.isDefault)
6953
+ this._defaultCommandName = cmd._name;
6954
+ if (opts.noHelp || opts.hidden)
6955
+ cmd._hidden = true;
6956
+ this._registerCommand(cmd);
6957
+ cmd.parent = this;
6958
+ cmd._checkForBrokenPassThrough();
6959
+ return this;
6960
+ }
6961
+ /**
6962
+ * Factory routine to create a new unattached argument.
6963
+ *
6964
+ * See .argument() for creating an attached argument, which uses this routine to
6965
+ * create the argument. You can override createArgument to return a custom argument.
6966
+ *
6967
+ * @param {string} name
6968
+ * @param {string} [description]
6969
+ * @return {Argument} new argument
6970
+ */
6971
+ createArgument(name, description) {
6972
+ return new Argument(name, description);
6973
+ }
6974
+ /**
6975
+ * Define argument syntax for command.
6976
+ *
6977
+ * The default is that the argument is required, and you can explicitly
6978
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
6979
+ *
6980
+ * @example
6981
+ * program.argument('<input-file>');
6982
+ * program.argument('[output-file]');
6983
+ *
6984
+ * @param {string} name
6985
+ * @param {string} [description]
6986
+ * @param {(Function|*)} [parseArg] - custom argument processing function or default value
6987
+ * @param {*} [defaultValue]
6988
+ * @return {Command} `this` command for chaining
6989
+ */
6990
+ argument(name, description, parseArg, defaultValue) {
6991
+ const argument = this.createArgument(name, description);
6992
+ if (typeof parseArg === "function") {
6993
+ argument.default(defaultValue).argParser(parseArg);
6994
+ } else {
6995
+ argument.default(parseArg);
6996
+ }
6997
+ this.addArgument(argument);
6998
+ return this;
6999
+ }
7000
+ /**
7001
+ * Define argument syntax for command, adding multiple at once (without descriptions).
7002
+ *
7003
+ * See also .argument().
7004
+ *
7005
+ * @example
7006
+ * program.arguments('<cmd> [env]');
7007
+ *
7008
+ * @param {string} names
7009
+ * @return {Command} `this` command for chaining
7010
+ */
7011
+ arguments(names) {
7012
+ names.trim().split(/ +/).forEach((detail) => {
7013
+ this.argument(detail);
7014
+ });
7015
+ return this;
7016
+ }
7017
+ /**
7018
+ * Define argument syntax for command, adding a prepared argument.
7019
+ *
7020
+ * @param {Argument} argument
7021
+ * @return {Command} `this` command for chaining
7022
+ */
7023
+ addArgument(argument) {
7024
+ const previousArgument = this.registeredArguments.slice(-1)[0];
7025
+ if (previousArgument?.variadic) {
7026
+ throw new Error(
7027
+ `only the last argument can be variadic '${previousArgument.name()}'`
7028
+ );
7029
+ }
7030
+ if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
7031
+ throw new Error(
7032
+ `a default value for a required argument is never used: '${argument.name()}'`
7033
+ );
7034
+ }
7035
+ this.registeredArguments.push(argument);
7036
+ return this;
7037
+ }
7038
+ /**
7039
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
7040
+ *
7041
+ * @example
7042
+ * program.helpCommand('help [cmd]');
7043
+ * program.helpCommand('help [cmd]', 'show help');
7044
+ * program.helpCommand(false); // suppress default help command
7045
+ * program.helpCommand(true); // add help command even if no subcommands
7046
+ *
7047
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
7048
+ * @param {string} [description] - custom description
7049
+ * @return {Command} `this` command for chaining
7050
+ */
7051
+ helpCommand(enableOrNameAndArgs, description) {
7052
+ if (typeof enableOrNameAndArgs === "boolean") {
7053
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
7054
+ if (enableOrNameAndArgs && this._defaultCommandGroup) {
7055
+ this._initCommandGroup(this._getHelpCommand());
7056
+ }
7057
+ return this;
7058
+ }
7059
+ const nameAndArgs = enableOrNameAndArgs ?? "help [command]";
7060
+ const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);
7061
+ const helpDescription = description ?? "display help for command";
7062
+ const helpCommand = this.createCommand(helpName);
7063
+ helpCommand.helpOption(false);
7064
+ if (helpArgs)
7065
+ helpCommand.arguments(helpArgs);
7066
+ if (helpDescription)
7067
+ helpCommand.description(helpDescription);
7068
+ this._addImplicitHelpCommand = true;
7069
+ this._helpCommand = helpCommand;
7070
+ if (enableOrNameAndArgs || description)
7071
+ this._initCommandGroup(helpCommand);
7072
+ return this;
7073
+ }
7074
+ /**
7075
+ * Add prepared custom help command.
7076
+ *
7077
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
7078
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
7079
+ * @return {Command} `this` command for chaining
7080
+ */
7081
+ addHelpCommand(helpCommand, deprecatedDescription) {
7082
+ if (typeof helpCommand !== "object") {
7083
+ this.helpCommand(helpCommand, deprecatedDescription);
7084
+ return this;
7085
+ }
7086
+ this._addImplicitHelpCommand = true;
7087
+ this._helpCommand = helpCommand;
7088
+ this._initCommandGroup(helpCommand);
7089
+ return this;
7090
+ }
7091
+ /**
7092
+ * Lazy create help command.
7093
+ *
7094
+ * @return {(Command|null)}
7095
+ * @package
7096
+ */
7097
+ _getHelpCommand() {
7098
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
7099
+ if (hasImplicitHelpCommand) {
7100
+ if (this._helpCommand === void 0) {
7101
+ this.helpCommand(void 0, void 0);
7102
+ }
7103
+ return this._helpCommand;
7104
+ }
7105
+ return null;
7106
+ }
7107
+ /**
7108
+ * Add hook for life cycle event.
7109
+ *
7110
+ * @param {string} event
7111
+ * @param {Function} listener
7112
+ * @return {Command} `this` command for chaining
7113
+ */
7114
+ hook(event, listener) {
7115
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
7116
+ if (!allowedValues.includes(event)) {
7117
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
7118
+ Expecting one of '${allowedValues.join("', '")}'`);
7119
+ }
7120
+ if (this._lifeCycleHooks[event]) {
7121
+ this._lifeCycleHooks[event].push(listener);
7122
+ } else {
7123
+ this._lifeCycleHooks[event] = [listener];
7124
+ }
7125
+ return this;
7126
+ }
7127
+ /**
7128
+ * Register callback to use as replacement for calling process.exit.
7129
+ *
7130
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
7131
+ * @return {Command} `this` command for chaining
7132
+ */
7133
+ exitOverride(fn) {
7134
+ if (fn) {
7135
+ this._exitCallback = fn;
7136
+ } else {
7137
+ this._exitCallback = (err) => {
7138
+ if (err.code !== "commander.executeSubCommandAsync") {
7139
+ throw err;
7140
+ } else {
7141
+ }
7142
+ };
7143
+ }
7144
+ return this;
7145
+ }
7146
+ /**
7147
+ * Call process.exit, and _exitCallback if defined.
7148
+ *
7149
+ * @param {number} exitCode exit code for using with process.exit
7150
+ * @param {string} code an id string representing the error
7151
+ * @param {string} message human-readable description of the error
7152
+ * @return never
7153
+ * @private
7154
+ */
7155
+ _exit(exitCode, code, message) {
7156
+ if (this._exitCallback) {
7157
+ this._exitCallback(new CommanderError(exitCode, code, message));
7158
+ }
7159
+ process2.exit(exitCode);
7160
+ }
7161
+ /**
7162
+ * Register callback `fn` for the command.
7163
+ *
7164
+ * @example
7165
+ * program
7166
+ * .command('serve')
7167
+ * .description('start service')
7168
+ * .action(function() {
7169
+ * // do work here
7170
+ * });
7171
+ *
7172
+ * @param {Function} fn
7173
+ * @return {Command} `this` command for chaining
7174
+ */
7175
+ action(fn) {
7176
+ const listener = (args) => {
7177
+ const expectedArgsCount = this.registeredArguments.length;
7178
+ const actionArgs = args.slice(0, expectedArgsCount);
7179
+ if (this._storeOptionsAsProperties) {
7180
+ actionArgs[expectedArgsCount] = this;
7181
+ } else {
7182
+ actionArgs[expectedArgsCount] = this.opts();
7183
+ }
7184
+ actionArgs.push(this);
7185
+ return fn.apply(this, actionArgs);
7186
+ };
7187
+ this._actionHandler = listener;
7188
+ return this;
7189
+ }
7190
+ /**
7191
+ * Factory routine to create a new unattached option.
7192
+ *
7193
+ * See .option() for creating an attached option, which uses this routine to
7194
+ * create the option. You can override createOption to return a custom option.
7195
+ *
7196
+ * @param {string} flags
7197
+ * @param {string} [description]
7198
+ * @return {Option} new option
7199
+ */
7200
+ createOption(flags, description) {
7201
+ return new Option(flags, description);
7202
+ }
7203
+ /**
7204
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
7205
+ *
7206
+ * @param {(Option | Argument)} target
7207
+ * @param {string} value
7208
+ * @param {*} previous
7209
+ * @param {string} invalidArgumentMessage
7210
+ * @private
7211
+ */
7212
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
7213
+ try {
7214
+ return target.parseArg(value, previous);
7215
+ } catch (err) {
7216
+ if (err.code === "commander.invalidArgument") {
7217
+ const message = `${invalidArgumentMessage} ${err.message}`;
7218
+ this.error(message, { exitCode: err.exitCode, code: err.code });
7219
+ }
7220
+ throw err;
7221
+ }
7222
+ }
7223
+ /**
7224
+ * Check for option flag conflicts.
7225
+ * Register option if no conflicts found, or throw on conflict.
7226
+ *
7227
+ * @param {Option} option
7228
+ * @private
7229
+ */
7230
+ _registerOption(option) {
7231
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
7232
+ if (matchingOption) {
7233
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
7234
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
7235
+ - already used by option '${matchingOption.flags}'`);
7236
+ }
7237
+ this._initOptionGroup(option);
7238
+ this.options.push(option);
7239
+ }
7240
+ /**
7241
+ * Check for command name and alias conflicts with existing commands.
7242
+ * Register command if no conflicts found, or throw on conflict.
7243
+ *
7244
+ * @param {Command} command
7245
+ * @private
7246
+ */
7247
+ _registerCommand(command2) {
7248
+ const knownBy = (cmd) => {
7249
+ return [cmd.name()].concat(cmd.aliases());
7250
+ };
7251
+ const alreadyUsed = knownBy(command2).find(
7252
+ (name) => this._findCommand(name)
7253
+ );
7254
+ if (alreadyUsed) {
7255
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
7256
+ const newCmd = knownBy(command2).join("|");
7257
+ throw new Error(
7258
+ `cannot add command '${newCmd}' as already have command '${existingCmd}'`
7259
+ );
7260
+ }
7261
+ this._initCommandGroup(command2);
7262
+ this.commands.push(command2);
7263
+ }
7264
+ /**
7265
+ * Add an option.
7266
+ *
7267
+ * @param {Option} option
7268
+ * @return {Command} `this` command for chaining
7269
+ */
7270
+ addOption(option) {
7271
+ this._registerOption(option);
7272
+ const oname = option.name();
7273
+ const name = option.attributeName();
7274
+ if (option.defaultValue !== void 0) {
7275
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
7276
+ }
7277
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
7278
+ if (val == null && option.presetArg !== void 0) {
7279
+ val = option.presetArg;
7280
+ }
7281
+ const oldValue = this.getOptionValue(name);
7282
+ if (val !== null && option.parseArg) {
7283
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
7284
+ } else if (val !== null && option.variadic) {
7285
+ val = option._collectValue(val, oldValue);
7286
+ }
7287
+ if (val == null) {
7288
+ if (option.negate) {
7289
+ val = false;
7290
+ } else if (option.isBoolean() || option.optional) {
7291
+ val = true;
7292
+ } else {
7293
+ val = "";
7294
+ }
7295
+ }
7296
+ this.setOptionValueWithSource(name, val, valueSource);
7297
+ };
7298
+ this.on("option:" + oname, (val) => {
7299
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
7300
+ handleOptionValue(val, invalidValueMessage, "cli");
7301
+ });
7302
+ if (option.envVar) {
7303
+ this.on("optionEnv:" + oname, (val) => {
7304
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
7305
+ handleOptionValue(val, invalidValueMessage, "env");
7306
+ });
7307
+ }
7308
+ return this;
7309
+ }
7310
+ /**
7311
+ * Internal implementation shared by .option() and .requiredOption()
7312
+ *
7313
+ * @return {Command} `this` command for chaining
7314
+ * @private
7315
+ */
7316
+ _optionEx(config, flags, description, fn, defaultValue) {
7317
+ if (typeof flags === "object" && flags instanceof Option) {
7318
+ throw new Error(
7319
+ "To add an Option object use addOption() instead of option() or requiredOption()"
7320
+ );
7321
+ }
7322
+ const option = this.createOption(flags, description);
7323
+ option.makeOptionMandatory(!!config.mandatory);
7324
+ if (typeof fn === "function") {
7325
+ option.default(defaultValue).argParser(fn);
7326
+ } else if (fn instanceof RegExp) {
7327
+ const regex2 = fn;
7328
+ fn = (val, def) => {
7329
+ const m = regex2.exec(val);
7330
+ return m ? m[0] : def;
7331
+ };
7332
+ option.default(defaultValue).argParser(fn);
7333
+ } else {
7334
+ option.default(fn);
7335
+ }
7336
+ return this.addOption(option);
7337
+ }
7338
+ /**
7339
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
7340
+ *
7341
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
7342
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
7343
+ *
7344
+ * See the README for more details, and see also addOption() and requiredOption().
7345
+ *
7346
+ * @example
7347
+ * program
7348
+ * .option('-p, --pepper', 'add pepper')
7349
+ * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
7350
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
7351
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
7352
+ *
7353
+ * @param {string} flags
7354
+ * @param {string} [description]
7355
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
7356
+ * @param {*} [defaultValue]
7357
+ * @return {Command} `this` command for chaining
7358
+ */
7359
+ option(flags, description, parseArg, defaultValue) {
7360
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
7361
+ }
7362
+ /**
7363
+ * Add a required option which must have a value after parsing. This usually means
7364
+ * the option must be specified on the command line. (Otherwise the same as .option().)
7365
+ *
7366
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
7367
+ *
7368
+ * @param {string} flags
7369
+ * @param {string} [description]
7370
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
7371
+ * @param {*} [defaultValue]
7372
+ * @return {Command} `this` command for chaining
7373
+ */
7374
+ requiredOption(flags, description, parseArg, defaultValue) {
7375
+ return this._optionEx(
7376
+ { mandatory: true },
7377
+ flags,
7378
+ description,
7379
+ parseArg,
7380
+ defaultValue
7381
+ );
7382
+ }
7383
+ /**
7384
+ * Alter parsing of short flags with optional values.
7385
+ *
7386
+ * @example
7387
+ * // for `.option('-f,--flag [value]'):
7388
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
7389
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
7390
+ *
7391
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
7392
+ * @return {Command} `this` command for chaining
7393
+ */
7394
+ combineFlagAndOptionalValue(combine = true) {
7395
+ this._combineFlagAndOptionalValue = !!combine;
7396
+ return this;
7397
+ }
7398
+ /**
7399
+ * Allow unknown options on the command line.
7400
+ *
7401
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
7402
+ * @return {Command} `this` command for chaining
7403
+ */
7404
+ allowUnknownOption(allowUnknown = true) {
7405
+ this._allowUnknownOption = !!allowUnknown;
7406
+ return this;
7407
+ }
7408
+ /**
7409
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
7410
+ *
7411
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
7412
+ * @return {Command} `this` command for chaining
7413
+ */
7414
+ allowExcessArguments(allowExcess = true) {
7415
+ this._allowExcessArguments = !!allowExcess;
7416
+ return this;
7417
+ }
7418
+ /**
7419
+ * Enable positional options. Positional means global options are specified before subcommands which lets
7420
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
7421
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
7422
+ *
7423
+ * @param {boolean} [positional]
7424
+ * @return {Command} `this` command for chaining
7425
+ */
7426
+ enablePositionalOptions(positional = true) {
7427
+ this._enablePositionalOptions = !!positional;
7428
+ return this;
7429
+ }
7430
+ /**
7431
+ * Pass through options that come after command-arguments rather than treat them as command-options,
7432
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
7433
+ * positional options to have been enabled on the program (parent commands).
7434
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
7435
+ *
7436
+ * @param {boolean} [passThrough] for unknown options.
7437
+ * @return {Command} `this` command for chaining
7438
+ */
7439
+ passThroughOptions(passThrough = true) {
7440
+ this._passThroughOptions = !!passThrough;
7441
+ this._checkForBrokenPassThrough();
7442
+ return this;
7443
+ }
7444
+ /**
7445
+ * @private
7446
+ */
7447
+ _checkForBrokenPassThrough() {
7448
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
7449
+ throw new Error(
7450
+ `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`
7451
+ );
7452
+ }
7453
+ }
7454
+ /**
7455
+ * Whether to store option values as properties on command object,
7456
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
7457
+ *
7458
+ * @param {boolean} [storeAsProperties=true]
7459
+ * @return {Command} `this` command for chaining
7460
+ */
7461
+ storeOptionsAsProperties(storeAsProperties = true) {
7462
+ if (this.options.length) {
7463
+ throw new Error("call .storeOptionsAsProperties() before adding options");
7464
+ }
7465
+ if (Object.keys(this._optionValues).length) {
7466
+ throw new Error(
7467
+ "call .storeOptionsAsProperties() before setting option values"
7468
+ );
7469
+ }
7470
+ this._storeOptionsAsProperties = !!storeAsProperties;
7471
+ return this;
7472
+ }
7473
+ /**
7474
+ * Retrieve option value.
7475
+ *
7476
+ * @param {string} key
7477
+ * @return {object} value
7478
+ */
7479
+ getOptionValue(key) {
7480
+ if (this._storeOptionsAsProperties) {
7481
+ return this[key];
7482
+ }
7483
+ return this._optionValues[key];
7484
+ }
7485
+ /**
7486
+ * Store option value.
7487
+ *
7488
+ * @param {string} key
7489
+ * @param {object} value
7490
+ * @return {Command} `this` command for chaining
7491
+ */
7492
+ setOptionValue(key, value) {
7493
+ return this.setOptionValueWithSource(key, value, void 0);
7494
+ }
7495
+ /**
7496
+ * Store option value and where the value came from.
7497
+ *
7498
+ * @param {string} key
7499
+ * @param {object} value
7500
+ * @param {string} source - expected values are default/config/env/cli/implied
7501
+ * @return {Command} `this` command for chaining
7502
+ */
7503
+ setOptionValueWithSource(key, value, source) {
7504
+ if (this._storeOptionsAsProperties) {
7505
+ this[key] = value;
7506
+ } else {
7507
+ this._optionValues[key] = value;
7508
+ }
7509
+ this._optionValueSources[key] = source;
7510
+ return this;
7511
+ }
7512
+ /**
7513
+ * Get source of option value.
7514
+ * Expected values are default | config | env | cli | implied
7515
+ *
7516
+ * @param {string} key
7517
+ * @return {string}
7518
+ */
7519
+ getOptionValueSource(key) {
7520
+ return this._optionValueSources[key];
7521
+ }
7522
+ /**
7523
+ * Get source of option value. See also .optsWithGlobals().
7524
+ * Expected values are default | config | env | cli | implied
7525
+ *
7526
+ * @param {string} key
7527
+ * @return {string}
7528
+ */
7529
+ getOptionValueSourceWithGlobals(key) {
7530
+ let source;
7531
+ this._getCommandAndAncestors().forEach((cmd) => {
7532
+ if (cmd.getOptionValueSource(key) !== void 0) {
7533
+ source = cmd.getOptionValueSource(key);
7534
+ }
7535
+ });
7536
+ return source;
7537
+ }
7538
+ /**
7539
+ * Get user arguments from implied or explicit arguments.
7540
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
7541
+ *
7542
+ * @private
7543
+ */
7544
+ _prepareUserArgs(argv, parseOptions) {
7545
+ if (argv !== void 0 && !Array.isArray(argv)) {
7546
+ throw new Error("first parameter to parse must be array or undefined");
7547
+ }
7548
+ parseOptions = parseOptions || {};
7549
+ if (argv === void 0 && parseOptions.from === void 0) {
7550
+ if (process2.versions?.electron) {
7551
+ parseOptions.from = "electron";
7552
+ }
7553
+ const execArgv = process2.execArgv ?? [];
7554
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
7555
+ parseOptions.from = "eval";
7556
+ }
7557
+ }
7558
+ if (argv === void 0) {
7559
+ argv = process2.argv;
7560
+ }
7561
+ this.rawArgs = argv.slice();
7562
+ let userArgs;
7563
+ switch (parseOptions.from) {
7564
+ case void 0:
7565
+ case "node":
7566
+ this._scriptPath = argv[1];
7567
+ userArgs = argv.slice(2);
7568
+ break;
7569
+ case "electron":
7570
+ if (process2.defaultApp) {
7571
+ this._scriptPath = argv[1];
7572
+ userArgs = argv.slice(2);
7573
+ } else {
7574
+ userArgs = argv.slice(1);
7575
+ }
7576
+ break;
7577
+ case "user":
7578
+ userArgs = argv.slice(0);
7579
+ break;
7580
+ case "eval":
7581
+ userArgs = argv.slice(1);
7582
+ break;
7583
+ default:
7584
+ throw new Error(
7585
+ `unexpected parse option { from: '${parseOptions.from}' }`
7586
+ );
7587
+ }
7588
+ if (!this._name && this._scriptPath)
7589
+ this.nameFromFilename(this._scriptPath);
7590
+ this._name = this._name || "program";
7591
+ return userArgs;
7592
+ }
7593
+ /**
7594
+ * Parse `argv`, setting options and invoking commands when defined.
7595
+ *
7596
+ * Use parseAsync instead of parse if any of your action handlers are async.
7597
+ *
7598
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
7599
+ *
7600
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
7601
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
7602
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
7603
+ * - `'user'`: just user arguments
7604
+ *
7605
+ * @example
7606
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
7607
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
7608
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
7609
+ *
7610
+ * @param {string[]} [argv] - optional, defaults to process.argv
7611
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
7612
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
7613
+ * @return {Command} `this` command for chaining
7614
+ */
7615
+ parse(argv, parseOptions) {
7616
+ this._prepareForParse();
7617
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
7618
+ this._parseCommand([], userArgs);
7619
+ return this;
7620
+ }
7621
+ /**
7622
+ * Parse `argv`, setting options and invoking commands when defined.
7623
+ *
7624
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
7625
+ *
7626
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
7627
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
7628
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
7629
+ * - `'user'`: just user arguments
7630
+ *
7631
+ * @example
7632
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
7633
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
7634
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
7635
+ *
7636
+ * @param {string[]} [argv]
7637
+ * @param {object} [parseOptions]
7638
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
7639
+ * @return {Promise}
7640
+ */
7641
+ async parseAsync(argv, parseOptions) {
7642
+ this._prepareForParse();
7643
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
7644
+ await this._parseCommand([], userArgs);
7645
+ return this;
7646
+ }
7647
+ _prepareForParse() {
7648
+ if (this._savedState === null) {
7649
+ this.options.filter(
7650
+ (option) => option.negate && option.defaultValue === void 0 && this.getOptionValue(option.attributeName()) === void 0
7651
+ ).forEach((option) => {
7652
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
7653
+ if (!this._findOption(positiveLongFlag)) {
7654
+ this.setOptionValueWithSource(
7655
+ option.attributeName(),
7656
+ true,
7657
+ "default"
7658
+ );
7659
+ }
7660
+ });
7661
+ this.saveStateBeforeParse();
7662
+ } else {
7663
+ this.restoreStateBeforeParse();
7664
+ }
7665
+ }
7666
+ /**
7667
+ * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
7668
+ * Not usually called directly, but available for subclasses to save their custom state.
7669
+ *
7670
+ * This is called in a lazy way. Only commands used in parsing chain will have state saved.
7671
+ */
7672
+ saveStateBeforeParse() {
7673
+ this._savedState = {
7674
+ // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing
7675
+ _name: this._name,
7676
+ // option values before parse have default values (including false for negated options)
7677
+ // shallow clones
7678
+ _optionValues: { ...this._optionValues },
7679
+ _optionValueSources: { ...this._optionValueSources }
7680
+ };
7681
+ }
7682
+ /**
7683
+ * Restore state before parse for calls after the first.
7684
+ * Not usually called directly, but available for subclasses to save their custom state.
7685
+ *
7686
+ * This is called in a lazy way. Only commands used in parsing chain will have state restored.
7687
+ */
7688
+ restoreStateBeforeParse() {
7689
+ if (this._storeOptionsAsProperties)
7690
+ throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
7691
+ - either make a new Command for each call to parse, or stop storing options as properties`);
7692
+ this._name = this._savedState._name;
7693
+ this._scriptPath = null;
7694
+ this.rawArgs = [];
7695
+ this._optionValues = { ...this._savedState._optionValues };
7696
+ this._optionValueSources = { ...this._savedState._optionValueSources };
7697
+ this.args = [];
7698
+ this.processedArgs = [];
7699
+ }
7700
+ /**
7701
+ * Throw if expected executable is missing. Add lots of help for author.
7702
+ *
7703
+ * @param {string} executableFile
7704
+ * @param {string} executableDir
7705
+ * @param {string} subcommandName
7706
+ */
7707
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
7708
+ if (fs.existsSync(executableFile))
7709
+ return;
7710
+ 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";
7711
+ const executableMissing = `'${executableFile}' does not exist
7712
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
7713
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
7714
+ - ${executableDirMessage}`;
7715
+ throw new Error(executableMissing);
7716
+ }
7717
+ /**
7718
+ * Execute a sub-command executable.
7719
+ *
7720
+ * @private
7721
+ */
7722
+ _executeSubCommand(subcommand, args) {
7723
+ args = args.slice();
7724
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
7725
+ function findFile(baseDir, baseName) {
7726
+ const localBin = path.resolve(baseDir, baseName);
7727
+ if (fs.existsSync(localBin))
7728
+ return localBin;
7729
+ if (sourceExt.includes(path.extname(baseName)))
7730
+ return void 0;
7731
+ const foundExt = sourceExt.find(
7732
+ (ext) => fs.existsSync(`${localBin}${ext}`)
7733
+ );
7734
+ if (foundExt)
7735
+ return `${localBin}${foundExt}`;
7736
+ return void 0;
7737
+ }
7738
+ this._checkForMissingMandatoryOptions();
7739
+ this._checkForConflictingOptions();
7740
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
7741
+ let executableDir = this._executableDir || "";
7742
+ if (this._scriptPath) {
7743
+ let resolvedScriptPath;
7744
+ try {
7745
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
7746
+ } catch {
7747
+ resolvedScriptPath = this._scriptPath;
7748
+ }
7749
+ executableDir = path.resolve(
7750
+ path.dirname(resolvedScriptPath),
7751
+ executableDir
7752
+ );
7753
+ }
7754
+ if (executableDir) {
7755
+ let localFile = findFile(executableDir, executableFile);
7756
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
7757
+ const legacyName = path.basename(
7758
+ this._scriptPath,
7759
+ path.extname(this._scriptPath)
7760
+ );
7761
+ if (legacyName !== this._name) {
7762
+ localFile = findFile(
7763
+ executableDir,
7764
+ `${legacyName}-${subcommand._name}`
7765
+ );
7766
+ }
7767
+ }
7768
+ executableFile = localFile || executableFile;
7769
+ }
7770
+ const launchWithNode = sourceExt.includes(path.extname(executableFile));
7771
+ let proc;
7772
+ if (process2.platform !== "win32") {
7773
+ if (launchWithNode) {
7774
+ args.unshift(executableFile);
7775
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
7776
+ proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
7777
+ } else {
7778
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
7779
+ }
7780
+ } else {
7781
+ this._checkForMissingExecutable(
7782
+ executableFile,
7783
+ executableDir,
7784
+ subcommand._name
7785
+ );
7786
+ args.unshift(executableFile);
7787
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
7788
+ proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
7789
+ }
7790
+ if (!proc.killed) {
7791
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
7792
+ signals.forEach((signal) => {
7793
+ process2.on(signal, () => {
7794
+ if (proc.killed === false && proc.exitCode === null) {
7795
+ proc.kill(signal);
7796
+ }
7797
+ });
7798
+ });
7799
+ }
7800
+ const exitCallback = this._exitCallback;
7801
+ proc.on("close", (code) => {
7802
+ code = code ?? 1;
7803
+ if (!exitCallback) {
7804
+ process2.exit(code);
7805
+ } else {
7806
+ exitCallback(
7807
+ new CommanderError(
7808
+ code,
7809
+ "commander.executeSubCommandAsync",
7810
+ "(close)"
7811
+ )
7812
+ );
7813
+ }
7814
+ });
7815
+ proc.on("error", (err) => {
7816
+ if (err.code === "ENOENT") {
7817
+ this._checkForMissingExecutable(
7818
+ executableFile,
7819
+ executableDir,
7820
+ subcommand._name
7821
+ );
7822
+ } else if (err.code === "EACCES") {
7823
+ throw new Error(`'${executableFile}' not executable`);
7824
+ }
7825
+ if (!exitCallback) {
7826
+ process2.exit(1);
7827
+ } else {
7828
+ const wrappedError = new CommanderError(
7829
+ 1,
7830
+ "commander.executeSubCommandAsync",
7831
+ "(error)"
7832
+ );
7833
+ wrappedError.nestedError = err;
7834
+ exitCallback(wrappedError);
7835
+ }
7836
+ });
7837
+ this.runningCommand = proc;
7838
+ }
7839
+ /**
7840
+ * @private
7841
+ */
7842
+ _dispatchSubcommand(commandName, operands, unknown) {
7843
+ const subCommand = this._findCommand(commandName);
7844
+ if (!subCommand)
7845
+ this.help({ error: true });
7846
+ subCommand._prepareForParse();
7847
+ let promiseChain;
7848
+ promiseChain = this._chainOrCallSubCommandHook(
7849
+ promiseChain,
7850
+ subCommand,
7851
+ "preSubcommand"
7852
+ );
7853
+ promiseChain = this._chainOrCall(promiseChain, () => {
7854
+ if (subCommand._executableHandler) {
7855
+ this._executeSubCommand(subCommand, operands.concat(unknown));
7856
+ } else {
7857
+ return subCommand._parseCommand(operands, unknown);
7858
+ }
7859
+ });
7860
+ return promiseChain;
7861
+ }
7862
+ /**
7863
+ * Invoke help directly if possible, or dispatch if necessary.
7864
+ * e.g. help foo
7865
+ *
7866
+ * @private
7867
+ */
7868
+ _dispatchHelpCommand(subcommandName) {
7869
+ if (!subcommandName) {
7870
+ this.help();
7871
+ }
7872
+ const subCommand = this._findCommand(subcommandName);
7873
+ if (subCommand && !subCommand._executableHandler) {
7874
+ subCommand.help();
7875
+ }
7876
+ return this._dispatchSubcommand(
7877
+ subcommandName,
7878
+ [],
7879
+ [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]
7880
+ );
7881
+ }
7882
+ /**
7883
+ * Check this.args against expected this.registeredArguments.
7884
+ *
7885
+ * @private
7886
+ */
7887
+ _checkNumberOfArguments() {
7888
+ this.registeredArguments.forEach((arg, i) => {
7889
+ if (arg.required && this.args[i] == null) {
7890
+ this.missingArgument(arg.name());
7891
+ }
7892
+ });
7893
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
7894
+ return;
7895
+ }
7896
+ if (this.args.length > this.registeredArguments.length) {
7897
+ this._excessArguments(this.args);
7898
+ }
7899
+ }
7900
+ /**
7901
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
7902
+ *
7903
+ * @private
7904
+ */
7905
+ _processArguments() {
7906
+ const myParseArg = (argument, value, previous) => {
7907
+ let parsedValue = value;
7908
+ if (value !== null && argument.parseArg) {
7909
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
7910
+ parsedValue = this._callParseArg(
7911
+ argument,
7912
+ value,
7913
+ previous,
7914
+ invalidValueMessage
7915
+ );
7916
+ }
7917
+ return parsedValue;
7918
+ };
7919
+ this._checkNumberOfArguments();
7920
+ const processedArgs = [];
7921
+ this.registeredArguments.forEach((declaredArg, index) => {
7922
+ let value = declaredArg.defaultValue;
7923
+ if (declaredArg.variadic) {
7924
+ if (index < this.args.length) {
7925
+ value = this.args.slice(index);
7926
+ if (declaredArg.parseArg) {
7927
+ value = value.reduce((processed, v) => {
7928
+ return myParseArg(declaredArg, v, processed);
7929
+ }, declaredArg.defaultValue);
7930
+ }
7931
+ } else if (value === void 0) {
7932
+ value = [];
7933
+ }
7934
+ } else if (index < this.args.length) {
7935
+ value = this.args[index];
7936
+ if (declaredArg.parseArg) {
7937
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
7938
+ }
7939
+ }
7940
+ processedArgs[index] = value;
7941
+ });
7942
+ this.processedArgs = processedArgs;
7943
+ }
7944
+ /**
7945
+ * Once we have a promise we chain, but call synchronously until then.
7946
+ *
7947
+ * @param {(Promise|undefined)} promise
7948
+ * @param {Function} fn
7949
+ * @return {(Promise|undefined)}
7950
+ * @private
7951
+ */
7952
+ _chainOrCall(promise, fn) {
7953
+ if (promise?.then && typeof promise.then === "function") {
7954
+ return promise.then(() => fn());
7955
+ }
7956
+ return fn();
7957
+ }
7958
+ /**
7959
+ *
7960
+ * @param {(Promise|undefined)} promise
7961
+ * @param {string} event
7962
+ * @return {(Promise|undefined)}
7963
+ * @private
7964
+ */
7965
+ _chainOrCallHooks(promise, event) {
7966
+ let result = promise;
7967
+ const hooks = [];
7968
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
7969
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
7970
+ hooks.push({ hookedCommand, callback });
7971
+ });
7972
+ });
7973
+ if (event === "postAction") {
7974
+ hooks.reverse();
7975
+ }
7976
+ hooks.forEach((hookDetail) => {
7977
+ result = this._chainOrCall(result, () => {
7978
+ return hookDetail.callback(hookDetail.hookedCommand, this);
7979
+ });
7980
+ });
7981
+ return result;
7982
+ }
7983
+ /**
7984
+ *
7985
+ * @param {(Promise|undefined)} promise
7986
+ * @param {Command} subCommand
7987
+ * @param {string} event
7988
+ * @return {(Promise|undefined)}
7989
+ * @private
7990
+ */
7991
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
7992
+ let result = promise;
7993
+ if (this._lifeCycleHooks[event] !== void 0) {
7994
+ this._lifeCycleHooks[event].forEach((hook) => {
7995
+ result = this._chainOrCall(result, () => {
7996
+ return hook(this, subCommand);
7997
+ });
7998
+ });
7999
+ }
8000
+ return result;
8001
+ }
8002
+ /**
8003
+ * Process arguments in context of this command.
8004
+ * Returns action result, in case it is a promise.
8005
+ *
8006
+ * @private
8007
+ */
8008
+ _parseCommand(operands, unknown) {
8009
+ const parsed = this.parseOptions(unknown);
8010
+ this._parseOptionsEnv();
8011
+ this._parseOptionsImplied();
8012
+ operands = operands.concat(parsed.operands);
8013
+ unknown = parsed.unknown;
8014
+ this.args = operands.concat(unknown);
8015
+ if (operands && this._findCommand(operands[0])) {
8016
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
8017
+ }
8018
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
8019
+ return this._dispatchHelpCommand(operands[1]);
8020
+ }
8021
+ if (this._defaultCommandName) {
8022
+ this._outputHelpIfRequested(unknown);
8023
+ return this._dispatchSubcommand(
8024
+ this._defaultCommandName,
8025
+ operands,
8026
+ unknown
8027
+ );
8028
+ }
8029
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
8030
+ this.help({ error: true });
8031
+ }
8032
+ this._outputHelpIfRequested(parsed.unknown);
8033
+ this._checkForMissingMandatoryOptions();
8034
+ this._checkForConflictingOptions();
8035
+ const checkForUnknownOptions = () => {
8036
+ if (parsed.unknown.length > 0) {
8037
+ this.unknownOption(parsed.unknown[0]);
8038
+ }
8039
+ };
8040
+ const commandEvent = `command:${this.name()}`;
8041
+ if (this._actionHandler) {
8042
+ checkForUnknownOptions();
8043
+ this._processArguments();
8044
+ let promiseChain;
8045
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
8046
+ promiseChain = this._chainOrCall(
8047
+ promiseChain,
8048
+ () => this._actionHandler(this.processedArgs)
8049
+ );
8050
+ if (this.parent) {
8051
+ promiseChain = this._chainOrCall(promiseChain, () => {
8052
+ this.parent.emit(commandEvent, operands, unknown);
8053
+ });
8054
+ }
8055
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
8056
+ return promiseChain;
8057
+ }
8058
+ if (this.parent?.listenerCount(commandEvent)) {
8059
+ checkForUnknownOptions();
8060
+ this._processArguments();
8061
+ this.parent.emit(commandEvent, operands, unknown);
8062
+ } else if (operands.length) {
8063
+ if (this._findCommand("*")) {
8064
+ return this._dispatchSubcommand("*", operands, unknown);
8065
+ }
8066
+ if (this.listenerCount("command:*")) {
8067
+ this.emit("command:*", operands, unknown);
8068
+ } else if (this.commands.length) {
8069
+ this.unknownCommand();
8070
+ } else {
8071
+ checkForUnknownOptions();
8072
+ this._processArguments();
8073
+ }
8074
+ } else if (this.commands.length) {
8075
+ checkForUnknownOptions();
8076
+ this.help({ error: true });
8077
+ } else {
8078
+ checkForUnknownOptions();
8079
+ this._processArguments();
8080
+ }
8081
+ }
8082
+ /**
8083
+ * Find matching command.
8084
+ *
8085
+ * @private
8086
+ * @return {Command | undefined}
8087
+ */
8088
+ _findCommand(name) {
8089
+ if (!name)
8090
+ return void 0;
8091
+ return this.commands.find(
8092
+ (cmd) => cmd._name === name || cmd._aliases.includes(name)
8093
+ );
8094
+ }
8095
+ /**
8096
+ * Return an option matching `arg` if any.
8097
+ *
8098
+ * @param {string} arg
8099
+ * @return {Option}
8100
+ * @package
8101
+ */
8102
+ _findOption(arg) {
8103
+ return this.options.find((option) => option.is(arg));
8104
+ }
8105
+ /**
8106
+ * Display an error message if a mandatory option does not have a value.
8107
+ * Called after checking for help flags in leaf subcommand.
8108
+ *
8109
+ * @private
8110
+ */
8111
+ _checkForMissingMandatoryOptions() {
8112
+ this._getCommandAndAncestors().forEach((cmd) => {
8113
+ cmd.options.forEach((anOption) => {
8114
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
8115
+ cmd.missingMandatoryOptionValue(anOption);
8116
+ }
8117
+ });
8118
+ });
8119
+ }
8120
+ /**
8121
+ * Display an error message if conflicting options are used together in this.
8122
+ *
8123
+ * @private
8124
+ */
8125
+ _checkForConflictingLocalOptions() {
8126
+ const definedNonDefaultOptions = this.options.filter((option) => {
8127
+ const optionKey = option.attributeName();
8128
+ if (this.getOptionValue(optionKey) === void 0) {
8129
+ return false;
8130
+ }
8131
+ return this.getOptionValueSource(optionKey) !== "default";
8132
+ });
8133
+ const optionsWithConflicting = definedNonDefaultOptions.filter(
8134
+ (option) => option.conflictsWith.length > 0
8135
+ );
8136
+ optionsWithConflicting.forEach((option) => {
8137
+ const conflictingAndDefined = definedNonDefaultOptions.find(
8138
+ (defined) => option.conflictsWith.includes(defined.attributeName())
8139
+ );
8140
+ if (conflictingAndDefined) {
8141
+ this._conflictingOption(option, conflictingAndDefined);
8142
+ }
8143
+ });
8144
+ }
8145
+ /**
8146
+ * Display an error message if conflicting options are used together.
8147
+ * Called after checking for help flags in leaf subcommand.
8148
+ *
8149
+ * @private
8150
+ */
8151
+ _checkForConflictingOptions() {
8152
+ this._getCommandAndAncestors().forEach((cmd) => {
8153
+ cmd._checkForConflictingLocalOptions();
8154
+ });
8155
+ }
8156
+ /**
8157
+ * Parse options from `argv` removing known options,
8158
+ * and return argv split into operands and unknown arguments.
8159
+ *
8160
+ * Side effects: modifies command by storing options. Does not reset state if called again.
8161
+ *
8162
+ * Examples:
8163
+ *
8164
+ * argv => operands, unknown
8165
+ * --known kkk op => [op], []
8166
+ * op --known kkk => [op], []
8167
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
8168
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
8169
+ *
8170
+ * @param {string[]} args
8171
+ * @return {{operands: string[], unknown: string[]}}
8172
+ */
8173
+ parseOptions(args) {
8174
+ const operands = [];
8175
+ const unknown = [];
8176
+ let dest = operands;
8177
+ function maybeOption(arg) {
8178
+ return arg.length > 1 && arg[0] === "-";
8179
+ }
8180
+ const negativeNumberArg = (arg) => {
8181
+ if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg))
8182
+ return false;
8183
+ return !this._getCommandAndAncestors().some(
8184
+ (cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short))
8185
+ );
8186
+ };
8187
+ let activeVariadicOption = null;
8188
+ let activeGroup = null;
8189
+ let i = 0;
8190
+ while (i < args.length || activeGroup) {
8191
+ const arg = activeGroup ?? args[i++];
8192
+ activeGroup = null;
8193
+ if (arg === "--") {
8194
+ if (dest === unknown)
8195
+ dest.push(arg);
8196
+ dest.push(...args.slice(i));
8197
+ break;
8198
+ }
8199
+ if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
8200
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
8201
+ continue;
8202
+ }
8203
+ activeVariadicOption = null;
8204
+ if (maybeOption(arg)) {
8205
+ const option = this._findOption(arg);
8206
+ if (option) {
8207
+ if (option.required) {
8208
+ const value = args[i++];
8209
+ if (value === void 0)
8210
+ this.optionMissingArgument(option);
8211
+ this.emit(`option:${option.name()}`, value);
8212
+ } else if (option.optional) {
8213
+ let value = null;
8214
+ if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) {
8215
+ value = args[i++];
8216
+ }
8217
+ this.emit(`option:${option.name()}`, value);
8218
+ } else {
8219
+ this.emit(`option:${option.name()}`);
8220
+ }
8221
+ activeVariadicOption = option.variadic ? option : null;
8222
+ continue;
8223
+ }
8224
+ }
8225
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
8226
+ const option = this._findOption(`-${arg[1]}`);
8227
+ if (option) {
8228
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
8229
+ this.emit(`option:${option.name()}`, arg.slice(2));
8230
+ } else {
8231
+ this.emit(`option:${option.name()}`);
8232
+ activeGroup = `-${arg.slice(2)}`;
8233
+ }
8234
+ continue;
8235
+ }
8236
+ }
8237
+ if (/^--[^=]+=/.test(arg)) {
8238
+ const index = arg.indexOf("=");
8239
+ const option = this._findOption(arg.slice(0, index));
8240
+ if (option && (option.required || option.optional)) {
8241
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
8242
+ continue;
8243
+ }
8244
+ }
8245
+ if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) {
8246
+ dest = unknown;
8247
+ }
8248
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
8249
+ if (this._findCommand(arg)) {
8250
+ operands.push(arg);
8251
+ unknown.push(...args.slice(i));
8252
+ break;
8253
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
8254
+ operands.push(arg, ...args.slice(i));
8255
+ break;
8256
+ } else if (this._defaultCommandName) {
8257
+ unknown.push(arg, ...args.slice(i));
8258
+ break;
8259
+ }
8260
+ }
8261
+ if (this._passThroughOptions) {
8262
+ dest.push(arg, ...args.slice(i));
8263
+ break;
8264
+ }
8265
+ dest.push(arg);
8266
+ }
8267
+ return { operands, unknown };
8268
+ }
8269
+ /**
8270
+ * Return an object containing local option values as key-value pairs.
8271
+ *
8272
+ * @return {object}
8273
+ */
8274
+ opts() {
8275
+ if (this._storeOptionsAsProperties) {
8276
+ const result = {};
8277
+ const len = this.options.length;
8278
+ for (let i = 0; i < len; i++) {
8279
+ const key = this.options[i].attributeName();
8280
+ result[key] = key === this._versionOptionName ? this._version : this[key];
8281
+ }
8282
+ return result;
8283
+ }
8284
+ return this._optionValues;
8285
+ }
8286
+ /**
8287
+ * Return an object containing merged local and global option values as key-value pairs.
8288
+ *
8289
+ * @return {object}
8290
+ */
8291
+ optsWithGlobals() {
8292
+ return this._getCommandAndAncestors().reduce(
8293
+ (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
8294
+ {}
8295
+ );
8296
+ }
8297
+ /**
8298
+ * Display error message and exit (or call exitOverride).
8299
+ *
8300
+ * @param {string} message
8301
+ * @param {object} [errorOptions]
8302
+ * @param {string} [errorOptions.code] - an id string representing the error
8303
+ * @param {number} [errorOptions.exitCode] - used with process.exit
8304
+ */
8305
+ error(message, errorOptions) {
8306
+ this._outputConfiguration.outputError(
8307
+ `${message}
8308
+ `,
8309
+ this._outputConfiguration.writeErr
8310
+ );
8311
+ if (typeof this._showHelpAfterError === "string") {
8312
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
8313
+ `);
8314
+ } else if (this._showHelpAfterError) {
8315
+ this._outputConfiguration.writeErr("\n");
8316
+ this.outputHelp({ error: true });
8317
+ }
8318
+ const config = errorOptions || {};
8319
+ const exitCode = config.exitCode || 1;
8320
+ const code = config.code || "commander.error";
8321
+ this._exit(exitCode, code, message);
8322
+ }
8323
+ /**
8324
+ * Apply any option related environment variables, if option does
8325
+ * not have a value from cli or client code.
8326
+ *
8327
+ * @private
8328
+ */
8329
+ _parseOptionsEnv() {
8330
+ this.options.forEach((option) => {
8331
+ if (option.envVar && option.envVar in process2.env) {
8332
+ const optionKey = option.attributeName();
8333
+ if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(
8334
+ this.getOptionValueSource(optionKey)
8335
+ )) {
8336
+ if (option.required || option.optional) {
8337
+ this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
8338
+ } else {
8339
+ this.emit(`optionEnv:${option.name()}`);
8340
+ }
8341
+ }
8342
+ }
8343
+ });
8344
+ }
8345
+ /**
8346
+ * Apply any implied option values, if option is undefined or default value.
8347
+ *
8348
+ * @private
8349
+ */
8350
+ _parseOptionsImplied() {
8351
+ const dualHelper = new DualOptions(this.options);
8352
+ const hasCustomOptionValue = (optionKey) => {
8353
+ return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
8354
+ };
8355
+ this.options.filter(
8356
+ (option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(
8357
+ this.getOptionValue(option.attributeName()),
8358
+ option
8359
+ )
8360
+ ).forEach((option) => {
8361
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
8362
+ this.setOptionValueWithSource(
8363
+ impliedKey,
8364
+ option.implied[impliedKey],
8365
+ "implied"
8366
+ );
8367
+ });
8368
+ });
8369
+ }
8370
+ /**
8371
+ * Argument `name` is missing.
8372
+ *
8373
+ * @param {string} name
8374
+ * @private
8375
+ */
8376
+ missingArgument(name) {
8377
+ const message = `error: missing required argument '${name}'`;
8378
+ this.error(message, { code: "commander.missingArgument" });
8379
+ }
8380
+ /**
8381
+ * `Option` is missing an argument.
8382
+ *
8383
+ * @param {Option} option
8384
+ * @private
8385
+ */
8386
+ optionMissingArgument(option) {
8387
+ const message = `error: option '${option.flags}' argument missing`;
8388
+ this.error(message, { code: "commander.optionMissingArgument" });
8389
+ }
8390
+ /**
8391
+ * `Option` does not have a value, and is a mandatory option.
8392
+ *
8393
+ * @param {Option} option
8394
+ * @private
8395
+ */
8396
+ missingMandatoryOptionValue(option) {
8397
+ const message = `error: required option '${option.flags}' not specified`;
8398
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
8399
+ }
8400
+ /**
8401
+ * `Option` conflicts with another option.
8402
+ *
8403
+ * @param {Option} option
8404
+ * @param {Option} conflictingOption
8405
+ * @private
8406
+ */
8407
+ _conflictingOption(option, conflictingOption) {
8408
+ const findBestOptionFromValue = (option2) => {
8409
+ const optionKey = option2.attributeName();
8410
+ const optionValue = this.getOptionValue(optionKey);
8411
+ const negativeOption = this.options.find(
8412
+ (target) => target.negate && optionKey === target.attributeName()
8413
+ );
8414
+ const positiveOption = this.options.find(
8415
+ (target) => !target.negate && optionKey === target.attributeName()
8416
+ );
8417
+ if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
8418
+ return negativeOption;
8419
+ }
8420
+ return positiveOption || option2;
8421
+ };
8422
+ const getErrorMessage = (option2) => {
8423
+ const bestOption = findBestOptionFromValue(option2);
8424
+ const optionKey = bestOption.attributeName();
8425
+ const source = this.getOptionValueSource(optionKey);
8426
+ if (source === "env") {
8427
+ return `environment variable '${bestOption.envVar}'`;
8428
+ }
8429
+ return `option '${bestOption.flags}'`;
8430
+ };
8431
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
8432
+ this.error(message, { code: "commander.conflictingOption" });
8433
+ }
8434
+ /**
8435
+ * Unknown option `flag`.
8436
+ *
8437
+ * @param {string} flag
8438
+ * @private
8439
+ */
8440
+ unknownOption(flag) {
8441
+ if (this._allowUnknownOption)
8442
+ return;
8443
+ let suggestion = "";
8444
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
8445
+ let candidateFlags = [];
8446
+ let command2 = this;
8447
+ do {
8448
+ const moreFlags = command2.createHelp().visibleOptions(command2).filter((option) => option.long).map((option) => option.long);
8449
+ candidateFlags = candidateFlags.concat(moreFlags);
8450
+ command2 = command2.parent;
8451
+ } while (command2 && !command2._enablePositionalOptions);
8452
+ suggestion = suggestSimilar(flag, candidateFlags);
8453
+ }
8454
+ const message = `error: unknown option '${flag}'${suggestion}`;
8455
+ this.error(message, { code: "commander.unknownOption" });
8456
+ }
8457
+ /**
8458
+ * Excess arguments, more than expected.
8459
+ *
8460
+ * @param {string[]} receivedArgs
8461
+ * @private
8462
+ */
8463
+ _excessArguments(receivedArgs) {
8464
+ if (this._allowExcessArguments)
8465
+ return;
8466
+ const expected = this.registeredArguments.length;
8467
+ const s = expected === 1 ? "" : "s";
8468
+ const received = receivedArgs.length;
8469
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
8470
+ const details = receivedArgs.join(", ");
8471
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${received}: ${details}.`;
8472
+ this.error(message, { code: "commander.excessArguments" });
8473
+ }
8474
+ /**
8475
+ * Unknown command.
8476
+ *
8477
+ * @private
8478
+ */
8479
+ unknownCommand() {
8480
+ const unknownName = this.args[0];
8481
+ let suggestion = "";
8482
+ if (this._showSuggestionAfterError) {
8483
+ const candidateNames = [];
8484
+ this.createHelp().visibleCommands(this).forEach((command2) => {
8485
+ candidateNames.push(command2.name());
8486
+ if (command2.alias())
8487
+ candidateNames.push(command2.alias());
8488
+ });
8489
+ suggestion = suggestSimilar(unknownName, candidateNames);
8490
+ }
8491
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
8492
+ this.error(message, { code: "commander.unknownCommand" });
8493
+ }
8494
+ /**
8495
+ * Get or set the program version.
8496
+ *
8497
+ * This method auto-registers the "-V, --version" option which will print the version number.
8498
+ *
8499
+ * You can optionally supply the flags and description to override the defaults.
8500
+ *
8501
+ * @param {string} [str]
8502
+ * @param {string} [flags]
8503
+ * @param {string} [description]
8504
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
8505
+ */
8506
+ version(str, flags, description) {
8507
+ if (str === void 0)
8508
+ return this._version;
8509
+ this._version = str;
8510
+ flags = flags || "-V, --version";
8511
+ description = description || "output the version number";
8512
+ const versionOption = this.createOption(flags, description);
8513
+ this._versionOptionName = versionOption.attributeName();
8514
+ this._registerOption(versionOption);
8515
+ this.on("option:" + versionOption.name(), () => {
8516
+ this._outputConfiguration.writeOut(`${str}
8517
+ `);
8518
+ this._exit(0, "commander.version", str);
8519
+ });
8520
+ return this;
8521
+ }
8522
+ /**
8523
+ * Set the description.
8524
+ *
8525
+ * @param {string} [str]
8526
+ * @param {object} [argsDescription]
8527
+ * @return {(string|Command)}
8528
+ */
8529
+ description(str, argsDescription) {
8530
+ if (str === void 0 && argsDescription === void 0)
8531
+ return this._description;
8532
+ this._description = str;
8533
+ if (argsDescription) {
8534
+ this._argsDescription = argsDescription;
8535
+ }
8536
+ return this;
8537
+ }
8538
+ /**
8539
+ * Set the summary. Used when listed as subcommand of parent.
8540
+ *
8541
+ * @param {string} [str]
8542
+ * @return {(string|Command)}
8543
+ */
8544
+ summary(str) {
8545
+ if (str === void 0)
8546
+ return this._summary;
8547
+ this._summary = str;
8548
+ return this;
8549
+ }
8550
+ /**
8551
+ * Set an alias for the command.
8552
+ *
8553
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
8554
+ *
8555
+ * @param {string} [alias]
8556
+ * @return {(string|Command)}
8557
+ */
8558
+ alias(alias) {
8559
+ if (alias === void 0)
8560
+ return this._aliases[0];
8561
+ let command2 = this;
8562
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
8563
+ command2 = this.commands[this.commands.length - 1];
8564
+ }
8565
+ if (alias === command2._name)
8566
+ throw new Error("Command alias can't be the same as its name");
8567
+ const matchingCommand = this.parent?._findCommand(alias);
8568
+ if (matchingCommand) {
8569
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
8570
+ throw new Error(
8571
+ `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`
8572
+ );
8573
+ }
8574
+ command2._aliases.push(alias);
8575
+ return this;
8576
+ }
8577
+ /**
8578
+ * Set aliases for the command.
8579
+ *
8580
+ * Only the first alias is shown in the auto-generated help.
8581
+ *
8582
+ * @param {string[]} [aliases]
8583
+ * @return {(string[]|Command)}
8584
+ */
8585
+ aliases(aliases) {
8586
+ if (aliases === void 0)
8587
+ return this._aliases;
8588
+ aliases.forEach((alias) => this.alias(alias));
8589
+ return this;
8590
+ }
8591
+ /**
8592
+ * Set / get the command usage `str`.
8593
+ *
8594
+ * @param {string} [str]
8595
+ * @return {(string|Command)}
8596
+ */
8597
+ usage(str) {
8598
+ if (str === void 0) {
8599
+ if (this._usage)
8600
+ return this._usage;
8601
+ const args = this.registeredArguments.map((arg) => {
8602
+ return humanReadableArgName(arg);
8603
+ });
8604
+ return [].concat(
8605
+ this.options.length || this._helpOption !== null ? "[options]" : [],
8606
+ this.commands.length ? "[command]" : [],
8607
+ this.registeredArguments.length ? args : []
8608
+ ).join(" ");
8609
+ }
8610
+ this._usage = str;
8611
+ return this;
8612
+ }
8613
+ /**
8614
+ * Get or set the name of the command.
8615
+ *
8616
+ * @param {string} [str]
8617
+ * @return {(string|Command)}
8618
+ */
8619
+ name(str) {
8620
+ if (str === void 0)
8621
+ return this._name;
8622
+ this._name = str;
8623
+ return this;
8624
+ }
8625
+ /**
8626
+ * Set/get the help group heading for this subcommand in parent command's help.
8627
+ *
8628
+ * @param {string} [heading]
8629
+ * @return {Command | string}
8630
+ */
8631
+ helpGroup(heading) {
8632
+ if (heading === void 0)
8633
+ return this._helpGroupHeading ?? "";
8634
+ this._helpGroupHeading = heading;
8635
+ return this;
8636
+ }
8637
+ /**
8638
+ * Set/get the default help group heading for subcommands added to this command.
8639
+ * (This does not override a group set directly on the subcommand using .helpGroup().)
8640
+ *
8641
+ * @example
8642
+ * program.commandsGroup('Development Commands:);
8643
+ * program.command('watch')...
8644
+ * program.command('lint')...
8645
+ * ...
8646
+ *
8647
+ * @param {string} [heading]
8648
+ * @returns {Command | string}
8649
+ */
8650
+ commandsGroup(heading) {
8651
+ if (heading === void 0)
8652
+ return this._defaultCommandGroup ?? "";
8653
+ this._defaultCommandGroup = heading;
8654
+ return this;
8655
+ }
8656
+ /**
8657
+ * Set/get the default help group heading for options added to this command.
8658
+ * (This does not override a group set directly on the option using .helpGroup().)
8659
+ *
8660
+ * @example
8661
+ * program
8662
+ * .optionsGroup('Development Options:')
8663
+ * .option('-d, --debug', 'output extra debugging')
8664
+ * .option('-p, --profile', 'output profiling information')
8665
+ *
8666
+ * @param {string} [heading]
8667
+ * @returns {Command | string}
8668
+ */
8669
+ optionsGroup(heading) {
8670
+ if (heading === void 0)
8671
+ return this._defaultOptionGroup ?? "";
8672
+ this._defaultOptionGroup = heading;
8673
+ return this;
8674
+ }
8675
+ /**
8676
+ * @param {Option} option
8677
+ * @private
8678
+ */
8679
+ _initOptionGroup(option) {
8680
+ if (this._defaultOptionGroup && !option.helpGroupHeading)
8681
+ option.helpGroup(this._defaultOptionGroup);
8682
+ }
8683
+ /**
8684
+ * @param {Command} cmd
8685
+ * @private
8686
+ */
8687
+ _initCommandGroup(cmd) {
8688
+ if (this._defaultCommandGroup && !cmd.helpGroup())
8689
+ cmd.helpGroup(this._defaultCommandGroup);
8690
+ }
8691
+ /**
8692
+ * Set the name of the command from script filename, such as process.argv[1],
8693
+ * or import.meta.filename.
8694
+ *
8695
+ * (Used internally and public although not documented in README.)
8696
+ *
8697
+ * @example
8698
+ * program.nameFromFilename(import.meta.filename);
8699
+ *
8700
+ * @param {string} filename
8701
+ * @return {Command}
8702
+ */
8703
+ nameFromFilename(filename) {
8704
+ this._name = path.basename(filename, path.extname(filename));
8705
+ return this;
8706
+ }
8707
+ /**
8708
+ * Get or set the directory for searching for executable subcommands of this command.
8709
+ *
8710
+ * @example
8711
+ * program.executableDir(import.meta.dirname);
8712
+ * // or
8713
+ * program.executableDir('subcommands');
8714
+ *
8715
+ * @param {string} [path]
8716
+ * @return {(string|null|Command)}
8717
+ */
8718
+ executableDir(path3) {
8719
+ if (path3 === void 0)
8720
+ return this._executableDir;
8721
+ this._executableDir = path3;
8722
+ return this;
8723
+ }
8724
+ /**
8725
+ * Return program help documentation.
8726
+ *
8727
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
8728
+ * @return {string}
8729
+ */
8730
+ helpInformation(contextOptions) {
8731
+ const helper = this.createHelp();
8732
+ const context = this._getOutputContext(contextOptions);
8733
+ helper.prepareContext({
8734
+ error: context.error,
8735
+ helpWidth: context.helpWidth,
8736
+ outputHasColors: context.hasColors
8737
+ });
8738
+ const text = helper.formatHelp(this, helper);
8739
+ if (context.hasColors)
8740
+ return text;
8741
+ return this._outputConfiguration.stripColor(text);
8742
+ }
8743
+ /**
8744
+ * @typedef HelpContext
8745
+ * @type {object}
8746
+ * @property {boolean} error
8747
+ * @property {number} helpWidth
8748
+ * @property {boolean} hasColors
8749
+ * @property {function} write - includes stripColor if needed
8750
+ *
8751
+ * @returns {HelpContext}
8752
+ * @private
8753
+ */
8754
+ _getOutputContext(contextOptions) {
8755
+ contextOptions = contextOptions || {};
8756
+ const error = !!contextOptions.error;
8757
+ let baseWrite;
8758
+ let hasColors;
8759
+ let helpWidth;
8760
+ if (error) {
8761
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
8762
+ hasColors = this._outputConfiguration.getErrHasColors();
8763
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
8764
+ } else {
8765
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
8766
+ hasColors = this._outputConfiguration.getOutHasColors();
8767
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
8768
+ }
8769
+ const write = (str) => {
8770
+ if (!hasColors)
8771
+ str = this._outputConfiguration.stripColor(str);
8772
+ return baseWrite(str);
8773
+ };
8774
+ return { error, write, hasColors, helpWidth };
8775
+ }
8776
+ /**
8777
+ * Output help information for this command.
8778
+ *
8779
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
8780
+ *
8781
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
8782
+ */
8783
+ outputHelp(contextOptions) {
8784
+ let deprecatedCallback;
8785
+ if (typeof contextOptions === "function") {
8786
+ deprecatedCallback = contextOptions;
8787
+ contextOptions = void 0;
8788
+ }
8789
+ const outputContext = this._getOutputContext(contextOptions);
8790
+ const eventContext = {
8791
+ error: outputContext.error,
8792
+ write: outputContext.write,
8793
+ command: this
8794
+ };
8795
+ this._getCommandAndAncestors().reverse().forEach((command2) => command2.emit("beforeAllHelp", eventContext));
8796
+ this.emit("beforeHelp", eventContext);
8797
+ let helpInformation = this.helpInformation({ error: outputContext.error });
8798
+ if (deprecatedCallback) {
8799
+ helpInformation = deprecatedCallback(helpInformation);
8800
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
8801
+ throw new Error("outputHelp callback must return a string or a Buffer");
8802
+ }
8803
+ }
8804
+ outputContext.write(helpInformation);
8805
+ if (this._getHelpOption()?.long) {
8806
+ this.emit(this._getHelpOption().long);
8807
+ }
8808
+ this.emit("afterHelp", eventContext);
8809
+ this._getCommandAndAncestors().forEach(
8810
+ (command2) => command2.emit("afterAllHelp", eventContext)
8811
+ );
8812
+ }
8813
+ /**
8814
+ * You can pass in flags and a description to customise the built-in help option.
8815
+ * Pass in false to disable the built-in help option.
8816
+ *
8817
+ * @example
8818
+ * program.helpOption('-?, --help' 'show help'); // customise
8819
+ * program.helpOption(false); // disable
8820
+ *
8821
+ * @param {(string | boolean)} flags
8822
+ * @param {string} [description]
8823
+ * @return {Command} `this` command for chaining
8824
+ */
8825
+ helpOption(flags, description) {
8826
+ if (typeof flags === "boolean") {
8827
+ if (flags) {
8828
+ if (this._helpOption === null)
8829
+ this._helpOption = void 0;
8830
+ if (this._defaultOptionGroup) {
8831
+ this._initOptionGroup(this._getHelpOption());
8832
+ }
8833
+ } else {
8834
+ this._helpOption = null;
8835
+ }
8836
+ return this;
8837
+ }
8838
+ this._helpOption = this.createOption(
8839
+ flags ?? "-h, --help",
8840
+ description ?? "display help for command"
8841
+ );
8842
+ if (flags || description)
8843
+ this._initOptionGroup(this._helpOption);
8844
+ return this;
8845
+ }
8846
+ /**
8847
+ * Lazy create help option.
8848
+ * Returns null if has been disabled with .helpOption(false).
8849
+ *
8850
+ * @returns {(Option | null)} the help option
8851
+ * @package
8852
+ */
8853
+ _getHelpOption() {
8854
+ if (this._helpOption === void 0) {
8855
+ this.helpOption(void 0, void 0);
8856
+ }
8857
+ return this._helpOption;
8858
+ }
8859
+ /**
8860
+ * Supply your own option to use for the built-in help option.
8861
+ * This is an alternative to using helpOption() to customise the flags and description etc.
8862
+ *
8863
+ * @param {Option} option
8864
+ * @return {Command} `this` command for chaining
8865
+ */
8866
+ addHelpOption(option) {
8867
+ this._helpOption = option;
8868
+ this._initOptionGroup(option);
8869
+ return this;
8870
+ }
8871
+ /**
8872
+ * Output help information and exit.
8873
+ *
8874
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
8875
+ *
8876
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
8877
+ */
8878
+ help(contextOptions) {
8879
+ this.outputHelp(contextOptions);
8880
+ let exitCode = Number(process2.exitCode ?? 0);
8881
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
8882
+ exitCode = 1;
8883
+ }
8884
+ this._exit(exitCode, "commander.help", "(outputHelp)");
8885
+ }
8886
+ /**
8887
+ * // Do a little typing to coordinate emit and listener for the help text events.
8888
+ * @typedef HelpTextEventContext
8889
+ * @type {object}
8890
+ * @property {boolean} error
8891
+ * @property {Command} command
8892
+ * @property {function} write
8893
+ */
8894
+ /**
8895
+ * Add additional text to be displayed with the built-in help.
8896
+ *
8897
+ * Position is 'before' or 'after' to affect just this command,
8898
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
8899
+ *
8900
+ * @param {string} position - before or after built-in help
8901
+ * @param {(string | Function)} text - string to add, or a function returning a string
8902
+ * @return {Command} `this` command for chaining
8903
+ */
8904
+ addHelpText(position, text) {
8905
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
8906
+ if (!allowedValues.includes(position)) {
8907
+ throw new Error(`Unexpected value for position to addHelpText.
8908
+ Expecting one of '${allowedValues.join("', '")}'`);
8909
+ }
8910
+ const helpEvent = `${position}Help`;
8911
+ this.on(helpEvent, (context) => {
8912
+ let helpStr;
8913
+ if (typeof text === "function") {
8914
+ helpStr = text({ error: context.error, command: context.command });
8915
+ } else {
8916
+ helpStr = text;
8917
+ }
8918
+ if (helpStr) {
8919
+ context.write(`${helpStr}
8920
+ `);
8921
+ }
8922
+ });
8923
+ return this;
8924
+ }
8925
+ /**
8926
+ * Output help information if help flags specified
8927
+ *
8928
+ * @param {Array} args - array of options to search for help flags
8929
+ * @private
8930
+ */
8931
+ _outputHelpIfRequested(args) {
8932
+ const helpOption = this._getHelpOption();
8933
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
8934
+ if (helpRequested) {
8935
+ this.outputHelp();
8936
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
8937
+ }
8938
+ }
8939
+ };
8940
+ function incrementNodeInspectorPort(args) {
8941
+ return args.map((arg) => {
8942
+ if (!arg.startsWith("--inspect")) {
8943
+ return arg;
8944
+ }
8945
+ let debugOption;
8946
+ let debugHost = "127.0.0.1";
8947
+ let debugPort = "9229";
8948
+ let match;
8949
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
8950
+ debugOption = match[1];
8951
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
8952
+ debugOption = match[1];
8953
+ if (/^\d+$/.test(match[3])) {
8954
+ debugPort = match[3];
8955
+ } else {
8956
+ debugHost = match[3];
8957
+ }
8958
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
8959
+ debugOption = match[1];
8960
+ debugHost = match[3];
8961
+ debugPort = match[4];
8962
+ }
8963
+ if (debugOption && debugPort !== "0") {
8964
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
8965
+ }
8966
+ return arg;
8967
+ });
8968
+ }
8969
+ function useColor() {
8970
+ if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
8971
+ return false;
8972
+ if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== void 0)
8973
+ return true;
8974
+ return void 0;
8975
+ }
8976
+
8977
+ // node_modules/commander/index.js
8978
+ var program = new Command();
8979
+
5562
8980
  // cli.ts
8981
+ import process3 from "node:process";
5563
8982
  var __filename = fileURLToPath2(import.meta.url);
5564
- var __dirname2 = path.dirname(__filename);
8983
+ var __dirname2 = path2.dirname(__filename);
5565
8984
  var require22 = createRequire3(import.meta.url);
5566
- var nativeBindingPath = path.resolve(__dirname2, "./blaze.win32-x64-msvc.node");
8985
+ var nativeBindingPath = path2.resolve(__dirname2, "./blaze.win32-x64-msvc.node");
5567
8986
  var blazeCore;
5568
8987
  try {
5569
8988
  blazeCore = require22(nativeBindingPath);
5570
8989
  } catch (e) {
5571
8990
  console.error(`\u274C Failed to load native C++ bindings from ${nativeBindingPath}`);
5572
- process.exit(1);
8991
+ process3.exit(1);
5573
8992
  }
5574
8993
  var i18n = {
5575
8994
  "en-US": {
@@ -5609,6 +9028,7 @@ var i18n = {
5609
9028
  volume: "\u{1F4CA} Throughput Velocity & Workload Volume",
5610
9029
  concurrency: "\u{1F504} Active Concurrency (VUs) vs. TTF Trend & AI Load Forecast",
5611
9030
  status: "\u{1F369} HTTP Status Code Proportions",
9031
+ verbs: "\u{1F369} HTTP Verb Distribution",
5612
9032
  scatter: "\u{1F4C8} Time-to-First-Byte Scatter Plot"
5613
9033
  },
5614
9034
  telemetry: {
@@ -5661,6 +9081,7 @@ var i18n = {
5661
9081
  volume: "\u{1F4CA} Velocidad de Rendimiento y Carga de Trabajo",
5662
9082
  concurrency: "\u{1F504} Concurrencia (VUs) vs Tendencia TTF",
5663
9083
  status: "\u{1F369} Proporciones de C\xF3digos HTTP",
9084
+ verbs: "\u{1F369} Distribuci\xF3n de Verbos HTTP",
5664
9085
  scatter: "\u{1F4C8} Gr\xE1fico de Dispersi\xF3n de Tiempo de Respuesta"
5665
9086
  },
5666
9087
  telemetry: {
@@ -5713,6 +9134,7 @@ var i18n = {
5713
9134
  volume: "\u{1F4CA} \u0633\u0631\u0639\u0629 \u0627\u0644\u0625\u0646\u062A\u0627\u062C\u064A\u0629 \u0648\u062D\u062C\u0645 \u0639\u0628\u0621 \u0627\u0644\u0639\u0645\u0644",
5714
9135
  concurrency: "\u{1F504} \u0627\u0644\u062A\u0632\u0627\u0645\u0646 \u0627\u0644\u0646\u0634\u0637 (VUs) \u0645\u0642\u0627\u0628\u0644 \u0627\u062A\u062C\u0627\u0647 TTF \u0648\u062A\u0648\u0642\u0639\u0627\u062A \u0627\u0644\u062D\u0645\u0644",
5715
9136
  status: "\u{1F369} \u0646\u0633\u0628 \u0631\u0645\u0648\u0632 \u062D\u0627\u0644\u0629 HTTP",
9137
+ verbs: "\u{1F369} \u062A\u0648\u0632\u064A\u0639 \u0623\u0641\u0639\u0627\u0644 HTTP",
5716
9138
  scatter: "\u{1F4C8} \u0645\u062E\u0637\u0637 \u0627\u0644\u062A\u0634\u062A\u062A \u0644\u0644\u0648\u0642\u062A \u0644\u0623\u0648\u0644 \u0628\u0627\u064A\u062A"
5717
9139
  },
5718
9140
  telemetry: {
@@ -5762,6 +9184,7 @@ var i18n = {
5762
9184
  volume: "\u{1F4CA} \u0925\u094D\u0930\u0942\u092A\u0941\u091F \u0935\u0947\u0917 \u0914\u0930 \u0935\u0930\u094D\u0915\u0932\u094B\u0921 \u0935\u0949\u0932\u094D\u092F\u0942\u092E",
5763
9185
  concurrency: "\u{1F504} \u0938\u0915\u094D\u0930\u093F\u092F \u0938\u092E\u0935\u0930\u094D\u0924\u0940 (VUs) \u092C\u0928\u093E\u092E TTF \u091F\u094D\u0930\u0947\u0902\u0921",
5764
9186
  status: "\u{1F369} HTTP \u0938\u094D\u091F\u0947\u091F\u0938 \u0915\u094B\u0921 \u0905\u0928\u0941\u092A\u093E\u0924",
9187
+ verbs: "\u{1F369} HTTP \u0935\u0930\u094D\u092C \u0935\u093F\u0924\u0930\u0923",
5765
9188
  scatter: "\u{1F4C8} \u091F\u093E\u0907\u092E-\u091F\u0942-\u092B\u0930\u094D\u0938\u094D\u091F-\u092C\u093E\u0907\u091F \u0938\u094D\u0915\u0948\u091F\u0930 \u092A\u094D\u0932\u0949\u091F"
5766
9189
  },
5767
9190
  telemetry: {
@@ -5811,6 +9234,7 @@ var i18n = {
5811
9234
  volume: "\u{1F4CA} \u0B9A\u0BC6\u0BAF\u0BB2\u0BCD\u0BA4\u0BBF\u0BB1\u0BA9\u0BCD \u0BB5\u0BC7\u0B95\u0BAE\u0BCD \u0BAE\u0BB1\u0BCD\u0BB1\u0BC1\u0BAE\u0BCD \u0BAA\u0BA3\u0BBF\u0B9A\u0BCD\u0B9A\u0BC1\u0BAE\u0BC8",
5812
9235
  concurrency: "\u{1F504} \u0B9A\u0BC6\u0BAF\u0BB2\u0BBF\u0BB2\u0BCD \u0B89\u0BB3\u0BCD\u0BB3 \u0B87\u0BA3\u0BC8\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD (VUs) \u0BAE\u0BB1\u0BCD\u0BB1\u0BC1\u0BAE\u0BCD TTF \u0BAA\u0BCB\u0B95\u0BCD\u0B95\u0BC1",
5813
9236
  status: "\u{1F369} HTTP \u0BA8\u0BBF\u0BB2\u0BC8 \u0B95\u0BC1\u0BB1\u0BBF\u0BAF\u0BC0\u0B9F\u0BC1 \u0BB5\u0BBF\u0B95\u0BBF\u0BA4\u0B99\u0BCD\u0B95\u0BB3\u0BCD",
9237
+ verbs: "\u{1F369} HTTP \u0BB5\u0BBF\u0BA9\u0BC8\u0B9A\u0BCD\u0B9A\u0BCA\u0BB2\u0BCD \u0BB5\u0BBF\u0BA8\u0BBF\u0BAF\u0BCB\u0B95\u0BAE\u0BCD",
5814
9238
  scatter: "\u{1F4C8} TTFB \u0B9A\u0BBF\u0BA4\u0BB1\u0BB2\u0BCD \u0BB5\u0BB0\u0BC8\u0BAA\u0B9F\u0BAE\u0BCD"
5815
9239
  },
5816
9240
  telemetry: {
@@ -5860,13 +9284,14 @@ var i18n = {
5860
9284
  volume: "\u{1F4CA} \u0DB4\u0DCA\u200D\u0DBB\u0DC0\u0DCF\u0DC4 \u0DC0\u0DDA\u0D9C\u0DBA \u0DC3\u0DC4 \u0DC0\u0DD0\u0DA9 \u0DB6\u0DBB",
5861
9285
  concurrency: "\u{1F504} \u0DC3\u0D9A\u0DCA\u200D\u0DBB\u0DD3\u0DBA \u0DC3\u0DB8\u0D9C\u0DCF\u0DB8\u0DD3\u0DAD\u0DCA\u0DC0\u0DBA (VUs) \u0DC3\u0DC4 TTF \u0DB4\u0DCA\u200D\u0DBB\u0DC0\u0DAB\u0DAD\u0DCF\u0DC0",
5862
9286
  status: "\u{1F369} HTTP \u0DAD\u0DAD\u0DCA\u0DC0 \u0D9A\u0DDA\u0DAD \u0D85\u0DB1\u0DD4\u0DB4\u0DCF\u0DAD",
9287
+ verbs: "\u{1F369} HTTP \u0D9A\u0DCA\u200D\u0DBB\u0DD2\u0DBA\u0DCF\u0DB4\u0DAF \u0DB6\u0DD9\u0DAF\u0DCF\u0DC4\u0DD0\u0DBB\u0DD3\u0DB8",
5863
9288
  scatter: "\u{1F4C8} TTFB \u0DC3\u0DCA\u0D9A\u0DD0\u0DA7\u0DBB\u0DCA \u0DB4\u0DCA\u0DBD\u0DDC\u0DA7\u0DCA"
5864
9289
  },
5865
9290
  telemetry: {
5866
9291
  title: "\u0DA7\u0DD9\u0DBD\u0DD2\u0DB8\u0DD9\u0DA7\u0DCA\u200D\u0DBB\u0DD2 \u0D85\u0DB1\u0DD4\u0D9A\u0DD8\u0DAD\u0DD2 \u0DBD\u0DDC\u0D9C\u0DCA",
5867
9292
  threads: "\u0DC3\u0DB8\u0D9C\u0DCF\u0DB8\u0DD3\u0DAD\u0DCA\u0DC0\u0DBA (Threads)",
5868
9293
  throughput: "\u0DB4\u0DCA\u200D\u0DBB\u0DC0\u0DCF\u0DC4 \u0D85\u0DB1\u0DD4\u0DB4\u0DCF\u0DAD\u0DBA",
5869
- avgLatency: "\u0DC3\u0DCF\u0DB8\u0DCF\u0DB1\u0DCA\u200D\u0E22 \u0DB4\u0DCA\u200D\u0DBB\u0DB8\u0DCF\u0DAF\u0DBA",
9294
+ avgLatency: "\u0DC3\u0DCF\u0DB8\u0DCF\u0DB1\u0DCA\u200D\u0DBA \u0DB4\u0DCA\u200D\u0DBB\u0DB8\u0DCF\u0DAF\u0DBA",
5870
9295
  p95: "P95 \u0DB4\u0DCA\u200D\u0DBB\u0DB8\u0DCF\u0DAF\u0DBA",
5871
9296
  errors: "\u0DAF\u0DDD\u0DC2 \u0D85\u0DB1\u0DD4\u0DB4\u0DCF\u0DAD\u0DBA",
5872
9297
  status: "\u0DAD\u0DAD\u0DCA\u0DC0\u0DBA",
@@ -5907,10 +9332,10 @@ function loadBaselineData(filePath) {
5907
9332
  if (!filePath)
5908
9333
  return null;
5909
9334
  try {
5910
- const resolved = path.resolve(filePath);
5911
- if (fs.existsSync(resolved)) {
9335
+ const resolved = path2.resolve(filePath);
9336
+ if (fs2.existsSync(resolved)) {
5912
9337
  console.log(`\u{1F4C1} Loaded baseline comparison telemetry from: ${resolved}`);
5913
- return JSON.parse(fs.readFileSync(resolved, "utf-8"));
9338
+ return JSON.parse(fs2.readFileSync(resolved, "utf-8"));
5914
9339
  }
5915
9340
  } catch (e) {
5916
9341
  console.error(`\u274C Failed to parse baseline telemetry file: ${e}`);
@@ -5949,7 +9374,7 @@ function getCrossBrowserMatrixData() {
5949
9374
  ];
5950
9375
  }
5951
9376
  async function generateElifExplanation(metrics) {
5952
- const apiKey = process.env.GEMINI_API_KEY;
9377
+ const apiKey = process3.env.GEMINI_API_KEY;
5953
9378
  if (!apiKey) {
5954
9379
  console.warn("\u26A0\uFE0F Warning: GEMINI_API_KEY missing. Skipping ELIF plain-language breakdown.");
5955
9380
  return null;
@@ -5976,7 +9401,7 @@ ${JSON.stringify(metrics, null, 2)}
5976
9401
  }
5977
9402
  }
5978
9403
  async function generateWittyAudioBriefing(cards) {
5979
- const apiKey = process.env.GEMINI_API_KEY;
9404
+ const apiKey = process3.env.GEMINI_API_KEY;
5980
9405
  if (!apiKey) {
5981
9406
  return "Hey Product Manager! Here is your quick performance update. Actually, your Gemini API Key is missing, so I am improvising. Your health score is sitting at " + cards.healthScore + " out of 100. Check the logs, configure your credentials, and let's make it snappy next time!";
5982
9407
  }
@@ -6004,7 +9429,7 @@ Compose a witty, energetic daily audio update script that takes exactly 30 secon
6004
9429
  }
6005
9430
  }
6006
9431
  async function generateGeminiRCA(history, finalSummary, errorLogs) {
6007
- const apiKey = process.env.GEMINI_API_KEY;
9432
+ const apiKey = process3.env.GEMINI_API_KEY;
6008
9433
  if (!apiKey) {
6009
9434
  return `<span style="color: #ef4444;">\u26A0\uFE0F Gemini API Key missing. Export GEMINI_API_KEY to enable automated 2.5 Flash RCA analysis.</span>`;
6010
9435
  }
@@ -6137,11 +9562,11 @@ Generate the complete TypeScript test script now.`;
6137
9562
  }
6138
9563
  }
6139
9564
  async function runCli() {
6140
- const argv = await yargs_default(hideBin(process.argv)).usage("Usage: blaze-performance-tester <script-path> [options]").option("prompt", {
9565
+ const argv = await yargs_default(hideBin(process3.argv)).usage("Usage: blaze-performance-tester <script-path> [options]").option("prompt", {
6141
9566
  describe: "Natural language scenario to generate the test script",
6142
9567
  type: "string"
6143
9568
  }).option("threads", { type: "number", description: "Number of concurrent threads" }).option("duration", { type: "number", description: "Test duration in seconds" }).option("ramp-up", { type: "number", description: "Ramp-up time in seconds" }).option("ramp-down", { type: "number", description: "Ramp-down time in seconds" }).option("locale", { type: "string", description: "Dashboard UI Locale (e.g. en-US, es-ES, ar-AE)" }).help(false).strict(false).argv;
6144
- const args = process.argv.slice(2);
9569
+ const args = process3.argv.slice(2);
6145
9570
  if (args.length === 0 || args.includes("--help") || args.includes("-h")) {
6146
9571
  printUsage();
6147
9572
  return;
@@ -6160,21 +9585,21 @@ async function runCli() {
6160
9585
  const promptText = argv.prompt;
6161
9586
  try {
6162
9587
  const scriptContent = await generateTestScriptFromPrompt(promptText, config);
6163
- const dir = path.dirname(config.targetScript);
6164
- if (!fs.existsSync(dir)) {
6165
- fs.mkdirSync(dir, { recursive: true });
9588
+ const dir = path2.dirname(config.targetScript);
9589
+ if (!fs2.existsSync(dir)) {
9590
+ fs2.mkdirSync(dir, { recursive: true });
6166
9591
  }
6167
- fs.writeFileSync(config.targetScript, scriptContent, "utf-8");
9592
+ fs2.writeFileSync(config.targetScript, scriptContent, "utf-8");
6168
9593
  console.log(`[Success] Test script generated at: ${config.targetScript}
6169
9594
  `);
6170
9595
  } catch (error) {
6171
9596
  console.error(`[Error] Failed to generate script from prompt:`, error);
6172
- process.exit(1);
9597
+ process3.exit(1);
6173
9598
  }
6174
9599
  }
6175
- if (!fs.existsSync(config.targetScript)) {
9600
+ if (!fs2.existsSync(config.targetScript)) {
6176
9601
  console.error(`[Error] Test script not found at ${config.targetScript}.`);
6177
- process.exit(1);
9602
+ process3.exit(1);
6178
9603
  }
6179
9604
  console.log(`Starting performance test using script: ${config.targetScript}`);
6180
9605
  console.log(`Params -> Threads: ${config.threads || 1}, Duration: ${config.durationSec || 0}s, Locale: ${config.locale}`);
@@ -6188,7 +9613,7 @@ async function runCli() {
6188
9613
  }
6189
9614
  }
6190
9615
  function parseArguments(args) {
6191
- const targetScript = path.resolve(args[0] || ".");
9616
+ const targetScript = path2.resolve(args[0] || ".");
6192
9617
  const isAgentic = args.includes("--agentic");
6193
9618
  const isCorrelate = args.includes("--correlate");
6194
9619
  const isSeo = args.includes("--seo");
@@ -6351,6 +9776,7 @@ async function runIntelligentAgenticStressTest(config) {
6351
9776
  let aggregateErrorLogs = [];
6352
9777
  let lastRawRequests = [];
6353
9778
  let total1xx = 0, total2xx = 0, total3xx = 0, total4xx = 0, total5xx = 0;
9779
+ let totalGet = 0, totalPost = 0, totalPut = 0, totalDelete = 0, totalPatch = 0;
6354
9780
  let totalRequestsAccumulator = 0;
6355
9781
  const globalCodeCounts = { 400: 0, 401: 0, 403: 0, 404: 0, 429: 0, 500: 0, 502: 0, 503: 0, 504: 0 };
6356
9782
  const globalMetricsAccumulator = { dns: [], tcp: [], tls: [], ttfb: [], latencies: [], bandwidths: [] };
@@ -6371,6 +9797,11 @@ async function runIntelligentAgenticStressTest(config) {
6371
9797
  total3xx += metrics.c3xx;
6372
9798
  total4xx += metrics.c4xx;
6373
9799
  total5xx += metrics.c5xx;
9800
+ totalGet += metrics.verbCounts.GET;
9801
+ totalPost += metrics.verbCounts.POST;
9802
+ totalPut += metrics.verbCounts.PUT;
9803
+ totalDelete += metrics.verbCounts.DELETE;
9804
+ totalPatch += metrics.verbCounts.PATCH;
6374
9805
  totalRequestsAccumulator += metrics.totalRequests;
6375
9806
  const targetCodes = [400, 401, 403, 404, 429, 500, 502, 503, 504];
6376
9807
  targetCodes.forEach((code) => {
@@ -6472,7 +9903,26 @@ async function runIntelligentAgenticStressTest(config) {
6472
9903
  breakdownRates[code] = totalRequestsAccumulator === 0 ? 0 : globalCodeCounts[code] / totalRequestsAccumulator * 100;
6473
9904
  });
6474
9905
  const baselineData = loadBaselineData(config.baselinePath);
6475
- exportHtmlDashboard(history, config, verdictReason, semanticReport, { total1xx, total2xx, total3xx, total4xx, total5xx, breakdownRates }, finalSummaryCards, lastRawRequests, geminiAnalysisHtml, wittyBriefingText, baselineData);
9906
+ exportHtmlDashboard(
9907
+ history,
9908
+ config,
9909
+ verdictReason,
9910
+ semanticReport,
9911
+ {
9912
+ total1xx,
9913
+ total2xx,
9914
+ total3xx,
9915
+ total4xx,
9916
+ total5xx,
9917
+ breakdownRates,
9918
+ verbCounts: { GET: totalGet, POST: totalPost, PUT: totalPut, DELETE: totalDelete, PATCH: totalPatch }
9919
+ },
9920
+ finalSummaryCards,
9921
+ lastRawRequests,
9922
+ geminiAnalysisHtml,
9923
+ wittyBriefingText,
9924
+ baselineData
9925
+ );
6476
9926
  }
6477
9927
  async function runStandardStressTest(config) {
6478
9928
  console.log(`\u{1F3CB}\uFE0F Running Standard Stress Test [Threads: ${config.threads} | Duration: ${config.durationSec}s | RampUp: ${config.rampUpSec}s | RampDown: ${config.rampDownSec}s]`);
@@ -6541,7 +9991,8 @@ async function runStandardStressTest(config) {
6541
9991
  total3xx: metrics.c3xx,
6542
9992
  total4xx: metrics.c4xx,
6543
9993
  total5xx: metrics.c5xx,
6544
- breakdownRates
9994
+ breakdownRates,
9995
+ verbCounts: metrics.verbCounts
6545
9996
  }, finalSummaryCards, rawRequests, geminiAnalysisHtml, wittyBriefingText, baselineData);
6546
9997
  }
6547
9998
  function getFallbackClusterLogs() {
@@ -6568,6 +10019,7 @@ function generateSimulationData(threads, durationSec, maxAllowedLatencyMs, rampU
6568
10019
  const targetThresholdBreak = Math.max(5, Math.floor(maxAllowedLatencyMs * 0.05));
6569
10020
  const errorPool = getFallbackClusterLogs();
6570
10021
  const deviceProfilesList = ["Mobile Safari", "Desktop Chrome", "Desktop Firefox", "Edge Corporate"];
10022
+ const httpVerbsList = ["GET", "POST", "PUT", "DELETE", "PATCH"];
6571
10023
  for (let i = 0; i < totalRequests; i++) {
6572
10024
  const offsetMs = Math.random() * totalTestMs;
6573
10025
  const loadFactor = getLoadMultiplier(offsetMs, rampUpMs, steadyMs, rampDownMs);
@@ -6595,6 +10047,7 @@ function generateSimulationData(threads, durationSec, maxAllowedLatencyMs, rampU
6595
10047
  statusCode = targetResponseCodes[Math.floor(Math.random() * targetResponseCodes.length)];
6596
10048
  errorMessage = errorPool[Math.floor(Math.random() * errorPool.length)];
6597
10049
  }
10050
+ const verb = httpVerbsList[i % httpVerbsList.length];
6598
10051
  data.push({
6599
10052
  durationMs: isError ? baseLatency * 0.1 : baseLatency,
6600
10053
  timestampMs: startTime + offsetMs,
@@ -6603,7 +10056,8 @@ function generateSimulationData(threads, durationSec, maxAllowedLatencyMs, rampU
6603
10056
  tlsTimeMs: 6 + Math.random() * 1.8,
6604
10057
  statusCode,
6605
10058
  errorMessage,
6606
- deviceProfile
10059
+ deviceProfile,
10060
+ method: verb
6607
10061
  });
6608
10062
  }
6609
10063
  return data.sort((a, b) => a.timestampMs - b.timestampMs);
@@ -6620,6 +10074,7 @@ function processMetricsTelemetry(requests, durationSec) {
6620
10074
  const avgTtfbMs = avgDnsMs + avgTcpMs + avgTlsMs + avgLatencyMs * 0.3;
6621
10075
  let c1xx = 0, c2xx = 0, c3xx = 0, c4xx = 0, c5xx = 0;
6622
10076
  const codeCounts = { 400: 0, 401: 0, 403: 0, 404: 0, 429: 0, 500: 502, 503: 0, 504: 0 };
10077
+ const verbCounts = { GET: 0, POST: 0, PUT: 0, DELETE: 0, PATCH: 0 };
6623
10078
  [400, 401, 403, 404, 429, 500, 502, 503, 504].forEach((c) => codeCounts[c] = 0);
6624
10079
  requests.forEach((r) => {
6625
10080
  if (r.statusCode >= 100 && r.statusCode < 200)
@@ -6635,6 +10090,12 @@ function processMetricsTelemetry(requests, durationSec) {
6635
10090
  if (r.statusCode in codeCounts) {
6636
10091
  codeCounts[r.statusCode]++;
6637
10092
  }
10093
+ const verb = (r.method || "GET").toUpperCase();
10094
+ if (verb in verbCounts) {
10095
+ verbCounts[verb]++;
10096
+ } else {
10097
+ verbCounts.GET++;
10098
+ }
6638
10099
  });
6639
10100
  const errorCount = c4xx + c5xx;
6640
10101
  const errorRate = totalRequests === 0 ? 0 : errorCount / totalRequests;
@@ -6661,7 +10122,8 @@ function processMetricsTelemetry(requests, durationSec) {
6661
10122
  avgTlsMs,
6662
10123
  avgTtfbMs,
6663
10124
  bandwidthMb,
6664
- codeCounts
10125
+ codeCounts,
10126
+ verbCounts
6665
10127
  };
6666
10128
  }
6667
10129
  function printMatrixDashboard(m, threads) {
@@ -6702,7 +10164,7 @@ function exportHtmlDashboard(history, config, verdictReason, semanticReport, res
6702
10164
  const formattedDate = formatter.format(/* @__PURE__ */ new Date());
6703
10165
  const summaryArtifactPath = config.outputHtml.replace(/\.html$/, "-summary.json");
6704
10166
  try {
6705
- fs.writeFileSync(summaryArtifactPath, JSON.stringify(cards, null, 2), "utf-8");
10167
+ fs2.writeFileSync(summaryArtifactPath, JSON.stringify(cards, null, 2), "utf-8");
6706
10168
  } catch (e) {
6707
10169
  }
6708
10170
  const labels = history.map((h, i) => `${i + 1}s`);
@@ -7185,6 +10647,13 @@ ${formattedTicketLogs}
7185
10647
  </div>
7186
10648
  </div>
7187
10649
 
10650
+ <div class="graph-card">
10651
+ <div class="graph-title">${dict.charts.verbs}</div>
10652
+ <div style="height: 280px; position: relative;">
10653
+ <canvas id="verbDonutChart"></canvas>
10654
+ </div>
10655
+ </div>
10656
+
7188
10657
  <div class="graph-card">
7189
10658
  <div class="graph-title">${dict.charts.scatter}</div>
7190
10659
  <div style="height: 280px; position: relative;">
@@ -7416,6 +10885,29 @@ ${formattedTicketLogs}
7416
10885
  }
7417
10886
  });
7418
10887
 
10888
+ // Render HTTP Verb Distribution Donut Chart
10889
+ const verbData = ${JSON.stringify(responseMatrix.verbCounts || { GET: 0, POST: 0, PUT: 0, DELETE: 0, PATCH: 0 })};
10890
+ new Chart(document.getElementById('verbDonutChart'), {
10891
+ type: 'doughnut',
10892
+ data: {
10893
+ labels: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'],
10894
+ datasets: [{
10895
+ data: [verbData.GET || 0, verbData.POST || 0, verbData.PUT || 0, verbData.DELETE || 0, verbData.PATCH || 0],
10896
+ backgroundColor: ['#38bdf8', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6'],
10897
+ borderWidth: 1,
10898
+ borderColor: '#1e293b'
10899
+ }]
10900
+ },
10901
+ options: {
10902
+ responsive: true,
10903
+ maintainAspectRatio: false,
10904
+ plugins: {
10905
+ legend: { position: 'top', labels: { color: '#94a3b8', font: { size: 11 } } },
10906
+ cutout: '65%'
10907
+ }
10908
+ }
10909
+ });
10910
+
7419
10911
  // Render User-Agent Device Splitting Donut Charts dynamically
7420
10912
  ${deviceMetrics.map((dm, idx) => `
7421
10913
  new Chart(document.getElementById('deviceDonutChart_${idx}'), {
@@ -7433,50 +10925,78 @@ ${formattedTicketLogs}
7433
10925
  responsive: true,
7434
10926
  maintainAspectRatio: false,
7435
10927
  plugins: {
7436
- legend: { display: false },
7437
- cutout: '70%'
10928
+ legend: { display: false }
7438
10929
  }
7439
10930
  }
7440
10931
  });
7441
- `).join("\n")}
10932
+ `).join("")}
7442
10933
 
10934
+ // Scatter Chart Engine Initialization
10935
+ const scatterPointsData = ${JSON.stringify(scatterPoints)};
7443
10936
  new Chart(document.getElementById('ttfbScatterChart'), {
7444
10937
  type: 'scatter',
7445
10938
  data: {
7446
10939
  datasets: [{
7447
- label: 'Delay',
7448
- data: ${JSON.stringify(scatterPoints)},
7449
- backgroundColor: '#a855f7',
7450
- pointRadius: 4,
7451
- pointHoverRadius: 6
10940
+ label: 'Request TTFB Latency (ms)',
10941
+ data: scatterPointsData,
10942
+ backgroundColor: '#38bdf8'
7452
10943
  }]
7453
10944
  },
7454
10945
  options: {
7455
10946
  responsive: true,
7456
10947
  maintainAspectRatio: false,
7457
- plugins: {
7458
- legend: { position: 'top', labels: { color: '#94a3b8', font: { size: 11 } } }
7459
- },
7460
10948
  scales: {
7461
- x: { grid: { color: '#1e293b' }, ticks: { color: '#64748b' } },
7462
- y: { grid: { color: '#1e293b' }, ticks: { color: '#64748b' } }
10949
+ x: {
10950
+ title: { display: true, text: 'Time Elapsed (s)', color: '#94a3b8' },
10951
+ grid: { color: '#1e293b' },
10952
+ ticks: { color: '#64748b' }
10953
+ },
10954
+ y: {
10955
+ title: { display: true, text: 'TTFB (ms)', color: '#94a3b8' },
10956
+ grid: { color: '#1e293b' },
10957
+ ticks: { color: '#64748b' }
10958
+ }
10959
+ },
10960
+ plugins: {
10961
+ legend: { display: false }
7463
10962
  }
7464
10963
  }
7465
10964
  });
7466
- </script></body></html>`;
7467
- try {
7468
- fs.writeFileSync(config.outputHtml, htmlContent, "utf-8");
7469
- console.log(`\u{1F4CA} Standalone Localized Dashboard exported successfully to: ${path.resolve(config.outputHtml)}`);
7470
- } catch (err) {
7471
- console.error(`\u274C Failed to write HTML output dashboard: ${err}`);
7472
- }
10965
+ </script>
10966
+ </body>
10967
+ </html>`;
10968
+ fs2.writeFileSync(config.outputHtml, htmlContent, "utf-8");
10969
+ console.log(`
10970
+ \u{1F389} Performance Analysis Dashboard Exported to: ${path2.resolve(config.outputHtml)}`);
7473
10971
  }
7474
10972
  function printUsage() {
7475
- console.log(`Blaze Core Performance Test CLI Engine
10973
+ console.log(`
10974
+ Blaze Performance Tester CLI
10975
+
10976
+ Usage:
10977
+ blaze-performance-tester <script-path> [options]
10978
+
7476
10979
  Options:
7477
- --threads <count> | --duration <seconds> | --baseline <json_file> | --output <html_file> | --cross-browser | --locale <lang_code> | --option elif`);
10980
+ --threads <number> Number of concurrent virtual users (default: 10)
10981
+ --duration <seconds> Test duration in seconds (default: 10)
10982
+ --ramp-up <seconds> Ramp-up duration in seconds (default: 0)
10983
+ --ramp-down <seconds> Ramp-down duration in seconds (default: 0)
10984
+ --target-apdex <number> Minimum targeted Apdex score threshold (default: 0.85)
10985
+ --target-error <number> Maximum targeted Error Rate percentage threshold (default: 1%)
10986
+ --agentic Enable Autonomous AI Stress-Testing Agent
10987
+ --max-threads <number> Maximum concurrency cap for Agentic mode (default: 300)
10988
+ --correlate Execute with correlated variable transaction engine
10989
+ --seo Evaluate Search Engine Optimization (SEO) impact breakdown
10990
+ --cross-browser Evaluate cross-browser rendering telemetry matrix
10991
+ --output <path> Output path for the HTML dashboard (default: blaze-dashboard.html)
10992
+ --baseline <path> Compare results with a previous summary JSON artifact
10993
+ --locale <locale> Localization for UI dashboard (en-US, es-ES, ar-AE, hi-IN, ta-IN, si-LK)
10994
+ --prompt <string> Generate test scenario using Gemini AI from prompt text
10995
+ --option elif Outputs an Explain-Like-I'm-5 plain-language breakdown
10996
+ `);
7478
10997
  }
7479
- runCli().catch(console.error);
10998
+ var program2 = new Command();
10999
+ program2.name("blaze").description("Blaze Performance Tester \u2014 Enterprise AI-Native Performance Platform").version("1.0");
7480
11000
  export {
7481
11001
  runCli
7482
11002
  };