@cxyhhhhh/qqbot-cli 0.1.0-dev.202606011703 → 0.1.0-dev.202606011733

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