@shuiyangsuan/cli 0.0.3 → 0.0.6

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