@moxt-ai/mobius 0.0.88 → 0.0.90

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/cli.js CHANGED
@@ -10,10 +10,3378 @@ import { constants as constants2 } from "node:fs";
10
10
  import { mkdir as mkdir6, open as open7 } from "node:fs/promises";
11
11
  import { resolve as resolve7 } from "node:path";
12
12
 
13
+ // ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/error.js
14
+ var CommanderError = 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 InvalidArgumentError = class extends CommanderError {
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
+
42
+ // ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/argument.js
43
+ var Argument = class {
44
+ /**
45
+ * Initialize a new command argument with the given name and description.
46
+ * The default is that the argument is required, and you can explicitly
47
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
48
+ *
49
+ * @param {string} name
50
+ * @param {string} [description]
51
+ */
52
+ constructor(name, description) {
53
+ this.description = description || "";
54
+ this.variadic = false;
55
+ this.parseArg = void 0;
56
+ this.defaultValue = void 0;
57
+ this.defaultValueDescription = void 0;
58
+ this.argChoices = void 0;
59
+ switch (name[0]) {
60
+ case "<":
61
+ this.required = true;
62
+ this._name = name.slice(1, -1);
63
+ break;
64
+ case "[":
65
+ this.required = false;
66
+ this._name = name.slice(1, -1);
67
+ break;
68
+ default:
69
+ this.required = true;
70
+ this._name = name;
71
+ break;
72
+ }
73
+ if (this._name.endsWith("...")) {
74
+ this.variadic = true;
75
+ this._name = this._name.slice(0, -3);
76
+ }
77
+ }
78
+ /**
79
+ * Return argument name.
80
+ *
81
+ * @return {string}
82
+ */
83
+ name() {
84
+ return this._name;
85
+ }
86
+ /**
87
+ * @package
88
+ */
89
+ _collectValue(value, previous2) {
90
+ if (previous2 === this.defaultValue || !Array.isArray(previous2)) {
91
+ return [value];
92
+ }
93
+ previous2.push(value);
94
+ return previous2;
95
+ }
96
+ /**
97
+ * Set the default value, and optionally supply the description to be displayed in the help.
98
+ *
99
+ * @param {*} value
100
+ * @param {string} [description]
101
+ * @return {Argument}
102
+ */
103
+ default(value, description) {
104
+ this.defaultValue = value;
105
+ this.defaultValueDescription = description;
106
+ return this;
107
+ }
108
+ /**
109
+ * Set the custom handler for processing CLI command arguments into argument values.
110
+ *
111
+ * @param {Function} [fn]
112
+ * @return {Argument}
113
+ */
114
+ argParser(fn) {
115
+ this.parseArg = fn;
116
+ return this;
117
+ }
118
+ /**
119
+ * Only allow argument value to be one of choices.
120
+ *
121
+ * @param {string[]} values
122
+ * @return {Argument}
123
+ */
124
+ choices(values) {
125
+ this.argChoices = values.slice();
126
+ this.parseArg = (arg, previous2) => {
127
+ if (!this.argChoices.includes(arg)) {
128
+ throw new InvalidArgumentError(
129
+ `Allowed choices are ${this.argChoices.join(", ")}.`
130
+ );
131
+ }
132
+ if (this.variadic) {
133
+ return this._collectValue(arg, previous2);
134
+ }
135
+ return arg;
136
+ };
137
+ return this;
138
+ }
139
+ /**
140
+ * Make argument required.
141
+ *
142
+ * @returns {Argument}
143
+ */
144
+ argRequired() {
145
+ this.required = true;
146
+ return this;
147
+ }
148
+ /**
149
+ * Make argument optional.
150
+ *
151
+ * @returns {Argument}
152
+ */
153
+ argOptional() {
154
+ this.required = false;
155
+ return this;
156
+ }
157
+ };
158
+ function humanReadableArgName(arg) {
159
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
160
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
161
+ }
162
+
163
+ // ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/command.js
164
+ import { EventEmitter } from "node:events";
165
+ import childProcess from "node:child_process";
166
+ import path from "node:path";
167
+ import fs from "node:fs";
168
+ import process2 from "node:process";
169
+ import { stripVTControlCharacters as stripVTControlCharacters2 } from "node:util";
170
+
171
+ // ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/help.js
172
+ import { stripVTControlCharacters } from "node:util";
173
+ var Help = class {
174
+ constructor() {
175
+ this.helpWidth = void 0;
176
+ this.minWidthToWrap = 40;
177
+ this.sortSubcommands = false;
178
+ this.sortOptions = false;
179
+ this.showGlobalOptions = false;
180
+ }
181
+ /**
182
+ * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
183
+ * and just before calling `formatHelp()`.
184
+ *
185
+ * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
186
+ *
187
+ * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
188
+ */
189
+ prepareContext(contextOptions) {
190
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
191
+ }
192
+ /**
193
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
194
+ *
195
+ * @param {Command} cmd
196
+ * @returns {Command[]}
197
+ */
198
+ visibleCommands(cmd) {
199
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
200
+ const helpCommand = cmd._getHelpCommand();
201
+ if (helpCommand && !helpCommand._hidden) {
202
+ visibleCommands.push(helpCommand);
203
+ }
204
+ if (this.sortSubcommands) {
205
+ visibleCommands.sort((a, b) => {
206
+ return a.name().localeCompare(b.name());
207
+ });
208
+ }
209
+ return visibleCommands;
210
+ }
211
+ /**
212
+ * Compare options for sort.
213
+ *
214
+ * @param {Option} a
215
+ * @param {Option} b
216
+ * @returns {number}
217
+ */
218
+ compareOptions(a, b) {
219
+ const getSortKey = (option) => {
220
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
221
+ };
222
+ return getSortKey(a).localeCompare(getSortKey(b));
223
+ }
224
+ /**
225
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
226
+ *
227
+ * @param {Command} cmd
228
+ * @returns {Option[]}
229
+ */
230
+ visibleOptions(cmd) {
231
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
232
+ const helpOption = cmd._getHelpOption();
233
+ if (helpOption && !helpOption.hidden) {
234
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
235
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
236
+ if (!removeShort && !removeLong) {
237
+ visibleOptions.push(helpOption);
238
+ } else if (helpOption.long && !removeLong) {
239
+ visibleOptions.push(
240
+ cmd.createOption(helpOption.long, helpOption.description)
241
+ );
242
+ } else if (helpOption.short && !removeShort) {
243
+ visibleOptions.push(
244
+ cmd.createOption(helpOption.short, helpOption.description)
245
+ );
246
+ }
247
+ }
248
+ if (this.sortOptions) {
249
+ visibleOptions.sort(this.compareOptions);
250
+ }
251
+ return visibleOptions;
252
+ }
253
+ /**
254
+ * Get an array of the visible global options. (Not including help.)
255
+ *
256
+ * @param {Command} cmd
257
+ * @returns {Option[]}
258
+ */
259
+ visibleGlobalOptions(cmd) {
260
+ if (!this.showGlobalOptions) return [];
261
+ const globalOptions = [];
262
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
263
+ const visibleOptions = ancestorCmd.options.filter(
264
+ (option) => !option.hidden
265
+ );
266
+ globalOptions.push(...visibleOptions);
267
+ }
268
+ if (this.sortOptions) {
269
+ globalOptions.sort(this.compareOptions);
270
+ }
271
+ return globalOptions;
272
+ }
273
+ /**
274
+ * Get an array of the arguments if any have a description.
275
+ *
276
+ * @param {Command} cmd
277
+ * @returns {Argument[]}
278
+ */
279
+ visibleArguments(cmd) {
280
+ if (cmd._argsDescription) {
281
+ cmd.registeredArguments.forEach((argument) => {
282
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
283
+ });
284
+ }
285
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
286
+ return cmd.registeredArguments;
287
+ }
288
+ return [];
289
+ }
290
+ /**
291
+ * Get the command term to show in the list of subcommands.
292
+ *
293
+ * @param {Command} cmd
294
+ * @returns {string}
295
+ */
296
+ subcommandTerm(cmd) {
297
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
298
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
299
+ (args ? " " + args : "");
300
+ }
301
+ /**
302
+ * Get the option term to show in the list of options.
303
+ *
304
+ * @param {Option} option
305
+ * @returns {string}
306
+ */
307
+ optionTerm(option) {
308
+ return option.flags;
309
+ }
310
+ /**
311
+ * Get the argument term to show in the list of arguments.
312
+ *
313
+ * @param {Argument} argument
314
+ * @returns {string}
315
+ */
316
+ argumentTerm(argument) {
317
+ return argument.name();
318
+ }
319
+ /**
320
+ * Get the longest command term length.
321
+ *
322
+ * @param {Command} cmd
323
+ * @param {Help} helper
324
+ * @returns {number}
325
+ */
326
+ longestSubcommandTermLength(cmd, helper) {
327
+ return helper.visibleCommands(cmd).reduce((max, command) => {
328
+ return Math.max(
329
+ max,
330
+ this.displayWidth(
331
+ helper.styleSubcommandTerm(helper.subcommandTerm(command))
332
+ )
333
+ );
334
+ }, 0);
335
+ }
336
+ /**
337
+ * Get the longest option term length.
338
+ *
339
+ * @param {Command} cmd
340
+ * @param {Help} helper
341
+ * @returns {number}
342
+ */
343
+ longestOptionTermLength(cmd, helper) {
344
+ return helper.visibleOptions(cmd).reduce((max, option) => {
345
+ return Math.max(
346
+ max,
347
+ this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
348
+ );
349
+ }, 0);
350
+ }
351
+ /**
352
+ * Get the longest global option term length.
353
+ *
354
+ * @param {Command} cmd
355
+ * @param {Help} helper
356
+ * @returns {number}
357
+ */
358
+ longestGlobalOptionTermLength(cmd, helper) {
359
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
360
+ return Math.max(
361
+ max,
362
+ this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
363
+ );
364
+ }, 0);
365
+ }
366
+ /**
367
+ * Get the longest argument term length.
368
+ *
369
+ * @param {Command} cmd
370
+ * @param {Help} helper
371
+ * @returns {number}
372
+ */
373
+ longestArgumentTermLength(cmd, helper) {
374
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
375
+ return Math.max(
376
+ max,
377
+ this.displayWidth(
378
+ helper.styleArgumentTerm(helper.argumentTerm(argument))
379
+ )
380
+ );
381
+ }, 0);
382
+ }
383
+ /**
384
+ * Get the command usage to be displayed at the top of the built-in help.
385
+ *
386
+ * @param {Command} cmd
387
+ * @returns {string}
388
+ */
389
+ commandUsage(cmd) {
390
+ let cmdName = cmd._name;
391
+ if (cmd._aliases[0]) {
392
+ cmdName = cmdName + "|" + cmd._aliases[0];
393
+ }
394
+ let ancestorCmdNames = "";
395
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
396
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
397
+ }
398
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
399
+ }
400
+ /**
401
+ * Get the description for the command.
402
+ *
403
+ * @param {Command} cmd
404
+ * @returns {string}
405
+ */
406
+ commandDescription(cmd) {
407
+ return cmd.description();
408
+ }
409
+ /**
410
+ * Get the subcommand summary to show in the list of subcommands.
411
+ * (Fallback to description for backwards compatibility.)
412
+ *
413
+ * @param {Command} cmd
414
+ * @returns {string}
415
+ */
416
+ subcommandDescription(cmd) {
417
+ return cmd.summary() || cmd.description();
418
+ }
419
+ /**
420
+ * Get the option description to show in the list of options.
421
+ *
422
+ * @param {Option} option
423
+ * @return {string}
424
+ */
425
+ optionDescription(option) {
426
+ const extraInfo = [];
427
+ if (option.argChoices) {
428
+ extraInfo.push(
429
+ // use stringify to match the display of the default value
430
+ `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
431
+ );
432
+ }
433
+ if (option.defaultValue !== void 0) {
434
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
435
+ if (showDefault) {
436
+ extraInfo.push(
437
+ `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`
438
+ );
439
+ }
440
+ }
441
+ if (option.presetArg !== void 0 && option.optional) {
442
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
443
+ }
444
+ if (option.envVar !== void 0) {
445
+ extraInfo.push(`env: ${option.envVar}`);
446
+ }
447
+ if (extraInfo.length > 0) {
448
+ const extraDescription = `(${extraInfo.join(", ")})`;
449
+ if (option.description) {
450
+ return `${option.description} ${extraDescription}`;
451
+ }
452
+ return extraDescription;
453
+ }
454
+ return option.description;
455
+ }
456
+ /**
457
+ * Get the argument description to show in the list of arguments.
458
+ *
459
+ * @param {Argument} argument
460
+ * @return {string}
461
+ */
462
+ argumentDescription(argument) {
463
+ const extraInfo = [];
464
+ if (argument.argChoices) {
465
+ extraInfo.push(
466
+ // use stringify to match the display of the default value
467
+ `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
468
+ );
469
+ }
470
+ if (argument.defaultValue !== void 0) {
471
+ extraInfo.push(
472
+ `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`
473
+ );
474
+ }
475
+ if (extraInfo.length > 0) {
476
+ const extraDescription = `(${extraInfo.join(", ")})`;
477
+ if (argument.description) {
478
+ return `${argument.description} ${extraDescription}`;
479
+ }
480
+ return extraDescription;
481
+ }
482
+ return argument.description;
483
+ }
484
+ /**
485
+ * Format a list of items, given a heading and an array of formatted items.
486
+ *
487
+ * @param {string} heading
488
+ * @param {string[]} items
489
+ * @param {Help} helper
490
+ * @returns string[]
491
+ */
492
+ formatItemList(heading, items, helper) {
493
+ if (items.length === 0) return [];
494
+ return [helper.styleTitle(heading), ...items, ""];
495
+ }
496
+ /**
497
+ * Group items by their help group heading.
498
+ *
499
+ * @param {Command[] | Option[]} unsortedItems
500
+ * @param {Command[] | Option[]} visibleItems
501
+ * @param {Function} getGroup
502
+ * @returns {Map<string, Command[] | Option[]>}
503
+ */
504
+ groupItems(unsortedItems, visibleItems, getGroup) {
505
+ const result = /* @__PURE__ */ new Map();
506
+ unsortedItems.forEach((item) => {
507
+ const group = getGroup(item);
508
+ if (!result.has(group)) result.set(group, []);
509
+ });
510
+ visibleItems.forEach((item) => {
511
+ const group = getGroup(item);
512
+ if (!result.has(group)) {
513
+ result.set(group, []);
514
+ }
515
+ result.get(group).push(item);
516
+ });
517
+ return result;
518
+ }
519
+ /**
520
+ * Generate the built-in help text.
521
+ *
522
+ * @param {Command} cmd
523
+ * @param {Help} helper
524
+ * @returns {string}
525
+ */
526
+ formatHelp(cmd, helper) {
527
+ const termWidth = helper.padWidth(cmd, helper);
528
+ const helpWidth = helper.helpWidth ?? 80;
529
+ function callFormatItem(term, description) {
530
+ return helper.formatItem(term, termWidth, description, helper);
531
+ }
532
+ let output2 = [
533
+ `${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
534
+ ""
535
+ ];
536
+ const commandDescription = helper.commandDescription(cmd);
537
+ if (commandDescription.length > 0) {
538
+ output2 = output2.concat([
539
+ helper.boxWrap(
540
+ helper.styleCommandDescription(commandDescription),
541
+ helpWidth
542
+ ),
543
+ ""
544
+ ]);
545
+ }
546
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
547
+ return callFormatItem(
548
+ helper.styleArgumentTerm(helper.argumentTerm(argument)),
549
+ helper.styleArgumentDescription(helper.argumentDescription(argument))
550
+ );
551
+ });
552
+ output2 = output2.concat(
553
+ this.formatItemList("Arguments:", argumentList, helper)
554
+ );
555
+ const optionGroups = this.groupItems(
556
+ cmd.options,
557
+ helper.visibleOptions(cmd),
558
+ (option) => option.helpGroupHeading ?? "Options:"
559
+ );
560
+ optionGroups.forEach((options, group) => {
561
+ const optionList = options.map((option) => {
562
+ return callFormatItem(
563
+ helper.styleOptionTerm(helper.optionTerm(option)),
564
+ helper.styleOptionDescription(helper.optionDescription(option))
565
+ );
566
+ });
567
+ output2 = output2.concat(this.formatItemList(group, optionList, helper));
568
+ });
569
+ if (helper.showGlobalOptions) {
570
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
571
+ return callFormatItem(
572
+ helper.styleOptionTerm(helper.optionTerm(option)),
573
+ helper.styleOptionDescription(helper.optionDescription(option))
574
+ );
575
+ });
576
+ output2 = output2.concat(
577
+ this.formatItemList("Global Options:", globalOptionList, helper)
578
+ );
579
+ }
580
+ const commandGroups = this.groupItems(
581
+ cmd.commands,
582
+ helper.visibleCommands(cmd),
583
+ (sub) => sub.helpGroup() || "Commands:"
584
+ );
585
+ commandGroups.forEach((commands, group) => {
586
+ const commandList = commands.map((sub) => {
587
+ return callFormatItem(
588
+ helper.styleSubcommandTerm(helper.subcommandTerm(sub)),
589
+ helper.styleSubcommandDescription(helper.subcommandDescription(sub))
590
+ );
591
+ });
592
+ output2 = output2.concat(this.formatItemList(group, commandList, helper));
593
+ });
594
+ return output2.join("\n");
595
+ }
596
+ /**
597
+ * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
598
+ *
599
+ * @param {string} str
600
+ * @returns {number}
601
+ */
602
+ displayWidth(str) {
603
+ return stripVTControlCharacters(str).length;
604
+ }
605
+ /**
606
+ * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
607
+ *
608
+ * @param {string} str
609
+ * @returns {string}
610
+ */
611
+ styleTitle(str) {
612
+ return str;
613
+ }
614
+ styleUsage(str) {
615
+ return str.split(" ").map((word) => {
616
+ if (word === "[options]") return this.styleOptionText(word);
617
+ if (word === "[command]") return this.styleSubcommandText(word);
618
+ if (word[0] === "[" || word[0] === "<")
619
+ return this.styleArgumentText(word);
620
+ return this.styleCommandText(word);
621
+ }).join(" ");
622
+ }
623
+ styleCommandDescription(str) {
624
+ return this.styleDescriptionText(str);
625
+ }
626
+ styleOptionDescription(str) {
627
+ return this.styleDescriptionText(str);
628
+ }
629
+ styleSubcommandDescription(str) {
630
+ return this.styleDescriptionText(str);
631
+ }
632
+ styleArgumentDescription(str) {
633
+ return this.styleDescriptionText(str);
634
+ }
635
+ styleDescriptionText(str) {
636
+ return str;
637
+ }
638
+ styleOptionTerm(str) {
639
+ return this.styleOptionText(str);
640
+ }
641
+ styleSubcommandTerm(str) {
642
+ return str.split(" ").map((word) => {
643
+ if (word === "[options]") return this.styleOptionText(word);
644
+ if (word[0] === "[" || word[0] === "<")
645
+ return this.styleArgumentText(word);
646
+ return this.styleSubcommandText(word);
647
+ }).join(" ");
648
+ }
649
+ styleArgumentTerm(str) {
650
+ return this.styleArgumentText(str);
651
+ }
652
+ styleOptionText(str) {
653
+ return str;
654
+ }
655
+ styleArgumentText(str) {
656
+ return str;
657
+ }
658
+ styleSubcommandText(str) {
659
+ return str;
660
+ }
661
+ styleCommandText(str) {
662
+ return str;
663
+ }
664
+ /**
665
+ * Calculate the pad width from the maximum term length.
666
+ *
667
+ * @param {Command} cmd
668
+ * @param {Help} helper
669
+ * @returns {number}
670
+ */
671
+ padWidth(cmd, helper) {
672
+ return Math.max(
673
+ helper.longestOptionTermLength(cmd, helper),
674
+ helper.longestGlobalOptionTermLength(cmd, helper),
675
+ helper.longestSubcommandTermLength(cmd, helper),
676
+ helper.longestArgumentTermLength(cmd, helper)
677
+ );
678
+ }
679
+ /**
680
+ * Detect manually wrapped and indented strings by checking for line break followed by whitespace.
681
+ *
682
+ * @param {string} str
683
+ * @returns {boolean}
684
+ */
685
+ preformatted(str) {
686
+ return /\n[^\S\r\n]/.test(str);
687
+ }
688
+ /**
689
+ * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
690
+ *
691
+ * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
692
+ * TTT DDD DDDD
693
+ * DD DDD
694
+ *
695
+ * @param {string} term
696
+ * @param {number} termWidth
697
+ * @param {string} description
698
+ * @param {Help} helper
699
+ * @returns {string}
700
+ */
701
+ formatItem(term, termWidth, description, helper) {
702
+ const itemIndent = 2;
703
+ const itemIndentStr = " ".repeat(itemIndent);
704
+ if (!description) return itemIndentStr + term;
705
+ const paddedTerm = term.padEnd(
706
+ termWidth + term.length - helper.displayWidth(term)
707
+ );
708
+ const spacerWidth = 2;
709
+ const helpWidth = this.helpWidth ?? 80;
710
+ const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
711
+ let formattedDescription;
712
+ if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
713
+ formattedDescription = description;
714
+ } else {
715
+ const wrappedDescription = helper.boxWrap(description, remainingWidth);
716
+ formattedDescription = wrappedDescription.replace(
717
+ /\n/g,
718
+ "\n" + " ".repeat(termWidth + spacerWidth)
719
+ );
720
+ }
721
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
722
+ ${itemIndentStr}`);
723
+ }
724
+ /**
725
+ * Wrap a string at whitespace, preserving existing line breaks.
726
+ * Wrapping is skipped if the width is less than `minWidthToWrap`.
727
+ *
728
+ * @param {string} str
729
+ * @param {number} width
730
+ * @returns {string}
731
+ */
732
+ boxWrap(str, width) {
733
+ if (width < this.minWidthToWrap) return str;
734
+ const rawLines = str.split(/\r\n|\n/);
735
+ const chunkPattern = /[\s]*[^\s]+/g;
736
+ const wrappedLines = [];
737
+ rawLines.forEach((line) => {
738
+ const chunks = line.match(chunkPattern);
739
+ if (chunks === null) {
740
+ wrappedLines.push("");
741
+ return;
742
+ }
743
+ let sumChunks = [chunks.shift()];
744
+ let sumWidth = this.displayWidth(sumChunks[0]);
745
+ chunks.forEach((chunk) => {
746
+ const visibleWidth = this.displayWidth(chunk);
747
+ if (sumWidth + visibleWidth <= width) {
748
+ sumChunks.push(chunk);
749
+ sumWidth += visibleWidth;
750
+ return;
751
+ }
752
+ wrappedLines.push(sumChunks.join(""));
753
+ const nextChunk = chunk.trimStart();
754
+ sumChunks = [nextChunk];
755
+ sumWidth = this.displayWidth(nextChunk);
756
+ });
757
+ wrappedLines.push(sumChunks.join(""));
758
+ });
759
+ return wrappedLines.join("\n");
760
+ }
761
+ };
762
+
763
+ // ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/option.js
764
+ var Option = class {
765
+ /**
766
+ * Initialize a new `Option` with the given `flags` and `description`.
767
+ *
768
+ * @param {string} flags
769
+ * @param {string} [description]
770
+ */
771
+ constructor(flags, description) {
772
+ this.flags = flags;
773
+ this.description = description || "";
774
+ this.required = flags.includes("<");
775
+ this.optional = flags.includes("[");
776
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
777
+ this.mandatory = false;
778
+ const optionFlags = splitOptionFlags(flags);
779
+ this.short = optionFlags.shortFlag;
780
+ this.long = optionFlags.longFlag;
781
+ this.negate = false;
782
+ if (this.long) {
783
+ this.negate = this.long.startsWith("--no-");
784
+ }
785
+ this.defaultValue = void 0;
786
+ this.defaultValueDescription = void 0;
787
+ this.presetArg = void 0;
788
+ this.envVar = void 0;
789
+ this.parseArg = void 0;
790
+ this.hidden = false;
791
+ this.argChoices = void 0;
792
+ this.conflictsWith = [];
793
+ this.implied = void 0;
794
+ this.helpGroupHeading = void 0;
795
+ }
796
+ /**
797
+ * Set the default value, and optionally supply the description to be displayed in the help.
798
+ *
799
+ * @param {*} value
800
+ * @param {string} [description]
801
+ * @return {Option}
802
+ */
803
+ default(value, description) {
804
+ this.defaultValue = value;
805
+ this.defaultValueDescription = description;
806
+ return this;
807
+ }
808
+ /**
809
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
810
+ * The custom processing (parseArg) is called.
811
+ *
812
+ * @example
813
+ * new Option('--color').default('GREYSCALE').preset('RGB');
814
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
815
+ *
816
+ * @param {*} arg
817
+ * @return {Option}
818
+ */
819
+ preset(arg) {
820
+ this.presetArg = arg;
821
+ return this;
822
+ }
823
+ /**
824
+ * Add option name(s) that conflict with this option.
825
+ * An error will be displayed if conflicting options are found during parsing.
826
+ *
827
+ * @example
828
+ * new Option('--rgb').conflicts('cmyk');
829
+ * new Option('--js').conflicts(['ts', 'jsx']);
830
+ *
831
+ * @param {(string | string[])} names
832
+ * @return {Option}
833
+ */
834
+ conflicts(names) {
835
+ this.conflictsWith = this.conflictsWith.concat(names);
836
+ return this;
837
+ }
838
+ /**
839
+ * Specify implied option values for when this option is set and the implied options are not.
840
+ *
841
+ * The custom processing (parseArg) is not called on the implied values.
842
+ *
843
+ * @example
844
+ * program
845
+ * .addOption(new Option('--log', 'write logging information to file'))
846
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
847
+ *
848
+ * @param {object} impliedOptionValues
849
+ * @return {Option}
850
+ */
851
+ implies(impliedOptionValues) {
852
+ let newImplied = impliedOptionValues;
853
+ if (typeof impliedOptionValues === "string") {
854
+ newImplied = { [impliedOptionValues]: true };
855
+ }
856
+ this.implied = Object.assign(this.implied || {}, newImplied);
857
+ return this;
858
+ }
859
+ /**
860
+ * Set environment variable to check for option value.
861
+ *
862
+ * An environment variable is only used if when processed the current option value is
863
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
864
+ *
865
+ * @param {string} name
866
+ * @return {Option}
867
+ */
868
+ env(name) {
869
+ this.envVar = name;
870
+ return this;
871
+ }
872
+ /**
873
+ * Set the custom handler for processing CLI option arguments into option values.
874
+ *
875
+ * @param {Function} [fn]
876
+ * @return {Option}
877
+ */
878
+ argParser(fn) {
879
+ this.parseArg = fn;
880
+ return this;
881
+ }
882
+ /**
883
+ * Whether the option is mandatory and must have a value after parsing.
884
+ *
885
+ * @param {boolean} [mandatory=true]
886
+ * @return {Option}
887
+ */
888
+ makeOptionMandatory(mandatory = true) {
889
+ this.mandatory = !!mandatory;
890
+ return this;
891
+ }
892
+ /**
893
+ * Hide option in help.
894
+ *
895
+ * @param {boolean} [hide=true]
896
+ * @return {Option}
897
+ */
898
+ hideHelp(hide2 = true) {
899
+ this.hidden = !!hide2;
900
+ return this;
901
+ }
902
+ /**
903
+ * @package
904
+ */
905
+ _collectValue(value, previous2) {
906
+ if (previous2 === this.defaultValue || !Array.isArray(previous2)) {
907
+ return [value];
908
+ }
909
+ previous2.push(value);
910
+ return previous2;
911
+ }
912
+ /**
913
+ * Only allow option value to be one of choices.
914
+ *
915
+ * @param {string[]} values
916
+ * @return {Option}
917
+ */
918
+ choices(values) {
919
+ this.argChoices = values.slice();
920
+ this.parseArg = (arg, previous2) => {
921
+ if (!this.argChoices.includes(arg)) {
922
+ throw new InvalidArgumentError(
923
+ `Allowed choices are ${this.argChoices.join(", ")}.`
924
+ );
925
+ }
926
+ if (this.variadic) {
927
+ return this._collectValue(arg, previous2);
928
+ }
929
+ return arg;
930
+ };
931
+ return this;
932
+ }
933
+ /**
934
+ * Return option name.
935
+ *
936
+ * @return {string}
937
+ */
938
+ name() {
939
+ if (this.long) {
940
+ return this.long.replace(/^--/, "");
941
+ }
942
+ return this.short.replace(/^-/, "");
943
+ }
944
+ /**
945
+ * Return option name, in a camelcase format that can be used
946
+ * as an object attribute key.
947
+ *
948
+ * @return {string}
949
+ */
950
+ attributeName() {
951
+ if (this.negate) {
952
+ return camelcase(this.name().replace(/^no-/, ""));
953
+ }
954
+ return camelcase(this.name());
955
+ }
956
+ /**
957
+ * Set the help group heading.
958
+ *
959
+ * @param {string} heading
960
+ * @return {Option}
961
+ */
962
+ helpGroup(heading) {
963
+ this.helpGroupHeading = heading;
964
+ return this;
965
+ }
966
+ /**
967
+ * Check if `arg` matches the short or long flag.
968
+ *
969
+ * @param {string} arg
970
+ * @return {boolean}
971
+ * @package
972
+ */
973
+ is(arg) {
974
+ return this.short === arg || this.long === arg;
975
+ }
976
+ /**
977
+ * Return whether a boolean option.
978
+ *
979
+ * Options are one of boolean, negated, required argument, or optional argument.
980
+ *
981
+ * @return {boolean}
982
+ * @package
983
+ */
984
+ isBoolean() {
985
+ return !this.required && !this.optional && !this.negate;
986
+ }
987
+ };
988
+ var DualOptions = class {
989
+ /**
990
+ * @param {Option[]} options
991
+ */
992
+ constructor(options) {
993
+ this.positiveOptions = /* @__PURE__ */ new Map();
994
+ this.negativeOptions = /* @__PURE__ */ new Map();
995
+ this.dualOptions = /* @__PURE__ */ new Set();
996
+ options.forEach((option) => {
997
+ if (option.negate) {
998
+ this.negativeOptions.set(option.attributeName(), option);
999
+ } else {
1000
+ this.positiveOptions.set(option.attributeName(), option);
1001
+ }
1002
+ });
1003
+ this.negativeOptions.forEach((value, key) => {
1004
+ if (this.positiveOptions.has(key)) {
1005
+ this.dualOptions.add(key);
1006
+ }
1007
+ });
1008
+ }
1009
+ /**
1010
+ * Did the value come from the option, and not from possible matching dual option?
1011
+ *
1012
+ * @param {*} value
1013
+ * @param {Option} option
1014
+ * @returns {boolean}
1015
+ */
1016
+ valueFromOption(value, option) {
1017
+ const optionKey = option.attributeName();
1018
+ if (!this.dualOptions.has(optionKey)) return true;
1019
+ const preset = this.negativeOptions.get(optionKey).presetArg;
1020
+ const negativeValue = preset !== void 0 ? preset : false;
1021
+ return option.negate === (negativeValue === value);
1022
+ }
1023
+ };
1024
+ function camelcase(str) {
1025
+ return str.split("-").reduce((str2, word) => {
1026
+ return str2 + word[0].toUpperCase() + word.slice(1);
1027
+ });
1028
+ }
1029
+ function splitOptionFlags(flags) {
1030
+ let shortFlag;
1031
+ let longFlag;
1032
+ const shortFlagExp = /^-[^-]$/;
1033
+ const longFlagExp = /^--[^-]/;
1034
+ const flagParts = flags.split(/[ |,]+/).concat("guard");
1035
+ if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
1036
+ if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
1037
+ if (!shortFlag && shortFlagExp.test(flagParts[0]))
1038
+ shortFlag = flagParts.shift();
1039
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
1040
+ shortFlag = longFlag;
1041
+ longFlag = flagParts.shift();
1042
+ }
1043
+ if (flagParts[0].startsWith("-")) {
1044
+ const unsupportedFlag = flagParts[0];
1045
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
1046
+ if (/^-[^-][^-]/.test(unsupportedFlag))
1047
+ throw new Error(
1048
+ `${baseError}
1049
+ - a short flag is a single dash and a single character
1050
+ - either use a single dash and a single character (for a short flag)
1051
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`
1052
+ );
1053
+ if (shortFlagExp.test(unsupportedFlag))
1054
+ throw new Error(`${baseError}
1055
+ - too many short flags`);
1056
+ if (longFlagExp.test(unsupportedFlag))
1057
+ throw new Error(`${baseError}
1058
+ - too many long flags`);
1059
+ throw new Error(`${baseError}
1060
+ - unrecognised flag format`);
1061
+ }
1062
+ if (shortFlag === void 0 && longFlag === void 0)
1063
+ throw new Error(
1064
+ `option creation failed due to no flags found in '${flags}'.`
1065
+ );
1066
+ return { shortFlag, longFlag };
1067
+ }
1068
+
1069
+ // ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/suggestSimilar.js
1070
+ var maxDistance = 3;
1071
+ function editDistance(a, b) {
1072
+ if (Math.abs(a.length - b.length) > maxDistance)
1073
+ return Math.max(a.length, b.length);
1074
+ const d = [];
1075
+ for (let i = 0; i <= a.length; i++) {
1076
+ d[i] = [i];
1077
+ }
1078
+ for (let j = 0; j <= b.length; j++) {
1079
+ d[0][j] = j;
1080
+ }
1081
+ for (let j = 1; j <= b.length; j++) {
1082
+ for (let i = 1; i <= a.length; i++) {
1083
+ let cost;
1084
+ if (a[i - 1] === b[j - 1]) {
1085
+ cost = 0;
1086
+ } else {
1087
+ cost = 1;
1088
+ }
1089
+ d[i][j] = Math.min(
1090
+ d[i - 1][j] + 1,
1091
+ // deletion
1092
+ d[i][j - 1] + 1,
1093
+ // insertion
1094
+ d[i - 1][j - 1] + cost
1095
+ // substitution
1096
+ );
1097
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
1098
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
1099
+ }
1100
+ }
1101
+ }
1102
+ return d[a.length][b.length];
1103
+ }
1104
+ function suggestSimilar(word, candidates) {
1105
+ if (!candidates || candidates.length === 0) return "";
1106
+ candidates = Array.from(new Set(candidates));
1107
+ const searchingOptions = word.startsWith("--");
1108
+ if (searchingOptions) {
1109
+ word = word.slice(2);
1110
+ candidates = candidates.map((candidate) => candidate.slice(2));
1111
+ }
1112
+ let similar = [];
1113
+ let bestDistance = maxDistance;
1114
+ const minSimilarity = 0.4;
1115
+ candidates.forEach((candidate) => {
1116
+ if (candidate.length <= 1) return;
1117
+ const distance = editDistance(word, candidate);
1118
+ const length = Math.max(word.length, candidate.length);
1119
+ const similarity = (length - distance) / length;
1120
+ if (similarity > minSimilarity) {
1121
+ if (distance < bestDistance) {
1122
+ bestDistance = distance;
1123
+ similar = [candidate];
1124
+ } else if (distance === bestDistance) {
1125
+ similar.push(candidate);
1126
+ }
1127
+ }
1128
+ });
1129
+ similar.sort((a, b) => a.localeCompare(b));
1130
+ if (searchingOptions) {
1131
+ similar = similar.map((candidate) => `--${candidate}`);
1132
+ }
1133
+ if (similar.length > 1) {
1134
+ return `
1135
+ (Did you mean one of ${similar.join(", ")}?)`;
1136
+ }
1137
+ if (similar.length === 1) {
1138
+ return `
1139
+ (Did you mean ${similar[0]}?)`;
1140
+ }
1141
+ return "";
1142
+ }
1143
+
1144
+ // ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/command.js
1145
+ var Command = class _Command extends EventEmitter {
1146
+ /**
1147
+ * Initialize a new `Command`.
1148
+ *
1149
+ * @param {string} [name]
1150
+ */
1151
+ constructor(name) {
1152
+ super();
1153
+ this.commands = [];
1154
+ this.options = [];
1155
+ this.parent = null;
1156
+ this._allowUnknownOption = false;
1157
+ this._allowExcessArguments = false;
1158
+ this.registeredArguments = [];
1159
+ this._args = this.registeredArguments;
1160
+ this.args = [];
1161
+ this.rawArgs = [];
1162
+ this.processedArgs = [];
1163
+ this._scriptPath = null;
1164
+ this._name = name || "";
1165
+ this._optionValues = {};
1166
+ this._optionValueSources = {};
1167
+ this._storeOptionsAsProperties = false;
1168
+ this._actionHandler = null;
1169
+ this._executableHandler = false;
1170
+ this._executableFile = null;
1171
+ this._executableDir = null;
1172
+ this._defaultCommandName = null;
1173
+ this._exitCallback = null;
1174
+ this._aliases = [];
1175
+ this._combineFlagAndOptionalValue = true;
1176
+ this._description = "";
1177
+ this._summary = "";
1178
+ this._argsDescription = void 0;
1179
+ this._enablePositionalOptions = false;
1180
+ this._passThroughOptions = false;
1181
+ this._lifeCycleHooks = {};
1182
+ this._showHelpAfterError = false;
1183
+ this._showSuggestionAfterError = true;
1184
+ this._savedState = null;
1185
+ this._outputConfiguration = {
1186
+ writeOut: (str) => process2.stdout.write(str),
1187
+ writeErr: (str) => process2.stderr.write(str),
1188
+ outputError: (str, write) => write(str),
1189
+ getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : void 0,
1190
+ getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : void 0,
1191
+ getOutHasColors: () => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()),
1192
+ getErrHasColors: () => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()),
1193
+ stripColor: (str) => stripVTControlCharacters2(str)
1194
+ };
1195
+ this._hidden = false;
1196
+ this._helpOption = void 0;
1197
+ this._addImplicitHelpCommand = void 0;
1198
+ this._helpCommand = void 0;
1199
+ this._helpConfiguration = {};
1200
+ this._helpGroupHeading = void 0;
1201
+ this._defaultCommandGroup = void 0;
1202
+ this._defaultOptionGroup = void 0;
1203
+ }
1204
+ /**
1205
+ * Copy settings that are useful to have in common across root command and subcommands.
1206
+ *
1207
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1208
+ *
1209
+ * @param {Command} sourceCommand
1210
+ * @return {Command} `this` command for chaining
1211
+ */
1212
+ copyInheritedSettings(sourceCommand) {
1213
+ this._outputConfiguration = sourceCommand._outputConfiguration;
1214
+ this._helpOption = sourceCommand._helpOption;
1215
+ this._helpCommand = sourceCommand._helpCommand;
1216
+ this._helpConfiguration = sourceCommand._helpConfiguration;
1217
+ this._exitCallback = sourceCommand._exitCallback;
1218
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1219
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1220
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
1221
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1222
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
1223
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1224
+ return this;
1225
+ }
1226
+ /**
1227
+ * @returns {Command[]}
1228
+ * @private
1229
+ */
1230
+ _getCommandAndAncestors() {
1231
+ const result = [];
1232
+ for (let command = this; command; command = command.parent) {
1233
+ result.push(command);
1234
+ }
1235
+ return result;
1236
+ }
1237
+ /**
1238
+ * Define a command.
1239
+ *
1240
+ * There are two styles of command: pay attention to where to put the description.
1241
+ *
1242
+ * @example
1243
+ * // Command implemented using action handler (description is supplied separately to `.command`)
1244
+ * program
1245
+ * .command('clone <source> [destination]')
1246
+ * .description('clone a repository into a newly created directory')
1247
+ * .action((source, destination) => {
1248
+ * console.log('clone command called');
1249
+ * });
1250
+ *
1251
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
1252
+ * program
1253
+ * .command('start <service>', 'start named service')
1254
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
1255
+ *
1256
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1257
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1258
+ * @param {object} [execOpts] - configuration options (for executable)
1259
+ * @return {Command} returns new command for action handler, or `this` for executable command
1260
+ */
1261
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1262
+ let desc = actionOptsOrExecDesc;
1263
+ let opts = execOpts;
1264
+ if (typeof desc === "object" && desc !== null) {
1265
+ opts = desc;
1266
+ desc = null;
1267
+ }
1268
+ opts = opts || {};
1269
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1270
+ const cmd = this.createCommand(name);
1271
+ if (desc) {
1272
+ cmd.description(desc);
1273
+ cmd._executableHandler = true;
1274
+ }
1275
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1276
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
1277
+ cmd._executableFile = opts.executableFile || null;
1278
+ if (args) cmd.arguments(args);
1279
+ this._registerCommand(cmd);
1280
+ cmd.parent = this;
1281
+ cmd.copyInheritedSettings(this);
1282
+ if (desc) return this;
1283
+ return cmd;
1284
+ }
1285
+ /**
1286
+ * Factory routine to create a new unattached command.
1287
+ *
1288
+ * See .command() for creating an attached subcommand, which uses this routine to
1289
+ * create the command. You can override createCommand to customise subcommands.
1290
+ *
1291
+ * @param {string} [name]
1292
+ * @return {Command} new command
1293
+ */
1294
+ createCommand(name) {
1295
+ return new _Command(name);
1296
+ }
1297
+ /**
1298
+ * You can customise the help with a subclass of Help by overriding createHelp,
1299
+ * or by overriding Help properties using configureHelp().
1300
+ *
1301
+ * @return {Help}
1302
+ */
1303
+ createHelp() {
1304
+ return Object.assign(new Help(), this.configureHelp());
1305
+ }
1306
+ /**
1307
+ * You can customise the help by overriding Help properties using configureHelp(),
1308
+ * or with a subclass of Help by overriding createHelp().
1309
+ *
1310
+ * @param {object} [configuration] - configuration options
1311
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1312
+ */
1313
+ configureHelp(configuration) {
1314
+ if (configuration === void 0) return this._helpConfiguration;
1315
+ this._helpConfiguration = configuration;
1316
+ return this;
1317
+ }
1318
+ /**
1319
+ * The default output goes to stdout and stderr. You can customise this for special
1320
+ * applications. You can also customise the display of errors by overriding outputError.
1321
+ *
1322
+ * The configuration properties are all functions:
1323
+ *
1324
+ * // change how output being written, defaults to stdout and stderr
1325
+ * writeOut(str)
1326
+ * writeErr(str)
1327
+ * // change how output being written for errors, defaults to writeErr
1328
+ * outputError(str, write) // used for displaying errors and not used for displaying help
1329
+ * // specify width for wrapping help
1330
+ * getOutHelpWidth()
1331
+ * getErrHelpWidth()
1332
+ * // color support, currently only used with Help
1333
+ * getOutHasColors()
1334
+ * getErrHasColors()
1335
+ * stripColor() // used to remove ANSI escape codes if output does not have colors
1336
+ *
1337
+ * @param {object} [configuration] - configuration options
1338
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1339
+ */
1340
+ configureOutput(configuration) {
1341
+ if (configuration === void 0) return this._outputConfiguration;
1342
+ this._outputConfiguration = {
1343
+ ...this._outputConfiguration,
1344
+ ...configuration
1345
+ };
1346
+ return this;
1347
+ }
1348
+ /**
1349
+ * Display the help or a custom message after an error occurs.
1350
+ *
1351
+ * @param {(boolean|string)} [displayHelp]
1352
+ * @return {Command} `this` command for chaining
1353
+ */
1354
+ showHelpAfterError(displayHelp = true) {
1355
+ if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
1356
+ this._showHelpAfterError = displayHelp;
1357
+ return this;
1358
+ }
1359
+ /**
1360
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
1361
+ *
1362
+ * @param {boolean} [displaySuggestion]
1363
+ * @return {Command} `this` command for chaining
1364
+ */
1365
+ showSuggestionAfterError(displaySuggestion = true) {
1366
+ this._showSuggestionAfterError = !!displaySuggestion;
1367
+ return this;
1368
+ }
1369
+ /**
1370
+ * Add a prepared subcommand.
1371
+ *
1372
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
1373
+ *
1374
+ * @param {Command} cmd - new subcommand
1375
+ * @param {object} [opts] - configuration options
1376
+ * @return {Command} `this` command for chaining
1377
+ */
1378
+ addCommand(cmd, opts) {
1379
+ if (!cmd._name) {
1380
+ throw new Error(`Command passed to .addCommand() must have a name
1381
+ - specify the name in Command constructor or using .name()`);
1382
+ }
1383
+ opts = opts || {};
1384
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1385
+ if (opts.noHelp || opts.hidden) cmd._hidden = true;
1386
+ this._registerCommand(cmd);
1387
+ cmd.parent = this;
1388
+ cmd._checkForBrokenPassThrough();
1389
+ return this;
1390
+ }
1391
+ /**
1392
+ * Factory routine to create a new unattached argument.
1393
+ *
1394
+ * See .argument() for creating an attached argument, which uses this routine to
1395
+ * create the argument. You can override createArgument to return a custom argument.
1396
+ *
1397
+ * @param {string} name
1398
+ * @param {string} [description]
1399
+ * @return {Argument} new argument
1400
+ */
1401
+ createArgument(name, description) {
1402
+ return new Argument(name, description);
1403
+ }
1404
+ /**
1405
+ * Define argument syntax for command.
1406
+ *
1407
+ * The default is that the argument is required, and you can explicitly
1408
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
1409
+ *
1410
+ * @example
1411
+ * program.argument('<input-file>');
1412
+ * program.argument('[output-file]');
1413
+ *
1414
+ * @param {string} name
1415
+ * @param {string} [description]
1416
+ * @param {(Function|*)} [parseArg] - custom argument processing function or default value
1417
+ * @param {*} [defaultValue]
1418
+ * @return {Command} `this` command for chaining
1419
+ */
1420
+ argument(name, description, parseArg, defaultValue) {
1421
+ const argument = this.createArgument(name, description);
1422
+ if (typeof parseArg === "function") {
1423
+ argument.default(defaultValue).argParser(parseArg);
1424
+ } else {
1425
+ argument.default(parseArg);
1426
+ }
1427
+ this.addArgument(argument);
1428
+ return this;
1429
+ }
1430
+ /**
1431
+ * Define argument syntax for command, adding multiple at once (without descriptions).
1432
+ *
1433
+ * See also .argument().
1434
+ *
1435
+ * @example
1436
+ * program.arguments('<cmd> [env]');
1437
+ *
1438
+ * @param {string} names
1439
+ * @return {Command} `this` command for chaining
1440
+ */
1441
+ arguments(names) {
1442
+ names.trim().split(/ +/).forEach((detail) => {
1443
+ this.argument(detail);
1444
+ });
1445
+ return this;
1446
+ }
1447
+ /**
1448
+ * Define argument syntax for command, adding a prepared argument.
1449
+ *
1450
+ * @param {Argument} argument
1451
+ * @return {Command} `this` command for chaining
1452
+ */
1453
+ addArgument(argument) {
1454
+ const previousArgument = this.registeredArguments.slice(-1)[0];
1455
+ if (previousArgument?.variadic) {
1456
+ throw new Error(
1457
+ `only the last argument can be variadic '${previousArgument.name()}'`
1458
+ );
1459
+ }
1460
+ if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
1461
+ throw new Error(
1462
+ `a default value for a required argument is never used: '${argument.name()}'`
1463
+ );
1464
+ }
1465
+ this.registeredArguments.push(argument);
1466
+ return this;
1467
+ }
1468
+ /**
1469
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
1470
+ *
1471
+ * @example
1472
+ * program.helpCommand('help [cmd]');
1473
+ * program.helpCommand('help [cmd]', 'show help');
1474
+ * program.helpCommand(false); // suppress default help command
1475
+ * program.helpCommand(true); // add help command even if no subcommands
1476
+ *
1477
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
1478
+ * @param {string} [description] - custom description
1479
+ * @return {Command} `this` command for chaining
1480
+ */
1481
+ helpCommand(enableOrNameAndArgs, description) {
1482
+ if (typeof enableOrNameAndArgs === "boolean") {
1483
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
1484
+ if (enableOrNameAndArgs && this._defaultCommandGroup) {
1485
+ this._initCommandGroup(this._getHelpCommand());
1486
+ }
1487
+ return this;
1488
+ }
1489
+ const nameAndArgs = enableOrNameAndArgs ?? "help [command]";
1490
+ const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);
1491
+ const helpDescription = description ?? "display help for command";
1492
+ const helpCommand = this.createCommand(helpName);
1493
+ helpCommand.helpOption(false);
1494
+ if (helpArgs) helpCommand.arguments(helpArgs);
1495
+ if (helpDescription) helpCommand.description(helpDescription);
1496
+ this._addImplicitHelpCommand = true;
1497
+ this._helpCommand = helpCommand;
1498
+ if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);
1499
+ return this;
1500
+ }
1501
+ /**
1502
+ * Add prepared custom help command.
1503
+ *
1504
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
1505
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
1506
+ * @return {Command} `this` command for chaining
1507
+ */
1508
+ addHelpCommand(helpCommand, deprecatedDescription) {
1509
+ if (typeof helpCommand !== "object") {
1510
+ this.helpCommand(helpCommand, deprecatedDescription);
1511
+ return this;
1512
+ }
1513
+ this._addImplicitHelpCommand = true;
1514
+ this._helpCommand = helpCommand;
1515
+ this._initCommandGroup(helpCommand);
1516
+ return this;
1517
+ }
1518
+ /**
1519
+ * Lazy create help command.
1520
+ *
1521
+ * @return {(Command|null)}
1522
+ * @package
1523
+ */
1524
+ _getHelpCommand() {
1525
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
1526
+ if (hasImplicitHelpCommand) {
1527
+ if (this._helpCommand === void 0) {
1528
+ this.helpCommand(void 0, void 0);
1529
+ }
1530
+ return this._helpCommand;
1531
+ }
1532
+ return null;
1533
+ }
1534
+ /**
1535
+ * Add hook for life cycle event.
1536
+ *
1537
+ * @param {string} event
1538
+ * @param {Function} listener
1539
+ * @return {Command} `this` command for chaining
1540
+ */
1541
+ hook(event, listener) {
1542
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
1543
+ if (!allowedValues.includes(event)) {
1544
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
1545
+ Expecting one of '${allowedValues.join("', '")}'`);
1546
+ }
1547
+ if (this._lifeCycleHooks[event]) {
1548
+ this._lifeCycleHooks[event].push(listener);
1549
+ } else {
1550
+ this._lifeCycleHooks[event] = [listener];
1551
+ }
1552
+ return this;
1553
+ }
1554
+ /**
1555
+ * Register callback to use as replacement for calling process.exit.
1556
+ *
1557
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
1558
+ * @return {Command} `this` command for chaining
1559
+ */
1560
+ exitOverride(fn) {
1561
+ if (fn) {
1562
+ this._exitCallback = fn;
1563
+ } else {
1564
+ this._exitCallback = (err) => {
1565
+ if (err.code !== "commander.executeSubCommandAsync") {
1566
+ throw err;
1567
+ } else {
1568
+ }
1569
+ };
1570
+ }
1571
+ return this;
1572
+ }
1573
+ /**
1574
+ * Call process.exit, and _exitCallback if defined.
1575
+ *
1576
+ * @param {number} exitCode exit code for using with process.exit
1577
+ * @param {string} code an id string representing the error
1578
+ * @param {string} message human-readable description of the error
1579
+ * @return never
1580
+ * @private
1581
+ */
1582
+ _exit(exitCode, code, message) {
1583
+ if (this._exitCallback) {
1584
+ this._exitCallback(new CommanderError(exitCode, code, message));
1585
+ }
1586
+ process2.exit(exitCode);
1587
+ }
1588
+ /**
1589
+ * Register callback `fn` for the command.
1590
+ *
1591
+ * @example
1592
+ * program
1593
+ * .command('serve')
1594
+ * .description('start service')
1595
+ * .action(function() {
1596
+ * // do work here
1597
+ * });
1598
+ *
1599
+ * @param {Function} fn
1600
+ * @return {Command} `this` command for chaining
1601
+ */
1602
+ action(fn) {
1603
+ const listener = (args) => {
1604
+ const expectedArgsCount = this.registeredArguments.length;
1605
+ const actionArgs = args.slice(0, expectedArgsCount);
1606
+ if (this._storeOptionsAsProperties) {
1607
+ actionArgs[expectedArgsCount] = this;
1608
+ } else {
1609
+ actionArgs[expectedArgsCount] = this.opts();
1610
+ }
1611
+ actionArgs.push(this);
1612
+ return fn.apply(this, actionArgs);
1613
+ };
1614
+ this._actionHandler = listener;
1615
+ return this;
1616
+ }
1617
+ /**
1618
+ * Factory routine to create a new unattached option.
1619
+ *
1620
+ * See .option() for creating an attached option, which uses this routine to
1621
+ * create the option. You can override createOption to return a custom option.
1622
+ *
1623
+ * @param {string} flags
1624
+ * @param {string} [description]
1625
+ * @return {Option} new option
1626
+ */
1627
+ createOption(flags, description) {
1628
+ return new Option(flags, description);
1629
+ }
1630
+ /**
1631
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
1632
+ *
1633
+ * @param {(Option | Argument)} target
1634
+ * @param {string} value
1635
+ * @param {*} previous
1636
+ * @param {string} invalidArgumentMessage
1637
+ * @private
1638
+ */
1639
+ _callParseArg(target, value, previous2, invalidArgumentMessage) {
1640
+ try {
1641
+ return target.parseArg(value, previous2);
1642
+ } catch (err) {
1643
+ if (err.code === "commander.invalidArgument") {
1644
+ const message = `${invalidArgumentMessage} ${err.message}`;
1645
+ this.error(message, { exitCode: err.exitCode, code: err.code });
1646
+ }
1647
+ throw err;
1648
+ }
1649
+ }
1650
+ /**
1651
+ * Check for option flag conflicts.
1652
+ * Register option if no conflicts found, or throw on conflict.
1653
+ *
1654
+ * @param {Option} option
1655
+ * @private
1656
+ */
1657
+ _registerOption(option) {
1658
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1659
+ if (matchingOption) {
1660
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1661
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1662
+ - already used by option '${matchingOption.flags}'`);
1663
+ }
1664
+ this._initOptionGroup(option);
1665
+ this.options.push(option);
1666
+ }
1667
+ /**
1668
+ * Check for command name and alias conflicts with existing commands.
1669
+ * Register command if no conflicts found, or throw on conflict.
1670
+ *
1671
+ * @param {Command} command
1672
+ * @private
1673
+ */
1674
+ _registerCommand(command) {
1675
+ const knownBy = (cmd) => {
1676
+ return [cmd.name()].concat(cmd.aliases());
1677
+ };
1678
+ const alreadyUsed = knownBy(command).find(
1679
+ (name) => this._findCommand(name)
1680
+ );
1681
+ if (alreadyUsed) {
1682
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1683
+ const newCmd = knownBy(command).join("|");
1684
+ throw new Error(
1685
+ `cannot add command '${newCmd}' as already have command '${existingCmd}'`
1686
+ );
1687
+ }
1688
+ this._initCommandGroup(command);
1689
+ this.commands.push(command);
1690
+ }
1691
+ /**
1692
+ * Add an option.
1693
+ *
1694
+ * @param {Option} option
1695
+ * @return {Command} `this` command for chaining
1696
+ */
1697
+ addOption(option) {
1698
+ this._registerOption(option);
1699
+ const oname = option.name();
1700
+ const name = option.attributeName();
1701
+ if (option.defaultValue !== void 0) {
1702
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
1703
+ }
1704
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1705
+ if (val == null && option.presetArg !== void 0) {
1706
+ val = option.presetArg;
1707
+ }
1708
+ const oldValue = this.getOptionValue(name);
1709
+ if (val !== null && option.parseArg) {
1710
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1711
+ } else if (val !== null && option.variadic) {
1712
+ val = option._collectValue(val, oldValue);
1713
+ }
1714
+ if (val == null) {
1715
+ if (option.negate) {
1716
+ val = false;
1717
+ } else if (option.isBoolean() || option.optional) {
1718
+ val = true;
1719
+ } else {
1720
+ val = "";
1721
+ }
1722
+ }
1723
+ this.setOptionValueWithSource(name, val, valueSource);
1724
+ };
1725
+ this.on("option:" + oname, (val) => {
1726
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1727
+ handleOptionValue(val, invalidValueMessage, "cli");
1728
+ });
1729
+ if (option.envVar) {
1730
+ this.on("optionEnv:" + oname, (val) => {
1731
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1732
+ handleOptionValue(val, invalidValueMessage, "env");
1733
+ });
1734
+ }
1735
+ return this;
1736
+ }
1737
+ /**
1738
+ * Internal implementation shared by .option() and .requiredOption()
1739
+ *
1740
+ * @return {Command} `this` command for chaining
1741
+ * @private
1742
+ */
1743
+ _optionEx(config2, flags, description, fn, defaultValue) {
1744
+ if (typeof flags === "object" && flags instanceof Option) {
1745
+ throw new Error(
1746
+ "To add an Option object use addOption() instead of option() or requiredOption()"
1747
+ );
1748
+ }
1749
+ const option = this.createOption(flags, description);
1750
+ option.makeOptionMandatory(!!config2.mandatory);
1751
+ if (typeof fn === "function") {
1752
+ option.default(defaultValue).argParser(fn);
1753
+ } else if (fn instanceof RegExp) {
1754
+ const regex = fn;
1755
+ fn = (val, def) => {
1756
+ const m = regex.exec(val);
1757
+ return m ? m[0] : def;
1758
+ };
1759
+ option.default(defaultValue).argParser(fn);
1760
+ } else {
1761
+ option.default(fn);
1762
+ }
1763
+ return this.addOption(option);
1764
+ }
1765
+ /**
1766
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
1767
+ *
1768
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
1769
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
1770
+ *
1771
+ * See the README for more details, and see also addOption() and requiredOption().
1772
+ *
1773
+ * @example
1774
+ * program
1775
+ * .option('-p, --pepper', 'add pepper')
1776
+ * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
1777
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
1778
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
1779
+ *
1780
+ * @param {string} flags
1781
+ * @param {string} [description]
1782
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1783
+ * @param {*} [defaultValue]
1784
+ * @return {Command} `this` command for chaining
1785
+ */
1786
+ option(flags, description, parseArg, defaultValue) {
1787
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1788
+ }
1789
+ /**
1790
+ * Add a required option which must have a value after parsing. This usually means
1791
+ * the option must be specified on the command line. (Otherwise the same as .option().)
1792
+ *
1793
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1794
+ *
1795
+ * @param {string} flags
1796
+ * @param {string} [description]
1797
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1798
+ * @param {*} [defaultValue]
1799
+ * @return {Command} `this` command for chaining
1800
+ */
1801
+ requiredOption(flags, description, parseArg, defaultValue) {
1802
+ return this._optionEx(
1803
+ { mandatory: true },
1804
+ flags,
1805
+ description,
1806
+ parseArg,
1807
+ defaultValue
1808
+ );
1809
+ }
1810
+ /**
1811
+ * Alter parsing of short flags with optional values.
1812
+ *
1813
+ * @example
1814
+ * // for `.option('-f,--flag [value]'):
1815
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
1816
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
1817
+ *
1818
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
1819
+ * @return {Command} `this` command for chaining
1820
+ */
1821
+ combineFlagAndOptionalValue(combine = true) {
1822
+ this._combineFlagAndOptionalValue = !!combine;
1823
+ return this;
1824
+ }
1825
+ /**
1826
+ * Allow unknown options on the command line.
1827
+ *
1828
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
1829
+ * @return {Command} `this` command for chaining
1830
+ */
1831
+ allowUnknownOption(allowUnknown = true) {
1832
+ this._allowUnknownOption = !!allowUnknown;
1833
+ return this;
1834
+ }
1835
+ /**
1836
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1837
+ *
1838
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
1839
+ * @return {Command} `this` command for chaining
1840
+ */
1841
+ allowExcessArguments(allowExcess = true) {
1842
+ this._allowExcessArguments = !!allowExcess;
1843
+ return this;
1844
+ }
1845
+ /**
1846
+ * Enable positional options. Positional means global options are specified before subcommands which lets
1847
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1848
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
1849
+ *
1850
+ * @param {boolean} [positional]
1851
+ * @return {Command} `this` command for chaining
1852
+ */
1853
+ enablePositionalOptions(positional = true) {
1854
+ this._enablePositionalOptions = !!positional;
1855
+ return this;
1856
+ }
1857
+ /**
1858
+ * Pass through options that come after command-arguments rather than treat them as command-options,
1859
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
1860
+ * positional options to have been enabled on the program (parent commands).
1861
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
1862
+ *
1863
+ * @param {boolean} [passThrough] for unknown options.
1864
+ * @return {Command} `this` command for chaining
1865
+ */
1866
+ passThroughOptions(passThrough = true) {
1867
+ this._passThroughOptions = !!passThrough;
1868
+ this._checkForBrokenPassThrough();
1869
+ return this;
1870
+ }
1871
+ /**
1872
+ * @private
1873
+ */
1874
+ _checkForBrokenPassThrough() {
1875
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
1876
+ throw new Error(
1877
+ `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`
1878
+ );
1879
+ }
1880
+ }
1881
+ /**
1882
+ * Whether to store option values as properties on command object,
1883
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
1884
+ *
1885
+ * @param {boolean} [storeAsProperties=true]
1886
+ * @return {Command} `this` command for chaining
1887
+ */
1888
+ storeOptionsAsProperties(storeAsProperties = true) {
1889
+ if (this.options.length) {
1890
+ throw new Error("call .storeOptionsAsProperties() before adding options");
1891
+ }
1892
+ if (Object.keys(this._optionValues).length) {
1893
+ throw new Error(
1894
+ "call .storeOptionsAsProperties() before setting option values"
1895
+ );
1896
+ }
1897
+ this._storeOptionsAsProperties = !!storeAsProperties;
1898
+ return this;
1899
+ }
1900
+ /**
1901
+ * Retrieve option value.
1902
+ *
1903
+ * @param {string} key
1904
+ * @return {object} value
1905
+ */
1906
+ getOptionValue(key) {
1907
+ if (this._storeOptionsAsProperties) {
1908
+ return this[key];
1909
+ }
1910
+ return this._optionValues[key];
1911
+ }
1912
+ /**
1913
+ * Store option value.
1914
+ *
1915
+ * @param {string} key
1916
+ * @param {object} value
1917
+ * @return {Command} `this` command for chaining
1918
+ */
1919
+ setOptionValue(key, value) {
1920
+ return this.setOptionValueWithSource(key, value, void 0);
1921
+ }
1922
+ /**
1923
+ * Store option value and where the value came from.
1924
+ *
1925
+ * @param {string} key
1926
+ * @param {object} value
1927
+ * @param {string} source - expected values are default/config/env/cli/implied
1928
+ * @return {Command} `this` command for chaining
1929
+ */
1930
+ setOptionValueWithSource(key, value, source) {
1931
+ if (this._storeOptionsAsProperties) {
1932
+ this[key] = value;
1933
+ } else {
1934
+ this._optionValues[key] = value;
1935
+ }
1936
+ this._optionValueSources[key] = source;
1937
+ return this;
1938
+ }
1939
+ /**
1940
+ * Get source of option value.
1941
+ * Expected values are default | config | env | cli | implied
1942
+ *
1943
+ * @param {string} key
1944
+ * @return {string}
1945
+ */
1946
+ getOptionValueSource(key) {
1947
+ return this._optionValueSources[key];
1948
+ }
1949
+ /**
1950
+ * Get source of option value. See also .optsWithGlobals().
1951
+ * Expected values are default | config | env | cli | implied
1952
+ *
1953
+ * @param {string} key
1954
+ * @return {string}
1955
+ */
1956
+ getOptionValueSourceWithGlobals(key) {
1957
+ let source;
1958
+ this._getCommandAndAncestors().forEach((cmd) => {
1959
+ if (cmd.getOptionValueSource(key) !== void 0) {
1960
+ source = cmd.getOptionValueSource(key);
1961
+ }
1962
+ });
1963
+ return source;
1964
+ }
1965
+ /**
1966
+ * Get user arguments from implied or explicit arguments.
1967
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
1968
+ *
1969
+ * @private
1970
+ */
1971
+ _prepareUserArgs(argv, parseOptions) {
1972
+ if (argv !== void 0 && !Array.isArray(argv)) {
1973
+ throw new Error("first parameter to parse must be array or undefined");
1974
+ }
1975
+ parseOptions = parseOptions || {};
1976
+ if (argv === void 0 && parseOptions.from === void 0) {
1977
+ if (process2.versions?.electron) {
1978
+ parseOptions.from = "electron";
1979
+ }
1980
+ const execArgv = process2.execArgv ?? [];
1981
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
1982
+ parseOptions.from = "eval";
1983
+ }
1984
+ }
1985
+ if (argv === void 0) {
1986
+ argv = process2.argv;
1987
+ }
1988
+ this.rawArgs = argv.slice();
1989
+ let userArgs;
1990
+ switch (parseOptions.from) {
1991
+ case void 0:
1992
+ case "node":
1993
+ this._scriptPath = argv[1];
1994
+ userArgs = argv.slice(2);
1995
+ break;
1996
+ case "electron":
1997
+ if (process2.defaultApp) {
1998
+ this._scriptPath = argv[1];
1999
+ userArgs = argv.slice(2);
2000
+ } else {
2001
+ userArgs = argv.slice(1);
2002
+ }
2003
+ break;
2004
+ case "user":
2005
+ userArgs = argv.slice(0);
2006
+ break;
2007
+ case "eval":
2008
+ userArgs = argv.slice(1);
2009
+ break;
2010
+ default:
2011
+ throw new Error(
2012
+ `unexpected parse option { from: '${parseOptions.from}' }`
2013
+ );
2014
+ }
2015
+ if (!this._name && this._scriptPath)
2016
+ this.nameFromFilename(this._scriptPath);
2017
+ this._name = this._name || "program";
2018
+ return userArgs;
2019
+ }
2020
+ /**
2021
+ * Parse `argv`, setting options and invoking commands when defined.
2022
+ *
2023
+ * Use parseAsync instead of parse if any of your action handlers are async.
2024
+ *
2025
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
2026
+ *
2027
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
2028
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
2029
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
2030
+ * - `'user'`: just user arguments
2031
+ *
2032
+ * @example
2033
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
2034
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
2035
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2036
+ *
2037
+ * @param {string[]} [argv] - optional, defaults to process.argv
2038
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
2039
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
2040
+ * @return {Command} `this` command for chaining
2041
+ */
2042
+ parse(argv, parseOptions) {
2043
+ this._prepareForParse();
2044
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
2045
+ this._parseCommand([], userArgs);
2046
+ return this;
2047
+ }
2048
+ /**
2049
+ * Parse `argv`, setting options and invoking commands when defined.
2050
+ *
2051
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
2052
+ *
2053
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
2054
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
2055
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
2056
+ * - `'user'`: just user arguments
2057
+ *
2058
+ * @example
2059
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
2060
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
2061
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2062
+ *
2063
+ * @param {string[]} [argv]
2064
+ * @param {object} [parseOptions]
2065
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
2066
+ * @return {Promise}
2067
+ */
2068
+ async parseAsync(argv, parseOptions) {
2069
+ this._prepareForParse();
2070
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
2071
+ await this._parseCommand([], userArgs);
2072
+ return this;
2073
+ }
2074
+ _prepareForParse() {
2075
+ if (this._savedState === null) {
2076
+ this.options.filter(
2077
+ (option) => option.negate && option.defaultValue === void 0 && this.getOptionValue(option.attributeName()) === void 0
2078
+ ).forEach((option) => {
2079
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
2080
+ if (!this._findOption(positiveLongFlag)) {
2081
+ this.setOptionValueWithSource(
2082
+ option.attributeName(),
2083
+ true,
2084
+ "default"
2085
+ );
2086
+ }
2087
+ });
2088
+ this.saveStateBeforeParse();
2089
+ } else {
2090
+ this.restoreStateBeforeParse();
2091
+ }
2092
+ }
2093
+ /**
2094
+ * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
2095
+ * Not usually called directly, but available for subclasses to save their custom state.
2096
+ *
2097
+ * This is called in a lazy way. Only commands used in parsing chain will have state saved.
2098
+ */
2099
+ saveStateBeforeParse() {
2100
+ this._savedState = {
2101
+ // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing
2102
+ _name: this._name,
2103
+ // option values before parse have default values (including false for negated options)
2104
+ // shallow clones
2105
+ _optionValues: { ...this._optionValues },
2106
+ _optionValueSources: { ...this._optionValueSources }
2107
+ };
2108
+ }
2109
+ /**
2110
+ * Restore state before parse for calls after the first.
2111
+ * Not usually called directly, but available for subclasses to save their custom state.
2112
+ *
2113
+ * This is called in a lazy way. Only commands used in parsing chain will have state restored.
2114
+ */
2115
+ restoreStateBeforeParse() {
2116
+ if (this._storeOptionsAsProperties)
2117
+ throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
2118
+ - either make a new Command for each call to parse, or stop storing options as properties`);
2119
+ this._name = this._savedState._name;
2120
+ this._scriptPath = null;
2121
+ this.rawArgs = [];
2122
+ this._optionValues = { ...this._savedState._optionValues };
2123
+ this._optionValueSources = { ...this._savedState._optionValueSources };
2124
+ this.args = [];
2125
+ this.processedArgs = [];
2126
+ }
2127
+ /**
2128
+ * Throw if expected executable is missing. Add lots of help for author.
2129
+ *
2130
+ * @param {string} executableFile
2131
+ * @param {string} executableDir
2132
+ * @param {string} subcommandName
2133
+ */
2134
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
2135
+ if (fs.existsSync(executableFile)) return;
2136
+ 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";
2137
+ const executableMissing = `'${executableFile}' does not exist
2138
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
2139
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
2140
+ - ${executableDirMessage}`;
2141
+ throw new Error(executableMissing);
2142
+ }
2143
+ /**
2144
+ * Execute a sub-command executable.
2145
+ *
2146
+ * @private
2147
+ */
2148
+ _executeSubCommand(subcommand, args) {
2149
+ args = args.slice();
2150
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
2151
+ function findFile(baseDir, baseName) {
2152
+ const localBin = path.resolve(baseDir, baseName);
2153
+ if (fs.existsSync(localBin)) return localBin;
2154
+ if (sourceExt.includes(path.extname(baseName))) return void 0;
2155
+ const foundExt = sourceExt.find(
2156
+ (ext) => fs.existsSync(`${localBin}${ext}`)
2157
+ );
2158
+ if (foundExt) return `${localBin}${foundExt}`;
2159
+ return void 0;
2160
+ }
2161
+ this._checkForMissingMandatoryOptions();
2162
+ this._checkForConflictingOptions();
2163
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
2164
+ let executableDir = this._executableDir || "";
2165
+ if (this._scriptPath) {
2166
+ let resolvedScriptPath;
2167
+ try {
2168
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
2169
+ } catch {
2170
+ resolvedScriptPath = this._scriptPath;
2171
+ }
2172
+ executableDir = path.resolve(
2173
+ path.dirname(resolvedScriptPath),
2174
+ executableDir
2175
+ );
2176
+ }
2177
+ if (executableDir) {
2178
+ let localFile = findFile(executableDir, executableFile);
2179
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
2180
+ const legacyName = path.basename(
2181
+ this._scriptPath,
2182
+ path.extname(this._scriptPath)
2183
+ );
2184
+ if (legacyName !== this._name) {
2185
+ localFile = findFile(
2186
+ executableDir,
2187
+ `${legacyName}-${subcommand._name}`
2188
+ );
2189
+ }
2190
+ }
2191
+ executableFile = localFile || executableFile;
2192
+ }
2193
+ const launchWithNode = sourceExt.includes(path.extname(executableFile));
2194
+ let proc;
2195
+ if (process2.platform !== "win32") {
2196
+ if (launchWithNode) {
2197
+ args.unshift(executableFile);
2198
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
2199
+ proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
2200
+ } else {
2201
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
2202
+ }
2203
+ } else {
2204
+ this._checkForMissingExecutable(
2205
+ executableFile,
2206
+ executableDir,
2207
+ subcommand._name
2208
+ );
2209
+ args.unshift(executableFile);
2210
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
2211
+ proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
2212
+ }
2213
+ if (!proc.killed) {
2214
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
2215
+ signals.forEach((signal) => {
2216
+ process2.on(signal, () => {
2217
+ if (proc.killed === false && proc.exitCode === null) {
2218
+ proc.kill(signal);
2219
+ }
2220
+ });
2221
+ });
2222
+ }
2223
+ const exitCallback = this._exitCallback;
2224
+ proc.on("close", (code) => {
2225
+ code = code ?? 1;
2226
+ if (!exitCallback) {
2227
+ process2.exit(code);
2228
+ } else {
2229
+ exitCallback(
2230
+ new CommanderError(
2231
+ code,
2232
+ "commander.executeSubCommandAsync",
2233
+ "(close)"
2234
+ )
2235
+ );
2236
+ }
2237
+ });
2238
+ proc.on("error", (err) => {
2239
+ if (err.code === "ENOENT") {
2240
+ this._checkForMissingExecutable(
2241
+ executableFile,
2242
+ executableDir,
2243
+ subcommand._name
2244
+ );
2245
+ } else if (err.code === "EACCES") {
2246
+ throw new Error(`'${executableFile}' not executable`);
2247
+ }
2248
+ if (!exitCallback) {
2249
+ process2.exit(1);
2250
+ } else {
2251
+ const wrappedError = new CommanderError(
2252
+ 1,
2253
+ "commander.executeSubCommandAsync",
2254
+ "(error)"
2255
+ );
2256
+ wrappedError.nestedError = err;
2257
+ exitCallback(wrappedError);
2258
+ }
2259
+ });
2260
+ this.runningCommand = proc;
2261
+ }
2262
+ /**
2263
+ * @private
2264
+ */
2265
+ _dispatchSubcommand(commandName, operands, unknown2) {
2266
+ const subCommand = this._findCommand(commandName);
2267
+ if (!subCommand) this.help({ error: true });
2268
+ subCommand._prepareForParse();
2269
+ let promiseChain;
2270
+ promiseChain = this._chainOrCallSubCommandHook(
2271
+ promiseChain,
2272
+ subCommand,
2273
+ "preSubcommand"
2274
+ );
2275
+ promiseChain = this._chainOrCall(promiseChain, () => {
2276
+ if (subCommand._executableHandler) {
2277
+ this._executeSubCommand(subCommand, operands.concat(unknown2));
2278
+ } else {
2279
+ return subCommand._parseCommand(operands, unknown2);
2280
+ }
2281
+ });
2282
+ return promiseChain;
2283
+ }
2284
+ /**
2285
+ * Invoke help directly if possible, or dispatch if necessary.
2286
+ * e.g. help foo
2287
+ *
2288
+ * @private
2289
+ */
2290
+ _dispatchHelpCommand(subcommandName) {
2291
+ if (!subcommandName) {
2292
+ this.help();
2293
+ }
2294
+ const subCommand = this._findCommand(subcommandName);
2295
+ if (subCommand && !subCommand._executableHandler) {
2296
+ subCommand.help();
2297
+ }
2298
+ return this._dispatchSubcommand(
2299
+ subcommandName,
2300
+ [],
2301
+ [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]
2302
+ );
2303
+ }
2304
+ /**
2305
+ * Check this.args against expected this.registeredArguments.
2306
+ *
2307
+ * @private
2308
+ */
2309
+ _checkNumberOfArguments() {
2310
+ this.registeredArguments.forEach((arg, i) => {
2311
+ if (arg.required && this.args[i] == null) {
2312
+ this.missingArgument(arg.name());
2313
+ }
2314
+ });
2315
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
2316
+ return;
2317
+ }
2318
+ if (this.args.length > this.registeredArguments.length) {
2319
+ this._excessArguments(this.args);
2320
+ }
2321
+ }
2322
+ /**
2323
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
2324
+ *
2325
+ * @private
2326
+ */
2327
+ _processArguments() {
2328
+ const myParseArg = (argument, value, previous2) => {
2329
+ let parsedValue = value;
2330
+ if (value !== null && argument.parseArg) {
2331
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
2332
+ parsedValue = this._callParseArg(
2333
+ argument,
2334
+ value,
2335
+ previous2,
2336
+ invalidValueMessage
2337
+ );
2338
+ }
2339
+ return parsedValue;
2340
+ };
2341
+ this._checkNumberOfArguments();
2342
+ const processedArgs = [];
2343
+ this.registeredArguments.forEach((declaredArg, index2) => {
2344
+ let value = declaredArg.defaultValue;
2345
+ if (declaredArg.variadic) {
2346
+ if (index2 < this.args.length) {
2347
+ value = this.args.slice(index2);
2348
+ if (declaredArg.parseArg) {
2349
+ value = value.reduce((processed, v) => {
2350
+ return myParseArg(declaredArg, v, processed);
2351
+ }, declaredArg.defaultValue);
2352
+ }
2353
+ } else if (value === void 0) {
2354
+ value = [];
2355
+ }
2356
+ } else if (index2 < this.args.length) {
2357
+ value = this.args[index2];
2358
+ if (declaredArg.parseArg) {
2359
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
2360
+ }
2361
+ }
2362
+ processedArgs[index2] = value;
2363
+ });
2364
+ this.processedArgs = processedArgs;
2365
+ }
2366
+ /**
2367
+ * Once we have a promise we chain, but call synchronously until then.
2368
+ *
2369
+ * @param {(Promise|undefined)} promise
2370
+ * @param {Function} fn
2371
+ * @return {(Promise|undefined)}
2372
+ * @private
2373
+ */
2374
+ _chainOrCall(promise2, fn) {
2375
+ if (promise2?.then && typeof promise2.then === "function") {
2376
+ return promise2.then(() => fn());
2377
+ }
2378
+ return fn();
2379
+ }
2380
+ /**
2381
+ *
2382
+ * @param {(Promise|undefined)} promise
2383
+ * @param {string} event
2384
+ * @return {(Promise|undefined)}
2385
+ * @private
2386
+ */
2387
+ _chainOrCallHooks(promise2, event) {
2388
+ let result = promise2;
2389
+ const hooks = [];
2390
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
2391
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
2392
+ hooks.push({ hookedCommand, callback });
2393
+ });
2394
+ });
2395
+ if (event === "postAction") {
2396
+ hooks.reverse();
2397
+ }
2398
+ hooks.forEach((hookDetail) => {
2399
+ result = this._chainOrCall(result, () => {
2400
+ return hookDetail.callback(hookDetail.hookedCommand, this);
2401
+ });
2402
+ });
2403
+ return result;
2404
+ }
2405
+ /**
2406
+ *
2407
+ * @param {(Promise|undefined)} promise
2408
+ * @param {Command} subCommand
2409
+ * @param {string} event
2410
+ * @return {(Promise|undefined)}
2411
+ * @private
2412
+ */
2413
+ _chainOrCallSubCommandHook(promise2, subCommand, event) {
2414
+ let result = promise2;
2415
+ if (this._lifeCycleHooks[event] !== void 0) {
2416
+ this._lifeCycleHooks[event].forEach((hook) => {
2417
+ result = this._chainOrCall(result, () => {
2418
+ return hook(this, subCommand);
2419
+ });
2420
+ });
2421
+ }
2422
+ return result;
2423
+ }
2424
+ /**
2425
+ * Process arguments in context of this command.
2426
+ * Returns action result, in case it is a promise.
2427
+ *
2428
+ * @private
2429
+ */
2430
+ _parseCommand(operands, unknown2) {
2431
+ const parsed = this.parseOptions(unknown2);
2432
+ this._parseOptionsEnv();
2433
+ this._parseOptionsImplied();
2434
+ operands = operands.concat(parsed.operands);
2435
+ unknown2 = parsed.unknown;
2436
+ this.args = operands.concat(unknown2);
2437
+ if (operands && this._findCommand(operands[0])) {
2438
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown2);
2439
+ }
2440
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
2441
+ return this._dispatchHelpCommand(operands[1]);
2442
+ }
2443
+ if (this._defaultCommandName) {
2444
+ this._outputHelpIfRequested(unknown2);
2445
+ return this._dispatchSubcommand(
2446
+ this._defaultCommandName,
2447
+ operands,
2448
+ unknown2
2449
+ );
2450
+ }
2451
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
2452
+ this.help({ error: true });
2453
+ }
2454
+ this._outputHelpIfRequested(parsed.unknown);
2455
+ this._checkForMissingMandatoryOptions();
2456
+ this._checkForConflictingOptions();
2457
+ const checkForUnknownOptions = () => {
2458
+ if (parsed.unknown.length > 0) {
2459
+ this.unknownOption(parsed.unknown[0]);
2460
+ }
2461
+ };
2462
+ const commandEvent = `command:${this.name()}`;
2463
+ if (this._actionHandler) {
2464
+ checkForUnknownOptions();
2465
+ this._processArguments();
2466
+ let promiseChain;
2467
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
2468
+ promiseChain = this._chainOrCall(
2469
+ promiseChain,
2470
+ () => this._actionHandler(this.processedArgs)
2471
+ );
2472
+ if (this.parent) {
2473
+ promiseChain = this._chainOrCall(promiseChain, () => {
2474
+ this.parent.emit(commandEvent, operands, unknown2);
2475
+ });
2476
+ }
2477
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
2478
+ return promiseChain;
2479
+ }
2480
+ if (this.parent?.listenerCount(commandEvent)) {
2481
+ checkForUnknownOptions();
2482
+ this._processArguments();
2483
+ this.parent.emit(commandEvent, operands, unknown2);
2484
+ } else if (operands.length) {
2485
+ if (this._findCommand("*")) {
2486
+ return this._dispatchSubcommand("*", operands, unknown2);
2487
+ }
2488
+ if (this.listenerCount("command:*")) {
2489
+ this.emit("command:*", operands, unknown2);
2490
+ } else if (this.commands.length) {
2491
+ this.unknownCommand();
2492
+ } else {
2493
+ checkForUnknownOptions();
2494
+ this._processArguments();
2495
+ }
2496
+ } else if (this.commands.length) {
2497
+ checkForUnknownOptions();
2498
+ this.help({ error: true });
2499
+ } else {
2500
+ checkForUnknownOptions();
2501
+ this._processArguments();
2502
+ }
2503
+ }
2504
+ /**
2505
+ * Find matching command.
2506
+ *
2507
+ * @private
2508
+ * @return {Command | undefined}
2509
+ */
2510
+ _findCommand(name) {
2511
+ if (!name) return void 0;
2512
+ return this.commands.find(
2513
+ (cmd) => cmd._name === name || cmd._aliases.includes(name)
2514
+ );
2515
+ }
2516
+ /**
2517
+ * Return an option matching `arg` if any.
2518
+ *
2519
+ * @param {string} arg
2520
+ * @return {Option}
2521
+ * @package
2522
+ */
2523
+ _findOption(arg) {
2524
+ return this.options.find((option) => option.is(arg));
2525
+ }
2526
+ /**
2527
+ * Display an error message if a mandatory option does not have a value.
2528
+ * Called after checking for help flags in leaf subcommand.
2529
+ *
2530
+ * @private
2531
+ */
2532
+ _checkForMissingMandatoryOptions() {
2533
+ this._getCommandAndAncestors().forEach((cmd) => {
2534
+ cmd.options.forEach((anOption) => {
2535
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
2536
+ cmd.missingMandatoryOptionValue(anOption);
2537
+ }
2538
+ });
2539
+ });
2540
+ }
2541
+ /**
2542
+ * Display an error message if conflicting options are used together in this.
2543
+ *
2544
+ * @private
2545
+ */
2546
+ _checkForConflictingLocalOptions() {
2547
+ const definedNonDefaultOptions = this.options.filter((option) => {
2548
+ const optionKey = option.attributeName();
2549
+ if (this.getOptionValue(optionKey) === void 0) {
2550
+ return false;
2551
+ }
2552
+ return this.getOptionValueSource(optionKey) !== "default";
2553
+ });
2554
+ const optionsWithConflicting = definedNonDefaultOptions.filter(
2555
+ (option) => option.conflictsWith.length > 0
2556
+ );
2557
+ optionsWithConflicting.forEach((option) => {
2558
+ const conflictingAndDefined = definedNonDefaultOptions.find(
2559
+ (defined) => option.conflictsWith.includes(defined.attributeName())
2560
+ );
2561
+ if (conflictingAndDefined) {
2562
+ this._conflictingOption(option, conflictingAndDefined);
2563
+ }
2564
+ });
2565
+ }
2566
+ /**
2567
+ * Display an error message if conflicting options are used together.
2568
+ * Called after checking for help flags in leaf subcommand.
2569
+ *
2570
+ * @private
2571
+ */
2572
+ _checkForConflictingOptions() {
2573
+ this._getCommandAndAncestors().forEach((cmd) => {
2574
+ cmd._checkForConflictingLocalOptions();
2575
+ });
2576
+ }
2577
+ /**
2578
+ * Parse options from `argv` removing known options,
2579
+ * and return argv split into operands and unknown arguments.
2580
+ *
2581
+ * Side effects: modifies command by storing options. Does not reset state if called again.
2582
+ *
2583
+ * Examples:
2584
+ *
2585
+ * argv => operands, unknown
2586
+ * --known kkk op => [op], []
2587
+ * op --known kkk => [op], []
2588
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
2589
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
2590
+ *
2591
+ * @param {string[]} args
2592
+ * @return {{operands: string[], unknown: string[]}}
2593
+ */
2594
+ parseOptions(args) {
2595
+ const operands = [];
2596
+ const unknown2 = [];
2597
+ let dest = operands;
2598
+ function maybeOption(arg) {
2599
+ return arg.length > 1 && arg[0] === "-";
2600
+ }
2601
+ const negativeNumberArg = (arg) => {
2602
+ if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)) return false;
2603
+ return !this._getCommandAndAncestors().some(
2604
+ (cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short))
2605
+ );
2606
+ };
2607
+ let activeVariadicOption = null;
2608
+ let activeGroup = null;
2609
+ let i = 0;
2610
+ while (i < args.length || activeGroup) {
2611
+ const arg = activeGroup ?? args[i++];
2612
+ activeGroup = null;
2613
+ if (arg === "--") {
2614
+ if (dest === unknown2) dest.push(arg);
2615
+ dest.push(...args.slice(i));
2616
+ break;
2617
+ }
2618
+ if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
2619
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
2620
+ continue;
2621
+ }
2622
+ activeVariadicOption = null;
2623
+ if (maybeOption(arg)) {
2624
+ const option = this._findOption(arg);
2625
+ if (option) {
2626
+ if (option.required) {
2627
+ const value = args[i++];
2628
+ if (value === void 0) this.optionMissingArgument(option);
2629
+ this.emit(`option:${option.name()}`, value);
2630
+ } else if (option.optional) {
2631
+ let value = null;
2632
+ if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) {
2633
+ value = args[i++];
2634
+ }
2635
+ this.emit(`option:${option.name()}`, value);
2636
+ } else {
2637
+ this.emit(`option:${option.name()}`);
2638
+ }
2639
+ activeVariadicOption = option.variadic ? option : null;
2640
+ continue;
2641
+ }
2642
+ }
2643
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
2644
+ const option = this._findOption(`-${arg[1]}`);
2645
+ if (option) {
2646
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
2647
+ this.emit(`option:${option.name()}`, arg.slice(2));
2648
+ } else {
2649
+ this.emit(`option:${option.name()}`);
2650
+ activeGroup = `-${arg.slice(2)}`;
2651
+ }
2652
+ continue;
2653
+ }
2654
+ }
2655
+ if (/^--[^=]+=/.test(arg)) {
2656
+ const index2 = arg.indexOf("=");
2657
+ const option = this._findOption(arg.slice(0, index2));
2658
+ if (option && (option.required || option.optional)) {
2659
+ this.emit(`option:${option.name()}`, arg.slice(index2 + 1));
2660
+ continue;
2661
+ }
2662
+ }
2663
+ if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) {
2664
+ dest = unknown2;
2665
+ }
2666
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown2.length === 0) {
2667
+ if (this._findCommand(arg)) {
2668
+ operands.push(arg);
2669
+ unknown2.push(...args.slice(i));
2670
+ break;
2671
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
2672
+ operands.push(arg, ...args.slice(i));
2673
+ break;
2674
+ } else if (this._defaultCommandName) {
2675
+ unknown2.push(arg, ...args.slice(i));
2676
+ break;
2677
+ }
2678
+ }
2679
+ if (this._passThroughOptions) {
2680
+ dest.push(arg, ...args.slice(i));
2681
+ break;
2682
+ }
2683
+ dest.push(arg);
2684
+ }
2685
+ return { operands, unknown: unknown2 };
2686
+ }
2687
+ /**
2688
+ * Return an object containing local option values as key-value pairs.
2689
+ *
2690
+ * @return {object}
2691
+ */
2692
+ opts() {
2693
+ if (this._storeOptionsAsProperties) {
2694
+ const result = {};
2695
+ const len = this.options.length;
2696
+ for (let i = 0; i < len; i++) {
2697
+ const key = this.options[i].attributeName();
2698
+ result[key] = key === this._versionOptionName ? this._version : this[key];
2699
+ }
2700
+ return result;
2701
+ }
2702
+ return this._optionValues;
2703
+ }
2704
+ /**
2705
+ * Return an object containing merged local and global option values as key-value pairs.
2706
+ *
2707
+ * @return {object}
2708
+ */
2709
+ optsWithGlobals() {
2710
+ return this._getCommandAndAncestors().reduce(
2711
+ (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
2712
+ {}
2713
+ );
2714
+ }
2715
+ /**
2716
+ * Display error message and exit (or call exitOverride).
2717
+ *
2718
+ * @param {string} message
2719
+ * @param {object} [errorOptions]
2720
+ * @param {string} [errorOptions.code] - an id string representing the error
2721
+ * @param {number} [errorOptions.exitCode] - used with process.exit
2722
+ */
2723
+ error(message, errorOptions) {
2724
+ this._outputConfiguration.outputError(
2725
+ `${message}
2726
+ `,
2727
+ this._outputConfiguration.writeErr
2728
+ );
2729
+ if (typeof this._showHelpAfterError === "string") {
2730
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
2731
+ `);
2732
+ } else if (this._showHelpAfterError) {
2733
+ this._outputConfiguration.writeErr("\n");
2734
+ this.outputHelp({ error: true });
2735
+ }
2736
+ const config2 = errorOptions || {};
2737
+ const exitCode = config2.exitCode || 1;
2738
+ const code = config2.code || "commander.error";
2739
+ this._exit(exitCode, code, message);
2740
+ }
2741
+ /**
2742
+ * Apply any option related environment variables, if option does
2743
+ * not have a value from cli or client code.
2744
+ *
2745
+ * @private
2746
+ */
2747
+ _parseOptionsEnv() {
2748
+ this.options.forEach((option) => {
2749
+ if (option.envVar && option.envVar in process2.env) {
2750
+ const optionKey = option.attributeName();
2751
+ if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(
2752
+ this.getOptionValueSource(optionKey)
2753
+ )) {
2754
+ if (option.required || option.optional) {
2755
+ this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
2756
+ } else {
2757
+ this.emit(`optionEnv:${option.name()}`);
2758
+ }
2759
+ }
2760
+ }
2761
+ });
2762
+ }
2763
+ /**
2764
+ * Apply any implied option values, if option is undefined or default value.
2765
+ *
2766
+ * @private
2767
+ */
2768
+ _parseOptionsImplied() {
2769
+ const dualHelper = new DualOptions(this.options);
2770
+ const hasCustomOptionValue = (optionKey) => {
2771
+ return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
2772
+ };
2773
+ this.options.filter(
2774
+ (option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(
2775
+ this.getOptionValue(option.attributeName()),
2776
+ option
2777
+ )
2778
+ ).forEach((option) => {
2779
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
2780
+ this.setOptionValueWithSource(
2781
+ impliedKey,
2782
+ option.implied[impliedKey],
2783
+ "implied"
2784
+ );
2785
+ });
2786
+ });
2787
+ }
2788
+ /**
2789
+ * Argument `name` is missing.
2790
+ *
2791
+ * @param {string} name
2792
+ * @private
2793
+ */
2794
+ missingArgument(name) {
2795
+ const message = `error: missing required argument '${name}'`;
2796
+ this.error(message, { code: "commander.missingArgument" });
2797
+ }
2798
+ /**
2799
+ * `Option` is missing an argument.
2800
+ *
2801
+ * @param {Option} option
2802
+ * @private
2803
+ */
2804
+ optionMissingArgument(option) {
2805
+ const message = `error: option '${option.flags}' argument missing`;
2806
+ this.error(message, { code: "commander.optionMissingArgument" });
2807
+ }
2808
+ /**
2809
+ * `Option` does not have a value, and is a mandatory option.
2810
+ *
2811
+ * @param {Option} option
2812
+ * @private
2813
+ */
2814
+ missingMandatoryOptionValue(option) {
2815
+ const message = `error: required option '${option.flags}' not specified`;
2816
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
2817
+ }
2818
+ /**
2819
+ * `Option` conflicts with another option.
2820
+ *
2821
+ * @param {Option} option
2822
+ * @param {Option} conflictingOption
2823
+ * @private
2824
+ */
2825
+ _conflictingOption(option, conflictingOption) {
2826
+ const findBestOptionFromValue = (option2) => {
2827
+ const optionKey = option2.attributeName();
2828
+ const optionValue = this.getOptionValue(optionKey);
2829
+ const negativeOption = this.options.find(
2830
+ (target) => target.negate && optionKey === target.attributeName()
2831
+ );
2832
+ const positiveOption = this.options.find(
2833
+ (target) => !target.negate && optionKey === target.attributeName()
2834
+ );
2835
+ if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
2836
+ return negativeOption;
2837
+ }
2838
+ return positiveOption || option2;
2839
+ };
2840
+ const getErrorMessage = (option2) => {
2841
+ const bestOption = findBestOptionFromValue(option2);
2842
+ const optionKey = bestOption.attributeName();
2843
+ const source = this.getOptionValueSource(optionKey);
2844
+ if (source === "env") {
2845
+ return `environment variable '${bestOption.envVar}'`;
2846
+ }
2847
+ return `option '${bestOption.flags}'`;
2848
+ };
2849
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2850
+ this.error(message, { code: "commander.conflictingOption" });
2851
+ }
2852
+ /**
2853
+ * Unknown option `flag`.
2854
+ *
2855
+ * @param {string} flag
2856
+ * @private
2857
+ */
2858
+ unknownOption(flag) {
2859
+ if (this._allowUnknownOption) return;
2860
+ let suggestion = "";
2861
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
2862
+ let candidateFlags = [];
2863
+ let command = this;
2864
+ do {
2865
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
2866
+ candidateFlags = candidateFlags.concat(moreFlags);
2867
+ command = command.parent;
2868
+ } while (command && !command._enablePositionalOptions);
2869
+ suggestion = suggestSimilar(flag, candidateFlags);
2870
+ }
2871
+ const message = `error: unknown option '${flag}'${suggestion}`;
2872
+ this.error(message, { code: "commander.unknownOption" });
2873
+ }
2874
+ /**
2875
+ * Excess arguments, more than expected.
2876
+ *
2877
+ * @param {string[]} receivedArgs
2878
+ * @private
2879
+ */
2880
+ _excessArguments(receivedArgs) {
2881
+ if (this._allowExcessArguments) return;
2882
+ const expected = this.registeredArguments.length;
2883
+ const s = expected === 1 ? "" : "s";
2884
+ const received = receivedArgs.length;
2885
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
2886
+ const details = receivedArgs.join(", ");
2887
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${received}: ${details}.`;
2888
+ this.error(message, { code: "commander.excessArguments" });
2889
+ }
2890
+ /**
2891
+ * Unknown command.
2892
+ *
2893
+ * @private
2894
+ */
2895
+ unknownCommand() {
2896
+ const unknownName = this.args[0];
2897
+ let suggestion = "";
2898
+ if (this._showSuggestionAfterError) {
2899
+ const candidateNames = [];
2900
+ this.createHelp().visibleCommands(this).forEach((command) => {
2901
+ candidateNames.push(command.name());
2902
+ if (command.alias()) candidateNames.push(command.alias());
2903
+ });
2904
+ suggestion = suggestSimilar(unknownName, candidateNames);
2905
+ }
2906
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
2907
+ this.error(message, { code: "commander.unknownCommand" });
2908
+ }
2909
+ /**
2910
+ * Get or set the program version.
2911
+ *
2912
+ * This method auto-registers the "-V, --version" option which will print the version number.
2913
+ *
2914
+ * You can optionally supply the flags and description to override the defaults.
2915
+ *
2916
+ * @param {string} [str]
2917
+ * @param {string} [flags]
2918
+ * @param {string} [description]
2919
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
2920
+ */
2921
+ version(str, flags, description) {
2922
+ if (str === void 0) return this._version;
2923
+ this._version = str;
2924
+ flags = flags || "-V, --version";
2925
+ description = description || "output the version number";
2926
+ const versionOption = this.createOption(flags, description);
2927
+ this._versionOptionName = versionOption.attributeName();
2928
+ this._registerOption(versionOption);
2929
+ this.on("option:" + versionOption.name(), () => {
2930
+ this._outputConfiguration.writeOut(`${str}
2931
+ `);
2932
+ this._exit(0, "commander.version", str);
2933
+ });
2934
+ return this;
2935
+ }
2936
+ /**
2937
+ * Set the description.
2938
+ *
2939
+ * @param {string} [str]
2940
+ * @param {object} [argsDescription]
2941
+ * @return {(string|Command)}
2942
+ */
2943
+ description(str, argsDescription) {
2944
+ if (str === void 0 && argsDescription === void 0)
2945
+ return this._description;
2946
+ this._description = str;
2947
+ if (argsDescription) {
2948
+ this._argsDescription = argsDescription;
2949
+ }
2950
+ return this;
2951
+ }
2952
+ /**
2953
+ * Set the summary. Used when listed as subcommand of parent.
2954
+ *
2955
+ * @param {string} [str]
2956
+ * @return {(string|Command)}
2957
+ */
2958
+ summary(str) {
2959
+ if (str === void 0) return this._summary;
2960
+ this._summary = str;
2961
+ return this;
2962
+ }
2963
+ /**
2964
+ * Set an alias for the command.
2965
+ *
2966
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
2967
+ *
2968
+ * @param {string} [alias]
2969
+ * @return {(string|Command)}
2970
+ */
2971
+ alias(alias) {
2972
+ if (alias === void 0) return this._aliases[0];
2973
+ let command = this;
2974
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
2975
+ command = this.commands[this.commands.length - 1];
2976
+ }
2977
+ if (alias === command._name)
2978
+ throw new Error("Command alias can't be the same as its name");
2979
+ const matchingCommand = this.parent?._findCommand(alias);
2980
+ if (matchingCommand) {
2981
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
2982
+ throw new Error(
2983
+ `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`
2984
+ );
2985
+ }
2986
+ command._aliases.push(alias);
2987
+ return this;
2988
+ }
2989
+ /**
2990
+ * Set aliases for the command.
2991
+ *
2992
+ * Only the first alias is shown in the auto-generated help.
2993
+ *
2994
+ * @param {string[]} [aliases]
2995
+ * @return {(string[]|Command)}
2996
+ */
2997
+ aliases(aliases) {
2998
+ if (aliases === void 0) return this._aliases;
2999
+ aliases.forEach((alias) => this.alias(alias));
3000
+ return this;
3001
+ }
3002
+ /**
3003
+ * Set / get the command usage `str`.
3004
+ *
3005
+ * @param {string} [str]
3006
+ * @return {(string|Command)}
3007
+ */
3008
+ usage(str) {
3009
+ if (str === void 0) {
3010
+ if (this._usage) return this._usage;
3011
+ const args = this.registeredArguments.map((arg) => {
3012
+ return humanReadableArgName(arg);
3013
+ });
3014
+ return [].concat(
3015
+ this.options.length || this._helpOption !== null ? "[options]" : [],
3016
+ this.commands.length ? "[command]" : [],
3017
+ this.registeredArguments.length ? args : []
3018
+ ).join(" ");
3019
+ }
3020
+ this._usage = str;
3021
+ return this;
3022
+ }
3023
+ /**
3024
+ * Get or set the name of the command.
3025
+ *
3026
+ * @param {string} [str]
3027
+ * @return {(string|Command)}
3028
+ */
3029
+ name(str) {
3030
+ if (str === void 0) return this._name;
3031
+ this._name = str;
3032
+ return this;
3033
+ }
3034
+ /**
3035
+ * Set/get the help group heading for this subcommand in parent command's help.
3036
+ *
3037
+ * @param {string} [heading]
3038
+ * @return {Command | string}
3039
+ */
3040
+ helpGroup(heading) {
3041
+ if (heading === void 0) return this._helpGroupHeading ?? "";
3042
+ this._helpGroupHeading = heading;
3043
+ return this;
3044
+ }
3045
+ /**
3046
+ * Set/get the default help group heading for subcommands added to this command.
3047
+ * (This does not override a group set directly on the subcommand using .helpGroup().)
3048
+ *
3049
+ * @example
3050
+ * program.commandsGroup('Development Commands:);
3051
+ * program.command('watch')...
3052
+ * program.command('lint')...
3053
+ * ...
3054
+ *
3055
+ * @param {string} [heading]
3056
+ * @returns {Command | string}
3057
+ */
3058
+ commandsGroup(heading) {
3059
+ if (heading === void 0) return this._defaultCommandGroup ?? "";
3060
+ this._defaultCommandGroup = heading;
3061
+ return this;
3062
+ }
3063
+ /**
3064
+ * Set/get the default help group heading for options added to this command.
3065
+ * (This does not override a group set directly on the option using .helpGroup().)
3066
+ *
3067
+ * @example
3068
+ * program
3069
+ * .optionsGroup('Development Options:')
3070
+ * .option('-d, --debug', 'output extra debugging')
3071
+ * .option('-p, --profile', 'output profiling information')
3072
+ *
3073
+ * @param {string} [heading]
3074
+ * @returns {Command | string}
3075
+ */
3076
+ optionsGroup(heading) {
3077
+ if (heading === void 0) return this._defaultOptionGroup ?? "";
3078
+ this._defaultOptionGroup = heading;
3079
+ return this;
3080
+ }
3081
+ /**
3082
+ * @param {Option} option
3083
+ * @private
3084
+ */
3085
+ _initOptionGroup(option) {
3086
+ if (this._defaultOptionGroup && !option.helpGroupHeading)
3087
+ option.helpGroup(this._defaultOptionGroup);
3088
+ }
3089
+ /**
3090
+ * @param {Command} cmd
3091
+ * @private
3092
+ */
3093
+ _initCommandGroup(cmd) {
3094
+ if (this._defaultCommandGroup && !cmd.helpGroup())
3095
+ cmd.helpGroup(this._defaultCommandGroup);
3096
+ }
3097
+ /**
3098
+ * Set the name of the command from script filename, such as process.argv[1],
3099
+ * or import.meta.filename.
3100
+ *
3101
+ * (Used internally and public although not documented in README.)
3102
+ *
3103
+ * @example
3104
+ * program.nameFromFilename(import.meta.filename);
3105
+ *
3106
+ * @param {string} filename
3107
+ * @return {Command}
3108
+ */
3109
+ nameFromFilename(filename) {
3110
+ this._name = path.basename(filename, path.extname(filename));
3111
+ return this;
3112
+ }
3113
+ /**
3114
+ * Get or set the directory for searching for executable subcommands of this command.
3115
+ *
3116
+ * @example
3117
+ * program.executableDir(import.meta.dirname);
3118
+ * // or
3119
+ * program.executableDir('subcommands');
3120
+ *
3121
+ * @param {string} [path]
3122
+ * @return {(string|null|Command)}
3123
+ */
3124
+ executableDir(path3) {
3125
+ if (path3 === void 0) return this._executableDir;
3126
+ this._executableDir = path3;
3127
+ return this;
3128
+ }
3129
+ /**
3130
+ * Return program help documentation.
3131
+ *
3132
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
3133
+ * @return {string}
3134
+ */
3135
+ helpInformation(contextOptions) {
3136
+ const helper = this.createHelp();
3137
+ const context = this._getOutputContext(contextOptions);
3138
+ helper.prepareContext({
3139
+ error: context.error,
3140
+ helpWidth: context.helpWidth,
3141
+ outputHasColors: context.hasColors
3142
+ });
3143
+ const text3 = helper.formatHelp(this, helper);
3144
+ if (context.hasColors) return text3;
3145
+ return this._outputConfiguration.stripColor(text3);
3146
+ }
3147
+ /**
3148
+ * @typedef HelpContext
3149
+ * @type {object}
3150
+ * @property {boolean} error
3151
+ * @property {number} helpWidth
3152
+ * @property {boolean} hasColors
3153
+ * @property {function} write - includes stripColor if needed
3154
+ *
3155
+ * @returns {HelpContext}
3156
+ * @private
3157
+ */
3158
+ _getOutputContext(contextOptions) {
3159
+ contextOptions = contextOptions || {};
3160
+ const error62 = !!contextOptions.error;
3161
+ let baseWrite;
3162
+ let hasColors;
3163
+ let helpWidth;
3164
+ if (error62) {
3165
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
3166
+ hasColors = this._outputConfiguration.getErrHasColors();
3167
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
3168
+ } else {
3169
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
3170
+ hasColors = this._outputConfiguration.getOutHasColors();
3171
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
3172
+ }
3173
+ const write = (str) => {
3174
+ if (!hasColors) str = this._outputConfiguration.stripColor(str);
3175
+ return baseWrite(str);
3176
+ };
3177
+ return { error: error62, write, hasColors, helpWidth };
3178
+ }
3179
+ /**
3180
+ * Output help information for this command.
3181
+ *
3182
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
3183
+ *
3184
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
3185
+ */
3186
+ outputHelp(contextOptions) {
3187
+ let deprecatedCallback;
3188
+ if (typeof contextOptions === "function") {
3189
+ deprecatedCallback = contextOptions;
3190
+ contextOptions = void 0;
3191
+ }
3192
+ const outputContext = this._getOutputContext(contextOptions);
3193
+ const eventContext = {
3194
+ error: outputContext.error,
3195
+ write: outputContext.write,
3196
+ command: this
3197
+ };
3198
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
3199
+ this.emit("beforeHelp", eventContext);
3200
+ let helpInformation = this.helpInformation({ error: outputContext.error });
3201
+ if (deprecatedCallback) {
3202
+ helpInformation = deprecatedCallback(helpInformation);
3203
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
3204
+ throw new Error("outputHelp callback must return a string or a Buffer");
3205
+ }
3206
+ }
3207
+ outputContext.write(helpInformation);
3208
+ if (this._getHelpOption()?.long) {
3209
+ this.emit(this._getHelpOption().long);
3210
+ }
3211
+ this.emit("afterHelp", eventContext);
3212
+ this._getCommandAndAncestors().forEach(
3213
+ (command) => command.emit("afterAllHelp", eventContext)
3214
+ );
3215
+ }
3216
+ /**
3217
+ * You can pass in flags and a description to customise the built-in help option.
3218
+ * Pass in false to disable the built-in help option.
3219
+ *
3220
+ * @example
3221
+ * program.helpOption('-?, --help' 'show help'); // customise
3222
+ * program.helpOption(false); // disable
3223
+ *
3224
+ * @param {(string | boolean)} flags
3225
+ * @param {string} [description]
3226
+ * @return {Command} `this` command for chaining
3227
+ */
3228
+ helpOption(flags, description) {
3229
+ if (typeof flags === "boolean") {
3230
+ if (flags) {
3231
+ if (this._helpOption === null) this._helpOption = void 0;
3232
+ if (this._defaultOptionGroup) {
3233
+ this._initOptionGroup(this._getHelpOption());
3234
+ }
3235
+ } else {
3236
+ this._helpOption = null;
3237
+ }
3238
+ return this;
3239
+ }
3240
+ this._helpOption = this.createOption(
3241
+ flags ?? "-h, --help",
3242
+ description ?? "display help for command"
3243
+ );
3244
+ if (flags || description) this._initOptionGroup(this._helpOption);
3245
+ return this;
3246
+ }
3247
+ /**
3248
+ * Lazy create help option.
3249
+ * Returns null if has been disabled with .helpOption(false).
3250
+ *
3251
+ * @returns {(Option | null)} the help option
3252
+ * @package
3253
+ */
3254
+ _getHelpOption() {
3255
+ if (this._helpOption === void 0) {
3256
+ this.helpOption(void 0, void 0);
3257
+ }
3258
+ return this._helpOption;
3259
+ }
3260
+ /**
3261
+ * Supply your own option to use for the built-in help option.
3262
+ * This is an alternative to using helpOption() to customise the flags and description etc.
3263
+ *
3264
+ * @param {Option} option
3265
+ * @return {Command} `this` command for chaining
3266
+ */
3267
+ addHelpOption(option) {
3268
+ this._helpOption = option;
3269
+ this._initOptionGroup(option);
3270
+ return this;
3271
+ }
3272
+ /**
3273
+ * Output help information and exit.
3274
+ *
3275
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
3276
+ *
3277
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
3278
+ */
3279
+ help(contextOptions) {
3280
+ this.outputHelp(contextOptions);
3281
+ let exitCode = Number(process2.exitCode ?? 0);
3282
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
3283
+ exitCode = 1;
3284
+ }
3285
+ this._exit(exitCode, "commander.help", "(outputHelp)");
3286
+ }
3287
+ /**
3288
+ * // Do a little typing to coordinate emit and listener for the help text events.
3289
+ * @typedef HelpTextEventContext
3290
+ * @type {object}
3291
+ * @property {boolean} error
3292
+ * @property {Command} command
3293
+ * @property {function} write
3294
+ */
3295
+ /**
3296
+ * Add additional text to be displayed with the built-in help.
3297
+ *
3298
+ * Position is 'before' or 'after' to affect just this command,
3299
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
3300
+ *
3301
+ * @param {string} position - before or after built-in help
3302
+ * @param {(string | Function)} text - string to add, or a function returning a string
3303
+ * @return {Command} `this` command for chaining
3304
+ */
3305
+ addHelpText(position2, text3) {
3306
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
3307
+ if (!allowedValues.includes(position2)) {
3308
+ throw new Error(`Unexpected value for position to addHelpText.
3309
+ Expecting one of '${allowedValues.join("', '")}'`);
3310
+ }
3311
+ const helpEvent = `${position2}Help`;
3312
+ this.on(helpEvent, (context) => {
3313
+ let helpStr;
3314
+ if (typeof text3 === "function") {
3315
+ helpStr = text3({ error: context.error, command: context.command });
3316
+ } else {
3317
+ helpStr = text3;
3318
+ }
3319
+ if (helpStr) {
3320
+ context.write(`${helpStr}
3321
+ `);
3322
+ }
3323
+ });
3324
+ return this;
3325
+ }
3326
+ /**
3327
+ * Output help information if help flags specified
3328
+ *
3329
+ * @param {Array} args - array of options to search for help flags
3330
+ * @private
3331
+ */
3332
+ _outputHelpIfRequested(args) {
3333
+ const helpOption = this._getHelpOption();
3334
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
3335
+ if (helpRequested) {
3336
+ this.outputHelp();
3337
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
3338
+ }
3339
+ }
3340
+ };
3341
+ function incrementNodeInspectorPort(args) {
3342
+ return args.map((arg) => {
3343
+ if (!arg.startsWith("--inspect")) {
3344
+ return arg;
3345
+ }
3346
+ let debugOption;
3347
+ let debugHost = "127.0.0.1";
3348
+ let debugPort = "9229";
3349
+ let match;
3350
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
3351
+ debugOption = match[1];
3352
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
3353
+ debugOption = match[1];
3354
+ if (/^\d+$/.test(match[3])) {
3355
+ debugPort = match[3];
3356
+ } else {
3357
+ debugHost = match[3];
3358
+ }
3359
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
3360
+ debugOption = match[1];
3361
+ debugHost = match[3];
3362
+ debugPort = match[4];
3363
+ }
3364
+ if (debugOption && debugPort !== "0") {
3365
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
3366
+ }
3367
+ return arg;
3368
+ });
3369
+ }
3370
+ function useColor() {
3371
+ if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
3372
+ return false;
3373
+ if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== void 0)
3374
+ return true;
3375
+ return void 0;
3376
+ }
3377
+
3378
+ // ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/index.js
3379
+ var program = new Command();
3380
+
13
3381
  // package.json
14
3382
  var package_default = {
15
3383
  name: "@moxt-ai/mobius",
16
- version: "0.0.88",
3384
+ version: "0.0.90",
17
3385
  description: "Mobius CLI for pairing and running local AI agent services.",
18
3386
  type: "module",
19
3387
  bin: {
@@ -52,6 +3420,7 @@ var package_default = {
52
3420
  },
53
3421
  dependencies: {
54
3422
  "@agentclientprotocol/sdk": "^1.4.0",
3423
+ commander: "15.0.0",
55
3424
  "mdast-util-from-markdown": "2.0.3",
56
3425
  undici: "8.10.2",
57
3426
  "unist-util-visit": "5.1.0",
@@ -658,8 +4027,8 @@ async function runBoundedProcess(options) {
658
4027
  }
659
4028
 
660
4029
  // src/agent-catalog/local-agent.ts
661
- function readTrustedIdentity(path2) {
662
- const resolvedPath = realpathSync(path2);
4030
+ function readTrustedIdentity(path3) {
4031
+ const resolvedPath = realpathSync(path3);
663
4032
  const metadata = statSync(resolvedPath);
664
4033
  return new ExecutableIdentity(
665
4034
  resolvedPath,
@@ -1038,9 +4407,9 @@ function isContainedPath(root, candidate) {
1038
4407
  const difference = relative(root, candidate);
1039
4408
  return difference.length > 0 && difference !== ".." && !difference.startsWith(`..${sep}`) && !isAbsolute(difference);
1040
4409
  }
1041
- async function readJsonRecord(path2, maximumBytes) {
4410
+ async function readJsonRecord(path3, maximumBytes) {
1042
4411
  try {
1043
- const handle = await open(path2, "r");
4412
+ const handle = await open(path3, "r");
1044
4413
  try {
1045
4414
  const metadata = await handle.stat();
1046
4415
  if (!metadata.isFile() || metadata.size > maximumBytes) {
@@ -2274,10 +5643,10 @@ function mergeDefs(...defs) {
2274
5643
  function cloneDef(schema) {
2275
5644
  return mergeDefs(schema._zod.def);
2276
5645
  }
2277
- function getElementAtPath(obj, path2) {
2278
- if (!path2)
5646
+ function getElementAtPath(obj, path3) {
5647
+ if (!path3)
2279
5648
  return obj;
2280
- return path2.reduce((acc, key) => acc?.[key], obj);
5649
+ return path3.reduce((acc, key) => acc?.[key], obj);
2281
5650
  }
2282
5651
  function promiseAllObject(promisesObj) {
2283
5652
  const keys = Object.keys(promisesObj);
@@ -2617,11 +5986,11 @@ function explicitlyAborted(x, startIndex = 0) {
2617
5986
  }
2618
5987
  return false;
2619
5988
  }
2620
- function prefixIssues(path2, issues) {
5989
+ function prefixIssues(path3, issues) {
2621
5990
  return issues.map((iss) => {
2622
5991
  var _a3;
2623
5992
  (_a3 = iss).path ?? (_a3.path = []);
2624
- iss.path.unshift(path2);
5993
+ iss.path.unshift(path3);
2625
5994
  return iss;
2626
5995
  });
2627
5996
  }
@@ -3071,16 +6440,16 @@ function flattenError(error62, mapper = (issue2) => issue2.message) {
3071
6440
  }
3072
6441
  function formatError(error62, mapper = (issue2) => issue2.message) {
3073
6442
  const fieldErrors = { _errors: [] };
3074
- const processError = (error63, path2 = []) => {
6443
+ const processError = (error63, path3 = []) => {
3075
6444
  for (const issue2 of error63.issues) {
3076
6445
  if (issue2.code === "invalid_union" && issue2.errors.length) {
3077
- issue2.errors.map((issues) => processError({ issues }, [...path2, ...issue2.path]));
6446
+ issue2.errors.map((issues) => processError({ issues }, [...path3, ...issue2.path]));
3078
6447
  } else if (issue2.code === "invalid_key") {
3079
- processError({ issues: issue2.issues }, [...path2, ...issue2.path]);
6448
+ processError({ issues: issue2.issues }, [...path3, ...issue2.path]);
3080
6449
  } else if (issue2.code === "invalid_element") {
3081
- processError({ issues: issue2.issues }, [...path2, ...issue2.path]);
6450
+ processError({ issues: issue2.issues }, [...path3, ...issue2.path]);
3082
6451
  } else {
3083
- const fullpath = [...path2, ...issue2.path];
6452
+ const fullpath = [...path3, ...issue2.path];
3084
6453
  if (fullpath.length === 0) {
3085
6454
  fieldErrors._errors.push(mapper(issue2));
3086
6455
  } else {
@@ -3119,17 +6488,17 @@ function formatError(error62, mapper = (issue2) => issue2.message) {
3119
6488
  }
3120
6489
  function treeifyError(error62, mapper = (issue2) => issue2.message) {
3121
6490
  const result = { errors: [] };
3122
- const processError = (error63, path2 = []) => {
6491
+ const processError = (error63, path3 = []) => {
3123
6492
  var _a3;
3124
6493
  for (const issue2 of error63.issues) {
3125
6494
  if (issue2.code === "invalid_union" && issue2.errors.length) {
3126
- issue2.errors.map((issues) => processError({ issues }, [...path2, ...issue2.path]));
6495
+ issue2.errors.map((issues) => processError({ issues }, [...path3, ...issue2.path]));
3127
6496
  } else if (issue2.code === "invalid_key") {
3128
- processError({ issues: issue2.issues }, [...path2, ...issue2.path]);
6497
+ processError({ issues: issue2.issues }, [...path3, ...issue2.path]);
3129
6498
  } else if (issue2.code === "invalid_element") {
3130
- processError({ issues: issue2.issues }, [...path2, ...issue2.path]);
6499
+ processError({ issues: issue2.issues }, [...path3, ...issue2.path]);
3131
6500
  } else {
3132
- const fullpath = [...path2, ...issue2.path];
6501
+ const fullpath = [...path3, ...issue2.path];
3133
6502
  if (fullpath.length === 0) {
3134
6503
  result.errors.push(mapper(issue2));
3135
6504
  continue;
@@ -3168,8 +6537,8 @@ function treeifyError(error62, mapper = (issue2) => issue2.message) {
3168
6537
  }
3169
6538
  function toDotPath(_path) {
3170
6539
  const segs = [];
3171
- const path2 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
3172
- for (const seg of path2) {
6540
+ const path3 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
6541
+ for (const seg of path3) {
3173
6542
  if (typeof seg === "number")
3174
6543
  segs.push(`[${seg}]`);
3175
6544
  else if (typeof seg === "symbol")
@@ -20271,13 +23640,13 @@ function resolveRef(ref, ctx) {
20271
23640
  if (!ref.startsWith("#")) {
20272
23641
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
20273
23642
  }
20274
- const path2 = ref.slice(1).split("/").filter(Boolean);
20275
- if (path2.length === 0) {
23643
+ const path3 = ref.slice(1).split("/").filter(Boolean);
23644
+ if (path3.length === 0) {
20276
23645
  return ctx.rootSchema;
20277
23646
  }
20278
23647
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
20279
- if (path2[0] === defsKey) {
20280
- const key = path2[1] === void 0 ? void 0 : decodeJSONPointerSegment(path2[1]);
23648
+ if (path3[0] === defsKey) {
23649
+ const key = path3[1] === void 0 ? void 0 : decodeJSONPointerSegment(path3[1]);
20281
23650
  if (!key || !ctx.defs[key]) {
20282
23651
  throw new Error(`Reference not found: ${ref}`);
20283
23652
  }
@@ -21640,7 +25009,7 @@ function presentToolItem(item) {
21640
25009
  return {
21641
25010
  content: content3,
21642
25011
  kind: "edit",
21643
- locations: paths.map((path2) => ({ path: path2 })),
25012
+ locations: paths.map((path3) => ({ path: path3 })),
21644
25013
  rawInput: { changes: item.changes.map((change) => change.path) },
21645
25014
  rawOutput: null,
21646
25015
  status: patchStatus(item.status),
@@ -22779,15 +26148,15 @@ var DEEPSEEK_HARNESS_IMAGE_PROMPT_PATCH = `# Managed by Mobius: pin the ACP brid
22779
26148
  provider: deepseek-official
22780
26149
  model: deepseek-v4-flash-vision-exp
22781
26150
  `;
22782
- async function prepareAgentHome(path2, imagePrompts) {
22783
- if (!isAbsolute3(path2) || normalize(path2) !== path2) {
26151
+ async function prepareAgentHome(path3, imagePrompts) {
26152
+ if (!isAbsolute3(path3) || normalize(path3) !== path3) {
22784
26153
  throw new AgentProbeError("agent_environment_invalid", "The configured Agent home is invalid");
22785
26154
  }
22786
26155
  try {
22787
26156
  if (imagePrompts) {
22788
- await mkdir2(path2, { mode: 448, recursive: true });
26157
+ await mkdir2(path3, { mode: 448, recursive: true });
22789
26158
  }
22790
- const resolved = await realpath3(path2);
26159
+ const resolved = await realpath3(path3);
22791
26160
  const metadata = await stat3(resolved);
22792
26161
  if (!metadata.isDirectory() || typeof process.getuid === "function" && metadata.uid !== process.getuid()) {
22793
26162
  throw new Error("Agent home is not a user-owned directory");
@@ -23235,10 +26604,10 @@ function isContainedPath3(root, candidate) {
23235
26604
  const difference = relative3(root, candidate);
23236
26605
  return difference.length > 0 && difference !== ".." && !difference.startsWith(`..${sep3}`) && !isAbsolute5(difference);
23237
26606
  }
23238
- async function hashFile(path2, signal) {
26607
+ async function hashFile(path3, signal) {
23239
26608
  signal.throwIfAborted();
23240
26609
  const digest = createHash("sha256");
23241
- const stream = createReadStream(path2, { signal });
26610
+ const stream = createReadStream(path3, { signal });
23242
26611
  try {
23243
26612
  for await (const chunk of stream) {
23244
26613
  signal.throwIfAborted();
@@ -23265,10 +26634,10 @@ async function hashFile(path2, signal) {
23265
26634
  );
23266
26635
  }
23267
26636
  }
23268
- async function readManifest(path2) {
26637
+ async function readManifest(path3) {
23269
26638
  let handle;
23270
26639
  try {
23271
- handle = await open3(path2, "r");
26640
+ handle = await open3(path3, "r");
23272
26641
  } catch (error62) {
23273
26642
  throw new ManagedAgentArchiveError(
23274
26643
  "managed_archive_verification_failed",
@@ -26637,7 +30006,7 @@ function decodeVerifiedConnection(value) {
26637
30006
  validateConnectionId(connectionId2),
26638
30007
  validateIdentifier(channelId, "invalid_connection"),
26639
30008
  defaultWorkspace,
26640
- current || versionThree ? validateIdentifier(savedPairingId, "invalid_connection") : "",
30009
+ (current || versionThree) && savedPairingId.length > 0 ? validateIdentifier(savedPairingId, "invalid_connection") : "",
26641
30010
  parseRelayOrigin(relayOrigin),
26642
30011
  validateRuntimeCredential(runtimeCredential2),
26643
30012
  validateIdentifier(runtimeId, "invalid_connection")
@@ -26683,11 +30052,11 @@ function decodeConnection(value) {
26683
30052
  }
26684
30053
  throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
26685
30054
  }
26686
- async function readJsonFile(path2, signal, missingCode) {
30055
+ async function readJsonFile(path3, signal, missingCode) {
26687
30056
  signal.throwIfAborted();
26688
30057
  let handle;
26689
30058
  try {
26690
- handle = await open4(path2, "r");
30059
+ handle = await open4(path3, "r");
26691
30060
  } catch (cause) {
26692
30061
  if (isNodeError(cause, "ENOENT")) {
26693
30062
  throw new RuntimeInstallationStoreError(missingCode, "The saved Runtime connection was not found", {
@@ -26721,9 +30090,9 @@ async function readJsonFile(path2, signal, missingCode) {
26721
30090
  });
26722
30091
  }
26723
30092
  }
26724
- async function writeJsonAtomically(path2, value, signal) {
30093
+ async function writeJsonAtomically(path3, value, signal) {
26725
30094
  signal.throwIfAborted();
26726
- const directory = dirname3(path2);
30095
+ const directory = dirname3(path3);
26727
30096
  const temporaryPath = join15(directory, `.${randomUUID()}.tmp`);
26728
30097
  try {
26729
30098
  await mkdir4(directory, { mode: 448, recursive: true });
@@ -26731,7 +30100,7 @@ async function writeJsonAtomically(path2, value, signal) {
26731
30100
  await writeFile3(temporaryPath, `${JSON.stringify(value, null, 2)}
26732
30101
  `, { flag: "wx", mode: 384 });
26733
30102
  signal.throwIfAborted();
26734
- await rename3(temporaryPath, path2);
30103
+ await rename3(temporaryPath, path3);
26735
30104
  } catch (cause) {
26736
30105
  await unlink(temporaryPath).catch(() => void 0);
26737
30106
  signal.throwIfAborted();
@@ -27116,8 +30485,8 @@ function parseResumeConnectionId(arguments_) {
27116
30485
  }
27117
30486
  return value;
27118
30487
  }
27119
- async function resolveDefaultWorkspace(path2) {
27120
- const requestedWorkspace = resolve5(path2);
30488
+ async function resolveDefaultWorkspace(path3) {
30489
+ const requestedWorkspace = resolve5(path3);
27121
30490
  try {
27122
30491
  await mkdir5(requestedWorkspace, { recursive: true, mode: 448 });
27123
30492
  const defaultWorkspace = await realpath6(requestedWorkspace);
@@ -27320,9 +30689,9 @@ import { dirname as dirname4 } from "node:path";
27320
30689
  import { DatabaseSync } from "node:sqlite";
27321
30690
  var AuditStore = class {
27322
30691
  database;
27323
- constructor(path2) {
27324
- mkdirSync(dirname4(path2), { recursive: true });
27325
- this.database = new DatabaseSync(path2);
30692
+ constructor(path3) {
30693
+ mkdirSync(dirname4(path3), { recursive: true });
30694
+ this.database = new DatabaseSync(path3);
27326
30695
  this.database.exec(`
27327
30696
  CREATE TABLE IF NOT EXISTS audit_events (
27328
30697
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -35446,13 +38815,13 @@ async function emitMarkdownChunksWithLocalImages(options) {
35446
38815
  }
35447
38816
 
35448
38817
  // src/acp/native-session.ts
35449
- var path = external_exports.string().min(1).max(2048).refine((value) => !value.includes("\0"));
38818
+ var path2 = external_exports.string().min(1).max(2048).refine((value) => !value.includes("\0"));
35450
38819
  var title = external_exports.string().transform((value) => value.slice(0, 500));
35451
38820
  var nativeSessionIdSchema = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,255}$/);
35452
38821
  var nativeSessionInfoSchema = external_exports.object({
35453
38822
  sessionId: nativeSessionIdSchema,
35454
- cwd: path,
35455
- additionalDirectories: external_exports.array(path).max(16).default([]).readonly(),
38823
+ cwd: path2,
38824
+ additionalDirectories: external_exports.array(path2).max(16).default([]).readonly(),
35456
38825
  title: title.nullish(),
35457
38826
  updatedAt: external_exports.iso.datetime({ offset: true }).nullish()
35458
38827
  }).readonly();
@@ -35974,9 +39343,9 @@ var MemoryAcpSessionStore = class {
35974
39343
  };
35975
39344
  var SqliteAcpSessionStore = class {
35976
39345
  #database;
35977
- constructor(path2) {
35978
- mkdirSync2(dirname5(path2), { recursive: true });
35979
- this.#database = new DatabaseSync2(path2);
39346
+ constructor(path3) {
39347
+ mkdirSync2(dirname5(path3), { recursive: true });
39348
+ this.#database = new DatabaseSync2(path3);
35980
39349
  this.#database.exec(`
35981
39350
  CREATE TABLE IF NOT EXISTS acp_deleted_sessions (session_id TEXT PRIMARY KEY) STRICT;
35982
39351
  CREATE TABLE IF NOT EXISTS acp_sessions (
@@ -39549,9 +42918,9 @@ function findSpecification(specifications, agentId) {
39549
42918
  }
39550
42919
  throw new InstallationManagerError("unknown_agent", "The requested Agent is not supported");
39551
42920
  }
39552
- function resolveDefaultWorkspace2(path2) {
42921
+ function resolveDefaultWorkspace2(path3) {
39553
42922
  try {
39554
- const directory = realpathSync2(resolve6(path2));
42923
+ const directory = realpathSync2(resolve6(path3));
39555
42924
  if (!statSync2(directory).isDirectory()) {
39556
42925
  throw new Error("Default workspace is not a directory");
39557
42926
  }
@@ -39564,9 +42933,9 @@ function resolveDefaultWorkspace2(path2) {
39564
42933
  );
39565
42934
  }
39566
42935
  }
39567
- function resolveIntegrationStateDirectory(path2) {
42936
+ function resolveIntegrationStateDirectory(path3) {
39568
42937
  try {
39569
- const directory = realpathSync2(resolve6(path2));
42938
+ const directory = realpathSync2(resolve6(path3));
39570
42939
  const metadata = statSync2(directory);
39571
42940
  if (!metadata.isDirectory() || typeof process.getuid === "function" && metadata.uid !== process.getuid()) {
39572
42941
  throw new Error("Installation directory is not user-owned");
@@ -39841,8 +43210,8 @@ var WorkspaceDirectoryListing = class {
39841
43210
  this.parentDirectoryId = parentDirectoryId;
39842
43211
  }
39843
43212
  };
39844
- function encodePath(path2) {
39845
- const encoded = Buffer.from(path2, "utf8").toString("base64url");
43213
+ function encodePath(path3) {
43214
+ const encoded = Buffer.from(path3, "utf8").toString("base64url");
39846
43215
  if (encoded.length === 0 || encoded.length > 2e3) {
39847
43216
  throw new LocalAuthorizationError("The local directory path is too long to select");
39848
43217
  }
@@ -39879,9 +43248,9 @@ var WorkspaceDirectoryService = class {
39879
43248
  return homedir2();
39880
43249
  }
39881
43250
  if (id.startsWith("path-")) {
39882
- const path2 = decodePath(id, "path-");
39883
- if (isAbsolute10(path2)) {
39884
- return path2;
43251
+ const path3 = decodePath(id, "path-");
43252
+ if (isAbsolute10(path3)) {
43253
+ return path3;
39885
43254
  }
39886
43255
  }
39887
43256
  throw new LocalAuthorizationError("The directory identifier is invalid");
@@ -39910,18 +43279,18 @@ var WorkspaceDirectoryService = class {
39910
43279
  });
39911
43280
  }
39912
43281
  };
39913
- label = (path2) => {
39914
- const suffix = relative4(homedir2(), path2);
39915
- return suffix === "" ? "~" : !isAbsolute10(suffix) && suffix !== ".." && !suffix.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) ? `~/${suffix.replaceAll("\\", "/")}` : path2;
43282
+ label = (path3) => {
43283
+ const suffix = relative4(homedir2(), path3);
43284
+ return suffix === "" ? "~" : !isAbsolute10(suffix) && suffix !== ".." && !suffix.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) ? `~/${suffix.replaceAll("\\", "/")}` : path3;
39916
43285
  };
39917
43286
  identify = async (bindingId, requestedPath2, signal) => {
39918
43287
  this.authorizeMachine(bindingId);
39919
- const path2 = await this.resolvePath(requestedPath2, signal);
43288
+ const path3 = await this.resolvePath(requestedPath2, signal);
39920
43289
  return {
39921
- path: path2,
39922
- directoryId: encodePath(path2),
39923
- name: basename5(path2) || path2,
39924
- label: this.label(path2)
43290
+ path: path3,
43291
+ directoryId: encodePath(path3),
43292
+ name: basename5(path3) || path3,
43293
+ label: this.label(path3)
39925
43294
  };
39926
43295
  };
39927
43296
  resolve = async (bindingId, id, signal) => {
@@ -39942,8 +43311,8 @@ var WorkspaceDirectoryService = class {
39942
43311
  continue;
39943
43312
  }
39944
43313
  try {
39945
- const path2 = await this.resolvePath(join16(target, child.name), signal);
39946
- entries.push({ directoryId: encodePath(path2), name: child.name });
43314
+ const path3 = await this.resolvePath(join16(target, child.name), signal);
43315
+ entries.push({ directoryId: encodePath(path3), name: child.name });
39947
43316
  } catch (cause) {
39948
43317
  signal.throwIfAborted();
39949
43318
  if (!(cause instanceof LocalAuthorizationError)) {
@@ -40037,7 +43406,7 @@ var responseSchema = external_exports.union([
40037
43406
  var threadSchema = external_exports.object({
40038
43407
  thread: external_exports.object({
40039
43408
  id: nativeSessionIdSchema,
40040
- cwd: external_exports.string().min(1).max(2048).refine((path2) => !path2.includes("\0"))
43409
+ cwd: external_exports.string().min(1).max(2048).refine((path3) => !path3.includes("\0"))
40041
43410
  })
40042
43411
  });
40043
43412
  var turnsSchema = external_exports.object({
@@ -40671,13 +44040,13 @@ var NativeSessionService = class {
40671
44040
  const additionalEntries = [];
40672
44041
  const resolvedPaths = /* @__PURE__ */ new Set([cwd]);
40673
44042
  for (const directoryId2 of command.additionalDirectoryIds) {
40674
- const path2 = await this.#directories.resolve(this.#config.bindingId, directoryId2, signal);
40675
- if (resolvedPaths.has(path2)) {
44043
+ const path3 = await this.#directories.resolve(this.#config.bindingId, directoryId2, signal);
44044
+ if (resolvedPaths.has(path3)) {
40676
44045
  throw new LocalAuthorizationError("Workspace directories must resolve to distinct locations");
40677
44046
  }
40678
- resolvedPaths.add(path2);
40679
- additionalDirectories.push(path2);
40680
- additionalEntries.push({ directoryId: directoryId2, name: basename6(path2) });
44047
+ resolvedPaths.add(path3);
44048
+ additionalDirectories.push(path3);
44049
+ additionalEntries.push({ directoryId: directoryId2, name: basename6(path3) });
40681
44050
  }
40682
44051
  const listing = await this.#directories.list(this.#config.bindingId, command.directoryId, signal);
40683
44052
  const opened = await this.#sessions.forkSessionAtTurn(
@@ -40756,8 +44125,8 @@ var NativeSessionService = class {
40756
44125
  const additionalDirectories = [];
40757
44126
  const additionalEntries = [];
40758
44127
  const paths = /* @__PURE__ */ new Set([primary.path]);
40759
- for (const path2 of info.additionalDirectories) {
40760
- const directory = await this.#directories.identify(command.bindingId, path2, options.signal);
44128
+ for (const path3 of info.additionalDirectories) {
44129
+ const directory = await this.#directories.identify(command.bindingId, path3, options.signal);
40761
44130
  if (paths.has(directory.path)) {
40762
44131
  throw new LocalAuthorizationError("Native session roots must be distinct");
40763
44132
  }
@@ -40795,7 +44164,7 @@ var NativeSessionService = class {
40795
44164
  if (target === null) {
40796
44165
  throw new LocalAuthorizationError("The selected native session is not authorized");
40797
44166
  }
40798
- if (target.cwd !== selected.cwd || target.additionalDirectories.length !== selected.additionalDirectories.length || target.additionalDirectories.some((path2, index3) => path2 !== selected.additionalDirectories[index3])) {
44167
+ if (target.cwd !== selected.cwd || target.additionalDirectories.length !== selected.additionalDirectories.length || target.additionalDirectories.some((path3, index3) => path3 !== selected.additionalDirectories[index3])) {
40799
44168
  throw new AcpExecutionError(
40800
44169
  "This session's directory changed. Refresh the list before continuing.",
40801
44170
  {},
@@ -41609,11 +44978,11 @@ function rowString(row, field) {
41609
44978
  var SessionEventOutbox = class {
41610
44979
  #database;
41611
44980
  #limits;
41612
- constructor(path2, limits = DEFAULT_OUTBOX_LIMITS) {
44981
+ constructor(path3, limits = DEFAULT_OUTBOX_LIMITS) {
41613
44982
  validateLimits(limits);
41614
44983
  this.#limits = limits;
41615
- mkdirSync4(dirname7(path2), { recursive: true });
41616
- this.#database = new DatabaseSync3(path2);
44984
+ mkdirSync4(dirname7(path3), { recursive: true });
44985
+ this.#database = new DatabaseSync3(path3);
41617
44986
  this.#database.exec(`
41618
44987
  CREATE TABLE IF NOT EXISTS relay_session_event_outbox (
41619
44988
  ordinal INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -45055,17 +48424,17 @@ var START_TIMEOUT_MILLISECONDS = 12e4;
45055
48424
  var MAXIMUM_MESSAGE_BYTES = 64 * 1024;
45056
48425
  var CONNECTION_ID_PATTERN2 = /^mcn_[a-f0-9]{32}$/;
45057
48426
  async function acquireManagerLock(stateDirectory) {
45058
- const path2 = join18(stateDirectory, "manager.lock");
48427
+ const path3 = join18(stateDirectory, "manager.lock");
45059
48428
  for (let attempt = 0; attempt < 2; attempt += 1) {
45060
48429
  try {
45061
- await writeFile4(path2, `${process.pid.toString()}
48430
+ await writeFile4(path3, `${process.pid.toString()}
45062
48431
  `, { flag: "wx", mode: 384 });
45063
- return async () => await unlink2(path2).catch(() => void 0);
48432
+ return async () => await unlink2(path3).catch(() => void 0);
45064
48433
  } catch (cause) {
45065
48434
  if (!isNodeError2(cause, "EEXIST")) {
45066
48435
  throw cause;
45067
48436
  }
45068
- const encoded = await readFile3(path2, "utf8").catch(() => "");
48437
+ const encoded = await readFile3(path3, "utf8").catch(() => "");
45069
48438
  const pid = Number(encoded.trim());
45070
48439
  if (Number.isSafeInteger(pid) && pid > 1) {
45071
48440
  try {
@@ -45077,7 +48446,7 @@ async function acquireManagerLock(stateDirectory) {
45077
48446
  }
45078
48447
  }
45079
48448
  }
45080
- await unlink2(path2).catch(() => void 0);
48449
+ await unlink2(path3).catch(() => void 0);
45081
48450
  }
45082
48451
  }
45083
48452
  return null;
@@ -45093,9 +48462,9 @@ function controlTokenPath(stateDirectory) {
45093
48462
  return join18(stateDirectory, "manager.token");
45094
48463
  }
45095
48464
  async function readOrCreateControlToken(stateDirectory) {
45096
- const path2 = controlTokenPath(stateDirectory);
48465
+ const path3 = controlTokenPath(stateDirectory);
45097
48466
  try {
45098
- return (await readFile3(path2, "utf8")).trim();
48467
+ return (await readFile3(path3, "utf8")).trim();
45099
48468
  } catch (cause) {
45100
48469
  if (!isNodeError2(cause, "ENOENT")) {
45101
48470
  throw cause;
@@ -45103,14 +48472,14 @@ async function readOrCreateControlToken(stateDirectory) {
45103
48472
  }
45104
48473
  const token = randomBytes(32).toString("base64url");
45105
48474
  try {
45106
- await writeFile4(path2, `${token}
48475
+ await writeFile4(path3, `${token}
45107
48476
  `, { flag: "wx", mode: 384 });
45108
48477
  return token;
45109
48478
  } catch (cause) {
45110
48479
  if (!isNodeError2(cause, "EEXIST")) {
45111
48480
  throw cause;
45112
48481
  }
45113
- return (await readFile3(path2, "utf8")).trim();
48482
+ return (await readFile3(path3, "utf8")).trim();
45114
48483
  }
45115
48484
  }
45116
48485
  function isNodeError2(error62, code) {
@@ -45614,28 +48983,6 @@ async function runManager(installation, managerVersion, signal) {
45614
48983
  var shutdown = new AbortController();
45615
48984
  process.once("SIGINT", () => shutdown.abort());
45616
48985
  process.once("SIGTERM", () => shutdown.abort());
45617
- var USAGE = `Mobius CLI
45618
-
45619
- Usage:
45620
- mobius --version
45621
- mobius pair --url <relay-url> --pairing <runtime-pairing-id> --code <pairing-code> [--app-id <app-id>] [--workspace <directory>]
45622
- mobius pair list [--output-json=<existing-file.json>]
45623
- mobius pair stop --connection <connection-id>
45624
- mobius pair remove --connection <connection-id>
45625
- mobius start --connection <connection-id>
45626
- mobius quit
45627
- mobius agents [--json]
45628
-
45629
- Commands:
45630
- --version Print the installed Mobius CLI version
45631
- pair Pair this machine or list, stop, and remove managed pairings
45632
- start Start the manager and activate a saved connection
45633
- quit Stop the manager and every active Runtime
45634
- agents Show detected, missing, and integration-ready Agents
45635
-
45636
- Pairing grants this browser access to the machine with your user account's permissions.
45637
- New conversations default to this Mobius installation's private workspace; choose other directories in the browser.
45638
- `;
45639
48986
  function formatPairTable(pairs) {
45640
48987
  const headers = ["connection_id", "app_id", "runtime_id", "workspace", "status"];
45641
48988
  const rows = pairs.map((pair) => [pair.connectionId, pair.appId, pair.runtimeId, pair.workspace, pair.status]);
@@ -45648,22 +48995,42 @@ function formatPairTable(pairs) {
45648
48995
  ${divider}
45649
48996
  ${rows.map(line).join("\n")}${rows.length === 0 ? "" : "\n"}`;
45650
48997
  }
45651
- function pairListOutputPath(arguments_) {
45652
- if (arguments_.length === 0) {
45653
- return null;
45654
- }
45655
- const prefix = "--output-json=";
45656
- const option = arguments_.length === 1 ? arguments_[0] : void 0;
45657
- if (option === void 0 || !option.startsWith(prefix) || option.length === prefix.length) {
45658
- throw new Error("Usage: mobius pair list [--output-json=<existing-file.json>]");
48998
+ function readOnce(optionName) {
48999
+ return (value, previous2) => {
49000
+ if (previous2 !== void 0) {
49001
+ throw new InvalidArgumentError(`${optionName} may only be specified once`);
49002
+ }
49003
+ return value;
49004
+ };
49005
+ }
49006
+ function valueOption(flags, description, mandatory = false) {
49007
+ const option = new Option(flags, description).argParser(readOnce(flags.split(" ")[0] ?? flags));
49008
+ return mandatory ? option.makeOptionMandatory() : option;
49009
+ }
49010
+ function requireOption(value, flags, command) {
49011
+ if (value === void 0) {
49012
+ command.error(`required option '${flags}' not specified`, {
49013
+ code: "commander.missingMandatoryOptionValue"
49014
+ });
45659
49015
  }
45660
- return resolve7(option.slice(prefix.length));
49016
+ return value;
49017
+ }
49018
+ function pairArguments(options) {
49019
+ return [
49020
+ "--url",
49021
+ options.url,
49022
+ "--code",
49023
+ options.code,
49024
+ ...options.pairing === void 0 ? [] : ["--pairing", options.pairing],
49025
+ ...options.appId === void 0 ? [] : ["--app-id", options.appId],
49026
+ ...options.workspace === void 0 ? [] : ["--workspace", options.workspace]
49027
+ ];
45661
49028
  }
45662
- async function writePairList(path2, pairs) {
49029
+ async function writePairList(path3, pairs) {
45663
49030
  shutdown.signal.throwIfAborted();
45664
49031
  let file2;
45665
49032
  try {
45666
- file2 = await open7(path2, constants2.O_WRONLY | constants2.O_NOFOLLOW);
49033
+ file2 = await open7(path3, constants2.O_WRONLY | constants2.O_NOFOLLOW);
45667
49034
  } catch (cause) {
45668
49035
  if (typeof cause === "object" && cause !== null && "code" in cause && cause.code === "ENOENT") {
45669
49036
  throw new Error("The JSON output file does not exist", { cause });
@@ -45690,24 +49057,19 @@ async function writePairList(path2, pairs) {
45690
49057
  await file2.close();
45691
49058
  }
45692
49059
  }
45693
- async function main() {
45694
- const command = process.argv[2];
45695
- if (command === void 0 || command === "--help" || command === "-h") {
45696
- process.stdout.write(USAGE);
45697
- return;
45698
- }
45699
- if (command === "--version" || command === "-v" || command === "version") {
49060
+ function createProgram() {
49061
+ const program2 = new Command().name("mobius").description("Pair and run local AI agent services.").version(package_default.version, "-v, --version", "print the installed Mobius CLI version").showHelpAfterError().exitOverride().addHelpText(
49062
+ "after",
49063
+ "\nPairing grants this browser access to the machine with your user account's permissions.\nNew conversations default to this Mobius installation's private workspace; choose other directories in the browser.\n"
49064
+ );
49065
+ program2.action(() => program2.outputHelp());
49066
+ program2.command("version", { hidden: true }).description("print the installed Mobius CLI version").action(() => {
45700
49067
  process.stdout.write(`${package_default.version}
45701
49068
  `);
45702
- return;
45703
- }
45704
- if (command === "agents") {
45705
- const arguments_ = process.argv.slice(3);
45706
- if (arguments_.length > 1 || arguments_.length === 1 && arguments_[0] !== "--json") {
45707
- throw new Error("Usage: mobius agents [--json]");
45708
- }
45709
- const installation2 = await openMobiusCliInstallation(shutdown.signal, process.env);
45710
- const localContext = new DaemonLocalContext(installation2.stateDirectory, process.env);
49069
+ });
49070
+ program2.command("agents").description("show detected, missing, and integration-ready Agents").option("--json", "write the Agent inventory as JSON").action(async (options) => {
49071
+ const installation = await openMobiusCliInstallation(shutdown.signal, process.env);
49072
+ const localContext = new DaemonLocalContext(installation.stateDirectory, process.env);
45711
49073
  const defaultWorkspace = loadDefaultWorkspace(localContext.environment);
45712
49074
  await mkdir6(defaultWorkspace, { recursive: true, mode: 448 });
45713
49075
  const inventory = await discoverLocalAgentInventory({
@@ -45715,71 +49077,26 @@ async function main() {
45715
49077
  environment: localContext.environment,
45716
49078
  signal: shutdown.signal
45717
49079
  });
45718
- process.stdout.write(formatAgentDiagnostics(inventory, arguments_[0] === "--json"));
45719
- return;
45720
- }
45721
- const installation = await openMobiusCliInstallation(shutdown.signal, process.env);
45722
- if (command === "__manager") {
49080
+ process.stdout.write(formatAgentDiagnostics(inventory, options.json === true));
49081
+ });
49082
+ program2.command("__manager", { hidden: true }).action(async () => {
49083
+ const installation = await openMobiusCliInstallation(shutdown.signal, process.env);
45723
49084
  await runManager(installation, package_default.version, shutdown.signal);
45724
- return;
45725
- }
45726
- if (command === "pair") {
45727
- if (process.argv[3] === "list") {
45728
- const outputPath = pairListOutputPath(process.argv.slice(4));
45729
- const response2 = await requestManager(
45730
- installation,
45731
- package_default.version,
45732
- { kind: "list" },
45733
- shutdown.signal
45734
- );
45735
- if (response2.kind === "error") {
45736
- throw new Error(response2.message);
45737
- }
45738
- if (response2.kind !== "listed") {
45739
- throw new Error("The Mobius manager returned an unexpected response");
45740
- }
45741
- if (outputPath === null) {
45742
- process.stdout.write(formatPairTable(response2.pairs));
45743
- } else {
45744
- await writePairList(outputPath, response2.pairs);
45745
- }
45746
- return;
45747
- }
45748
- const pairAction = process.argv[3];
45749
- if (pairAction === "stop" || pairAction === "remove") {
45750
- if (process.argv.length !== 6 || process.argv[4] !== "--connection" || process.argv[5] === void 0) {
45751
- throw new Error(`Usage: mobius pair ${pairAction} --connection <connection-id>`);
45752
- }
45753
- const response2 = await requestManager(
45754
- installation,
45755
- package_default.version,
45756
- {
45757
- connectionId: process.argv[5],
45758
- kind: pairAction === "stop" ? "stop-pair" : "remove-pair"
45759
- },
45760
- shutdown.signal
45761
- );
45762
- if (response2.kind === "error") {
45763
- throw new Error(response2.message);
45764
- }
45765
- if (pairAction === "stop" && response2.kind === "pair-stopped") {
45766
- process.stdout.write(`Pairing stopped: ${response2.pair.connectionId}
45767
- `);
45768
- return;
45769
- }
45770
- if (pairAction === "remove" && response2.kind === "pair-removed") {
45771
- process.stdout.write(`Pairing removed: ${response2.connectionId}
45772
- `);
45773
- return;
45774
- }
45775
- throw new Error("The Mobius manager returned an unexpected response");
45776
- }
49085
+ });
49086
+ const pair = program2.command("pair").description("pair this machine or manage saved pairings");
49087
+ pair.addOption(valueOption("--url <relay-url>", "relay HTTP or HTTPS URL")).addOption(valueOption("--code <pairing-code>", "pairing code shown in the browser")).addOption(valueOption("--pairing <runtime-pairing-id>", "Runtime pairing identifier")).addOption(valueOption("--app-id <app-id>", "application identifier")).addOption(valueOption("--workspace <directory>", "default workspace directory")).action(async (options) => {
49088
+ const requested = {
49089
+ ...options,
49090
+ code: requireOption(options.code, "--code <pairing-code>", pair),
49091
+ url: requireOption(options.url, "--url <relay-url>", pair)
49092
+ };
49093
+ const installation = await openMobiusCliInstallation(shutdown.signal, process.env);
45777
49094
  process.stdout.write(`mobius version: ${package_default.version}
45778
49095
  `);
45779
49096
  const response = await requestManager(
45780
49097
  installation,
45781
49098
  package_default.version,
45782
- { arguments: process.argv.slice(3), kind: "pair" },
49099
+ { arguments: pairArguments(requested), kind: "pair" },
45783
49100
  shutdown.signal
45784
49101
  );
45785
49102
  if (response.kind === "error") {
@@ -45798,11 +49115,64 @@ async function main() {
45798
49115
  process.stdout.write(`Status: ${response.pair.status}
45799
49116
  `);
45800
49117
  process.stdout.write("Mobius daemon is ready for Agent requests.\n");
45801
- } else if (command === "start") {
49118
+ });
49119
+ pair.command("list").description("list saved pairings").addOption(valueOption("--output-json <existing-file.json>", "write JSON to an existing file")).action(async (options) => {
49120
+ const installation = await openMobiusCliInstallation(shutdown.signal, process.env);
49121
+ const outputPath = options.outputJson === void 0 ? null : resolve7(options.outputJson);
49122
+ const response = await requestManager(
49123
+ installation,
49124
+ package_default.version,
49125
+ { kind: "list" },
49126
+ shutdown.signal
49127
+ );
49128
+ if (response.kind === "error") {
49129
+ throw new Error(response.message);
49130
+ }
49131
+ if (response.kind !== "listed") {
49132
+ throw new Error("The Mobius manager returned an unexpected response");
49133
+ }
49134
+ if (outputPath === null) {
49135
+ process.stdout.write(formatPairTable(response.pairs));
49136
+ } else {
49137
+ await writePairList(outputPath, response.pairs);
49138
+ }
49139
+ });
49140
+ const addPairMutation = (name) => {
49141
+ pair.command(name).description(`${name} a saved pairing`).addOption(valueOption("--connection <connection-id>", "saved Runtime connection identifier", true)).action(async (options) => {
49142
+ const installation = await openMobiusCliInstallation(shutdown.signal, process.env);
49143
+ const response = await requestManager(
49144
+ installation,
49145
+ package_default.version,
49146
+ {
49147
+ connectionId: options.connection,
49148
+ kind: name === "stop" ? "stop-pair" : "remove-pair"
49149
+ },
49150
+ shutdown.signal
49151
+ );
49152
+ if (response.kind === "error") {
49153
+ throw new Error(response.message);
49154
+ }
49155
+ if (name === "stop" && response.kind === "pair-stopped") {
49156
+ process.stdout.write(`Pairing stopped: ${response.pair.connectionId}
49157
+ `);
49158
+ return;
49159
+ }
49160
+ if (name === "remove" && response.kind === "pair-removed") {
49161
+ process.stdout.write(`Pairing removed: ${response.connectionId}
49162
+ `);
49163
+ return;
49164
+ }
49165
+ throw new Error("The Mobius manager returned an unexpected response");
49166
+ });
49167
+ };
49168
+ addPairMutation("stop");
49169
+ addPairMutation("remove");
49170
+ program2.command("start").description("start the manager and activate a saved connection").addOption(valueOption("--connection <connection-id>", "saved Runtime connection identifier", true)).action(async (options) => {
49171
+ const installation = await openMobiusCliInstallation(shutdown.signal, process.env);
45802
49172
  const response = await requestManager(
45803
49173
  installation,
45804
49174
  package_default.version,
45805
- { arguments: process.argv.slice(3), kind: "start" },
49175
+ { arguments: ["--connection", options.connection], kind: "start" },
45806
49176
  shutdown.signal
45807
49177
  );
45808
49178
  if (response.kind === "error") {
@@ -45817,24 +49187,31 @@ async function main() {
45817
49187
  process.stdout.write(`Status: ${response.pair.status}
45818
49188
  `);
45819
49189
  process.stdout.write("Mobius daemon is ready for Agent requests.\n");
45820
- } else if (command === "quit") {
45821
- if (process.argv.length !== 3) {
45822
- throw new Error("Usage: mobius quit");
45823
- }
45824
- const response = await requestManager(installation, package_default.version, { kind: "stop" }, shutdown.signal);
49190
+ });
49191
+ program2.command("quit").description("stop the manager and every active Runtime").action(async () => {
49192
+ const installation = await openMobiusCliInstallation(shutdown.signal, process.env);
49193
+ const response = await requestManager(
49194
+ installation,
49195
+ package_default.version,
49196
+ { kind: "stop" },
49197
+ shutdown.signal
49198
+ );
45825
49199
  if (response.kind === "error") {
45826
49200
  throw new Error(response.message);
45827
49201
  }
45828
49202
  process.stdout.write("Mobius daemon stopped.\n");
45829
- return;
45830
- } else {
45831
- throw new Error(USAGE.trimEnd());
45832
- }
49203
+ });
49204
+ return program2;
49205
+ }
49206
+ async function main() {
49207
+ await createProgram().parseAsync(process.argv);
45833
49208
  }
45834
49209
  try {
45835
49210
  await main();
45836
49211
  } catch (error62) {
45837
- if (!shutdown.signal.aborted) {
49212
+ if (error62 instanceof CommanderError) {
49213
+ process.exitCode = error62.exitCode;
49214
+ } else if (!shutdown.signal.aborted) {
45838
49215
  const message = error62 instanceof Error ? error62.message : "Unknown failure";
45839
49216
  process.stderr.write(`Mobius daemon failed: ${message}
45840
49217
  `);