@saga-ai/cli 0.1.0 → 0.1.1

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