@agentscope-ai/chat 1.1.29 → 1.1.30

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