@tplog/zendcli 1.2.0 → 1.3.0

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