create-nextly-app 0.0.1 → 0.0.2-alpha.1

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