@cohaku/cli 0.2.6

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