inray 0.0.3 → 0.0.5

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 (137) hide show
  1. package/LICENSE.md +28 -27
  2. package/README.md +158 -52
  3. package/dist/async/abortable.d.ts +2 -2
  4. package/dist/async/abortable.d.ts.map +1 -1
  5. package/dist/async/abortable.js.map +1 -1
  6. package/dist/cli/mod.d.ts +2 -0
  7. package/dist/cli/mod.d.ts.map +1 -0
  8. package/dist/cli/mod.js +2 -0
  9. package/dist/cli/mod.js.map +1 -0
  10. package/dist/cli/src/index.d.ts +25 -0
  11. package/dist/cli/src/index.d.ts.map +1 -0
  12. package/dist/cli/src/index.js +25 -0
  13. package/dist/cli/src/index.js.map +1 -0
  14. package/dist/cli/src/lib/argument.d.ts +82 -0
  15. package/dist/cli/src/lib/argument.d.ts.map +1 -0
  16. package/dist/cli/src/lib/argument.js +143 -0
  17. package/dist/cli/src/lib/argument.js.map +1 -0
  18. package/dist/cli/src/lib/command.d.ts +1051 -0
  19. package/dist/cli/src/lib/command.d.ts.map +1 -0
  20. package/dist/cli/src/lib/command.js +2208 -0
  21. package/dist/cli/src/lib/command.js.map +1 -0
  22. package/dist/cli/src/lib/error.d.ts +35 -0
  23. package/dist/cli/src/lib/error.d.ts.map +1 -0
  24. package/dist/cli/src/lib/error.js +49 -0
  25. package/dist/cli/src/lib/error.js.map +1 -0
  26. package/dist/cli/src/lib/help.d.ts +250 -0
  27. package/dist/cli/src/lib/help.d.ts.map +1 -0
  28. package/dist/cli/src/lib/help.js +583 -0
  29. package/dist/cli/src/lib/help.js.map +1 -0
  30. package/dist/cli/src/lib/option.d.ts +189 -0
  31. package/dist/cli/src/lib/option.d.ts.map +1 -0
  32. package/dist/cli/src/lib/option.js +364 -0
  33. package/dist/cli/src/lib/option.js.map +1 -0
  34. package/dist/cli/src/lib/suggestSimilar.d.ts +18 -0
  35. package/dist/cli/src/lib/suggestSimilar.d.ts.map +1 -0
  36. package/dist/cli/src/lib/suggestSimilar.js +99 -0
  37. package/dist/cli/src/lib/suggestSimilar.js.map +1 -0
  38. package/dist/logtape/logtape/level.d.ts +1 -2
  39. package/dist/logtape/logtape/level.d.ts.map +1 -1
  40. package/dist/logtape/logtape/level.js +1 -1
  41. package/dist/logtape/logtape/level.js.map +1 -1
  42. package/dist/logtape/logtape/mod.d.ts +1 -1
  43. package/dist/logtape/logtape/mod.d.ts.map +1 -1
  44. package/dist/logtape/logtape/mod.js +1 -1
  45. package/dist/logtape/logtape/mod.js.map +1 -1
  46. package/dist/utils/mod.d.ts +1 -1
  47. package/dist/utils/mod.d.ts.map +1 -1
  48. package/dist/utils/mod.js.map +1 -1
  49. package/dist/utils/validation/inRangeOfMaxInt32.d.ts +2 -0
  50. package/dist/utils/validation/inRangeOfMaxInt32.d.ts.map +1 -0
  51. package/dist/utils/validation/inRangeOfMaxInt32.js +4 -0
  52. package/dist/utils/validation/inRangeOfMaxInt32.js.map +1 -0
  53. package/dist/utils/validation/isEmail.d.ts +2 -0
  54. package/dist/utils/validation/isEmail.d.ts.map +1 -0
  55. package/dist/utils/validation/isEmail.js +7 -0
  56. package/dist/utils/validation/isEmail.js.map +1 -0
  57. package/dist/utils/validation/isEmptyObject.d.ts +9 -0
  58. package/dist/utils/validation/isEmptyObject.d.ts.map +1 -0
  59. package/dist/utils/validation/isEmptyObject.js +16 -0
  60. package/dist/utils/validation/isEmptyObject.js.map +1 -0
  61. package/dist/utils/validation/isNotEmptyString.d.ts +7 -0
  62. package/dist/utils/validation/isNotEmptyString.d.ts.map +1 -0
  63. package/dist/utils/validation/isNotEmptyString.js +17 -0
  64. package/dist/utils/validation/isNotEmptyString.js.map +1 -0
  65. package/dist/utils/validation/isPositiveInteger.d.ts +2 -0
  66. package/dist/utils/validation/isPositiveInteger.d.ts.map +1 -0
  67. package/dist/utils/validation/isPositiveInteger.js +7 -0
  68. package/dist/utils/validation/isPositiveInteger.js.map +1 -0
  69. package/dist/utils/validation/isUuid.d.ts +2 -0
  70. package/dist/utils/validation/isUuid.d.ts.map +1 -0
  71. package/dist/utils/validation/isUuid.js +7 -0
  72. package/dist/utils/validation/isUuid.js.map +1 -0
  73. package/dist/utils/validation/isUuidArray.d.ts +2 -0
  74. package/dist/utils/validation/isUuidArray.d.ts.map +1 -0
  75. package/dist/utils/validation/isUuidArray.js +7 -0
  76. package/dist/utils/validation/isUuidArray.js.map +1 -0
  77. package/dist/utils/validation/isValidFileName.d.ts +2 -0
  78. package/dist/utils/validation/isValidFileName.d.ts.map +1 -0
  79. package/dist/utils/validation/isValidFileName.js +33 -0
  80. package/dist/utils/validation/isValidFileName.js.map +1 -0
  81. package/dist/utils/validation/isValidUrlLike.d.ts +6 -0
  82. package/dist/utils/validation/isValidUrlLike.d.ts.map +1 -0
  83. package/dist/utils/validation/isValidUrlLike.js +8 -0
  84. package/dist/utils/validation/isValidUrlLike.js.map +1 -0
  85. package/dist/utils/validation/mod.d.ts +21 -0
  86. package/dist/utils/validation/mod.d.ts.map +1 -0
  87. package/dist/utils/validation/mod.js +21 -0
  88. package/dist/utils/validation/mod.js.map +1 -0
  89. package/dist/utils/validation/vEnvBoolean.d.ts +3 -0
  90. package/dist/utils/validation/vEnvBoolean.d.ts.map +1 -0
  91. package/dist/utils/validation/vEnvBoolean.js +5 -0
  92. package/dist/utils/validation/vEnvBoolean.js.map +1 -0
  93. package/dist/utils/validation/vEnvBooleanOrUndefined.d.ts +3 -0
  94. package/dist/utils/validation/vEnvBooleanOrUndefined.d.ts.map +1 -0
  95. package/dist/utils/validation/vEnvBooleanOrUndefined.js +5 -0
  96. package/dist/utils/validation/vEnvBooleanOrUndefined.js.map +1 -0
  97. package/dist/utils/validation/vEnvLogLevel.d.ts +4 -0
  98. package/dist/utils/validation/vEnvLogLevel.d.ts.map +1 -0
  99. package/dist/utils/validation/vEnvLogLevel.js +6 -0
  100. package/dist/utils/validation/vEnvLogLevel.js.map +1 -0
  101. package/dist/utils/validation/vFileName.d.ts +4 -0
  102. package/dist/utils/validation/vFileName.d.ts.map +1 -0
  103. package/dist/utils/validation/vFileName.js +21 -0
  104. package/dist/utils/validation/vFileName.js.map +1 -0
  105. package/dist/utils/validation/vISO8601DateTime.d.ts +5 -0
  106. package/dist/utils/validation/vISO8601DateTime.d.ts.map +1 -0
  107. package/dist/utils/validation/vISO8601DateTime.js +37 -0
  108. package/dist/utils/validation/vISO8601DateTime.js.map +1 -0
  109. package/dist/utils/validation/vLatinInput.d.ts +3 -0
  110. package/dist/utils/validation/vLatinInput.d.ts.map +1 -0
  111. package/dist/utils/validation/vLatinInput.js +3 -0
  112. package/dist/utils/validation/vLatinInput.js.map +1 -0
  113. package/dist/utils/validation/vOmniBoolean.d.ts +3 -0
  114. package/dist/utils/validation/vOmniBoolean.d.ts.map +1 -0
  115. package/dist/utils/validation/vOmniBoolean.js +10 -0
  116. package/dist/utils/validation/vOmniBoolean.js.map +1 -0
  117. package/dist/utils/validation/vQueryBoolean.d.ts +3 -0
  118. package/dist/utils/validation/vQueryBoolean.d.ts.map +1 -0
  119. package/dist/utils/validation/vQueryBoolean.js +7 -0
  120. package/dist/utils/validation/vQueryBoolean.js.map +1 -0
  121. package/dist/utils/validation/vQueryEmailArray.d.ts +9 -0
  122. package/dist/utils/validation/vQueryEmailArray.d.ts.map +1 -0
  123. package/dist/utils/validation/vQueryEmailArray.js +29 -0
  124. package/dist/utils/validation/vQueryEmailArray.js.map +1 -0
  125. package/dist/utils/validation/vQueryNumberArray.d.ts +10 -0
  126. package/dist/utils/validation/vQueryNumberArray.d.ts.map +1 -0
  127. package/dist/utils/validation/vQueryNumberArray.js +32 -0
  128. package/dist/utils/validation/vQueryNumberArray.js.map +1 -0
  129. package/dist/utils/validation/vQueryStringifiedEnumArray.d.ts +3 -0
  130. package/dist/utils/validation/vQueryStringifiedEnumArray.d.ts.map +1 -0
  131. package/dist/utils/validation/vQueryStringifiedEnumArray.js +25 -0
  132. package/dist/utils/validation/vQueryStringifiedEnumArray.js.map +1 -0
  133. package/dist/utils/validation/vQueryUuidArray.d.ts +9 -0
  134. package/dist/utils/validation/vQueryUuidArray.d.ts.map +1 -0
  135. package/dist/utils/validation/vQueryUuidArray.js +27 -0
  136. package/dist/utils/validation/vQueryUuidArray.js.map +1 -0
  137. package/package.json +15 -2
@@ -0,0 +1,2208 @@
1
+ /**
2
+ * Original library: commander.js (v15.0.0)
3
+ * - Copyright (c) 2011 TJ Holowaychuk
4
+ * - Copyright (c) John Gee and "commander.js" authors
5
+ *
6
+ * Modified and integrated in "Inray":
7
+ * - Evgeniy Bushin
8
+ */
9
+ /***/
10
+ import { EventEmitter } from 'node:events';
11
+ import childProcess from 'node:child_process';
12
+ import path from 'node:path';
13
+ import fs from 'node:fs';
14
+ import process from 'node:process';
15
+ import { stripVTControlCharacters } from 'node:util';
16
+ import { Argument, humanReadableArgName } from "./argument.js";
17
+ import { CommanderError } from "./error.js";
18
+ import { Help } from "./help.js";
19
+ import { Option, DualOptions } from "./option.js";
20
+ import { suggestSimilar } from "./suggestSimilar.js";
21
+ export class Command extends EventEmitter {
22
+ args;
23
+ processedArgs;
24
+ commands;
25
+ options;
26
+ registeredArguments;
27
+ parent;
28
+ _allowUnknownOption;
29
+ _allowExcessArguments;
30
+ _args;
31
+ rawArgs;
32
+ _version;
33
+ _scriptPath;
34
+ _name;
35
+ _optionValues;
36
+ _optionValueSources;
37
+ _storeOptionsAsProperties;
38
+ _actionHandler;
39
+ _executableHandler;
40
+ _executableFile;
41
+ _executableDir;
42
+ _defaultCommandName;
43
+ _exitCallback;
44
+ _aliases;
45
+ _combineFlagAndOptionalValue;
46
+ _description;
47
+ _summary;
48
+ _argsDescription;
49
+ _enablePositionalOptions;
50
+ _passThroughOptions;
51
+ _lifeCycleHooks;
52
+ _showHelpAfterError;
53
+ _showSuggestionAfterError;
54
+ _savedState;
55
+ _outputConfiguration;
56
+ _hidden;
57
+ _helpOption;
58
+ _addImplicitHelpCommand;
59
+ _helpCommand;
60
+ _helpConfiguration;
61
+ _helpGroupHeading;
62
+ _defaultCommandGroup;
63
+ _defaultOptionGroup;
64
+ _usage;
65
+ _versionOptionName;
66
+ runningCommand; // child process from executable subcommand
67
+ /**
68
+ * Initialize a new `Command`.
69
+ *
70
+ * @param {string} [name]
71
+ */
72
+ constructor(name) {
73
+ super();
74
+ /** @type {Command[]} */
75
+ this.commands = [];
76
+ /** @type {Option[]} */
77
+ this.options = [];
78
+ this.parent = null;
79
+ this._allowUnknownOption = false;
80
+ this._allowExcessArguments = false;
81
+ /** @type {Argument[]} */
82
+ this.registeredArguments = [];
83
+ this._args = this.registeredArguments; // deprecated old name
84
+ /** @type {string[]} */
85
+ this.args = []; // cli args with options removed
86
+ this.rawArgs = [];
87
+ this.processedArgs = []; // like .args but after custom processing and collecting variadic
88
+ this._scriptPath = null;
89
+ this._name = name || '';
90
+ this._optionValues = {};
91
+ this._optionValueSources = {}; // default, env, cli etc
92
+ this._storeOptionsAsProperties = false;
93
+ this._actionHandler = null;
94
+ this._executableHandler = false;
95
+ this._executableFile = null; // custom name for executable
96
+ this._executableDir = null; // custom search directory for subcommands
97
+ this._defaultCommandName = null;
98
+ this._exitCallback = null;
99
+ this._aliases = [];
100
+ this._combineFlagAndOptionalValue = true;
101
+ this._description = '';
102
+ this._summary = '';
103
+ this._argsDescription = undefined; // legacy
104
+ this._enablePositionalOptions = false;
105
+ this._passThroughOptions = false;
106
+ this._lifeCycleHooks = {}; // a hash of arrays
107
+ /** @type {(boolean | string)} */
108
+ this._showHelpAfterError = false;
109
+ this._showSuggestionAfterError = true;
110
+ this._savedState = null; // used in save/restoreStateBeforeParse
111
+ // see configureOutput() for docs
112
+ this._outputConfiguration = {
113
+ writeOut: (str) => process.stdout.write(str),
114
+ writeErr: (str) => process.stderr.write(str),
115
+ outputError: (str, write) => write(str),
116
+ getOutHelpWidth: () => (process.stdout.isTTY ? process.stdout.columns : undefined),
117
+ getErrHelpWidth: () => (process.stderr.isTTY ? process.stderr.columns : undefined),
118
+ getOutHasColors: () => useColor() ?? (process.stdout.isTTY && process.stdout.hasColors?.()),
119
+ getErrHasColors: () => useColor() ?? (process.stderr.isTTY && process.stderr.hasColors?.()),
120
+ stripColor: (str) => stripVTControlCharacters(str)
121
+ };
122
+ this._hidden = false;
123
+ /** @type {(Option | null | undefined)} */
124
+ this._helpOption = undefined; // Lazy created on demand. May be null if help option is disabled.
125
+ this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited
126
+ /** @type {Command} */
127
+ this._helpCommand = undefined; // lazy initialised, inherited
128
+ this._helpConfiguration = {};
129
+ /** @type {string | undefined} */
130
+ this._helpGroupHeading = undefined; // soft initialised when added to parent
131
+ /** @type {string | undefined} */
132
+ this._defaultCommandGroup = undefined;
133
+ /** @type {string | undefined} */
134
+ this._defaultOptionGroup = undefined;
135
+ }
136
+ /**
137
+ * Copy settings that are useful to have in common across root command and subcommands.
138
+ *
139
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
140
+ *
141
+ * @param {Command} sourceCommand
142
+ * @return {Command} `this` command for chaining
143
+ */
144
+ copyInheritedSettings(sourceCommand) {
145
+ this._outputConfiguration = sourceCommand._outputConfiguration;
146
+ this._helpOption = sourceCommand._helpOption;
147
+ this._helpCommand = sourceCommand._helpCommand;
148
+ this._helpConfiguration = sourceCommand._helpConfiguration;
149
+ this._exitCallback = sourceCommand._exitCallback;
150
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
151
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
152
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
153
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
154
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
155
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
156
+ return this;
157
+ }
158
+ /**
159
+ * @returns {Command[]}
160
+ * @private
161
+ */
162
+ _getCommandAndAncestors() {
163
+ const result = [];
164
+ // eslint-disable-next-line @typescript-eslint/no-this-alias // и что это такое
165
+ for (let command = this; command; command = command.parent) {
166
+ result.push(command);
167
+ }
168
+ return result;
169
+ }
170
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
171
+ let desc = actionOptsOrExecDesc;
172
+ // opts is a mix of CommandOptions / ExecutableCommandOptions / deprecated noHelp
173
+ let opts = execOpts;
174
+ if (typeof desc === 'object' && desc !== null) {
175
+ opts = desc;
176
+ desc = null;
177
+ }
178
+ opts = opts || {};
179
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
180
+ const cmd = this.createCommand(name);
181
+ if (desc) {
182
+ cmd.description(desc);
183
+ cmd._executableHandler = true;
184
+ }
185
+ if (opts.isDefault)
186
+ this._defaultCommandName = cmd._name;
187
+ cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden
188
+ cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor
189
+ if (args)
190
+ cmd.arguments(args);
191
+ this._registerCommand(cmd);
192
+ cmd.parent = this;
193
+ cmd.copyInheritedSettings(this);
194
+ if (desc)
195
+ return this;
196
+ return cmd;
197
+ }
198
+ /**
199
+ * Factory routine to create a new unattached command.
200
+ *
201
+ * See .command() for creating an attached subcommand, which uses this routine to
202
+ * create the command. You can override createCommand to customise subcommands.
203
+ *
204
+ * @param {string} [name]
205
+ * @return {Command} new command
206
+ */
207
+ createCommand(name) {
208
+ return new Command(name);
209
+ }
210
+ /**
211
+ * You can customise the help with a subclass of Help by overriding createHelp,
212
+ * or by overriding Help properties using configureHelp().
213
+ *
214
+ * @return {Help}
215
+ */
216
+ createHelp() {
217
+ return Object.assign(new Help(), this.configureHelp());
218
+ }
219
+ configureHelp(configuration) {
220
+ if (configuration === undefined)
221
+ return this._helpConfiguration;
222
+ this._helpConfiguration = configuration;
223
+ return this;
224
+ }
225
+ configureOutput(configuration) {
226
+ if (configuration === undefined)
227
+ return this._outputConfiguration;
228
+ this._outputConfiguration = {
229
+ ...this._outputConfiguration,
230
+ ...configuration
231
+ };
232
+ return this;
233
+ }
234
+ /**
235
+ * Display the help or a custom message after an error occurs.
236
+ *
237
+ * @param {(boolean|string)} [displayHelp]
238
+ * @return {Command} `this` command for chaining
239
+ */
240
+ showHelpAfterError(displayHelp = true) {
241
+ if (typeof displayHelp !== 'string')
242
+ displayHelp = !!displayHelp;
243
+ this._showHelpAfterError = displayHelp;
244
+ return this;
245
+ }
246
+ /**
247
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
248
+ *
249
+ * @param {boolean} [displaySuggestion]
250
+ * @return {Command} `this` command for chaining
251
+ */
252
+ showSuggestionAfterError(displaySuggestion = true) {
253
+ this._showSuggestionAfterError = !!displaySuggestion;
254
+ return this;
255
+ }
256
+ /**
257
+ * Add a prepared subcommand.
258
+ *
259
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
260
+ *
261
+ * @param {Command} cmd - new subcommand
262
+ * @param {object} [opts] - configuration options
263
+ * @return {Command} `this` command for chaining
264
+ */
265
+ addCommand(cmd, opts) {
266
+ if (!cmd._name) {
267
+ throw new Error(`Command passed to .addCommand() must have a name
268
+ - specify the name in Command constructor or using .name()`);
269
+ }
270
+ opts = opts || {};
271
+ if (opts.isDefault)
272
+ this._defaultCommandName = cmd._name;
273
+ if (opts.hidden)
274
+ cmd._hidden = true; // modifying passed command due to existing implementation
275
+ this._registerCommand(cmd);
276
+ cmd.parent = this;
277
+ cmd._checkForBrokenPassThrough();
278
+ return this;
279
+ }
280
+ /**
281
+ * Factory routine to create a new unattached argument.
282
+ *
283
+ * See .argument() for creating an attached argument, which uses this routine to
284
+ * create the argument. You can override createArgument to return a custom argument.
285
+ *
286
+ * @param {string} name
287
+ * @param {string} [description]
288
+ * @return {Argument} new argument
289
+ */
290
+ createArgument(name, description) {
291
+ return new Argument(name, description);
292
+ }
293
+ /**
294
+ * Define argument syntax for command.
295
+ *
296
+ * The default is that the argument is required, and you can explicitly
297
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
298
+ *
299
+ * @example
300
+ * program.argument('<input-file>');
301
+ * program.argument('[output-file]');
302
+ *
303
+ * @return {Command} `this` command for chaining
304
+ */
305
+ argument(name, description, parseArg, defaultValue) {
306
+ const argument = this.createArgument(name, description);
307
+ if (typeof parseArg === 'function') {
308
+ argument.default(defaultValue).argParser(parseArg);
309
+ }
310
+ else {
311
+ argument.default(parseArg);
312
+ }
313
+ this.addArgument(argument);
314
+ return this;
315
+ }
316
+ /**
317
+ * Define argument syntax for command, adding multiple at once (without descriptions).
318
+ *
319
+ * See also .argument().
320
+ *
321
+ * @example
322
+ * program.arguments('<cmd> [env]');
323
+ *
324
+ * @param {string} names
325
+ * @return {Command} `this` command for chaining
326
+ */
327
+ arguments(names) {
328
+ names
329
+ .trim()
330
+ .split(/ +/)
331
+ .forEach((detail) => {
332
+ this.argument(detail);
333
+ });
334
+ return this;
335
+ }
336
+ /**
337
+ * Define argument syntax for command, adding a prepared argument.
338
+ *
339
+ * @param {Argument} argument
340
+ * @return {Command} `this` command for chaining
341
+ */
342
+ addArgument(argument) {
343
+ const previousArgument = this.registeredArguments.slice(-1)[0];
344
+ if (previousArgument?.variadic) {
345
+ throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
346
+ }
347
+ if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {
348
+ throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
349
+ }
350
+ this.registeredArguments.push(argument);
351
+ return this;
352
+ }
353
+ helpCommand(enableOrNameAndArgs, description) {
354
+ if (typeof enableOrNameAndArgs === 'boolean') {
355
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
356
+ if (enableOrNameAndArgs && this._defaultCommandGroup) {
357
+ // make the command to store the group
358
+ const helpCommand = this._getHelpCommand();
359
+ if (helpCommand)
360
+ this._initCommandGroup(helpCommand);
361
+ }
362
+ return this;
363
+ }
364
+ const nameAndArgs = enableOrNameAndArgs ?? 'help [command]';
365
+ const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);
366
+ const helpDescription = description ?? 'display help for command';
367
+ const helpCommand = this.createCommand(helpName);
368
+ helpCommand.helpOption(false);
369
+ if (helpArgs)
370
+ helpCommand.arguments(helpArgs);
371
+ if (helpDescription)
372
+ helpCommand.description(helpDescription);
373
+ this._addImplicitHelpCommand = true;
374
+ this._helpCommand = helpCommand;
375
+ // init group unless lazy create
376
+ if (enableOrNameAndArgs || description)
377
+ this._initCommandGroup(helpCommand);
378
+ return this;
379
+ }
380
+ addHelpCommand(helpCommand, deprecatedDescription) {
381
+ // If not passed an object, call through to helpCommand for backwards compatibility,
382
+ // as addHelpCommand was originally used like helpCommand is now.
383
+ if (typeof helpCommand !== 'object') {
384
+ this.helpCommand(helpCommand, deprecatedDescription);
385
+ return this;
386
+ }
387
+ this._addImplicitHelpCommand = true;
388
+ this._helpCommand = helpCommand;
389
+ this._initCommandGroup(helpCommand);
390
+ return this;
391
+ }
392
+ /**
393
+ * Lazy create help command.
394
+ *
395
+ * @return {(Command|null)}
396
+ * @package
397
+ */
398
+ _getHelpCommand() {
399
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand('help'));
400
+ if (hasImplicitHelpCommand) {
401
+ if (this._helpCommand === undefined) {
402
+ this.helpCommand(); // use default name and description
403
+ }
404
+ return this._helpCommand ?? null;
405
+ }
406
+ return null;
407
+ }
408
+ /**
409
+ * Add hook for life cycle event.
410
+ *
411
+ * @param {string} event
412
+ * @param {Function} listener
413
+ * @return {Command} `this` command for chaining
414
+ */
415
+ hook(event, listener) {
416
+ const allowedValues = ['preSubcommand', 'preAction', 'postAction'];
417
+ if (!allowedValues.includes(event)) {
418
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
419
+ Expecting one of '${allowedValues.join("', '")}'`);
420
+ }
421
+ if (this._lifeCycleHooks[event]) {
422
+ this._lifeCycleHooks[event].push(listener);
423
+ }
424
+ else {
425
+ this._lifeCycleHooks[event] = [listener];
426
+ }
427
+ return this;
428
+ }
429
+ /**
430
+ * Register callback to use as replacement for calling process.exit.
431
+ *
432
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
433
+ * @return {Command} `this` command for chaining
434
+ */
435
+ exitOverride(fn) {
436
+ if (fn) {
437
+ this._exitCallback = fn;
438
+ }
439
+ else {
440
+ this._exitCallback = (err) => {
441
+ if (err.code !== 'commander.executeSubCommandAsync') {
442
+ throw err;
443
+ }
444
+ else {
445
+ // Async callback from spawn events, not useful to throw.
446
+ }
447
+ };
448
+ }
449
+ return this;
450
+ }
451
+ /**
452
+ * Call process.exit, and _exitCallback if defined.
453
+ *
454
+ * @param {number} exitCode exit code for using with process.exit
455
+ * @param {string} code an id string representing the error
456
+ * @param {string} message human-readable description of the error
457
+ * @return never
458
+ * @private
459
+ */
460
+ _exit(exitCode, code, message) {
461
+ if (this._exitCallback) {
462
+ this._exitCallback(new CommanderError(exitCode, code, message));
463
+ // Expecting this line is not reached.
464
+ }
465
+ process.exit(exitCode);
466
+ }
467
+ /**
468
+ * Register callback `fn` for the command.
469
+ *
470
+ * @example
471
+ * program
472
+ * .command('serve')
473
+ * .description('start service')
474
+ * .action(function() {
475
+ * // do work here
476
+ * });
477
+ *
478
+ * @param {Function} fn
479
+ * @return {Command} `this` command for chaining
480
+ */
481
+ action(fn) {
482
+ const listener = (args) => {
483
+ // The .action callback takes an extra parameter which is the command or options.
484
+ const expectedArgsCount = this.registeredArguments.length;
485
+ const actionArgs = args.slice(0, expectedArgsCount);
486
+ if (this._storeOptionsAsProperties) {
487
+ actionArgs[expectedArgsCount] = this; // backwards compatible "options"
488
+ }
489
+ else {
490
+ actionArgs[expectedArgsCount] = this.opts();
491
+ }
492
+ actionArgs.push(this);
493
+ return fn.apply(this, actionArgs);
494
+ };
495
+ this._actionHandler = listener;
496
+ return this;
497
+ }
498
+ /**
499
+ * Factory routine to create a new unattached option.
500
+ *
501
+ * See .option() for creating an attached option, which uses this routine to
502
+ * create the option. You can override createOption to return a custom option.
503
+ *
504
+ * @param {string} flags
505
+ * @param {string} [description]
506
+ * @return {Option} new option
507
+ */
508
+ createOption(flags, description) {
509
+ return new Option(flags, description);
510
+ }
511
+ /**
512
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
513
+ *
514
+ * @param {(Option | Argument)} target
515
+ * @param {string} value
516
+ * @param {*} previous
517
+ * @param {string} invalidArgumentMessage
518
+ * @private
519
+ */
520
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
521
+ try {
522
+ return target.parseArg(value, previous);
523
+ }
524
+ catch (err) {
525
+ if (err.code === 'commander.invalidArgument') {
526
+ const message = `${invalidArgumentMessage} ${err.message}`;
527
+ this.error(message, { exitCode: err.exitCode, code: err.code });
528
+ }
529
+ throw err;
530
+ }
531
+ }
532
+ /**
533
+ * Check for option flag conflicts.
534
+ * Register option if no conflicts found, or throw on conflict.
535
+ *
536
+ * @param {Option} option
537
+ * @private
538
+ */
539
+ _registerOption(option) {
540
+ const matchingOption = (option.short && this._findOption(option.short)) || (option.long && this._findOption(option.long));
541
+ if (matchingOption) {
542
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
543
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
544
+ - already used by option '${matchingOption.flags}'`);
545
+ }
546
+ this._initOptionGroup(option);
547
+ this.options.push(option);
548
+ }
549
+ /**
550
+ * Check for command name and alias conflicts with existing commands.
551
+ * Register command if no conflicts found, or throw on conflict.
552
+ *
553
+ * @param {Command} command
554
+ * @private
555
+ */
556
+ _registerCommand(command) {
557
+ const knownBy = (cmd) => {
558
+ return [cmd.name()].concat(cmd.aliases());
559
+ };
560
+ const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
561
+ if (alreadyUsed) {
562
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');
563
+ const newCmd = knownBy(command).join('|');
564
+ throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
565
+ }
566
+ this._initCommandGroup(command);
567
+ this.commands.push(command);
568
+ }
569
+ /**
570
+ * Add an option.
571
+ *
572
+ * @param {Option} option
573
+ * @return {Command} `this` command for chaining
574
+ */
575
+ addOption(option) {
576
+ this._registerOption(option);
577
+ const oname = option.name();
578
+ const name = option.attributeName();
579
+ // store default value
580
+ if (option.defaultValue !== undefined) {
581
+ this.setOptionValueWithSource(name, option.defaultValue, 'default');
582
+ }
583
+ // handler for cli and env supplied values
584
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
585
+ // val is null for optional option used without an optional-argument.
586
+ // val is undefined for boolean and negated option.
587
+ if (val == null && option.presetArg !== undefined) {
588
+ val = option.presetArg;
589
+ }
590
+ // custom processing
591
+ const oldValue = this.getOptionValue(name);
592
+ if (val !== null && option.parseArg) {
593
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
594
+ }
595
+ else if (val !== null && option.variadic) {
596
+ val = option._collectValue(val, oldValue);
597
+ }
598
+ // Fill-in appropriate missing values. Long winded but easy to follow.
599
+ if (val == null) {
600
+ if (option.negate) {
601
+ val = false;
602
+ }
603
+ else if (option.isBoolean() || option.optional) {
604
+ val = true;
605
+ }
606
+ else {
607
+ val = ''; // not normal, parseArg might have failed or be a mock function for testing
608
+ }
609
+ }
610
+ this.setOptionValueWithSource(name, val, valueSource);
611
+ };
612
+ this.on('option:' + oname, (val) => {
613
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
614
+ handleOptionValue(val, invalidValueMessage, 'cli');
615
+ });
616
+ if (option.envVar) {
617
+ this.on('optionEnv:' + oname, (val) => {
618
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
619
+ handleOptionValue(val, invalidValueMessage, 'env');
620
+ });
621
+ }
622
+ return this;
623
+ }
624
+ /**
625
+ * Internal implementation shared by .option() and .requiredOption()
626
+ *
627
+ * @return {Command} `this` command for chaining
628
+ * @private
629
+ */
630
+ _optionEx(config, flags, description, fn, defaultValue) {
631
+ if (typeof flags === 'object' && flags instanceof Option) {
632
+ throw new Error('To add an Option object use addOption() instead of option() or requiredOption()');
633
+ }
634
+ const option = this.createOption(flags, description);
635
+ option.makeOptionMandatory(!!config.mandatory);
636
+ if (typeof fn === 'function') {
637
+ option.default(defaultValue).argParser(fn);
638
+ }
639
+ else {
640
+ option.default(fn);
641
+ }
642
+ return this.addOption(option);
643
+ }
644
+ option(flags, description, parseArg, defaultValue) {
645
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
646
+ }
647
+ requiredOption(flags, description, parseArg, defaultValue) {
648
+ return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
649
+ }
650
+ /**
651
+ * Alter parsing of short flags with optional values.
652
+ *
653
+ * @example
654
+ * // for `.option('-f,--flag [value]'):
655
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
656
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
657
+ *
658
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
659
+ * @return {Command} `this` command for chaining
660
+ */
661
+ combineFlagAndOptionalValue(combine = true) {
662
+ this._combineFlagAndOptionalValue = !!combine;
663
+ return this;
664
+ }
665
+ /**
666
+ * Allow unknown options on the command line.
667
+ *
668
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
669
+ * @return {Command} `this` command for chaining
670
+ */
671
+ allowUnknownOption(allowUnknown = true) {
672
+ this._allowUnknownOption = !!allowUnknown;
673
+ return this;
674
+ }
675
+ /**
676
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
677
+ *
678
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
679
+ * @return {Command} `this` command for chaining
680
+ */
681
+ allowExcessArguments(allowExcess = true) {
682
+ this._allowExcessArguments = !!allowExcess;
683
+ return this;
684
+ }
685
+ /**
686
+ * Enable positional options. Positional means global options are specified before subcommands which lets
687
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
688
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
689
+ *
690
+ * @param {boolean} [positional]
691
+ * @return {Command} `this` command for chaining
692
+ */
693
+ enablePositionalOptions(positional = true) {
694
+ this._enablePositionalOptions = !!positional;
695
+ return this;
696
+ }
697
+ /**
698
+ * Pass through options that come after command-arguments rather than treat them as command-options,
699
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
700
+ * positional options to have been enabled on the program (parent commands).
701
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
702
+ *
703
+ * @param {boolean} [passThrough] for unknown options.
704
+ * @return {Command} `this` command for chaining
705
+ */
706
+ passThroughOptions(passThrough = true) {
707
+ this._passThroughOptions = !!passThrough;
708
+ this._checkForBrokenPassThrough();
709
+ return this;
710
+ }
711
+ /**
712
+ * @private
713
+ */
714
+ _checkForBrokenPassThrough() {
715
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
716
+ throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
717
+ }
718
+ }
719
+ /**
720
+ * Whether to store option values as properties on command object,
721
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
722
+ *
723
+ * @param {boolean} [storeAsProperties=true]
724
+ * @return {Command} `this` command for chaining
725
+ */
726
+ storeOptionsAsProperties(storeAsProperties = true) {
727
+ if (this.options.length) {
728
+ throw new Error('call .storeOptionsAsProperties() before adding options');
729
+ }
730
+ if (Object.keys(this._optionValues).length) {
731
+ throw new Error('call .storeOptionsAsProperties() before setting option values');
732
+ }
733
+ this._storeOptionsAsProperties = !!storeAsProperties;
734
+ return this;
735
+ }
736
+ /**
737
+ * Retrieve option value.
738
+ *
739
+ * @param {string} key
740
+ * @return {object} value
741
+ */
742
+ getOptionValue(key) {
743
+ if (this._storeOptionsAsProperties) {
744
+ return this[key];
745
+ }
746
+ return this._optionValues[key];
747
+ }
748
+ /**
749
+ * Store option value.
750
+ *
751
+ * @param {string} key
752
+ * @param {object} value
753
+ * @return {Command} `this` command for chaining
754
+ */
755
+ setOptionValue(key, value) {
756
+ return this.setOptionValueWithSource(key, value, undefined);
757
+ }
758
+ /**
759
+ * Store option value and where the value came from.
760
+ *
761
+ * @param {string} key
762
+ * @param {object} value
763
+ * @param {string} source - expected values are default/config/env/cli/implied
764
+ * @return {Command} `this` command for chaining
765
+ */
766
+ setOptionValueWithSource(key, value, source) {
767
+ if (this._storeOptionsAsProperties) {
768
+ this[key] = value;
769
+ }
770
+ else {
771
+ this._optionValues[key] = value;
772
+ }
773
+ this._optionValueSources[key] = source;
774
+ return this;
775
+ }
776
+ /**
777
+ * Get source of option value.
778
+ * Expected values are default | config | env | cli | implied
779
+ *
780
+ * @param {string} key
781
+ * @return {string}
782
+ */
783
+ getOptionValueSource(key) {
784
+ return this._optionValueSources[key];
785
+ }
786
+ /**
787
+ * Get source of option value. See also .optsWithGlobals().
788
+ * Expected values are default | config | env | cli | implied
789
+ *
790
+ * @param {string} key
791
+ * @return {string}
792
+ */
793
+ getOptionValueSourceWithGlobals(key) {
794
+ // global overwrites local, like optsWithGlobals
795
+ let source;
796
+ this._getCommandAndAncestors().forEach((cmd) => {
797
+ if (cmd.getOptionValueSource(key) !== undefined) {
798
+ source = cmd.getOptionValueSource(key);
799
+ }
800
+ });
801
+ return source;
802
+ }
803
+ /**
804
+ * Get user arguments from implied or explicit arguments.
805
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
806
+ *
807
+ * @private
808
+ */
809
+ _prepareUserArgs(argv, _parseOptions) {
810
+ if (argv !== undefined && !Array.isArray(argv)) {
811
+ throw new Error('first parameter to parse must be array or undefined');
812
+ }
813
+ const parseOptions = _parseOptions || {}; // TODO грязь
814
+ // auto-detect argument conventions if nothing supplied
815
+ if (argv === undefined && parseOptions.from === undefined) {
816
+ if (process.versions?.electron) {
817
+ parseOptions.from = 'electron';
818
+ }
819
+ // check node specific options for scenarios where user CLI args follow executable without scriptname
820
+ const execArgv = process.execArgv ?? [];
821
+ if (execArgv.includes('-e') ||
822
+ execArgv.includes('--eval') ||
823
+ execArgv.includes('-p') ||
824
+ execArgv.includes('--print')) {
825
+ parseOptions.from = 'eval'; // internal usage, not documented
826
+ }
827
+ }
828
+ // default to using process.argv
829
+ if (argv === undefined) {
830
+ argv = process.argv;
831
+ }
832
+ this.rawArgs = argv.slice();
833
+ // extract the user args and scriptPath
834
+ let userArgs;
835
+ switch (parseOptions.from) {
836
+ case undefined:
837
+ case 'node':
838
+ this._scriptPath = argv[1];
839
+ userArgs = argv.slice(2);
840
+ break;
841
+ case 'electron':
842
+ // @ts-ignore: because defaultApp is an unknown property
843
+ if (process.defaultApp) {
844
+ this._scriptPath = argv[1];
845
+ userArgs = argv.slice(2);
846
+ }
847
+ else {
848
+ userArgs = argv.slice(1);
849
+ }
850
+ break;
851
+ case 'user':
852
+ userArgs = argv.slice(0);
853
+ break;
854
+ case 'eval':
855
+ userArgs = argv.slice(1);
856
+ break;
857
+ default:
858
+ throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
859
+ }
860
+ // Find default name for program from arguments.
861
+ if (!this._name && this._scriptPath)
862
+ this.nameFromFilename(this._scriptPath);
863
+ this._name = this._name || 'program';
864
+ return userArgs;
865
+ }
866
+ /**
867
+ * Parse `argv`, setting options and invoking commands when defined.
868
+ *
869
+ * Use parseAsync instead of parse if any of your action handlers are async.
870
+ *
871
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
872
+ *
873
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
874
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
875
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
876
+ * - `'user'`: just user arguments
877
+ *
878
+ * @example
879
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
880
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
881
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
882
+ *
883
+ * @param {string[]} [argv] - optional, defaults to process.argv
884
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
885
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
886
+ * @return {Command} `this` command for chaining
887
+ */
888
+ parse(argv, parseOptions) {
889
+ this._prepareForParse();
890
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
891
+ this._parseCommand([], userArgs);
892
+ return this;
893
+ }
894
+ /**
895
+ * Parse `argv`, setting options and invoking commands when defined.
896
+ *
897
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
898
+ *
899
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
900
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
901
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
902
+ * - `'user'`: just user arguments
903
+ *
904
+ * @example
905
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
906
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
907
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
908
+ *
909
+ * @param {string[]} [argv]
910
+ * @param {object} [parseOptions]
911
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
912
+ * @return {Promise}
913
+ */
914
+ async parseAsync(argv, parseOptions) {
915
+ this._prepareForParse();
916
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
917
+ await this._parseCommand([], userArgs);
918
+ return this;
919
+ }
920
+ _prepareForParse() {
921
+ // Save the state the first time, then restore the state before each subsequent parse.
922
+ if (this._savedState === null) {
923
+ // Do the special default of lone negated option to true, now that we have all the options.
924
+ // Filter for negated options that have not been processed already.
925
+ this.options
926
+ .filter((option) => option.negate &&
927
+ option.defaultValue === undefined &&
928
+ this.getOptionValue(option.attributeName()) === undefined)
929
+ .forEach((option) => {
930
+ // check for lone negated option: --no-foo without a --foo option
931
+ const positiveLongFlag = option.long.replace(/^--no-/, '--');
932
+ if (!this._findOption(positiveLongFlag)) {
933
+ this.setOptionValueWithSource(option.attributeName(), true, 'default');
934
+ }
935
+ });
936
+ this.saveStateBeforeParse();
937
+ }
938
+ else {
939
+ this.restoreStateBeforeParse();
940
+ }
941
+ }
942
+ /**
943
+ * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
944
+ * Not usually called directly, but available for subclasses to save their custom state.
945
+ *
946
+ * This is called in a lazy way. Only commands used in parsing chain will have state saved.
947
+ */
948
+ saveStateBeforeParse() {
949
+ this._savedState = {
950
+ // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing
951
+ _name: this._name,
952
+ // option values before parse have default values (including false for negated options)
953
+ // shallow clones
954
+ _optionValues: { ...this._optionValues },
955
+ _optionValueSources: { ...this._optionValueSources }
956
+ };
957
+ }
958
+ /**
959
+ * Restore state before parse for calls after the first.
960
+ * Not usually called directly, but available for subclasses to save their custom state.
961
+ *
962
+ * This is called in a lazy way. Only commands used in parsing chain will have state restored.
963
+ */
964
+ restoreStateBeforeParse() {
965
+ if (this._storeOptionsAsProperties)
966
+ throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
967
+ - either make a new Command for each call to parse, or stop storing options as properties`);
968
+ // clear state from _prepareUserArgs
969
+ this._name = this._savedState._name;
970
+ this._scriptPath = null;
971
+ this.rawArgs = [];
972
+ // clear state from setOptionValueWithSource
973
+ this._optionValues = { ...this._savedState._optionValues };
974
+ this._optionValueSources = { ...this._savedState._optionValueSources };
975
+ // clear state from _parseCommand
976
+ this.args = [];
977
+ // clear state from _processArguments
978
+ this.processedArgs = [];
979
+ }
980
+ /**
981
+ * Throw if expected executable is missing. Add lots of help for author.
982
+ *
983
+ * @param {string} executableFile
984
+ * @param {string} executableDir
985
+ * @param {string} subcommandName
986
+ */
987
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
988
+ if (fs.existsSync(executableFile))
989
+ return;
990
+ const executableDirMessage = executableDir
991
+ ? `searched for local subcommand relative to directory '${executableDir}'`
992
+ : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';
993
+ const executableMissing = `'${executableFile}' does not exist
994
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
995
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
996
+ - ${executableDirMessage}`;
997
+ throw new Error(executableMissing);
998
+ }
999
+ /**
1000
+ * Execute a sub-command executable.
1001
+ *
1002
+ * @private
1003
+ */
1004
+ _executeSubCommand(subcommand, args) {
1005
+ args = args.slice();
1006
+ const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];
1007
+ function findFile(baseDir, baseName) {
1008
+ // Look for specified file
1009
+ const localBin = path.resolve(baseDir, baseName);
1010
+ if (fs.existsSync(localBin))
1011
+ return localBin;
1012
+ // Stop looking if candidate already has an expected extension.
1013
+ if (sourceExt.includes(path.extname(baseName)))
1014
+ return undefined;
1015
+ // Try all the extensions.
1016
+ const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
1017
+ if (foundExt)
1018
+ return `${localBin}${foundExt}`;
1019
+ return undefined;
1020
+ }
1021
+ // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.
1022
+ this._checkForMissingMandatoryOptions();
1023
+ this._checkForConflictingOptions();
1024
+ // executableFile and executableDir might be full path, or just a name
1025
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1026
+ let executableDir = this._executableDir || '';
1027
+ if (this._scriptPath) {
1028
+ let resolvedScriptPath; // resolve possible symlink for installed npm binary
1029
+ try {
1030
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
1031
+ }
1032
+ catch {
1033
+ resolvedScriptPath = this._scriptPath;
1034
+ }
1035
+ executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
1036
+ }
1037
+ // Look for a local file in preference to a command in PATH.
1038
+ if (executableDir) {
1039
+ let localFile = findFile(executableDir, executableFile);
1040
+ // Legacy search using prefix of script name instead of command name
1041
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1042
+ const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
1043
+ if (legacyName !== this._name) {
1044
+ localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
1045
+ }
1046
+ }
1047
+ executableFile = localFile || executableFile;
1048
+ }
1049
+ const launchWithNode = sourceExt.includes(path.extname(executableFile));
1050
+ let proc;
1051
+ if (process.platform !== 'win32') {
1052
+ if (launchWithNode) {
1053
+ args.unshift(executableFile);
1054
+ // add executable arguments to spawn
1055
+ args = incrementNodeInspectorPort(process.execArgv).concat(args);
1056
+ proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });
1057
+ }
1058
+ else {
1059
+ proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });
1060
+ }
1061
+ }
1062
+ else {
1063
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
1064
+ args.unshift(executableFile);
1065
+ // add executable arguments to spawn
1066
+ args = incrementNodeInspectorPort(process.execArgv).concat(args);
1067
+ proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });
1068
+ }
1069
+ if (!proc.killed) {
1070
+ // testing mainly to avoid leak warnings during unit tests with mocked spawn
1071
+ const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];
1072
+ signals.forEach((signal) => {
1073
+ process.on(signal, () => {
1074
+ if (proc.killed === false && proc.exitCode === null) {
1075
+ // @ts-ignore because signals not typed to known strings
1076
+ proc.kill(signal);
1077
+ }
1078
+ });
1079
+ });
1080
+ }
1081
+ // By default terminate process when spawned process terminates.
1082
+ const exitCallback = this._exitCallback;
1083
+ proc.on('close', (code) => {
1084
+ code = code ?? 1; // code is null if spawned process terminated due to a signal
1085
+ if (!exitCallback) {
1086
+ process.exit(code);
1087
+ }
1088
+ else {
1089
+ exitCallback(new CommanderError(code, 'commander.executeSubCommandAsync', '(close)'));
1090
+ }
1091
+ });
1092
+ proc.on('error', (err) => {
1093
+ // @ts-ignore: because err.code is an unknown property
1094
+ if (err.code === 'ENOENT') {
1095
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
1096
+ // @ts-ignore: because err.code is an unknown property
1097
+ }
1098
+ else if (err.code === 'EACCES') {
1099
+ throw new Error(`'${executableFile}' not executable`);
1100
+ }
1101
+ if (!exitCallback) {
1102
+ process.exit(1);
1103
+ }
1104
+ else {
1105
+ const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)');
1106
+ wrappedError.nestedError = err;
1107
+ exitCallback(wrappedError);
1108
+ }
1109
+ });
1110
+ // Store the reference to the child process
1111
+ this.runningCommand = proc;
1112
+ }
1113
+ /**
1114
+ * @private
1115
+ */
1116
+ _dispatchSubcommand(commandName, operands, unknown) {
1117
+ const subCommand = this._findCommand(commandName);
1118
+ if (!subCommand)
1119
+ this.help({ error: true });
1120
+ subCommand._prepareForParse();
1121
+ let promiseChain;
1122
+ promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, 'preSubcommand');
1123
+ promiseChain = this._chainOrCall(promiseChain, () => {
1124
+ if (subCommand._executableHandler) {
1125
+ this._executeSubCommand(subCommand, operands.concat(unknown));
1126
+ }
1127
+ else {
1128
+ return subCommand._parseCommand(operands, unknown);
1129
+ }
1130
+ });
1131
+ return promiseChain;
1132
+ }
1133
+ /**
1134
+ * Invoke help directly if possible, or dispatch if necessary.
1135
+ * e.g. help foo
1136
+ *
1137
+ * @private
1138
+ */
1139
+ _dispatchHelpCommand(subcommandName) {
1140
+ if (!subcommandName) {
1141
+ this.help();
1142
+ }
1143
+ const subCommand = this._findCommand(subcommandName);
1144
+ if (subCommand && !subCommand._executableHandler) {
1145
+ subCommand.help();
1146
+ }
1147
+ // Fallback to parsing the help flag to invoke the help.
1148
+ return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help']);
1149
+ }
1150
+ /**
1151
+ * Check this.args against expected this.registeredArguments.
1152
+ *
1153
+ * @private
1154
+ */
1155
+ _checkNumberOfArguments() {
1156
+ // too few
1157
+ this.registeredArguments.forEach((arg, i) => {
1158
+ if (arg.required && this.args[i] == null) {
1159
+ this.missingArgument(arg.name());
1160
+ }
1161
+ });
1162
+ // too many
1163
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
1164
+ return;
1165
+ }
1166
+ if (this.args.length > this.registeredArguments.length) {
1167
+ this._excessArguments(this.args);
1168
+ }
1169
+ }
1170
+ /**
1171
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
1172
+ *
1173
+ * @private
1174
+ */
1175
+ _processArguments() {
1176
+ const myParseArg = (argument, value, previous) => {
1177
+ // Extra processing for nice error message on parsing failure.
1178
+ let parsedValue = value;
1179
+ if (value !== null && argument.parseArg) {
1180
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
1181
+ parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
1182
+ }
1183
+ return parsedValue;
1184
+ };
1185
+ this._checkNumberOfArguments();
1186
+ const processedArgs = [];
1187
+ this.registeredArguments.forEach((declaredArg, index) => {
1188
+ let value = declaredArg.defaultValue;
1189
+ if (declaredArg.variadic) {
1190
+ // Collect together remaining arguments for passing together as an array.
1191
+ if (index < this.args.length) {
1192
+ value = this.args.slice(index);
1193
+ if (declaredArg.parseArg) {
1194
+ value = value.reduce((processed, v) => {
1195
+ return myParseArg(declaredArg, v, processed);
1196
+ }, declaredArg.defaultValue);
1197
+ }
1198
+ }
1199
+ else if (value === undefined) {
1200
+ value = [];
1201
+ }
1202
+ }
1203
+ else if (index < this.args.length) {
1204
+ value = this.args[index];
1205
+ if (declaredArg.parseArg) {
1206
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
1207
+ }
1208
+ }
1209
+ processedArgs[index] = value;
1210
+ });
1211
+ this.processedArgs = processedArgs;
1212
+ }
1213
+ /**
1214
+ * Once we have a promise we chain, but call synchronously until then.
1215
+ *
1216
+ * @param {(Promise|undefined)} promise
1217
+ * @param {Function} fn
1218
+ * @return {(Promise|undefined)}
1219
+ * @private
1220
+ */
1221
+ _chainOrCall(promise, fn) {
1222
+ // thenable
1223
+ if (promise?.then && typeof promise.then === 'function') {
1224
+ // already have a promise, chain callback
1225
+ return promise.then(() => fn());
1226
+ }
1227
+ // callback might return a promise
1228
+ return fn();
1229
+ }
1230
+ /**
1231
+ *
1232
+ * @param {(Promise|undefined)} promise
1233
+ * @param {string} event
1234
+ * @return {(Promise|undefined)}
1235
+ * @private
1236
+ */
1237
+ _chainOrCallHooks(promise, event) {
1238
+ let result = promise;
1239
+ const hooks = [];
1240
+ this._getCommandAndAncestors()
1241
+ .reverse()
1242
+ .filter((cmd) => cmd._lifeCycleHooks[event] !== undefined)
1243
+ .forEach((hookedCommand) => {
1244
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
1245
+ hooks.push({ hookedCommand, callback });
1246
+ });
1247
+ });
1248
+ if (event === 'postAction') {
1249
+ hooks.reverse();
1250
+ }
1251
+ hooks.forEach((hookDetail) => {
1252
+ result = this._chainOrCall(result, () => {
1253
+ return hookDetail.callback(hookDetail.hookedCommand, this);
1254
+ });
1255
+ });
1256
+ return result;
1257
+ }
1258
+ /**
1259
+ *
1260
+ * @param {(Promise|undefined)} promise
1261
+ * @param {Command} subCommand
1262
+ * @param {string} event
1263
+ * @return {(Promise|undefined)}
1264
+ * @private
1265
+ */
1266
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
1267
+ let result = promise;
1268
+ if (this._lifeCycleHooks[event] !== undefined) {
1269
+ this._lifeCycleHooks[event].forEach((hook) => {
1270
+ result = this._chainOrCall(result, () => {
1271
+ return hook(this, subCommand);
1272
+ });
1273
+ });
1274
+ }
1275
+ return result;
1276
+ }
1277
+ /**
1278
+ * Process arguments in context of this command.
1279
+ * Returns action result, in case it is a promise.
1280
+ *
1281
+ * @private
1282
+ */
1283
+ _parseCommand(operands, unknown) {
1284
+ const parsed = this.parseOptions(unknown);
1285
+ this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env
1286
+ this._parseOptionsImplied();
1287
+ operands = operands.concat(parsed.operands);
1288
+ unknown = parsed.unknown;
1289
+ this.args = operands.concat(unknown);
1290
+ if (operands && this._findCommand(operands[0])) {
1291
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
1292
+ }
1293
+ const helpCommand = this._getHelpCommand();
1294
+ if (helpCommand && operands[0] === helpCommand.name()) {
1295
+ return this._dispatchHelpCommand(operands[1]);
1296
+ }
1297
+ if (this._defaultCommandName) {
1298
+ this._outputHelpIfRequested(unknown); // Run the help for default command from parent rather than passing to default command
1299
+ return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
1300
+ }
1301
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
1302
+ // probably missing subcommand and no handler, user needs help (and exit)
1303
+ this.help({ error: true });
1304
+ }
1305
+ this._outputHelpIfRequested(parsed.unknown);
1306
+ this._checkForMissingMandatoryOptions();
1307
+ this._checkForConflictingOptions();
1308
+ // We do not always call this check to avoid masking a "better" error, like unknown command.
1309
+ const checkForUnknownOptions = () => {
1310
+ if (parsed.unknown.length > 0) {
1311
+ this.unknownOption(parsed.unknown[0]);
1312
+ }
1313
+ };
1314
+ const commandEvent = `command:${this.name()}`;
1315
+ const actionHandler = this._actionHandler;
1316
+ if (actionHandler) {
1317
+ checkForUnknownOptions();
1318
+ this._processArguments();
1319
+ let promiseChain;
1320
+ promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');
1321
+ promiseChain = this._chainOrCall(promiseChain, () => actionHandler(this.processedArgs));
1322
+ const parent = this.parent;
1323
+ if (parent) {
1324
+ promiseChain = this._chainOrCall(promiseChain, () => {
1325
+ parent.emit(commandEvent, operands, unknown); // legacy
1326
+ });
1327
+ }
1328
+ promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');
1329
+ return promiseChain;
1330
+ }
1331
+ if (this.parent?.listenerCount(commandEvent)) {
1332
+ checkForUnknownOptions();
1333
+ this._processArguments();
1334
+ this.parent.emit(commandEvent, operands, unknown); // legacy
1335
+ }
1336
+ else if (operands.length) {
1337
+ if (this._findCommand('*')) {
1338
+ // legacy default command
1339
+ return this._dispatchSubcommand('*', operands, unknown);
1340
+ }
1341
+ if (this.listenerCount('command:*')) {
1342
+ // skip option check, emit event for possible misspelling suggestion
1343
+ this.emit('command:*', operands, unknown);
1344
+ }
1345
+ else if (this.commands.length) {
1346
+ this.unknownCommand();
1347
+ }
1348
+ else {
1349
+ checkForUnknownOptions();
1350
+ this._processArguments();
1351
+ }
1352
+ }
1353
+ else if (this.commands.length) {
1354
+ checkForUnknownOptions();
1355
+ // This command has subcommands and nothing hooked up at this level, so display help (and exit).
1356
+ this.help({ error: true });
1357
+ }
1358
+ else {
1359
+ checkForUnknownOptions();
1360
+ this._processArguments();
1361
+ // fall through for caller to handle after calling .parse()
1362
+ }
1363
+ }
1364
+ /**
1365
+ * Find matching command.
1366
+ *
1367
+ * @private
1368
+ * @return {Command | undefined}
1369
+ */
1370
+ _findCommand(name) {
1371
+ if (!name)
1372
+ return undefined;
1373
+ return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
1374
+ }
1375
+ /**
1376
+ * Return an option matching `arg` if any.
1377
+ *
1378
+ * @param {string} arg
1379
+ * @return {Option}
1380
+ * @package
1381
+ */
1382
+ _findOption(arg) {
1383
+ return this.options.find((option) => option.is(arg));
1384
+ }
1385
+ /**
1386
+ * Display an error message if a mandatory option does not have a value.
1387
+ * Called after checking for help flags in leaf subcommand.
1388
+ *
1389
+ * @private
1390
+ */
1391
+ _checkForMissingMandatoryOptions() {
1392
+ // Walk up hierarchy so can call in subcommand after checking for displaying help.
1393
+ this._getCommandAndAncestors().forEach((cmd) => {
1394
+ cmd.options.forEach((anOption) => {
1395
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === undefined) {
1396
+ cmd.missingMandatoryOptionValue(anOption);
1397
+ }
1398
+ });
1399
+ });
1400
+ }
1401
+ /**
1402
+ * Display an error message if conflicting options are used together in this.
1403
+ *
1404
+ * @private
1405
+ */
1406
+ _checkForConflictingLocalOptions() {
1407
+ const definedNonDefaultOptions = this.options.filter((option) => {
1408
+ const optionKey = option.attributeName();
1409
+ if (this.getOptionValue(optionKey) === undefined) {
1410
+ return false;
1411
+ }
1412
+ return this.getOptionValueSource(optionKey) !== 'default';
1413
+ });
1414
+ const optionsWithConflicting = definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0);
1415
+ optionsWithConflicting.forEach((option) => {
1416
+ const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
1417
+ if (conflictingAndDefined) {
1418
+ this._conflictingOption(option, conflictingAndDefined);
1419
+ }
1420
+ });
1421
+ }
1422
+ /**
1423
+ * Display an error message if conflicting options are used together.
1424
+ * Called after checking for help flags in leaf subcommand.
1425
+ *
1426
+ * @private
1427
+ */
1428
+ _checkForConflictingOptions() {
1429
+ // Walk up hierarchy so can call in subcommand after checking for displaying help.
1430
+ this._getCommandAndAncestors().forEach((cmd) => {
1431
+ cmd._checkForConflictingLocalOptions();
1432
+ });
1433
+ }
1434
+ /**
1435
+ * Parse options from `argv` removing known options,
1436
+ * and return argv split into operands and unknown arguments.
1437
+ *
1438
+ * Side effects: modifies command by storing options. Does not reset state if called again.
1439
+ *
1440
+ * Examples:
1441
+ *
1442
+ * argv => operands, unknown
1443
+ * --known kkk op => [op], []
1444
+ * op --known kkk => [op], []
1445
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
1446
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
1447
+ *
1448
+ * @param {string[]} args
1449
+ * @return {{operands: string[], unknown: string[]}}
1450
+ */
1451
+ parseOptions(args) {
1452
+ const operands = []; // operands, not options or values
1453
+ const unknown = []; // first unknown option and remaining unknown args
1454
+ let dest = operands;
1455
+ function maybeOption(arg) {
1456
+ return arg.length > 1 && arg[0] === '-';
1457
+ }
1458
+ const negativeNumberArg = (arg) => {
1459
+ // return false if not a negative number
1460
+ if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg))
1461
+ return false;
1462
+ // negative number is ok unless digit used as an option in command hierarchy
1463
+ return !this._getCommandAndAncestors().some((cmd) => cmd.options.map((opt) => opt.short).some((short) => short !== undefined && /^-\d$/.test(short)));
1464
+ };
1465
+ // parse options
1466
+ let activeVariadicOption = null;
1467
+ let activeGroup = null; // working through group of short options, like -abc
1468
+ let i = 0;
1469
+ while (i < args.length || activeGroup) {
1470
+ const arg = activeGroup ?? args[i++];
1471
+ activeGroup = null;
1472
+ // literal
1473
+ if (arg === '--') {
1474
+ if (dest === unknown)
1475
+ dest.push(arg);
1476
+ dest.push(...args.slice(i));
1477
+ break;
1478
+ }
1479
+ if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
1480
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
1481
+ continue;
1482
+ }
1483
+ activeVariadicOption = null;
1484
+ if (maybeOption(arg)) {
1485
+ const option = this._findOption(arg);
1486
+ // recognised option, call listener to assign value with possible custom processing
1487
+ if (option) {
1488
+ if (option.required) {
1489
+ const value = args[i++];
1490
+ if (value === undefined)
1491
+ this.optionMissingArgument(option);
1492
+ this.emit(`option:${option.name()}`, value);
1493
+ }
1494
+ else if (option.optional) {
1495
+ let value = null;
1496
+ // historical behaviour is optional value is following arg unless an option
1497
+ if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) {
1498
+ value = args[i++];
1499
+ }
1500
+ this.emit(`option:${option.name()}`, value);
1501
+ }
1502
+ else {
1503
+ // boolean flag
1504
+ this.emit(`option:${option.name()}`);
1505
+ }
1506
+ activeVariadicOption = option.variadic ? option : null;
1507
+ continue;
1508
+ }
1509
+ }
1510
+ // Look for combo options following single dash, eat first one if known.
1511
+ if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {
1512
+ const option = this._findOption(`-${arg[1]}`);
1513
+ if (option) {
1514
+ if (option.required || (option.optional && this._combineFlagAndOptionalValue)) {
1515
+ // option with value following in same argument
1516
+ this.emit(`option:${option.name()}`, arg.slice(2));
1517
+ }
1518
+ else {
1519
+ // boolean option
1520
+ this.emit(`option:${option.name()}`);
1521
+ // remove the processed option and keep processing group
1522
+ activeGroup = `-${arg.slice(2)}`;
1523
+ }
1524
+ continue;
1525
+ }
1526
+ }
1527
+ // Look for known long flag with value, like --foo=bar
1528
+ if (/^--[^=]+=/.test(arg)) {
1529
+ const index = arg.indexOf('=');
1530
+ const option = this._findOption(arg.slice(0, index));
1531
+ if (option && (option.required || option.optional)) {
1532
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
1533
+ continue;
1534
+ }
1535
+ }
1536
+ // Not a recognised option by this command.
1537
+ // Might be a command-argument, or subcommand option, or unknown option, or help command or option.
1538
+ // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.
1539
+ // A negative number in a leaf command is not an unknown option.
1540
+ if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) {
1541
+ dest = unknown;
1542
+ }
1543
+ // If using positionalOptions, stop processing our options at subcommand.
1544
+ if ((this._enablePositionalOptions || this._passThroughOptions) &&
1545
+ operands.length === 0 &&
1546
+ unknown.length === 0) {
1547
+ if (this._findCommand(arg)) {
1548
+ operands.push(arg);
1549
+ unknown.push(...args.slice(i));
1550
+ break;
1551
+ }
1552
+ else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
1553
+ operands.push(arg, ...args.slice(i));
1554
+ break;
1555
+ }
1556
+ else if (this._defaultCommandName) {
1557
+ unknown.push(arg, ...args.slice(i));
1558
+ break;
1559
+ }
1560
+ }
1561
+ // If using passThroughOptions, stop processing options at first command-argument.
1562
+ if (this._passThroughOptions) {
1563
+ dest.push(arg, ...args.slice(i));
1564
+ break;
1565
+ }
1566
+ // add arg
1567
+ dest.push(arg);
1568
+ }
1569
+ return { operands, unknown };
1570
+ }
1571
+ /**
1572
+ * Return an object containing local option values as key-value pairs.
1573
+ *
1574
+ * @return {object}
1575
+ */
1576
+ opts() {
1577
+ if (this._storeOptionsAsProperties) {
1578
+ // Preserve original behaviour so backwards compatible when still using properties
1579
+ const result = {};
1580
+ const len = this.options.length;
1581
+ for (let i = 0; i < len; i++) {
1582
+ const key = this.options[i].attributeName();
1583
+ result[key] = key === this._versionOptionName ? this._version : this[key];
1584
+ }
1585
+ return result;
1586
+ }
1587
+ return this._optionValues;
1588
+ }
1589
+ /**
1590
+ * Return an object containing merged local and global option values as key-value pairs.
1591
+ *
1592
+ * @return {object}
1593
+ */
1594
+ optsWithGlobals() {
1595
+ // globals overwrite locals
1596
+ return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
1597
+ }
1598
+ /**
1599
+ * Display error message and exit (or call exitOverride).
1600
+ *
1601
+ * @param {string} message
1602
+ * @param {object} [errorOptions]
1603
+ * @param {string} [errorOptions.code] - an id string representing the error
1604
+ * @param {number} [errorOptions.exitCode] - used with process.exit
1605
+ */
1606
+ error(message, errorOptions) {
1607
+ // output handling
1608
+ this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);
1609
+ if (typeof this._showHelpAfterError === 'string') {
1610
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);
1611
+ }
1612
+ else if (this._showHelpAfterError) {
1613
+ this._outputConfiguration.writeErr('\n');
1614
+ this.outputHelp({ error: true });
1615
+ }
1616
+ // exit handling
1617
+ const config = errorOptions || {};
1618
+ const exitCode = config.exitCode || 1;
1619
+ const code = config.code || 'commander.error';
1620
+ this._exit(exitCode, code, message);
1621
+ }
1622
+ /**
1623
+ * Apply any option related environment variables, if option does
1624
+ * not have a value from cli or client code.
1625
+ *
1626
+ * @private
1627
+ */
1628
+ _parseOptionsEnv() {
1629
+ this.options.forEach((option) => {
1630
+ if (option.envVar && option.envVar in process.env) {
1631
+ const optionKey = option.attributeName();
1632
+ // Priority check. Do not overwrite cli or options from unknown source (client-code).
1633
+ if (this.getOptionValue(optionKey) === undefined ||
1634
+ ['default', 'config', 'env'].includes(this.getOptionValueSource(optionKey))) {
1635
+ if (option.required || option.optional) {
1636
+ // option can take a value
1637
+ // keep very simple, optional always takes value
1638
+ this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);
1639
+ }
1640
+ else {
1641
+ // boolean
1642
+ // keep very simple, only care that envVar defined and not the value
1643
+ this.emit(`optionEnv:${option.name()}`);
1644
+ }
1645
+ }
1646
+ }
1647
+ });
1648
+ }
1649
+ /**
1650
+ * Apply any implied option values, if option is undefined or default value.
1651
+ *
1652
+ * @private
1653
+ */
1654
+ _parseOptionsImplied() {
1655
+ const dualHelper = new DualOptions(this.options);
1656
+ const hasCustomOptionValue = (optionKey) => {
1657
+ return (this.getOptionValue(optionKey) !== undefined &&
1658
+ !['default', 'implied'].includes(this.getOptionValueSource(optionKey)));
1659
+ };
1660
+ this.options
1661
+ .filter((option) => option.implied !== undefined &&
1662
+ hasCustomOptionValue(option.attributeName()) &&
1663
+ dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option))
1664
+ .forEach((option) => {
1665
+ const implied = option.implied;
1666
+ Object.keys(implied)
1667
+ .filter((impliedKey) => !hasCustomOptionValue(impliedKey))
1668
+ .forEach((impliedKey) => {
1669
+ this.setOptionValueWithSource(impliedKey, implied[impliedKey], 'implied');
1670
+ });
1671
+ });
1672
+ }
1673
+ /**
1674
+ * Argument `name` is missing.
1675
+ *
1676
+ * @param {string} name
1677
+ * @private
1678
+ */
1679
+ missingArgument(name) {
1680
+ const message = `error: missing required argument '${name}'`;
1681
+ this.error(message, { code: 'commander.missingArgument' });
1682
+ }
1683
+ /**
1684
+ * `Option` is missing an argument.
1685
+ *
1686
+ * @param {Option} option
1687
+ * @private
1688
+ */
1689
+ optionMissingArgument(option) {
1690
+ const message = `error: option '${option.flags}' argument missing`;
1691
+ this.error(message, { code: 'commander.optionMissingArgument' });
1692
+ }
1693
+ /**
1694
+ * `Option` does not have a value, and is a mandatory option.
1695
+ *
1696
+ * @param {Option} option
1697
+ * @private
1698
+ */
1699
+ missingMandatoryOptionValue(option) {
1700
+ const message = `error: required option '${option.flags}' not specified`;
1701
+ this.error(message, { code: 'commander.missingMandatoryOptionValue' });
1702
+ }
1703
+ /**
1704
+ * `Option` conflicts with another option.
1705
+ *
1706
+ * @param {Option} option
1707
+ * @param {Option} conflictingOption
1708
+ * @private
1709
+ */
1710
+ _conflictingOption(option, conflictingOption) {
1711
+ // The calling code does not know whether a negated option is the source of the
1712
+ // value, so do some work to take an educated guess.
1713
+ const findBestOptionFromValue = (option) => {
1714
+ const optionKey = option.attributeName();
1715
+ const optionValue = this.getOptionValue(optionKey);
1716
+ const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
1717
+ const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
1718
+ if (negativeOption &&
1719
+ ((negativeOption.presetArg === undefined && optionValue === false) ||
1720
+ (negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg))) {
1721
+ return negativeOption;
1722
+ }
1723
+ return positiveOption || option;
1724
+ };
1725
+ const getErrorMessage = (option) => {
1726
+ const bestOption = findBestOptionFromValue(option);
1727
+ const optionKey = bestOption.attributeName();
1728
+ const source = this.getOptionValueSource(optionKey);
1729
+ if (source === 'env') {
1730
+ return `environment variable '${bestOption.envVar}'`;
1731
+ }
1732
+ return `option '${bestOption.flags}'`;
1733
+ };
1734
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
1735
+ this.error(message, { code: 'commander.conflictingOption' });
1736
+ }
1737
+ /**
1738
+ * Unknown option `flag`.
1739
+ *
1740
+ * @param {string} flag
1741
+ * @private
1742
+ */
1743
+ unknownOption(flag) {
1744
+ if (this._allowUnknownOption)
1745
+ return;
1746
+ let suggestion = '';
1747
+ if (flag.startsWith('--') && this._showSuggestionAfterError) {
1748
+ // Looping to pick up the global options too
1749
+ let candidateFlags = [];
1750
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
1751
+ let command = this;
1752
+ do {
1753
+ const moreFlags = command
1754
+ .createHelp()
1755
+ .visibleOptions(command)
1756
+ .filter((option) => option.long)
1757
+ .map((option) => option.long);
1758
+ candidateFlags = candidateFlags.concat(moreFlags);
1759
+ command = command.parent;
1760
+ } while (command && !command._enablePositionalOptions);
1761
+ suggestion = suggestSimilar(flag, candidateFlags);
1762
+ }
1763
+ const message = `error: unknown option '${flag}'${suggestion}`;
1764
+ this.error(message, { code: 'commander.unknownOption' });
1765
+ }
1766
+ /**
1767
+ * Excess arguments, more than expected.
1768
+ *
1769
+ * @param {string[]} receivedArgs
1770
+ * @private
1771
+ */
1772
+ _excessArguments(receivedArgs) {
1773
+ if (this._allowExcessArguments)
1774
+ return;
1775
+ const expected = this.registeredArguments.length;
1776
+ const s = expected === 1 ? '' : 's';
1777
+ const received = receivedArgs.length;
1778
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : '';
1779
+ const details = receivedArgs.join(', ');
1780
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${received}: ${details}.`;
1781
+ this.error(message, { code: 'commander.excessArguments' });
1782
+ }
1783
+ /**
1784
+ * Unknown command.
1785
+ *
1786
+ * @private
1787
+ */
1788
+ unknownCommand() {
1789
+ const unknownName = this.args[0];
1790
+ let suggestion = '';
1791
+ if (this._showSuggestionAfterError) {
1792
+ const candidateNames = [];
1793
+ this.createHelp()
1794
+ .visibleCommands(this)
1795
+ .forEach((command) => {
1796
+ candidateNames.push(command.name());
1797
+ // just visible alias
1798
+ if (command.alias())
1799
+ candidateNames.push(command.alias());
1800
+ });
1801
+ suggestion = suggestSimilar(unknownName, candidateNames);
1802
+ }
1803
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
1804
+ this.error(message, { code: 'commander.unknownCommand' });
1805
+ }
1806
+ version(str, flags, description) {
1807
+ if (str === undefined)
1808
+ return this._version;
1809
+ this._version = str;
1810
+ flags = flags || '-V, --version';
1811
+ description = description || 'output the version number';
1812
+ const versionOption = this.createOption(flags, description);
1813
+ this._versionOptionName = versionOption.attributeName();
1814
+ this._registerOption(versionOption);
1815
+ this.on('option:' + versionOption.name(), () => {
1816
+ this._outputConfiguration.writeOut(`${str}\n`);
1817
+ this._exit(0, 'commander.version', str);
1818
+ });
1819
+ return this;
1820
+ }
1821
+ description(str, argsDescription) {
1822
+ if (str === undefined && argsDescription === undefined) {
1823
+ return this._description;
1824
+ }
1825
+ this._description = str;
1826
+ if (argsDescription) {
1827
+ this._argsDescription = argsDescription;
1828
+ }
1829
+ return this;
1830
+ }
1831
+ summary(str) {
1832
+ if (str === undefined)
1833
+ return this._summary;
1834
+ this._summary = str;
1835
+ return this;
1836
+ }
1837
+ alias(alias) {
1838
+ if (alias === undefined)
1839
+ return this._aliases[0]; // just return first, for backwards compatibility
1840
+ let command = this;
1841
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
1842
+ // assume adding alias for last added executable subcommand, rather than this
1843
+ command = this.commands[this.commands.length - 1];
1844
+ }
1845
+ if (alias === command._name)
1846
+ throw new Error("Command alias can't be the same as its name");
1847
+ const matchingCommand = this.parent?._findCommand(alias);
1848
+ if (matchingCommand) {
1849
+ // c.f. _registerCommand
1850
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join('|');
1851
+ throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
1852
+ }
1853
+ command._aliases.push(alias);
1854
+ return this;
1855
+ }
1856
+ aliases(aliases) {
1857
+ // Getter for the array of aliases is the main reason for having aliases() in addition to alias().
1858
+ if (aliases === undefined)
1859
+ return this._aliases;
1860
+ aliases.forEach((alias) => this.alias(alias));
1861
+ return this;
1862
+ }
1863
+ usage(str) {
1864
+ if (str === undefined) {
1865
+ if (this._usage)
1866
+ return this._usage;
1867
+ const args = this.registeredArguments.map((arg) => {
1868
+ return humanReadableArgName(arg);
1869
+ });
1870
+ return []
1871
+ .concat(this.options.length || this._helpOption !== null ? '[options]' : [], this.commands.length ? '[command]' : [], this.registeredArguments.length ? args : [])
1872
+ .join(' ');
1873
+ }
1874
+ this._usage = str;
1875
+ return this;
1876
+ }
1877
+ name(str) {
1878
+ if (str === undefined)
1879
+ return this._name;
1880
+ this._name = str;
1881
+ return this;
1882
+ }
1883
+ helpGroup(heading) {
1884
+ if (heading === undefined)
1885
+ return this._helpGroupHeading ?? '';
1886
+ this._helpGroupHeading = heading;
1887
+ return this;
1888
+ }
1889
+ commandsGroup(heading) {
1890
+ if (heading === undefined)
1891
+ return this._defaultCommandGroup ?? '';
1892
+ this._defaultCommandGroup = heading;
1893
+ return this;
1894
+ }
1895
+ optionsGroup(heading) {
1896
+ if (heading === undefined)
1897
+ return this._defaultOptionGroup ?? '';
1898
+ this._defaultOptionGroup = heading;
1899
+ return this;
1900
+ }
1901
+ /**
1902
+ * @param {Option} option
1903
+ * @private
1904
+ */
1905
+ _initOptionGroup(option) {
1906
+ if (this._defaultOptionGroup && !option.helpGroupHeading)
1907
+ option.helpGroup(this._defaultOptionGroup);
1908
+ }
1909
+ /**
1910
+ * @param {Command} cmd
1911
+ * @private
1912
+ */
1913
+ _initCommandGroup(cmd) {
1914
+ if (this._defaultCommandGroup && !cmd.helpGroup())
1915
+ cmd.helpGroup(this._defaultCommandGroup);
1916
+ }
1917
+ /**
1918
+ * Set the name of the command from script filename, such as process.argv[1],
1919
+ * or import.meta.filename.
1920
+ *
1921
+ * (Used internally and public although not documented in README.)
1922
+ *
1923
+ * @example
1924
+ * program.nameFromFilename(import.meta.filename);
1925
+ *
1926
+ * @param {string} filename
1927
+ * @return {Command}
1928
+ */
1929
+ nameFromFilename(filename) {
1930
+ this._name = path.basename(filename, path.extname(filename));
1931
+ return this;
1932
+ }
1933
+ executableDir(path) {
1934
+ if (path === undefined)
1935
+ return this._executableDir;
1936
+ this._executableDir = path;
1937
+ return this;
1938
+ }
1939
+ /**
1940
+ * Return program help documentation.
1941
+ *
1942
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
1943
+ * @return {string}
1944
+ */
1945
+ helpInformation(contextOptions) {
1946
+ const helper = this.createHelp();
1947
+ const context = this._getOutputContext(contextOptions);
1948
+ helper.prepareContext({
1949
+ error: context.error,
1950
+ helpWidth: context.helpWidth,
1951
+ outputHasColors: context.hasColors
1952
+ });
1953
+ const text = helper.formatHelp(this, helper);
1954
+ if (context.hasColors)
1955
+ return text;
1956
+ return this._outputConfiguration.stripColor(text);
1957
+ }
1958
+ /**
1959
+ * @typedef HelpContext
1960
+ * @type {object}
1961
+ * @property {boolean} error
1962
+ * @property {number} helpWidth
1963
+ * @property {boolean} hasColors
1964
+ * @property {function} write - includes stripColor if needed
1965
+ *
1966
+ * @returns {HelpContext}
1967
+ * @private
1968
+ */
1969
+ _getOutputContext(contextOptions) {
1970
+ contextOptions = contextOptions || {};
1971
+ const error = !!contextOptions.error;
1972
+ let baseWrite;
1973
+ let hasColors;
1974
+ let helpWidth;
1975
+ if (error) {
1976
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
1977
+ hasColors = this._outputConfiguration.getErrHasColors();
1978
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
1979
+ }
1980
+ else {
1981
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
1982
+ hasColors = this._outputConfiguration.getOutHasColors();
1983
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
1984
+ }
1985
+ const write = (str) => {
1986
+ if (!hasColors)
1987
+ str = this._outputConfiguration.stripColor(str);
1988
+ return baseWrite(str);
1989
+ };
1990
+ return { error, write, hasColors, helpWidth };
1991
+ }
1992
+ outputHelp(contextOptions) {
1993
+ let deprecatedCallback;
1994
+ let helpContext;
1995
+ if (typeof contextOptions === 'function') {
1996
+ deprecatedCallback = contextOptions;
1997
+ }
1998
+ else {
1999
+ helpContext = contextOptions;
2000
+ }
2001
+ const outputContext = this._getOutputContext(helpContext);
2002
+ /** @type {HelpTextEventContext} */
2003
+ const eventContext = {
2004
+ error: outputContext.error,
2005
+ write: outputContext.write,
2006
+ command: this
2007
+ };
2008
+ this._getCommandAndAncestors()
2009
+ .reverse()
2010
+ .forEach((command) => command.emit('beforeAllHelp', eventContext));
2011
+ this.emit('beforeHelp', eventContext);
2012
+ let helpInformation = this.helpInformation({ error: outputContext.error });
2013
+ if (deprecatedCallback) {
2014
+ helpInformation = deprecatedCallback(helpInformation);
2015
+ if (typeof helpInformation !== 'string' && !Buffer.isBuffer(helpInformation)) {
2016
+ throw new Error('outputHelp callback must return a string or a Buffer');
2017
+ }
2018
+ }
2019
+ outputContext.write(helpInformation);
2020
+ const helpOption = this._getHelpOption();
2021
+ if (helpOption?.long) {
2022
+ this.emit(helpOption.long); // deprecated
2023
+ }
2024
+ this.emit('afterHelp', eventContext);
2025
+ this._getCommandAndAncestors().forEach((command) => command.emit('afterAllHelp', eventContext));
2026
+ }
2027
+ /**
2028
+ * You can pass in flags and a description to customise the built-in help option.
2029
+ * Pass in false to disable the built-in help option.
2030
+ *
2031
+ * @example
2032
+ * program.helpOption('-?, --help' 'show help'); // customise
2033
+ * program.helpOption(false); // disable
2034
+ *
2035
+ * @param {(string | boolean)} flags
2036
+ * @param {string} [description]
2037
+ * @return {Command} `this` command for chaining
2038
+ */
2039
+ helpOption(flags, description) {
2040
+ // Support enabling/disabling built-in help option.
2041
+ if (typeof flags === 'boolean') {
2042
+ if (flags) {
2043
+ if (this._helpOption === null)
2044
+ this._helpOption = undefined; // reenable
2045
+ if (this._defaultOptionGroup) {
2046
+ // make the option to store the group
2047
+ const helpOption = this._getHelpOption();
2048
+ if (helpOption)
2049
+ this._initOptionGroup(helpOption);
2050
+ }
2051
+ }
2052
+ else {
2053
+ this._helpOption = null; // disable
2054
+ }
2055
+ return this;
2056
+ }
2057
+ // Customise flags and description.
2058
+ this._helpOption = this.createOption(flags ?? '-h, --help', description ?? 'display help for command');
2059
+ // init group unless lazy create
2060
+ if (flags || description)
2061
+ this._initOptionGroup(this._helpOption);
2062
+ return this;
2063
+ }
2064
+ /**
2065
+ * Lazy create help option.
2066
+ * Returns null if has been disabled with .helpOption(false).
2067
+ *
2068
+ * @returns {(Option | null)} the help option
2069
+ * @package
2070
+ */
2071
+ _getHelpOption() {
2072
+ // Lazy create help option on demand.
2073
+ if (this._helpOption === undefined) {
2074
+ this.helpOption(undefined, undefined);
2075
+ }
2076
+ return this._helpOption ?? null;
2077
+ }
2078
+ /**
2079
+ * Supply your own option to use for the built-in help option.
2080
+ * This is an alternative to using helpOption() to customise the flags and description etc.
2081
+ *
2082
+ * @param {Option} option
2083
+ * @return {Command} `this` command for chaining
2084
+ */
2085
+ addHelpOption(option) {
2086
+ this._helpOption = option;
2087
+ this._initOptionGroup(option);
2088
+ return this;
2089
+ }
2090
+ help(contextOptions) {
2091
+ this.outputHelp(contextOptions);
2092
+ let exitCode = Number(process.exitCode ?? 0); // process.exitCode does allow a string or an integer, but we prefer just a number
2093
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== 'function' && contextOptions.error) {
2094
+ exitCode = 1;
2095
+ }
2096
+ // message: do not have all displayed text available so only passing placeholder.
2097
+ this._exit(exitCode, 'commander.help', '(outputHelp)');
2098
+ }
2099
+ addHelpText(position, text) {
2100
+ const allowedValues = ['beforeAll', 'before', 'after', 'afterAll'];
2101
+ if (!allowedValues.includes(position)) {
2102
+ throw new Error(`Unexpected value for position to addHelpText.
2103
+ Expecting one of '${allowedValues.join("', '")}'`);
2104
+ }
2105
+ const helpEvent = `${position}Help`;
2106
+ this.on(helpEvent, (/** @type {HelpTextEventContext} */ context) => {
2107
+ let helpStr;
2108
+ if (typeof text === 'function') {
2109
+ helpStr = text({ error: context.error, command: context.command });
2110
+ }
2111
+ else {
2112
+ helpStr = text;
2113
+ }
2114
+ // Ignore falsy value when nothing to output.
2115
+ if (helpStr) {
2116
+ context.write(`${helpStr}\n`);
2117
+ }
2118
+ });
2119
+ return this;
2120
+ }
2121
+ /**
2122
+ * Output help information if help flags specified
2123
+ *
2124
+ * @param {Array} args - array of options to search for help flags
2125
+ * @private
2126
+ */
2127
+ _outputHelpIfRequested(args) {
2128
+ const helpOption = this._getHelpOption();
2129
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
2130
+ if (helpRequested) {
2131
+ this.outputHelp();
2132
+ // (Do not have all displayed text available so only passing placeholder.)
2133
+ this._exit(0, 'commander.helpDisplayed', '(outputHelp)');
2134
+ }
2135
+ }
2136
+ }
2137
+ /**
2138
+ * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).
2139
+ *
2140
+ * @param {string[]} args - array of arguments from node.execArgv
2141
+ * @returns {string[]}
2142
+ * @private
2143
+ */
2144
+ function incrementNodeInspectorPort(args) {
2145
+ // Testing for these options:
2146
+ // --inspect[=[host:]port]
2147
+ // --inspect-brk[=[host:]port]
2148
+ // --inspect-port=[host:]port
2149
+ return args.map((arg) => {
2150
+ if (!arg.startsWith('--inspect')) {
2151
+ return arg;
2152
+ }
2153
+ let debugOption;
2154
+ let debugHost = '127.0.0.1';
2155
+ let debugPort = '9229';
2156
+ let match;
2157
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
2158
+ // e.g. --inspect
2159
+ debugOption = match[1];
2160
+ }
2161
+ else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
2162
+ debugOption = match[1];
2163
+ if (/^\d+$/.test(match[3])) {
2164
+ // e.g. --inspect=1234
2165
+ debugPort = match[3];
2166
+ }
2167
+ else {
2168
+ // e.g. --inspect=localhost
2169
+ debugHost = match[3];
2170
+ }
2171
+ }
2172
+ else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
2173
+ // e.g. --inspect=localhost:1234
2174
+ debugOption = match[1];
2175
+ debugHost = match[3];
2176
+ debugPort = match[4];
2177
+ }
2178
+ if (debugOption && debugPort !== '0') {
2179
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
2180
+ }
2181
+ return arg;
2182
+ });
2183
+ }
2184
+ /**
2185
+ * Exported for using from tests, not otherwise used outside this file.
2186
+ *
2187
+ * @returns {boolean | undefined}
2188
+ * @package
2189
+ */
2190
+ export function useColor() {
2191
+ // Test for common conventions.
2192
+ // NB: the observed behaviour is in combination with how author adds color! For example:
2193
+ // - we do not test NODE_DISABLE_COLORS, but util:styletext does
2194
+ // - we do test NO_COLOR, but Chalk does not
2195
+ //
2196
+ // References:
2197
+ // https://no-color.org
2198
+ // https://bixense.com/clicolors/
2199
+ // https://github.com/nodejs/node/blob/0a00217a5f67ef4a22384cfc80eb6dd9a917fdc1/lib/internal/tty.js#L109
2200
+ // https://github.com/chalk/supports-color/blob/c214314a14bcb174b12b3014b2b0a8de375029ae/index.js#L33
2201
+ // (https://force-color.org recent web page from 2023, does not match major javascript implementations)
2202
+ if (process.env.NO_COLOR || process.env.FORCE_COLOR === '0' || process.env.FORCE_COLOR === 'false')
2203
+ return false;
2204
+ if (process.env.FORCE_COLOR || process.env.CLICOLOR_FORCE !== undefined)
2205
+ return true;
2206
+ return undefined;
2207
+ }
2208
+ //# sourceMappingURL=command.js.map