@hygraph/cli 0.0.0 → 0.0.1

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