@agentconnect.md/daemon 1.0.0-rc.22 → 1.0.0-rc.221

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