hot-updater 0.0.1

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