bs58ify 0.0.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js ADDED
@@ -0,0 +1,3082 @@
1
+ #!/usr/bin/env node
2
+ import { writeFile } from "node:fs/promises";
3
+ import { fileURLToPath } from "node:url";
4
+ import { EventEmitter } from "node:events";
5
+ import childProcess from "node:child_process";
6
+ import path from "node:path";
7
+ import fs from "node:fs";
8
+ import process$1 from "node:process";
9
+ import { stripVTControlCharacters } from "node:util";
10
+ //#region node_modules/commander/lib/error.js
11
+ /**
12
+ * CommanderError class
13
+ */
14
+ var CommanderError = class extends Error {
15
+ /**
16
+ * Constructs the CommanderError class
17
+ * @param {number} exitCode suggested exit code which could be used with process.exit
18
+ * @param {string} code an id string representing the error
19
+ * @param {string} message human-readable description of the error
20
+ */
21
+ constructor(exitCode, code, message) {
22
+ super(message);
23
+ Error.captureStackTrace(this, this.constructor);
24
+ this.name = this.constructor.name;
25
+ this.code = code;
26
+ this.exitCode = exitCode;
27
+ this.nestedError = void 0;
28
+ }
29
+ };
30
+ /**
31
+ * InvalidArgumentError class
32
+ */
33
+ var InvalidArgumentError = class extends CommanderError {
34
+ /**
35
+ * Constructs the InvalidArgumentError class
36
+ * @param {string} [message] explanation of why argument is invalid
37
+ */
38
+ constructor(message) {
39
+ super(1, "commander.invalidArgument", message);
40
+ Error.captureStackTrace(this, this.constructor);
41
+ this.name = this.constructor.name;
42
+ }
43
+ };
44
+ //#endregion
45
+ //#region node_modules/commander/lib/argument.js
46
+ var Argument = class {
47
+ /**
48
+ * Initialize a new command argument with the given name and description.
49
+ * The default is that the argument is required, and you can explicitly
50
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
51
+ *
52
+ * @param {string} name
53
+ * @param {string} [description]
54
+ */
55
+ constructor(name, description) {
56
+ this.description = description || "";
57
+ this.variadic = false;
58
+ this.parseArg = void 0;
59
+ this.defaultValue = void 0;
60
+ this.defaultValueDescription = void 0;
61
+ this.argChoices = void 0;
62
+ switch (name[0]) {
63
+ case "<":
64
+ this.required = true;
65
+ this._name = name.slice(1, -1);
66
+ break;
67
+ case "[":
68
+ this.required = false;
69
+ this._name = name.slice(1, -1);
70
+ break;
71
+ default:
72
+ this.required = true;
73
+ this._name = name;
74
+ break;
75
+ }
76
+ if (this._name.endsWith("...")) {
77
+ this.variadic = true;
78
+ this._name = this._name.slice(0, -3);
79
+ }
80
+ }
81
+ /**
82
+ * Return argument name.
83
+ *
84
+ * @return {string}
85
+ */
86
+ name() {
87
+ return this._name;
88
+ }
89
+ /**
90
+ * @package
91
+ */
92
+ _collectValue(value, previous) {
93
+ if (previous === this.defaultValue || !Array.isArray(previous)) return [value];
94
+ previous.push(value);
95
+ return previous;
96
+ }
97
+ /**
98
+ * Set the default value, and optionally supply the description to be displayed in the help.
99
+ *
100
+ * @param {*} value
101
+ * @param {string} [description]
102
+ * @return {Argument}
103
+ */
104
+ default(value, description) {
105
+ this.defaultValue = value;
106
+ this.defaultValueDescription = description;
107
+ return this;
108
+ }
109
+ /**
110
+ * Set the custom handler for processing CLI command arguments into argument values.
111
+ *
112
+ * @param {Function} [fn]
113
+ * @return {Argument}
114
+ */
115
+ argParser(fn) {
116
+ this.parseArg = fn;
117
+ return this;
118
+ }
119
+ /**
120
+ * Only allow argument value to be one of choices.
121
+ *
122
+ * @param {string[]} values
123
+ * @return {Argument}
124
+ */
125
+ choices(values) {
126
+ this.argChoices = values.slice();
127
+ this.parseArg = (arg, previous) => {
128
+ if (!this.argChoices.includes(arg)) throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
129
+ if (this.variadic) return this._collectValue(arg, previous);
130
+ return arg;
131
+ };
132
+ return this;
133
+ }
134
+ /**
135
+ * Make argument required.
136
+ *
137
+ * @returns {Argument}
138
+ */
139
+ argRequired() {
140
+ this.required = true;
141
+ return this;
142
+ }
143
+ /**
144
+ * Make argument optional.
145
+ *
146
+ * @returns {Argument}
147
+ */
148
+ argOptional() {
149
+ this.required = false;
150
+ return this;
151
+ }
152
+ };
153
+ /**
154
+ * Takes an argument and returns its human readable equivalent for help usage.
155
+ *
156
+ * @param {Argument} arg
157
+ * @return {string}
158
+ * @private
159
+ */
160
+ function humanReadableArgName(arg) {
161
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
162
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
163
+ }
164
+ //#endregion
165
+ //#region node_modules/commander/lib/help.js
166
+ /**
167
+ * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`
168
+ * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types
169
+ * @typedef { import("./argument.js").Argument } Argument
170
+ * @typedef { import("./command.js").Command } Command
171
+ * @typedef { import("./option.js").Option } Option
172
+ */
173
+ var Help = class {
174
+ constructor() {
175
+ this.helpWidth = void 0;
176
+ this.minWidthToWrap = 40;
177
+ this.sortSubcommands = false;
178
+ this.sortOptions = false;
179
+ this.showGlobalOptions = false;
180
+ }
181
+ /**
182
+ * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
183
+ * and just before calling `formatHelp()`.
184
+ *
185
+ * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
186
+ *
187
+ * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
188
+ */
189
+ prepareContext(contextOptions) {
190
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
191
+ }
192
+ /**
193
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
194
+ *
195
+ * @param {Command} cmd
196
+ * @returns {Command[]}
197
+ */
198
+ visibleCommands(cmd) {
199
+ const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);
200
+ const helpCommand = cmd._getHelpCommand();
201
+ if (helpCommand && !helpCommand._hidden) visibleCommands.push(helpCommand);
202
+ if (this.sortSubcommands) visibleCommands.sort((a, b) => {
203
+ return a.name().localeCompare(b.name());
204
+ });
205
+ return visibleCommands;
206
+ }
207
+ /**
208
+ * Compare options for sort.
209
+ *
210
+ * @param {Option} a
211
+ * @param {Option} b
212
+ * @returns {number}
213
+ */
214
+ compareOptions(a, b) {
215
+ const getSortKey = (option) => {
216
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
217
+ };
218
+ return getSortKey(a).localeCompare(getSortKey(b));
219
+ }
220
+ /**
221
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
222
+ *
223
+ * @param {Command} cmd
224
+ * @returns {Option[]}
225
+ */
226
+ visibleOptions(cmd) {
227
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
228
+ const helpOption = cmd._getHelpOption();
229
+ if (helpOption && !helpOption.hidden) {
230
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
231
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
232
+ if (!removeShort && !removeLong) visibleOptions.push(helpOption);
233
+ else if (helpOption.long && !removeLong) visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
234
+ else if (helpOption.short && !removeShort) visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
235
+ }
236
+ if (this.sortOptions) visibleOptions.sort(this.compareOptions);
237
+ return visibleOptions;
238
+ }
239
+ /**
240
+ * Get an array of the visible global options. (Not including help.)
241
+ *
242
+ * @param {Command} cmd
243
+ * @returns {Option[]}
244
+ */
245
+ visibleGlobalOptions(cmd) {
246
+ if (!this.showGlobalOptions) return [];
247
+ const globalOptions = [];
248
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
249
+ const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
250
+ globalOptions.push(...visibleOptions);
251
+ }
252
+ if (this.sortOptions) globalOptions.sort(this.compareOptions);
253
+ return globalOptions;
254
+ }
255
+ /**
256
+ * Get an array of the arguments if any have a description.
257
+ *
258
+ * @param {Command} cmd
259
+ * @returns {Argument[]}
260
+ */
261
+ visibleArguments(cmd) {
262
+ if (cmd._argsDescription) cmd.registeredArguments.forEach((argument) => {
263
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
264
+ });
265
+ if (cmd.registeredArguments.find((argument) => argument.description)) return cmd.registeredArguments;
266
+ return [];
267
+ }
268
+ /**
269
+ * Get the command term to show in the list of subcommands.
270
+ *
271
+ * @param {Command} cmd
272
+ * @returns {string}
273
+ */
274
+ subcommandTerm(cmd) {
275
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
276
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
277
+ }
278
+ /**
279
+ * Get the option term to show in the list of options.
280
+ *
281
+ * @param {Option} option
282
+ * @returns {string}
283
+ */
284
+ optionTerm(option) {
285
+ return option.flags;
286
+ }
287
+ /**
288
+ * Get the argument term to show in the list of arguments.
289
+ *
290
+ * @param {Argument} argument
291
+ * @returns {string}
292
+ */
293
+ argumentTerm(argument) {
294
+ return argument.name();
295
+ }
296
+ /**
297
+ * Get the longest command term length.
298
+ *
299
+ * @param {Command} cmd
300
+ * @param {Help} helper
301
+ * @returns {number}
302
+ */
303
+ longestSubcommandTermLength(cmd, helper) {
304
+ return helper.visibleCommands(cmd).reduce((max, command) => {
305
+ return Math.max(max, this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command))));
306
+ }, 0);
307
+ }
308
+ /**
309
+ * Get the longest option term length.
310
+ *
311
+ * @param {Command} cmd
312
+ * @param {Help} helper
313
+ * @returns {number}
314
+ */
315
+ longestOptionTermLength(cmd, helper) {
316
+ return helper.visibleOptions(cmd).reduce((max, option) => {
317
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
318
+ }, 0);
319
+ }
320
+ /**
321
+ * Get the longest global option term length.
322
+ *
323
+ * @param {Command} cmd
324
+ * @param {Help} helper
325
+ * @returns {number}
326
+ */
327
+ longestGlobalOptionTermLength(cmd, helper) {
328
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
329
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
330
+ }, 0);
331
+ }
332
+ /**
333
+ * Get the longest argument term length.
334
+ *
335
+ * @param {Command} cmd
336
+ * @param {Help} helper
337
+ * @returns {number}
338
+ */
339
+ longestArgumentTermLength(cmd, helper) {
340
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
341
+ return Math.max(max, this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument))));
342
+ }, 0);
343
+ }
344
+ /**
345
+ * Get the command usage to be displayed at the top of the built-in help.
346
+ *
347
+ * @param {Command} cmd
348
+ * @returns {string}
349
+ */
350
+ commandUsage(cmd) {
351
+ let cmdName = cmd._name;
352
+ if (cmd._aliases[0]) cmdName = cmdName + "|" + cmd._aliases[0];
353
+ let ancestorCmdNames = "";
354
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
355
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
356
+ }
357
+ /**
358
+ * Get the description for the command.
359
+ *
360
+ * @param {Command} cmd
361
+ * @returns {string}
362
+ */
363
+ commandDescription(cmd) {
364
+ return cmd.description();
365
+ }
366
+ /**
367
+ * Get the subcommand summary to show in the list of subcommands.
368
+ * (Fallback to description for backwards compatibility.)
369
+ *
370
+ * @param {Command} cmd
371
+ * @returns {string}
372
+ */
373
+ subcommandDescription(cmd) {
374
+ return cmd.summary() || cmd.description();
375
+ }
376
+ /**
377
+ * Get the option description to show in the list of options.
378
+ *
379
+ * @param {Option} option
380
+ * @return {string}
381
+ */
382
+ optionDescription(option) {
383
+ const extraInfo = [];
384
+ if (option.argChoices) extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
385
+ if (option.defaultValue !== void 0) {
386
+ if (option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean") extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
387
+ }
388
+ if (option.presetArg !== void 0 && option.optional) extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
389
+ if (option.envVar !== void 0) extraInfo.push(`env: ${option.envVar}`);
390
+ if (extraInfo.length > 0) {
391
+ const extraDescription = `(${extraInfo.join(", ")})`;
392
+ if (option.description) return `${option.description} ${extraDescription}`;
393
+ return extraDescription;
394
+ }
395
+ return option.description;
396
+ }
397
+ /**
398
+ * Get the argument description to show in the list of arguments.
399
+ *
400
+ * @param {Argument} argument
401
+ * @return {string}
402
+ */
403
+ argumentDescription(argument) {
404
+ const extraInfo = [];
405
+ if (argument.argChoices) extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
406
+ if (argument.defaultValue !== void 0) extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
407
+ if (extraInfo.length > 0) {
408
+ const extraDescription = `(${extraInfo.join(", ")})`;
409
+ if (argument.description) return `${argument.description} ${extraDescription}`;
410
+ return extraDescription;
411
+ }
412
+ return argument.description;
413
+ }
414
+ /**
415
+ * Format a list of items, given a heading and an array of formatted items.
416
+ *
417
+ * @param {string} heading
418
+ * @param {string[]} items
419
+ * @param {Help} helper
420
+ * @returns string[]
421
+ */
422
+ formatItemList(heading, items, helper) {
423
+ if (items.length === 0) return [];
424
+ return [
425
+ helper.styleTitle(heading),
426
+ ...items,
427
+ ""
428
+ ];
429
+ }
430
+ /**
431
+ * Group items by their help group heading.
432
+ *
433
+ * @param {Command[] | Option[]} unsortedItems
434
+ * @param {Command[] | Option[]} visibleItems
435
+ * @param {Function} getGroup
436
+ * @returns {Map<string, Command[] | Option[]>}
437
+ */
438
+ groupItems(unsortedItems, visibleItems, getGroup) {
439
+ const result = /* @__PURE__ */ new Map();
440
+ unsortedItems.forEach((item) => {
441
+ const group = getGroup(item);
442
+ if (!result.has(group)) result.set(group, []);
443
+ });
444
+ visibleItems.forEach((item) => {
445
+ const group = getGroup(item);
446
+ if (!result.has(group)) result.set(group, []);
447
+ result.get(group).push(item);
448
+ });
449
+ return result;
450
+ }
451
+ /**
452
+ * Generate the built-in help text.
453
+ *
454
+ * @param {Command} cmd
455
+ * @param {Help} helper
456
+ * @returns {string}
457
+ */
458
+ formatHelp(cmd, helper) {
459
+ const termWidth = helper.padWidth(cmd, helper);
460
+ const helpWidth = helper.helpWidth ?? 80;
461
+ function callFormatItem(term, description) {
462
+ return helper.formatItem(term, termWidth, description, helper);
463
+ }
464
+ let output = [`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`, ""];
465
+ const commandDescription = helper.commandDescription(cmd);
466
+ if (commandDescription.length > 0) output = output.concat([helper.boxWrap(helper.styleCommandDescription(commandDescription), helpWidth), ""]);
467
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
468
+ return callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)), helper.styleArgumentDescription(helper.argumentDescription(argument)));
469
+ });
470
+ output = output.concat(this.formatItemList("Arguments:", argumentList, helper));
471
+ this.groupItems(cmd.options, helper.visibleOptions(cmd), (option) => option.helpGroupHeading ?? "Options:").forEach((options, group) => {
472
+ const optionList = options.map((option) => {
473
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
474
+ });
475
+ output = output.concat(this.formatItemList(group, optionList, helper));
476
+ });
477
+ if (helper.showGlobalOptions) {
478
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
479
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
480
+ });
481
+ output = output.concat(this.formatItemList("Global Options:", globalOptionList, helper));
482
+ }
483
+ this.groupItems(cmd.commands, helper.visibleCommands(cmd), (sub) => sub.helpGroup() || "Commands:").forEach((commands, group) => {
484
+ const commandList = commands.map((sub) => {
485
+ return callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(sub)), helper.styleSubcommandDescription(helper.subcommandDescription(sub)));
486
+ });
487
+ output = output.concat(this.formatItemList(group, commandList, helper));
488
+ });
489
+ return output.join("\n");
490
+ }
491
+ /**
492
+ * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
493
+ *
494
+ * @param {string} str
495
+ * @returns {number}
496
+ */
497
+ displayWidth(str) {
498
+ return stripVTControlCharacters(str).length;
499
+ }
500
+ /**
501
+ * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
502
+ *
503
+ * @param {string} str
504
+ * @returns {string}
505
+ */
506
+ styleTitle(str) {
507
+ return str;
508
+ }
509
+ styleUsage(str) {
510
+ return str.split(" ").map((word) => {
511
+ if (word === "[options]") return this.styleOptionText(word);
512
+ if (word === "[command]") return this.styleSubcommandText(word);
513
+ if (word[0] === "[" || word[0] === "<") return this.styleArgumentText(word);
514
+ return this.styleCommandText(word);
515
+ }).join(" ");
516
+ }
517
+ styleCommandDescription(str) {
518
+ return this.styleDescriptionText(str);
519
+ }
520
+ styleOptionDescription(str) {
521
+ return this.styleDescriptionText(str);
522
+ }
523
+ styleSubcommandDescription(str) {
524
+ return this.styleDescriptionText(str);
525
+ }
526
+ styleArgumentDescription(str) {
527
+ return this.styleDescriptionText(str);
528
+ }
529
+ styleDescriptionText(str) {
530
+ return str;
531
+ }
532
+ styleOptionTerm(str) {
533
+ return this.styleOptionText(str);
534
+ }
535
+ styleSubcommandTerm(str) {
536
+ return str.split(" ").map((word) => {
537
+ if (word === "[options]") return this.styleOptionText(word);
538
+ if (word[0] === "[" || word[0] === "<") return this.styleArgumentText(word);
539
+ return this.styleSubcommandText(word);
540
+ }).join(" ");
541
+ }
542
+ styleArgumentTerm(str) {
543
+ return this.styleArgumentText(str);
544
+ }
545
+ styleOptionText(str) {
546
+ return str;
547
+ }
548
+ styleArgumentText(str) {
549
+ return str;
550
+ }
551
+ styleSubcommandText(str) {
552
+ return str;
553
+ }
554
+ styleCommandText(str) {
555
+ return str;
556
+ }
557
+ /**
558
+ * Calculate the pad width from the maximum term length.
559
+ *
560
+ * @param {Command} cmd
561
+ * @param {Help} helper
562
+ * @returns {number}
563
+ */
564
+ padWidth(cmd, helper) {
565
+ return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
566
+ }
567
+ /**
568
+ * Detect manually wrapped and indented strings by checking for line break followed by whitespace.
569
+ *
570
+ * @param {string} str
571
+ * @returns {boolean}
572
+ */
573
+ preformatted(str) {
574
+ return /\n[^\S\r\n]/.test(str);
575
+ }
576
+ /**
577
+ * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
578
+ *
579
+ * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
580
+ * TTT DDD DDDD
581
+ * DD DDD
582
+ *
583
+ * @param {string} term
584
+ * @param {number} termWidth
585
+ * @param {string} description
586
+ * @param {Help} helper
587
+ * @returns {string}
588
+ */
589
+ formatItem(term, termWidth, description, helper) {
590
+ const itemIndent = 2;
591
+ const itemIndentStr = " ".repeat(itemIndent);
592
+ if (!description) return itemIndentStr + term;
593
+ const paddedTerm = term.padEnd(termWidth + term.length - helper.displayWidth(term));
594
+ const spacerWidth = 2;
595
+ const remainingWidth = (this.helpWidth ?? 80) - termWidth - spacerWidth - itemIndent;
596
+ let formattedDescription;
597
+ if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) formattedDescription = description;
598
+ else formattedDescription = helper.boxWrap(description, remainingWidth).replace(/\n/g, "\n" + " ".repeat(termWidth + spacerWidth));
599
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `\n${itemIndentStr}`);
600
+ }
601
+ /**
602
+ * Wrap a string at whitespace, preserving existing line breaks.
603
+ * Wrapping is skipped if the width is less than `minWidthToWrap`.
604
+ *
605
+ * @param {string} str
606
+ * @param {number} width
607
+ * @returns {string}
608
+ */
609
+ boxWrap(str, width) {
610
+ if (width < this.minWidthToWrap) return str;
611
+ const rawLines = str.split(/\r\n|\n/);
612
+ const chunkPattern = /[\s]*[^\s]+/g;
613
+ const wrappedLines = [];
614
+ rawLines.forEach((line) => {
615
+ const chunks = line.match(chunkPattern);
616
+ if (chunks === null) {
617
+ wrappedLines.push("");
618
+ return;
619
+ }
620
+ let sumChunks = [chunks.shift()];
621
+ let sumWidth = this.displayWidth(sumChunks[0]);
622
+ chunks.forEach((chunk) => {
623
+ const visibleWidth = this.displayWidth(chunk);
624
+ if (sumWidth + visibleWidth <= width) {
625
+ sumChunks.push(chunk);
626
+ sumWidth += visibleWidth;
627
+ return;
628
+ }
629
+ wrappedLines.push(sumChunks.join(""));
630
+ const nextChunk = chunk.trimStart();
631
+ sumChunks = [nextChunk];
632
+ sumWidth = this.displayWidth(nextChunk);
633
+ });
634
+ wrappedLines.push(sumChunks.join(""));
635
+ });
636
+ return wrappedLines.join("\n");
637
+ }
638
+ };
639
+ //#endregion
640
+ //#region node_modules/commander/lib/option.js
641
+ var Option = class {
642
+ /**
643
+ * Initialize a new `Option` with the given `flags` and `description`.
644
+ *
645
+ * @param {string} flags
646
+ * @param {string} [description]
647
+ */
648
+ constructor(flags, description) {
649
+ this.flags = flags;
650
+ this.description = description || "";
651
+ this.required = flags.includes("<");
652
+ this.optional = flags.includes("[");
653
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
654
+ this.mandatory = false;
655
+ const optionFlags = splitOptionFlags(flags);
656
+ this.short = optionFlags.shortFlag;
657
+ this.long = optionFlags.longFlag;
658
+ this.negate = false;
659
+ if (this.long) this.negate = this.long.startsWith("--no-");
660
+ this.defaultValue = void 0;
661
+ this.defaultValueDescription = void 0;
662
+ this.presetArg = void 0;
663
+ this.envVar = void 0;
664
+ this.parseArg = void 0;
665
+ this.hidden = false;
666
+ this.argChoices = void 0;
667
+ this.conflictsWith = [];
668
+ this.implied = void 0;
669
+ this.helpGroupHeading = void 0;
670
+ }
671
+ /**
672
+ * Set the default value, and optionally supply the description to be displayed in the help.
673
+ *
674
+ * @param {*} value
675
+ * @param {string} [description]
676
+ * @return {Option}
677
+ */
678
+ default(value, description) {
679
+ this.defaultValue = value;
680
+ this.defaultValueDescription = description;
681
+ return this;
682
+ }
683
+ /**
684
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
685
+ * The custom processing (parseArg) is called.
686
+ *
687
+ * @example
688
+ * new Option('--color').default('GREYSCALE').preset('RGB');
689
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
690
+ *
691
+ * @param {*} arg
692
+ * @return {Option}
693
+ */
694
+ preset(arg) {
695
+ this.presetArg = arg;
696
+ return this;
697
+ }
698
+ /**
699
+ * Add option name(s) that conflict with this option.
700
+ * An error will be displayed if conflicting options are found during parsing.
701
+ *
702
+ * @example
703
+ * new Option('--rgb').conflicts('cmyk');
704
+ * new Option('--js').conflicts(['ts', 'jsx']);
705
+ *
706
+ * @param {(string | string[])} names
707
+ * @return {Option}
708
+ */
709
+ conflicts(names) {
710
+ this.conflictsWith = this.conflictsWith.concat(names);
711
+ return this;
712
+ }
713
+ /**
714
+ * Specify implied option values for when this option is set and the implied options are not.
715
+ *
716
+ * The custom processing (parseArg) is not called on the implied values.
717
+ *
718
+ * @example
719
+ * program
720
+ * .addOption(new Option('--log', 'write logging information to file'))
721
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
722
+ *
723
+ * @param {object} impliedOptionValues
724
+ * @return {Option}
725
+ */
726
+ implies(impliedOptionValues) {
727
+ let newImplied = impliedOptionValues;
728
+ if (typeof impliedOptionValues === "string") newImplied = { [impliedOptionValues]: true };
729
+ this.implied = Object.assign(this.implied || {}, newImplied);
730
+ return this;
731
+ }
732
+ /**
733
+ * Set environment variable to check for option value.
734
+ *
735
+ * An environment variable is only used if when processed the current option value is
736
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
737
+ *
738
+ * @param {string} name
739
+ * @return {Option}
740
+ */
741
+ env(name) {
742
+ this.envVar = name;
743
+ return this;
744
+ }
745
+ /**
746
+ * Set the custom handler for processing CLI option arguments into option values.
747
+ *
748
+ * @param {Function} [fn]
749
+ * @return {Option}
750
+ */
751
+ argParser(fn) {
752
+ this.parseArg = fn;
753
+ return this;
754
+ }
755
+ /**
756
+ * Whether the option is mandatory and must have a value after parsing.
757
+ *
758
+ * @param {boolean} [mandatory=true]
759
+ * @return {Option}
760
+ */
761
+ makeOptionMandatory(mandatory = true) {
762
+ this.mandatory = !!mandatory;
763
+ return this;
764
+ }
765
+ /**
766
+ * Hide option in help.
767
+ *
768
+ * @param {boolean} [hide=true]
769
+ * @return {Option}
770
+ */
771
+ hideHelp(hide = true) {
772
+ this.hidden = !!hide;
773
+ return this;
774
+ }
775
+ /**
776
+ * @package
777
+ */
778
+ _collectValue(value, previous) {
779
+ if (previous === this.defaultValue || !Array.isArray(previous)) return [value];
780
+ previous.push(value);
781
+ return previous;
782
+ }
783
+ /**
784
+ * Only allow option value to be one of choices.
785
+ *
786
+ * @param {string[]} values
787
+ * @return {Option}
788
+ */
789
+ choices(values) {
790
+ this.argChoices = values.slice();
791
+ this.parseArg = (arg, previous) => {
792
+ if (!this.argChoices.includes(arg)) throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
793
+ if (this.variadic) return this._collectValue(arg, previous);
794
+ return arg;
795
+ };
796
+ return this;
797
+ }
798
+ /**
799
+ * Return option name.
800
+ *
801
+ * @return {string}
802
+ */
803
+ name() {
804
+ if (this.long) return this.long.replace(/^--/, "");
805
+ return this.short.replace(/^-/, "");
806
+ }
807
+ /**
808
+ * Return option name, in a camelcase format that can be used
809
+ * as an object attribute key.
810
+ *
811
+ * @return {string}
812
+ */
813
+ attributeName() {
814
+ if (this.negate) return camelcase(this.name().replace(/^no-/, ""));
815
+ return camelcase(this.name());
816
+ }
817
+ /**
818
+ * Set the help group heading.
819
+ *
820
+ * @param {string} heading
821
+ * @return {Option}
822
+ */
823
+ helpGroup(heading) {
824
+ this.helpGroupHeading = heading;
825
+ return this;
826
+ }
827
+ /**
828
+ * Check if `arg` matches the short or long flag.
829
+ *
830
+ * @param {string} arg
831
+ * @return {boolean}
832
+ * @package
833
+ */
834
+ is(arg) {
835
+ return this.short === arg || this.long === arg;
836
+ }
837
+ /**
838
+ * Return whether a boolean option.
839
+ *
840
+ * Options are one of boolean, negated, required argument, or optional argument.
841
+ *
842
+ * @return {boolean}
843
+ * @package
844
+ */
845
+ isBoolean() {
846
+ return !this.required && !this.optional && !this.negate;
847
+ }
848
+ };
849
+ /**
850
+ * This class is to make it easier to work with dual options, without changing the existing
851
+ * implementation. We support separate dual options for separate positive and negative options,
852
+ * like `--build` and `--no-build`, which share a single option value. This works nicely for some
853
+ * use cases, but is tricky for others where we want separate behaviours despite
854
+ * the single shared option value.
855
+ */
856
+ var DualOptions = class {
857
+ /**
858
+ * @param {Option[]} options
859
+ */
860
+ constructor(options) {
861
+ this.positiveOptions = /* @__PURE__ */ new Map();
862
+ this.negativeOptions = /* @__PURE__ */ new Map();
863
+ this.dualOptions = /* @__PURE__ */ new Set();
864
+ options.forEach((option) => {
865
+ if (option.negate) this.negativeOptions.set(option.attributeName(), option);
866
+ else this.positiveOptions.set(option.attributeName(), option);
867
+ });
868
+ this.negativeOptions.forEach((value, key) => {
869
+ if (this.positiveOptions.has(key)) this.dualOptions.add(key);
870
+ });
871
+ }
872
+ /**
873
+ * Did the value come from the option, and not from possible matching dual option?
874
+ *
875
+ * @param {*} value
876
+ * @param {Option} option
877
+ * @returns {boolean}
878
+ */
879
+ valueFromOption(value, option) {
880
+ const optionKey = option.attributeName();
881
+ if (!this.dualOptions.has(optionKey)) return true;
882
+ const preset = this.negativeOptions.get(optionKey).presetArg;
883
+ const negativeValue = preset !== void 0 ? preset : false;
884
+ return option.negate === (negativeValue === value);
885
+ }
886
+ };
887
+ /**
888
+ * Convert string from kebab-case to camelCase.
889
+ *
890
+ * @param {string} str
891
+ * @return {string}
892
+ * @private
893
+ */
894
+ function camelcase(str) {
895
+ return str.split("-").reduce((str, word) => {
896
+ return str + word[0].toUpperCase() + word.slice(1);
897
+ });
898
+ }
899
+ /**
900
+ * Split the short and long flag out of something like '-m,--mixed <value>'
901
+ *
902
+ * @private
903
+ */
904
+ function splitOptionFlags(flags) {
905
+ let shortFlag;
906
+ let longFlag;
907
+ const shortFlagExp = /^-[^-]$/;
908
+ const longFlagExp = /^--[^-]/;
909
+ const flagParts = flags.split(/[ |,]+/).concat("guard");
910
+ if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
911
+ if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
912
+ if (!shortFlag && shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
913
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
914
+ shortFlag = longFlag;
915
+ longFlag = flagParts.shift();
916
+ }
917
+ if (flagParts[0].startsWith("-")) {
918
+ const unsupportedFlag = flagParts[0];
919
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
920
+ if (/^-[^-][^-]/.test(unsupportedFlag)) throw new Error(`${baseError}
921
+ - a short flag is a single dash and a single character
922
+ - either use a single dash and a single character (for a short flag)
923
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);
924
+ if (shortFlagExp.test(unsupportedFlag)) throw new Error(`${baseError}
925
+ - too many short flags`);
926
+ if (longFlagExp.test(unsupportedFlag)) throw new Error(`${baseError}
927
+ - too many long flags`);
928
+ throw new Error(`${baseError}
929
+ - unrecognised flag format`);
930
+ }
931
+ if (shortFlag === void 0 && longFlag === void 0) throw new Error(`option creation failed due to no flags found in '${flags}'.`);
932
+ return {
933
+ shortFlag,
934
+ longFlag
935
+ };
936
+ }
937
+ //#endregion
938
+ //#region node_modules/commander/lib/suggestSimilar.js
939
+ const maxDistance = 3;
940
+ function editDistance(a, b) {
941
+ if (Math.abs(a.length - b.length) > maxDistance) return Math.max(a.length, b.length);
942
+ const d = [];
943
+ for (let i = 0; i <= a.length; i++) d[i] = [i];
944
+ for (let j = 0; j <= b.length; j++) d[0][j] = j;
945
+ for (let j = 1; j <= b.length; j++) for (let i = 1; i <= a.length; i++) {
946
+ let cost;
947
+ if (a[i - 1] === b[j - 1]) cost = 0;
948
+ else cost = 1;
949
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
950
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
951
+ }
952
+ return d[a.length][b.length];
953
+ }
954
+ /**
955
+ * Find close matches, restricted to same number of edits.
956
+ *
957
+ * @param {string} word
958
+ * @param {string[]} candidates
959
+ * @returns {string}
960
+ */
961
+ function suggestSimilar(word, candidates) {
962
+ if (!candidates || candidates.length === 0) return "";
963
+ candidates = Array.from(new Set(candidates));
964
+ const searchingOptions = word.startsWith("--");
965
+ if (searchingOptions) {
966
+ word = word.slice(2);
967
+ candidates = candidates.map((candidate) => candidate.slice(2));
968
+ }
969
+ let similar = [];
970
+ let bestDistance = maxDistance;
971
+ const minSimilarity = .4;
972
+ candidates.forEach((candidate) => {
973
+ if (candidate.length <= 1) return;
974
+ const distance = editDistance(word, candidate);
975
+ const length = Math.max(word.length, candidate.length);
976
+ if ((length - distance) / length > minSimilarity) {
977
+ if (distance < bestDistance) {
978
+ bestDistance = distance;
979
+ similar = [candidate];
980
+ } else if (distance === bestDistance) similar.push(candidate);
981
+ }
982
+ });
983
+ similar.sort((a, b) => a.localeCompare(b));
984
+ if (searchingOptions) similar = similar.map((candidate) => `--${candidate}`);
985
+ if (similar.length > 1) return `\n(Did you mean one of ${similar.join(", ")}?)`;
986
+ if (similar.length === 1) return `\n(Did you mean ${similar[0]}?)`;
987
+ return "";
988
+ }
989
+ //#endregion
990
+ //#region node_modules/commander/lib/command.js
991
+ var Command = class Command extends EventEmitter {
992
+ /**
993
+ * Initialize a new `Command`.
994
+ *
995
+ * @param {string} [name]
996
+ */
997
+ constructor(name) {
998
+ super();
999
+ /** @type {Command[]} */
1000
+ this.commands = [];
1001
+ /** @type {Option[]} */
1002
+ this.options = [];
1003
+ this.parent = null;
1004
+ this._allowUnknownOption = false;
1005
+ this._allowExcessArguments = false;
1006
+ /** @type {Argument[]} */
1007
+ this.registeredArguments = [];
1008
+ this._args = this.registeredArguments;
1009
+ /** @type {string[]} */
1010
+ this.args = [];
1011
+ this.rawArgs = [];
1012
+ this.processedArgs = [];
1013
+ this._scriptPath = null;
1014
+ this._name = name || "";
1015
+ this._optionValues = {};
1016
+ this._optionValueSources = {};
1017
+ this._storeOptionsAsProperties = false;
1018
+ this._actionHandler = null;
1019
+ this._executableHandler = false;
1020
+ this._executableFile = null;
1021
+ this._executableDir = null;
1022
+ this._defaultCommandName = null;
1023
+ this._exitCallback = null;
1024
+ this._aliases = [];
1025
+ this._combineFlagAndOptionalValue = true;
1026
+ this._description = "";
1027
+ this._summary = "";
1028
+ this._argsDescription = void 0;
1029
+ this._enablePositionalOptions = false;
1030
+ this._passThroughOptions = false;
1031
+ this._lifeCycleHooks = {};
1032
+ /** @type {(boolean | string)} */
1033
+ this._showHelpAfterError = false;
1034
+ this._showSuggestionAfterError = true;
1035
+ this._savedState = null;
1036
+ this._outputConfiguration = {
1037
+ writeOut: (str) => process$1.stdout.write(str),
1038
+ writeErr: (str) => process$1.stderr.write(str),
1039
+ outputError: (str, write) => write(str),
1040
+ getOutHelpWidth: () => process$1.stdout.isTTY ? process$1.stdout.columns : void 0,
1041
+ getErrHelpWidth: () => process$1.stderr.isTTY ? process$1.stderr.columns : void 0,
1042
+ getOutHasColors: () => useColor() ?? (process$1.stdout.isTTY && process$1.stdout.hasColors?.()),
1043
+ getErrHasColors: () => useColor() ?? (process$1.stderr.isTTY && process$1.stderr.hasColors?.()),
1044
+ stripColor: (str) => stripVTControlCharacters(str)
1045
+ };
1046
+ this._hidden = false;
1047
+ /** @type {(Option | null | undefined)} */
1048
+ this._helpOption = void 0;
1049
+ this._addImplicitHelpCommand = void 0;
1050
+ /** @type {Command} */
1051
+ this._helpCommand = void 0;
1052
+ this._helpConfiguration = {};
1053
+ /** @type {string | undefined} */
1054
+ this._helpGroupHeading = void 0;
1055
+ /** @type {string | undefined} */
1056
+ this._defaultCommandGroup = void 0;
1057
+ /** @type {string | undefined} */
1058
+ this._defaultOptionGroup = void 0;
1059
+ }
1060
+ /**
1061
+ * Copy settings that are useful to have in common across root command and subcommands.
1062
+ *
1063
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1064
+ *
1065
+ * @param {Command} sourceCommand
1066
+ * @return {Command} `this` command for chaining
1067
+ */
1068
+ copyInheritedSettings(sourceCommand) {
1069
+ this._outputConfiguration = sourceCommand._outputConfiguration;
1070
+ this._helpOption = sourceCommand._helpOption;
1071
+ this._helpCommand = sourceCommand._helpCommand;
1072
+ this._helpConfiguration = sourceCommand._helpConfiguration;
1073
+ this._exitCallback = sourceCommand._exitCallback;
1074
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1075
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1076
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
1077
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1078
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
1079
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1080
+ return this;
1081
+ }
1082
+ /**
1083
+ * @returns {Command[]}
1084
+ * @private
1085
+ */
1086
+ _getCommandAndAncestors() {
1087
+ const result = [];
1088
+ for (let command = this; command; command = command.parent) result.push(command);
1089
+ return result;
1090
+ }
1091
+ /**
1092
+ * Define a command.
1093
+ *
1094
+ * There are two styles of command: pay attention to where to put the description.
1095
+ *
1096
+ * @example
1097
+ * // Command implemented using action handler (description is supplied separately to `.command`)
1098
+ * program
1099
+ * .command('clone <source> [destination]')
1100
+ * .description('clone a repository into a newly created directory')
1101
+ * .action((source, destination) => {
1102
+ * console.log('clone command called');
1103
+ * });
1104
+ *
1105
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
1106
+ * program
1107
+ * .command('start <service>', 'start named service')
1108
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
1109
+ *
1110
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1111
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1112
+ * @param {object} [execOpts] - configuration options (for executable)
1113
+ * @return {Command} returns new command for action handler, or `this` for executable command
1114
+ */
1115
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1116
+ let desc = actionOptsOrExecDesc;
1117
+ let opts = execOpts;
1118
+ if (typeof desc === "object" && desc !== null) {
1119
+ opts = desc;
1120
+ desc = null;
1121
+ }
1122
+ opts = opts || {};
1123
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1124
+ const cmd = this.createCommand(name);
1125
+ if (desc) {
1126
+ cmd.description(desc);
1127
+ cmd._executableHandler = true;
1128
+ }
1129
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1130
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
1131
+ cmd._executableFile = opts.executableFile || null;
1132
+ if (args) cmd.arguments(args);
1133
+ this._registerCommand(cmd);
1134
+ cmd.parent = this;
1135
+ cmd.copyInheritedSettings(this);
1136
+ if (desc) return this;
1137
+ return cmd;
1138
+ }
1139
+ /**
1140
+ * Factory routine to create a new unattached command.
1141
+ *
1142
+ * See .command() for creating an attached subcommand, which uses this routine to
1143
+ * create the command. You can override createCommand to customise subcommands.
1144
+ *
1145
+ * @param {string} [name]
1146
+ * @return {Command} new command
1147
+ */
1148
+ createCommand(name) {
1149
+ return new Command(name);
1150
+ }
1151
+ /**
1152
+ * You can customise the help with a subclass of Help by overriding createHelp,
1153
+ * or by overriding Help properties using configureHelp().
1154
+ *
1155
+ * @return {Help}
1156
+ */
1157
+ createHelp() {
1158
+ return Object.assign(new Help(), this.configureHelp());
1159
+ }
1160
+ /**
1161
+ * You can customise the help by overriding Help properties using configureHelp(),
1162
+ * or with a subclass of Help by overriding createHelp().
1163
+ *
1164
+ * @param {object} [configuration] - configuration options
1165
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1166
+ */
1167
+ configureHelp(configuration) {
1168
+ if (configuration === void 0) return this._helpConfiguration;
1169
+ this._helpConfiguration = configuration;
1170
+ return this;
1171
+ }
1172
+ /**
1173
+ * The default output goes to stdout and stderr. You can customise this for special
1174
+ * applications. You can also customise the display of errors by overriding outputError.
1175
+ *
1176
+ * The configuration properties are all functions:
1177
+ *
1178
+ * // change how output being written, defaults to stdout and stderr
1179
+ * writeOut(str)
1180
+ * writeErr(str)
1181
+ * // change how output being written for errors, defaults to writeErr
1182
+ * outputError(str, write) // used for displaying errors and not used for displaying help
1183
+ * // specify width for wrapping help
1184
+ * getOutHelpWidth()
1185
+ * getErrHelpWidth()
1186
+ * // color support, currently only used with Help
1187
+ * getOutHasColors()
1188
+ * getErrHasColors()
1189
+ * stripColor() // used to remove ANSI escape codes if output does not have colors
1190
+ *
1191
+ * @param {object} [configuration] - configuration options
1192
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1193
+ */
1194
+ configureOutput(configuration) {
1195
+ if (configuration === void 0) return this._outputConfiguration;
1196
+ this._outputConfiguration = {
1197
+ ...this._outputConfiguration,
1198
+ ...configuration
1199
+ };
1200
+ return this;
1201
+ }
1202
+ /**
1203
+ * Display the help or a custom message after an error occurs.
1204
+ *
1205
+ * @param {(boolean|string)} [displayHelp]
1206
+ * @return {Command} `this` command for chaining
1207
+ */
1208
+ showHelpAfterError(displayHelp = true) {
1209
+ if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
1210
+ this._showHelpAfterError = displayHelp;
1211
+ return this;
1212
+ }
1213
+ /**
1214
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
1215
+ *
1216
+ * @param {boolean} [displaySuggestion]
1217
+ * @return {Command} `this` command for chaining
1218
+ */
1219
+ showSuggestionAfterError(displaySuggestion = true) {
1220
+ this._showSuggestionAfterError = !!displaySuggestion;
1221
+ return this;
1222
+ }
1223
+ /**
1224
+ * Add a prepared subcommand.
1225
+ *
1226
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
1227
+ *
1228
+ * @param {Command} cmd - new subcommand
1229
+ * @param {object} [opts] - configuration options
1230
+ * @return {Command} `this` command for chaining
1231
+ */
1232
+ addCommand(cmd, opts) {
1233
+ if (!cmd._name) throw new Error(`Command passed to .addCommand() must have a name
1234
+ - specify the name in Command constructor or using .name()`);
1235
+ opts = opts || {};
1236
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1237
+ if (opts.noHelp || opts.hidden) cmd._hidden = true;
1238
+ this._registerCommand(cmd);
1239
+ cmd.parent = this;
1240
+ cmd._checkForBrokenPassThrough();
1241
+ return this;
1242
+ }
1243
+ /**
1244
+ * Factory routine to create a new unattached argument.
1245
+ *
1246
+ * See .argument() for creating an attached argument, which uses this routine to
1247
+ * create the argument. You can override createArgument to return a custom argument.
1248
+ *
1249
+ * @param {string} name
1250
+ * @param {string} [description]
1251
+ * @return {Argument} new argument
1252
+ */
1253
+ createArgument(name, description) {
1254
+ return new Argument(name, description);
1255
+ }
1256
+ /**
1257
+ * Define argument syntax for command.
1258
+ *
1259
+ * The default is that the argument is required, and you can explicitly
1260
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
1261
+ *
1262
+ * @example
1263
+ * program.argument('<input-file>');
1264
+ * program.argument('[output-file]');
1265
+ *
1266
+ * @param {string} name
1267
+ * @param {string} [description]
1268
+ * @param {(Function|*)} [parseArg] - custom argument processing function or default value
1269
+ * @param {*} [defaultValue]
1270
+ * @return {Command} `this` command for chaining
1271
+ */
1272
+ argument(name, description, parseArg, defaultValue) {
1273
+ const argument = this.createArgument(name, description);
1274
+ if (typeof parseArg === "function") argument.default(defaultValue).argParser(parseArg);
1275
+ else argument.default(parseArg);
1276
+ this.addArgument(argument);
1277
+ return this;
1278
+ }
1279
+ /**
1280
+ * Define argument syntax for command, adding multiple at once (without descriptions).
1281
+ *
1282
+ * See also .argument().
1283
+ *
1284
+ * @example
1285
+ * program.arguments('<cmd> [env]');
1286
+ *
1287
+ * @param {string} names
1288
+ * @return {Command} `this` command for chaining
1289
+ */
1290
+ arguments(names) {
1291
+ names.trim().split(/ +/).forEach((detail) => {
1292
+ this.argument(detail);
1293
+ });
1294
+ return this;
1295
+ }
1296
+ /**
1297
+ * Define argument syntax for command, adding a prepared argument.
1298
+ *
1299
+ * @param {Argument} argument
1300
+ * @return {Command} `this` command for chaining
1301
+ */
1302
+ addArgument(argument) {
1303
+ const previousArgument = this.registeredArguments.slice(-1)[0];
1304
+ if (previousArgument?.variadic) throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
1305
+ if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
1306
+ this.registeredArguments.push(argument);
1307
+ return this;
1308
+ }
1309
+ /**
1310
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
1311
+ *
1312
+ * @example
1313
+ * program.helpCommand('help [cmd]');
1314
+ * program.helpCommand('help [cmd]', 'show help');
1315
+ * program.helpCommand(false); // suppress default help command
1316
+ * program.helpCommand(true); // add help command even if no subcommands
1317
+ *
1318
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
1319
+ * @param {string} [description] - custom description
1320
+ * @return {Command} `this` command for chaining
1321
+ */
1322
+ helpCommand(enableOrNameAndArgs, description) {
1323
+ if (typeof enableOrNameAndArgs === "boolean") {
1324
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
1325
+ if (enableOrNameAndArgs && this._defaultCommandGroup) this._initCommandGroup(this._getHelpCommand());
1326
+ return this;
1327
+ }
1328
+ const [, helpName, helpArgs] = (enableOrNameAndArgs ?? "help [command]").match(/([^ ]+) *(.*)/);
1329
+ const helpDescription = description ?? "display help for command";
1330
+ const helpCommand = this.createCommand(helpName);
1331
+ helpCommand.helpOption(false);
1332
+ if (helpArgs) helpCommand.arguments(helpArgs);
1333
+ if (helpDescription) helpCommand.description(helpDescription);
1334
+ this._addImplicitHelpCommand = true;
1335
+ this._helpCommand = helpCommand;
1336
+ if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);
1337
+ return this;
1338
+ }
1339
+ /**
1340
+ * Add prepared custom help command.
1341
+ *
1342
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
1343
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
1344
+ * @return {Command} `this` command for chaining
1345
+ */
1346
+ addHelpCommand(helpCommand, deprecatedDescription) {
1347
+ if (typeof helpCommand !== "object") {
1348
+ this.helpCommand(helpCommand, deprecatedDescription);
1349
+ return this;
1350
+ }
1351
+ this._addImplicitHelpCommand = true;
1352
+ this._helpCommand = helpCommand;
1353
+ this._initCommandGroup(helpCommand);
1354
+ return this;
1355
+ }
1356
+ /**
1357
+ * Lazy create help command.
1358
+ *
1359
+ * @return {(Command|null)}
1360
+ * @package
1361
+ */
1362
+ _getHelpCommand() {
1363
+ if (this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"))) {
1364
+ if (this._helpCommand === void 0) this.helpCommand(void 0, void 0);
1365
+ return this._helpCommand;
1366
+ }
1367
+ return null;
1368
+ }
1369
+ /**
1370
+ * Add hook for life cycle event.
1371
+ *
1372
+ * @param {string} event
1373
+ * @param {Function} listener
1374
+ * @return {Command} `this` command for chaining
1375
+ */
1376
+ hook(event, listener) {
1377
+ const allowedValues = [
1378
+ "preSubcommand",
1379
+ "preAction",
1380
+ "postAction"
1381
+ ];
1382
+ if (!allowedValues.includes(event)) throw new Error(`Unexpected value for event passed to hook : '${event}'.
1383
+ Expecting one of '${allowedValues.join("', '")}'`);
1384
+ if (this._lifeCycleHooks[event]) this._lifeCycleHooks[event].push(listener);
1385
+ else this._lifeCycleHooks[event] = [listener];
1386
+ return this;
1387
+ }
1388
+ /**
1389
+ * Register callback to use as replacement for calling process.exit.
1390
+ *
1391
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
1392
+ * @return {Command} `this` command for chaining
1393
+ */
1394
+ exitOverride(fn) {
1395
+ if (fn) this._exitCallback = fn;
1396
+ else this._exitCallback = (err) => {
1397
+ if (err.code !== "commander.executeSubCommandAsync") throw err;
1398
+ };
1399
+ return this;
1400
+ }
1401
+ /**
1402
+ * Call process.exit, and _exitCallback if defined.
1403
+ *
1404
+ * @param {number} exitCode exit code for using with process.exit
1405
+ * @param {string} code an id string representing the error
1406
+ * @param {string} message human-readable description of the error
1407
+ * @return never
1408
+ * @private
1409
+ */
1410
+ _exit(exitCode, code, message) {
1411
+ if (this._exitCallback) this._exitCallback(new CommanderError(exitCode, code, message));
1412
+ process$1.exit(exitCode);
1413
+ }
1414
+ /**
1415
+ * Register callback `fn` for the command.
1416
+ *
1417
+ * @example
1418
+ * program
1419
+ * .command('serve')
1420
+ * .description('start service')
1421
+ * .action(function() {
1422
+ * // do work here
1423
+ * });
1424
+ *
1425
+ * @param {Function} fn
1426
+ * @return {Command} `this` command for chaining
1427
+ */
1428
+ action(fn) {
1429
+ const listener = (args) => {
1430
+ const expectedArgsCount = this.registeredArguments.length;
1431
+ const actionArgs = args.slice(0, expectedArgsCount);
1432
+ if (this._storeOptionsAsProperties) actionArgs[expectedArgsCount] = this;
1433
+ else actionArgs[expectedArgsCount] = this.opts();
1434
+ actionArgs.push(this);
1435
+ return fn.apply(this, actionArgs);
1436
+ };
1437
+ this._actionHandler = listener;
1438
+ return this;
1439
+ }
1440
+ /**
1441
+ * Factory routine to create a new unattached option.
1442
+ *
1443
+ * See .option() for creating an attached option, which uses this routine to
1444
+ * create the option. You can override createOption to return a custom option.
1445
+ *
1446
+ * @param {string} flags
1447
+ * @param {string} [description]
1448
+ * @return {Option} new option
1449
+ */
1450
+ createOption(flags, description) {
1451
+ return new Option(flags, description);
1452
+ }
1453
+ /**
1454
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
1455
+ *
1456
+ * @param {(Option | Argument)} target
1457
+ * @param {string} value
1458
+ * @param {*} previous
1459
+ * @param {string} invalidArgumentMessage
1460
+ * @private
1461
+ */
1462
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
1463
+ try {
1464
+ return target.parseArg(value, previous);
1465
+ } catch (err) {
1466
+ if (err.code === "commander.invalidArgument") {
1467
+ const message = `${invalidArgumentMessage} ${err.message}`;
1468
+ this.error(message, {
1469
+ exitCode: err.exitCode,
1470
+ code: err.code
1471
+ });
1472
+ }
1473
+ throw err;
1474
+ }
1475
+ }
1476
+ /**
1477
+ * Check for option flag conflicts.
1478
+ * Register option if no conflicts found, or throw on conflict.
1479
+ *
1480
+ * @param {Option} option
1481
+ * @private
1482
+ */
1483
+ _registerOption(option) {
1484
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1485
+ if (matchingOption) {
1486
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1487
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1488
+ - already used by option '${matchingOption.flags}'`);
1489
+ }
1490
+ this._initOptionGroup(option);
1491
+ this.options.push(option);
1492
+ }
1493
+ /**
1494
+ * Check for command name and alias conflicts with existing commands.
1495
+ * Register command if no conflicts found, or throw on conflict.
1496
+ *
1497
+ * @param {Command} command
1498
+ * @private
1499
+ */
1500
+ _registerCommand(command) {
1501
+ const knownBy = (cmd) => {
1502
+ return [cmd.name()].concat(cmd.aliases());
1503
+ };
1504
+ const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
1505
+ if (alreadyUsed) {
1506
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1507
+ const newCmd = knownBy(command).join("|");
1508
+ throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
1509
+ }
1510
+ this._initCommandGroup(command);
1511
+ this.commands.push(command);
1512
+ }
1513
+ /**
1514
+ * Add an option.
1515
+ *
1516
+ * @param {Option} option
1517
+ * @return {Command} `this` command for chaining
1518
+ */
1519
+ addOption(option) {
1520
+ this._registerOption(option);
1521
+ const oname = option.name();
1522
+ const name = option.attributeName();
1523
+ if (option.defaultValue !== void 0) this.setOptionValueWithSource(name, option.defaultValue, "default");
1524
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1525
+ if (val == null && option.presetArg !== void 0) val = option.presetArg;
1526
+ const oldValue = this.getOptionValue(name);
1527
+ if (val !== null && option.parseArg) val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1528
+ else if (val !== null && option.variadic) val = option._collectValue(val, oldValue);
1529
+ if (val == null) if (option.negate) val = false;
1530
+ else if (option.isBoolean() || option.optional) val = true;
1531
+ else val = "";
1532
+ this.setOptionValueWithSource(name, val, valueSource);
1533
+ };
1534
+ this.on("option:" + oname, (val) => {
1535
+ handleOptionValue(val, `error: option '${option.flags}' argument '${val}' is invalid.`, "cli");
1536
+ });
1537
+ if (option.envVar) this.on("optionEnv:" + oname, (val) => {
1538
+ handleOptionValue(val, `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`, "env");
1539
+ });
1540
+ return this;
1541
+ }
1542
+ /**
1543
+ * Internal implementation shared by .option() and .requiredOption()
1544
+ *
1545
+ * @return {Command} `this` command for chaining
1546
+ * @private
1547
+ */
1548
+ _optionEx(config, flags, description, fn, defaultValue) {
1549
+ if (typeof flags === "object" && flags instanceof Option) throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
1550
+ const option = this.createOption(flags, description);
1551
+ option.makeOptionMandatory(!!config.mandatory);
1552
+ if (typeof fn === "function") option.default(defaultValue).argParser(fn);
1553
+ else if (fn instanceof RegExp) {
1554
+ const regex = fn;
1555
+ fn = (val, def) => {
1556
+ const m = regex.exec(val);
1557
+ return m ? m[0] : def;
1558
+ };
1559
+ option.default(defaultValue).argParser(fn);
1560
+ } else option.default(fn);
1561
+ return this.addOption(option);
1562
+ }
1563
+ /**
1564
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
1565
+ *
1566
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
1567
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
1568
+ *
1569
+ * See the README for more details, and see also addOption() and requiredOption().
1570
+ *
1571
+ * @example
1572
+ * program
1573
+ * .option('-p, --pepper', 'add pepper')
1574
+ * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
1575
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
1576
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
1577
+ *
1578
+ * @param {string} flags
1579
+ * @param {string} [description]
1580
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1581
+ * @param {*} [defaultValue]
1582
+ * @return {Command} `this` command for chaining
1583
+ */
1584
+ option(flags, description, parseArg, defaultValue) {
1585
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1586
+ }
1587
+ /**
1588
+ * Add a required option which must have a value after parsing. This usually means
1589
+ * the option must be specified on the command line. (Otherwise the same as .option().)
1590
+ *
1591
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1592
+ *
1593
+ * @param {string} flags
1594
+ * @param {string} [description]
1595
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1596
+ * @param {*} [defaultValue]
1597
+ * @return {Command} `this` command for chaining
1598
+ */
1599
+ requiredOption(flags, description, parseArg, defaultValue) {
1600
+ return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
1601
+ }
1602
+ /**
1603
+ * Alter parsing of short flags with optional values.
1604
+ *
1605
+ * @example
1606
+ * // for `.option('-f,--flag [value]'):
1607
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
1608
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
1609
+ *
1610
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
1611
+ * @return {Command} `this` command for chaining
1612
+ */
1613
+ combineFlagAndOptionalValue(combine = true) {
1614
+ this._combineFlagAndOptionalValue = !!combine;
1615
+ return this;
1616
+ }
1617
+ /**
1618
+ * Allow unknown options on the command line.
1619
+ *
1620
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
1621
+ * @return {Command} `this` command for chaining
1622
+ */
1623
+ allowUnknownOption(allowUnknown = true) {
1624
+ this._allowUnknownOption = !!allowUnknown;
1625
+ return this;
1626
+ }
1627
+ /**
1628
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1629
+ *
1630
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
1631
+ * @return {Command} `this` command for chaining
1632
+ */
1633
+ allowExcessArguments(allowExcess = true) {
1634
+ this._allowExcessArguments = !!allowExcess;
1635
+ return this;
1636
+ }
1637
+ /**
1638
+ * Enable positional options. Positional means global options are specified before subcommands which lets
1639
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1640
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
1641
+ *
1642
+ * @param {boolean} [positional]
1643
+ * @return {Command} `this` command for chaining
1644
+ */
1645
+ enablePositionalOptions(positional = true) {
1646
+ this._enablePositionalOptions = !!positional;
1647
+ return this;
1648
+ }
1649
+ /**
1650
+ * Pass through options that come after command-arguments rather than treat them as command-options,
1651
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
1652
+ * positional options to have been enabled on the program (parent commands).
1653
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
1654
+ *
1655
+ * @param {boolean} [passThrough] for unknown options.
1656
+ * @return {Command} `this` command for chaining
1657
+ */
1658
+ passThroughOptions(passThrough = true) {
1659
+ this._passThroughOptions = !!passThrough;
1660
+ this._checkForBrokenPassThrough();
1661
+ return this;
1662
+ }
1663
+ /**
1664
+ * @private
1665
+ */
1666
+ _checkForBrokenPassThrough() {
1667
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
1668
+ }
1669
+ /**
1670
+ * Whether to store option values as properties on command object,
1671
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
1672
+ *
1673
+ * @param {boolean} [storeAsProperties=true]
1674
+ * @return {Command} `this` command for chaining
1675
+ */
1676
+ storeOptionsAsProperties(storeAsProperties = true) {
1677
+ if (this.options.length) throw new Error("call .storeOptionsAsProperties() before adding options");
1678
+ if (Object.keys(this._optionValues).length) throw new Error("call .storeOptionsAsProperties() before setting option values");
1679
+ this._storeOptionsAsProperties = !!storeAsProperties;
1680
+ return this;
1681
+ }
1682
+ /**
1683
+ * Retrieve option value.
1684
+ *
1685
+ * @param {string} key
1686
+ * @return {object} value
1687
+ */
1688
+ getOptionValue(key) {
1689
+ if (this._storeOptionsAsProperties) return this[key];
1690
+ return this._optionValues[key];
1691
+ }
1692
+ /**
1693
+ * Store option value.
1694
+ *
1695
+ * @param {string} key
1696
+ * @param {object} value
1697
+ * @return {Command} `this` command for chaining
1698
+ */
1699
+ setOptionValue(key, value) {
1700
+ return this.setOptionValueWithSource(key, value, void 0);
1701
+ }
1702
+ /**
1703
+ * Store option value and where the value came from.
1704
+ *
1705
+ * @param {string} key
1706
+ * @param {object} value
1707
+ * @param {string} source - expected values are default/config/env/cli/implied
1708
+ * @return {Command} `this` command for chaining
1709
+ */
1710
+ setOptionValueWithSource(key, value, source) {
1711
+ if (this._storeOptionsAsProperties) this[key] = value;
1712
+ else this._optionValues[key] = value;
1713
+ this._optionValueSources[key] = source;
1714
+ return this;
1715
+ }
1716
+ /**
1717
+ * Get source of option value.
1718
+ * Expected values are default | config | env | cli | implied
1719
+ *
1720
+ * @param {string} key
1721
+ * @return {string}
1722
+ */
1723
+ getOptionValueSource(key) {
1724
+ return this._optionValueSources[key];
1725
+ }
1726
+ /**
1727
+ * Get source of option value. See also .optsWithGlobals().
1728
+ * Expected values are default | config | env | cli | implied
1729
+ *
1730
+ * @param {string} key
1731
+ * @return {string}
1732
+ */
1733
+ getOptionValueSourceWithGlobals(key) {
1734
+ let source;
1735
+ this._getCommandAndAncestors().forEach((cmd) => {
1736
+ if (cmd.getOptionValueSource(key) !== void 0) source = cmd.getOptionValueSource(key);
1737
+ });
1738
+ return source;
1739
+ }
1740
+ /**
1741
+ * Get user arguments from implied or explicit arguments.
1742
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
1743
+ *
1744
+ * @private
1745
+ */
1746
+ _prepareUserArgs(argv, parseOptions) {
1747
+ if (argv !== void 0 && !Array.isArray(argv)) throw new Error("first parameter to parse must be array or undefined");
1748
+ parseOptions = parseOptions || {};
1749
+ if (argv === void 0 && parseOptions.from === void 0) {
1750
+ if (process$1.versions?.electron) parseOptions.from = "electron";
1751
+ const execArgv = process$1.execArgv ?? [];
1752
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) parseOptions.from = "eval";
1753
+ }
1754
+ if (argv === void 0) argv = process$1.argv;
1755
+ this.rawArgs = argv.slice();
1756
+ let userArgs;
1757
+ switch (parseOptions.from) {
1758
+ case void 0:
1759
+ case "node":
1760
+ this._scriptPath = argv[1];
1761
+ userArgs = argv.slice(2);
1762
+ break;
1763
+ case "electron":
1764
+ if (process$1.defaultApp) {
1765
+ this._scriptPath = argv[1];
1766
+ userArgs = argv.slice(2);
1767
+ } else userArgs = argv.slice(1);
1768
+ break;
1769
+ case "user":
1770
+ userArgs = argv.slice(0);
1771
+ break;
1772
+ case "eval":
1773
+ userArgs = argv.slice(1);
1774
+ break;
1775
+ default: throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
1776
+ }
1777
+ if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath);
1778
+ this._name = this._name || "program";
1779
+ return userArgs;
1780
+ }
1781
+ /**
1782
+ * Parse `argv`, setting options and invoking commands when defined.
1783
+ *
1784
+ * Use parseAsync instead of parse if any of your action handlers are async.
1785
+ *
1786
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1787
+ *
1788
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1789
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1790
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1791
+ * - `'user'`: just user arguments
1792
+ *
1793
+ * @example
1794
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
1795
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
1796
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1797
+ *
1798
+ * @param {string[]} [argv] - optional, defaults to process.argv
1799
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
1800
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
1801
+ * @return {Command} `this` command for chaining
1802
+ */
1803
+ parse(argv, parseOptions) {
1804
+ this._prepareForParse();
1805
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1806
+ this._parseCommand([], userArgs);
1807
+ return this;
1808
+ }
1809
+ /**
1810
+ * Parse `argv`, setting options and invoking commands when defined.
1811
+ *
1812
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1813
+ *
1814
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1815
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1816
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1817
+ * - `'user'`: just user arguments
1818
+ *
1819
+ * @example
1820
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
1821
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
1822
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1823
+ *
1824
+ * @param {string[]} [argv]
1825
+ * @param {object} [parseOptions]
1826
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
1827
+ * @return {Promise}
1828
+ */
1829
+ async parseAsync(argv, parseOptions) {
1830
+ this._prepareForParse();
1831
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1832
+ await this._parseCommand([], userArgs);
1833
+ return this;
1834
+ }
1835
+ _prepareForParse() {
1836
+ if (this._savedState === null) {
1837
+ this.options.filter((option) => option.negate && option.defaultValue === void 0 && this.getOptionValue(option.attributeName()) === void 0).forEach((option) => {
1838
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1839
+ if (!this._findOption(positiveLongFlag)) this.setOptionValueWithSource(option.attributeName(), true, "default");
1840
+ });
1841
+ this.saveStateBeforeParse();
1842
+ } else this.restoreStateBeforeParse();
1843
+ }
1844
+ /**
1845
+ * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
1846
+ * Not usually called directly, but available for subclasses to save their custom state.
1847
+ *
1848
+ * This is called in a lazy way. Only commands used in parsing chain will have state saved.
1849
+ */
1850
+ saveStateBeforeParse() {
1851
+ this._savedState = {
1852
+ _name: this._name,
1853
+ _optionValues: { ...this._optionValues },
1854
+ _optionValueSources: { ...this._optionValueSources }
1855
+ };
1856
+ }
1857
+ /**
1858
+ * Restore state before parse for calls after the first.
1859
+ * Not usually called directly, but available for subclasses to save their custom state.
1860
+ *
1861
+ * This is called in a lazy way. Only commands used in parsing chain will have state restored.
1862
+ */
1863
+ restoreStateBeforeParse() {
1864
+ if (this._storeOptionsAsProperties) throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
1865
+ - either make a new Command for each call to parse, or stop storing options as properties`);
1866
+ this._name = this._savedState._name;
1867
+ this._scriptPath = null;
1868
+ this.rawArgs = [];
1869
+ this._optionValues = { ...this._savedState._optionValues };
1870
+ this._optionValueSources = { ...this._savedState._optionValueSources };
1871
+ this.args = [];
1872
+ this.processedArgs = [];
1873
+ }
1874
+ /**
1875
+ * Throw if expected executable is missing. Add lots of help for author.
1876
+ *
1877
+ * @param {string} executableFile
1878
+ * @param {string} executableDir
1879
+ * @param {string} subcommandName
1880
+ */
1881
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
1882
+ if (fs.existsSync(executableFile)) return;
1883
+ const executableMissing = `'${executableFile}' does not exist
1884
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1885
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1886
+ - ${executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory"}`;
1887
+ throw new Error(executableMissing);
1888
+ }
1889
+ /**
1890
+ * Execute a sub-command executable.
1891
+ *
1892
+ * @private
1893
+ */
1894
+ _executeSubCommand(subcommand, args) {
1895
+ args = args.slice();
1896
+ const sourceExt = [
1897
+ ".js",
1898
+ ".ts",
1899
+ ".tsx",
1900
+ ".mjs",
1901
+ ".cjs"
1902
+ ];
1903
+ function findFile(baseDir, baseName) {
1904
+ const localBin = path.resolve(baseDir, baseName);
1905
+ if (fs.existsSync(localBin)) return localBin;
1906
+ if (sourceExt.includes(path.extname(baseName))) return void 0;
1907
+ const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
1908
+ if (foundExt) return `${localBin}${foundExt}`;
1909
+ }
1910
+ this._checkForMissingMandatoryOptions();
1911
+ this._checkForConflictingOptions();
1912
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1913
+ let executableDir = this._executableDir || "";
1914
+ if (this._scriptPath) {
1915
+ let resolvedScriptPath;
1916
+ try {
1917
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
1918
+ } catch {
1919
+ resolvedScriptPath = this._scriptPath;
1920
+ }
1921
+ executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
1922
+ }
1923
+ if (executableDir) {
1924
+ let localFile = findFile(executableDir, executableFile);
1925
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1926
+ const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
1927
+ if (legacyName !== this._name) localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
1928
+ }
1929
+ executableFile = localFile || executableFile;
1930
+ }
1931
+ const launchWithNode = sourceExt.includes(path.extname(executableFile));
1932
+ let proc;
1933
+ if (process$1.platform !== "win32") if (launchWithNode) {
1934
+ args.unshift(executableFile);
1935
+ args = incrementNodeInspectorPort(process$1.execArgv).concat(args);
1936
+ proc = childProcess.spawn(process$1.argv[0], args, { stdio: "inherit" });
1937
+ } else proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1938
+ else {
1939
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
1940
+ args.unshift(executableFile);
1941
+ args = incrementNodeInspectorPort(process$1.execArgv).concat(args);
1942
+ proc = childProcess.spawn(process$1.execPath, args, { stdio: "inherit" });
1943
+ }
1944
+ if (!proc.killed) [
1945
+ "SIGUSR1",
1946
+ "SIGUSR2",
1947
+ "SIGTERM",
1948
+ "SIGINT",
1949
+ "SIGHUP"
1950
+ ].forEach((signal) => {
1951
+ process$1.on(signal, () => {
1952
+ if (proc.killed === false && proc.exitCode === null) proc.kill(signal);
1953
+ });
1954
+ });
1955
+ const exitCallback = this._exitCallback;
1956
+ proc.on("close", (code) => {
1957
+ code = code ?? 1;
1958
+ if (!exitCallback) process$1.exit(code);
1959
+ else exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
1960
+ });
1961
+ proc.on("error", (err) => {
1962
+ if (err.code === "ENOENT") this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
1963
+ else if (err.code === "EACCES") throw new Error(`'${executableFile}' not executable`);
1964
+ if (!exitCallback) process$1.exit(1);
1965
+ else {
1966
+ const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
1967
+ wrappedError.nestedError = err;
1968
+ exitCallback(wrappedError);
1969
+ }
1970
+ });
1971
+ this.runningCommand = proc;
1972
+ }
1973
+ /**
1974
+ * @private
1975
+ */
1976
+ _dispatchSubcommand(commandName, operands, unknown) {
1977
+ const subCommand = this._findCommand(commandName);
1978
+ if (!subCommand) this.help({ error: true });
1979
+ subCommand._prepareForParse();
1980
+ let promiseChain;
1981
+ promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
1982
+ promiseChain = this._chainOrCall(promiseChain, () => {
1983
+ if (subCommand._executableHandler) this._executeSubCommand(subCommand, operands.concat(unknown));
1984
+ else return subCommand._parseCommand(operands, unknown);
1985
+ });
1986
+ return promiseChain;
1987
+ }
1988
+ /**
1989
+ * Invoke help directly if possible, or dispatch if necessary.
1990
+ * e.g. help foo
1991
+ *
1992
+ * @private
1993
+ */
1994
+ _dispatchHelpCommand(subcommandName) {
1995
+ if (!subcommandName) this.help();
1996
+ const subCommand = this._findCommand(subcommandName);
1997
+ if (subCommand && !subCommand._executableHandler) subCommand.help();
1998
+ return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
1999
+ }
2000
+ /**
2001
+ * Check this.args against expected this.registeredArguments.
2002
+ *
2003
+ * @private
2004
+ */
2005
+ _checkNumberOfArguments() {
2006
+ this.registeredArguments.forEach((arg, i) => {
2007
+ if (arg.required && this.args[i] == null) this.missingArgument(arg.name());
2008
+ });
2009
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) return;
2010
+ if (this.args.length > this.registeredArguments.length) this._excessArguments(this.args);
2011
+ }
2012
+ /**
2013
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
2014
+ *
2015
+ * @private
2016
+ */
2017
+ _processArguments() {
2018
+ const myParseArg = (argument, value, previous) => {
2019
+ let parsedValue = value;
2020
+ if (value !== null && argument.parseArg) {
2021
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
2022
+ parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
2023
+ }
2024
+ return parsedValue;
2025
+ };
2026
+ this._checkNumberOfArguments();
2027
+ const processedArgs = [];
2028
+ this.registeredArguments.forEach((declaredArg, index) => {
2029
+ let value = declaredArg.defaultValue;
2030
+ if (declaredArg.variadic) {
2031
+ if (index < this.args.length) {
2032
+ value = this.args.slice(index);
2033
+ if (declaredArg.parseArg) value = value.reduce((processed, v) => {
2034
+ return myParseArg(declaredArg, v, processed);
2035
+ }, declaredArg.defaultValue);
2036
+ } else if (value === void 0) value = [];
2037
+ } else if (index < this.args.length) {
2038
+ value = this.args[index];
2039
+ if (declaredArg.parseArg) value = myParseArg(declaredArg, value, declaredArg.defaultValue);
2040
+ }
2041
+ processedArgs[index] = value;
2042
+ });
2043
+ this.processedArgs = processedArgs;
2044
+ }
2045
+ /**
2046
+ * Once we have a promise we chain, but call synchronously until then.
2047
+ *
2048
+ * @param {(Promise|undefined)} promise
2049
+ * @param {Function} fn
2050
+ * @return {(Promise|undefined)}
2051
+ * @private
2052
+ */
2053
+ _chainOrCall(promise, fn) {
2054
+ if (promise?.then && typeof promise.then === "function") return promise.then(() => fn());
2055
+ return fn();
2056
+ }
2057
+ /**
2058
+ *
2059
+ * @param {(Promise|undefined)} promise
2060
+ * @param {string} event
2061
+ * @return {(Promise|undefined)}
2062
+ * @private
2063
+ */
2064
+ _chainOrCallHooks(promise, event) {
2065
+ let result = promise;
2066
+ const hooks = [];
2067
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
2068
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
2069
+ hooks.push({
2070
+ hookedCommand,
2071
+ callback
2072
+ });
2073
+ });
2074
+ });
2075
+ if (event === "postAction") hooks.reverse();
2076
+ hooks.forEach((hookDetail) => {
2077
+ result = this._chainOrCall(result, () => {
2078
+ return hookDetail.callback(hookDetail.hookedCommand, this);
2079
+ });
2080
+ });
2081
+ return result;
2082
+ }
2083
+ /**
2084
+ *
2085
+ * @param {(Promise|undefined)} promise
2086
+ * @param {Command} subCommand
2087
+ * @param {string} event
2088
+ * @return {(Promise|undefined)}
2089
+ * @private
2090
+ */
2091
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
2092
+ let result = promise;
2093
+ if (this._lifeCycleHooks[event] !== void 0) this._lifeCycleHooks[event].forEach((hook) => {
2094
+ result = this._chainOrCall(result, () => {
2095
+ return hook(this, subCommand);
2096
+ });
2097
+ });
2098
+ return result;
2099
+ }
2100
+ /**
2101
+ * Process arguments in context of this command.
2102
+ * Returns action result, in case it is a promise.
2103
+ *
2104
+ * @private
2105
+ */
2106
+ _parseCommand(operands, unknown) {
2107
+ const parsed = this.parseOptions(unknown);
2108
+ this._parseOptionsEnv();
2109
+ this._parseOptionsImplied();
2110
+ operands = operands.concat(parsed.operands);
2111
+ unknown = parsed.unknown;
2112
+ this.args = operands.concat(unknown);
2113
+ if (operands && this._findCommand(operands[0])) return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2114
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) return this._dispatchHelpCommand(operands[1]);
2115
+ if (this._defaultCommandName) {
2116
+ this._outputHelpIfRequested(unknown);
2117
+ return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
2118
+ }
2119
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) this.help({ error: true });
2120
+ this._outputHelpIfRequested(parsed.unknown);
2121
+ this._checkForMissingMandatoryOptions();
2122
+ this._checkForConflictingOptions();
2123
+ const checkForUnknownOptions = () => {
2124
+ if (parsed.unknown.length > 0) this.unknownOption(parsed.unknown[0]);
2125
+ };
2126
+ const commandEvent = `command:${this.name()}`;
2127
+ if (this._actionHandler) {
2128
+ checkForUnknownOptions();
2129
+ this._processArguments();
2130
+ let promiseChain;
2131
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
2132
+ promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
2133
+ if (this.parent) promiseChain = this._chainOrCall(promiseChain, () => {
2134
+ this.parent.emit(commandEvent, operands, unknown);
2135
+ });
2136
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
2137
+ return promiseChain;
2138
+ }
2139
+ if (this.parent?.listenerCount(commandEvent)) {
2140
+ checkForUnknownOptions();
2141
+ this._processArguments();
2142
+ this.parent.emit(commandEvent, operands, unknown);
2143
+ } else if (operands.length) {
2144
+ if (this._findCommand("*")) return this._dispatchSubcommand("*", operands, unknown);
2145
+ if (this.listenerCount("command:*")) this.emit("command:*", operands, unknown);
2146
+ else if (this.commands.length) this.unknownCommand();
2147
+ else {
2148
+ checkForUnknownOptions();
2149
+ this._processArguments();
2150
+ }
2151
+ } else if (this.commands.length) {
2152
+ checkForUnknownOptions();
2153
+ this.help({ error: true });
2154
+ } else {
2155
+ checkForUnknownOptions();
2156
+ this._processArguments();
2157
+ }
2158
+ }
2159
+ /**
2160
+ * Find matching command.
2161
+ *
2162
+ * @private
2163
+ * @return {Command | undefined}
2164
+ */
2165
+ _findCommand(name) {
2166
+ if (!name) return void 0;
2167
+ return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
2168
+ }
2169
+ /**
2170
+ * Return an option matching `arg` if any.
2171
+ *
2172
+ * @param {string} arg
2173
+ * @return {Option}
2174
+ * @package
2175
+ */
2176
+ _findOption(arg) {
2177
+ return this.options.find((option) => option.is(arg));
2178
+ }
2179
+ /**
2180
+ * Display an error message if a mandatory option does not have a value.
2181
+ * Called after checking for help flags in leaf subcommand.
2182
+ *
2183
+ * @private
2184
+ */
2185
+ _checkForMissingMandatoryOptions() {
2186
+ this._getCommandAndAncestors().forEach((cmd) => {
2187
+ cmd.options.forEach((anOption) => {
2188
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) cmd.missingMandatoryOptionValue(anOption);
2189
+ });
2190
+ });
2191
+ }
2192
+ /**
2193
+ * Display an error message if conflicting options are used together in this.
2194
+ *
2195
+ * @private
2196
+ */
2197
+ _checkForConflictingLocalOptions() {
2198
+ const definedNonDefaultOptions = this.options.filter((option) => {
2199
+ const optionKey = option.attributeName();
2200
+ if (this.getOptionValue(optionKey) === void 0) return false;
2201
+ return this.getOptionValueSource(optionKey) !== "default";
2202
+ });
2203
+ definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0).forEach((option) => {
2204
+ const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
2205
+ if (conflictingAndDefined) this._conflictingOption(option, conflictingAndDefined);
2206
+ });
2207
+ }
2208
+ /**
2209
+ * Display an error message if conflicting options are used together.
2210
+ * Called after checking for help flags in leaf subcommand.
2211
+ *
2212
+ * @private
2213
+ */
2214
+ _checkForConflictingOptions() {
2215
+ this._getCommandAndAncestors().forEach((cmd) => {
2216
+ cmd._checkForConflictingLocalOptions();
2217
+ });
2218
+ }
2219
+ /**
2220
+ * Parse options from `argv` removing known options,
2221
+ * and return argv split into operands and unknown arguments.
2222
+ *
2223
+ * Side effects: modifies command by storing options. Does not reset state if called again.
2224
+ *
2225
+ * Examples:
2226
+ *
2227
+ * argv => operands, unknown
2228
+ * --known kkk op => [op], []
2229
+ * op --known kkk => [op], []
2230
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
2231
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
2232
+ *
2233
+ * @param {string[]} args
2234
+ * @return {{operands: string[], unknown: string[]}}
2235
+ */
2236
+ parseOptions(args) {
2237
+ const operands = [];
2238
+ const unknown = [];
2239
+ let dest = operands;
2240
+ function maybeOption(arg) {
2241
+ return arg.length > 1 && arg[0] === "-";
2242
+ }
2243
+ const negativeNumberArg = (arg) => {
2244
+ if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)) return false;
2245
+ return !this._getCommandAndAncestors().some((cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short)));
2246
+ };
2247
+ let activeVariadicOption = null;
2248
+ let activeGroup = null;
2249
+ let i = 0;
2250
+ while (i < args.length || activeGroup) {
2251
+ const arg = activeGroup ?? args[i++];
2252
+ activeGroup = null;
2253
+ if (arg === "--") {
2254
+ if (dest === unknown) dest.push(arg);
2255
+ dest.push(...args.slice(i));
2256
+ break;
2257
+ }
2258
+ if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
2259
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
2260
+ continue;
2261
+ }
2262
+ activeVariadicOption = null;
2263
+ if (maybeOption(arg)) {
2264
+ const option = this._findOption(arg);
2265
+ if (option) {
2266
+ if (option.required) {
2267
+ const value = args[i++];
2268
+ if (value === void 0) this.optionMissingArgument(option);
2269
+ this.emit(`option:${option.name()}`, value);
2270
+ } else if (option.optional) {
2271
+ let value = null;
2272
+ if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) value = args[i++];
2273
+ this.emit(`option:${option.name()}`, value);
2274
+ } else this.emit(`option:${option.name()}`);
2275
+ activeVariadicOption = option.variadic ? option : null;
2276
+ continue;
2277
+ }
2278
+ }
2279
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
2280
+ const option = this._findOption(`-${arg[1]}`);
2281
+ if (option) {
2282
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) this.emit(`option:${option.name()}`, arg.slice(2));
2283
+ else {
2284
+ this.emit(`option:${option.name()}`);
2285
+ activeGroup = `-${arg.slice(2)}`;
2286
+ }
2287
+ continue;
2288
+ }
2289
+ }
2290
+ if (/^--[^=]+=/.test(arg)) {
2291
+ const index = arg.indexOf("=");
2292
+ const option = this._findOption(arg.slice(0, index));
2293
+ if (option && (option.required || option.optional)) {
2294
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
2295
+ continue;
2296
+ }
2297
+ }
2298
+ if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) dest = unknown;
2299
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
2300
+ if (this._findCommand(arg)) {
2301
+ operands.push(arg);
2302
+ unknown.push(...args.slice(i));
2303
+ break;
2304
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
2305
+ operands.push(arg, ...args.slice(i));
2306
+ break;
2307
+ } else if (this._defaultCommandName) {
2308
+ unknown.push(arg, ...args.slice(i));
2309
+ break;
2310
+ }
2311
+ }
2312
+ if (this._passThroughOptions) {
2313
+ dest.push(arg, ...args.slice(i));
2314
+ break;
2315
+ }
2316
+ dest.push(arg);
2317
+ }
2318
+ return {
2319
+ operands,
2320
+ unknown
2321
+ };
2322
+ }
2323
+ /**
2324
+ * Return an object containing local option values as key-value pairs.
2325
+ *
2326
+ * @return {object}
2327
+ */
2328
+ opts() {
2329
+ if (this._storeOptionsAsProperties) {
2330
+ const result = {};
2331
+ const len = this.options.length;
2332
+ for (let i = 0; i < len; i++) {
2333
+ const key = this.options[i].attributeName();
2334
+ result[key] = key === this._versionOptionName ? this._version : this[key];
2335
+ }
2336
+ return result;
2337
+ }
2338
+ return this._optionValues;
2339
+ }
2340
+ /**
2341
+ * Return an object containing merged local and global option values as key-value pairs.
2342
+ *
2343
+ * @return {object}
2344
+ */
2345
+ optsWithGlobals() {
2346
+ return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
2347
+ }
2348
+ /**
2349
+ * Display error message and exit (or call exitOverride).
2350
+ *
2351
+ * @param {string} message
2352
+ * @param {object} [errorOptions]
2353
+ * @param {string} [errorOptions.code] - an id string representing the error
2354
+ * @param {number} [errorOptions.exitCode] - used with process.exit
2355
+ */
2356
+ error(message, errorOptions) {
2357
+ this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);
2358
+ if (typeof this._showHelpAfterError === "string") this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);
2359
+ else if (this._showHelpAfterError) {
2360
+ this._outputConfiguration.writeErr("\n");
2361
+ this.outputHelp({ error: true });
2362
+ }
2363
+ const config = errorOptions || {};
2364
+ const exitCode = config.exitCode || 1;
2365
+ const code = config.code || "commander.error";
2366
+ this._exit(exitCode, code, message);
2367
+ }
2368
+ /**
2369
+ * Apply any option related environment variables, if option does
2370
+ * not have a value from cli or client code.
2371
+ *
2372
+ * @private
2373
+ */
2374
+ _parseOptionsEnv() {
2375
+ this.options.forEach((option) => {
2376
+ if (option.envVar && option.envVar in process$1.env) {
2377
+ const optionKey = option.attributeName();
2378
+ if (this.getOptionValue(optionKey) === void 0 || [
2379
+ "default",
2380
+ "config",
2381
+ "env"
2382
+ ].includes(this.getOptionValueSource(optionKey))) if (option.required || option.optional) this.emit(`optionEnv:${option.name()}`, process$1.env[option.envVar]);
2383
+ else this.emit(`optionEnv:${option.name()}`);
2384
+ }
2385
+ });
2386
+ }
2387
+ /**
2388
+ * Apply any implied option values, if option is undefined or default value.
2389
+ *
2390
+ * @private
2391
+ */
2392
+ _parseOptionsImplied() {
2393
+ const dualHelper = new DualOptions(this.options);
2394
+ const hasCustomOptionValue = (optionKey) => {
2395
+ return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
2396
+ };
2397
+ this.options.filter((option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
2398
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
2399
+ this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
2400
+ });
2401
+ });
2402
+ }
2403
+ /**
2404
+ * Argument `name` is missing.
2405
+ *
2406
+ * @param {string} name
2407
+ * @private
2408
+ */
2409
+ missingArgument(name) {
2410
+ const message = `error: missing required argument '${name}'`;
2411
+ this.error(message, { code: "commander.missingArgument" });
2412
+ }
2413
+ /**
2414
+ * `Option` is missing an argument.
2415
+ *
2416
+ * @param {Option} option
2417
+ * @private
2418
+ */
2419
+ optionMissingArgument(option) {
2420
+ const message = `error: option '${option.flags}' argument missing`;
2421
+ this.error(message, { code: "commander.optionMissingArgument" });
2422
+ }
2423
+ /**
2424
+ * `Option` does not have a value, and is a mandatory option.
2425
+ *
2426
+ * @param {Option} option
2427
+ * @private
2428
+ */
2429
+ missingMandatoryOptionValue(option) {
2430
+ const message = `error: required option '${option.flags}' not specified`;
2431
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
2432
+ }
2433
+ /**
2434
+ * `Option` conflicts with another option.
2435
+ *
2436
+ * @param {Option} option
2437
+ * @param {Option} conflictingOption
2438
+ * @private
2439
+ */
2440
+ _conflictingOption(option, conflictingOption) {
2441
+ const findBestOptionFromValue = (option) => {
2442
+ const optionKey = option.attributeName();
2443
+ const optionValue = this.getOptionValue(optionKey);
2444
+ const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
2445
+ const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
2446
+ if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) return negativeOption;
2447
+ return positiveOption || option;
2448
+ };
2449
+ const getErrorMessage = (option) => {
2450
+ const bestOption = findBestOptionFromValue(option);
2451
+ const optionKey = bestOption.attributeName();
2452
+ if (this.getOptionValueSource(optionKey) === "env") return `environment variable '${bestOption.envVar}'`;
2453
+ return `option '${bestOption.flags}'`;
2454
+ };
2455
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2456
+ this.error(message, { code: "commander.conflictingOption" });
2457
+ }
2458
+ /**
2459
+ * Unknown option `flag`.
2460
+ *
2461
+ * @param {string} flag
2462
+ * @private
2463
+ */
2464
+ unknownOption(flag) {
2465
+ if (this._allowUnknownOption) return;
2466
+ let suggestion = "";
2467
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
2468
+ let candidateFlags = [];
2469
+ let command = this;
2470
+ do {
2471
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
2472
+ candidateFlags = candidateFlags.concat(moreFlags);
2473
+ command = command.parent;
2474
+ } while (command && !command._enablePositionalOptions);
2475
+ suggestion = suggestSimilar(flag, candidateFlags);
2476
+ }
2477
+ const message = `error: unknown option '${flag}'${suggestion}`;
2478
+ this.error(message, { code: "commander.unknownOption" });
2479
+ }
2480
+ /**
2481
+ * Excess arguments, more than expected.
2482
+ *
2483
+ * @param {string[]} receivedArgs
2484
+ * @private
2485
+ */
2486
+ _excessArguments(receivedArgs) {
2487
+ if (this._allowExcessArguments) return;
2488
+ const expected = this.registeredArguments.length;
2489
+ const s = expected === 1 ? "" : "s";
2490
+ const received = receivedArgs.length;
2491
+ const message = `error: too many arguments${this.parent ? ` for '${this.name()}'` : ""}. Expected ${expected} argument${s} but got ${received}: ${receivedArgs.join(", ")}.`;
2492
+ this.error(message, { code: "commander.excessArguments" });
2493
+ }
2494
+ /**
2495
+ * Unknown command.
2496
+ *
2497
+ * @private
2498
+ */
2499
+ unknownCommand() {
2500
+ const unknownName = this.args[0];
2501
+ let suggestion = "";
2502
+ if (this._showSuggestionAfterError) {
2503
+ const candidateNames = [];
2504
+ this.createHelp().visibleCommands(this).forEach((command) => {
2505
+ candidateNames.push(command.name());
2506
+ if (command.alias()) candidateNames.push(command.alias());
2507
+ });
2508
+ suggestion = suggestSimilar(unknownName, candidateNames);
2509
+ }
2510
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
2511
+ this.error(message, { code: "commander.unknownCommand" });
2512
+ }
2513
+ /**
2514
+ * Get or set the program version.
2515
+ *
2516
+ * This method auto-registers the "-V, --version" option which will print the version number.
2517
+ *
2518
+ * You can optionally supply the flags and description to override the defaults.
2519
+ *
2520
+ * @param {string} [str]
2521
+ * @param {string} [flags]
2522
+ * @param {string} [description]
2523
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
2524
+ */
2525
+ version(str, flags, description) {
2526
+ if (str === void 0) return this._version;
2527
+ this._version = str;
2528
+ flags = flags || "-V, --version";
2529
+ description = description || "output the version number";
2530
+ const versionOption = this.createOption(flags, description);
2531
+ this._versionOptionName = versionOption.attributeName();
2532
+ this._registerOption(versionOption);
2533
+ this.on("option:" + versionOption.name(), () => {
2534
+ this._outputConfiguration.writeOut(`${str}\n`);
2535
+ this._exit(0, "commander.version", str);
2536
+ });
2537
+ return this;
2538
+ }
2539
+ /**
2540
+ * Set the description.
2541
+ *
2542
+ * @param {string} [str]
2543
+ * @param {object} [argsDescription]
2544
+ * @return {(string|Command)}
2545
+ */
2546
+ description(str, argsDescription) {
2547
+ if (str === void 0 && argsDescription === void 0) return this._description;
2548
+ this._description = str;
2549
+ if (argsDescription) this._argsDescription = argsDescription;
2550
+ return this;
2551
+ }
2552
+ /**
2553
+ * Set the summary. Used when listed as subcommand of parent.
2554
+ *
2555
+ * @param {string} [str]
2556
+ * @return {(string|Command)}
2557
+ */
2558
+ summary(str) {
2559
+ if (str === void 0) return this._summary;
2560
+ this._summary = str;
2561
+ return this;
2562
+ }
2563
+ /**
2564
+ * Set an alias for the command.
2565
+ *
2566
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
2567
+ *
2568
+ * @param {string} [alias]
2569
+ * @return {(string|Command)}
2570
+ */
2571
+ alias(alias) {
2572
+ if (alias === void 0) return this._aliases[0];
2573
+ /** @type {Command} */
2574
+ let command = this;
2575
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) command = this.commands[this.commands.length - 1];
2576
+ if (alias === command._name) throw new Error("Command alias can't be the same as its name");
2577
+ const matchingCommand = this.parent?._findCommand(alias);
2578
+ if (matchingCommand) {
2579
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
2580
+ throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
2581
+ }
2582
+ command._aliases.push(alias);
2583
+ return this;
2584
+ }
2585
+ /**
2586
+ * Set aliases for the command.
2587
+ *
2588
+ * Only the first alias is shown in the auto-generated help.
2589
+ *
2590
+ * @param {string[]} [aliases]
2591
+ * @return {(string[]|Command)}
2592
+ */
2593
+ aliases(aliases) {
2594
+ if (aliases === void 0) return this._aliases;
2595
+ aliases.forEach((alias) => this.alias(alias));
2596
+ return this;
2597
+ }
2598
+ /**
2599
+ * Set / get the command usage `str`.
2600
+ *
2601
+ * @param {string} [str]
2602
+ * @return {(string|Command)}
2603
+ */
2604
+ usage(str) {
2605
+ if (str === void 0) {
2606
+ if (this._usage) return this._usage;
2607
+ const args = this.registeredArguments.map((arg) => {
2608
+ return humanReadableArgName(arg);
2609
+ });
2610
+ return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
2611
+ }
2612
+ this._usage = str;
2613
+ return this;
2614
+ }
2615
+ /**
2616
+ * Get or set the name of the command.
2617
+ *
2618
+ * @param {string} [str]
2619
+ * @return {(string|Command)}
2620
+ */
2621
+ name(str) {
2622
+ if (str === void 0) return this._name;
2623
+ this._name = str;
2624
+ return this;
2625
+ }
2626
+ /**
2627
+ * Set/get the help group heading for this subcommand in parent command's help.
2628
+ *
2629
+ * @param {string} [heading]
2630
+ * @return {Command | string}
2631
+ */
2632
+ helpGroup(heading) {
2633
+ if (heading === void 0) return this._helpGroupHeading ?? "";
2634
+ this._helpGroupHeading = heading;
2635
+ return this;
2636
+ }
2637
+ /**
2638
+ * Set/get the default help group heading for subcommands added to this command.
2639
+ * (This does not override a group set directly on the subcommand using .helpGroup().)
2640
+ *
2641
+ * @example
2642
+ * program.commandsGroup('Development Commands:);
2643
+ * program.command('watch')...
2644
+ * program.command('lint')...
2645
+ * ...
2646
+ *
2647
+ * @param {string} [heading]
2648
+ * @returns {Command | string}
2649
+ */
2650
+ commandsGroup(heading) {
2651
+ if (heading === void 0) return this._defaultCommandGroup ?? "";
2652
+ this._defaultCommandGroup = heading;
2653
+ return this;
2654
+ }
2655
+ /**
2656
+ * Set/get the default help group heading for options added to this command.
2657
+ * (This does not override a group set directly on the option using .helpGroup().)
2658
+ *
2659
+ * @example
2660
+ * program
2661
+ * .optionsGroup('Development Options:')
2662
+ * .option('-d, --debug', 'output extra debugging')
2663
+ * .option('-p, --profile', 'output profiling information')
2664
+ *
2665
+ * @param {string} [heading]
2666
+ * @returns {Command | string}
2667
+ */
2668
+ optionsGroup(heading) {
2669
+ if (heading === void 0) return this._defaultOptionGroup ?? "";
2670
+ this._defaultOptionGroup = heading;
2671
+ return this;
2672
+ }
2673
+ /**
2674
+ * @param {Option} option
2675
+ * @private
2676
+ */
2677
+ _initOptionGroup(option) {
2678
+ if (this._defaultOptionGroup && !option.helpGroupHeading) option.helpGroup(this._defaultOptionGroup);
2679
+ }
2680
+ /**
2681
+ * @param {Command} cmd
2682
+ * @private
2683
+ */
2684
+ _initCommandGroup(cmd) {
2685
+ if (this._defaultCommandGroup && !cmd.helpGroup()) cmd.helpGroup(this._defaultCommandGroup);
2686
+ }
2687
+ /**
2688
+ * Set the name of the command from script filename, such as process.argv[1],
2689
+ * or import.meta.filename.
2690
+ *
2691
+ * (Used internally and public although not documented in README.)
2692
+ *
2693
+ * @example
2694
+ * program.nameFromFilename(import.meta.filename);
2695
+ *
2696
+ * @param {string} filename
2697
+ * @return {Command}
2698
+ */
2699
+ nameFromFilename(filename) {
2700
+ this._name = path.basename(filename, path.extname(filename));
2701
+ return this;
2702
+ }
2703
+ /**
2704
+ * Get or set the directory for searching for executable subcommands of this command.
2705
+ *
2706
+ * @example
2707
+ * program.executableDir(import.meta.dirname);
2708
+ * // or
2709
+ * program.executableDir('subcommands');
2710
+ *
2711
+ * @param {string} [path]
2712
+ * @return {(string|null|Command)}
2713
+ */
2714
+ executableDir(path) {
2715
+ if (path === void 0) return this._executableDir;
2716
+ this._executableDir = path;
2717
+ return this;
2718
+ }
2719
+ /**
2720
+ * Return program help documentation.
2721
+ *
2722
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
2723
+ * @return {string}
2724
+ */
2725
+ helpInformation(contextOptions) {
2726
+ const helper = this.createHelp();
2727
+ const context = this._getOutputContext(contextOptions);
2728
+ helper.prepareContext({
2729
+ error: context.error,
2730
+ helpWidth: context.helpWidth,
2731
+ outputHasColors: context.hasColors
2732
+ });
2733
+ const text = helper.formatHelp(this, helper);
2734
+ if (context.hasColors) return text;
2735
+ return this._outputConfiguration.stripColor(text);
2736
+ }
2737
+ /**
2738
+ * @typedef HelpContext
2739
+ * @type {object}
2740
+ * @property {boolean} error
2741
+ * @property {number} helpWidth
2742
+ * @property {boolean} hasColors
2743
+ * @property {function} write - includes stripColor if needed
2744
+ *
2745
+ * @returns {HelpContext}
2746
+ * @private
2747
+ */
2748
+ _getOutputContext(contextOptions) {
2749
+ contextOptions = contextOptions || {};
2750
+ const error = !!contextOptions.error;
2751
+ let baseWrite;
2752
+ let hasColors;
2753
+ let helpWidth;
2754
+ if (error) {
2755
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
2756
+ hasColors = this._outputConfiguration.getErrHasColors();
2757
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
2758
+ } else {
2759
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
2760
+ hasColors = this._outputConfiguration.getOutHasColors();
2761
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
2762
+ }
2763
+ const write = (str) => {
2764
+ if (!hasColors) str = this._outputConfiguration.stripColor(str);
2765
+ return baseWrite(str);
2766
+ };
2767
+ return {
2768
+ error,
2769
+ write,
2770
+ hasColors,
2771
+ helpWidth
2772
+ };
2773
+ }
2774
+ /**
2775
+ * Output help information for this command.
2776
+ *
2777
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2778
+ *
2779
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2780
+ */
2781
+ outputHelp(contextOptions) {
2782
+ let deprecatedCallback;
2783
+ if (typeof contextOptions === "function") {
2784
+ deprecatedCallback = contextOptions;
2785
+ contextOptions = void 0;
2786
+ }
2787
+ const outputContext = this._getOutputContext(contextOptions);
2788
+ /** @type {HelpTextEventContext} */
2789
+ const eventContext = {
2790
+ error: outputContext.error,
2791
+ write: outputContext.write,
2792
+ command: this
2793
+ };
2794
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
2795
+ this.emit("beforeHelp", eventContext);
2796
+ let helpInformation = this.helpInformation({ error: outputContext.error });
2797
+ if (deprecatedCallback) {
2798
+ helpInformation = deprecatedCallback(helpInformation);
2799
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) throw new Error("outputHelp callback must return a string or a Buffer");
2800
+ }
2801
+ outputContext.write(helpInformation);
2802
+ if (this._getHelpOption()?.long) this.emit(this._getHelpOption().long);
2803
+ this.emit("afterHelp", eventContext);
2804
+ this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", eventContext));
2805
+ }
2806
+ /**
2807
+ * You can pass in flags and a description to customise the built-in help option.
2808
+ * Pass in false to disable the built-in help option.
2809
+ *
2810
+ * @example
2811
+ * program.helpOption('-?, --help' 'show help'); // customise
2812
+ * program.helpOption(false); // disable
2813
+ *
2814
+ * @param {(string | boolean)} flags
2815
+ * @param {string} [description]
2816
+ * @return {Command} `this` command for chaining
2817
+ */
2818
+ helpOption(flags, description) {
2819
+ if (typeof flags === "boolean") {
2820
+ if (flags) {
2821
+ if (this._helpOption === null) this._helpOption = void 0;
2822
+ if (this._defaultOptionGroup) this._initOptionGroup(this._getHelpOption());
2823
+ } else this._helpOption = null;
2824
+ return this;
2825
+ }
2826
+ this._helpOption = this.createOption(flags ?? "-h, --help", description ?? "display help for command");
2827
+ if (flags || description) this._initOptionGroup(this._helpOption);
2828
+ return this;
2829
+ }
2830
+ /**
2831
+ * Lazy create help option.
2832
+ * Returns null if has been disabled with .helpOption(false).
2833
+ *
2834
+ * @returns {(Option | null)} the help option
2835
+ * @package
2836
+ */
2837
+ _getHelpOption() {
2838
+ if (this._helpOption === void 0) this.helpOption(void 0, void 0);
2839
+ return this._helpOption;
2840
+ }
2841
+ /**
2842
+ * Supply your own option to use for the built-in help option.
2843
+ * This is an alternative to using helpOption() to customise the flags and description etc.
2844
+ *
2845
+ * @param {Option} option
2846
+ * @return {Command} `this` command for chaining
2847
+ */
2848
+ addHelpOption(option) {
2849
+ this._helpOption = option;
2850
+ this._initOptionGroup(option);
2851
+ return this;
2852
+ }
2853
+ /**
2854
+ * Output help information and exit.
2855
+ *
2856
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2857
+ *
2858
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2859
+ */
2860
+ help(contextOptions) {
2861
+ this.outputHelp(contextOptions);
2862
+ let exitCode = Number(process$1.exitCode ?? 0);
2863
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) exitCode = 1;
2864
+ this._exit(exitCode, "commander.help", "(outputHelp)");
2865
+ }
2866
+ /**
2867
+ * // Do a little typing to coordinate emit and listener for the help text events.
2868
+ * @typedef HelpTextEventContext
2869
+ * @type {object}
2870
+ * @property {boolean} error
2871
+ * @property {Command} command
2872
+ * @property {function} write
2873
+ */
2874
+ /**
2875
+ * Add additional text to be displayed with the built-in help.
2876
+ *
2877
+ * Position is 'before' or 'after' to affect just this command,
2878
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
2879
+ *
2880
+ * @param {string} position - before or after built-in help
2881
+ * @param {(string | Function)} text - string to add, or a function returning a string
2882
+ * @return {Command} `this` command for chaining
2883
+ */
2884
+ addHelpText(position, text) {
2885
+ const allowedValues = [
2886
+ "beforeAll",
2887
+ "before",
2888
+ "after",
2889
+ "afterAll"
2890
+ ];
2891
+ if (!allowedValues.includes(position)) throw new Error(`Unexpected value for position to addHelpText.
2892
+ Expecting one of '${allowedValues.join("', '")}'`);
2893
+ const helpEvent = `${position}Help`;
2894
+ this.on(helpEvent, (context) => {
2895
+ let helpStr;
2896
+ if (typeof text === "function") helpStr = text({
2897
+ error: context.error,
2898
+ command: context.command
2899
+ });
2900
+ else helpStr = text;
2901
+ if (helpStr) context.write(`${helpStr}\n`);
2902
+ });
2903
+ return this;
2904
+ }
2905
+ /**
2906
+ * Output help information if help flags specified
2907
+ *
2908
+ * @param {Array} args - array of options to search for help flags
2909
+ * @private
2910
+ */
2911
+ _outputHelpIfRequested(args) {
2912
+ const helpOption = this._getHelpOption();
2913
+ if (helpOption && args.find((arg) => helpOption.is(arg))) {
2914
+ this.outputHelp();
2915
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
2916
+ }
2917
+ }
2918
+ };
2919
+ /**
2920
+ * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).
2921
+ *
2922
+ * @param {string[]} args - array of arguments from node.execArgv
2923
+ * @returns {string[]}
2924
+ * @private
2925
+ */
2926
+ function incrementNodeInspectorPort(args) {
2927
+ return args.map((arg) => {
2928
+ if (!arg.startsWith("--inspect")) return arg;
2929
+ let debugOption;
2930
+ let debugHost = "127.0.0.1";
2931
+ let debugPort = "9229";
2932
+ let match;
2933
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) debugOption = match[1];
2934
+ else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
2935
+ debugOption = match[1];
2936
+ if (/^\d+$/.test(match[3])) debugPort = match[3];
2937
+ else debugHost = match[3];
2938
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
2939
+ debugOption = match[1];
2940
+ debugHost = match[3];
2941
+ debugPort = match[4];
2942
+ }
2943
+ if (debugOption && debugPort !== "0") return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
2944
+ return arg;
2945
+ });
2946
+ }
2947
+ /**
2948
+ * Exported for using from tests, not otherwise used outside this file.
2949
+ *
2950
+ * @returns {boolean | undefined}
2951
+ * @package
2952
+ */
2953
+ function useColor() {
2954
+ if (process$1.env.NO_COLOR || process$1.env.FORCE_COLOR === "0" || process$1.env.FORCE_COLOR === "false") return false;
2955
+ if (process$1.env.FORCE_COLOR || process$1.env.CLICOLOR_FORCE !== void 0) return true;
2956
+ }
2957
+ new Command();
2958
+ //#endregion
2959
+ //#region node_modules/base-x/src/esm/index.js
2960
+ function base(ALPHABET) {
2961
+ if (ALPHABET.length >= 255) throw new TypeError("Alphabet too long");
2962
+ const BASE_MAP = /* @__PURE__ */ new Uint8Array(256);
2963
+ for (let j = 0; j < BASE_MAP.length; j++) BASE_MAP[j] = 255;
2964
+ for (let i = 0; i < ALPHABET.length; i++) {
2965
+ const x = ALPHABET.charAt(i);
2966
+ const xc = x.charCodeAt(0);
2967
+ if (BASE_MAP[xc] !== 255) throw new TypeError(x + " is ambiguous");
2968
+ BASE_MAP[xc] = i;
2969
+ }
2970
+ const BASE = ALPHABET.length;
2971
+ const LEADER = ALPHABET.charAt(0);
2972
+ const FACTOR = Math.log(BASE) / Math.log(256);
2973
+ const iFACTOR = Math.log(256) / Math.log(BASE);
2974
+ function encode(source) {
2975
+ if (source instanceof Uint8Array) {} else if (ArrayBuffer.isView(source)) source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
2976
+ else if (Array.isArray(source)) source = Uint8Array.from(source);
2977
+ if (!(source instanceof Uint8Array)) throw new TypeError("Expected Uint8Array");
2978
+ if (source.length === 0) return "";
2979
+ let zeroes = 0;
2980
+ let length = 0;
2981
+ let pbegin = 0;
2982
+ const pend = source.length;
2983
+ while (pbegin !== pend && source[pbegin] === 0) {
2984
+ pbegin++;
2985
+ zeroes++;
2986
+ }
2987
+ const size = (pend - pbegin) * iFACTOR + 1 >>> 0;
2988
+ const b58 = new Uint8Array(size);
2989
+ while (pbegin !== pend) {
2990
+ let carry = source[pbegin];
2991
+ let i = 0;
2992
+ for (let it1 = size - 1; (carry !== 0 || i < length) && it1 !== -1; it1--, i++) {
2993
+ carry += 256 * b58[it1] >>> 0;
2994
+ b58[it1] = carry % BASE >>> 0;
2995
+ carry = carry / BASE >>> 0;
2996
+ }
2997
+ if (carry !== 0) throw new Error("Non-zero carry");
2998
+ length = i;
2999
+ pbegin++;
3000
+ }
3001
+ let it2 = size - length;
3002
+ while (it2 !== size && b58[it2] === 0) it2++;
3003
+ let str = LEADER.repeat(zeroes);
3004
+ for (; it2 < size; ++it2) str += ALPHABET.charAt(b58[it2]);
3005
+ return str;
3006
+ }
3007
+ function decodeUnsafe(source) {
3008
+ if (typeof source !== "string") throw new TypeError("Expected String");
3009
+ if (source.length === 0) return /* @__PURE__ */ new Uint8Array();
3010
+ let psz = 0;
3011
+ let zeroes = 0;
3012
+ let length = 0;
3013
+ while (source[psz] === LEADER) {
3014
+ zeroes++;
3015
+ psz++;
3016
+ }
3017
+ const size = (source.length - psz) * FACTOR + 1 >>> 0;
3018
+ const b256 = new Uint8Array(size);
3019
+ while (psz < source.length) {
3020
+ const charCode = source.charCodeAt(psz);
3021
+ if (charCode > 255) return;
3022
+ let carry = BASE_MAP[charCode];
3023
+ if (carry === 255) return;
3024
+ let i = 0;
3025
+ for (let it3 = size - 1; (carry !== 0 || i < length) && it3 !== -1; it3--, i++) {
3026
+ carry += BASE * b256[it3] >>> 0;
3027
+ b256[it3] = carry % 256 >>> 0;
3028
+ carry = carry / 256 >>> 0;
3029
+ }
3030
+ if (carry !== 0) throw new Error("Non-zero carry");
3031
+ length = i;
3032
+ psz++;
3033
+ }
3034
+ let it4 = size - length;
3035
+ while (it4 !== size && b256[it4] === 0) it4++;
3036
+ const vch = new Uint8Array(zeroes + (size - it4));
3037
+ let j = zeroes;
3038
+ while (it4 !== size) vch[j++] = b256[it4++];
3039
+ return vch;
3040
+ }
3041
+ function decode(string) {
3042
+ const buffer = decodeUnsafe(string);
3043
+ if (buffer) return buffer;
3044
+ throw new Error("Non-base" + BASE + " character");
3045
+ }
3046
+ return {
3047
+ encode,
3048
+ decodeUnsafe,
3049
+ decode
3050
+ };
3051
+ }
3052
+ var esm_default = base("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");
3053
+ //#endregion
3054
+ //#region src/conversion.ts
3055
+ function encodeByteArray(input) {
3056
+ const values = JSON.parse(input);
3057
+ if (!Array.isArray(values) || values.some((value) => !Number.isInteger(value) || value < 0 || value > 255)) throw new Error("Input must be a JSON array of bytes.");
3058
+ return esm_default.encode(new Uint8Array(values));
3059
+ }
3060
+ function decodeBase58(input) {
3061
+ return JSON.stringify(Array.from(esm_default.decode(input)));
3062
+ }
3063
+ //#endregion
3064
+ //#region src/cli.ts
3065
+ function createProgram() {
3066
+ const program = new Command().name("bs58ify").description("Encode and decode Base58 byte arrays.");
3067
+ return program.action(() => {
3068
+ program.outputHelp();
3069
+ }).addCommand(new Command("encode").description("Encode a JSON byte array as Base58.").argument("<uint8array>", "JSON array of bytes").argument("<output>", "file to write the Base58 result to").action(async (input, outputPath) => {
3070
+ await writeFile(outputPath, encodeByteArray(input));
3071
+ console.log(`Encoded Base58 value written to ${outputPath}`);
3072
+ })).addCommand(new Command("decode").description("Decode Base58 as a JSON byte array.").argument("<base58>", "Base58-encoded value").argument("<output>", "file to write the JSON result to").action(async (input, outputPath) => {
3073
+ await writeFile(outputPath, decodeBase58(input));
3074
+ console.log(`Decoded JSON byte array written to ${outputPath}`);
3075
+ }));
3076
+ }
3077
+ if (process.argv[1] === fileURLToPath(import.meta.url)) createProgram().parseAsync().catch((error) => {
3078
+ console.error(error instanceof Error ? error.message : error);
3079
+ process.exitCode = 1;
3080
+ });
3081
+ //#endregion
3082
+ export { createProgram };