@halooojustin/cch 0.1.0

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