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