dowwntime 1.0.0

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