release-note 0.0.2 → 0.0.3

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