@meg-ai/tunnel-cli 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +4101 -0
  2. package/package.json +57 -0
package/dist/index.js ADDED
@@ -0,0 +1,4101 @@
1
+ #!/usr/bin/env node
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 __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
9
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
10
+ }) : x)(function(x) {
11
+ if (typeof require !== "undefined") return require.apply(this, arguments);
12
+ throw Error('Dynamic require of "' + x + '" is not supported');
13
+ });
14
+ var __commonJS = (cb, mod) => function __require2() {
15
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
16
+ };
17
+ var __copyProps = (to, from, except, desc) => {
18
+ if (from && typeof from === "object" || typeof from === "function") {
19
+ for (let key of __getOwnPropNames(from))
20
+ if (!__hasOwnProp.call(to, key) && key !== except)
21
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
22
+ }
23
+ return to;
24
+ };
25
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
26
+ // If the importer is in node compatibility mode or this is not an ESM
27
+ // file that has been converted to a CommonJS file using a Babel-
28
+ // compatible transform (i.e. "__esModule" has not been set), then set
29
+ // "default" to the CommonJS "module.exports" for node compatibility.
30
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
31
+ mod
32
+ ));
33
+
34
+ // node_modules/commander/lib/error.js
35
+ var require_error = __commonJS({
36
+ "node_modules/commander/lib/error.js"(exports) {
37
+ var CommanderError2 = class extends Error {
38
+ /**
39
+ * Constructs the CommanderError class
40
+ * @param {number} exitCode suggested exit code which could be used with process.exit
41
+ * @param {string} code an id string representing the error
42
+ * @param {string} message human-readable description of the error
43
+ */
44
+ constructor(exitCode, code, message) {
45
+ super(message);
46
+ Error.captureStackTrace(this, this.constructor);
47
+ this.name = this.constructor.name;
48
+ this.code = code;
49
+ this.exitCode = exitCode;
50
+ this.nestedError = void 0;
51
+ }
52
+ };
53
+ var InvalidArgumentError2 = class extends CommanderError2 {
54
+ /**
55
+ * Constructs the InvalidArgumentError class
56
+ * @param {string} [message] explanation of why argument is invalid
57
+ */
58
+ constructor(message) {
59
+ super(1, "commander.invalidArgument", message);
60
+ Error.captureStackTrace(this, this.constructor);
61
+ this.name = this.constructor.name;
62
+ }
63
+ };
64
+ exports.CommanderError = CommanderError2;
65
+ exports.InvalidArgumentError = InvalidArgumentError2;
66
+ }
67
+ });
68
+
69
+ // node_modules/commander/lib/argument.js
70
+ var require_argument = __commonJS({
71
+ "node_modules/commander/lib/argument.js"(exports) {
72
+ var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
73
+ var Argument2 = class {
74
+ /**
75
+ * Initialize a new command argument with the given name and description.
76
+ * The default is that the argument is required, and you can explicitly
77
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
78
+ *
79
+ * @param {string} name
80
+ * @param {string} [description]
81
+ */
82
+ constructor(name, description) {
83
+ this.description = description || "";
84
+ this.variadic = false;
85
+ this.parseArg = void 0;
86
+ this.defaultValue = void 0;
87
+ this.defaultValueDescription = void 0;
88
+ this.argChoices = void 0;
89
+ switch (name[0]) {
90
+ case "<":
91
+ this.required = true;
92
+ this._name = name.slice(1, -1);
93
+ break;
94
+ case "[":
95
+ this.required = false;
96
+ this._name = name.slice(1, -1);
97
+ break;
98
+ default:
99
+ this.required = true;
100
+ this._name = name;
101
+ break;
102
+ }
103
+ if (this._name.length > 3 && this._name.slice(-3) === "...") {
104
+ this.variadic = true;
105
+ this._name = this._name.slice(0, -3);
106
+ }
107
+ }
108
+ /**
109
+ * Return argument name.
110
+ *
111
+ * @return {string}
112
+ */
113
+ name() {
114
+ return this._name;
115
+ }
116
+ /**
117
+ * @package
118
+ */
119
+ _concatValue(value, previous) {
120
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
121
+ return [value];
122
+ }
123
+ return previous.concat(value);
124
+ }
125
+ /**
126
+ * Set the default value, and optionally supply the description to be displayed in the help.
127
+ *
128
+ * @param {*} value
129
+ * @param {string} [description]
130
+ * @return {Argument}
131
+ */
132
+ default(value, description) {
133
+ this.defaultValue = value;
134
+ this.defaultValueDescription = description;
135
+ return this;
136
+ }
137
+ /**
138
+ * Set the custom handler for processing CLI command arguments into argument values.
139
+ *
140
+ * @param {Function} [fn]
141
+ * @return {Argument}
142
+ */
143
+ argParser(fn) {
144
+ this.parseArg = fn;
145
+ return this;
146
+ }
147
+ /**
148
+ * Only allow argument value to be one of choices.
149
+ *
150
+ * @param {string[]} values
151
+ * @return {Argument}
152
+ */
153
+ choices(values) {
154
+ this.argChoices = values.slice();
155
+ this.parseArg = (arg, previous) => {
156
+ if (!this.argChoices.includes(arg)) {
157
+ throw new InvalidArgumentError2(
158
+ `Allowed choices are ${this.argChoices.join(", ")}.`
159
+ );
160
+ }
161
+ if (this.variadic) {
162
+ return this._concatValue(arg, previous);
163
+ }
164
+ return arg;
165
+ };
166
+ return this;
167
+ }
168
+ /**
169
+ * Make argument required.
170
+ *
171
+ * @returns {Argument}
172
+ */
173
+ argRequired() {
174
+ this.required = true;
175
+ return this;
176
+ }
177
+ /**
178
+ * Make argument optional.
179
+ *
180
+ * @returns {Argument}
181
+ */
182
+ argOptional() {
183
+ this.required = false;
184
+ return this;
185
+ }
186
+ };
187
+ function humanReadableArgName(arg) {
188
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
189
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
190
+ }
191
+ exports.Argument = Argument2;
192
+ exports.humanReadableArgName = humanReadableArgName;
193
+ }
194
+ });
195
+
196
+ // node_modules/commander/lib/help.js
197
+ var require_help = __commonJS({
198
+ "node_modules/commander/lib/help.js"(exports) {
199
+ var { humanReadableArgName } = require_argument();
200
+ var Help2 = class {
201
+ constructor() {
202
+ this.helpWidth = void 0;
203
+ this.minWidthToWrap = 40;
204
+ this.sortSubcommands = false;
205
+ this.sortOptions = false;
206
+ this.showGlobalOptions = false;
207
+ }
208
+ /**
209
+ * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
210
+ * and just before calling `formatHelp()`.
211
+ *
212
+ * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
213
+ *
214
+ * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
215
+ */
216
+ prepareContext(contextOptions) {
217
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
218
+ }
219
+ /**
220
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
221
+ *
222
+ * @param {Command} cmd
223
+ * @returns {Command[]}
224
+ */
225
+ visibleCommands(cmd) {
226
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
227
+ const helpCommand = cmd._getHelpCommand();
228
+ if (helpCommand && !helpCommand._hidden) {
229
+ visibleCommands.push(helpCommand);
230
+ }
231
+ if (this.sortSubcommands) {
232
+ visibleCommands.sort((a, b) => {
233
+ return a.name().localeCompare(b.name());
234
+ });
235
+ }
236
+ return visibleCommands;
237
+ }
238
+ /**
239
+ * Compare options for sort.
240
+ *
241
+ * @param {Option} a
242
+ * @param {Option} b
243
+ * @returns {number}
244
+ */
245
+ compareOptions(a, b) {
246
+ const getSortKey = (option) => {
247
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
248
+ };
249
+ return getSortKey(a).localeCompare(getSortKey(b));
250
+ }
251
+ /**
252
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
253
+ *
254
+ * @param {Command} cmd
255
+ * @returns {Option[]}
256
+ */
257
+ visibleOptions(cmd) {
258
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
259
+ const helpOption = cmd._getHelpOption();
260
+ if (helpOption && !helpOption.hidden) {
261
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
262
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
263
+ if (!removeShort && !removeLong) {
264
+ visibleOptions.push(helpOption);
265
+ } else if (helpOption.long && !removeLong) {
266
+ visibleOptions.push(
267
+ cmd.createOption(helpOption.long, helpOption.description)
268
+ );
269
+ } else if (helpOption.short && !removeShort) {
270
+ visibleOptions.push(
271
+ cmd.createOption(helpOption.short, helpOption.description)
272
+ );
273
+ }
274
+ }
275
+ if (this.sortOptions) {
276
+ visibleOptions.sort(this.compareOptions);
277
+ }
278
+ return visibleOptions;
279
+ }
280
+ /**
281
+ * Get an array of the visible global options. (Not including help.)
282
+ *
283
+ * @param {Command} cmd
284
+ * @returns {Option[]}
285
+ */
286
+ visibleGlobalOptions(cmd) {
287
+ if (!this.showGlobalOptions) return [];
288
+ const globalOptions = [];
289
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
290
+ const visibleOptions = ancestorCmd.options.filter(
291
+ (option) => !option.hidden
292
+ );
293
+ globalOptions.push(...visibleOptions);
294
+ }
295
+ if (this.sortOptions) {
296
+ globalOptions.sort(this.compareOptions);
297
+ }
298
+ return globalOptions;
299
+ }
300
+ /**
301
+ * Get an array of the arguments if any have a description.
302
+ *
303
+ * @param {Command} cmd
304
+ * @returns {Argument[]}
305
+ */
306
+ visibleArguments(cmd) {
307
+ if (cmd._argsDescription) {
308
+ cmd.registeredArguments.forEach((argument) => {
309
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
310
+ });
311
+ }
312
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
313
+ return cmd.registeredArguments;
314
+ }
315
+ return [];
316
+ }
317
+ /**
318
+ * Get the command term to show in the list of subcommands.
319
+ *
320
+ * @param {Command} cmd
321
+ * @returns {string}
322
+ */
323
+ subcommandTerm(cmd) {
324
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
325
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
326
+ (args ? " " + args : "");
327
+ }
328
+ /**
329
+ * Get the option term to show in the list of options.
330
+ *
331
+ * @param {Option} option
332
+ * @returns {string}
333
+ */
334
+ optionTerm(option) {
335
+ return option.flags;
336
+ }
337
+ /**
338
+ * Get the argument term to show in the list of arguments.
339
+ *
340
+ * @param {Argument} argument
341
+ * @returns {string}
342
+ */
343
+ argumentTerm(argument) {
344
+ return argument.name();
345
+ }
346
+ /**
347
+ * Get the longest command term length.
348
+ *
349
+ * @param {Command} cmd
350
+ * @param {Help} helper
351
+ * @returns {number}
352
+ */
353
+ longestSubcommandTermLength(cmd, helper) {
354
+ return helper.visibleCommands(cmd).reduce((max, command) => {
355
+ return Math.max(
356
+ max,
357
+ this.displayWidth(
358
+ helper.styleSubcommandTerm(helper.subcommandTerm(command))
359
+ )
360
+ );
361
+ }, 0);
362
+ }
363
+ /**
364
+ * Get the longest option term length.
365
+ *
366
+ * @param {Command} cmd
367
+ * @param {Help} helper
368
+ * @returns {number}
369
+ */
370
+ longestOptionTermLength(cmd, helper) {
371
+ return helper.visibleOptions(cmd).reduce((max, option) => {
372
+ return Math.max(
373
+ max,
374
+ this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
375
+ );
376
+ }, 0);
377
+ }
378
+ /**
379
+ * Get the longest global option term length.
380
+ *
381
+ * @param {Command} cmd
382
+ * @param {Help} helper
383
+ * @returns {number}
384
+ */
385
+ longestGlobalOptionTermLength(cmd, helper) {
386
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
387
+ return Math.max(
388
+ max,
389
+ this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
390
+ );
391
+ }, 0);
392
+ }
393
+ /**
394
+ * Get the longest argument term length.
395
+ *
396
+ * @param {Command} cmd
397
+ * @param {Help} helper
398
+ * @returns {number}
399
+ */
400
+ longestArgumentTermLength(cmd, helper) {
401
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
402
+ return Math.max(
403
+ max,
404
+ this.displayWidth(
405
+ helper.styleArgumentTerm(helper.argumentTerm(argument))
406
+ )
407
+ );
408
+ }, 0);
409
+ }
410
+ /**
411
+ * Get the command usage to be displayed at the top of the built-in help.
412
+ *
413
+ * @param {Command} cmd
414
+ * @returns {string}
415
+ */
416
+ commandUsage(cmd) {
417
+ let cmdName = cmd._name;
418
+ if (cmd._aliases[0]) {
419
+ cmdName = cmdName + "|" + cmd._aliases[0];
420
+ }
421
+ let ancestorCmdNames = "";
422
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
423
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
424
+ }
425
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
426
+ }
427
+ /**
428
+ * Get the description for the command.
429
+ *
430
+ * @param {Command} cmd
431
+ * @returns {string}
432
+ */
433
+ commandDescription(cmd) {
434
+ return cmd.description();
435
+ }
436
+ /**
437
+ * Get the subcommand summary to show in the list of subcommands.
438
+ * (Fallback to description for backwards compatibility.)
439
+ *
440
+ * @param {Command} cmd
441
+ * @returns {string}
442
+ */
443
+ subcommandDescription(cmd) {
444
+ return cmd.summary() || cmd.description();
445
+ }
446
+ /**
447
+ * Get the option description to show in the list of options.
448
+ *
449
+ * @param {Option} option
450
+ * @return {string}
451
+ */
452
+ optionDescription(option) {
453
+ const extraInfo = [];
454
+ if (option.argChoices) {
455
+ extraInfo.push(
456
+ // use stringify to match the display of the default value
457
+ `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
458
+ );
459
+ }
460
+ if (option.defaultValue !== void 0) {
461
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
462
+ if (showDefault) {
463
+ extraInfo.push(
464
+ `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`
465
+ );
466
+ }
467
+ }
468
+ if (option.presetArg !== void 0 && option.optional) {
469
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
470
+ }
471
+ if (option.envVar !== void 0) {
472
+ extraInfo.push(`env: ${option.envVar}`);
473
+ }
474
+ if (extraInfo.length > 0) {
475
+ return `${option.description} (${extraInfo.join(", ")})`;
476
+ }
477
+ return option.description;
478
+ }
479
+ /**
480
+ * Get the argument description to show in the list of arguments.
481
+ *
482
+ * @param {Argument} argument
483
+ * @return {string}
484
+ */
485
+ argumentDescription(argument) {
486
+ const extraInfo = [];
487
+ if (argument.argChoices) {
488
+ extraInfo.push(
489
+ // use stringify to match the display of the default value
490
+ `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
491
+ );
492
+ }
493
+ if (argument.defaultValue !== void 0) {
494
+ extraInfo.push(
495
+ `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`
496
+ );
497
+ }
498
+ if (extraInfo.length > 0) {
499
+ const extraDescription = `(${extraInfo.join(", ")})`;
500
+ if (argument.description) {
501
+ return `${argument.description} ${extraDescription}`;
502
+ }
503
+ return extraDescription;
504
+ }
505
+ return argument.description;
506
+ }
507
+ /**
508
+ * Generate the built-in help text.
509
+ *
510
+ * @param {Command} cmd
511
+ * @param {Help} helper
512
+ * @returns {string}
513
+ */
514
+ formatHelp(cmd, helper) {
515
+ const termWidth = helper.padWidth(cmd, helper);
516
+ const helpWidth = helper.helpWidth ?? 80;
517
+ function callFormatItem(term, description) {
518
+ return helper.formatItem(term, termWidth, description, helper);
519
+ }
520
+ let output = [
521
+ `${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
522
+ ""
523
+ ];
524
+ const commandDescription = helper.commandDescription(cmd);
525
+ if (commandDescription.length > 0) {
526
+ output = output.concat([
527
+ helper.boxWrap(
528
+ helper.styleCommandDescription(commandDescription),
529
+ helpWidth
530
+ ),
531
+ ""
532
+ ]);
533
+ }
534
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
535
+ return callFormatItem(
536
+ helper.styleArgumentTerm(helper.argumentTerm(argument)),
537
+ helper.styleArgumentDescription(helper.argumentDescription(argument))
538
+ );
539
+ });
540
+ if (argumentList.length > 0) {
541
+ output = output.concat([
542
+ helper.styleTitle("Arguments:"),
543
+ ...argumentList,
544
+ ""
545
+ ]);
546
+ }
547
+ const optionList = helper.visibleOptions(cmd).map((option) => {
548
+ return callFormatItem(
549
+ helper.styleOptionTerm(helper.optionTerm(option)),
550
+ helper.styleOptionDescription(helper.optionDescription(option))
551
+ );
552
+ });
553
+ if (optionList.length > 0) {
554
+ output = output.concat([
555
+ helper.styleTitle("Options:"),
556
+ ...optionList,
557
+ ""
558
+ ]);
559
+ }
560
+ if (helper.showGlobalOptions) {
561
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
562
+ return callFormatItem(
563
+ helper.styleOptionTerm(helper.optionTerm(option)),
564
+ helper.styleOptionDescription(helper.optionDescription(option))
565
+ );
566
+ });
567
+ if (globalOptionList.length > 0) {
568
+ output = output.concat([
569
+ helper.styleTitle("Global Options:"),
570
+ ...globalOptionList,
571
+ ""
572
+ ]);
573
+ }
574
+ }
575
+ const commandList = helper.visibleCommands(cmd).map((cmd2) => {
576
+ return callFormatItem(
577
+ helper.styleSubcommandTerm(helper.subcommandTerm(cmd2)),
578
+ helper.styleSubcommandDescription(helper.subcommandDescription(cmd2))
579
+ );
580
+ });
581
+ if (commandList.length > 0) {
582
+ output = output.concat([
583
+ helper.styleTitle("Commands:"),
584
+ ...commandList,
585
+ ""
586
+ ]);
587
+ }
588
+ return output.join("\n");
589
+ }
590
+ /**
591
+ * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
592
+ *
593
+ * @param {string} str
594
+ * @returns {number}
595
+ */
596
+ displayWidth(str) {
597
+ return stripColor(str).length;
598
+ }
599
+ /**
600
+ * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
601
+ *
602
+ * @param {string} str
603
+ * @returns {string}
604
+ */
605
+ styleTitle(str) {
606
+ return str;
607
+ }
608
+ styleUsage(str) {
609
+ return str.split(" ").map((word) => {
610
+ if (word === "[options]") return this.styleOptionText(word);
611
+ if (word === "[command]") return this.styleSubcommandText(word);
612
+ if (word[0] === "[" || word[0] === "<")
613
+ return this.styleArgumentText(word);
614
+ return this.styleCommandText(word);
615
+ }).join(" ");
616
+ }
617
+ styleCommandDescription(str) {
618
+ return this.styleDescriptionText(str);
619
+ }
620
+ styleOptionDescription(str) {
621
+ return this.styleDescriptionText(str);
622
+ }
623
+ styleSubcommandDescription(str) {
624
+ return this.styleDescriptionText(str);
625
+ }
626
+ styleArgumentDescription(str) {
627
+ return this.styleDescriptionText(str);
628
+ }
629
+ styleDescriptionText(str) {
630
+ return str;
631
+ }
632
+ styleOptionTerm(str) {
633
+ return this.styleOptionText(str);
634
+ }
635
+ styleSubcommandTerm(str) {
636
+ return str.split(" ").map((word) => {
637
+ if (word === "[options]") return this.styleOptionText(word);
638
+ if (word[0] === "[" || word[0] === "<")
639
+ return this.styleArgumentText(word);
640
+ return this.styleSubcommandText(word);
641
+ }).join(" ");
642
+ }
643
+ styleArgumentTerm(str) {
644
+ return this.styleArgumentText(str);
645
+ }
646
+ styleOptionText(str) {
647
+ return str;
648
+ }
649
+ styleArgumentText(str) {
650
+ return str;
651
+ }
652
+ styleSubcommandText(str) {
653
+ return str;
654
+ }
655
+ styleCommandText(str) {
656
+ return str;
657
+ }
658
+ /**
659
+ * Calculate the pad width from the maximum term length.
660
+ *
661
+ * @param {Command} cmd
662
+ * @param {Help} helper
663
+ * @returns {number}
664
+ */
665
+ padWidth(cmd, helper) {
666
+ return Math.max(
667
+ helper.longestOptionTermLength(cmd, helper),
668
+ helper.longestGlobalOptionTermLength(cmd, helper),
669
+ helper.longestSubcommandTermLength(cmd, helper),
670
+ helper.longestArgumentTermLength(cmd, helper)
671
+ );
672
+ }
673
+ /**
674
+ * Detect manually wrapped and indented strings by checking for line break followed by whitespace.
675
+ *
676
+ * @param {string} str
677
+ * @returns {boolean}
678
+ */
679
+ preformatted(str) {
680
+ return /\n[^\S\r\n]/.test(str);
681
+ }
682
+ /**
683
+ * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
684
+ *
685
+ * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
686
+ * TTT DDD DDDD
687
+ * DD DDD
688
+ *
689
+ * @param {string} term
690
+ * @param {number} termWidth
691
+ * @param {string} description
692
+ * @param {Help} helper
693
+ * @returns {string}
694
+ */
695
+ formatItem(term, termWidth, description, helper) {
696
+ const itemIndent = 2;
697
+ const itemIndentStr = " ".repeat(itemIndent);
698
+ if (!description) return itemIndentStr + term;
699
+ const paddedTerm = term.padEnd(
700
+ termWidth + term.length - helper.displayWidth(term)
701
+ );
702
+ const spacerWidth = 2;
703
+ const helpWidth = this.helpWidth ?? 80;
704
+ const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
705
+ let formattedDescription;
706
+ if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
707
+ formattedDescription = description;
708
+ } else {
709
+ const wrappedDescription = helper.boxWrap(description, remainingWidth);
710
+ formattedDescription = wrappedDescription.replace(
711
+ /\n/g,
712
+ "\n" + " ".repeat(termWidth + spacerWidth)
713
+ );
714
+ }
715
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
716
+ ${itemIndentStr}`);
717
+ }
718
+ /**
719
+ * Wrap a string at whitespace, preserving existing line breaks.
720
+ * Wrapping is skipped if the width is less than `minWidthToWrap`.
721
+ *
722
+ * @param {string} str
723
+ * @param {number} width
724
+ * @returns {string}
725
+ */
726
+ boxWrap(str, width) {
727
+ if (width < this.minWidthToWrap) return str;
728
+ const rawLines = str.split(/\r\n|\n/);
729
+ const chunkPattern = /[\s]*[^\s]+/g;
730
+ const wrappedLines = [];
731
+ rawLines.forEach((line) => {
732
+ const chunks = line.match(chunkPattern);
733
+ if (chunks === null) {
734
+ wrappedLines.push("");
735
+ return;
736
+ }
737
+ let sumChunks = [chunks.shift()];
738
+ let sumWidth = this.displayWidth(sumChunks[0]);
739
+ chunks.forEach((chunk) => {
740
+ const visibleWidth = this.displayWidth(chunk);
741
+ if (sumWidth + visibleWidth <= width) {
742
+ sumChunks.push(chunk);
743
+ sumWidth += visibleWidth;
744
+ return;
745
+ }
746
+ wrappedLines.push(sumChunks.join(""));
747
+ const nextChunk = chunk.trimStart();
748
+ sumChunks = [nextChunk];
749
+ sumWidth = this.displayWidth(nextChunk);
750
+ });
751
+ wrappedLines.push(sumChunks.join(""));
752
+ });
753
+ return wrappedLines.join("\n");
754
+ }
755
+ };
756
+ function stripColor(str) {
757
+ const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
758
+ return str.replace(sgrPattern, "");
759
+ }
760
+ exports.Help = Help2;
761
+ exports.stripColor = stripColor;
762
+ }
763
+ });
764
+
765
+ // node_modules/commander/lib/option.js
766
+ var require_option = __commonJS({
767
+ "node_modules/commander/lib/option.js"(exports) {
768
+ var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
769
+ var Option2 = class {
770
+ /**
771
+ * Initialize a new `Option` with the given `flags` and `description`.
772
+ *
773
+ * @param {string} flags
774
+ * @param {string} [description]
775
+ */
776
+ constructor(flags, description) {
777
+ this.flags = flags;
778
+ this.description = description || "";
779
+ this.required = flags.includes("<");
780
+ this.optional = flags.includes("[");
781
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
782
+ this.mandatory = false;
783
+ const optionFlags = splitOptionFlags(flags);
784
+ this.short = optionFlags.shortFlag;
785
+ this.long = optionFlags.longFlag;
786
+ this.negate = false;
787
+ if (this.long) {
788
+ this.negate = this.long.startsWith("--no-");
789
+ }
790
+ this.defaultValue = void 0;
791
+ this.defaultValueDescription = void 0;
792
+ this.presetArg = void 0;
793
+ this.envVar = void 0;
794
+ this.parseArg = void 0;
795
+ this.hidden = false;
796
+ this.argChoices = void 0;
797
+ this.conflictsWith = [];
798
+ this.implied = void 0;
799
+ }
800
+ /**
801
+ * Set the default value, and optionally supply the description to be displayed in the help.
802
+ *
803
+ * @param {*} value
804
+ * @param {string} [description]
805
+ * @return {Option}
806
+ */
807
+ default(value, description) {
808
+ this.defaultValue = value;
809
+ this.defaultValueDescription = description;
810
+ return this;
811
+ }
812
+ /**
813
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
814
+ * The custom processing (parseArg) is called.
815
+ *
816
+ * @example
817
+ * new Option('--color').default('GREYSCALE').preset('RGB');
818
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
819
+ *
820
+ * @param {*} arg
821
+ * @return {Option}
822
+ */
823
+ preset(arg) {
824
+ this.presetArg = arg;
825
+ return this;
826
+ }
827
+ /**
828
+ * Add option name(s) that conflict with this option.
829
+ * An error will be displayed if conflicting options are found during parsing.
830
+ *
831
+ * @example
832
+ * new Option('--rgb').conflicts('cmyk');
833
+ * new Option('--js').conflicts(['ts', 'jsx']);
834
+ *
835
+ * @param {(string | string[])} names
836
+ * @return {Option}
837
+ */
838
+ conflicts(names) {
839
+ this.conflictsWith = this.conflictsWith.concat(names);
840
+ return this;
841
+ }
842
+ /**
843
+ * Specify implied option values for when this option is set and the implied options are not.
844
+ *
845
+ * The custom processing (parseArg) is not called on the implied values.
846
+ *
847
+ * @example
848
+ * program
849
+ * .addOption(new Option('--log', 'write logging information to file'))
850
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
851
+ *
852
+ * @param {object} impliedOptionValues
853
+ * @return {Option}
854
+ */
855
+ implies(impliedOptionValues) {
856
+ let newImplied = impliedOptionValues;
857
+ if (typeof impliedOptionValues === "string") {
858
+ newImplied = { [impliedOptionValues]: true };
859
+ }
860
+ this.implied = Object.assign(this.implied || {}, newImplied);
861
+ return this;
862
+ }
863
+ /**
864
+ * Set environment variable to check for option value.
865
+ *
866
+ * An environment variable is only used if when processed the current option value is
867
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
868
+ *
869
+ * @param {string} name
870
+ * @return {Option}
871
+ */
872
+ env(name) {
873
+ this.envVar = name;
874
+ return this;
875
+ }
876
+ /**
877
+ * Set the custom handler for processing CLI option arguments into option values.
878
+ *
879
+ * @param {Function} [fn]
880
+ * @return {Option}
881
+ */
882
+ argParser(fn) {
883
+ this.parseArg = fn;
884
+ return this;
885
+ }
886
+ /**
887
+ * Whether the option is mandatory and must have a value after parsing.
888
+ *
889
+ * @param {boolean} [mandatory=true]
890
+ * @return {Option}
891
+ */
892
+ makeOptionMandatory(mandatory = true) {
893
+ this.mandatory = !!mandatory;
894
+ return this;
895
+ }
896
+ /**
897
+ * Hide option in help.
898
+ *
899
+ * @param {boolean} [hide=true]
900
+ * @return {Option}
901
+ */
902
+ hideHelp(hide = true) {
903
+ this.hidden = !!hide;
904
+ return this;
905
+ }
906
+ /**
907
+ * @package
908
+ */
909
+ _concatValue(value, previous) {
910
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
911
+ return [value];
912
+ }
913
+ return previous.concat(value);
914
+ }
915
+ /**
916
+ * Only allow option value to be one of choices.
917
+ *
918
+ * @param {string[]} values
919
+ * @return {Option}
920
+ */
921
+ choices(values) {
922
+ this.argChoices = values.slice();
923
+ this.parseArg = (arg, previous) => {
924
+ if (!this.argChoices.includes(arg)) {
925
+ throw new InvalidArgumentError2(
926
+ `Allowed choices are ${this.argChoices.join(", ")}.`
927
+ );
928
+ }
929
+ if (this.variadic) {
930
+ return this._concatValue(arg, previous);
931
+ }
932
+ return arg;
933
+ };
934
+ return this;
935
+ }
936
+ /**
937
+ * Return option name.
938
+ *
939
+ * @return {string}
940
+ */
941
+ name() {
942
+ if (this.long) {
943
+ return this.long.replace(/^--/, "");
944
+ }
945
+ return this.short.replace(/^-/, "");
946
+ }
947
+ /**
948
+ * Return option name, in a camelcase format that can be used
949
+ * as an object attribute key.
950
+ *
951
+ * @return {string}
952
+ */
953
+ attributeName() {
954
+ if (this.negate) {
955
+ return camelcase(this.name().replace(/^no-/, ""));
956
+ }
957
+ return camelcase(this.name());
958
+ }
959
+ /**
960
+ * Check if `arg` matches the short or long flag.
961
+ *
962
+ * @param {string} arg
963
+ * @return {boolean}
964
+ * @package
965
+ */
966
+ is(arg) {
967
+ return this.short === arg || this.long === arg;
968
+ }
969
+ /**
970
+ * Return whether a boolean option.
971
+ *
972
+ * Options are one of boolean, negated, required argument, or optional argument.
973
+ *
974
+ * @return {boolean}
975
+ * @package
976
+ */
977
+ isBoolean() {
978
+ return !this.required && !this.optional && !this.negate;
979
+ }
980
+ };
981
+ var DualOptions = class {
982
+ /**
983
+ * @param {Option[]} options
984
+ */
985
+ constructor(options) {
986
+ this.positiveOptions = /* @__PURE__ */ new Map();
987
+ this.negativeOptions = /* @__PURE__ */ new Map();
988
+ this.dualOptions = /* @__PURE__ */ new Set();
989
+ options.forEach((option) => {
990
+ if (option.negate) {
991
+ this.negativeOptions.set(option.attributeName(), option);
992
+ } else {
993
+ this.positiveOptions.set(option.attributeName(), option);
994
+ }
995
+ });
996
+ this.negativeOptions.forEach((value, key) => {
997
+ if (this.positiveOptions.has(key)) {
998
+ this.dualOptions.add(key);
999
+ }
1000
+ });
1001
+ }
1002
+ /**
1003
+ * Did the value come from the option, and not from possible matching dual option?
1004
+ *
1005
+ * @param {*} value
1006
+ * @param {Option} option
1007
+ * @returns {boolean}
1008
+ */
1009
+ valueFromOption(value, option) {
1010
+ const optionKey = option.attributeName();
1011
+ if (!this.dualOptions.has(optionKey)) return true;
1012
+ const preset = this.negativeOptions.get(optionKey).presetArg;
1013
+ const negativeValue = preset !== void 0 ? preset : false;
1014
+ return option.negate === (negativeValue === value);
1015
+ }
1016
+ };
1017
+ function camelcase(str) {
1018
+ return str.split("-").reduce((str2, word) => {
1019
+ return str2 + word[0].toUpperCase() + word.slice(1);
1020
+ });
1021
+ }
1022
+ function splitOptionFlags(flags) {
1023
+ let shortFlag;
1024
+ let longFlag;
1025
+ const shortFlagExp = /^-[^-]$/;
1026
+ const longFlagExp = /^--[^-]/;
1027
+ const flagParts = flags.split(/[ |,]+/).concat("guard");
1028
+ if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
1029
+ if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
1030
+ if (!shortFlag && shortFlagExp.test(flagParts[0]))
1031
+ shortFlag = flagParts.shift();
1032
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
1033
+ shortFlag = longFlag;
1034
+ longFlag = flagParts.shift();
1035
+ }
1036
+ if (flagParts[0].startsWith("-")) {
1037
+ const unsupportedFlag = flagParts[0];
1038
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
1039
+ if (/^-[^-][^-]/.test(unsupportedFlag))
1040
+ throw new Error(
1041
+ `${baseError}
1042
+ - a short flag is a single dash and a single character
1043
+ - either use a single dash and a single character (for a short flag)
1044
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`
1045
+ );
1046
+ if (shortFlagExp.test(unsupportedFlag))
1047
+ throw new Error(`${baseError}
1048
+ - too many short flags`);
1049
+ if (longFlagExp.test(unsupportedFlag))
1050
+ throw new Error(`${baseError}
1051
+ - too many long flags`);
1052
+ throw new Error(`${baseError}
1053
+ - unrecognised flag format`);
1054
+ }
1055
+ if (shortFlag === void 0 && longFlag === void 0)
1056
+ throw new Error(
1057
+ `option creation failed due to no flags found in '${flags}'.`
1058
+ );
1059
+ return { shortFlag, longFlag };
1060
+ }
1061
+ exports.Option = Option2;
1062
+ exports.DualOptions = DualOptions;
1063
+ }
1064
+ });
1065
+
1066
+ // node_modules/commander/lib/suggestSimilar.js
1067
+ var require_suggestSimilar = __commonJS({
1068
+ "node_modules/commander/lib/suggestSimilar.js"(exports) {
1069
+ var maxDistance = 3;
1070
+ function editDistance(a, b) {
1071
+ if (Math.abs(a.length - b.length) > maxDistance)
1072
+ return Math.max(a.length, b.length);
1073
+ const d = [];
1074
+ for (let i = 0; i <= a.length; i++) {
1075
+ d[i] = [i];
1076
+ }
1077
+ for (let j = 0; j <= b.length; j++) {
1078
+ d[0][j] = j;
1079
+ }
1080
+ for (let j = 1; j <= b.length; j++) {
1081
+ for (let i = 1; i <= a.length; i++) {
1082
+ let cost = 1;
1083
+ if (a[i - 1] === b[j - 1]) {
1084
+ cost = 0;
1085
+ } else {
1086
+ cost = 1;
1087
+ }
1088
+ d[i][j] = Math.min(
1089
+ d[i - 1][j] + 1,
1090
+ // deletion
1091
+ d[i][j - 1] + 1,
1092
+ // insertion
1093
+ d[i - 1][j - 1] + cost
1094
+ // substitution
1095
+ );
1096
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
1097
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
1098
+ }
1099
+ }
1100
+ }
1101
+ return d[a.length][b.length];
1102
+ }
1103
+ function suggestSimilar(word, candidates) {
1104
+ if (!candidates || candidates.length === 0) return "";
1105
+ candidates = Array.from(new Set(candidates));
1106
+ const searchingOptions = word.startsWith("--");
1107
+ if (searchingOptions) {
1108
+ word = word.slice(2);
1109
+ candidates = candidates.map((candidate) => candidate.slice(2));
1110
+ }
1111
+ let similar = [];
1112
+ let bestDistance = maxDistance;
1113
+ const minSimilarity = 0.4;
1114
+ candidates.forEach((candidate) => {
1115
+ if (candidate.length <= 1) return;
1116
+ const distance = editDistance(word, candidate);
1117
+ const length = Math.max(word.length, candidate.length);
1118
+ const similarity = (length - distance) / length;
1119
+ if (similarity > minSimilarity) {
1120
+ if (distance < bestDistance) {
1121
+ bestDistance = distance;
1122
+ similar = [candidate];
1123
+ } else if (distance === bestDistance) {
1124
+ similar.push(candidate);
1125
+ }
1126
+ }
1127
+ });
1128
+ similar.sort((a, b) => a.localeCompare(b));
1129
+ if (searchingOptions) {
1130
+ similar = similar.map((candidate) => `--${candidate}`);
1131
+ }
1132
+ if (similar.length > 1) {
1133
+ return `
1134
+ (Did you mean one of ${similar.join(", ")}?)`;
1135
+ }
1136
+ if (similar.length === 1) {
1137
+ return `
1138
+ (Did you mean ${similar[0]}?)`;
1139
+ }
1140
+ return "";
1141
+ }
1142
+ exports.suggestSimilar = suggestSimilar;
1143
+ }
1144
+ });
1145
+
1146
+ // node_modules/commander/lib/command.js
1147
+ var require_command = __commonJS({
1148
+ "node_modules/commander/lib/command.js"(exports) {
1149
+ var EventEmitter = __require("node:events").EventEmitter;
1150
+ var childProcess = __require("node:child_process");
1151
+ var path = __require("node:path");
1152
+ var fs = __require("node:fs");
1153
+ var process3 = __require("node:process");
1154
+ var { Argument: Argument2, humanReadableArgName } = require_argument();
1155
+ var { CommanderError: CommanderError2 } = require_error();
1156
+ var { Help: Help2, stripColor } = require_help();
1157
+ var { Option: Option2, DualOptions } = require_option();
1158
+ var { suggestSimilar } = require_suggestSimilar();
1159
+ var Command2 = class _Command extends EventEmitter {
1160
+ /**
1161
+ * Initialize a new `Command`.
1162
+ *
1163
+ * @param {string} [name]
1164
+ */
1165
+ constructor(name) {
1166
+ super();
1167
+ this.commands = [];
1168
+ this.options = [];
1169
+ this.parent = null;
1170
+ this._allowUnknownOption = false;
1171
+ this._allowExcessArguments = false;
1172
+ this.registeredArguments = [];
1173
+ this._args = this.registeredArguments;
1174
+ this.args = [];
1175
+ this.rawArgs = [];
1176
+ this.processedArgs = [];
1177
+ this._scriptPath = null;
1178
+ this._name = name || "";
1179
+ this._optionValues = {};
1180
+ this._optionValueSources = {};
1181
+ this._storeOptionsAsProperties = false;
1182
+ this._actionHandler = null;
1183
+ this._executableHandler = false;
1184
+ this._executableFile = null;
1185
+ this._executableDir = null;
1186
+ this._defaultCommandName = null;
1187
+ this._exitCallback = null;
1188
+ this._aliases = [];
1189
+ this._combineFlagAndOptionalValue = true;
1190
+ this._description = "";
1191
+ this._summary = "";
1192
+ this._argsDescription = void 0;
1193
+ this._enablePositionalOptions = false;
1194
+ this._passThroughOptions = false;
1195
+ this._lifeCycleHooks = {};
1196
+ this._showHelpAfterError = false;
1197
+ this._showSuggestionAfterError = true;
1198
+ this._savedState = null;
1199
+ this._outputConfiguration = {
1200
+ writeOut: (str) => process3.stdout.write(str),
1201
+ writeErr: (str) => process3.stderr.write(str),
1202
+ outputError: (str, write) => write(str),
1203
+ getOutHelpWidth: () => process3.stdout.isTTY ? process3.stdout.columns : void 0,
1204
+ getErrHelpWidth: () => process3.stderr.isTTY ? process3.stderr.columns : void 0,
1205
+ getOutHasColors: () => useColor() ?? (process3.stdout.isTTY && process3.stdout.hasColors?.()),
1206
+ getErrHasColors: () => useColor() ?? (process3.stderr.isTTY && process3.stderr.hasColors?.()),
1207
+ stripColor: (str) => stripColor(str)
1208
+ };
1209
+ this._hidden = false;
1210
+ this._helpOption = void 0;
1211
+ this._addImplicitHelpCommand = void 0;
1212
+ this._helpCommand = void 0;
1213
+ this._helpConfiguration = {};
1214
+ }
1215
+ /**
1216
+ * Copy settings that are useful to have in common across root command and subcommands.
1217
+ *
1218
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1219
+ *
1220
+ * @param {Command} sourceCommand
1221
+ * @return {Command} `this` command for chaining
1222
+ */
1223
+ copyInheritedSettings(sourceCommand) {
1224
+ this._outputConfiguration = sourceCommand._outputConfiguration;
1225
+ this._helpOption = sourceCommand._helpOption;
1226
+ this._helpCommand = sourceCommand._helpCommand;
1227
+ this._helpConfiguration = sourceCommand._helpConfiguration;
1228
+ this._exitCallback = sourceCommand._exitCallback;
1229
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1230
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1231
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
1232
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1233
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
1234
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1235
+ return this;
1236
+ }
1237
+ /**
1238
+ * @returns {Command[]}
1239
+ * @private
1240
+ */
1241
+ _getCommandAndAncestors() {
1242
+ const result = [];
1243
+ for (let command = this; command; command = command.parent) {
1244
+ result.push(command);
1245
+ }
1246
+ return result;
1247
+ }
1248
+ /**
1249
+ * Define a command.
1250
+ *
1251
+ * There are two styles of command: pay attention to where to put the description.
1252
+ *
1253
+ * @example
1254
+ * // Command implemented using action handler (description is supplied separately to `.command`)
1255
+ * program
1256
+ * .command('clone <source> [destination]')
1257
+ * .description('clone a repository into a newly created directory')
1258
+ * .action((source, destination) => {
1259
+ * console.log('clone command called');
1260
+ * });
1261
+ *
1262
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
1263
+ * program
1264
+ * .command('start <service>', 'start named service')
1265
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
1266
+ *
1267
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1268
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1269
+ * @param {object} [execOpts] - configuration options (for executable)
1270
+ * @return {Command} returns new command for action handler, or `this` for executable command
1271
+ */
1272
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1273
+ let desc = actionOptsOrExecDesc;
1274
+ let opts = execOpts;
1275
+ if (typeof desc === "object" && desc !== null) {
1276
+ opts = desc;
1277
+ desc = null;
1278
+ }
1279
+ opts = opts || {};
1280
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1281
+ const cmd = this.createCommand(name);
1282
+ if (desc) {
1283
+ cmd.description(desc);
1284
+ cmd._executableHandler = true;
1285
+ }
1286
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1287
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
1288
+ cmd._executableFile = opts.executableFile || null;
1289
+ if (args) cmd.arguments(args);
1290
+ this._registerCommand(cmd);
1291
+ cmd.parent = this;
1292
+ cmd.copyInheritedSettings(this);
1293
+ if (desc) return this;
1294
+ return cmd;
1295
+ }
1296
+ /**
1297
+ * Factory routine to create a new unattached command.
1298
+ *
1299
+ * See .command() for creating an attached subcommand, which uses this routine to
1300
+ * create the command. You can override createCommand to customise subcommands.
1301
+ *
1302
+ * @param {string} [name]
1303
+ * @return {Command} new command
1304
+ */
1305
+ createCommand(name) {
1306
+ return new _Command(name);
1307
+ }
1308
+ /**
1309
+ * You can customise the help with a subclass of Help by overriding createHelp,
1310
+ * or by overriding Help properties using configureHelp().
1311
+ *
1312
+ * @return {Help}
1313
+ */
1314
+ createHelp() {
1315
+ return Object.assign(new Help2(), this.configureHelp());
1316
+ }
1317
+ /**
1318
+ * You can customise the help by overriding Help properties using configureHelp(),
1319
+ * or with a subclass of Help by overriding createHelp().
1320
+ *
1321
+ * @param {object} [configuration] - configuration options
1322
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1323
+ */
1324
+ configureHelp(configuration) {
1325
+ if (configuration === void 0) return this._helpConfiguration;
1326
+ this._helpConfiguration = configuration;
1327
+ return this;
1328
+ }
1329
+ /**
1330
+ * The default output goes to stdout and stderr. You can customise this for special
1331
+ * applications. You can also customise the display of errors by overriding outputError.
1332
+ *
1333
+ * The configuration properties are all functions:
1334
+ *
1335
+ * // change how output being written, defaults to stdout and stderr
1336
+ * writeOut(str)
1337
+ * writeErr(str)
1338
+ * // change how output being written for errors, defaults to writeErr
1339
+ * outputError(str, write) // used for displaying errors and not used for displaying help
1340
+ * // specify width for wrapping help
1341
+ * getOutHelpWidth()
1342
+ * getErrHelpWidth()
1343
+ * // color support, currently only used with Help
1344
+ * getOutHasColors()
1345
+ * getErrHasColors()
1346
+ * stripColor() // used to remove ANSI escape codes if output does not have colors
1347
+ *
1348
+ * @param {object} [configuration] - configuration options
1349
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1350
+ */
1351
+ configureOutput(configuration) {
1352
+ if (configuration === void 0) return this._outputConfiguration;
1353
+ Object.assign(this._outputConfiguration, configuration);
1354
+ return this;
1355
+ }
1356
+ /**
1357
+ * Display the help or a custom message after an error occurs.
1358
+ *
1359
+ * @param {(boolean|string)} [displayHelp]
1360
+ * @return {Command} `this` command for chaining
1361
+ */
1362
+ showHelpAfterError(displayHelp = true) {
1363
+ if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
1364
+ this._showHelpAfterError = displayHelp;
1365
+ return this;
1366
+ }
1367
+ /**
1368
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
1369
+ *
1370
+ * @param {boolean} [displaySuggestion]
1371
+ * @return {Command} `this` command for chaining
1372
+ */
1373
+ showSuggestionAfterError(displaySuggestion = true) {
1374
+ this._showSuggestionAfterError = !!displaySuggestion;
1375
+ return this;
1376
+ }
1377
+ /**
1378
+ * Add a prepared subcommand.
1379
+ *
1380
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
1381
+ *
1382
+ * @param {Command} cmd - new subcommand
1383
+ * @param {object} [opts] - configuration options
1384
+ * @return {Command} `this` command for chaining
1385
+ */
1386
+ addCommand(cmd, opts) {
1387
+ if (!cmd._name) {
1388
+ throw new Error(`Command passed to .addCommand() must have a name
1389
+ - specify the name in Command constructor or using .name()`);
1390
+ }
1391
+ opts = opts || {};
1392
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1393
+ if (opts.noHelp || opts.hidden) cmd._hidden = true;
1394
+ this._registerCommand(cmd);
1395
+ cmd.parent = this;
1396
+ cmd._checkForBrokenPassThrough();
1397
+ return this;
1398
+ }
1399
+ /**
1400
+ * Factory routine to create a new unattached argument.
1401
+ *
1402
+ * See .argument() for creating an attached argument, which uses this routine to
1403
+ * create the argument. You can override createArgument to return a custom argument.
1404
+ *
1405
+ * @param {string} name
1406
+ * @param {string} [description]
1407
+ * @return {Argument} new argument
1408
+ */
1409
+ createArgument(name, description) {
1410
+ return new Argument2(name, description);
1411
+ }
1412
+ /**
1413
+ * Define argument syntax for command.
1414
+ *
1415
+ * The default is that the argument is required, and you can explicitly
1416
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
1417
+ *
1418
+ * @example
1419
+ * program.argument('<input-file>');
1420
+ * program.argument('[output-file]');
1421
+ *
1422
+ * @param {string} name
1423
+ * @param {string} [description]
1424
+ * @param {(Function|*)} [fn] - custom argument processing function
1425
+ * @param {*} [defaultValue]
1426
+ * @return {Command} `this` command for chaining
1427
+ */
1428
+ argument(name, description, fn, defaultValue) {
1429
+ const argument = this.createArgument(name, description);
1430
+ if (typeof fn === "function") {
1431
+ argument.default(defaultValue).argParser(fn);
1432
+ } else {
1433
+ argument.default(fn);
1434
+ }
1435
+ this.addArgument(argument);
1436
+ return this;
1437
+ }
1438
+ /**
1439
+ * Define argument syntax for command, adding multiple at once (without descriptions).
1440
+ *
1441
+ * See also .argument().
1442
+ *
1443
+ * @example
1444
+ * program.arguments('<cmd> [env]');
1445
+ *
1446
+ * @param {string} names
1447
+ * @return {Command} `this` command for chaining
1448
+ */
1449
+ arguments(names) {
1450
+ names.trim().split(/ +/).forEach((detail) => {
1451
+ this.argument(detail);
1452
+ });
1453
+ return this;
1454
+ }
1455
+ /**
1456
+ * Define argument syntax for command, adding a prepared argument.
1457
+ *
1458
+ * @param {Argument} argument
1459
+ * @return {Command} `this` command for chaining
1460
+ */
1461
+ addArgument(argument) {
1462
+ const previousArgument = this.registeredArguments.slice(-1)[0];
1463
+ if (previousArgument && previousArgument.variadic) {
1464
+ throw new Error(
1465
+ `only the last argument can be variadic '${previousArgument.name()}'`
1466
+ );
1467
+ }
1468
+ if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
1469
+ throw new Error(
1470
+ `a default value for a required argument is never used: '${argument.name()}'`
1471
+ );
1472
+ }
1473
+ this.registeredArguments.push(argument);
1474
+ return this;
1475
+ }
1476
+ /**
1477
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
1478
+ *
1479
+ * @example
1480
+ * program.helpCommand('help [cmd]');
1481
+ * program.helpCommand('help [cmd]', 'show help');
1482
+ * program.helpCommand(false); // suppress default help command
1483
+ * program.helpCommand(true); // add help command even if no subcommands
1484
+ *
1485
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
1486
+ * @param {string} [description] - custom description
1487
+ * @return {Command} `this` command for chaining
1488
+ */
1489
+ helpCommand(enableOrNameAndArgs, description) {
1490
+ if (typeof enableOrNameAndArgs === "boolean") {
1491
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
1492
+ return this;
1493
+ }
1494
+ enableOrNameAndArgs = enableOrNameAndArgs ?? "help [command]";
1495
+ const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);
1496
+ const helpDescription = description ?? "display help for command";
1497
+ const helpCommand = this.createCommand(helpName);
1498
+ helpCommand.helpOption(false);
1499
+ if (helpArgs) helpCommand.arguments(helpArgs);
1500
+ if (helpDescription) helpCommand.description(helpDescription);
1501
+ this._addImplicitHelpCommand = true;
1502
+ this._helpCommand = helpCommand;
1503
+ return this;
1504
+ }
1505
+ /**
1506
+ * Add prepared custom help command.
1507
+ *
1508
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
1509
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
1510
+ * @return {Command} `this` command for chaining
1511
+ */
1512
+ addHelpCommand(helpCommand, deprecatedDescription) {
1513
+ if (typeof helpCommand !== "object") {
1514
+ this.helpCommand(helpCommand, deprecatedDescription);
1515
+ return this;
1516
+ }
1517
+ this._addImplicitHelpCommand = true;
1518
+ this._helpCommand = helpCommand;
1519
+ return this;
1520
+ }
1521
+ /**
1522
+ * Lazy create help command.
1523
+ *
1524
+ * @return {(Command|null)}
1525
+ * @package
1526
+ */
1527
+ _getHelpCommand() {
1528
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
1529
+ if (hasImplicitHelpCommand) {
1530
+ if (this._helpCommand === void 0) {
1531
+ this.helpCommand(void 0, void 0);
1532
+ }
1533
+ return this._helpCommand;
1534
+ }
1535
+ return null;
1536
+ }
1537
+ /**
1538
+ * Add hook for life cycle event.
1539
+ *
1540
+ * @param {string} event
1541
+ * @param {Function} listener
1542
+ * @return {Command} `this` command for chaining
1543
+ */
1544
+ hook(event, listener) {
1545
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
1546
+ if (!allowedValues.includes(event)) {
1547
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
1548
+ Expecting one of '${allowedValues.join("', '")}'`);
1549
+ }
1550
+ if (this._lifeCycleHooks[event]) {
1551
+ this._lifeCycleHooks[event].push(listener);
1552
+ } else {
1553
+ this._lifeCycleHooks[event] = [listener];
1554
+ }
1555
+ return this;
1556
+ }
1557
+ /**
1558
+ * Register callback to use as replacement for calling process.exit.
1559
+ *
1560
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
1561
+ * @return {Command} `this` command for chaining
1562
+ */
1563
+ exitOverride(fn) {
1564
+ if (fn) {
1565
+ this._exitCallback = fn;
1566
+ } else {
1567
+ this._exitCallback = (err) => {
1568
+ if (err.code !== "commander.executeSubCommandAsync") {
1569
+ throw err;
1570
+ } else {
1571
+ }
1572
+ };
1573
+ }
1574
+ return this;
1575
+ }
1576
+ /**
1577
+ * Call process.exit, and _exitCallback if defined.
1578
+ *
1579
+ * @param {number} exitCode exit code for using with process.exit
1580
+ * @param {string} code an id string representing the error
1581
+ * @param {string} message human-readable description of the error
1582
+ * @return never
1583
+ * @private
1584
+ */
1585
+ _exit(exitCode, code, message) {
1586
+ if (this._exitCallback) {
1587
+ this._exitCallback(new CommanderError2(exitCode, code, message));
1588
+ }
1589
+ process3.exit(exitCode);
1590
+ }
1591
+ /**
1592
+ * Register callback `fn` for the command.
1593
+ *
1594
+ * @example
1595
+ * program
1596
+ * .command('serve')
1597
+ * .description('start service')
1598
+ * .action(function() {
1599
+ * // do work here
1600
+ * });
1601
+ *
1602
+ * @param {Function} fn
1603
+ * @return {Command} `this` command for chaining
1604
+ */
1605
+ action(fn) {
1606
+ const listener = (args) => {
1607
+ const expectedArgsCount = this.registeredArguments.length;
1608
+ const actionArgs = args.slice(0, expectedArgsCount);
1609
+ if (this._storeOptionsAsProperties) {
1610
+ actionArgs[expectedArgsCount] = this;
1611
+ } else {
1612
+ actionArgs[expectedArgsCount] = this.opts();
1613
+ }
1614
+ actionArgs.push(this);
1615
+ return fn.apply(this, actionArgs);
1616
+ };
1617
+ this._actionHandler = listener;
1618
+ return this;
1619
+ }
1620
+ /**
1621
+ * Factory routine to create a new unattached option.
1622
+ *
1623
+ * See .option() for creating an attached option, which uses this routine to
1624
+ * create the option. You can override createOption to return a custom option.
1625
+ *
1626
+ * @param {string} flags
1627
+ * @param {string} [description]
1628
+ * @return {Option} new option
1629
+ */
1630
+ createOption(flags, description) {
1631
+ return new Option2(flags, description);
1632
+ }
1633
+ /**
1634
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
1635
+ *
1636
+ * @param {(Option | Argument)} target
1637
+ * @param {string} value
1638
+ * @param {*} previous
1639
+ * @param {string} invalidArgumentMessage
1640
+ * @private
1641
+ */
1642
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
1643
+ try {
1644
+ return target.parseArg(value, previous);
1645
+ } catch (err) {
1646
+ if (err.code === "commander.invalidArgument") {
1647
+ const message = `${invalidArgumentMessage} ${err.message}`;
1648
+ this.error(message, { exitCode: err.exitCode, code: err.code });
1649
+ }
1650
+ throw err;
1651
+ }
1652
+ }
1653
+ /**
1654
+ * Check for option flag conflicts.
1655
+ * Register option if no conflicts found, or throw on conflict.
1656
+ *
1657
+ * @param {Option} option
1658
+ * @private
1659
+ */
1660
+ _registerOption(option) {
1661
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1662
+ if (matchingOption) {
1663
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1664
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1665
+ - already used by option '${matchingOption.flags}'`);
1666
+ }
1667
+ this.options.push(option);
1668
+ }
1669
+ /**
1670
+ * Check for command name and alias conflicts with existing commands.
1671
+ * Register command if no conflicts found, or throw on conflict.
1672
+ *
1673
+ * @param {Command} command
1674
+ * @private
1675
+ */
1676
+ _registerCommand(command) {
1677
+ const knownBy = (cmd) => {
1678
+ return [cmd.name()].concat(cmd.aliases());
1679
+ };
1680
+ const alreadyUsed = knownBy(command).find(
1681
+ (name) => this._findCommand(name)
1682
+ );
1683
+ if (alreadyUsed) {
1684
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1685
+ const newCmd = knownBy(command).join("|");
1686
+ throw new Error(
1687
+ `cannot add command '${newCmd}' as already have command '${existingCmd}'`
1688
+ );
1689
+ }
1690
+ this.commands.push(command);
1691
+ }
1692
+ /**
1693
+ * Add an option.
1694
+ *
1695
+ * @param {Option} option
1696
+ * @return {Command} `this` command for chaining
1697
+ */
1698
+ addOption(option) {
1699
+ this._registerOption(option);
1700
+ const oname = option.name();
1701
+ const name = option.attributeName();
1702
+ if (option.negate) {
1703
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1704
+ if (!this._findOption(positiveLongFlag)) {
1705
+ this.setOptionValueWithSource(
1706
+ name,
1707
+ option.defaultValue === void 0 ? true : option.defaultValue,
1708
+ "default"
1709
+ );
1710
+ }
1711
+ } else if (option.defaultValue !== void 0) {
1712
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
1713
+ }
1714
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1715
+ if (val == null && option.presetArg !== void 0) {
1716
+ val = option.presetArg;
1717
+ }
1718
+ const oldValue = this.getOptionValue(name);
1719
+ if (val !== null && option.parseArg) {
1720
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1721
+ } else if (val !== null && option.variadic) {
1722
+ val = option._concatValue(val, oldValue);
1723
+ }
1724
+ if (val == null) {
1725
+ if (option.negate) {
1726
+ val = false;
1727
+ } else if (option.isBoolean() || option.optional) {
1728
+ val = true;
1729
+ } else {
1730
+ val = "";
1731
+ }
1732
+ }
1733
+ this.setOptionValueWithSource(name, val, valueSource);
1734
+ };
1735
+ this.on("option:" + oname, (val) => {
1736
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1737
+ handleOptionValue(val, invalidValueMessage, "cli");
1738
+ });
1739
+ if (option.envVar) {
1740
+ this.on("optionEnv:" + oname, (val) => {
1741
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1742
+ handleOptionValue(val, invalidValueMessage, "env");
1743
+ });
1744
+ }
1745
+ return this;
1746
+ }
1747
+ /**
1748
+ * Internal implementation shared by .option() and .requiredOption()
1749
+ *
1750
+ * @return {Command} `this` command for chaining
1751
+ * @private
1752
+ */
1753
+ _optionEx(config, flags, description, fn, defaultValue) {
1754
+ if (typeof flags === "object" && flags instanceof Option2) {
1755
+ throw new Error(
1756
+ "To add an Option object use addOption() instead of option() or requiredOption()"
1757
+ );
1758
+ }
1759
+ const option = this.createOption(flags, description);
1760
+ option.makeOptionMandatory(!!config.mandatory);
1761
+ if (typeof fn === "function") {
1762
+ option.default(defaultValue).argParser(fn);
1763
+ } else if (fn instanceof RegExp) {
1764
+ const regex = fn;
1765
+ fn = (val, def) => {
1766
+ const m = regex.exec(val);
1767
+ return m ? m[0] : def;
1768
+ };
1769
+ option.default(defaultValue).argParser(fn);
1770
+ } else {
1771
+ option.default(fn);
1772
+ }
1773
+ return this.addOption(option);
1774
+ }
1775
+ /**
1776
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
1777
+ *
1778
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
1779
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
1780
+ *
1781
+ * See the README for more details, and see also addOption() and requiredOption().
1782
+ *
1783
+ * @example
1784
+ * program
1785
+ * .option('-p, --pepper', 'add pepper')
1786
+ * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
1787
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
1788
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
1789
+ *
1790
+ * @param {string} flags
1791
+ * @param {string} [description]
1792
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1793
+ * @param {*} [defaultValue]
1794
+ * @return {Command} `this` command for chaining
1795
+ */
1796
+ option(flags, description, parseArg, defaultValue) {
1797
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1798
+ }
1799
+ /**
1800
+ * Add a required option which must have a value after parsing. This usually means
1801
+ * the option must be specified on the command line. (Otherwise the same as .option().)
1802
+ *
1803
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1804
+ *
1805
+ * @param {string} flags
1806
+ * @param {string} [description]
1807
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1808
+ * @param {*} [defaultValue]
1809
+ * @return {Command} `this` command for chaining
1810
+ */
1811
+ requiredOption(flags, description, parseArg, defaultValue) {
1812
+ return this._optionEx(
1813
+ { mandatory: true },
1814
+ flags,
1815
+ description,
1816
+ parseArg,
1817
+ defaultValue
1818
+ );
1819
+ }
1820
+ /**
1821
+ * Alter parsing of short flags with optional values.
1822
+ *
1823
+ * @example
1824
+ * // for `.option('-f,--flag [value]'):
1825
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
1826
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
1827
+ *
1828
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
1829
+ * @return {Command} `this` command for chaining
1830
+ */
1831
+ combineFlagAndOptionalValue(combine = true) {
1832
+ this._combineFlagAndOptionalValue = !!combine;
1833
+ return this;
1834
+ }
1835
+ /**
1836
+ * Allow unknown options on the command line.
1837
+ *
1838
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
1839
+ * @return {Command} `this` command for chaining
1840
+ */
1841
+ allowUnknownOption(allowUnknown = true) {
1842
+ this._allowUnknownOption = !!allowUnknown;
1843
+ return this;
1844
+ }
1845
+ /**
1846
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1847
+ *
1848
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
1849
+ * @return {Command} `this` command for chaining
1850
+ */
1851
+ allowExcessArguments(allowExcess = true) {
1852
+ this._allowExcessArguments = !!allowExcess;
1853
+ return this;
1854
+ }
1855
+ /**
1856
+ * Enable positional options. Positional means global options are specified before subcommands which lets
1857
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1858
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
1859
+ *
1860
+ * @param {boolean} [positional]
1861
+ * @return {Command} `this` command for chaining
1862
+ */
1863
+ enablePositionalOptions(positional = true) {
1864
+ this._enablePositionalOptions = !!positional;
1865
+ return this;
1866
+ }
1867
+ /**
1868
+ * Pass through options that come after command-arguments rather than treat them as command-options,
1869
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
1870
+ * positional options to have been enabled on the program (parent commands).
1871
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
1872
+ *
1873
+ * @param {boolean} [passThrough] for unknown options.
1874
+ * @return {Command} `this` command for chaining
1875
+ */
1876
+ passThroughOptions(passThrough = true) {
1877
+ this._passThroughOptions = !!passThrough;
1878
+ this._checkForBrokenPassThrough();
1879
+ return this;
1880
+ }
1881
+ /**
1882
+ * @private
1883
+ */
1884
+ _checkForBrokenPassThrough() {
1885
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
1886
+ throw new Error(
1887
+ `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`
1888
+ );
1889
+ }
1890
+ }
1891
+ /**
1892
+ * Whether to store option values as properties on command object,
1893
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
1894
+ *
1895
+ * @param {boolean} [storeAsProperties=true]
1896
+ * @return {Command} `this` command for chaining
1897
+ */
1898
+ storeOptionsAsProperties(storeAsProperties = true) {
1899
+ if (this.options.length) {
1900
+ throw new Error("call .storeOptionsAsProperties() before adding options");
1901
+ }
1902
+ if (Object.keys(this._optionValues).length) {
1903
+ throw new Error(
1904
+ "call .storeOptionsAsProperties() before setting option values"
1905
+ );
1906
+ }
1907
+ this._storeOptionsAsProperties = !!storeAsProperties;
1908
+ return this;
1909
+ }
1910
+ /**
1911
+ * Retrieve option value.
1912
+ *
1913
+ * @param {string} key
1914
+ * @return {object} value
1915
+ */
1916
+ getOptionValue(key) {
1917
+ if (this._storeOptionsAsProperties) {
1918
+ return this[key];
1919
+ }
1920
+ return this._optionValues[key];
1921
+ }
1922
+ /**
1923
+ * Store option value.
1924
+ *
1925
+ * @param {string} key
1926
+ * @param {object} value
1927
+ * @return {Command} `this` command for chaining
1928
+ */
1929
+ setOptionValue(key, value) {
1930
+ return this.setOptionValueWithSource(key, value, void 0);
1931
+ }
1932
+ /**
1933
+ * Store option value and where the value came from.
1934
+ *
1935
+ * @param {string} key
1936
+ * @param {object} value
1937
+ * @param {string} source - expected values are default/config/env/cli/implied
1938
+ * @return {Command} `this` command for chaining
1939
+ */
1940
+ setOptionValueWithSource(key, value, source) {
1941
+ if (this._storeOptionsAsProperties) {
1942
+ this[key] = value;
1943
+ } else {
1944
+ this._optionValues[key] = value;
1945
+ }
1946
+ this._optionValueSources[key] = source;
1947
+ return this;
1948
+ }
1949
+ /**
1950
+ * Get source of option value.
1951
+ * Expected values are default | config | env | cli | implied
1952
+ *
1953
+ * @param {string} key
1954
+ * @return {string}
1955
+ */
1956
+ getOptionValueSource(key) {
1957
+ return this._optionValueSources[key];
1958
+ }
1959
+ /**
1960
+ * Get source of option value. See also .optsWithGlobals().
1961
+ * Expected values are default | config | env | cli | implied
1962
+ *
1963
+ * @param {string} key
1964
+ * @return {string}
1965
+ */
1966
+ getOptionValueSourceWithGlobals(key) {
1967
+ let source;
1968
+ this._getCommandAndAncestors().forEach((cmd) => {
1969
+ if (cmd.getOptionValueSource(key) !== void 0) {
1970
+ source = cmd.getOptionValueSource(key);
1971
+ }
1972
+ });
1973
+ return source;
1974
+ }
1975
+ /**
1976
+ * Get user arguments from implied or explicit arguments.
1977
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
1978
+ *
1979
+ * @private
1980
+ */
1981
+ _prepareUserArgs(argv, parseOptions) {
1982
+ if (argv !== void 0 && !Array.isArray(argv)) {
1983
+ throw new Error("first parameter to parse must be array or undefined");
1984
+ }
1985
+ parseOptions = parseOptions || {};
1986
+ if (argv === void 0 && parseOptions.from === void 0) {
1987
+ if (process3.versions?.electron) {
1988
+ parseOptions.from = "electron";
1989
+ }
1990
+ const execArgv = process3.execArgv ?? [];
1991
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
1992
+ parseOptions.from = "eval";
1993
+ }
1994
+ }
1995
+ if (argv === void 0) {
1996
+ argv = process3.argv;
1997
+ }
1998
+ this.rawArgs = argv.slice();
1999
+ let userArgs;
2000
+ switch (parseOptions.from) {
2001
+ case void 0:
2002
+ case "node":
2003
+ this._scriptPath = argv[1];
2004
+ userArgs = argv.slice(2);
2005
+ break;
2006
+ case "electron":
2007
+ if (process3.defaultApp) {
2008
+ this._scriptPath = argv[1];
2009
+ userArgs = argv.slice(2);
2010
+ } else {
2011
+ userArgs = argv.slice(1);
2012
+ }
2013
+ break;
2014
+ case "user":
2015
+ userArgs = argv.slice(0);
2016
+ break;
2017
+ case "eval":
2018
+ userArgs = argv.slice(1);
2019
+ break;
2020
+ default:
2021
+ throw new Error(
2022
+ `unexpected parse option { from: '${parseOptions.from}' }`
2023
+ );
2024
+ }
2025
+ if (!this._name && this._scriptPath)
2026
+ this.nameFromFilename(this._scriptPath);
2027
+ this._name = this._name || "program";
2028
+ return userArgs;
2029
+ }
2030
+ /**
2031
+ * Parse `argv`, setting options and invoking commands when defined.
2032
+ *
2033
+ * Use parseAsync instead of parse if any of your action handlers are async.
2034
+ *
2035
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
2036
+ *
2037
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
2038
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
2039
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
2040
+ * - `'user'`: just user arguments
2041
+ *
2042
+ * @example
2043
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
2044
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
2045
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2046
+ *
2047
+ * @param {string[]} [argv] - optional, defaults to process.argv
2048
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
2049
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
2050
+ * @return {Command} `this` command for chaining
2051
+ */
2052
+ parse(argv, parseOptions) {
2053
+ this._prepareForParse();
2054
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
2055
+ this._parseCommand([], userArgs);
2056
+ return this;
2057
+ }
2058
+ /**
2059
+ * Parse `argv`, setting options and invoking commands when defined.
2060
+ *
2061
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
2062
+ *
2063
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
2064
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
2065
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
2066
+ * - `'user'`: just user arguments
2067
+ *
2068
+ * @example
2069
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
2070
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
2071
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2072
+ *
2073
+ * @param {string[]} [argv]
2074
+ * @param {object} [parseOptions]
2075
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
2076
+ * @return {Promise}
2077
+ */
2078
+ async parseAsync(argv, parseOptions) {
2079
+ this._prepareForParse();
2080
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
2081
+ await this._parseCommand([], userArgs);
2082
+ return this;
2083
+ }
2084
+ _prepareForParse() {
2085
+ if (this._savedState === null) {
2086
+ this.saveStateBeforeParse();
2087
+ } else {
2088
+ this.restoreStateBeforeParse();
2089
+ }
2090
+ }
2091
+ /**
2092
+ * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
2093
+ * Not usually called directly, but available for subclasses to save their custom state.
2094
+ *
2095
+ * This is called in a lazy way. Only commands used in parsing chain will have state saved.
2096
+ */
2097
+ saveStateBeforeParse() {
2098
+ this._savedState = {
2099
+ // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing
2100
+ _name: this._name,
2101
+ // option values before parse have default values (including false for negated options)
2102
+ // shallow clones
2103
+ _optionValues: { ...this._optionValues },
2104
+ _optionValueSources: { ...this._optionValueSources }
2105
+ };
2106
+ }
2107
+ /**
2108
+ * Restore state before parse for calls after the first.
2109
+ * Not usually called directly, but available for subclasses to save their custom state.
2110
+ *
2111
+ * This is called in a lazy way. Only commands used in parsing chain will have state restored.
2112
+ */
2113
+ restoreStateBeforeParse() {
2114
+ if (this._storeOptionsAsProperties)
2115
+ throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
2116
+ - either make a new Command for each call to parse, or stop storing options as properties`);
2117
+ this._name = this._savedState._name;
2118
+ this._scriptPath = null;
2119
+ this.rawArgs = [];
2120
+ this._optionValues = { ...this._savedState._optionValues };
2121
+ this._optionValueSources = { ...this._savedState._optionValueSources };
2122
+ this.args = [];
2123
+ this.processedArgs = [];
2124
+ }
2125
+ /**
2126
+ * Throw if expected executable is missing. Add lots of help for author.
2127
+ *
2128
+ * @param {string} executableFile
2129
+ * @param {string} executableDir
2130
+ * @param {string} subcommandName
2131
+ */
2132
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
2133
+ if (fs.existsSync(executableFile)) return;
2134
+ 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";
2135
+ const executableMissing = `'${executableFile}' does not exist
2136
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
2137
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
2138
+ - ${executableDirMessage}`;
2139
+ throw new Error(executableMissing);
2140
+ }
2141
+ /**
2142
+ * Execute a sub-command executable.
2143
+ *
2144
+ * @private
2145
+ */
2146
+ _executeSubCommand(subcommand, args) {
2147
+ args = args.slice();
2148
+ let launchWithNode = false;
2149
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
2150
+ function findFile(baseDir, baseName) {
2151
+ const localBin = path.resolve(baseDir, baseName);
2152
+ if (fs.existsSync(localBin)) return localBin;
2153
+ if (sourceExt.includes(path.extname(baseName))) return void 0;
2154
+ const foundExt = sourceExt.find(
2155
+ (ext) => fs.existsSync(`${localBin}${ext}`)
2156
+ );
2157
+ if (foundExt) return `${localBin}${foundExt}`;
2158
+ return void 0;
2159
+ }
2160
+ this._checkForMissingMandatoryOptions();
2161
+ this._checkForConflictingOptions();
2162
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
2163
+ let executableDir = this._executableDir || "";
2164
+ if (this._scriptPath) {
2165
+ let resolvedScriptPath;
2166
+ try {
2167
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
2168
+ } catch {
2169
+ resolvedScriptPath = this._scriptPath;
2170
+ }
2171
+ executableDir = path.resolve(
2172
+ path.dirname(resolvedScriptPath),
2173
+ executableDir
2174
+ );
2175
+ }
2176
+ if (executableDir) {
2177
+ let localFile = findFile(executableDir, executableFile);
2178
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
2179
+ const legacyName = path.basename(
2180
+ this._scriptPath,
2181
+ path.extname(this._scriptPath)
2182
+ );
2183
+ if (legacyName !== this._name) {
2184
+ localFile = findFile(
2185
+ executableDir,
2186
+ `${legacyName}-${subcommand._name}`
2187
+ );
2188
+ }
2189
+ }
2190
+ executableFile = localFile || executableFile;
2191
+ }
2192
+ launchWithNode = sourceExt.includes(path.extname(executableFile));
2193
+ let proc;
2194
+ if (process3.platform !== "win32") {
2195
+ if (launchWithNode) {
2196
+ args.unshift(executableFile);
2197
+ args = incrementNodeInspectorPort(process3.execArgv).concat(args);
2198
+ proc = childProcess.spawn(process3.argv[0], args, { stdio: "inherit" });
2199
+ } else {
2200
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
2201
+ }
2202
+ } else {
2203
+ this._checkForMissingExecutable(
2204
+ executableFile,
2205
+ executableDir,
2206
+ subcommand._name
2207
+ );
2208
+ args.unshift(executableFile);
2209
+ args = incrementNodeInspectorPort(process3.execArgv).concat(args);
2210
+ proc = childProcess.spawn(process3.execPath, args, { stdio: "inherit" });
2211
+ }
2212
+ if (!proc.killed) {
2213
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
2214
+ signals.forEach((signal) => {
2215
+ process3.on(signal, () => {
2216
+ if (proc.killed === false && proc.exitCode === null) {
2217
+ proc.kill(signal);
2218
+ }
2219
+ });
2220
+ });
2221
+ }
2222
+ const exitCallback = this._exitCallback;
2223
+ proc.on("close", (code) => {
2224
+ code = code ?? 1;
2225
+ if (!exitCallback) {
2226
+ process3.exit(code);
2227
+ } else {
2228
+ exitCallback(
2229
+ new CommanderError2(
2230
+ code,
2231
+ "commander.executeSubCommandAsync",
2232
+ "(close)"
2233
+ )
2234
+ );
2235
+ }
2236
+ });
2237
+ proc.on("error", (err) => {
2238
+ if (err.code === "ENOENT") {
2239
+ this._checkForMissingExecutable(
2240
+ executableFile,
2241
+ executableDir,
2242
+ subcommand._name
2243
+ );
2244
+ } else if (err.code === "EACCES") {
2245
+ throw new Error(`'${executableFile}' not executable`);
2246
+ }
2247
+ if (!exitCallback) {
2248
+ process3.exit(1);
2249
+ } else {
2250
+ const wrappedError = new CommanderError2(
2251
+ 1,
2252
+ "commander.executeSubCommandAsync",
2253
+ "(error)"
2254
+ );
2255
+ wrappedError.nestedError = err;
2256
+ exitCallback(wrappedError);
2257
+ }
2258
+ });
2259
+ this.runningCommand = proc;
2260
+ }
2261
+ /**
2262
+ * @private
2263
+ */
2264
+ _dispatchSubcommand(commandName, operands, unknown) {
2265
+ const subCommand = this._findCommand(commandName);
2266
+ if (!subCommand) this.help({ error: true });
2267
+ subCommand._prepareForParse();
2268
+ let promiseChain;
2269
+ promiseChain = this._chainOrCallSubCommandHook(
2270
+ promiseChain,
2271
+ subCommand,
2272
+ "preSubcommand"
2273
+ );
2274
+ promiseChain = this._chainOrCall(promiseChain, () => {
2275
+ if (subCommand._executableHandler) {
2276
+ this._executeSubCommand(subCommand, operands.concat(unknown));
2277
+ } else {
2278
+ return subCommand._parseCommand(operands, unknown);
2279
+ }
2280
+ });
2281
+ return promiseChain;
2282
+ }
2283
+ /**
2284
+ * Invoke help directly if possible, or dispatch if necessary.
2285
+ * e.g. help foo
2286
+ *
2287
+ * @private
2288
+ */
2289
+ _dispatchHelpCommand(subcommandName) {
2290
+ if (!subcommandName) {
2291
+ this.help();
2292
+ }
2293
+ const subCommand = this._findCommand(subcommandName);
2294
+ if (subCommand && !subCommand._executableHandler) {
2295
+ subCommand.help();
2296
+ }
2297
+ return this._dispatchSubcommand(
2298
+ subcommandName,
2299
+ [],
2300
+ [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]
2301
+ );
2302
+ }
2303
+ /**
2304
+ * Check this.args against expected this.registeredArguments.
2305
+ *
2306
+ * @private
2307
+ */
2308
+ _checkNumberOfArguments() {
2309
+ this.registeredArguments.forEach((arg, i) => {
2310
+ if (arg.required && this.args[i] == null) {
2311
+ this.missingArgument(arg.name());
2312
+ }
2313
+ });
2314
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
2315
+ return;
2316
+ }
2317
+ if (this.args.length > this.registeredArguments.length) {
2318
+ this._excessArguments(this.args);
2319
+ }
2320
+ }
2321
+ /**
2322
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
2323
+ *
2324
+ * @private
2325
+ */
2326
+ _processArguments() {
2327
+ const myParseArg = (argument, value, previous) => {
2328
+ let parsedValue = value;
2329
+ if (value !== null && argument.parseArg) {
2330
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
2331
+ parsedValue = this._callParseArg(
2332
+ argument,
2333
+ value,
2334
+ previous,
2335
+ invalidValueMessage
2336
+ );
2337
+ }
2338
+ return parsedValue;
2339
+ };
2340
+ this._checkNumberOfArguments();
2341
+ const processedArgs = [];
2342
+ this.registeredArguments.forEach((declaredArg, index) => {
2343
+ let value = declaredArg.defaultValue;
2344
+ if (declaredArg.variadic) {
2345
+ if (index < this.args.length) {
2346
+ value = this.args.slice(index);
2347
+ if (declaredArg.parseArg) {
2348
+ value = value.reduce((processed, v) => {
2349
+ return myParseArg(declaredArg, v, processed);
2350
+ }, declaredArg.defaultValue);
2351
+ }
2352
+ } else if (value === void 0) {
2353
+ value = [];
2354
+ }
2355
+ } else if (index < this.args.length) {
2356
+ value = this.args[index];
2357
+ if (declaredArg.parseArg) {
2358
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
2359
+ }
2360
+ }
2361
+ processedArgs[index] = value;
2362
+ });
2363
+ this.processedArgs = processedArgs;
2364
+ }
2365
+ /**
2366
+ * Once we have a promise we chain, but call synchronously until then.
2367
+ *
2368
+ * @param {(Promise|undefined)} promise
2369
+ * @param {Function} fn
2370
+ * @return {(Promise|undefined)}
2371
+ * @private
2372
+ */
2373
+ _chainOrCall(promise, fn) {
2374
+ if (promise && promise.then && typeof promise.then === "function") {
2375
+ return promise.then(() => fn());
2376
+ }
2377
+ return fn();
2378
+ }
2379
+ /**
2380
+ *
2381
+ * @param {(Promise|undefined)} promise
2382
+ * @param {string} event
2383
+ * @return {(Promise|undefined)}
2384
+ * @private
2385
+ */
2386
+ _chainOrCallHooks(promise, event) {
2387
+ let result = promise;
2388
+ const hooks = [];
2389
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
2390
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
2391
+ hooks.push({ hookedCommand, callback });
2392
+ });
2393
+ });
2394
+ if (event === "postAction") {
2395
+ hooks.reverse();
2396
+ }
2397
+ hooks.forEach((hookDetail) => {
2398
+ result = this._chainOrCall(result, () => {
2399
+ return hookDetail.callback(hookDetail.hookedCommand, this);
2400
+ });
2401
+ });
2402
+ return result;
2403
+ }
2404
+ /**
2405
+ *
2406
+ * @param {(Promise|undefined)} promise
2407
+ * @param {Command} subCommand
2408
+ * @param {string} event
2409
+ * @return {(Promise|undefined)}
2410
+ * @private
2411
+ */
2412
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
2413
+ let result = promise;
2414
+ if (this._lifeCycleHooks[event] !== void 0) {
2415
+ this._lifeCycleHooks[event].forEach((hook) => {
2416
+ result = this._chainOrCall(result, () => {
2417
+ return hook(this, subCommand);
2418
+ });
2419
+ });
2420
+ }
2421
+ return result;
2422
+ }
2423
+ /**
2424
+ * Process arguments in context of this command.
2425
+ * Returns action result, in case it is a promise.
2426
+ *
2427
+ * @private
2428
+ */
2429
+ _parseCommand(operands, unknown) {
2430
+ const parsed = this.parseOptions(unknown);
2431
+ this._parseOptionsEnv();
2432
+ this._parseOptionsImplied();
2433
+ operands = operands.concat(parsed.operands);
2434
+ unknown = parsed.unknown;
2435
+ this.args = operands.concat(unknown);
2436
+ if (operands && this._findCommand(operands[0])) {
2437
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2438
+ }
2439
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
2440
+ return this._dispatchHelpCommand(operands[1]);
2441
+ }
2442
+ if (this._defaultCommandName) {
2443
+ this._outputHelpIfRequested(unknown);
2444
+ return this._dispatchSubcommand(
2445
+ this._defaultCommandName,
2446
+ operands,
2447
+ unknown
2448
+ );
2449
+ }
2450
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
2451
+ this.help({ error: true });
2452
+ }
2453
+ this._outputHelpIfRequested(parsed.unknown);
2454
+ this._checkForMissingMandatoryOptions();
2455
+ this._checkForConflictingOptions();
2456
+ const checkForUnknownOptions = () => {
2457
+ if (parsed.unknown.length > 0) {
2458
+ this.unknownOption(parsed.unknown[0]);
2459
+ }
2460
+ };
2461
+ const commandEvent = `command:${this.name()}`;
2462
+ if (this._actionHandler) {
2463
+ checkForUnknownOptions();
2464
+ this._processArguments();
2465
+ let promiseChain;
2466
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
2467
+ promiseChain = this._chainOrCall(
2468
+ promiseChain,
2469
+ () => this._actionHandler(this.processedArgs)
2470
+ );
2471
+ if (this.parent) {
2472
+ promiseChain = this._chainOrCall(promiseChain, () => {
2473
+ this.parent.emit(commandEvent, operands, unknown);
2474
+ });
2475
+ }
2476
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
2477
+ return promiseChain;
2478
+ }
2479
+ if (this.parent && this.parent.listenerCount(commandEvent)) {
2480
+ checkForUnknownOptions();
2481
+ this._processArguments();
2482
+ this.parent.emit(commandEvent, operands, unknown);
2483
+ } else if (operands.length) {
2484
+ if (this._findCommand("*")) {
2485
+ return this._dispatchSubcommand("*", operands, unknown);
2486
+ }
2487
+ if (this.listenerCount("command:*")) {
2488
+ this.emit("command:*", operands, unknown);
2489
+ } else if (this.commands.length) {
2490
+ this.unknownCommand();
2491
+ } else {
2492
+ checkForUnknownOptions();
2493
+ this._processArguments();
2494
+ }
2495
+ } else if (this.commands.length) {
2496
+ checkForUnknownOptions();
2497
+ this.help({ error: true });
2498
+ } else {
2499
+ checkForUnknownOptions();
2500
+ this._processArguments();
2501
+ }
2502
+ }
2503
+ /**
2504
+ * Find matching command.
2505
+ *
2506
+ * @private
2507
+ * @return {Command | undefined}
2508
+ */
2509
+ _findCommand(name) {
2510
+ if (!name) return void 0;
2511
+ return this.commands.find(
2512
+ (cmd) => cmd._name === name || cmd._aliases.includes(name)
2513
+ );
2514
+ }
2515
+ /**
2516
+ * Return an option matching `arg` if any.
2517
+ *
2518
+ * @param {string} arg
2519
+ * @return {Option}
2520
+ * @package
2521
+ */
2522
+ _findOption(arg) {
2523
+ return this.options.find((option) => option.is(arg));
2524
+ }
2525
+ /**
2526
+ * Display an error message if a mandatory option does not have a value.
2527
+ * Called after checking for help flags in leaf subcommand.
2528
+ *
2529
+ * @private
2530
+ */
2531
+ _checkForMissingMandatoryOptions() {
2532
+ this._getCommandAndAncestors().forEach((cmd) => {
2533
+ cmd.options.forEach((anOption) => {
2534
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
2535
+ cmd.missingMandatoryOptionValue(anOption);
2536
+ }
2537
+ });
2538
+ });
2539
+ }
2540
+ /**
2541
+ * Display an error message if conflicting options are used together in this.
2542
+ *
2543
+ * @private
2544
+ */
2545
+ _checkForConflictingLocalOptions() {
2546
+ const definedNonDefaultOptions = this.options.filter((option) => {
2547
+ const optionKey = option.attributeName();
2548
+ if (this.getOptionValue(optionKey) === void 0) {
2549
+ return false;
2550
+ }
2551
+ return this.getOptionValueSource(optionKey) !== "default";
2552
+ });
2553
+ const optionsWithConflicting = definedNonDefaultOptions.filter(
2554
+ (option) => option.conflictsWith.length > 0
2555
+ );
2556
+ optionsWithConflicting.forEach((option) => {
2557
+ const conflictingAndDefined = definedNonDefaultOptions.find(
2558
+ (defined) => option.conflictsWith.includes(defined.attributeName())
2559
+ );
2560
+ if (conflictingAndDefined) {
2561
+ this._conflictingOption(option, conflictingAndDefined);
2562
+ }
2563
+ });
2564
+ }
2565
+ /**
2566
+ * Display an error message if conflicting options are used together.
2567
+ * Called after checking for help flags in leaf subcommand.
2568
+ *
2569
+ * @private
2570
+ */
2571
+ _checkForConflictingOptions() {
2572
+ this._getCommandAndAncestors().forEach((cmd) => {
2573
+ cmd._checkForConflictingLocalOptions();
2574
+ });
2575
+ }
2576
+ /**
2577
+ * Parse options from `argv` removing known options,
2578
+ * and return argv split into operands and unknown arguments.
2579
+ *
2580
+ * Side effects: modifies command by storing options. Does not reset state if called again.
2581
+ *
2582
+ * Examples:
2583
+ *
2584
+ * argv => operands, unknown
2585
+ * --known kkk op => [op], []
2586
+ * op --known kkk => [op], []
2587
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
2588
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
2589
+ *
2590
+ * @param {string[]} argv
2591
+ * @return {{operands: string[], unknown: string[]}}
2592
+ */
2593
+ parseOptions(argv) {
2594
+ const operands = [];
2595
+ const unknown = [];
2596
+ let dest = operands;
2597
+ const args = argv.slice();
2598
+ function maybeOption(arg) {
2599
+ return arg.length > 1 && arg[0] === "-";
2600
+ }
2601
+ let activeVariadicOption = null;
2602
+ while (args.length) {
2603
+ const arg = args.shift();
2604
+ if (arg === "--") {
2605
+ if (dest === unknown) dest.push(arg);
2606
+ dest.push(...args);
2607
+ break;
2608
+ }
2609
+ if (activeVariadicOption && !maybeOption(arg)) {
2610
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
2611
+ continue;
2612
+ }
2613
+ activeVariadicOption = null;
2614
+ if (maybeOption(arg)) {
2615
+ const option = this._findOption(arg);
2616
+ if (option) {
2617
+ if (option.required) {
2618
+ const value = args.shift();
2619
+ if (value === void 0) this.optionMissingArgument(option);
2620
+ this.emit(`option:${option.name()}`, value);
2621
+ } else if (option.optional) {
2622
+ let value = null;
2623
+ if (args.length > 0 && !maybeOption(args[0])) {
2624
+ value = args.shift();
2625
+ }
2626
+ this.emit(`option:${option.name()}`, value);
2627
+ } else {
2628
+ this.emit(`option:${option.name()}`);
2629
+ }
2630
+ activeVariadicOption = option.variadic ? option : null;
2631
+ continue;
2632
+ }
2633
+ }
2634
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
2635
+ const option = this._findOption(`-${arg[1]}`);
2636
+ if (option) {
2637
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
2638
+ this.emit(`option:${option.name()}`, arg.slice(2));
2639
+ } else {
2640
+ this.emit(`option:${option.name()}`);
2641
+ args.unshift(`-${arg.slice(2)}`);
2642
+ }
2643
+ continue;
2644
+ }
2645
+ }
2646
+ if (/^--[^=]+=/.test(arg)) {
2647
+ const index = arg.indexOf("=");
2648
+ const option = this._findOption(arg.slice(0, index));
2649
+ if (option && (option.required || option.optional)) {
2650
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
2651
+ continue;
2652
+ }
2653
+ }
2654
+ if (maybeOption(arg)) {
2655
+ dest = unknown;
2656
+ }
2657
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
2658
+ if (this._findCommand(arg)) {
2659
+ operands.push(arg);
2660
+ if (args.length > 0) unknown.push(...args);
2661
+ break;
2662
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
2663
+ operands.push(arg);
2664
+ if (args.length > 0) operands.push(...args);
2665
+ break;
2666
+ } else if (this._defaultCommandName) {
2667
+ unknown.push(arg);
2668
+ if (args.length > 0) unknown.push(...args);
2669
+ break;
2670
+ }
2671
+ }
2672
+ if (this._passThroughOptions) {
2673
+ dest.push(arg);
2674
+ if (args.length > 0) dest.push(...args);
2675
+ break;
2676
+ }
2677
+ dest.push(arg);
2678
+ }
2679
+ return { operands, unknown };
2680
+ }
2681
+ /**
2682
+ * Return an object containing local option values as key-value pairs.
2683
+ *
2684
+ * @return {object}
2685
+ */
2686
+ opts() {
2687
+ if (this._storeOptionsAsProperties) {
2688
+ const result = {};
2689
+ const len = this.options.length;
2690
+ for (let i = 0; i < len; i++) {
2691
+ const key = this.options[i].attributeName();
2692
+ result[key] = key === this._versionOptionName ? this._version : this[key];
2693
+ }
2694
+ return result;
2695
+ }
2696
+ return this._optionValues;
2697
+ }
2698
+ /**
2699
+ * Return an object containing merged local and global option values as key-value pairs.
2700
+ *
2701
+ * @return {object}
2702
+ */
2703
+ optsWithGlobals() {
2704
+ return this._getCommandAndAncestors().reduce(
2705
+ (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
2706
+ {}
2707
+ );
2708
+ }
2709
+ /**
2710
+ * Display error message and exit (or call exitOverride).
2711
+ *
2712
+ * @param {string} message
2713
+ * @param {object} [errorOptions]
2714
+ * @param {string} [errorOptions.code] - an id string representing the error
2715
+ * @param {number} [errorOptions.exitCode] - used with process.exit
2716
+ */
2717
+ error(message, errorOptions) {
2718
+ this._outputConfiguration.outputError(
2719
+ `${message}
2720
+ `,
2721
+ this._outputConfiguration.writeErr
2722
+ );
2723
+ if (typeof this._showHelpAfterError === "string") {
2724
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
2725
+ `);
2726
+ } else if (this._showHelpAfterError) {
2727
+ this._outputConfiguration.writeErr("\n");
2728
+ this.outputHelp({ error: true });
2729
+ }
2730
+ const config = errorOptions || {};
2731
+ const exitCode = config.exitCode || 1;
2732
+ const code = config.code || "commander.error";
2733
+ this._exit(exitCode, code, message);
2734
+ }
2735
+ /**
2736
+ * Apply any option related environment variables, if option does
2737
+ * not have a value from cli or client code.
2738
+ *
2739
+ * @private
2740
+ */
2741
+ _parseOptionsEnv() {
2742
+ this.options.forEach((option) => {
2743
+ if (option.envVar && option.envVar in process3.env) {
2744
+ const optionKey = option.attributeName();
2745
+ if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(
2746
+ this.getOptionValueSource(optionKey)
2747
+ )) {
2748
+ if (option.required || option.optional) {
2749
+ this.emit(`optionEnv:${option.name()}`, process3.env[option.envVar]);
2750
+ } else {
2751
+ this.emit(`optionEnv:${option.name()}`);
2752
+ }
2753
+ }
2754
+ }
2755
+ });
2756
+ }
2757
+ /**
2758
+ * Apply any implied option values, if option is undefined or default value.
2759
+ *
2760
+ * @private
2761
+ */
2762
+ _parseOptionsImplied() {
2763
+ const dualHelper = new DualOptions(this.options);
2764
+ const hasCustomOptionValue = (optionKey) => {
2765
+ return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
2766
+ };
2767
+ this.options.filter(
2768
+ (option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(
2769
+ this.getOptionValue(option.attributeName()),
2770
+ option
2771
+ )
2772
+ ).forEach((option) => {
2773
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
2774
+ this.setOptionValueWithSource(
2775
+ impliedKey,
2776
+ option.implied[impliedKey],
2777
+ "implied"
2778
+ );
2779
+ });
2780
+ });
2781
+ }
2782
+ /**
2783
+ * Argument `name` is missing.
2784
+ *
2785
+ * @param {string} name
2786
+ * @private
2787
+ */
2788
+ missingArgument(name) {
2789
+ const message = `error: missing required argument '${name}'`;
2790
+ this.error(message, { code: "commander.missingArgument" });
2791
+ }
2792
+ /**
2793
+ * `Option` is missing an argument.
2794
+ *
2795
+ * @param {Option} option
2796
+ * @private
2797
+ */
2798
+ optionMissingArgument(option) {
2799
+ const message = `error: option '${option.flags}' argument missing`;
2800
+ this.error(message, { code: "commander.optionMissingArgument" });
2801
+ }
2802
+ /**
2803
+ * `Option` does not have a value, and is a mandatory option.
2804
+ *
2805
+ * @param {Option} option
2806
+ * @private
2807
+ */
2808
+ missingMandatoryOptionValue(option) {
2809
+ const message = `error: required option '${option.flags}' not specified`;
2810
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
2811
+ }
2812
+ /**
2813
+ * `Option` conflicts with another option.
2814
+ *
2815
+ * @param {Option} option
2816
+ * @param {Option} conflictingOption
2817
+ * @private
2818
+ */
2819
+ _conflictingOption(option, conflictingOption) {
2820
+ const findBestOptionFromValue = (option2) => {
2821
+ const optionKey = option2.attributeName();
2822
+ const optionValue = this.getOptionValue(optionKey);
2823
+ const negativeOption = this.options.find(
2824
+ (target) => target.negate && optionKey === target.attributeName()
2825
+ );
2826
+ const positiveOption = this.options.find(
2827
+ (target) => !target.negate && optionKey === target.attributeName()
2828
+ );
2829
+ if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
2830
+ return negativeOption;
2831
+ }
2832
+ return positiveOption || option2;
2833
+ };
2834
+ const getErrorMessage = (option2) => {
2835
+ const bestOption = findBestOptionFromValue(option2);
2836
+ const optionKey = bestOption.attributeName();
2837
+ const source = this.getOptionValueSource(optionKey);
2838
+ if (source === "env") {
2839
+ return `environment variable '${bestOption.envVar}'`;
2840
+ }
2841
+ return `option '${bestOption.flags}'`;
2842
+ };
2843
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2844
+ this.error(message, { code: "commander.conflictingOption" });
2845
+ }
2846
+ /**
2847
+ * Unknown option `flag`.
2848
+ *
2849
+ * @param {string} flag
2850
+ * @private
2851
+ */
2852
+ unknownOption(flag) {
2853
+ if (this._allowUnknownOption) return;
2854
+ let suggestion = "";
2855
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
2856
+ let candidateFlags = [];
2857
+ let command = this;
2858
+ do {
2859
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
2860
+ candidateFlags = candidateFlags.concat(moreFlags);
2861
+ command = command.parent;
2862
+ } while (command && !command._enablePositionalOptions);
2863
+ suggestion = suggestSimilar(flag, candidateFlags);
2864
+ }
2865
+ const message = `error: unknown option '${flag}'${suggestion}`;
2866
+ this.error(message, { code: "commander.unknownOption" });
2867
+ }
2868
+ /**
2869
+ * Excess arguments, more than expected.
2870
+ *
2871
+ * @param {string[]} receivedArgs
2872
+ * @private
2873
+ */
2874
+ _excessArguments(receivedArgs) {
2875
+ if (this._allowExcessArguments) return;
2876
+ const expected = this.registeredArguments.length;
2877
+ const s = expected === 1 ? "" : "s";
2878
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
2879
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
2880
+ this.error(message, { code: "commander.excessArguments" });
2881
+ }
2882
+ /**
2883
+ * Unknown command.
2884
+ *
2885
+ * @private
2886
+ */
2887
+ unknownCommand() {
2888
+ const unknownName = this.args[0];
2889
+ let suggestion = "";
2890
+ if (this._showSuggestionAfterError) {
2891
+ const candidateNames = [];
2892
+ this.createHelp().visibleCommands(this).forEach((command) => {
2893
+ candidateNames.push(command.name());
2894
+ if (command.alias()) candidateNames.push(command.alias());
2895
+ });
2896
+ suggestion = suggestSimilar(unknownName, candidateNames);
2897
+ }
2898
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
2899
+ this.error(message, { code: "commander.unknownCommand" });
2900
+ }
2901
+ /**
2902
+ * Get or set the program version.
2903
+ *
2904
+ * This method auto-registers the "-V, --version" option which will print the version number.
2905
+ *
2906
+ * You can optionally supply the flags and description to override the defaults.
2907
+ *
2908
+ * @param {string} [str]
2909
+ * @param {string} [flags]
2910
+ * @param {string} [description]
2911
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
2912
+ */
2913
+ version(str, flags, description) {
2914
+ if (str === void 0) return this._version;
2915
+ this._version = str;
2916
+ flags = flags || "-V, --version";
2917
+ description = description || "output the version number";
2918
+ const versionOption = this.createOption(flags, description);
2919
+ this._versionOptionName = versionOption.attributeName();
2920
+ this._registerOption(versionOption);
2921
+ this.on("option:" + versionOption.name(), () => {
2922
+ this._outputConfiguration.writeOut(`${str}
2923
+ `);
2924
+ this._exit(0, "commander.version", str);
2925
+ });
2926
+ return this;
2927
+ }
2928
+ /**
2929
+ * Set the description.
2930
+ *
2931
+ * @param {string} [str]
2932
+ * @param {object} [argsDescription]
2933
+ * @return {(string|Command)}
2934
+ */
2935
+ description(str, argsDescription) {
2936
+ if (str === void 0 && argsDescription === void 0)
2937
+ return this._description;
2938
+ this._description = str;
2939
+ if (argsDescription) {
2940
+ this._argsDescription = argsDescription;
2941
+ }
2942
+ return this;
2943
+ }
2944
+ /**
2945
+ * Set the summary. Used when listed as subcommand of parent.
2946
+ *
2947
+ * @param {string} [str]
2948
+ * @return {(string|Command)}
2949
+ */
2950
+ summary(str) {
2951
+ if (str === void 0) return this._summary;
2952
+ this._summary = str;
2953
+ return this;
2954
+ }
2955
+ /**
2956
+ * Set an alias for the command.
2957
+ *
2958
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
2959
+ *
2960
+ * @param {string} [alias]
2961
+ * @return {(string|Command)}
2962
+ */
2963
+ alias(alias) {
2964
+ if (alias === void 0) return this._aliases[0];
2965
+ let command = this;
2966
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
2967
+ command = this.commands[this.commands.length - 1];
2968
+ }
2969
+ if (alias === command._name)
2970
+ throw new Error("Command alias can't be the same as its name");
2971
+ const matchingCommand = this.parent?._findCommand(alias);
2972
+ if (matchingCommand) {
2973
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
2974
+ throw new Error(
2975
+ `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`
2976
+ );
2977
+ }
2978
+ command._aliases.push(alias);
2979
+ return this;
2980
+ }
2981
+ /**
2982
+ * Set aliases for the command.
2983
+ *
2984
+ * Only the first alias is shown in the auto-generated help.
2985
+ *
2986
+ * @param {string[]} [aliases]
2987
+ * @return {(string[]|Command)}
2988
+ */
2989
+ aliases(aliases) {
2990
+ if (aliases === void 0) return this._aliases;
2991
+ aliases.forEach((alias) => this.alias(alias));
2992
+ return this;
2993
+ }
2994
+ /**
2995
+ * Set / get the command usage `str`.
2996
+ *
2997
+ * @param {string} [str]
2998
+ * @return {(string|Command)}
2999
+ */
3000
+ usage(str) {
3001
+ if (str === void 0) {
3002
+ if (this._usage) return this._usage;
3003
+ const args = this.registeredArguments.map((arg) => {
3004
+ return humanReadableArgName(arg);
3005
+ });
3006
+ return [].concat(
3007
+ this.options.length || this._helpOption !== null ? "[options]" : [],
3008
+ this.commands.length ? "[command]" : [],
3009
+ this.registeredArguments.length ? args : []
3010
+ ).join(" ");
3011
+ }
3012
+ this._usage = str;
3013
+ return this;
3014
+ }
3015
+ /**
3016
+ * Get or set the name of the command.
3017
+ *
3018
+ * @param {string} [str]
3019
+ * @return {(string|Command)}
3020
+ */
3021
+ name(str) {
3022
+ if (str === void 0) return this._name;
3023
+ this._name = str;
3024
+ return this;
3025
+ }
3026
+ /**
3027
+ * Set the name of the command from script filename, such as process.argv[1],
3028
+ * or require.main.filename, or __filename.
3029
+ *
3030
+ * (Used internally and public although not documented in README.)
3031
+ *
3032
+ * @example
3033
+ * program.nameFromFilename(require.main.filename);
3034
+ *
3035
+ * @param {string} filename
3036
+ * @return {Command}
3037
+ */
3038
+ nameFromFilename(filename) {
3039
+ this._name = path.basename(filename, path.extname(filename));
3040
+ return this;
3041
+ }
3042
+ /**
3043
+ * Get or set the directory for searching for executable subcommands of this command.
3044
+ *
3045
+ * @example
3046
+ * program.executableDir(__dirname);
3047
+ * // or
3048
+ * program.executableDir('subcommands');
3049
+ *
3050
+ * @param {string} [path]
3051
+ * @return {(string|null|Command)}
3052
+ */
3053
+ executableDir(path2) {
3054
+ if (path2 === void 0) return this._executableDir;
3055
+ this._executableDir = path2;
3056
+ return this;
3057
+ }
3058
+ /**
3059
+ * Return program help documentation.
3060
+ *
3061
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
3062
+ * @return {string}
3063
+ */
3064
+ helpInformation(contextOptions) {
3065
+ const helper = this.createHelp();
3066
+ const context = this._getOutputContext(contextOptions);
3067
+ helper.prepareContext({
3068
+ error: context.error,
3069
+ helpWidth: context.helpWidth,
3070
+ outputHasColors: context.hasColors
3071
+ });
3072
+ const text = helper.formatHelp(this, helper);
3073
+ if (context.hasColors) return text;
3074
+ return this._outputConfiguration.stripColor(text);
3075
+ }
3076
+ /**
3077
+ * @typedef HelpContext
3078
+ * @type {object}
3079
+ * @property {boolean} error
3080
+ * @property {number} helpWidth
3081
+ * @property {boolean} hasColors
3082
+ * @property {function} write - includes stripColor if needed
3083
+ *
3084
+ * @returns {HelpContext}
3085
+ * @private
3086
+ */
3087
+ _getOutputContext(contextOptions) {
3088
+ contextOptions = contextOptions || {};
3089
+ const error = !!contextOptions.error;
3090
+ let baseWrite;
3091
+ let hasColors;
3092
+ let helpWidth;
3093
+ if (error) {
3094
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
3095
+ hasColors = this._outputConfiguration.getErrHasColors();
3096
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
3097
+ } else {
3098
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
3099
+ hasColors = this._outputConfiguration.getOutHasColors();
3100
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
3101
+ }
3102
+ const write = (str) => {
3103
+ if (!hasColors) str = this._outputConfiguration.stripColor(str);
3104
+ return baseWrite(str);
3105
+ };
3106
+ return { error, write, hasColors, helpWidth };
3107
+ }
3108
+ /**
3109
+ * Output help information for this command.
3110
+ *
3111
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
3112
+ *
3113
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
3114
+ */
3115
+ outputHelp(contextOptions) {
3116
+ let deprecatedCallback;
3117
+ if (typeof contextOptions === "function") {
3118
+ deprecatedCallback = contextOptions;
3119
+ contextOptions = void 0;
3120
+ }
3121
+ const outputContext = this._getOutputContext(contextOptions);
3122
+ const eventContext = {
3123
+ error: outputContext.error,
3124
+ write: outputContext.write,
3125
+ command: this
3126
+ };
3127
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
3128
+ this.emit("beforeHelp", eventContext);
3129
+ let helpInformation = this.helpInformation({ error: outputContext.error });
3130
+ if (deprecatedCallback) {
3131
+ helpInformation = deprecatedCallback(helpInformation);
3132
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
3133
+ throw new Error("outputHelp callback must return a string or a Buffer");
3134
+ }
3135
+ }
3136
+ outputContext.write(helpInformation);
3137
+ if (this._getHelpOption()?.long) {
3138
+ this.emit(this._getHelpOption().long);
3139
+ }
3140
+ this.emit("afterHelp", eventContext);
3141
+ this._getCommandAndAncestors().forEach(
3142
+ (command) => command.emit("afterAllHelp", eventContext)
3143
+ );
3144
+ }
3145
+ /**
3146
+ * You can pass in flags and a description to customise the built-in help option.
3147
+ * Pass in false to disable the built-in help option.
3148
+ *
3149
+ * @example
3150
+ * program.helpOption('-?, --help' 'show help'); // customise
3151
+ * program.helpOption(false); // disable
3152
+ *
3153
+ * @param {(string | boolean)} flags
3154
+ * @param {string} [description]
3155
+ * @return {Command} `this` command for chaining
3156
+ */
3157
+ helpOption(flags, description) {
3158
+ if (typeof flags === "boolean") {
3159
+ if (flags) {
3160
+ this._helpOption = this._helpOption ?? void 0;
3161
+ } else {
3162
+ this._helpOption = null;
3163
+ }
3164
+ return this;
3165
+ }
3166
+ flags = flags ?? "-h, --help";
3167
+ description = description ?? "display help for command";
3168
+ this._helpOption = this.createOption(flags, description);
3169
+ return this;
3170
+ }
3171
+ /**
3172
+ * Lazy create help option.
3173
+ * Returns null if has been disabled with .helpOption(false).
3174
+ *
3175
+ * @returns {(Option | null)} the help option
3176
+ * @package
3177
+ */
3178
+ _getHelpOption() {
3179
+ if (this._helpOption === void 0) {
3180
+ this.helpOption(void 0, void 0);
3181
+ }
3182
+ return this._helpOption;
3183
+ }
3184
+ /**
3185
+ * Supply your own option to use for the built-in help option.
3186
+ * This is an alternative to using helpOption() to customise the flags and description etc.
3187
+ *
3188
+ * @param {Option} option
3189
+ * @return {Command} `this` command for chaining
3190
+ */
3191
+ addHelpOption(option) {
3192
+ this._helpOption = option;
3193
+ return this;
3194
+ }
3195
+ /**
3196
+ * Output help information and exit.
3197
+ *
3198
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
3199
+ *
3200
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
3201
+ */
3202
+ help(contextOptions) {
3203
+ this.outputHelp(contextOptions);
3204
+ let exitCode = Number(process3.exitCode ?? 0);
3205
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
3206
+ exitCode = 1;
3207
+ }
3208
+ this._exit(exitCode, "commander.help", "(outputHelp)");
3209
+ }
3210
+ /**
3211
+ * // Do a little typing to coordinate emit and listener for the help text events.
3212
+ * @typedef HelpTextEventContext
3213
+ * @type {object}
3214
+ * @property {boolean} error
3215
+ * @property {Command} command
3216
+ * @property {function} write
3217
+ */
3218
+ /**
3219
+ * Add additional text to be displayed with the built-in help.
3220
+ *
3221
+ * Position is 'before' or 'after' to affect just this command,
3222
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
3223
+ *
3224
+ * @param {string} position - before or after built-in help
3225
+ * @param {(string | Function)} text - string to add, or a function returning a string
3226
+ * @return {Command} `this` command for chaining
3227
+ */
3228
+ addHelpText(position, text) {
3229
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
3230
+ if (!allowedValues.includes(position)) {
3231
+ throw new Error(`Unexpected value for position to addHelpText.
3232
+ Expecting one of '${allowedValues.join("', '")}'`);
3233
+ }
3234
+ const helpEvent = `${position}Help`;
3235
+ this.on(helpEvent, (context) => {
3236
+ let helpStr;
3237
+ if (typeof text === "function") {
3238
+ helpStr = text({ error: context.error, command: context.command });
3239
+ } else {
3240
+ helpStr = text;
3241
+ }
3242
+ if (helpStr) {
3243
+ context.write(`${helpStr}
3244
+ `);
3245
+ }
3246
+ });
3247
+ return this;
3248
+ }
3249
+ /**
3250
+ * Output help information if help flags specified
3251
+ *
3252
+ * @param {Array} args - array of options to search for help flags
3253
+ * @private
3254
+ */
3255
+ _outputHelpIfRequested(args) {
3256
+ const helpOption = this._getHelpOption();
3257
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
3258
+ if (helpRequested) {
3259
+ this.outputHelp();
3260
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
3261
+ }
3262
+ }
3263
+ };
3264
+ function incrementNodeInspectorPort(args) {
3265
+ return args.map((arg) => {
3266
+ if (!arg.startsWith("--inspect")) {
3267
+ return arg;
3268
+ }
3269
+ let debugOption;
3270
+ let debugHost = "127.0.0.1";
3271
+ let debugPort = "9229";
3272
+ let match;
3273
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
3274
+ debugOption = match[1];
3275
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
3276
+ debugOption = match[1];
3277
+ if (/^\d+$/.test(match[3])) {
3278
+ debugPort = match[3];
3279
+ } else {
3280
+ debugHost = match[3];
3281
+ }
3282
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
3283
+ debugOption = match[1];
3284
+ debugHost = match[3];
3285
+ debugPort = match[4];
3286
+ }
3287
+ if (debugOption && debugPort !== "0") {
3288
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
3289
+ }
3290
+ return arg;
3291
+ });
3292
+ }
3293
+ function useColor() {
3294
+ if (process3.env.NO_COLOR || process3.env.FORCE_COLOR === "0" || process3.env.FORCE_COLOR === "false")
3295
+ return false;
3296
+ if (process3.env.FORCE_COLOR || process3.env.CLICOLOR_FORCE !== void 0)
3297
+ return true;
3298
+ return void 0;
3299
+ }
3300
+ exports.Command = Command2;
3301
+ exports.useColor = useColor;
3302
+ }
3303
+ });
3304
+
3305
+ // node_modules/commander/index.js
3306
+ var require_commander = __commonJS({
3307
+ "node_modules/commander/index.js"(exports) {
3308
+ var { Argument: Argument2 } = require_argument();
3309
+ var { Command: Command2 } = require_command();
3310
+ var { CommanderError: CommanderError2, InvalidArgumentError: InvalidArgumentError2 } = require_error();
3311
+ var { Help: Help2 } = require_help();
3312
+ var { Option: Option2 } = require_option();
3313
+ exports.program = new Command2();
3314
+ exports.createCommand = (name) => new Command2(name);
3315
+ exports.createOption = (flags, description) => new Option2(flags, description);
3316
+ exports.createArgument = (name, description) => new Argument2(name, description);
3317
+ exports.Command = Command2;
3318
+ exports.Option = Option2;
3319
+ exports.Argument = Argument2;
3320
+ exports.Help = Help2;
3321
+ exports.CommanderError = CommanderError2;
3322
+ exports.InvalidArgumentError = InvalidArgumentError2;
3323
+ exports.InvalidOptionArgumentError = InvalidArgumentError2;
3324
+ }
3325
+ });
3326
+
3327
+ // node_modules/commander/esm.mjs
3328
+ var import_index = __toESM(require_commander(), 1);
3329
+ var {
3330
+ program,
3331
+ createCommand,
3332
+ createArgument,
3333
+ createOption,
3334
+ CommanderError,
3335
+ InvalidArgumentError,
3336
+ InvalidOptionArgumentError,
3337
+ // deprecated old name
3338
+ Command,
3339
+ Argument,
3340
+ Option,
3341
+ Help
3342
+ } = import_index.default;
3343
+
3344
+ // node_modules/chalk/source/vendor/ansi-styles/index.js
3345
+ var ANSI_BACKGROUND_OFFSET = 10;
3346
+ var wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`;
3347
+ var wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`;
3348
+ var wrapAnsi16m = (offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`;
3349
+ var styles = {
3350
+ modifier: {
3351
+ reset: [0, 0],
3352
+ // 21 isn't widely supported and 22 does the same thing
3353
+ bold: [1, 22],
3354
+ dim: [2, 22],
3355
+ italic: [3, 23],
3356
+ underline: [4, 24],
3357
+ overline: [53, 55],
3358
+ inverse: [7, 27],
3359
+ hidden: [8, 28],
3360
+ strikethrough: [9, 29]
3361
+ },
3362
+ color: {
3363
+ black: [30, 39],
3364
+ red: [31, 39],
3365
+ green: [32, 39],
3366
+ yellow: [33, 39],
3367
+ blue: [34, 39],
3368
+ magenta: [35, 39],
3369
+ cyan: [36, 39],
3370
+ white: [37, 39],
3371
+ // Bright color
3372
+ blackBright: [90, 39],
3373
+ gray: [90, 39],
3374
+ // Alias of `blackBright`
3375
+ grey: [90, 39],
3376
+ // Alias of `blackBright`
3377
+ redBright: [91, 39],
3378
+ greenBright: [92, 39],
3379
+ yellowBright: [93, 39],
3380
+ blueBright: [94, 39],
3381
+ magentaBright: [95, 39],
3382
+ cyanBright: [96, 39],
3383
+ whiteBright: [97, 39]
3384
+ },
3385
+ bgColor: {
3386
+ bgBlack: [40, 49],
3387
+ bgRed: [41, 49],
3388
+ bgGreen: [42, 49],
3389
+ bgYellow: [43, 49],
3390
+ bgBlue: [44, 49],
3391
+ bgMagenta: [45, 49],
3392
+ bgCyan: [46, 49],
3393
+ bgWhite: [47, 49],
3394
+ // Bright color
3395
+ bgBlackBright: [100, 49],
3396
+ bgGray: [100, 49],
3397
+ // Alias of `bgBlackBright`
3398
+ bgGrey: [100, 49],
3399
+ // Alias of `bgBlackBright`
3400
+ bgRedBright: [101, 49],
3401
+ bgGreenBright: [102, 49],
3402
+ bgYellowBright: [103, 49],
3403
+ bgBlueBright: [104, 49],
3404
+ bgMagentaBright: [105, 49],
3405
+ bgCyanBright: [106, 49],
3406
+ bgWhiteBright: [107, 49]
3407
+ }
3408
+ };
3409
+ var modifierNames = Object.keys(styles.modifier);
3410
+ var foregroundColorNames = Object.keys(styles.color);
3411
+ var backgroundColorNames = Object.keys(styles.bgColor);
3412
+ var colorNames = [...foregroundColorNames, ...backgroundColorNames];
3413
+ function assembleStyles() {
3414
+ const codes = /* @__PURE__ */ new Map();
3415
+ for (const [groupName, group] of Object.entries(styles)) {
3416
+ for (const [styleName, style] of Object.entries(group)) {
3417
+ styles[styleName] = {
3418
+ open: `\x1B[${style[0]}m`,
3419
+ close: `\x1B[${style[1]}m`
3420
+ };
3421
+ group[styleName] = styles[styleName];
3422
+ codes.set(style[0], style[1]);
3423
+ }
3424
+ Object.defineProperty(styles, groupName, {
3425
+ value: group,
3426
+ enumerable: false
3427
+ });
3428
+ }
3429
+ Object.defineProperty(styles, "codes", {
3430
+ value: codes,
3431
+ enumerable: false
3432
+ });
3433
+ styles.color.close = "\x1B[39m";
3434
+ styles.bgColor.close = "\x1B[49m";
3435
+ styles.color.ansi = wrapAnsi16();
3436
+ styles.color.ansi256 = wrapAnsi256();
3437
+ styles.color.ansi16m = wrapAnsi16m();
3438
+ styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
3439
+ styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
3440
+ styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
3441
+ Object.defineProperties(styles, {
3442
+ rgbToAnsi256: {
3443
+ value(red, green, blue) {
3444
+ if (red === green && green === blue) {
3445
+ if (red < 8) {
3446
+ return 16;
3447
+ }
3448
+ if (red > 248) {
3449
+ return 231;
3450
+ }
3451
+ return Math.round((red - 8) / 247 * 24) + 232;
3452
+ }
3453
+ return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
3454
+ },
3455
+ enumerable: false
3456
+ },
3457
+ hexToRgb: {
3458
+ value(hex) {
3459
+ const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
3460
+ if (!matches) {
3461
+ return [0, 0, 0];
3462
+ }
3463
+ let [colorString] = matches;
3464
+ if (colorString.length === 3) {
3465
+ colorString = [...colorString].map((character) => character + character).join("");
3466
+ }
3467
+ const integer = Number.parseInt(colorString, 16);
3468
+ return [
3469
+ /* eslint-disable no-bitwise */
3470
+ integer >> 16 & 255,
3471
+ integer >> 8 & 255,
3472
+ integer & 255
3473
+ /* eslint-enable no-bitwise */
3474
+ ];
3475
+ },
3476
+ enumerable: false
3477
+ },
3478
+ hexToAnsi256: {
3479
+ value: (hex) => styles.rgbToAnsi256(...styles.hexToRgb(hex)),
3480
+ enumerable: false
3481
+ },
3482
+ ansi256ToAnsi: {
3483
+ value(code) {
3484
+ if (code < 8) {
3485
+ return 30 + code;
3486
+ }
3487
+ if (code < 16) {
3488
+ return 90 + (code - 8);
3489
+ }
3490
+ let red;
3491
+ let green;
3492
+ let blue;
3493
+ if (code >= 232) {
3494
+ red = ((code - 232) * 10 + 8) / 255;
3495
+ green = red;
3496
+ blue = red;
3497
+ } else {
3498
+ code -= 16;
3499
+ const remainder = code % 36;
3500
+ red = Math.floor(code / 36) / 5;
3501
+ green = Math.floor(remainder / 6) / 5;
3502
+ blue = remainder % 6 / 5;
3503
+ }
3504
+ const value = Math.max(red, green, blue) * 2;
3505
+ if (value === 0) {
3506
+ return 30;
3507
+ }
3508
+ let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
3509
+ if (value === 2) {
3510
+ result += 60;
3511
+ }
3512
+ return result;
3513
+ },
3514
+ enumerable: false
3515
+ },
3516
+ rgbToAnsi: {
3517
+ value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),
3518
+ enumerable: false
3519
+ },
3520
+ hexToAnsi: {
3521
+ value: (hex) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),
3522
+ enumerable: false
3523
+ }
3524
+ });
3525
+ return styles;
3526
+ }
3527
+ var ansiStyles = assembleStyles();
3528
+ var ansi_styles_default = ansiStyles;
3529
+
3530
+ // node_modules/chalk/source/vendor/supports-color/index.js
3531
+ import process2 from "node:process";
3532
+ import os from "node:os";
3533
+ import tty from "node:tty";
3534
+ function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process2.argv) {
3535
+ const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
3536
+ const position = argv.indexOf(prefix + flag);
3537
+ const terminatorPosition = argv.indexOf("--");
3538
+ return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
3539
+ }
3540
+ var { env } = process2;
3541
+ var flagForceColor;
3542
+ if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
3543
+ flagForceColor = 0;
3544
+ } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
3545
+ flagForceColor = 1;
3546
+ }
3547
+ function envForceColor() {
3548
+ if ("FORCE_COLOR" in env) {
3549
+ if (env.FORCE_COLOR === "true") {
3550
+ return 1;
3551
+ }
3552
+ if (env.FORCE_COLOR === "false") {
3553
+ return 0;
3554
+ }
3555
+ return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
3556
+ }
3557
+ }
3558
+ function translateLevel(level) {
3559
+ if (level === 0) {
3560
+ return false;
3561
+ }
3562
+ return {
3563
+ level,
3564
+ hasBasic: true,
3565
+ has256: level >= 2,
3566
+ has16m: level >= 3
3567
+ };
3568
+ }
3569
+ function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
3570
+ const noFlagForceColor = envForceColor();
3571
+ if (noFlagForceColor !== void 0) {
3572
+ flagForceColor = noFlagForceColor;
3573
+ }
3574
+ const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
3575
+ if (forceColor === 0) {
3576
+ return 0;
3577
+ }
3578
+ if (sniffFlags) {
3579
+ if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
3580
+ return 3;
3581
+ }
3582
+ if (hasFlag("color=256")) {
3583
+ return 2;
3584
+ }
3585
+ }
3586
+ if ("TF_BUILD" in env && "AGENT_NAME" in env) {
3587
+ return 1;
3588
+ }
3589
+ if (haveStream && !streamIsTTY && forceColor === void 0) {
3590
+ return 0;
3591
+ }
3592
+ const min = forceColor || 0;
3593
+ if (env.TERM === "dumb") {
3594
+ return min;
3595
+ }
3596
+ if (process2.platform === "win32") {
3597
+ const osRelease = os.release().split(".");
3598
+ if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
3599
+ return Number(osRelease[2]) >= 14931 ? 3 : 2;
3600
+ }
3601
+ return 1;
3602
+ }
3603
+ if ("CI" in env) {
3604
+ if (["GITHUB_ACTIONS", "GITEA_ACTIONS", "CIRCLECI"].some((key) => key in env)) {
3605
+ return 3;
3606
+ }
3607
+ if (["TRAVIS", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
3608
+ return 1;
3609
+ }
3610
+ return min;
3611
+ }
3612
+ if ("TEAMCITY_VERSION" in env) {
3613
+ return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
3614
+ }
3615
+ if (env.COLORTERM === "truecolor") {
3616
+ return 3;
3617
+ }
3618
+ if (env.TERM === "xterm-kitty") {
3619
+ return 3;
3620
+ }
3621
+ if (env.TERM === "xterm-ghostty") {
3622
+ return 3;
3623
+ }
3624
+ if (env.TERM === "wezterm") {
3625
+ return 3;
3626
+ }
3627
+ if ("TERM_PROGRAM" in env) {
3628
+ const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
3629
+ switch (env.TERM_PROGRAM) {
3630
+ case "iTerm.app": {
3631
+ return version >= 3 ? 3 : 2;
3632
+ }
3633
+ case "Apple_Terminal": {
3634
+ return 2;
3635
+ }
3636
+ }
3637
+ }
3638
+ if (/-256(color)?$/i.test(env.TERM)) {
3639
+ return 2;
3640
+ }
3641
+ if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
3642
+ return 1;
3643
+ }
3644
+ if ("COLORTERM" in env) {
3645
+ return 1;
3646
+ }
3647
+ return min;
3648
+ }
3649
+ function createSupportsColor(stream, options = {}) {
3650
+ const level = _supportsColor(stream, {
3651
+ streamIsTTY: stream && stream.isTTY,
3652
+ ...options
3653
+ });
3654
+ return translateLevel(level);
3655
+ }
3656
+ var supportsColor = {
3657
+ stdout: createSupportsColor({ isTTY: tty.isatty(1) }),
3658
+ stderr: createSupportsColor({ isTTY: tty.isatty(2) })
3659
+ };
3660
+ var supports_color_default = supportsColor;
3661
+
3662
+ // node_modules/chalk/source/utilities.js
3663
+ function stringReplaceAll(string, substring, replacer) {
3664
+ let index = string.indexOf(substring);
3665
+ if (index === -1) {
3666
+ return string;
3667
+ }
3668
+ const substringLength = substring.length;
3669
+ let endIndex = 0;
3670
+ let returnValue = "";
3671
+ do {
3672
+ returnValue += string.slice(endIndex, index) + substring + replacer;
3673
+ endIndex = index + substringLength;
3674
+ index = string.indexOf(substring, endIndex);
3675
+ } while (index !== -1);
3676
+ returnValue += string.slice(endIndex);
3677
+ return returnValue;
3678
+ }
3679
+ function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
3680
+ let endIndex = 0;
3681
+ let returnValue = "";
3682
+ do {
3683
+ const gotCR = string[index - 1] === "\r";
3684
+ returnValue += string.slice(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? "\r\n" : "\n") + postfix;
3685
+ endIndex = index + 1;
3686
+ index = string.indexOf("\n", endIndex);
3687
+ } while (index !== -1);
3688
+ returnValue += string.slice(endIndex);
3689
+ return returnValue;
3690
+ }
3691
+
3692
+ // node_modules/chalk/source/index.js
3693
+ var { stdout: stdoutColor, stderr: stderrColor } = supports_color_default;
3694
+ var GENERATOR = Symbol("GENERATOR");
3695
+ var STYLER = Symbol("STYLER");
3696
+ var IS_EMPTY = Symbol("IS_EMPTY");
3697
+ var levelMapping = [
3698
+ "ansi",
3699
+ "ansi",
3700
+ "ansi256",
3701
+ "ansi16m"
3702
+ ];
3703
+ var styles2 = /* @__PURE__ */ Object.create(null);
3704
+ var applyOptions = (object, options = {}) => {
3705
+ if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
3706
+ throw new Error("The `level` option should be an integer from 0 to 3");
3707
+ }
3708
+ const colorLevel = stdoutColor ? stdoutColor.level : 0;
3709
+ object.level = options.level === void 0 ? colorLevel : options.level;
3710
+ };
3711
+ var chalkFactory = (options) => {
3712
+ const chalk2 = (...strings) => strings.join(" ");
3713
+ applyOptions(chalk2, options);
3714
+ Object.setPrototypeOf(chalk2, createChalk.prototype);
3715
+ return chalk2;
3716
+ };
3717
+ function createChalk(options) {
3718
+ return chalkFactory(options);
3719
+ }
3720
+ Object.setPrototypeOf(createChalk.prototype, Function.prototype);
3721
+ for (const [styleName, style] of Object.entries(ansi_styles_default)) {
3722
+ styles2[styleName] = {
3723
+ get() {
3724
+ const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
3725
+ Object.defineProperty(this, styleName, { value: builder });
3726
+ return builder;
3727
+ }
3728
+ };
3729
+ }
3730
+ styles2.visible = {
3731
+ get() {
3732
+ const builder = createBuilder(this, this[STYLER], true);
3733
+ Object.defineProperty(this, "visible", { value: builder });
3734
+ return builder;
3735
+ }
3736
+ };
3737
+ var getModelAnsi = (model, level, type, ...arguments_) => {
3738
+ if (model === "rgb") {
3739
+ if (level === "ansi16m") {
3740
+ return ansi_styles_default[type].ansi16m(...arguments_);
3741
+ }
3742
+ if (level === "ansi256") {
3743
+ return ansi_styles_default[type].ansi256(ansi_styles_default.rgbToAnsi256(...arguments_));
3744
+ }
3745
+ return ansi_styles_default[type].ansi(ansi_styles_default.rgbToAnsi(...arguments_));
3746
+ }
3747
+ if (model === "hex") {
3748
+ return getModelAnsi("rgb", level, type, ...ansi_styles_default.hexToRgb(...arguments_));
3749
+ }
3750
+ return ansi_styles_default[type][model](...arguments_);
3751
+ };
3752
+ var usedModels = ["rgb", "hex", "ansi256"];
3753
+ for (const model of usedModels) {
3754
+ styles2[model] = {
3755
+ get() {
3756
+ const { level } = this;
3757
+ return function(...arguments_) {
3758
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "color", ...arguments_), ansi_styles_default.color.close, this[STYLER]);
3759
+ return createBuilder(this, styler, this[IS_EMPTY]);
3760
+ };
3761
+ }
3762
+ };
3763
+ const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
3764
+ styles2[bgModel] = {
3765
+ get() {
3766
+ const { level } = this;
3767
+ return function(...arguments_) {
3768
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_), ansi_styles_default.bgColor.close, this[STYLER]);
3769
+ return createBuilder(this, styler, this[IS_EMPTY]);
3770
+ };
3771
+ }
3772
+ };
3773
+ }
3774
+ var proto = Object.defineProperties(() => {
3775
+ }, {
3776
+ ...styles2,
3777
+ level: {
3778
+ enumerable: true,
3779
+ get() {
3780
+ return this[GENERATOR].level;
3781
+ },
3782
+ set(level) {
3783
+ this[GENERATOR].level = level;
3784
+ }
3785
+ }
3786
+ });
3787
+ var createStyler = (open, close, parent) => {
3788
+ let openAll;
3789
+ let closeAll;
3790
+ if (parent === void 0) {
3791
+ openAll = open;
3792
+ closeAll = close;
3793
+ } else {
3794
+ openAll = parent.openAll + open;
3795
+ closeAll = close + parent.closeAll;
3796
+ }
3797
+ return {
3798
+ open,
3799
+ close,
3800
+ openAll,
3801
+ closeAll,
3802
+ parent
3803
+ };
3804
+ };
3805
+ var createBuilder = (self, _styler, _isEmpty) => {
3806
+ const builder = (...arguments_) => applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" "));
3807
+ Object.setPrototypeOf(builder, proto);
3808
+ builder[GENERATOR] = self;
3809
+ builder[STYLER] = _styler;
3810
+ builder[IS_EMPTY] = _isEmpty;
3811
+ return builder;
3812
+ };
3813
+ var applyStyle = (self, string) => {
3814
+ if (self.level <= 0 || !string) {
3815
+ return self[IS_EMPTY] ? "" : string;
3816
+ }
3817
+ let styler = self[STYLER];
3818
+ if (styler === void 0) {
3819
+ return string;
3820
+ }
3821
+ const { openAll, closeAll } = styler;
3822
+ if (string.includes("\x1B")) {
3823
+ while (styler !== void 0) {
3824
+ string = stringReplaceAll(string, styler.close, styler.open);
3825
+ styler = styler.parent;
3826
+ }
3827
+ }
3828
+ const lfIndex = string.indexOf("\n");
3829
+ if (lfIndex !== -1) {
3830
+ string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
3831
+ }
3832
+ return openAll + string + closeAll;
3833
+ };
3834
+ Object.defineProperties(createChalk.prototype, styles2);
3835
+ var chalk = createChalk();
3836
+ var chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
3837
+ var source_default = chalk;
3838
+
3839
+ // src/config.ts
3840
+ import { readFileSync, writeFileSync, mkdirSync, existsSync } from "fs";
3841
+ import { join } from "path";
3842
+ import { homedir } from "os";
3843
+ var CONFIG_DIR = join(homedir(), ".meg-tunnel");
3844
+ var CONFIG_FILE = join(CONFIG_DIR, "config.json");
3845
+ function ensureDir() {
3846
+ if (!existsSync(CONFIG_DIR)) {
3847
+ mkdirSync(CONFIG_DIR, { recursive: true });
3848
+ }
3849
+ }
3850
+ function loadConfig() {
3851
+ ensureDir();
3852
+ if (!existsSync(CONFIG_FILE)) return {};
3853
+ try {
3854
+ return JSON.parse(readFileSync(CONFIG_FILE, "utf-8"));
3855
+ } catch {
3856
+ return {};
3857
+ }
3858
+ }
3859
+ function saveConfig(config) {
3860
+ ensureDir();
3861
+ writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2));
3862
+ }
3863
+ function getApiKey() {
3864
+ return process.env.MEG_TUNNEL_API_KEY ?? loadConfig().apiKey;
3865
+ }
3866
+ function getServerUrl() {
3867
+ return process.env.MEG_TUNNEL_SERVER_URL ?? loadConfig().serverUrl ?? "wss://arwdloamdg.execute-api.us-east-1.amazonaws.com/prod";
3868
+ }
3869
+
3870
+ // src/tunnel.ts
3871
+ import WebSocket from "ws";
3872
+ import http from "http";
3873
+ import https from "https";
3874
+ var PING_INTERVAL_MS = 5 * 60 * 1e3;
3875
+ var RECONNECT_DELAY_MS = 3e3;
3876
+ function createTunnel(options) {
3877
+ const { port, serverUrl, apiKey, subdomain, auth, rateLimit, onRegistered, onRequest, onDisconnect, onError } = options;
3878
+ let ws = null;
3879
+ let pingInterval = null;
3880
+ let reconnectTimeout = null;
3881
+ let closed = false;
3882
+ function connect() {
3883
+ if (closed) return;
3884
+ const url = `${serverUrl}?apiKey=${encodeURIComponent(apiKey)}`;
3885
+ ws = new WebSocket(url);
3886
+ ws.on("open", () => {
3887
+ const registerMsg = {
3888
+ type: "register",
3889
+ localPort: port,
3890
+ subdomain,
3891
+ auth,
3892
+ rateLimit
3893
+ };
3894
+ ws.send(JSON.stringify(registerMsg));
3895
+ pingInterval = setInterval(() => {
3896
+ if (ws?.readyState === WebSocket.OPEN) {
3897
+ ws.send(JSON.stringify({ type: "ping" }));
3898
+ }
3899
+ }, PING_INTERVAL_MS);
3900
+ });
3901
+ ws.on("message", (data) => {
3902
+ let msg;
3903
+ try {
3904
+ msg = JSON.parse(data.toString());
3905
+ } catch {
3906
+ return;
3907
+ }
3908
+ switch (msg.type) {
3909
+ case "registered":
3910
+ onRegistered({ tunnelId: msg.tunnelId, subdomain: msg.subdomain, url: msg.url });
3911
+ break;
3912
+ case "request":
3913
+ handleRequest(msg.requestId, msg.method, msg.path, msg.headers, msg.body, msg.query);
3914
+ break;
3915
+ case "pong":
3916
+ break;
3917
+ case "error":
3918
+ onError(msg.message);
3919
+ break;
3920
+ }
3921
+ });
3922
+ ws.on("close", () => {
3923
+ cleanup();
3924
+ if (!closed) {
3925
+ onDisconnect();
3926
+ reconnectTimeout = setTimeout(connect, RECONNECT_DELAY_MS);
3927
+ }
3928
+ });
3929
+ ws.on("error", (err) => {
3930
+ onError(err.message);
3931
+ });
3932
+ }
3933
+ function handleRequest(requestId, method, path, headers, body, query) {
3934
+ const startTime = Date.now();
3935
+ const fullPath = query ? `${path}?${query}` : path;
3936
+ const isHttps = false;
3937
+ const reqModule = isHttps ? https : http;
3938
+ const reqOptions = {
3939
+ hostname: "127.0.0.1",
3940
+ port,
3941
+ path: fullPath,
3942
+ method,
3943
+ headers: { ...headers, host: `127.0.0.1:${port}` }
3944
+ };
3945
+ const proxyReq = reqModule.request(reqOptions, (proxyRes) => {
3946
+ const chunks = [];
3947
+ proxyRes.on("data", (chunk) => chunks.push(chunk));
3948
+ proxyRes.on("end", () => {
3949
+ const responseBody = Buffer.concat(chunks).toString("utf-8");
3950
+ const statusCode = proxyRes.statusCode ?? 500;
3951
+ const duration = Date.now() - startTime;
3952
+ const responseHeaders = {};
3953
+ Object.entries(proxyRes.headers).forEach(([k, v]) => {
3954
+ if (v) responseHeaders[k] = Array.isArray(v) ? v.join(", ") : v;
3955
+ });
3956
+ const response = {
3957
+ type: "response",
3958
+ requestId,
3959
+ statusCode,
3960
+ headers: responseHeaders,
3961
+ body: responseBody || null
3962
+ };
3963
+ if (ws?.readyState === WebSocket.OPEN) {
3964
+ ws.send(JSON.stringify(response));
3965
+ }
3966
+ onRequest({ method, path, statusCode, duration });
3967
+ });
3968
+ });
3969
+ proxyReq.on("error", (err) => {
3970
+ const response = {
3971
+ type: "response",
3972
+ requestId,
3973
+ statusCode: 502,
3974
+ headers: { "content-type": "application/json" },
3975
+ body: JSON.stringify({ error: `Local server error: ${err.message}` })
3976
+ };
3977
+ if (ws?.readyState === WebSocket.OPEN) {
3978
+ ws.send(JSON.stringify(response));
3979
+ }
3980
+ onRequest({ method, path, statusCode: 502, duration: Date.now() - startTime });
3981
+ });
3982
+ if (body) {
3983
+ proxyReq.write(body);
3984
+ }
3985
+ proxyReq.end();
3986
+ }
3987
+ function cleanup() {
3988
+ if (pingInterval) {
3989
+ clearInterval(pingInterval);
3990
+ pingInterval = null;
3991
+ }
3992
+ }
3993
+ function close() {
3994
+ closed = true;
3995
+ cleanup();
3996
+ if (reconnectTimeout) {
3997
+ clearTimeout(reconnectTimeout);
3998
+ reconnectTimeout = null;
3999
+ }
4000
+ if (ws) {
4001
+ ws.close();
4002
+ ws = null;
4003
+ }
4004
+ }
4005
+ connect();
4006
+ return { close };
4007
+ }
4008
+
4009
+ // src/index.ts
4010
+ program.name("meg-tunnel").description("Expose local servers to the internet via meg-tunnels").version("1.0.0");
4011
+ program.command("http <port>").description("Create an HTTP tunnel to localhost:<port>").option("-s, --subdomain <subdomain>", "Use a specific subdomain").option("-a, --auth <user:pass>", "Enable basic auth").option("-r, --rate-limit <rpm>", "Max requests per minute", parseInt).option("--api-key <key>", "API key (overrides config)").option("--server <url>", "WebSocket server URL (overrides config)").action((portStr, opts) => {
4012
+ const port = parseInt(portStr, 10);
4013
+ if (isNaN(port) || port < 1 || port > 65535) {
4014
+ console.error(source_default.red("Invalid port number"));
4015
+ process.exit(1);
4016
+ }
4017
+ const apiKey = opts.apiKey ?? getApiKey();
4018
+ if (!apiKey) {
4019
+ console.error(source_default.red("No API key configured. Run: meg-tunnel config set-api-key <key>"));
4020
+ process.exit(1);
4021
+ }
4022
+ const serverUrl = opts.server ?? getServerUrl();
4023
+ let auth;
4024
+ if (opts.auth) {
4025
+ const [user, pass] = opts.auth.split(":");
4026
+ if (!user || !pass) {
4027
+ console.error(source_default.red("Auth must be in format user:pass"));
4028
+ process.exit(1);
4029
+ }
4030
+ auth = { user, pass };
4031
+ }
4032
+ console.log(source_default.bold("\n meg-tunnel\n"));
4033
+ console.log(source_default.gray(` Connecting to ${serverUrl}...`));
4034
+ console.log(source_default.gray(` Forwarding to http://localhost:${port}
4035
+ `));
4036
+ const tunnel = createTunnel({
4037
+ port,
4038
+ serverUrl,
4039
+ apiKey,
4040
+ subdomain: opts.subdomain,
4041
+ auth,
4042
+ rateLimit: opts.rateLimit,
4043
+ onRegistered: (info) => {
4044
+ console.log(source_default.green(" Tunnel established!\n"));
4045
+ console.log(` ${source_default.bold("Public URL:")} ${source_default.cyan(info.url)}`);
4046
+ console.log(` ${source_default.bold("Subdomain:")} ${info.subdomain}`);
4047
+ console.log(` ${source_default.bold("Tunnel ID:")} ${source_default.gray(info.tunnelId)}`);
4048
+ console.log(` ${source_default.bold("Forwarding:")} ${source_default.yellow(`http://localhost:${port}`)}`);
4049
+ if (auth) console.log(` ${source_default.bold("Auth:")} Basic auth enabled`);
4050
+ if (opts.rateLimit) console.log(` ${source_default.bold("Rate limit:")} ${opts.rateLimit} req/min`);
4051
+ console.log(source_default.gray("\n Press Ctrl+C to stop\n"));
4052
+ console.log(source_default.gray(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n"));
4053
+ },
4054
+ onRequest: (info) => {
4055
+ const statusColor = info.statusCode < 300 ? source_default.green : info.statusCode < 400 ? source_default.yellow : source_default.red;
4056
+ const timestamp = (/* @__PURE__ */ new Date()).toLocaleTimeString();
4057
+ console.log(
4058
+ ` ${source_default.gray(timestamp)} ${source_default.bold(info.method.padEnd(7))} ${info.path.padEnd(40)} ${statusColor(String(info.statusCode))} ${source_default.gray(`${info.duration}ms`)}`
4059
+ );
4060
+ },
4061
+ onDisconnect: () => {
4062
+ console.log(source_default.yellow("\n Disconnected. Reconnecting..."));
4063
+ },
4064
+ onError: (error) => {
4065
+ console.error(source_default.red(` Error: ${error}`));
4066
+ }
4067
+ });
4068
+ process.on("SIGINT", () => {
4069
+ console.log(source_default.gray("\n\n Shutting down tunnel..."));
4070
+ tunnel.close();
4071
+ process.exit(0);
4072
+ });
4073
+ process.on("SIGTERM", () => {
4074
+ tunnel.close();
4075
+ process.exit(0);
4076
+ });
4077
+ });
4078
+ var configCmd = program.command("config").description("Manage CLI configuration");
4079
+ configCmd.command("set-api-key <key>").description("Set the API key for authentication").action((key) => {
4080
+ const config = loadConfig();
4081
+ config.apiKey = key;
4082
+ saveConfig(config);
4083
+ console.log(source_default.green("API key saved"));
4084
+ });
4085
+ configCmd.command("set-server <url>").description("Set the WebSocket server URL").action((url) => {
4086
+ const config = loadConfig();
4087
+ config.serverUrl = url;
4088
+ saveConfig(config);
4089
+ console.log(source_default.green(`Server URL set to ${url}`));
4090
+ });
4091
+ configCmd.command("show").description("Show current configuration").action(() => {
4092
+ const config = loadConfig();
4093
+ console.log(source_default.bold("\n meg-tunnel configuration\n"));
4094
+ console.log(` API key: ${config.apiKey ? source_default.green(`${config.apiKey.slice(0, 10)}...`) : source_default.gray("not set")}`);
4095
+ console.log(` Server: ${config.serverUrl ?? source_default.gray("default")}`);
4096
+ console.log();
4097
+ });
4098
+ program.command("status").description("Show active tunnels").action(() => {
4099
+ console.log(source_default.gray("Use the dashboard to view active tunnels."));
4100
+ });
4101
+ program.parse();