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