eslint-cdk-plugin 3.4.4 → 3.4.6

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.
Files changed (62) hide show
  1. package/bin/index.mjs +4318 -0
  2. package/bin/prompt-DVcPfS2N.mjs +847 -0
  3. package/dist/index.cjs +26648 -1606
  4. package/dist/index.d.cts +55 -0
  5. package/dist/index.d.cts.map +1 -0
  6. package/dist/index.d.mts +55 -0
  7. package/dist/index.d.mts.map +1 -0
  8. package/dist/index.mjs +26650 -1584
  9. package/dist/index.mjs.map +1 -0
  10. package/package.json +20 -22
  11. package/src/configs/flat-config.ts +69 -0
  12. package/src/configs/index.ts +6 -0
  13. package/src/{utils/get-child-nodes.ts → core/ast-node/finder/child-nodes.ts} +2 -2
  14. package/src/{utils/getConstructor.ts → core/ast-node/finder/constructor.ts} +1 -1
  15. package/src/core/ast-node/finder/property-name.ts +20 -0
  16. package/src/core/ast-node/finder/public-property.ts +76 -0
  17. package/src/core/cdk-construct/type-checker/is-construct-or-stack.ts +21 -0
  18. package/src/core/cdk-construct/type-checker/is-construct.ts +22 -0
  19. package/src/{utils → core/cdk-construct/type-checker}/is-resource-with-readonly-interface.ts +5 -4
  20. package/src/core/cdk-construct/type-checker/is-resource.ts +17 -0
  21. package/src/core/cdk-construct/type-finder/index.ts +73 -0
  22. package/src/{utils/typecheck/ts-type.ts → core/ts-type/checker/is-array.ts} +2 -8
  23. package/src/core/ts-type/checker/is-class.ts +7 -0
  24. package/src/core/ts-type/checker/is-extends-target-super-class.ts +24 -0
  25. package/src/core/ts-type/checker/private/get-symbol.ts +5 -0
  26. package/src/core/ts-type/finder/array-element.ts +20 -0
  27. package/src/core/ts-type/finder/constructor-property-name.ts +21 -0
  28. package/src/{utils/getGenericTypeArgument.ts → core/ts-type/finder/generics-type-argument.ts} +5 -5
  29. package/src/index.ts +6 -108
  30. package/src/rules/construct-constructor-property.ts +48 -26
  31. package/src/rules/index.ts +34 -0
  32. package/src/rules/no-construct-in-interface.ts +5 -51
  33. package/src/rules/no-construct-in-public-property-of-construct.ts +20 -143
  34. package/src/rules/no-construct-stack-suffix.ts +5 -5
  35. package/src/rules/no-mutable-property-of-props-interface.ts +1 -1
  36. package/src/rules/no-mutable-public-property-of-construct.ts +47 -39
  37. package/src/rules/no-parent-name-construct-id-match.ts +4 -6
  38. package/src/rules/no-unused-props/index.ts +19 -10
  39. package/src/rules/no-unused-props/props-usage-analyzer.ts +207 -190
  40. package/src/rules/no-unused-props/props-usage-tracker.ts +4 -3
  41. package/src/rules/no-unused-props/visitor/direct-props-usage-visitor.ts +145 -0
  42. package/src/rules/no-unused-props/visitor/index.ts +5 -0
  43. package/src/rules/no-unused-props/visitor/instance-variable-usage-visitor.ts +117 -0
  44. package/src/rules/no-unused-props/visitor/interface/node-visitor.ts +9 -0
  45. package/src/rules/no-unused-props/visitor/method-call-collector-visitor.ts +60 -0
  46. package/src/rules/no-unused-props/visitor/props-alias-visitor.ts +81 -0
  47. package/src/rules/no-unused-props/visitor/traverse-nodes.ts +38 -0
  48. package/src/rules/no-variable-construct-id.ts +4 -4
  49. package/src/rules/pascal-case-construct-id.ts +5 -5
  50. package/src/rules/props-name-convention.ts +4 -4
  51. package/src/rules/require-jsdoc.ts +2 -2
  52. package/src/rules/require-passing-this.ts +4 -4
  53. package/src/rules/require-props-default-doc.ts +1 -1
  54. package/bin/migration.mjs +0 -100
  55. package/dist/index.d.ts +0 -47
  56. package/dist/index.d.ts.map +0 -1
  57. package/src/utils/getArrayElementType.ts +0 -14
  58. package/src/utils/getPropertyNames.ts +0 -41
  59. package/src/utils/typecheck/cdk.ts +0 -71
  60. package/src/utils/typecheck/ts-node.ts +0 -7
  61. /package/src/{utils/convertString.ts → shared/converter/to-pascal-case.ts} +0 -0
  62. /package/src/{utils/createRule.ts → shared/create-rule.ts} +0 -0
package/bin/index.mjs ADDED
@@ -0,0 +1,4318 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire } from "node:module";
3
+ import { sep } from "node:path";
4
+ import g$1 from "node:process";
5
+ import { formatWithOptions } from "node:util";
6
+ import * as tty from "node:tty";
7
+ import { execSync } from "child_process";
8
+ import * as fs from "fs";
9
+ import * as path from "path";
10
+
11
+ //#region rolldown:runtime
12
+ var __create = Object.create;
13
+ var __defProp = Object.defineProperty;
14
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
15
+ var __getOwnPropNames = Object.getOwnPropertyNames;
16
+ var __getProtoOf = Object.getPrototypeOf;
17
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
18
+ var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
19
+ var __copyProps = (to, from, except, desc) => {
20
+ if (from && typeof from === "object" || typeof from === "function") {
21
+ for (var keys = __getOwnPropNames(from), i$1 = 0, n$1 = keys.length, key; i$1 < n$1; i$1++) {
22
+ key = keys[i$1];
23
+ if (!__hasOwnProp.call(to, key) && key !== except) {
24
+ __defProp(to, key, {
25
+ get: ((k) => from[k]).bind(null, key),
26
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
27
+ });
28
+ }
29
+ }
30
+ }
31
+ return to;
32
+ };
33
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
34
+ value: mod,
35
+ enumerable: true
36
+ }) : target, mod));
37
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
38
+
39
+ //#endregion
40
+ //#region node_modules/.pnpm/commander@14.0.2/node_modules/commander/lib/error.js
41
+ var require_error = /* @__PURE__ */ __commonJSMin(((exports) => {
42
+ /**
43
+ * CommanderError class
44
+ */
45
+ var CommanderError$3 = class extends Error {
46
+ /**
47
+ * Constructs the CommanderError class
48
+ * @param {number} exitCode suggested exit code which could be used with process.exit
49
+ * @param {string} code an id string representing the error
50
+ * @param {string} message human-readable description of the error
51
+ */
52
+ constructor(exitCode, code, message) {
53
+ super(message);
54
+ Error.captureStackTrace(this, this.constructor);
55
+ this.name = this.constructor.name;
56
+ this.code = code;
57
+ this.exitCode = exitCode;
58
+ this.nestedError = void 0;
59
+ }
60
+ };
61
+ /**
62
+ * InvalidArgumentError class
63
+ */
64
+ var InvalidArgumentError$4 = class extends CommanderError$3 {
65
+ /**
66
+ * Constructs the InvalidArgumentError class
67
+ * @param {string} [message] explanation of why argument is invalid
68
+ */
69
+ constructor(message) {
70
+ super(1, "commander.invalidArgument", message);
71
+ Error.captureStackTrace(this, this.constructor);
72
+ this.name = this.constructor.name;
73
+ }
74
+ };
75
+ exports.CommanderError = CommanderError$3;
76
+ exports.InvalidArgumentError = InvalidArgumentError$4;
77
+ }));
78
+
79
+ //#endregion
80
+ //#region node_modules/.pnpm/commander@14.0.2/node_modules/commander/lib/argument.js
81
+ var require_argument = /* @__PURE__ */ __commonJSMin(((exports) => {
82
+ const { InvalidArgumentError: InvalidArgumentError$3 } = require_error();
83
+ var Argument$3 = class {
84
+ /**
85
+ * Initialize a new command argument with the given name and description.
86
+ * The default is that the argument is required, and you can explicitly
87
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
88
+ *
89
+ * @param {string} name
90
+ * @param {string} [description]
91
+ */
92
+ constructor(name, description) {
93
+ this.description = description || "";
94
+ this.variadic = false;
95
+ this.parseArg = void 0;
96
+ this.defaultValue = void 0;
97
+ this.defaultValueDescription = void 0;
98
+ this.argChoices = void 0;
99
+ switch (name[0]) {
100
+ case "<":
101
+ this.required = true;
102
+ this._name = name.slice(1, -1);
103
+ break;
104
+ case "[":
105
+ this.required = false;
106
+ this._name = name.slice(1, -1);
107
+ break;
108
+ default:
109
+ this.required = true;
110
+ this._name = name;
111
+ break;
112
+ }
113
+ if (this._name.endsWith("...")) {
114
+ this.variadic = true;
115
+ this._name = this._name.slice(0, -3);
116
+ }
117
+ }
118
+ /**
119
+ * Return argument name.
120
+ *
121
+ * @return {string}
122
+ */
123
+ name() {
124
+ return this._name;
125
+ }
126
+ /**
127
+ * @package
128
+ */
129
+ _collectValue(value, previous) {
130
+ if (previous === this.defaultValue || !Array.isArray(previous)) return [value];
131
+ previous.push(value);
132
+ return previous;
133
+ }
134
+ /**
135
+ * Set the default value, and optionally supply the description to be displayed in the help.
136
+ *
137
+ * @param {*} value
138
+ * @param {string} [description]
139
+ * @return {Argument}
140
+ */
141
+ default(value, description) {
142
+ this.defaultValue = value;
143
+ this.defaultValueDescription = description;
144
+ return this;
145
+ }
146
+ /**
147
+ * Set the custom handler for processing CLI command arguments into argument values.
148
+ *
149
+ * @param {Function} [fn]
150
+ * @return {Argument}
151
+ */
152
+ argParser(fn) {
153
+ this.parseArg = fn;
154
+ return this;
155
+ }
156
+ /**
157
+ * Only allow argument value to be one of choices.
158
+ *
159
+ * @param {string[]} values
160
+ * @return {Argument}
161
+ */
162
+ choices(values) {
163
+ this.argChoices = values.slice();
164
+ this.parseArg = (arg, previous) => {
165
+ if (!this.argChoices.includes(arg)) throw new InvalidArgumentError$3(`Allowed choices are ${this.argChoices.join(", ")}.`);
166
+ if (this.variadic) return this._collectValue(arg, previous);
167
+ return arg;
168
+ };
169
+ return this;
170
+ }
171
+ /**
172
+ * Make argument required.
173
+ *
174
+ * @returns {Argument}
175
+ */
176
+ argRequired() {
177
+ this.required = true;
178
+ return this;
179
+ }
180
+ /**
181
+ * Make argument optional.
182
+ *
183
+ * @returns {Argument}
184
+ */
185
+ argOptional() {
186
+ this.required = false;
187
+ return this;
188
+ }
189
+ };
190
+ /**
191
+ * Takes an argument and returns its human readable equivalent for help usage.
192
+ *
193
+ * @param {Argument} arg
194
+ * @return {string}
195
+ * @private
196
+ */
197
+ function humanReadableArgName$2(arg) {
198
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
199
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
200
+ }
201
+ exports.Argument = Argument$3;
202
+ exports.humanReadableArgName = humanReadableArgName$2;
203
+ }));
204
+
205
+ //#endregion
206
+ //#region node_modules/.pnpm/commander@14.0.2/node_modules/commander/lib/help.js
207
+ var require_help = /* @__PURE__ */ __commonJSMin(((exports) => {
208
+ const { humanReadableArgName: humanReadableArgName$1 } = require_argument();
209
+ /**
210
+ * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`
211
+ * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types
212
+ * @typedef { import("./argument.js").Argument } Argument
213
+ * @typedef { import("./command.js").Command } Command
214
+ * @typedef { import("./option.js").Option } Option
215
+ */
216
+ var Help$3 = class {
217
+ constructor() {
218
+ this.helpWidth = void 0;
219
+ this.minWidthToWrap = 40;
220
+ this.sortSubcommands = false;
221
+ this.sortOptions = false;
222
+ this.showGlobalOptions = false;
223
+ }
224
+ /**
225
+ * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
226
+ * and just before calling `formatHelp()`.
227
+ *
228
+ * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
229
+ *
230
+ * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
231
+ */
232
+ prepareContext(contextOptions) {
233
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
234
+ }
235
+ /**
236
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
237
+ *
238
+ * @param {Command} cmd
239
+ * @returns {Command[]}
240
+ */
241
+ visibleCommands(cmd) {
242
+ const visibleCommands = cmd.commands.filter((cmd$1) => !cmd$1._hidden);
243
+ const helpCommand = cmd._getHelpCommand();
244
+ if (helpCommand && !helpCommand._hidden) visibleCommands.push(helpCommand);
245
+ if (this.sortSubcommands) visibleCommands.sort((a$1, b$1) => {
246
+ return a$1.name().localeCompare(b$1.name());
247
+ });
248
+ return visibleCommands;
249
+ }
250
+ /**
251
+ * Compare options for sort.
252
+ *
253
+ * @param {Option} a
254
+ * @param {Option} b
255
+ * @returns {number}
256
+ */
257
+ compareOptions(a$1, b$1) {
258
+ const getSortKey = (option) => {
259
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
260
+ };
261
+ return getSortKey(a$1).localeCompare(getSortKey(b$1));
262
+ }
263
+ /**
264
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
265
+ *
266
+ * @param {Command} cmd
267
+ * @returns {Option[]}
268
+ */
269
+ visibleOptions(cmd) {
270
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
271
+ const helpOption = cmd._getHelpOption();
272
+ if (helpOption && !helpOption.hidden) {
273
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
274
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
275
+ if (!removeShort && !removeLong) visibleOptions.push(helpOption);
276
+ else if (helpOption.long && !removeLong) visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
277
+ else if (helpOption.short && !removeShort) visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
278
+ }
279
+ if (this.sortOptions) visibleOptions.sort(this.compareOptions);
280
+ return visibleOptions;
281
+ }
282
+ /**
283
+ * Get an array of the visible global options. (Not including help.)
284
+ *
285
+ * @param {Command} cmd
286
+ * @returns {Option[]}
287
+ */
288
+ visibleGlobalOptions(cmd) {
289
+ if (!this.showGlobalOptions) return [];
290
+ const globalOptions = [];
291
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
292
+ const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
293
+ globalOptions.push(...visibleOptions);
294
+ }
295
+ if (this.sortOptions) globalOptions.sort(this.compareOptions);
296
+ return globalOptions;
297
+ }
298
+ /**
299
+ * Get an array of the arguments if any have a description.
300
+ *
301
+ * @param {Command} cmd
302
+ * @returns {Argument[]}
303
+ */
304
+ visibleArguments(cmd) {
305
+ if (cmd._argsDescription) cmd.registeredArguments.forEach((argument) => {
306
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
307
+ });
308
+ if (cmd.registeredArguments.find((argument) => argument.description)) return cmd.registeredArguments;
309
+ return [];
310
+ }
311
+ /**
312
+ * Get the command term to show in the list of subcommands.
313
+ *
314
+ * @param {Command} cmd
315
+ * @returns {string}
316
+ */
317
+ subcommandTerm(cmd) {
318
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName$1(arg)).join(" ");
319
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
320
+ }
321
+ /**
322
+ * Get the option term to show in the list of options.
323
+ *
324
+ * @param {Option} option
325
+ * @returns {string}
326
+ */
327
+ optionTerm(option) {
328
+ return option.flags;
329
+ }
330
+ /**
331
+ * Get the argument term to show in the list of arguments.
332
+ *
333
+ * @param {Argument} argument
334
+ * @returns {string}
335
+ */
336
+ argumentTerm(argument) {
337
+ return argument.name();
338
+ }
339
+ /**
340
+ * Get the longest command term length.
341
+ *
342
+ * @param {Command} cmd
343
+ * @param {Help} helper
344
+ * @returns {number}
345
+ */
346
+ longestSubcommandTermLength(cmd, helper) {
347
+ return helper.visibleCommands(cmd).reduce((max, command) => {
348
+ return Math.max(max, this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command))));
349
+ }, 0);
350
+ }
351
+ /**
352
+ * Get the longest option term length.
353
+ *
354
+ * @param {Command} cmd
355
+ * @param {Help} helper
356
+ * @returns {number}
357
+ */
358
+ longestOptionTermLength(cmd, helper) {
359
+ return helper.visibleOptions(cmd).reduce((max, option) => {
360
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
361
+ }, 0);
362
+ }
363
+ /**
364
+ * Get the longest global option term length.
365
+ *
366
+ * @param {Command} cmd
367
+ * @param {Help} helper
368
+ * @returns {number}
369
+ */
370
+ longestGlobalOptionTermLength(cmd, helper) {
371
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
372
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
373
+ }, 0);
374
+ }
375
+ /**
376
+ * Get the longest argument term length.
377
+ *
378
+ * @param {Command} cmd
379
+ * @param {Help} helper
380
+ * @returns {number}
381
+ */
382
+ longestArgumentTermLength(cmd, helper) {
383
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
384
+ return Math.max(max, this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument))));
385
+ }, 0);
386
+ }
387
+ /**
388
+ * Get the command usage to be displayed at the top of the built-in help.
389
+ *
390
+ * @param {Command} cmd
391
+ * @returns {string}
392
+ */
393
+ commandUsage(cmd) {
394
+ let cmdName = cmd._name;
395
+ if (cmd._aliases[0]) cmdName = cmdName + "|" + cmd._aliases[0];
396
+ let ancestorCmdNames = "";
397
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
398
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
399
+ }
400
+ /**
401
+ * Get the description for the command.
402
+ *
403
+ * @param {Command} cmd
404
+ * @returns {string}
405
+ */
406
+ commandDescription(cmd) {
407
+ return cmd.description();
408
+ }
409
+ /**
410
+ * Get the subcommand summary to show in the list of subcommands.
411
+ * (Fallback to description for backwards compatibility.)
412
+ *
413
+ * @param {Command} cmd
414
+ * @returns {string}
415
+ */
416
+ subcommandDescription(cmd) {
417
+ return cmd.summary() || cmd.description();
418
+ }
419
+ /**
420
+ * Get the option description to show in the list of options.
421
+ *
422
+ * @param {Option} option
423
+ * @return {string}
424
+ */
425
+ optionDescription(option) {
426
+ const extraInfo = [];
427
+ if (option.argChoices) extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
428
+ if (option.defaultValue !== void 0) {
429
+ if (option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean") extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
430
+ }
431
+ if (option.presetArg !== void 0 && option.optional) extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
432
+ if (option.envVar !== void 0) extraInfo.push(`env: ${option.envVar}`);
433
+ if (extraInfo.length > 0) {
434
+ const extraDescription = `(${extraInfo.join(", ")})`;
435
+ if (option.description) return `${option.description} ${extraDescription}`;
436
+ return extraDescription;
437
+ }
438
+ return option.description;
439
+ }
440
+ /**
441
+ * Get the argument description to show in the list of arguments.
442
+ *
443
+ * @param {Argument} argument
444
+ * @return {string}
445
+ */
446
+ argumentDescription(argument) {
447
+ const extraInfo = [];
448
+ if (argument.argChoices) extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
449
+ if (argument.defaultValue !== void 0) extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
450
+ if (extraInfo.length > 0) {
451
+ const extraDescription = `(${extraInfo.join(", ")})`;
452
+ if (argument.description) return `${argument.description} ${extraDescription}`;
453
+ return extraDescription;
454
+ }
455
+ return argument.description;
456
+ }
457
+ /**
458
+ * Format a list of items, given a heading and an array of formatted items.
459
+ *
460
+ * @param {string} heading
461
+ * @param {string[]} items
462
+ * @param {Help} helper
463
+ * @returns string[]
464
+ */
465
+ formatItemList(heading, items, helper) {
466
+ if (items.length === 0) return [];
467
+ return [
468
+ helper.styleTitle(heading),
469
+ ...items,
470
+ ""
471
+ ];
472
+ }
473
+ /**
474
+ * Group items by their help group heading.
475
+ *
476
+ * @param {Command[] | Option[]} unsortedItems
477
+ * @param {Command[] | Option[]} visibleItems
478
+ * @param {Function} getGroup
479
+ * @returns {Map<string, Command[] | Option[]>}
480
+ */
481
+ groupItems(unsortedItems, visibleItems, getGroup) {
482
+ const result = /* @__PURE__ */ new Map();
483
+ unsortedItems.forEach((item) => {
484
+ const group = getGroup(item);
485
+ if (!result.has(group)) result.set(group, []);
486
+ });
487
+ visibleItems.forEach((item) => {
488
+ const group = getGroup(item);
489
+ if (!result.has(group)) result.set(group, []);
490
+ result.get(group).push(item);
491
+ });
492
+ return result;
493
+ }
494
+ /**
495
+ * Generate the built-in help text.
496
+ *
497
+ * @param {Command} cmd
498
+ * @param {Help} helper
499
+ * @returns {string}
500
+ */
501
+ formatHelp(cmd, helper) {
502
+ const termWidth = helper.padWidth(cmd, helper);
503
+ const helpWidth = helper.helpWidth ?? 80;
504
+ function callFormatItem(term, description) {
505
+ return helper.formatItem(term, termWidth, description, helper);
506
+ }
507
+ let output = [`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`, ""];
508
+ const commandDescription = helper.commandDescription(cmd);
509
+ if (commandDescription.length > 0) output = output.concat([helper.boxWrap(helper.styleCommandDescription(commandDescription), helpWidth), ""]);
510
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
511
+ return callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)), helper.styleArgumentDescription(helper.argumentDescription(argument)));
512
+ });
513
+ output = output.concat(this.formatItemList("Arguments:", argumentList, helper));
514
+ this.groupItems(cmd.options, helper.visibleOptions(cmd), (option) => option.helpGroupHeading ?? "Options:").forEach((options$1, group) => {
515
+ const optionList = options$1.map((option) => {
516
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
517
+ });
518
+ output = output.concat(this.formatItemList(group, optionList, helper));
519
+ });
520
+ if (helper.showGlobalOptions) {
521
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
522
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
523
+ });
524
+ output = output.concat(this.formatItemList("Global Options:", globalOptionList, helper));
525
+ }
526
+ this.groupItems(cmd.commands, helper.visibleCommands(cmd), (sub) => sub.helpGroup() || "Commands:").forEach((commands, group) => {
527
+ const commandList = commands.map((sub) => {
528
+ return callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(sub)), helper.styleSubcommandDescription(helper.subcommandDescription(sub)));
529
+ });
530
+ output = output.concat(this.formatItemList(group, commandList, helper));
531
+ });
532
+ return output.join("\n");
533
+ }
534
+ /**
535
+ * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
536
+ *
537
+ * @param {string} str
538
+ * @returns {number}
539
+ */
540
+ displayWidth(str) {
541
+ return stripColor$1(str).length;
542
+ }
543
+ /**
544
+ * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
545
+ *
546
+ * @param {string} str
547
+ * @returns {string}
548
+ */
549
+ styleTitle(str) {
550
+ return str;
551
+ }
552
+ styleUsage(str) {
553
+ return str.split(" ").map((word) => {
554
+ if (word === "[options]") return this.styleOptionText(word);
555
+ if (word === "[command]") return this.styleSubcommandText(word);
556
+ if (word[0] === "[" || word[0] === "<") return this.styleArgumentText(word);
557
+ return this.styleCommandText(word);
558
+ }).join(" ");
559
+ }
560
+ styleCommandDescription(str) {
561
+ return this.styleDescriptionText(str);
562
+ }
563
+ styleOptionDescription(str) {
564
+ return this.styleDescriptionText(str);
565
+ }
566
+ styleSubcommandDescription(str) {
567
+ return this.styleDescriptionText(str);
568
+ }
569
+ styleArgumentDescription(str) {
570
+ return this.styleDescriptionText(str);
571
+ }
572
+ styleDescriptionText(str) {
573
+ return str;
574
+ }
575
+ styleOptionTerm(str) {
576
+ return this.styleOptionText(str);
577
+ }
578
+ styleSubcommandTerm(str) {
579
+ return str.split(" ").map((word) => {
580
+ if (word === "[options]") return this.styleOptionText(word);
581
+ if (word[0] === "[" || word[0] === "<") return this.styleArgumentText(word);
582
+ return this.styleSubcommandText(word);
583
+ }).join(" ");
584
+ }
585
+ styleArgumentTerm(str) {
586
+ return this.styleArgumentText(str);
587
+ }
588
+ styleOptionText(str) {
589
+ return str;
590
+ }
591
+ styleArgumentText(str) {
592
+ return str;
593
+ }
594
+ styleSubcommandText(str) {
595
+ return str;
596
+ }
597
+ styleCommandText(str) {
598
+ return str;
599
+ }
600
+ /**
601
+ * Calculate the pad width from the maximum term length.
602
+ *
603
+ * @param {Command} cmd
604
+ * @param {Help} helper
605
+ * @returns {number}
606
+ */
607
+ padWidth(cmd, helper) {
608
+ return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
609
+ }
610
+ /**
611
+ * Detect manually wrapped and indented strings by checking for line break followed by whitespace.
612
+ *
613
+ * @param {string} str
614
+ * @returns {boolean}
615
+ */
616
+ preformatted(str) {
617
+ return /\n[^\S\r\n]/.test(str);
618
+ }
619
+ /**
620
+ * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
621
+ *
622
+ * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
623
+ * TTT DDD DDDD
624
+ * DD DDD
625
+ *
626
+ * @param {string} term
627
+ * @param {number} termWidth
628
+ * @param {string} description
629
+ * @param {Help} helper
630
+ * @returns {string}
631
+ */
632
+ formatItem(term, termWidth, description, helper) {
633
+ const itemIndent = 2;
634
+ const itemIndentStr = " ".repeat(itemIndent);
635
+ if (!description) return itemIndentStr + term;
636
+ const paddedTerm = term.padEnd(termWidth + term.length - helper.displayWidth(term));
637
+ const spacerWidth = 2;
638
+ const remainingWidth = (this.helpWidth ?? 80) - termWidth - spacerWidth - itemIndent;
639
+ let formattedDescription;
640
+ if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) formattedDescription = description;
641
+ else formattedDescription = helper.boxWrap(description, remainingWidth).replace(/\n/g, "\n" + " ".repeat(termWidth + spacerWidth));
642
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `\n${itemIndentStr}`);
643
+ }
644
+ /**
645
+ * Wrap a string at whitespace, preserving existing line breaks.
646
+ * Wrapping is skipped if the width is less than `minWidthToWrap`.
647
+ *
648
+ * @param {string} str
649
+ * @param {number} width
650
+ * @returns {string}
651
+ */
652
+ boxWrap(str, width) {
653
+ if (width < this.minWidthToWrap) return str;
654
+ const rawLines = str.split(/\r\n|\n/);
655
+ const chunkPattern = /[\s]*[^\s]+/g;
656
+ const wrappedLines = [];
657
+ rawLines.forEach((line) => {
658
+ const chunks = line.match(chunkPattern);
659
+ if (chunks === null) {
660
+ wrappedLines.push("");
661
+ return;
662
+ }
663
+ let sumChunks = [chunks.shift()];
664
+ let sumWidth = this.displayWidth(sumChunks[0]);
665
+ chunks.forEach((chunk) => {
666
+ const visibleWidth = this.displayWidth(chunk);
667
+ if (sumWidth + visibleWidth <= width) {
668
+ sumChunks.push(chunk);
669
+ sumWidth += visibleWidth;
670
+ return;
671
+ }
672
+ wrappedLines.push(sumChunks.join(""));
673
+ const nextChunk = chunk.trimStart();
674
+ sumChunks = [nextChunk];
675
+ sumWidth = this.displayWidth(nextChunk);
676
+ });
677
+ wrappedLines.push(sumChunks.join(""));
678
+ });
679
+ return wrappedLines.join("\n");
680
+ }
681
+ };
682
+ /**
683
+ * Strip style ANSI escape sequences from the string. In particular, SGR (Select Graphic Rendition) codes.
684
+ *
685
+ * @param {string} str
686
+ * @returns {string}
687
+ * @package
688
+ */
689
+ function stripColor$1(str) {
690
+ return str.replace(/\x1b\[\d*(;\d*)*m/g, "");
691
+ }
692
+ exports.Help = Help$3;
693
+ exports.stripColor = stripColor$1;
694
+ }));
695
+
696
+ //#endregion
697
+ //#region node_modules/.pnpm/commander@14.0.2/node_modules/commander/lib/option.js
698
+ var require_option = /* @__PURE__ */ __commonJSMin(((exports) => {
699
+ const { InvalidArgumentError: InvalidArgumentError$2 } = require_error();
700
+ var Option$3 = class {
701
+ /**
702
+ * Initialize a new `Option` with the given `flags` and `description`.
703
+ *
704
+ * @param {string} flags
705
+ * @param {string} [description]
706
+ */
707
+ constructor(flags, description) {
708
+ this.flags = flags;
709
+ this.description = description || "";
710
+ this.required = flags.includes("<");
711
+ this.optional = flags.includes("[");
712
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
713
+ this.mandatory = false;
714
+ const optionFlags = splitOptionFlags(flags);
715
+ this.short = optionFlags.shortFlag;
716
+ this.long = optionFlags.longFlag;
717
+ this.negate = false;
718
+ if (this.long) this.negate = this.long.startsWith("--no-");
719
+ this.defaultValue = void 0;
720
+ this.defaultValueDescription = void 0;
721
+ this.presetArg = void 0;
722
+ this.envVar = void 0;
723
+ this.parseArg = void 0;
724
+ this.hidden = false;
725
+ this.argChoices = void 0;
726
+ this.conflictsWith = [];
727
+ this.implied = void 0;
728
+ this.helpGroupHeading = void 0;
729
+ }
730
+ /**
731
+ * Set the default value, and optionally supply the description to be displayed in the help.
732
+ *
733
+ * @param {*} value
734
+ * @param {string} [description]
735
+ * @return {Option}
736
+ */
737
+ default(value, description) {
738
+ this.defaultValue = value;
739
+ this.defaultValueDescription = description;
740
+ return this;
741
+ }
742
+ /**
743
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
744
+ * The custom processing (parseArg) is called.
745
+ *
746
+ * @example
747
+ * new Option('--color').default('GREYSCALE').preset('RGB');
748
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
749
+ *
750
+ * @param {*} arg
751
+ * @return {Option}
752
+ */
753
+ preset(arg) {
754
+ this.presetArg = arg;
755
+ return this;
756
+ }
757
+ /**
758
+ * Add option name(s) that conflict with this option.
759
+ * An error will be displayed if conflicting options are found during parsing.
760
+ *
761
+ * @example
762
+ * new Option('--rgb').conflicts('cmyk');
763
+ * new Option('--js').conflicts(['ts', 'jsx']);
764
+ *
765
+ * @param {(string | string[])} names
766
+ * @return {Option}
767
+ */
768
+ conflicts(names) {
769
+ this.conflictsWith = this.conflictsWith.concat(names);
770
+ return this;
771
+ }
772
+ /**
773
+ * Specify implied option values for when this option is set and the implied options are not.
774
+ *
775
+ * The custom processing (parseArg) is not called on the implied values.
776
+ *
777
+ * @example
778
+ * program
779
+ * .addOption(new Option('--log', 'write logging information to file'))
780
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
781
+ *
782
+ * @param {object} impliedOptionValues
783
+ * @return {Option}
784
+ */
785
+ implies(impliedOptionValues) {
786
+ let newImplied = impliedOptionValues;
787
+ if (typeof impliedOptionValues === "string") newImplied = { [impliedOptionValues]: true };
788
+ this.implied = Object.assign(this.implied || {}, newImplied);
789
+ return this;
790
+ }
791
+ /**
792
+ * Set environment variable to check for option value.
793
+ *
794
+ * An environment variable is only used if when processed the current option value is
795
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
796
+ *
797
+ * @param {string} name
798
+ * @return {Option}
799
+ */
800
+ env(name) {
801
+ this.envVar = name;
802
+ return this;
803
+ }
804
+ /**
805
+ * Set the custom handler for processing CLI option arguments into option values.
806
+ *
807
+ * @param {Function} [fn]
808
+ * @return {Option}
809
+ */
810
+ argParser(fn) {
811
+ this.parseArg = fn;
812
+ return this;
813
+ }
814
+ /**
815
+ * Whether the option is mandatory and must have a value after parsing.
816
+ *
817
+ * @param {boolean} [mandatory=true]
818
+ * @return {Option}
819
+ */
820
+ makeOptionMandatory(mandatory = true) {
821
+ this.mandatory = !!mandatory;
822
+ return this;
823
+ }
824
+ /**
825
+ * Hide option in help.
826
+ *
827
+ * @param {boolean} [hide=true]
828
+ * @return {Option}
829
+ */
830
+ hideHelp(hide = true) {
831
+ this.hidden = !!hide;
832
+ return this;
833
+ }
834
+ /**
835
+ * @package
836
+ */
837
+ _collectValue(value, previous) {
838
+ if (previous === this.defaultValue || !Array.isArray(previous)) return [value];
839
+ previous.push(value);
840
+ return previous;
841
+ }
842
+ /**
843
+ * Only allow option value to be one of choices.
844
+ *
845
+ * @param {string[]} values
846
+ * @return {Option}
847
+ */
848
+ choices(values) {
849
+ this.argChoices = values.slice();
850
+ this.parseArg = (arg, previous) => {
851
+ if (!this.argChoices.includes(arg)) throw new InvalidArgumentError$2(`Allowed choices are ${this.argChoices.join(", ")}.`);
852
+ if (this.variadic) return this._collectValue(arg, previous);
853
+ return arg;
854
+ };
855
+ return this;
856
+ }
857
+ /**
858
+ * Return option name.
859
+ *
860
+ * @return {string}
861
+ */
862
+ name() {
863
+ if (this.long) return this.long.replace(/^--/, "");
864
+ return this.short.replace(/^-/, "");
865
+ }
866
+ /**
867
+ * Return option name, in a camelcase format that can be used
868
+ * as an object attribute key.
869
+ *
870
+ * @return {string}
871
+ */
872
+ attributeName() {
873
+ if (this.negate) return camelcase(this.name().replace(/^no-/, ""));
874
+ return camelcase(this.name());
875
+ }
876
+ /**
877
+ * Set the help group heading.
878
+ *
879
+ * @param {string} heading
880
+ * @return {Option}
881
+ */
882
+ helpGroup(heading) {
883
+ this.helpGroupHeading = heading;
884
+ return this;
885
+ }
886
+ /**
887
+ * Check if `arg` matches the short or long flag.
888
+ *
889
+ * @param {string} arg
890
+ * @return {boolean}
891
+ * @package
892
+ */
893
+ is(arg) {
894
+ return this.short === arg || this.long === arg;
895
+ }
896
+ /**
897
+ * Return whether a boolean option.
898
+ *
899
+ * Options are one of boolean, negated, required argument, or optional argument.
900
+ *
901
+ * @return {boolean}
902
+ * @package
903
+ */
904
+ isBoolean() {
905
+ return !this.required && !this.optional && !this.negate;
906
+ }
907
+ };
908
+ /**
909
+ * This class is to make it easier to work with dual options, without changing the existing
910
+ * implementation. We support separate dual options for separate positive and negative options,
911
+ * like `--build` and `--no-build`, which share a single option value. This works nicely for some
912
+ * use cases, but is tricky for others where we want separate behaviours despite
913
+ * the single shared option value.
914
+ */
915
+ var DualOptions$1 = class {
916
+ /**
917
+ * @param {Option[]} options
918
+ */
919
+ constructor(options$1) {
920
+ this.positiveOptions = /* @__PURE__ */ new Map();
921
+ this.negativeOptions = /* @__PURE__ */ new Map();
922
+ this.dualOptions = /* @__PURE__ */ new Set();
923
+ options$1.forEach((option) => {
924
+ if (option.negate) this.negativeOptions.set(option.attributeName(), option);
925
+ else this.positiveOptions.set(option.attributeName(), option);
926
+ });
927
+ this.negativeOptions.forEach((value, key) => {
928
+ if (this.positiveOptions.has(key)) this.dualOptions.add(key);
929
+ });
930
+ }
931
+ /**
932
+ * Did the value come from the option, and not from possible matching dual option?
933
+ *
934
+ * @param {*} value
935
+ * @param {Option} option
936
+ * @returns {boolean}
937
+ */
938
+ valueFromOption(value, option) {
939
+ const optionKey = option.attributeName();
940
+ if (!this.dualOptions.has(optionKey)) return true;
941
+ const preset = this.negativeOptions.get(optionKey).presetArg;
942
+ const negativeValue = preset !== void 0 ? preset : false;
943
+ return option.negate === (negativeValue === value);
944
+ }
945
+ };
946
+ /**
947
+ * Convert string from kebab-case to camelCase.
948
+ *
949
+ * @param {string} str
950
+ * @return {string}
951
+ * @private
952
+ */
953
+ function camelcase(str) {
954
+ return str.split("-").reduce((str$1, word) => {
955
+ return str$1 + word[0].toUpperCase() + word.slice(1);
956
+ });
957
+ }
958
+ /**
959
+ * Split the short and long flag out of something like '-m,--mixed <value>'
960
+ *
961
+ * @private
962
+ */
963
+ function splitOptionFlags(flags) {
964
+ let shortFlag;
965
+ let longFlag;
966
+ const shortFlagExp = /^-[^-]$/;
967
+ const longFlagExp = /^--[^-]/;
968
+ const flagParts = flags.split(/[ |,]+/).concat("guard");
969
+ if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
970
+ if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
971
+ if (!shortFlag && shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
972
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
973
+ shortFlag = longFlag;
974
+ longFlag = flagParts.shift();
975
+ }
976
+ if (flagParts[0].startsWith("-")) {
977
+ const unsupportedFlag = flagParts[0];
978
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
979
+ if (/^-[^-][^-]/.test(unsupportedFlag)) throw new Error(`${baseError}
980
+ - a short flag is a single dash and a single character
981
+ - either use a single dash and a single character (for a short flag)
982
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);
983
+ if (shortFlagExp.test(unsupportedFlag)) throw new Error(`${baseError}
984
+ - too many short flags`);
985
+ if (longFlagExp.test(unsupportedFlag)) throw new Error(`${baseError}
986
+ - too many long flags`);
987
+ throw new Error(`${baseError}
988
+ - unrecognised flag format`);
989
+ }
990
+ if (shortFlag === void 0 && longFlag === void 0) throw new Error(`option creation failed due to no flags found in '${flags}'.`);
991
+ return {
992
+ shortFlag,
993
+ longFlag
994
+ };
995
+ }
996
+ exports.Option = Option$3;
997
+ exports.DualOptions = DualOptions$1;
998
+ }));
999
+
1000
+ //#endregion
1001
+ //#region node_modules/.pnpm/commander@14.0.2/node_modules/commander/lib/suggestSimilar.js
1002
+ var require_suggestSimilar = /* @__PURE__ */ __commonJSMin(((exports) => {
1003
+ const maxDistance = 3;
1004
+ function editDistance(a$1, b$1) {
1005
+ if (Math.abs(a$1.length - b$1.length) > maxDistance) return Math.max(a$1.length, b$1.length);
1006
+ const d = [];
1007
+ for (let i$1 = 0; i$1 <= a$1.length; i$1++) d[i$1] = [i$1];
1008
+ for (let j = 0; j <= b$1.length; j++) d[0][j] = j;
1009
+ for (let j = 1; j <= b$1.length; j++) for (let i$1 = 1; i$1 <= a$1.length; i$1++) {
1010
+ let cost = 1;
1011
+ if (a$1[i$1 - 1] === b$1[j - 1]) cost = 0;
1012
+ else cost = 1;
1013
+ d[i$1][j] = Math.min(d[i$1 - 1][j] + 1, d[i$1][j - 1] + 1, d[i$1 - 1][j - 1] + cost);
1014
+ if (i$1 > 1 && j > 1 && a$1[i$1 - 1] === b$1[j - 2] && a$1[i$1 - 2] === b$1[j - 1]) d[i$1][j] = Math.min(d[i$1][j], d[i$1 - 2][j - 2] + 1);
1015
+ }
1016
+ return d[a$1.length][b$1.length];
1017
+ }
1018
+ /**
1019
+ * Find close matches, restricted to same number of edits.
1020
+ *
1021
+ * @param {string} word
1022
+ * @param {string[]} candidates
1023
+ * @returns {string}
1024
+ */
1025
+ function suggestSimilar$1(word, candidates) {
1026
+ if (!candidates || candidates.length === 0) return "";
1027
+ candidates = Array.from(new Set(candidates));
1028
+ const searchingOptions = word.startsWith("--");
1029
+ if (searchingOptions) {
1030
+ word = word.slice(2);
1031
+ candidates = candidates.map((candidate) => candidate.slice(2));
1032
+ }
1033
+ let similar = [];
1034
+ let bestDistance = maxDistance;
1035
+ const minSimilarity = .4;
1036
+ candidates.forEach((candidate) => {
1037
+ if (candidate.length <= 1) return;
1038
+ const distance = editDistance(word, candidate);
1039
+ const length = Math.max(word.length, candidate.length);
1040
+ if ((length - distance) / length > minSimilarity) {
1041
+ if (distance < bestDistance) {
1042
+ bestDistance = distance;
1043
+ similar = [candidate];
1044
+ } else if (distance === bestDistance) similar.push(candidate);
1045
+ }
1046
+ });
1047
+ similar.sort((a$1, b$1) => a$1.localeCompare(b$1));
1048
+ if (searchingOptions) similar = similar.map((candidate) => `--${candidate}`);
1049
+ if (similar.length > 1) return `\n(Did you mean one of ${similar.join(", ")}?)`;
1050
+ if (similar.length === 1) return `\n(Did you mean ${similar[0]}?)`;
1051
+ return "";
1052
+ }
1053
+ exports.suggestSimilar = suggestSimilar$1;
1054
+ }));
1055
+
1056
+ //#endregion
1057
+ //#region node_modules/.pnpm/commander@14.0.2/node_modules/commander/lib/command.js
1058
+ var require_command = /* @__PURE__ */ __commonJSMin(((exports) => {
1059
+ const EventEmitter = __require("node:events").EventEmitter;
1060
+ const childProcess = __require("node:child_process");
1061
+ const path$1 = __require("node:path");
1062
+ const fs$1 = __require("node:fs");
1063
+ const process$1 = __require("node:process");
1064
+ const { Argument: Argument$2, humanReadableArgName } = require_argument();
1065
+ const { CommanderError: CommanderError$2 } = require_error();
1066
+ const { Help: Help$2, stripColor } = require_help();
1067
+ const { Option: Option$2, DualOptions } = require_option();
1068
+ const { suggestSimilar } = require_suggestSimilar();
1069
+ var Command$2 = class Command$2 extends EventEmitter {
1070
+ /**
1071
+ * Initialize a new `Command`.
1072
+ *
1073
+ * @param {string} [name]
1074
+ */
1075
+ constructor(name) {
1076
+ super();
1077
+ /** @type {Command[]} */
1078
+ this.commands = [];
1079
+ /** @type {Option[]} */
1080
+ this.options = [];
1081
+ this.parent = null;
1082
+ this._allowUnknownOption = false;
1083
+ this._allowExcessArguments = false;
1084
+ /** @type {Argument[]} */
1085
+ this.registeredArguments = [];
1086
+ this._args = this.registeredArguments;
1087
+ /** @type {string[]} */
1088
+ this.args = [];
1089
+ this.rawArgs = [];
1090
+ this.processedArgs = [];
1091
+ this._scriptPath = null;
1092
+ this._name = name || "";
1093
+ this._optionValues = {};
1094
+ this._optionValueSources = {};
1095
+ this._storeOptionsAsProperties = false;
1096
+ this._actionHandler = null;
1097
+ this._executableHandler = false;
1098
+ this._executableFile = null;
1099
+ this._executableDir = null;
1100
+ this._defaultCommandName = null;
1101
+ this._exitCallback = null;
1102
+ this._aliases = [];
1103
+ this._combineFlagAndOptionalValue = true;
1104
+ this._description = "";
1105
+ this._summary = "";
1106
+ this._argsDescription = void 0;
1107
+ this._enablePositionalOptions = false;
1108
+ this._passThroughOptions = false;
1109
+ this._lifeCycleHooks = {};
1110
+ /** @type {(boolean | string)} */
1111
+ this._showHelpAfterError = false;
1112
+ this._showSuggestionAfterError = true;
1113
+ this._savedState = null;
1114
+ this._outputConfiguration = {
1115
+ writeOut: (str) => process$1.stdout.write(str),
1116
+ writeErr: (str) => process$1.stderr.write(str),
1117
+ outputError: (str, write) => write(str),
1118
+ getOutHelpWidth: () => process$1.stdout.isTTY ? process$1.stdout.columns : void 0,
1119
+ getErrHelpWidth: () => process$1.stderr.isTTY ? process$1.stderr.columns : void 0,
1120
+ getOutHasColors: () => useColor() ?? (process$1.stdout.isTTY && process$1.stdout.hasColors?.()),
1121
+ getErrHasColors: () => useColor() ?? (process$1.stderr.isTTY && process$1.stderr.hasColors?.()),
1122
+ stripColor: (str) => stripColor(str)
1123
+ };
1124
+ this._hidden = false;
1125
+ /** @type {(Option | null | undefined)} */
1126
+ this._helpOption = void 0;
1127
+ this._addImplicitHelpCommand = void 0;
1128
+ /** @type {Command} */
1129
+ this._helpCommand = void 0;
1130
+ this._helpConfiguration = {};
1131
+ /** @type {string | undefined} */
1132
+ this._helpGroupHeading = void 0;
1133
+ /** @type {string | undefined} */
1134
+ this._defaultCommandGroup = void 0;
1135
+ /** @type {string | undefined} */
1136
+ this._defaultOptionGroup = void 0;
1137
+ }
1138
+ /**
1139
+ * Copy settings that are useful to have in common across root command and subcommands.
1140
+ *
1141
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1142
+ *
1143
+ * @param {Command} sourceCommand
1144
+ * @return {Command} `this` command for chaining
1145
+ */
1146
+ copyInheritedSettings(sourceCommand) {
1147
+ this._outputConfiguration = sourceCommand._outputConfiguration;
1148
+ this._helpOption = sourceCommand._helpOption;
1149
+ this._helpCommand = sourceCommand._helpCommand;
1150
+ this._helpConfiguration = sourceCommand._helpConfiguration;
1151
+ this._exitCallback = sourceCommand._exitCallback;
1152
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1153
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1154
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
1155
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1156
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
1157
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1158
+ return this;
1159
+ }
1160
+ /**
1161
+ * @returns {Command[]}
1162
+ * @private
1163
+ */
1164
+ _getCommandAndAncestors() {
1165
+ const result = [];
1166
+ for (let command = this; command; command = command.parent) result.push(command);
1167
+ return result;
1168
+ }
1169
+ /**
1170
+ * Define a command.
1171
+ *
1172
+ * There are two styles of command: pay attention to where to put the description.
1173
+ *
1174
+ * @example
1175
+ * // Command implemented using action handler (description is supplied separately to `.command`)
1176
+ * program
1177
+ * .command('clone <source> [destination]')
1178
+ * .description('clone a repository into a newly created directory')
1179
+ * .action((source, destination) => {
1180
+ * console.log('clone command called');
1181
+ * });
1182
+ *
1183
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
1184
+ * program
1185
+ * .command('start <service>', 'start named service')
1186
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
1187
+ *
1188
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1189
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1190
+ * @param {object} [execOpts] - configuration options (for executable)
1191
+ * @return {Command} returns new command for action handler, or `this` for executable command
1192
+ */
1193
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1194
+ let desc = actionOptsOrExecDesc;
1195
+ let opts = execOpts;
1196
+ if (typeof desc === "object" && desc !== null) {
1197
+ opts = desc;
1198
+ desc = null;
1199
+ }
1200
+ opts = opts || {};
1201
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1202
+ const cmd = this.createCommand(name);
1203
+ if (desc) {
1204
+ cmd.description(desc);
1205
+ cmd._executableHandler = true;
1206
+ }
1207
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1208
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
1209
+ cmd._executableFile = opts.executableFile || null;
1210
+ if (args) cmd.arguments(args);
1211
+ this._registerCommand(cmd);
1212
+ cmd.parent = this;
1213
+ cmd.copyInheritedSettings(this);
1214
+ if (desc) return this;
1215
+ return cmd;
1216
+ }
1217
+ /**
1218
+ * Factory routine to create a new unattached command.
1219
+ *
1220
+ * See .command() for creating an attached subcommand, which uses this routine to
1221
+ * create the command. You can override createCommand to customise subcommands.
1222
+ *
1223
+ * @param {string} [name]
1224
+ * @return {Command} new command
1225
+ */
1226
+ createCommand(name) {
1227
+ return new Command$2(name);
1228
+ }
1229
+ /**
1230
+ * You can customise the help with a subclass of Help by overriding createHelp,
1231
+ * or by overriding Help properties using configureHelp().
1232
+ *
1233
+ * @return {Help}
1234
+ */
1235
+ createHelp() {
1236
+ return Object.assign(new Help$2(), this.configureHelp());
1237
+ }
1238
+ /**
1239
+ * You can customise the help by overriding Help properties using configureHelp(),
1240
+ * or with a subclass of Help by overriding createHelp().
1241
+ *
1242
+ * @param {object} [configuration] - configuration options
1243
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1244
+ */
1245
+ configureHelp(configuration) {
1246
+ if (configuration === void 0) return this._helpConfiguration;
1247
+ this._helpConfiguration = configuration;
1248
+ return this;
1249
+ }
1250
+ /**
1251
+ * The default output goes to stdout and stderr. You can customise this for special
1252
+ * applications. You can also customise the display of errors by overriding outputError.
1253
+ *
1254
+ * The configuration properties are all functions:
1255
+ *
1256
+ * // change how output being written, defaults to stdout and stderr
1257
+ * writeOut(str)
1258
+ * writeErr(str)
1259
+ * // change how output being written for errors, defaults to writeErr
1260
+ * outputError(str, write) // used for displaying errors and not used for displaying help
1261
+ * // specify width for wrapping help
1262
+ * getOutHelpWidth()
1263
+ * getErrHelpWidth()
1264
+ * // color support, currently only used with Help
1265
+ * getOutHasColors()
1266
+ * getErrHasColors()
1267
+ * stripColor() // used to remove ANSI escape codes if output does not have colors
1268
+ *
1269
+ * @param {object} [configuration] - configuration options
1270
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1271
+ */
1272
+ configureOutput(configuration) {
1273
+ if (configuration === void 0) return this._outputConfiguration;
1274
+ this._outputConfiguration = {
1275
+ ...this._outputConfiguration,
1276
+ ...configuration
1277
+ };
1278
+ return this;
1279
+ }
1280
+ /**
1281
+ * Display the help or a custom message after an error occurs.
1282
+ *
1283
+ * @param {(boolean|string)} [displayHelp]
1284
+ * @return {Command} `this` command for chaining
1285
+ */
1286
+ showHelpAfterError(displayHelp = true) {
1287
+ if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
1288
+ this._showHelpAfterError = displayHelp;
1289
+ return this;
1290
+ }
1291
+ /**
1292
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
1293
+ *
1294
+ * @param {boolean} [displaySuggestion]
1295
+ * @return {Command} `this` command for chaining
1296
+ */
1297
+ showSuggestionAfterError(displaySuggestion = true) {
1298
+ this._showSuggestionAfterError = !!displaySuggestion;
1299
+ return this;
1300
+ }
1301
+ /**
1302
+ * Add a prepared subcommand.
1303
+ *
1304
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
1305
+ *
1306
+ * @param {Command} cmd - new subcommand
1307
+ * @param {object} [opts] - configuration options
1308
+ * @return {Command} `this` command for chaining
1309
+ */
1310
+ addCommand(cmd, opts) {
1311
+ if (!cmd._name) throw new Error(`Command passed to .addCommand() must have a name
1312
+ - specify the name in Command constructor or using .name()`);
1313
+ opts = opts || {};
1314
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1315
+ if (opts.noHelp || opts.hidden) cmd._hidden = true;
1316
+ this._registerCommand(cmd);
1317
+ cmd.parent = this;
1318
+ cmd._checkForBrokenPassThrough();
1319
+ return this;
1320
+ }
1321
+ /**
1322
+ * Factory routine to create a new unattached argument.
1323
+ *
1324
+ * See .argument() for creating an attached argument, which uses this routine to
1325
+ * create the argument. You can override createArgument to return a custom argument.
1326
+ *
1327
+ * @param {string} name
1328
+ * @param {string} [description]
1329
+ * @return {Argument} new argument
1330
+ */
1331
+ createArgument(name, description) {
1332
+ return new Argument$2(name, description);
1333
+ }
1334
+ /**
1335
+ * Define argument syntax for command.
1336
+ *
1337
+ * The default is that the argument is required, and you can explicitly
1338
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
1339
+ *
1340
+ * @example
1341
+ * program.argument('<input-file>');
1342
+ * program.argument('[output-file]');
1343
+ *
1344
+ * @param {string} name
1345
+ * @param {string} [description]
1346
+ * @param {(Function|*)} [parseArg] - custom argument processing function or default value
1347
+ * @param {*} [defaultValue]
1348
+ * @return {Command} `this` command for chaining
1349
+ */
1350
+ argument(name, description, parseArg, defaultValue) {
1351
+ const argument = this.createArgument(name, description);
1352
+ if (typeof parseArg === "function") argument.default(defaultValue).argParser(parseArg);
1353
+ else argument.default(parseArg);
1354
+ this.addArgument(argument);
1355
+ return this;
1356
+ }
1357
+ /**
1358
+ * Define argument syntax for command, adding multiple at once (without descriptions).
1359
+ *
1360
+ * See also .argument().
1361
+ *
1362
+ * @example
1363
+ * program.arguments('<cmd> [env]');
1364
+ *
1365
+ * @param {string} names
1366
+ * @return {Command} `this` command for chaining
1367
+ */
1368
+ arguments(names) {
1369
+ names.trim().split(/ +/).forEach((detail) => {
1370
+ this.argument(detail);
1371
+ });
1372
+ return this;
1373
+ }
1374
+ /**
1375
+ * Define argument syntax for command, adding a prepared argument.
1376
+ *
1377
+ * @param {Argument} argument
1378
+ * @return {Command} `this` command for chaining
1379
+ */
1380
+ addArgument(argument) {
1381
+ const previousArgument = this.registeredArguments.slice(-1)[0];
1382
+ if (previousArgument?.variadic) throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
1383
+ 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()}'`);
1384
+ this.registeredArguments.push(argument);
1385
+ return this;
1386
+ }
1387
+ /**
1388
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
1389
+ *
1390
+ * @example
1391
+ * program.helpCommand('help [cmd]');
1392
+ * program.helpCommand('help [cmd]', 'show help');
1393
+ * program.helpCommand(false); // suppress default help command
1394
+ * program.helpCommand(true); // add help command even if no subcommands
1395
+ *
1396
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
1397
+ * @param {string} [description] - custom description
1398
+ * @return {Command} `this` command for chaining
1399
+ */
1400
+ helpCommand(enableOrNameAndArgs, description) {
1401
+ if (typeof enableOrNameAndArgs === "boolean") {
1402
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
1403
+ if (enableOrNameAndArgs && this._defaultCommandGroup) this._initCommandGroup(this._getHelpCommand());
1404
+ return this;
1405
+ }
1406
+ const [, helpName, helpArgs] = (enableOrNameAndArgs ?? "help [command]").match(/([^ ]+) *(.*)/);
1407
+ const helpDescription = description ?? "display help for command";
1408
+ const helpCommand = this.createCommand(helpName);
1409
+ helpCommand.helpOption(false);
1410
+ if (helpArgs) helpCommand.arguments(helpArgs);
1411
+ if (helpDescription) helpCommand.description(helpDescription);
1412
+ this._addImplicitHelpCommand = true;
1413
+ this._helpCommand = helpCommand;
1414
+ if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);
1415
+ return this;
1416
+ }
1417
+ /**
1418
+ * Add prepared custom help command.
1419
+ *
1420
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
1421
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
1422
+ * @return {Command} `this` command for chaining
1423
+ */
1424
+ addHelpCommand(helpCommand, deprecatedDescription) {
1425
+ if (typeof helpCommand !== "object") {
1426
+ this.helpCommand(helpCommand, deprecatedDescription);
1427
+ return this;
1428
+ }
1429
+ this._addImplicitHelpCommand = true;
1430
+ this._helpCommand = helpCommand;
1431
+ this._initCommandGroup(helpCommand);
1432
+ return this;
1433
+ }
1434
+ /**
1435
+ * Lazy create help command.
1436
+ *
1437
+ * @return {(Command|null)}
1438
+ * @package
1439
+ */
1440
+ _getHelpCommand() {
1441
+ if (this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"))) {
1442
+ if (this._helpCommand === void 0) this.helpCommand(void 0, void 0);
1443
+ return this._helpCommand;
1444
+ }
1445
+ return null;
1446
+ }
1447
+ /**
1448
+ * Add hook for life cycle event.
1449
+ *
1450
+ * @param {string} event
1451
+ * @param {Function} listener
1452
+ * @return {Command} `this` command for chaining
1453
+ */
1454
+ hook(event, listener) {
1455
+ const allowedValues = [
1456
+ "preSubcommand",
1457
+ "preAction",
1458
+ "postAction"
1459
+ ];
1460
+ if (!allowedValues.includes(event)) throw new Error(`Unexpected value for event passed to hook : '${event}'.
1461
+ Expecting one of '${allowedValues.join("', '")}'`);
1462
+ if (this._lifeCycleHooks[event]) this._lifeCycleHooks[event].push(listener);
1463
+ else this._lifeCycleHooks[event] = [listener];
1464
+ return this;
1465
+ }
1466
+ /**
1467
+ * Register callback to use as replacement for calling process.exit.
1468
+ *
1469
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
1470
+ * @return {Command} `this` command for chaining
1471
+ */
1472
+ exitOverride(fn) {
1473
+ if (fn) this._exitCallback = fn;
1474
+ else this._exitCallback = (err) => {
1475
+ if (err.code !== "commander.executeSubCommandAsync") throw err;
1476
+ };
1477
+ return this;
1478
+ }
1479
+ /**
1480
+ * Call process.exit, and _exitCallback if defined.
1481
+ *
1482
+ * @param {number} exitCode exit code for using with process.exit
1483
+ * @param {string} code an id string representing the error
1484
+ * @param {string} message human-readable description of the error
1485
+ * @return never
1486
+ * @private
1487
+ */
1488
+ _exit(exitCode, code, message) {
1489
+ if (this._exitCallback) this._exitCallback(new CommanderError$2(exitCode, code, message));
1490
+ process$1.exit(exitCode);
1491
+ }
1492
+ /**
1493
+ * Register callback `fn` for the command.
1494
+ *
1495
+ * @example
1496
+ * program
1497
+ * .command('serve')
1498
+ * .description('start service')
1499
+ * .action(function() {
1500
+ * // do work here
1501
+ * });
1502
+ *
1503
+ * @param {Function} fn
1504
+ * @return {Command} `this` command for chaining
1505
+ */
1506
+ action(fn) {
1507
+ const listener = (args) => {
1508
+ const expectedArgsCount = this.registeredArguments.length;
1509
+ const actionArgs = args.slice(0, expectedArgsCount);
1510
+ if (this._storeOptionsAsProperties) actionArgs[expectedArgsCount] = this;
1511
+ else actionArgs[expectedArgsCount] = this.opts();
1512
+ actionArgs.push(this);
1513
+ return fn.apply(this, actionArgs);
1514
+ };
1515
+ this._actionHandler = listener;
1516
+ return this;
1517
+ }
1518
+ /**
1519
+ * Factory routine to create a new unattached option.
1520
+ *
1521
+ * See .option() for creating an attached option, which uses this routine to
1522
+ * create the option. You can override createOption to return a custom option.
1523
+ *
1524
+ * @param {string} flags
1525
+ * @param {string} [description]
1526
+ * @return {Option} new option
1527
+ */
1528
+ createOption(flags, description) {
1529
+ return new Option$2(flags, description);
1530
+ }
1531
+ /**
1532
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
1533
+ *
1534
+ * @param {(Option | Argument)} target
1535
+ * @param {string} value
1536
+ * @param {*} previous
1537
+ * @param {string} invalidArgumentMessage
1538
+ * @private
1539
+ */
1540
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
1541
+ try {
1542
+ return target.parseArg(value, previous);
1543
+ } catch (err) {
1544
+ if (err.code === "commander.invalidArgument") {
1545
+ const message = `${invalidArgumentMessage} ${err.message}`;
1546
+ this.error(message, {
1547
+ exitCode: err.exitCode,
1548
+ code: err.code
1549
+ });
1550
+ }
1551
+ throw err;
1552
+ }
1553
+ }
1554
+ /**
1555
+ * Check for option flag conflicts.
1556
+ * Register option if no conflicts found, or throw on conflict.
1557
+ *
1558
+ * @param {Option} option
1559
+ * @private
1560
+ */
1561
+ _registerOption(option) {
1562
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1563
+ if (matchingOption) {
1564
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1565
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1566
+ - already used by option '${matchingOption.flags}'`);
1567
+ }
1568
+ this._initOptionGroup(option);
1569
+ this.options.push(option);
1570
+ }
1571
+ /**
1572
+ * Check for command name and alias conflicts with existing commands.
1573
+ * Register command if no conflicts found, or throw on conflict.
1574
+ *
1575
+ * @param {Command} command
1576
+ * @private
1577
+ */
1578
+ _registerCommand(command) {
1579
+ const knownBy = (cmd) => {
1580
+ return [cmd.name()].concat(cmd.aliases());
1581
+ };
1582
+ const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
1583
+ if (alreadyUsed) {
1584
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1585
+ const newCmd = knownBy(command).join("|");
1586
+ throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
1587
+ }
1588
+ this._initCommandGroup(command);
1589
+ this.commands.push(command);
1590
+ }
1591
+ /**
1592
+ * Add an option.
1593
+ *
1594
+ * @param {Option} option
1595
+ * @return {Command} `this` command for chaining
1596
+ */
1597
+ addOption(option) {
1598
+ this._registerOption(option);
1599
+ const oname = option.name();
1600
+ const name = option.attributeName();
1601
+ if (option.negate) {
1602
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1603
+ if (!this._findOption(positiveLongFlag)) this.setOptionValueWithSource(name, option.defaultValue === void 0 ? true : option.defaultValue, "default");
1604
+ } else if (option.defaultValue !== void 0) this.setOptionValueWithSource(name, option.defaultValue, "default");
1605
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1606
+ if (val == null && option.presetArg !== void 0) val = option.presetArg;
1607
+ const oldValue = this.getOptionValue(name);
1608
+ if (val !== null && option.parseArg) val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1609
+ else if (val !== null && option.variadic) val = option._collectValue(val, oldValue);
1610
+ if (val == null) if (option.negate) val = false;
1611
+ else if (option.isBoolean() || option.optional) val = true;
1612
+ else val = "";
1613
+ this.setOptionValueWithSource(name, val, valueSource);
1614
+ };
1615
+ this.on("option:" + oname, (val) => {
1616
+ handleOptionValue(val, `error: option '${option.flags}' argument '${val}' is invalid.`, "cli");
1617
+ });
1618
+ if (option.envVar) this.on("optionEnv:" + oname, (val) => {
1619
+ handleOptionValue(val, `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`, "env");
1620
+ });
1621
+ return this;
1622
+ }
1623
+ /**
1624
+ * Internal implementation shared by .option() and .requiredOption()
1625
+ *
1626
+ * @return {Command} `this` command for chaining
1627
+ * @private
1628
+ */
1629
+ _optionEx(config, flags, description, fn, defaultValue) {
1630
+ if (typeof flags === "object" && flags instanceof Option$2) throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
1631
+ const option = this.createOption(flags, description);
1632
+ option.makeOptionMandatory(!!config.mandatory);
1633
+ if (typeof fn === "function") option.default(defaultValue).argParser(fn);
1634
+ else if (fn instanceof RegExp) {
1635
+ const regex$1 = fn;
1636
+ fn = (val, def) => {
1637
+ const m = regex$1.exec(val);
1638
+ return m ? m[0] : def;
1639
+ };
1640
+ option.default(defaultValue).argParser(fn);
1641
+ } else option.default(fn);
1642
+ return this.addOption(option);
1643
+ }
1644
+ /**
1645
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
1646
+ *
1647
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
1648
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
1649
+ *
1650
+ * See the README for more details, and see also addOption() and requiredOption().
1651
+ *
1652
+ * @example
1653
+ * program
1654
+ * .option('-p, --pepper', 'add pepper')
1655
+ * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
1656
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
1657
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
1658
+ *
1659
+ * @param {string} flags
1660
+ * @param {string} [description]
1661
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1662
+ * @param {*} [defaultValue]
1663
+ * @return {Command} `this` command for chaining
1664
+ */
1665
+ option(flags, description, parseArg, defaultValue) {
1666
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1667
+ }
1668
+ /**
1669
+ * Add a required option which must have a value after parsing. This usually means
1670
+ * the option must be specified on the command line. (Otherwise the same as .option().)
1671
+ *
1672
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1673
+ *
1674
+ * @param {string} flags
1675
+ * @param {string} [description]
1676
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1677
+ * @param {*} [defaultValue]
1678
+ * @return {Command} `this` command for chaining
1679
+ */
1680
+ requiredOption(flags, description, parseArg, defaultValue) {
1681
+ return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
1682
+ }
1683
+ /**
1684
+ * Alter parsing of short flags with optional values.
1685
+ *
1686
+ * @example
1687
+ * // for `.option('-f,--flag [value]'):
1688
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
1689
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
1690
+ *
1691
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
1692
+ * @return {Command} `this` command for chaining
1693
+ */
1694
+ combineFlagAndOptionalValue(combine = true) {
1695
+ this._combineFlagAndOptionalValue = !!combine;
1696
+ return this;
1697
+ }
1698
+ /**
1699
+ * Allow unknown options on the command line.
1700
+ *
1701
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
1702
+ * @return {Command} `this` command for chaining
1703
+ */
1704
+ allowUnknownOption(allowUnknown = true) {
1705
+ this._allowUnknownOption = !!allowUnknown;
1706
+ return this;
1707
+ }
1708
+ /**
1709
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1710
+ *
1711
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
1712
+ * @return {Command} `this` command for chaining
1713
+ */
1714
+ allowExcessArguments(allowExcess = true) {
1715
+ this._allowExcessArguments = !!allowExcess;
1716
+ return this;
1717
+ }
1718
+ /**
1719
+ * Enable positional options. Positional means global options are specified before subcommands which lets
1720
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1721
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
1722
+ *
1723
+ * @param {boolean} [positional]
1724
+ * @return {Command} `this` command for chaining
1725
+ */
1726
+ enablePositionalOptions(positional = true) {
1727
+ this._enablePositionalOptions = !!positional;
1728
+ return this;
1729
+ }
1730
+ /**
1731
+ * Pass through options that come after command-arguments rather than treat them as command-options,
1732
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
1733
+ * positional options to have been enabled on the program (parent commands).
1734
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
1735
+ *
1736
+ * @param {boolean} [passThrough] for unknown options.
1737
+ * @return {Command} `this` command for chaining
1738
+ */
1739
+ passThroughOptions(passThrough = true) {
1740
+ this._passThroughOptions = !!passThrough;
1741
+ this._checkForBrokenPassThrough();
1742
+ return this;
1743
+ }
1744
+ /**
1745
+ * @private
1746
+ */
1747
+ _checkForBrokenPassThrough() {
1748
+ 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)`);
1749
+ }
1750
+ /**
1751
+ * Whether to store option values as properties on command object,
1752
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
1753
+ *
1754
+ * @param {boolean} [storeAsProperties=true]
1755
+ * @return {Command} `this` command for chaining
1756
+ */
1757
+ storeOptionsAsProperties(storeAsProperties = true) {
1758
+ if (this.options.length) throw new Error("call .storeOptionsAsProperties() before adding options");
1759
+ if (Object.keys(this._optionValues).length) throw new Error("call .storeOptionsAsProperties() before setting option values");
1760
+ this._storeOptionsAsProperties = !!storeAsProperties;
1761
+ return this;
1762
+ }
1763
+ /**
1764
+ * Retrieve option value.
1765
+ *
1766
+ * @param {string} key
1767
+ * @return {object} value
1768
+ */
1769
+ getOptionValue(key) {
1770
+ if (this._storeOptionsAsProperties) return this[key];
1771
+ return this._optionValues[key];
1772
+ }
1773
+ /**
1774
+ * Store option value.
1775
+ *
1776
+ * @param {string} key
1777
+ * @param {object} value
1778
+ * @return {Command} `this` command for chaining
1779
+ */
1780
+ setOptionValue(key, value) {
1781
+ return this.setOptionValueWithSource(key, value, void 0);
1782
+ }
1783
+ /**
1784
+ * Store option value and where the value came from.
1785
+ *
1786
+ * @param {string} key
1787
+ * @param {object} value
1788
+ * @param {string} source - expected values are default/config/env/cli/implied
1789
+ * @return {Command} `this` command for chaining
1790
+ */
1791
+ setOptionValueWithSource(key, value, source) {
1792
+ if (this._storeOptionsAsProperties) this[key] = value;
1793
+ else this._optionValues[key] = value;
1794
+ this._optionValueSources[key] = source;
1795
+ return this;
1796
+ }
1797
+ /**
1798
+ * Get source of option value.
1799
+ * Expected values are default | config | env | cli | implied
1800
+ *
1801
+ * @param {string} key
1802
+ * @return {string}
1803
+ */
1804
+ getOptionValueSource(key) {
1805
+ return this._optionValueSources[key];
1806
+ }
1807
+ /**
1808
+ * Get source of option value. See also .optsWithGlobals().
1809
+ * Expected values are default | config | env | cli | implied
1810
+ *
1811
+ * @param {string} key
1812
+ * @return {string}
1813
+ */
1814
+ getOptionValueSourceWithGlobals(key) {
1815
+ let source;
1816
+ this._getCommandAndAncestors().forEach((cmd) => {
1817
+ if (cmd.getOptionValueSource(key) !== void 0) source = cmd.getOptionValueSource(key);
1818
+ });
1819
+ return source;
1820
+ }
1821
+ /**
1822
+ * Get user arguments from implied or explicit arguments.
1823
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
1824
+ *
1825
+ * @private
1826
+ */
1827
+ _prepareUserArgs(argv$1, parseOptions) {
1828
+ if (argv$1 !== void 0 && !Array.isArray(argv$1)) throw new Error("first parameter to parse must be array or undefined");
1829
+ parseOptions = parseOptions || {};
1830
+ if (argv$1 === void 0 && parseOptions.from === void 0) {
1831
+ if (process$1.versions?.electron) parseOptions.from = "electron";
1832
+ const execArgv = process$1.execArgv ?? [];
1833
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) parseOptions.from = "eval";
1834
+ }
1835
+ if (argv$1 === void 0) argv$1 = process$1.argv;
1836
+ this.rawArgs = argv$1.slice();
1837
+ let userArgs;
1838
+ switch (parseOptions.from) {
1839
+ case void 0:
1840
+ case "node":
1841
+ this._scriptPath = argv$1[1];
1842
+ userArgs = argv$1.slice(2);
1843
+ break;
1844
+ case "electron":
1845
+ if (process$1.defaultApp) {
1846
+ this._scriptPath = argv$1[1];
1847
+ userArgs = argv$1.slice(2);
1848
+ } else userArgs = argv$1.slice(1);
1849
+ break;
1850
+ case "user":
1851
+ userArgs = argv$1.slice(0);
1852
+ break;
1853
+ case "eval":
1854
+ userArgs = argv$1.slice(1);
1855
+ break;
1856
+ default: throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
1857
+ }
1858
+ if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath);
1859
+ this._name = this._name || "program";
1860
+ return userArgs;
1861
+ }
1862
+ /**
1863
+ * Parse `argv`, setting options and invoking commands when defined.
1864
+ *
1865
+ * Use parseAsync instead of parse if any of your action handlers are async.
1866
+ *
1867
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1868
+ *
1869
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1870
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1871
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1872
+ * - `'user'`: just user arguments
1873
+ *
1874
+ * @example
1875
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
1876
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
1877
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1878
+ *
1879
+ * @param {string[]} [argv] - optional, defaults to process.argv
1880
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
1881
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
1882
+ * @return {Command} `this` command for chaining
1883
+ */
1884
+ parse(argv$1, parseOptions) {
1885
+ this._prepareForParse();
1886
+ const userArgs = this._prepareUserArgs(argv$1, parseOptions);
1887
+ this._parseCommand([], userArgs);
1888
+ return this;
1889
+ }
1890
+ /**
1891
+ * Parse `argv`, setting options and invoking commands when defined.
1892
+ *
1893
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1894
+ *
1895
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1896
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1897
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1898
+ * - `'user'`: just user arguments
1899
+ *
1900
+ * @example
1901
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
1902
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
1903
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1904
+ *
1905
+ * @param {string[]} [argv]
1906
+ * @param {object} [parseOptions]
1907
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
1908
+ * @return {Promise}
1909
+ */
1910
+ async parseAsync(argv$1, parseOptions) {
1911
+ this._prepareForParse();
1912
+ const userArgs = this._prepareUserArgs(argv$1, parseOptions);
1913
+ await this._parseCommand([], userArgs);
1914
+ return this;
1915
+ }
1916
+ _prepareForParse() {
1917
+ if (this._savedState === null) this.saveStateBeforeParse();
1918
+ else this.restoreStateBeforeParse();
1919
+ }
1920
+ /**
1921
+ * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
1922
+ * Not usually called directly, but available for subclasses to save their custom state.
1923
+ *
1924
+ * This is called in a lazy way. Only commands used in parsing chain will have state saved.
1925
+ */
1926
+ saveStateBeforeParse() {
1927
+ this._savedState = {
1928
+ _name: this._name,
1929
+ _optionValues: { ...this._optionValues },
1930
+ _optionValueSources: { ...this._optionValueSources }
1931
+ };
1932
+ }
1933
+ /**
1934
+ * Restore state before parse for calls after the first.
1935
+ * Not usually called directly, but available for subclasses to save their custom state.
1936
+ *
1937
+ * This is called in a lazy way. Only commands used in parsing chain will have state restored.
1938
+ */
1939
+ restoreStateBeforeParse() {
1940
+ if (this._storeOptionsAsProperties) throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
1941
+ - either make a new Command for each call to parse, or stop storing options as properties`);
1942
+ this._name = this._savedState._name;
1943
+ this._scriptPath = null;
1944
+ this.rawArgs = [];
1945
+ this._optionValues = { ...this._savedState._optionValues };
1946
+ this._optionValueSources = { ...this._savedState._optionValueSources };
1947
+ this.args = [];
1948
+ this.processedArgs = [];
1949
+ }
1950
+ /**
1951
+ * Throw if expected executable is missing. Add lots of help for author.
1952
+ *
1953
+ * @param {string} executableFile
1954
+ * @param {string} executableDir
1955
+ * @param {string} subcommandName
1956
+ */
1957
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
1958
+ if (fs$1.existsSync(executableFile)) return;
1959
+ const executableMissing = `'${executableFile}' does not exist
1960
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1961
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1962
+ - ${executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory"}`;
1963
+ throw new Error(executableMissing);
1964
+ }
1965
+ /**
1966
+ * Execute a sub-command executable.
1967
+ *
1968
+ * @private
1969
+ */
1970
+ _executeSubCommand(subcommand, args) {
1971
+ args = args.slice();
1972
+ let launchWithNode = false;
1973
+ const sourceExt = [
1974
+ ".js",
1975
+ ".ts",
1976
+ ".tsx",
1977
+ ".mjs",
1978
+ ".cjs"
1979
+ ];
1980
+ function findFile(baseDir, baseName) {
1981
+ const localBin = path$1.resolve(baseDir, baseName);
1982
+ if (fs$1.existsSync(localBin)) return localBin;
1983
+ if (sourceExt.includes(path$1.extname(baseName))) return void 0;
1984
+ const foundExt = sourceExt.find((ext) => fs$1.existsSync(`${localBin}${ext}`));
1985
+ if (foundExt) return `${localBin}${foundExt}`;
1986
+ }
1987
+ this._checkForMissingMandatoryOptions();
1988
+ this._checkForConflictingOptions();
1989
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1990
+ let executableDir = this._executableDir || "";
1991
+ if (this._scriptPath) {
1992
+ let resolvedScriptPath;
1993
+ try {
1994
+ resolvedScriptPath = fs$1.realpathSync(this._scriptPath);
1995
+ } catch {
1996
+ resolvedScriptPath = this._scriptPath;
1997
+ }
1998
+ executableDir = path$1.resolve(path$1.dirname(resolvedScriptPath), executableDir);
1999
+ }
2000
+ if (executableDir) {
2001
+ let localFile = findFile(executableDir, executableFile);
2002
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
2003
+ const legacyName = path$1.basename(this._scriptPath, path$1.extname(this._scriptPath));
2004
+ if (legacyName !== this._name) localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
2005
+ }
2006
+ executableFile = localFile || executableFile;
2007
+ }
2008
+ launchWithNode = sourceExt.includes(path$1.extname(executableFile));
2009
+ let proc;
2010
+ if (process$1.platform !== "win32") if (launchWithNode) {
2011
+ args.unshift(executableFile);
2012
+ args = incrementNodeInspectorPort(process$1.execArgv).concat(args);
2013
+ proc = childProcess.spawn(process$1.argv[0], args, { stdio: "inherit" });
2014
+ } else proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
2015
+ else {
2016
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
2017
+ args.unshift(executableFile);
2018
+ args = incrementNodeInspectorPort(process$1.execArgv).concat(args);
2019
+ proc = childProcess.spawn(process$1.execPath, args, { stdio: "inherit" });
2020
+ }
2021
+ if (!proc.killed) [
2022
+ "SIGUSR1",
2023
+ "SIGUSR2",
2024
+ "SIGTERM",
2025
+ "SIGINT",
2026
+ "SIGHUP"
2027
+ ].forEach((signal) => {
2028
+ process$1.on(signal, () => {
2029
+ if (proc.killed === false && proc.exitCode === null) proc.kill(signal);
2030
+ });
2031
+ });
2032
+ const exitCallback = this._exitCallback;
2033
+ proc.on("close", (code) => {
2034
+ code = code ?? 1;
2035
+ if (!exitCallback) process$1.exit(code);
2036
+ else exitCallback(new CommanderError$2(code, "commander.executeSubCommandAsync", "(close)"));
2037
+ });
2038
+ proc.on("error", (err) => {
2039
+ if (err.code === "ENOENT") this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
2040
+ else if (err.code === "EACCES") throw new Error(`'${executableFile}' not executable`);
2041
+ if (!exitCallback) process$1.exit(1);
2042
+ else {
2043
+ const wrappedError = new CommanderError$2(1, "commander.executeSubCommandAsync", "(error)");
2044
+ wrappedError.nestedError = err;
2045
+ exitCallback(wrappedError);
2046
+ }
2047
+ });
2048
+ this.runningCommand = proc;
2049
+ }
2050
+ /**
2051
+ * @private
2052
+ */
2053
+ _dispatchSubcommand(commandName, operands, unknown) {
2054
+ const subCommand = this._findCommand(commandName);
2055
+ if (!subCommand) this.help({ error: true });
2056
+ subCommand._prepareForParse();
2057
+ let promiseChain;
2058
+ promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
2059
+ promiseChain = this._chainOrCall(promiseChain, () => {
2060
+ if (subCommand._executableHandler) this._executeSubCommand(subCommand, operands.concat(unknown));
2061
+ else return subCommand._parseCommand(operands, unknown);
2062
+ });
2063
+ return promiseChain;
2064
+ }
2065
+ /**
2066
+ * Invoke help directly if possible, or dispatch if necessary.
2067
+ * e.g. help foo
2068
+ *
2069
+ * @private
2070
+ */
2071
+ _dispatchHelpCommand(subcommandName) {
2072
+ if (!subcommandName) this.help();
2073
+ const subCommand = this._findCommand(subcommandName);
2074
+ if (subCommand && !subCommand._executableHandler) subCommand.help();
2075
+ return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
2076
+ }
2077
+ /**
2078
+ * Check this.args against expected this.registeredArguments.
2079
+ *
2080
+ * @private
2081
+ */
2082
+ _checkNumberOfArguments() {
2083
+ this.registeredArguments.forEach((arg, i$1) => {
2084
+ if (arg.required && this.args[i$1] == null) this.missingArgument(arg.name());
2085
+ });
2086
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) return;
2087
+ if (this.args.length > this.registeredArguments.length) this._excessArguments(this.args);
2088
+ }
2089
+ /**
2090
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
2091
+ *
2092
+ * @private
2093
+ */
2094
+ _processArguments() {
2095
+ const myParseArg = (argument, value, previous) => {
2096
+ let parsedValue = value;
2097
+ if (value !== null && argument.parseArg) {
2098
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
2099
+ parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
2100
+ }
2101
+ return parsedValue;
2102
+ };
2103
+ this._checkNumberOfArguments();
2104
+ const processedArgs = [];
2105
+ this.registeredArguments.forEach((declaredArg, index) => {
2106
+ let value = declaredArg.defaultValue;
2107
+ if (declaredArg.variadic) {
2108
+ if (index < this.args.length) {
2109
+ value = this.args.slice(index);
2110
+ if (declaredArg.parseArg) value = value.reduce((processed, v) => {
2111
+ return myParseArg(declaredArg, v, processed);
2112
+ }, declaredArg.defaultValue);
2113
+ } else if (value === void 0) value = [];
2114
+ } else if (index < this.args.length) {
2115
+ value = this.args[index];
2116
+ if (declaredArg.parseArg) value = myParseArg(declaredArg, value, declaredArg.defaultValue);
2117
+ }
2118
+ processedArgs[index] = value;
2119
+ });
2120
+ this.processedArgs = processedArgs;
2121
+ }
2122
+ /**
2123
+ * Once we have a promise we chain, but call synchronously until then.
2124
+ *
2125
+ * @param {(Promise|undefined)} promise
2126
+ * @param {Function} fn
2127
+ * @return {(Promise|undefined)}
2128
+ * @private
2129
+ */
2130
+ _chainOrCall(promise, fn) {
2131
+ if (promise?.then && typeof promise.then === "function") return promise.then(() => fn());
2132
+ return fn();
2133
+ }
2134
+ /**
2135
+ *
2136
+ * @param {(Promise|undefined)} promise
2137
+ * @param {string} event
2138
+ * @return {(Promise|undefined)}
2139
+ * @private
2140
+ */
2141
+ _chainOrCallHooks(promise, event) {
2142
+ let result = promise;
2143
+ const hooks = [];
2144
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
2145
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
2146
+ hooks.push({
2147
+ hookedCommand,
2148
+ callback
2149
+ });
2150
+ });
2151
+ });
2152
+ if (event === "postAction") hooks.reverse();
2153
+ hooks.forEach((hookDetail) => {
2154
+ result = this._chainOrCall(result, () => {
2155
+ return hookDetail.callback(hookDetail.hookedCommand, this);
2156
+ });
2157
+ });
2158
+ return result;
2159
+ }
2160
+ /**
2161
+ *
2162
+ * @param {(Promise|undefined)} promise
2163
+ * @param {Command} subCommand
2164
+ * @param {string} event
2165
+ * @return {(Promise|undefined)}
2166
+ * @private
2167
+ */
2168
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
2169
+ let result = promise;
2170
+ if (this._lifeCycleHooks[event] !== void 0) this._lifeCycleHooks[event].forEach((hook) => {
2171
+ result = this._chainOrCall(result, () => {
2172
+ return hook(this, subCommand);
2173
+ });
2174
+ });
2175
+ return result;
2176
+ }
2177
+ /**
2178
+ * Process arguments in context of this command.
2179
+ * Returns action result, in case it is a promise.
2180
+ *
2181
+ * @private
2182
+ */
2183
+ _parseCommand(operands, unknown) {
2184
+ const parsed = this.parseOptions(unknown);
2185
+ this._parseOptionsEnv();
2186
+ this._parseOptionsImplied();
2187
+ operands = operands.concat(parsed.operands);
2188
+ unknown = parsed.unknown;
2189
+ this.args = operands.concat(unknown);
2190
+ if (operands && this._findCommand(operands[0])) return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2191
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) return this._dispatchHelpCommand(operands[1]);
2192
+ if (this._defaultCommandName) {
2193
+ this._outputHelpIfRequested(unknown);
2194
+ return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
2195
+ }
2196
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) this.help({ error: true });
2197
+ this._outputHelpIfRequested(parsed.unknown);
2198
+ this._checkForMissingMandatoryOptions();
2199
+ this._checkForConflictingOptions();
2200
+ const checkForUnknownOptions = () => {
2201
+ if (parsed.unknown.length > 0) this.unknownOption(parsed.unknown[0]);
2202
+ };
2203
+ const commandEvent = `command:${this.name()}`;
2204
+ if (this._actionHandler) {
2205
+ checkForUnknownOptions();
2206
+ this._processArguments();
2207
+ let promiseChain;
2208
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
2209
+ promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
2210
+ if (this.parent) promiseChain = this._chainOrCall(promiseChain, () => {
2211
+ this.parent.emit(commandEvent, operands, unknown);
2212
+ });
2213
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
2214
+ return promiseChain;
2215
+ }
2216
+ if (this.parent?.listenerCount(commandEvent)) {
2217
+ checkForUnknownOptions();
2218
+ this._processArguments();
2219
+ this.parent.emit(commandEvent, operands, unknown);
2220
+ } else if (operands.length) {
2221
+ if (this._findCommand("*")) return this._dispatchSubcommand("*", operands, unknown);
2222
+ if (this.listenerCount("command:*")) this.emit("command:*", operands, unknown);
2223
+ else if (this.commands.length) this.unknownCommand();
2224
+ else {
2225
+ checkForUnknownOptions();
2226
+ this._processArguments();
2227
+ }
2228
+ } else if (this.commands.length) {
2229
+ checkForUnknownOptions();
2230
+ this.help({ error: true });
2231
+ } else {
2232
+ checkForUnknownOptions();
2233
+ this._processArguments();
2234
+ }
2235
+ }
2236
+ /**
2237
+ * Find matching command.
2238
+ *
2239
+ * @private
2240
+ * @return {Command | undefined}
2241
+ */
2242
+ _findCommand(name) {
2243
+ if (!name) return void 0;
2244
+ return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
2245
+ }
2246
+ /**
2247
+ * Return an option matching `arg` if any.
2248
+ *
2249
+ * @param {string} arg
2250
+ * @return {Option}
2251
+ * @package
2252
+ */
2253
+ _findOption(arg) {
2254
+ return this.options.find((option) => option.is(arg));
2255
+ }
2256
+ /**
2257
+ * Display an error message if a mandatory option does not have a value.
2258
+ * Called after checking for help flags in leaf subcommand.
2259
+ *
2260
+ * @private
2261
+ */
2262
+ _checkForMissingMandatoryOptions() {
2263
+ this._getCommandAndAncestors().forEach((cmd) => {
2264
+ cmd.options.forEach((anOption) => {
2265
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) cmd.missingMandatoryOptionValue(anOption);
2266
+ });
2267
+ });
2268
+ }
2269
+ /**
2270
+ * Display an error message if conflicting options are used together in this.
2271
+ *
2272
+ * @private
2273
+ */
2274
+ _checkForConflictingLocalOptions() {
2275
+ const definedNonDefaultOptions = this.options.filter((option) => {
2276
+ const optionKey = option.attributeName();
2277
+ if (this.getOptionValue(optionKey) === void 0) return false;
2278
+ return this.getOptionValueSource(optionKey) !== "default";
2279
+ });
2280
+ definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0).forEach((option) => {
2281
+ const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
2282
+ if (conflictingAndDefined) this._conflictingOption(option, conflictingAndDefined);
2283
+ });
2284
+ }
2285
+ /**
2286
+ * Display an error message if conflicting options are used together.
2287
+ * Called after checking for help flags in leaf subcommand.
2288
+ *
2289
+ * @private
2290
+ */
2291
+ _checkForConflictingOptions() {
2292
+ this._getCommandAndAncestors().forEach((cmd) => {
2293
+ cmd._checkForConflictingLocalOptions();
2294
+ });
2295
+ }
2296
+ /**
2297
+ * Parse options from `argv` removing known options,
2298
+ * and return argv split into operands and unknown arguments.
2299
+ *
2300
+ * Side effects: modifies command by storing options. Does not reset state if called again.
2301
+ *
2302
+ * Examples:
2303
+ *
2304
+ * argv => operands, unknown
2305
+ * --known kkk op => [op], []
2306
+ * op --known kkk => [op], []
2307
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
2308
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
2309
+ *
2310
+ * @param {string[]} args
2311
+ * @return {{operands: string[], unknown: string[]}}
2312
+ */
2313
+ parseOptions(args) {
2314
+ const operands = [];
2315
+ const unknown = [];
2316
+ let dest = operands;
2317
+ function maybeOption(arg) {
2318
+ return arg.length > 1 && arg[0] === "-";
2319
+ }
2320
+ const negativeNumberArg = (arg) => {
2321
+ if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)) return false;
2322
+ return !this._getCommandAndAncestors().some((cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short)));
2323
+ };
2324
+ let activeVariadicOption = null;
2325
+ let activeGroup = null;
2326
+ let i$1 = 0;
2327
+ while (i$1 < args.length || activeGroup) {
2328
+ const arg = activeGroup ?? args[i$1++];
2329
+ activeGroup = null;
2330
+ if (arg === "--") {
2331
+ if (dest === unknown) dest.push(arg);
2332
+ dest.push(...args.slice(i$1));
2333
+ break;
2334
+ }
2335
+ if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
2336
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
2337
+ continue;
2338
+ }
2339
+ activeVariadicOption = null;
2340
+ if (maybeOption(arg)) {
2341
+ const option = this._findOption(arg);
2342
+ if (option) {
2343
+ if (option.required) {
2344
+ const value = args[i$1++];
2345
+ if (value === void 0) this.optionMissingArgument(option);
2346
+ this.emit(`option:${option.name()}`, value);
2347
+ } else if (option.optional) {
2348
+ let value = null;
2349
+ if (i$1 < args.length && (!maybeOption(args[i$1]) || negativeNumberArg(args[i$1]))) value = args[i$1++];
2350
+ this.emit(`option:${option.name()}`, value);
2351
+ } else this.emit(`option:${option.name()}`);
2352
+ activeVariadicOption = option.variadic ? option : null;
2353
+ continue;
2354
+ }
2355
+ }
2356
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
2357
+ const option = this._findOption(`-${arg[1]}`);
2358
+ if (option) {
2359
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) this.emit(`option:${option.name()}`, arg.slice(2));
2360
+ else {
2361
+ this.emit(`option:${option.name()}`);
2362
+ activeGroup = `-${arg.slice(2)}`;
2363
+ }
2364
+ continue;
2365
+ }
2366
+ }
2367
+ if (/^--[^=]+=/.test(arg)) {
2368
+ const index = arg.indexOf("=");
2369
+ const option = this._findOption(arg.slice(0, index));
2370
+ if (option && (option.required || option.optional)) {
2371
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
2372
+ continue;
2373
+ }
2374
+ }
2375
+ if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) dest = unknown;
2376
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
2377
+ if (this._findCommand(arg)) {
2378
+ operands.push(arg);
2379
+ unknown.push(...args.slice(i$1));
2380
+ break;
2381
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
2382
+ operands.push(arg, ...args.slice(i$1));
2383
+ break;
2384
+ } else if (this._defaultCommandName) {
2385
+ unknown.push(arg, ...args.slice(i$1));
2386
+ break;
2387
+ }
2388
+ }
2389
+ if (this._passThroughOptions) {
2390
+ dest.push(arg, ...args.slice(i$1));
2391
+ break;
2392
+ }
2393
+ dest.push(arg);
2394
+ }
2395
+ return {
2396
+ operands,
2397
+ unknown
2398
+ };
2399
+ }
2400
+ /**
2401
+ * Return an object containing local option values as key-value pairs.
2402
+ *
2403
+ * @return {object}
2404
+ */
2405
+ opts() {
2406
+ if (this._storeOptionsAsProperties) {
2407
+ const result = {};
2408
+ const len = this.options.length;
2409
+ for (let i$1 = 0; i$1 < len; i$1++) {
2410
+ const key = this.options[i$1].attributeName();
2411
+ result[key] = key === this._versionOptionName ? this._version : this[key];
2412
+ }
2413
+ return result;
2414
+ }
2415
+ return this._optionValues;
2416
+ }
2417
+ /**
2418
+ * Return an object containing merged local and global option values as key-value pairs.
2419
+ *
2420
+ * @return {object}
2421
+ */
2422
+ optsWithGlobals() {
2423
+ return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
2424
+ }
2425
+ /**
2426
+ * Display error message and exit (or call exitOverride).
2427
+ *
2428
+ * @param {string} message
2429
+ * @param {object} [errorOptions]
2430
+ * @param {string} [errorOptions.code] - an id string representing the error
2431
+ * @param {number} [errorOptions.exitCode] - used with process.exit
2432
+ */
2433
+ error(message, errorOptions) {
2434
+ this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);
2435
+ if (typeof this._showHelpAfterError === "string") this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);
2436
+ else if (this._showHelpAfterError) {
2437
+ this._outputConfiguration.writeErr("\n");
2438
+ this.outputHelp({ error: true });
2439
+ }
2440
+ const config = errorOptions || {};
2441
+ const exitCode = config.exitCode || 1;
2442
+ const code = config.code || "commander.error";
2443
+ this._exit(exitCode, code, message);
2444
+ }
2445
+ /**
2446
+ * Apply any option related environment variables, if option does
2447
+ * not have a value from cli or client code.
2448
+ *
2449
+ * @private
2450
+ */
2451
+ _parseOptionsEnv() {
2452
+ this.options.forEach((option) => {
2453
+ if (option.envVar && option.envVar in process$1.env) {
2454
+ const optionKey = option.attributeName();
2455
+ if (this.getOptionValue(optionKey) === void 0 || [
2456
+ "default",
2457
+ "config",
2458
+ "env"
2459
+ ].includes(this.getOptionValueSource(optionKey))) if (option.required || option.optional) this.emit(`optionEnv:${option.name()}`, process$1.env[option.envVar]);
2460
+ else this.emit(`optionEnv:${option.name()}`);
2461
+ }
2462
+ });
2463
+ }
2464
+ /**
2465
+ * Apply any implied option values, if option is undefined or default value.
2466
+ *
2467
+ * @private
2468
+ */
2469
+ _parseOptionsImplied() {
2470
+ const dualHelper = new DualOptions(this.options);
2471
+ const hasCustomOptionValue = (optionKey) => {
2472
+ return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
2473
+ };
2474
+ this.options.filter((option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
2475
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
2476
+ this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
2477
+ });
2478
+ });
2479
+ }
2480
+ /**
2481
+ * Argument `name` is missing.
2482
+ *
2483
+ * @param {string} name
2484
+ * @private
2485
+ */
2486
+ missingArgument(name) {
2487
+ const message = `error: missing required argument '${name}'`;
2488
+ this.error(message, { code: "commander.missingArgument" });
2489
+ }
2490
+ /**
2491
+ * `Option` is missing an argument.
2492
+ *
2493
+ * @param {Option} option
2494
+ * @private
2495
+ */
2496
+ optionMissingArgument(option) {
2497
+ const message = `error: option '${option.flags}' argument missing`;
2498
+ this.error(message, { code: "commander.optionMissingArgument" });
2499
+ }
2500
+ /**
2501
+ * `Option` does not have a value, and is a mandatory option.
2502
+ *
2503
+ * @param {Option} option
2504
+ * @private
2505
+ */
2506
+ missingMandatoryOptionValue(option) {
2507
+ const message = `error: required option '${option.flags}' not specified`;
2508
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
2509
+ }
2510
+ /**
2511
+ * `Option` conflicts with another option.
2512
+ *
2513
+ * @param {Option} option
2514
+ * @param {Option} conflictingOption
2515
+ * @private
2516
+ */
2517
+ _conflictingOption(option, conflictingOption) {
2518
+ const findBestOptionFromValue = (option$1) => {
2519
+ const optionKey = option$1.attributeName();
2520
+ const optionValue = this.getOptionValue(optionKey);
2521
+ const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
2522
+ const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
2523
+ if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) return negativeOption;
2524
+ return positiveOption || option$1;
2525
+ };
2526
+ const getErrorMessage$1 = (option$1) => {
2527
+ const bestOption = findBestOptionFromValue(option$1);
2528
+ const optionKey = bestOption.attributeName();
2529
+ if (this.getOptionValueSource(optionKey) === "env") return `environment variable '${bestOption.envVar}'`;
2530
+ return `option '${bestOption.flags}'`;
2531
+ };
2532
+ const message = `error: ${getErrorMessage$1(option)} cannot be used with ${getErrorMessage$1(conflictingOption)}`;
2533
+ this.error(message, { code: "commander.conflictingOption" });
2534
+ }
2535
+ /**
2536
+ * Unknown option `flag`.
2537
+ *
2538
+ * @param {string} flag
2539
+ * @private
2540
+ */
2541
+ unknownOption(flag) {
2542
+ if (this._allowUnknownOption) return;
2543
+ let suggestion = "";
2544
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
2545
+ let candidateFlags = [];
2546
+ let command = this;
2547
+ do {
2548
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
2549
+ candidateFlags = candidateFlags.concat(moreFlags);
2550
+ command = command.parent;
2551
+ } while (command && !command._enablePositionalOptions);
2552
+ suggestion = suggestSimilar(flag, candidateFlags);
2553
+ }
2554
+ const message = `error: unknown option '${flag}'${suggestion}`;
2555
+ this.error(message, { code: "commander.unknownOption" });
2556
+ }
2557
+ /**
2558
+ * Excess arguments, more than expected.
2559
+ *
2560
+ * @param {string[]} receivedArgs
2561
+ * @private
2562
+ */
2563
+ _excessArguments(receivedArgs) {
2564
+ if (this._allowExcessArguments) return;
2565
+ const expected = this.registeredArguments.length;
2566
+ const s$1 = expected === 1 ? "" : "s";
2567
+ const message = `error: too many arguments${this.parent ? ` for '${this.name()}'` : ""}. Expected ${expected} argument${s$1} but got ${receivedArgs.length}.`;
2568
+ this.error(message, { code: "commander.excessArguments" });
2569
+ }
2570
+ /**
2571
+ * Unknown command.
2572
+ *
2573
+ * @private
2574
+ */
2575
+ unknownCommand() {
2576
+ const unknownName = this.args[0];
2577
+ let suggestion = "";
2578
+ if (this._showSuggestionAfterError) {
2579
+ const candidateNames = [];
2580
+ this.createHelp().visibleCommands(this).forEach((command) => {
2581
+ candidateNames.push(command.name());
2582
+ if (command.alias()) candidateNames.push(command.alias());
2583
+ });
2584
+ suggestion = suggestSimilar(unknownName, candidateNames);
2585
+ }
2586
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
2587
+ this.error(message, { code: "commander.unknownCommand" });
2588
+ }
2589
+ /**
2590
+ * Get or set the program version.
2591
+ *
2592
+ * This method auto-registers the "-V, --version" option which will print the version number.
2593
+ *
2594
+ * You can optionally supply the flags and description to override the defaults.
2595
+ *
2596
+ * @param {string} [str]
2597
+ * @param {string} [flags]
2598
+ * @param {string} [description]
2599
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
2600
+ */
2601
+ version(str, flags, description) {
2602
+ if (str === void 0) return this._version;
2603
+ this._version = str;
2604
+ flags = flags || "-V, --version";
2605
+ description = description || "output the version number";
2606
+ const versionOption = this.createOption(flags, description);
2607
+ this._versionOptionName = versionOption.attributeName();
2608
+ this._registerOption(versionOption);
2609
+ this.on("option:" + versionOption.name(), () => {
2610
+ this._outputConfiguration.writeOut(`${str}\n`);
2611
+ this._exit(0, "commander.version", str);
2612
+ });
2613
+ return this;
2614
+ }
2615
+ /**
2616
+ * Set the description.
2617
+ *
2618
+ * @param {string} [str]
2619
+ * @param {object} [argsDescription]
2620
+ * @return {(string|Command)}
2621
+ */
2622
+ description(str, argsDescription) {
2623
+ if (str === void 0 && argsDescription === void 0) return this._description;
2624
+ this._description = str;
2625
+ if (argsDescription) this._argsDescription = argsDescription;
2626
+ return this;
2627
+ }
2628
+ /**
2629
+ * Set the summary. Used when listed as subcommand of parent.
2630
+ *
2631
+ * @param {string} [str]
2632
+ * @return {(string|Command)}
2633
+ */
2634
+ summary(str) {
2635
+ if (str === void 0) return this._summary;
2636
+ this._summary = str;
2637
+ return this;
2638
+ }
2639
+ /**
2640
+ * Set an alias for the command.
2641
+ *
2642
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
2643
+ *
2644
+ * @param {string} [alias]
2645
+ * @return {(string|Command)}
2646
+ */
2647
+ alias(alias) {
2648
+ if (alias === void 0) return this._aliases[0];
2649
+ /** @type {Command} */
2650
+ let command = this;
2651
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) command = this.commands[this.commands.length - 1];
2652
+ if (alias === command._name) throw new Error("Command alias can't be the same as its name");
2653
+ const matchingCommand = this.parent?._findCommand(alias);
2654
+ if (matchingCommand) {
2655
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
2656
+ throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
2657
+ }
2658
+ command._aliases.push(alias);
2659
+ return this;
2660
+ }
2661
+ /**
2662
+ * Set aliases for the command.
2663
+ *
2664
+ * Only the first alias is shown in the auto-generated help.
2665
+ *
2666
+ * @param {string[]} [aliases]
2667
+ * @return {(string[]|Command)}
2668
+ */
2669
+ aliases(aliases) {
2670
+ if (aliases === void 0) return this._aliases;
2671
+ aliases.forEach((alias) => this.alias(alias));
2672
+ return this;
2673
+ }
2674
+ /**
2675
+ * Set / get the command usage `str`.
2676
+ *
2677
+ * @param {string} [str]
2678
+ * @return {(string|Command)}
2679
+ */
2680
+ usage(str) {
2681
+ if (str === void 0) {
2682
+ if (this._usage) return this._usage;
2683
+ const args = this.registeredArguments.map((arg) => {
2684
+ return humanReadableArgName(arg);
2685
+ });
2686
+ return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
2687
+ }
2688
+ this._usage = str;
2689
+ return this;
2690
+ }
2691
+ /**
2692
+ * Get or set the name of the command.
2693
+ *
2694
+ * @param {string} [str]
2695
+ * @return {(string|Command)}
2696
+ */
2697
+ name(str) {
2698
+ if (str === void 0) return this._name;
2699
+ this._name = str;
2700
+ return this;
2701
+ }
2702
+ /**
2703
+ * Set/get the help group heading for this subcommand in parent command's help.
2704
+ *
2705
+ * @param {string} [heading]
2706
+ * @return {Command | string}
2707
+ */
2708
+ helpGroup(heading) {
2709
+ if (heading === void 0) return this._helpGroupHeading ?? "";
2710
+ this._helpGroupHeading = heading;
2711
+ return this;
2712
+ }
2713
+ /**
2714
+ * Set/get the default help group heading for subcommands added to this command.
2715
+ * (This does not override a group set directly on the subcommand using .helpGroup().)
2716
+ *
2717
+ * @example
2718
+ * program.commandsGroup('Development Commands:);
2719
+ * program.command('watch')...
2720
+ * program.command('lint')...
2721
+ * ...
2722
+ *
2723
+ * @param {string} [heading]
2724
+ * @returns {Command | string}
2725
+ */
2726
+ commandsGroup(heading) {
2727
+ if (heading === void 0) return this._defaultCommandGroup ?? "";
2728
+ this._defaultCommandGroup = heading;
2729
+ return this;
2730
+ }
2731
+ /**
2732
+ * Set/get the default help group heading for options added to this command.
2733
+ * (This does not override a group set directly on the option using .helpGroup().)
2734
+ *
2735
+ * @example
2736
+ * program
2737
+ * .optionsGroup('Development Options:')
2738
+ * .option('-d, --debug', 'output extra debugging')
2739
+ * .option('-p, --profile', 'output profiling information')
2740
+ *
2741
+ * @param {string} [heading]
2742
+ * @returns {Command | string}
2743
+ */
2744
+ optionsGroup(heading) {
2745
+ if (heading === void 0) return this._defaultOptionGroup ?? "";
2746
+ this._defaultOptionGroup = heading;
2747
+ return this;
2748
+ }
2749
+ /**
2750
+ * @param {Option} option
2751
+ * @private
2752
+ */
2753
+ _initOptionGroup(option) {
2754
+ if (this._defaultOptionGroup && !option.helpGroupHeading) option.helpGroup(this._defaultOptionGroup);
2755
+ }
2756
+ /**
2757
+ * @param {Command} cmd
2758
+ * @private
2759
+ */
2760
+ _initCommandGroup(cmd) {
2761
+ if (this._defaultCommandGroup && !cmd.helpGroup()) cmd.helpGroup(this._defaultCommandGroup);
2762
+ }
2763
+ /**
2764
+ * Set the name of the command from script filename, such as process.argv[1],
2765
+ * or require.main.filename, or __filename.
2766
+ *
2767
+ * (Used internally and public although not documented in README.)
2768
+ *
2769
+ * @example
2770
+ * program.nameFromFilename(require.main.filename);
2771
+ *
2772
+ * @param {string} filename
2773
+ * @return {Command}
2774
+ */
2775
+ nameFromFilename(filename) {
2776
+ this._name = path$1.basename(filename, path$1.extname(filename));
2777
+ return this;
2778
+ }
2779
+ /**
2780
+ * Get or set the directory for searching for executable subcommands of this command.
2781
+ *
2782
+ * @example
2783
+ * program.executableDir(__dirname);
2784
+ * // or
2785
+ * program.executableDir('subcommands');
2786
+ *
2787
+ * @param {string} [path]
2788
+ * @return {(string|null|Command)}
2789
+ */
2790
+ executableDir(path$2) {
2791
+ if (path$2 === void 0) return this._executableDir;
2792
+ this._executableDir = path$2;
2793
+ return this;
2794
+ }
2795
+ /**
2796
+ * Return program help documentation.
2797
+ *
2798
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
2799
+ * @return {string}
2800
+ */
2801
+ helpInformation(contextOptions) {
2802
+ const helper = this.createHelp();
2803
+ const context = this._getOutputContext(contextOptions);
2804
+ helper.prepareContext({
2805
+ error: context.error,
2806
+ helpWidth: context.helpWidth,
2807
+ outputHasColors: context.hasColors
2808
+ });
2809
+ const text = helper.formatHelp(this, helper);
2810
+ if (context.hasColors) return text;
2811
+ return this._outputConfiguration.stripColor(text);
2812
+ }
2813
+ /**
2814
+ * @typedef HelpContext
2815
+ * @type {object}
2816
+ * @property {boolean} error
2817
+ * @property {number} helpWidth
2818
+ * @property {boolean} hasColors
2819
+ * @property {function} write - includes stripColor if needed
2820
+ *
2821
+ * @returns {HelpContext}
2822
+ * @private
2823
+ */
2824
+ _getOutputContext(contextOptions) {
2825
+ contextOptions = contextOptions || {};
2826
+ const error = !!contextOptions.error;
2827
+ let baseWrite;
2828
+ let hasColors;
2829
+ let helpWidth;
2830
+ if (error) {
2831
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
2832
+ hasColors = this._outputConfiguration.getErrHasColors();
2833
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
2834
+ } else {
2835
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
2836
+ hasColors = this._outputConfiguration.getOutHasColors();
2837
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
2838
+ }
2839
+ const write = (str) => {
2840
+ if (!hasColors) str = this._outputConfiguration.stripColor(str);
2841
+ return baseWrite(str);
2842
+ };
2843
+ return {
2844
+ error,
2845
+ write,
2846
+ hasColors,
2847
+ helpWidth
2848
+ };
2849
+ }
2850
+ /**
2851
+ * Output help information for this command.
2852
+ *
2853
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2854
+ *
2855
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2856
+ */
2857
+ outputHelp(contextOptions) {
2858
+ let deprecatedCallback;
2859
+ if (typeof contextOptions === "function") {
2860
+ deprecatedCallback = contextOptions;
2861
+ contextOptions = void 0;
2862
+ }
2863
+ const outputContext = this._getOutputContext(contextOptions);
2864
+ /** @type {HelpTextEventContext} */
2865
+ const eventContext = {
2866
+ error: outputContext.error,
2867
+ write: outputContext.write,
2868
+ command: this
2869
+ };
2870
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
2871
+ this.emit("beforeHelp", eventContext);
2872
+ let helpInformation = this.helpInformation({ error: outputContext.error });
2873
+ if (deprecatedCallback) {
2874
+ helpInformation = deprecatedCallback(helpInformation);
2875
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) throw new Error("outputHelp callback must return a string or a Buffer");
2876
+ }
2877
+ outputContext.write(helpInformation);
2878
+ if (this._getHelpOption()?.long) this.emit(this._getHelpOption().long);
2879
+ this.emit("afterHelp", eventContext);
2880
+ this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", eventContext));
2881
+ }
2882
+ /**
2883
+ * You can pass in flags and a description to customise the built-in help option.
2884
+ * Pass in false to disable the built-in help option.
2885
+ *
2886
+ * @example
2887
+ * program.helpOption('-?, --help' 'show help'); // customise
2888
+ * program.helpOption(false); // disable
2889
+ *
2890
+ * @param {(string | boolean)} flags
2891
+ * @param {string} [description]
2892
+ * @return {Command} `this` command for chaining
2893
+ */
2894
+ helpOption(flags, description) {
2895
+ if (typeof flags === "boolean") {
2896
+ if (flags) {
2897
+ if (this._helpOption === null) this._helpOption = void 0;
2898
+ if (this._defaultOptionGroup) this._initOptionGroup(this._getHelpOption());
2899
+ } else this._helpOption = null;
2900
+ return this;
2901
+ }
2902
+ this._helpOption = this.createOption(flags ?? "-h, --help", description ?? "display help for command");
2903
+ if (flags || description) this._initOptionGroup(this._helpOption);
2904
+ return this;
2905
+ }
2906
+ /**
2907
+ * Lazy create help option.
2908
+ * Returns null if has been disabled with .helpOption(false).
2909
+ *
2910
+ * @returns {(Option | null)} the help option
2911
+ * @package
2912
+ */
2913
+ _getHelpOption() {
2914
+ if (this._helpOption === void 0) this.helpOption(void 0, void 0);
2915
+ return this._helpOption;
2916
+ }
2917
+ /**
2918
+ * Supply your own option to use for the built-in help option.
2919
+ * This is an alternative to using helpOption() to customise the flags and description etc.
2920
+ *
2921
+ * @param {Option} option
2922
+ * @return {Command} `this` command for chaining
2923
+ */
2924
+ addHelpOption(option) {
2925
+ this._helpOption = option;
2926
+ this._initOptionGroup(option);
2927
+ return this;
2928
+ }
2929
+ /**
2930
+ * Output help information and exit.
2931
+ *
2932
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2933
+ *
2934
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2935
+ */
2936
+ help(contextOptions) {
2937
+ this.outputHelp(contextOptions);
2938
+ let exitCode = Number(process$1.exitCode ?? 0);
2939
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) exitCode = 1;
2940
+ this._exit(exitCode, "commander.help", "(outputHelp)");
2941
+ }
2942
+ /**
2943
+ * // Do a little typing to coordinate emit and listener for the help text events.
2944
+ * @typedef HelpTextEventContext
2945
+ * @type {object}
2946
+ * @property {boolean} error
2947
+ * @property {Command} command
2948
+ * @property {function} write
2949
+ */
2950
+ /**
2951
+ * Add additional text to be displayed with the built-in help.
2952
+ *
2953
+ * Position is 'before' or 'after' to affect just this command,
2954
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
2955
+ *
2956
+ * @param {string} position - before or after built-in help
2957
+ * @param {(string | Function)} text - string to add, or a function returning a string
2958
+ * @return {Command} `this` command for chaining
2959
+ */
2960
+ addHelpText(position, text) {
2961
+ const allowedValues = [
2962
+ "beforeAll",
2963
+ "before",
2964
+ "after",
2965
+ "afterAll"
2966
+ ];
2967
+ if (!allowedValues.includes(position)) throw new Error(`Unexpected value for position to addHelpText.
2968
+ Expecting one of '${allowedValues.join("', '")}'`);
2969
+ const helpEvent = `${position}Help`;
2970
+ this.on(helpEvent, (context) => {
2971
+ let helpStr;
2972
+ if (typeof text === "function") helpStr = text({
2973
+ error: context.error,
2974
+ command: context.command
2975
+ });
2976
+ else helpStr = text;
2977
+ if (helpStr) context.write(`${helpStr}\n`);
2978
+ });
2979
+ return this;
2980
+ }
2981
+ /**
2982
+ * Output help information if help flags specified
2983
+ *
2984
+ * @param {Array} args - array of options to search for help flags
2985
+ * @private
2986
+ */
2987
+ _outputHelpIfRequested(args) {
2988
+ const helpOption = this._getHelpOption();
2989
+ if (helpOption && args.find((arg) => helpOption.is(arg))) {
2990
+ this.outputHelp();
2991
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
2992
+ }
2993
+ }
2994
+ };
2995
+ /**
2996
+ * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).
2997
+ *
2998
+ * @param {string[]} args - array of arguments from node.execArgv
2999
+ * @returns {string[]}
3000
+ * @private
3001
+ */
3002
+ function incrementNodeInspectorPort(args) {
3003
+ return args.map((arg) => {
3004
+ if (!arg.startsWith("--inspect")) return arg;
3005
+ let debugOption;
3006
+ let debugHost = "127.0.0.1";
3007
+ let debugPort = "9229";
3008
+ let match;
3009
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) debugOption = match[1];
3010
+ else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
3011
+ debugOption = match[1];
3012
+ if (/^\d+$/.test(match[3])) debugPort = match[3];
3013
+ else debugHost = match[3];
3014
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
3015
+ debugOption = match[1];
3016
+ debugHost = match[3];
3017
+ debugPort = match[4];
3018
+ }
3019
+ if (debugOption && debugPort !== "0") return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
3020
+ return arg;
3021
+ });
3022
+ }
3023
+ /**
3024
+ * @returns {boolean | undefined}
3025
+ * @package
3026
+ */
3027
+ function useColor() {
3028
+ if (process$1.env.NO_COLOR || process$1.env.FORCE_COLOR === "0" || process$1.env.FORCE_COLOR === "false") return false;
3029
+ if (process$1.env.FORCE_COLOR || process$1.env.CLICOLOR_FORCE !== void 0) return true;
3030
+ }
3031
+ exports.Command = Command$2;
3032
+ exports.useColor = useColor;
3033
+ }));
3034
+
3035
+ //#endregion
3036
+ //#region node_modules/.pnpm/commander@14.0.2/node_modules/commander/index.js
3037
+ var require_commander = /* @__PURE__ */ __commonJSMin(((exports) => {
3038
+ const { Argument: Argument$1 } = require_argument();
3039
+ const { Command: Command$1 } = require_command();
3040
+ const { CommanderError: CommanderError$1, InvalidArgumentError: InvalidArgumentError$1 } = require_error();
3041
+ const { Help: Help$1 } = require_help();
3042
+ const { Option: Option$1 } = require_option();
3043
+ exports.program = new Command$1();
3044
+ exports.createCommand = (name) => new Command$1(name);
3045
+ exports.createOption = (flags, description) => new Option$1(flags, description);
3046
+ exports.createArgument = (name, description) => new Argument$1(name, description);
3047
+ /**
3048
+ * Expose classes
3049
+ */
3050
+ exports.Command = Command$1;
3051
+ exports.Option = Option$1;
3052
+ exports.Argument = Argument$1;
3053
+ exports.Help = Help$1;
3054
+ exports.CommanderError = CommanderError$1;
3055
+ exports.InvalidArgumentError = InvalidArgumentError$1;
3056
+ exports.InvalidOptionArgumentError = InvalidArgumentError$1;
3057
+ }));
3058
+
3059
+ //#endregion
3060
+ //#region node_modules/.pnpm/commander@14.0.2/node_modules/commander/esm.mjs
3061
+ var import_commander = /* @__PURE__ */ __toESM(require_commander(), 1);
3062
+ const { program: program$1, createCommand, createArgument, createOption, CommanderError, InvalidArgumentError, InvalidOptionArgumentError, Command, Argument, Option, Help } = import_commander.default;
3063
+
3064
+ //#endregion
3065
+ //#region node_modules/.pnpm/consola@3.4.2/node_modules/consola/dist/core.mjs
3066
+ const LogLevels = {
3067
+ silent: Number.NEGATIVE_INFINITY,
3068
+ fatal: 0,
3069
+ error: 0,
3070
+ warn: 1,
3071
+ log: 2,
3072
+ info: 3,
3073
+ success: 3,
3074
+ fail: 3,
3075
+ ready: 3,
3076
+ start: 3,
3077
+ box: 3,
3078
+ debug: 4,
3079
+ trace: 5,
3080
+ verbose: Number.POSITIVE_INFINITY
3081
+ };
3082
+ const LogTypes = {
3083
+ silent: { level: -1 },
3084
+ fatal: { level: LogLevels.fatal },
3085
+ error: { level: LogLevels.error },
3086
+ warn: { level: LogLevels.warn },
3087
+ log: { level: LogLevels.log },
3088
+ info: { level: LogLevels.info },
3089
+ success: { level: LogLevels.success },
3090
+ fail: { level: LogLevels.fail },
3091
+ ready: { level: LogLevels.info },
3092
+ start: { level: LogLevels.info },
3093
+ box: { level: LogLevels.info },
3094
+ debug: { level: LogLevels.debug },
3095
+ trace: { level: LogLevels.trace },
3096
+ verbose: { level: LogLevels.verbose }
3097
+ };
3098
+ function isPlainObject$1(value) {
3099
+ if (value === null || typeof value !== "object") return false;
3100
+ const prototype = Object.getPrototypeOf(value);
3101
+ if (prototype !== null && prototype !== Object.prototype && Object.getPrototypeOf(prototype) !== null) return false;
3102
+ if (Symbol.iterator in value) return false;
3103
+ if (Symbol.toStringTag in value) return Object.prototype.toString.call(value) === "[object Module]";
3104
+ return true;
3105
+ }
3106
+ function _defu(baseObject, defaults, namespace = ".", merger) {
3107
+ if (!isPlainObject$1(defaults)) return _defu(baseObject, {}, namespace, merger);
3108
+ const object = Object.assign({}, defaults);
3109
+ for (const key in baseObject) {
3110
+ if (key === "__proto__" || key === "constructor") continue;
3111
+ const value = baseObject[key];
3112
+ if (value === null || value === void 0) continue;
3113
+ if (merger && merger(object, key, value, namespace)) continue;
3114
+ if (Array.isArray(value) && Array.isArray(object[key])) object[key] = [...value, ...object[key]];
3115
+ else if (isPlainObject$1(value) && isPlainObject$1(object[key])) object[key] = _defu(value, object[key], (namespace ? `${namespace}.` : "") + key.toString(), merger);
3116
+ else object[key] = value;
3117
+ }
3118
+ return object;
3119
+ }
3120
+ function createDefu(merger) {
3121
+ return (...arguments_) => arguments_.reduce((p, c$1) => _defu(p, c$1, "", merger), {});
3122
+ }
3123
+ const defu = createDefu();
3124
+ function isPlainObject(obj) {
3125
+ return Object.prototype.toString.call(obj) === "[object Object]";
3126
+ }
3127
+ function isLogObj(arg) {
3128
+ if (!isPlainObject(arg)) return false;
3129
+ if (!arg.message && !arg.args) return false;
3130
+ if (arg.stack) return false;
3131
+ return true;
3132
+ }
3133
+ let paused = false;
3134
+ const queue = [];
3135
+ var Consola = class Consola {
3136
+ options;
3137
+ _lastLog;
3138
+ _mockFn;
3139
+ /**
3140
+ * Creates an instance of Consola with specified options or defaults.
3141
+ *
3142
+ * @param {Partial<ConsolaOptions>} [options={}] - Configuration options for the Consola instance.
3143
+ */
3144
+ constructor(options$1 = {}) {
3145
+ const types = options$1.types || LogTypes;
3146
+ this.options = defu({
3147
+ ...options$1,
3148
+ defaults: { ...options$1.defaults },
3149
+ level: _normalizeLogLevel(options$1.level, types),
3150
+ reporters: [...options$1.reporters || []]
3151
+ }, {
3152
+ types: LogTypes,
3153
+ throttle: 1e3,
3154
+ throttleMin: 5,
3155
+ formatOptions: {
3156
+ date: true,
3157
+ colors: false,
3158
+ compact: true
3159
+ }
3160
+ });
3161
+ for (const type in types) {
3162
+ const defaults = {
3163
+ type,
3164
+ ...this.options.defaults,
3165
+ ...types[type]
3166
+ };
3167
+ this[type] = this._wrapLogFn(defaults);
3168
+ this[type].raw = this._wrapLogFn(defaults, true);
3169
+ }
3170
+ if (this.options.mockFn) this.mockTypes();
3171
+ this._lastLog = {};
3172
+ }
3173
+ /**
3174
+ * Gets the current log level of the Consola instance.
3175
+ *
3176
+ * @returns {number} The current log level.
3177
+ */
3178
+ get level() {
3179
+ return this.options.level;
3180
+ }
3181
+ /**
3182
+ * Sets the minimum log level that will be output by the instance.
3183
+ *
3184
+ * @param {number} level - The new log level to set.
3185
+ */
3186
+ set level(level) {
3187
+ this.options.level = _normalizeLogLevel(level, this.options.types, this.options.level);
3188
+ }
3189
+ /**
3190
+ * Displays a prompt to the user and returns the response.
3191
+ * Throw an error if `prompt` is not supported by the current configuration.
3192
+ *
3193
+ * @template T
3194
+ * @param {string} message - The message to display in the prompt.
3195
+ * @param {T} [opts] - Optional options for the prompt. See {@link PromptOptions}.
3196
+ * @returns {promise<T>} A promise that infer with the prompt options. See {@link PromptOptions}.
3197
+ */
3198
+ prompt(message, opts) {
3199
+ if (!this.options.prompt) throw new Error("prompt is not supported!");
3200
+ return this.options.prompt(message, opts);
3201
+ }
3202
+ /**
3203
+ * Creates a new instance of Consola, inheriting options from the current instance, with possible overrides.
3204
+ *
3205
+ * @param {Partial<ConsolaOptions>} options - Optional overrides for the new instance. See {@link ConsolaOptions}.
3206
+ * @returns {ConsolaInstance} A new Consola instance. See {@link ConsolaInstance}.
3207
+ */
3208
+ create(options$1) {
3209
+ const instance = new Consola({
3210
+ ...this.options,
3211
+ ...options$1
3212
+ });
3213
+ if (this._mockFn) instance.mockTypes(this._mockFn);
3214
+ return instance;
3215
+ }
3216
+ /**
3217
+ * Creates a new Consola instance with the specified default log object properties.
3218
+ *
3219
+ * @param {InputLogObject} defaults - Default properties to include in any log from the new instance. See {@link InputLogObject}.
3220
+ * @returns {ConsolaInstance} A new Consola instance. See {@link ConsolaInstance}.
3221
+ */
3222
+ withDefaults(defaults) {
3223
+ return this.create({
3224
+ ...this.options,
3225
+ defaults: {
3226
+ ...this.options.defaults,
3227
+ ...defaults
3228
+ }
3229
+ });
3230
+ }
3231
+ /**
3232
+ * Creates a new Consola instance with a specified tag, which will be included in every log.
3233
+ *
3234
+ * @param {string} tag - The tag to include in each log of the new instance.
3235
+ * @returns {ConsolaInstance} A new Consola instance. See {@link ConsolaInstance}.
3236
+ */
3237
+ withTag(tag) {
3238
+ return this.withDefaults({ tag: this.options.defaults.tag ? this.options.defaults.tag + ":" + tag : tag });
3239
+ }
3240
+ /**
3241
+ * Adds a custom reporter to the Consola instance.
3242
+ * Reporters will be called for each log message, depending on their implementation and log level.
3243
+ *
3244
+ * @param {ConsolaReporter} reporter - The reporter to add. See {@link ConsolaReporter}.
3245
+ * @returns {Consola} The current Consola instance.
3246
+ */
3247
+ addReporter(reporter) {
3248
+ this.options.reporters.push(reporter);
3249
+ return this;
3250
+ }
3251
+ /**
3252
+ * Removes a custom reporter from the Consola instance.
3253
+ * If no reporter is specified, all reporters will be removed.
3254
+ *
3255
+ * @param {ConsolaReporter} reporter - The reporter to remove. See {@link ConsolaReporter}.
3256
+ * @returns {Consola} The current Consola instance.
3257
+ */
3258
+ removeReporter(reporter) {
3259
+ if (reporter) {
3260
+ const i$1 = this.options.reporters.indexOf(reporter);
3261
+ if (i$1 !== -1) return this.options.reporters.splice(i$1, 1);
3262
+ } else this.options.reporters.splice(0);
3263
+ return this;
3264
+ }
3265
+ /**
3266
+ * Replaces all reporters of the Consola instance with the specified array of reporters.
3267
+ *
3268
+ * @param {ConsolaReporter[]} reporters - The new reporters to set. See {@link ConsolaReporter}.
3269
+ * @returns {Consola} The current Consola instance.
3270
+ */
3271
+ setReporters(reporters) {
3272
+ this.options.reporters = Array.isArray(reporters) ? reporters : [reporters];
3273
+ return this;
3274
+ }
3275
+ wrapAll() {
3276
+ this.wrapConsole();
3277
+ this.wrapStd();
3278
+ }
3279
+ restoreAll() {
3280
+ this.restoreConsole();
3281
+ this.restoreStd();
3282
+ }
3283
+ /**
3284
+ * Overrides console methods with Consola logging methods for consistent logging.
3285
+ */
3286
+ wrapConsole() {
3287
+ for (const type in this.options.types) {
3288
+ if (!console["__" + type]) console["__" + type] = console[type];
3289
+ console[type] = this[type].raw;
3290
+ }
3291
+ }
3292
+ /**
3293
+ * Restores the original console methods, removing Consola overrides.
3294
+ */
3295
+ restoreConsole() {
3296
+ for (const type in this.options.types) if (console["__" + type]) {
3297
+ console[type] = console["__" + type];
3298
+ delete console["__" + type];
3299
+ }
3300
+ }
3301
+ /**
3302
+ * Overrides standard output and error streams to redirect them through Consola.
3303
+ */
3304
+ wrapStd() {
3305
+ this._wrapStream(this.options.stdout, "log");
3306
+ this._wrapStream(this.options.stderr, "log");
3307
+ }
3308
+ _wrapStream(stream, type) {
3309
+ if (!stream) return;
3310
+ if (!stream.__write) stream.__write = stream.write;
3311
+ stream.write = (data) => {
3312
+ this[type].raw(String(data).trim());
3313
+ };
3314
+ }
3315
+ /**
3316
+ * Restores the original standard output and error streams, removing the Consola redirection.
3317
+ */
3318
+ restoreStd() {
3319
+ this._restoreStream(this.options.stdout);
3320
+ this._restoreStream(this.options.stderr);
3321
+ }
3322
+ _restoreStream(stream) {
3323
+ if (!stream) return;
3324
+ if (stream.__write) {
3325
+ stream.write = stream.__write;
3326
+ delete stream.__write;
3327
+ }
3328
+ }
3329
+ /**
3330
+ * Pauses logging, queues incoming logs until resumed.
3331
+ */
3332
+ pauseLogs() {
3333
+ paused = true;
3334
+ }
3335
+ /**
3336
+ * Resumes logging, processing any queued logs.
3337
+ */
3338
+ resumeLogs() {
3339
+ paused = false;
3340
+ const _queue = queue.splice(0);
3341
+ for (const item of _queue) item[0]._logFn(item[1], item[2]);
3342
+ }
3343
+ /**
3344
+ * Replaces logging methods with mocks if a mock function is provided.
3345
+ *
3346
+ * @param {ConsolaOptions["mockFn"]} mockFn - The function to use for mocking logging methods. See {@link ConsolaOptions["mockFn"]}.
3347
+ */
3348
+ mockTypes(mockFn) {
3349
+ const _mockFn = mockFn || this.options.mockFn;
3350
+ this._mockFn = _mockFn;
3351
+ if (typeof _mockFn !== "function") return;
3352
+ for (const type in this.options.types) {
3353
+ this[type] = _mockFn(type, this.options.types[type]) || this[type];
3354
+ this[type].raw = this[type];
3355
+ }
3356
+ }
3357
+ _wrapLogFn(defaults, isRaw) {
3358
+ return (...args) => {
3359
+ if (paused) {
3360
+ queue.push([
3361
+ this,
3362
+ defaults,
3363
+ args,
3364
+ isRaw
3365
+ ]);
3366
+ return;
3367
+ }
3368
+ return this._logFn(defaults, args, isRaw);
3369
+ };
3370
+ }
3371
+ _logFn(defaults, args, isRaw) {
3372
+ if ((defaults.level || 0) > this.level) return false;
3373
+ const logObj = {
3374
+ date: /* @__PURE__ */ new Date(),
3375
+ args: [],
3376
+ ...defaults,
3377
+ level: _normalizeLogLevel(defaults.level, this.options.types)
3378
+ };
3379
+ if (!isRaw && args.length === 1 && isLogObj(args[0])) Object.assign(logObj, args[0]);
3380
+ else logObj.args = [...args];
3381
+ if (logObj.message) {
3382
+ logObj.args.unshift(logObj.message);
3383
+ delete logObj.message;
3384
+ }
3385
+ if (logObj.additional) {
3386
+ if (!Array.isArray(logObj.additional)) logObj.additional = logObj.additional.split("\n");
3387
+ logObj.args.push("\n" + logObj.additional.join("\n"));
3388
+ delete logObj.additional;
3389
+ }
3390
+ logObj.type = typeof logObj.type === "string" ? logObj.type.toLowerCase() : "log";
3391
+ logObj.tag = typeof logObj.tag === "string" ? logObj.tag : "";
3392
+ const resolveLog = (newLog = false) => {
3393
+ const repeated = (this._lastLog.count || 0) - this.options.throttleMin;
3394
+ if (this._lastLog.object && repeated > 0) {
3395
+ const args2 = [...this._lastLog.object.args];
3396
+ if (repeated > 1) args2.push(`(repeated ${repeated} times)`);
3397
+ this._log({
3398
+ ...this._lastLog.object,
3399
+ args: args2
3400
+ });
3401
+ this._lastLog.count = 1;
3402
+ }
3403
+ if (newLog) {
3404
+ this._lastLog.object = logObj;
3405
+ this._log(logObj);
3406
+ }
3407
+ };
3408
+ clearTimeout(this._lastLog.timeout);
3409
+ const diffTime = this._lastLog.time && logObj.date ? logObj.date.getTime() - this._lastLog.time.getTime() : 0;
3410
+ this._lastLog.time = logObj.date;
3411
+ if (diffTime < this.options.throttle) try {
3412
+ const serializedLog = JSON.stringify([
3413
+ logObj.type,
3414
+ logObj.tag,
3415
+ logObj.args
3416
+ ]);
3417
+ const isSameLog = this._lastLog.serialized === serializedLog;
3418
+ this._lastLog.serialized = serializedLog;
3419
+ if (isSameLog) {
3420
+ this._lastLog.count = (this._lastLog.count || 0) + 1;
3421
+ if (this._lastLog.count > this.options.throttleMin) {
3422
+ this._lastLog.timeout = setTimeout(resolveLog, this.options.throttle);
3423
+ return;
3424
+ }
3425
+ }
3426
+ } catch {}
3427
+ resolveLog(true);
3428
+ }
3429
+ _log(logObj) {
3430
+ for (const reporter of this.options.reporters) reporter.log(logObj, { options: this.options });
3431
+ }
3432
+ };
3433
+ function _normalizeLogLevel(input, types = {}, defaultLevel = 3) {
3434
+ if (input === void 0) return defaultLevel;
3435
+ if (typeof input === "number") return input;
3436
+ if (types[input] && types[input].level !== void 0) return types[input].level;
3437
+ return defaultLevel;
3438
+ }
3439
+ Consola.prototype.add = Consola.prototype.addReporter;
3440
+ Consola.prototype.remove = Consola.prototype.removeReporter;
3441
+ Consola.prototype.clear = Consola.prototype.removeReporter;
3442
+ Consola.prototype.withScope = Consola.prototype.withTag;
3443
+ Consola.prototype.mock = Consola.prototype.mockTypes;
3444
+ Consola.prototype.pause = Consola.prototype.pauseLogs;
3445
+ Consola.prototype.resume = Consola.prototype.resumeLogs;
3446
+ function createConsola(options$1 = {}) {
3447
+ return new Consola(options$1);
3448
+ }
3449
+
3450
+ //#endregion
3451
+ //#region node_modules/.pnpm/consola@3.4.2/node_modules/consola/dist/shared/consola.DRwqZj3T.mjs
3452
+ function parseStack(stack, message) {
3453
+ const cwd = process.cwd() + sep;
3454
+ return stack.split("\n").splice(message.split("\n").length).map((l$1) => l$1.trim().replace("file://", "").replace(cwd, ""));
3455
+ }
3456
+ function writeStream(data, stream) {
3457
+ return (stream.__write || stream.write).call(stream, data);
3458
+ }
3459
+ const bracket = (x) => x ? `[${x}]` : "";
3460
+ var BasicReporter = class {
3461
+ formatStack(stack, message, opts) {
3462
+ const indent = " ".repeat((opts?.errorLevel || 0) + 1);
3463
+ return indent + parseStack(stack, message).join(`
3464
+ ${indent}`);
3465
+ }
3466
+ formatError(err, opts) {
3467
+ const message = err.message ?? formatWithOptions(opts, err);
3468
+ const stack = err.stack ? this.formatStack(err.stack, message, opts) : "";
3469
+ const level = opts?.errorLevel || 0;
3470
+ const causedPrefix = level > 0 ? `${" ".repeat(level)}[cause]: ` : "";
3471
+ const causedError = err.cause ? "\n\n" + this.formatError(err.cause, {
3472
+ ...opts,
3473
+ errorLevel: level + 1
3474
+ }) : "";
3475
+ return causedPrefix + message + "\n" + stack + causedError;
3476
+ }
3477
+ formatArgs(args, opts) {
3478
+ return formatWithOptions(opts, ...args.map((arg) => {
3479
+ if (arg && typeof arg.stack === "string") return this.formatError(arg, opts);
3480
+ return arg;
3481
+ }));
3482
+ }
3483
+ formatDate(date, opts) {
3484
+ return opts.date ? date.toLocaleTimeString() : "";
3485
+ }
3486
+ filterAndJoin(arr) {
3487
+ return arr.filter(Boolean).join(" ");
3488
+ }
3489
+ formatLogObj(logObj, opts) {
3490
+ const message = this.formatArgs(logObj.args, opts);
3491
+ if (logObj.type === "box") return "\n" + [
3492
+ bracket(logObj.tag),
3493
+ logObj.title && logObj.title,
3494
+ ...message.split("\n")
3495
+ ].filter(Boolean).map((l$1) => " > " + l$1).join("\n") + "\n";
3496
+ return this.filterAndJoin([
3497
+ bracket(logObj.type),
3498
+ bracket(logObj.tag),
3499
+ message
3500
+ ]);
3501
+ }
3502
+ log(logObj, ctx) {
3503
+ return writeStream(this.formatLogObj(logObj, {
3504
+ columns: ctx.options.stdout.columns || 0,
3505
+ ...ctx.options.formatOptions
3506
+ }) + "\n", logObj.level < 2 ? ctx.options.stderr || process.stderr : ctx.options.stdout || process.stdout);
3507
+ }
3508
+ };
3509
+
3510
+ //#endregion
3511
+ //#region node_modules/.pnpm/consola@3.4.2/node_modules/consola/dist/shared/consola.DXBYu-KD.mjs
3512
+ const { env = {}, argv = [], platform = "" } = typeof process === "undefined" ? {} : process;
3513
+ const isDisabled = "NO_COLOR" in env || argv.includes("--no-color");
3514
+ const isForced = "FORCE_COLOR" in env || argv.includes("--color");
3515
+ const isWindows = platform === "win32";
3516
+ const isDumbTerminal = env.TERM === "dumb";
3517
+ const isCompatibleTerminal = tty && tty.isatty && tty.isatty(1) && env.TERM && !isDumbTerminal;
3518
+ const isCI = "CI" in env && ("GITHUB_ACTIONS" in env || "GITLAB_CI" in env || "CIRCLECI" in env);
3519
+ const isColorSupported = !isDisabled && (isForced || isWindows && !isDumbTerminal || isCompatibleTerminal || isCI);
3520
+ function replaceClose(index, string, close, replace, head = string.slice(0, Math.max(0, index)) + replace, tail = string.slice(Math.max(0, index + close.length)), next = tail.indexOf(close)) {
3521
+ return head + (next < 0 ? tail : replaceClose(next, tail, close, replace));
3522
+ }
3523
+ function clearBleed(index, string, open, close, replace) {
3524
+ return index < 0 ? open + string + close : open + replaceClose(index, string, close, replace) + close;
3525
+ }
3526
+ function filterEmpty(open, close, replace = open, at = open.length + 1) {
3527
+ return (string) => string || !(string === "" || string === void 0) ? clearBleed(("" + string).indexOf(close, at), string, open, close, replace) : "";
3528
+ }
3529
+ function init(open, close, replace) {
3530
+ return filterEmpty(`\x1B[${open}m`, `\x1B[${close}m`, replace);
3531
+ }
3532
+ const colorDefs = {
3533
+ reset: init(0, 0),
3534
+ bold: init(1, 22, "\x1B[22m\x1B[1m"),
3535
+ dim: init(2, 22, "\x1B[22m\x1B[2m"),
3536
+ italic: init(3, 23),
3537
+ underline: init(4, 24),
3538
+ inverse: init(7, 27),
3539
+ hidden: init(8, 28),
3540
+ strikethrough: init(9, 29),
3541
+ black: init(30, 39),
3542
+ red: init(31, 39),
3543
+ green: init(32, 39),
3544
+ yellow: init(33, 39),
3545
+ blue: init(34, 39),
3546
+ magenta: init(35, 39),
3547
+ cyan: init(36, 39),
3548
+ white: init(37, 39),
3549
+ gray: init(90, 39),
3550
+ bgBlack: init(40, 49),
3551
+ bgRed: init(41, 49),
3552
+ bgGreen: init(42, 49),
3553
+ bgYellow: init(43, 49),
3554
+ bgBlue: init(44, 49),
3555
+ bgMagenta: init(45, 49),
3556
+ bgCyan: init(46, 49),
3557
+ bgWhite: init(47, 49),
3558
+ blackBright: init(90, 39),
3559
+ redBright: init(91, 39),
3560
+ greenBright: init(92, 39),
3561
+ yellowBright: init(93, 39),
3562
+ blueBright: init(94, 39),
3563
+ magentaBright: init(95, 39),
3564
+ cyanBright: init(96, 39),
3565
+ whiteBright: init(97, 39),
3566
+ bgBlackBright: init(100, 49),
3567
+ bgRedBright: init(101, 49),
3568
+ bgGreenBright: init(102, 49),
3569
+ bgYellowBright: init(103, 49),
3570
+ bgBlueBright: init(104, 49),
3571
+ bgMagentaBright: init(105, 49),
3572
+ bgCyanBright: init(106, 49),
3573
+ bgWhiteBright: init(107, 49)
3574
+ };
3575
+ function createColors(useColor$1 = isColorSupported) {
3576
+ return useColor$1 ? colorDefs : Object.fromEntries(Object.keys(colorDefs).map((key) => [key, String]));
3577
+ }
3578
+ const colors = createColors();
3579
+ function getColor$1(color, fallback = "reset") {
3580
+ return colors[color] || colors[fallback];
3581
+ }
3582
+ function colorize(color, text) {
3583
+ return getColor$1(color)(text);
3584
+ }
3585
+ const ansiRegex$1 = [String.raw`[\u001B\u009B][[\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\d\/#&.:=?%@~_]+)*|[a-zA-Z\d]+(?:;[-a-zA-Z\d\/#&.:=?%@~_]*)*)?\u0007)`, String.raw`(?:(?:\d{1,4}(?:;\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~]))`].join("|");
3586
+ function stripAnsi(text) {
3587
+ return text.replace(new RegExp(ansiRegex$1, "g"), "");
3588
+ }
3589
+ const boxStylePresets = {
3590
+ solid: {
3591
+ tl: "┌",
3592
+ tr: "┐",
3593
+ bl: "└",
3594
+ br: "┘",
3595
+ h: "─",
3596
+ v: "│"
3597
+ },
3598
+ double: {
3599
+ tl: "╔",
3600
+ tr: "╗",
3601
+ bl: "╚",
3602
+ br: "╝",
3603
+ h: "═",
3604
+ v: "║"
3605
+ },
3606
+ doubleSingle: {
3607
+ tl: "╓",
3608
+ tr: "╖",
3609
+ bl: "╙",
3610
+ br: "╜",
3611
+ h: "─",
3612
+ v: "║"
3613
+ },
3614
+ doubleSingleRounded: {
3615
+ tl: "╭",
3616
+ tr: "╮",
3617
+ bl: "╰",
3618
+ br: "╯",
3619
+ h: "─",
3620
+ v: "║"
3621
+ },
3622
+ singleThick: {
3623
+ tl: "┏",
3624
+ tr: "┓",
3625
+ bl: "┗",
3626
+ br: "┛",
3627
+ h: "━",
3628
+ v: "┃"
3629
+ },
3630
+ singleDouble: {
3631
+ tl: "╒",
3632
+ tr: "╕",
3633
+ bl: "╘",
3634
+ br: "╛",
3635
+ h: "═",
3636
+ v: "│"
3637
+ },
3638
+ singleDoubleRounded: {
3639
+ tl: "╭",
3640
+ tr: "╮",
3641
+ bl: "╰",
3642
+ br: "╯",
3643
+ h: "═",
3644
+ v: "│"
3645
+ },
3646
+ rounded: {
3647
+ tl: "╭",
3648
+ tr: "╮",
3649
+ bl: "╰",
3650
+ br: "╯",
3651
+ h: "─",
3652
+ v: "│"
3653
+ }
3654
+ };
3655
+ const defaultStyle = {
3656
+ borderColor: "white",
3657
+ borderStyle: "rounded",
3658
+ valign: "center",
3659
+ padding: 2,
3660
+ marginLeft: 1,
3661
+ marginTop: 1,
3662
+ marginBottom: 1
3663
+ };
3664
+ function box(text, _opts = {}) {
3665
+ const opts = {
3666
+ ..._opts,
3667
+ style: {
3668
+ ...defaultStyle,
3669
+ ..._opts.style
3670
+ }
3671
+ };
3672
+ const textLines = text.split("\n");
3673
+ const boxLines = [];
3674
+ const _color = getColor$1(opts.style.borderColor);
3675
+ const borderStyle = { ...typeof opts.style.borderStyle === "string" ? boxStylePresets[opts.style.borderStyle] || boxStylePresets.solid : opts.style.borderStyle };
3676
+ if (_color) for (const key in borderStyle) borderStyle[key] = _color(borderStyle[key]);
3677
+ const paddingOffset = opts.style.padding % 2 === 0 ? opts.style.padding : opts.style.padding + 1;
3678
+ const height = textLines.length + paddingOffset;
3679
+ const width = Math.max(...textLines.map((line) => stripAnsi(line).length), opts.title ? stripAnsi(opts.title).length : 0) + paddingOffset;
3680
+ const widthOffset = width + paddingOffset;
3681
+ const leftSpace = opts.style.marginLeft > 0 ? " ".repeat(opts.style.marginLeft) : "";
3682
+ if (opts.style.marginTop > 0) boxLines.push("".repeat(opts.style.marginTop));
3683
+ if (opts.title) {
3684
+ const title = _color ? _color(opts.title) : opts.title;
3685
+ const left = borderStyle.h.repeat(Math.floor((width - stripAnsi(opts.title).length) / 2));
3686
+ const right = borderStyle.h.repeat(width - stripAnsi(opts.title).length - stripAnsi(left).length + paddingOffset);
3687
+ boxLines.push(`${leftSpace}${borderStyle.tl}${left}${title}${right}${borderStyle.tr}`);
3688
+ } else boxLines.push(`${leftSpace}${borderStyle.tl}${borderStyle.h.repeat(widthOffset)}${borderStyle.tr}`);
3689
+ const valignOffset = opts.style.valign === "center" ? Math.floor((height - textLines.length) / 2) : opts.style.valign === "top" ? height - textLines.length - paddingOffset : height - textLines.length;
3690
+ for (let i$1 = 0; i$1 < height; i$1++) if (i$1 < valignOffset || i$1 >= valignOffset + textLines.length) boxLines.push(`${leftSpace}${borderStyle.v}${" ".repeat(widthOffset)}${borderStyle.v}`);
3691
+ else {
3692
+ const line = textLines[i$1 - valignOffset];
3693
+ const left = " ".repeat(paddingOffset);
3694
+ const right = " ".repeat(width - stripAnsi(line).length);
3695
+ boxLines.push(`${leftSpace}${borderStyle.v}${left}${line}${right}${borderStyle.v}`);
3696
+ }
3697
+ boxLines.push(`${leftSpace}${borderStyle.bl}${borderStyle.h.repeat(widthOffset)}${borderStyle.br}`);
3698
+ if (opts.style.marginBottom > 0) boxLines.push("".repeat(opts.style.marginBottom));
3699
+ return boxLines.join("\n");
3700
+ }
3701
+
3702
+ //#endregion
3703
+ //#region node_modules/.pnpm/consola@3.4.2/node_modules/consola/dist/index.mjs
3704
+ const r = Object.create(null), i = (e) => globalThis.process?.env || import.meta.env || globalThis.Deno?.env.toObject() || globalThis.__env__ || (e ? r : globalThis), o = new Proxy(r, {
3705
+ get(e, s$1) {
3706
+ return i()[s$1] ?? r[s$1];
3707
+ },
3708
+ has(e, s$1) {
3709
+ return s$1 in i() || s$1 in r;
3710
+ },
3711
+ set(e, s$1, E) {
3712
+ const B = i(true);
3713
+ return B[s$1] = E, true;
3714
+ },
3715
+ deleteProperty(e, s$1) {
3716
+ if (!s$1) return false;
3717
+ const E = i(true);
3718
+ return delete E[s$1], true;
3719
+ },
3720
+ ownKeys() {
3721
+ const e = i(true);
3722
+ return Object.keys(e);
3723
+ }
3724
+ }), t = typeof process < "u" && process.env && process.env.NODE_ENV || "", f = [
3725
+ ["APPVEYOR"],
3726
+ [
3727
+ "AWS_AMPLIFY",
3728
+ "AWS_APP_ID",
3729
+ { ci: true }
3730
+ ],
3731
+ ["AZURE_PIPELINES", "SYSTEM_TEAMFOUNDATIONCOLLECTIONURI"],
3732
+ ["AZURE_STATIC", "INPUT_AZURE_STATIC_WEB_APPS_API_TOKEN"],
3733
+ ["APPCIRCLE", "AC_APPCIRCLE"],
3734
+ ["BAMBOO", "bamboo_planKey"],
3735
+ ["BITBUCKET", "BITBUCKET_COMMIT"],
3736
+ ["BITRISE", "BITRISE_IO"],
3737
+ ["BUDDY", "BUDDY_WORKSPACE_ID"],
3738
+ ["BUILDKITE"],
3739
+ ["CIRCLE", "CIRCLECI"],
3740
+ ["CIRRUS", "CIRRUS_CI"],
3741
+ [
3742
+ "CLOUDFLARE_PAGES",
3743
+ "CF_PAGES",
3744
+ { ci: true }
3745
+ ],
3746
+ ["CODEBUILD", "CODEBUILD_BUILD_ARN"],
3747
+ ["CODEFRESH", "CF_BUILD_ID"],
3748
+ ["DRONE"],
3749
+ ["DRONE", "DRONE_BUILD_EVENT"],
3750
+ ["DSARI"],
3751
+ ["GITHUB_ACTIONS"],
3752
+ ["GITLAB", "GITLAB_CI"],
3753
+ ["GITLAB", "CI_MERGE_REQUEST_ID"],
3754
+ ["GOCD", "GO_PIPELINE_LABEL"],
3755
+ ["LAYERCI"],
3756
+ ["HUDSON", "HUDSON_URL"],
3757
+ ["JENKINS", "JENKINS_URL"],
3758
+ ["MAGNUM"],
3759
+ ["NETLIFY"],
3760
+ [
3761
+ "NETLIFY",
3762
+ "NETLIFY_LOCAL",
3763
+ { ci: false }
3764
+ ],
3765
+ ["NEVERCODE"],
3766
+ ["RENDER"],
3767
+ ["SAIL", "SAILCI"],
3768
+ ["SEMAPHORE"],
3769
+ ["SCREWDRIVER"],
3770
+ ["SHIPPABLE"],
3771
+ ["SOLANO", "TDDIUM"],
3772
+ ["STRIDER"],
3773
+ ["TEAMCITY", "TEAMCITY_VERSION"],
3774
+ ["TRAVIS"],
3775
+ ["VERCEL", "NOW_BUILDER"],
3776
+ [
3777
+ "VERCEL",
3778
+ "VERCEL",
3779
+ { ci: false }
3780
+ ],
3781
+ [
3782
+ "VERCEL",
3783
+ "VERCEL_ENV",
3784
+ { ci: false }
3785
+ ],
3786
+ ["APPCENTER", "APPCENTER_BUILD_ID"],
3787
+ [
3788
+ "CODESANDBOX",
3789
+ "CODESANDBOX_SSE",
3790
+ { ci: false }
3791
+ ],
3792
+ [
3793
+ "CODESANDBOX",
3794
+ "CODESANDBOX_HOST",
3795
+ { ci: false }
3796
+ ],
3797
+ ["STACKBLITZ"],
3798
+ ["STORMKIT"],
3799
+ ["CLEAVR"],
3800
+ ["ZEABUR"],
3801
+ [
3802
+ "CODESPHERE",
3803
+ "CODESPHERE_APP_ID",
3804
+ { ci: true }
3805
+ ],
3806
+ ["RAILWAY", "RAILWAY_PROJECT_ID"],
3807
+ ["RAILWAY", "RAILWAY_SERVICE_ID"],
3808
+ ["DENO-DEPLOY", "DENO_DEPLOYMENT_ID"],
3809
+ [
3810
+ "FIREBASE_APP_HOSTING",
3811
+ "FIREBASE_APP_HOSTING",
3812
+ { ci: true }
3813
+ ]
3814
+ ];
3815
+ function b() {
3816
+ if (globalThis.process?.env) for (const e of f) {
3817
+ const s$1 = e[1] || e[0];
3818
+ if (globalThis.process?.env[s$1]) return {
3819
+ name: e[0].toLowerCase(),
3820
+ ...e[2]
3821
+ };
3822
+ }
3823
+ return globalThis.process?.env?.SHELL === "/bin/jsh" && globalThis.process?.versions?.webcontainer ? {
3824
+ name: "stackblitz",
3825
+ ci: false
3826
+ } : {
3827
+ name: "",
3828
+ ci: false
3829
+ };
3830
+ }
3831
+ const l = b();
3832
+ l.name;
3833
+ function n(e) {
3834
+ return e ? e !== "false" : false;
3835
+ }
3836
+ const I = globalThis.process?.platform || "", T = n(o.CI) || l.ci !== false, a = n(globalThis.process?.stdout && globalThis.process?.stdout.isTTY), g = n(o.DEBUG), R = t === "test" || n(o.TEST);
3837
+ n(o.MINIMAL);
3838
+ const A = /^win/i.test(I);
3839
+ !n(o.NO_COLOR) && (n(o.FORCE_COLOR) || (a || A) && o.TERM);
3840
+ const C = (globalThis.process?.versions?.node || "").replace(/^v/, "") || null;
3841
+ Number(C?.split(".")[0]);
3842
+ const y = globalThis.process || Object.create(null), _ = { versions: {} };
3843
+ new Proxy(y, { get(e, s$1) {
3844
+ if (s$1 === "env") return o;
3845
+ if (s$1 in e) return e[s$1];
3846
+ if (s$1 in _) return _[s$1];
3847
+ } });
3848
+ const c = globalThis.process?.release?.name === "node", O = !!globalThis.Bun || !!globalThis.process?.versions?.bun, D = !!globalThis.Deno, L = !!globalThis.fastly, S = !!globalThis.Netlify, u = !!globalThis.EdgeRuntime, N = globalThis.navigator?.userAgent === "Cloudflare-Workers", F = [
3849
+ [S, "netlify"],
3850
+ [u, "edge-light"],
3851
+ [N, "workerd"],
3852
+ [L, "fastly"],
3853
+ [D, "deno"],
3854
+ [O, "bun"],
3855
+ [c, "node"]
3856
+ ];
3857
+ function G() {
3858
+ const e = F.find((s$1) => s$1[0]);
3859
+ if (e) return { name: e[1] };
3860
+ }
3861
+ G()?.name;
3862
+ function ansiRegex({ onlyFirst = false } = {}) {
3863
+ const pattern = [`[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))`, "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");
3864
+ return new RegExp(pattern, onlyFirst ? void 0 : "g");
3865
+ }
3866
+ const regex = ansiRegex();
3867
+ function stripAnsi$1(string) {
3868
+ if (typeof string !== "string") throw new TypeError(`Expected a \`string\`, got \`${typeof string}\``);
3869
+ return string.replace(regex, "");
3870
+ }
3871
+ function isAmbiguous(x) {
3872
+ return x === 161 || x === 164 || x === 167 || x === 168 || x === 170 || x === 173 || x === 174 || x >= 176 && x <= 180 || x >= 182 && x <= 186 || x >= 188 && x <= 191 || x === 198 || x === 208 || x === 215 || x === 216 || x >= 222 && x <= 225 || x === 230 || x >= 232 && x <= 234 || x === 236 || x === 237 || x === 240 || x === 242 || x === 243 || x >= 247 && x <= 250 || x === 252 || x === 254 || x === 257 || x === 273 || x === 275 || x === 283 || x === 294 || x === 295 || x === 299 || x >= 305 && x <= 307 || x === 312 || x >= 319 && x <= 322 || x === 324 || x >= 328 && x <= 331 || x === 333 || x === 338 || x === 339 || x === 358 || x === 359 || x === 363 || x === 462 || x === 464 || x === 466 || x === 468 || x === 470 || x === 472 || x === 474 || x === 476 || x === 593 || x === 609 || x === 708 || x === 711 || x >= 713 && x <= 715 || x === 717 || x === 720 || x >= 728 && x <= 731 || x === 733 || x === 735 || x >= 768 && x <= 879 || x >= 913 && x <= 929 || x >= 931 && x <= 937 || x >= 945 && x <= 961 || x >= 963 && x <= 969 || x === 1025 || x >= 1040 && x <= 1103 || x === 1105 || x === 8208 || x >= 8211 && x <= 8214 || x === 8216 || x === 8217 || x === 8220 || x === 8221 || x >= 8224 && x <= 8226 || x >= 8228 && x <= 8231 || x === 8240 || x === 8242 || x === 8243 || x === 8245 || x === 8251 || x === 8254 || x === 8308 || x === 8319 || x >= 8321 && x <= 8324 || x === 8364 || x === 8451 || x === 8453 || x === 8457 || x === 8467 || x === 8470 || x === 8481 || x === 8482 || x === 8486 || x === 8491 || x === 8531 || x === 8532 || x >= 8539 && x <= 8542 || x >= 8544 && x <= 8555 || x >= 8560 && x <= 8569 || x === 8585 || x >= 8592 && x <= 8601 || x === 8632 || x === 8633 || x === 8658 || x === 8660 || x === 8679 || x === 8704 || x === 8706 || x === 8707 || x === 8711 || x === 8712 || x === 8715 || x === 8719 || x === 8721 || x === 8725 || x === 8730 || x >= 8733 && x <= 8736 || x === 8739 || x === 8741 || x >= 8743 && x <= 8748 || x === 8750 || x >= 8756 && x <= 8759 || x === 8764 || x === 8765 || x === 8776 || x === 8780 || x === 8786 || x === 8800 || x === 8801 || x >= 8804 && x <= 8807 || x === 8810 || x === 8811 || x === 8814 || x === 8815 || x === 8834 || x === 8835 || x === 8838 || x === 8839 || x === 8853 || x === 8857 || x === 8869 || x === 8895 || x === 8978 || x >= 9312 && x <= 9449 || x >= 9451 && x <= 9547 || x >= 9552 && x <= 9587 || x >= 9600 && x <= 9615 || x >= 9618 && x <= 9621 || x === 9632 || x === 9633 || x >= 9635 && x <= 9641 || x === 9650 || x === 9651 || x === 9654 || x === 9655 || x === 9660 || x === 9661 || x === 9664 || x === 9665 || x >= 9670 && x <= 9672 || x === 9675 || x >= 9678 && x <= 9681 || x >= 9698 && x <= 9701 || x === 9711 || x === 9733 || x === 9734 || x === 9737 || x === 9742 || x === 9743 || x === 9756 || x === 9758 || x === 9792 || x === 9794 || x === 9824 || x === 9825 || x >= 9827 && x <= 9829 || x >= 9831 && x <= 9834 || x === 9836 || x === 9837 || x === 9839 || x === 9886 || x === 9887 || x === 9919 || x >= 9926 && x <= 9933 || x >= 9935 && x <= 9939 || x >= 9941 && x <= 9953 || x === 9955 || x === 9960 || x === 9961 || x >= 9963 && x <= 9969 || x === 9972 || x >= 9974 && x <= 9977 || x === 9979 || x === 9980 || x === 9982 || x === 9983 || x === 10045 || x >= 10102 && x <= 10111 || x >= 11094 && x <= 11097 || x >= 12872 && x <= 12879 || x >= 57344 && x <= 63743 || x >= 65024 && x <= 65039 || x === 65533 || x >= 127232 && x <= 127242 || x >= 127248 && x <= 127277 || x >= 127280 && x <= 127337 || x >= 127344 && x <= 127373 || x === 127375 || x === 127376 || x >= 127387 && x <= 127404 || x >= 917760 && x <= 917999 || x >= 983040 && x <= 1048573 || x >= 1048576 && x <= 1114109;
3873
+ }
3874
+ function isFullWidth(x) {
3875
+ return x === 12288 || x >= 65281 && x <= 65376 || x >= 65504 && x <= 65510;
3876
+ }
3877
+ function isWide(x) {
3878
+ return x >= 4352 && x <= 4447 || x === 8986 || x === 8987 || x === 9001 || x === 9002 || x >= 9193 && x <= 9196 || x === 9200 || x === 9203 || x === 9725 || x === 9726 || x === 9748 || x === 9749 || x >= 9776 && x <= 9783 || x >= 9800 && x <= 9811 || x === 9855 || x >= 9866 && x <= 9871 || x === 9875 || x === 9889 || x === 9898 || x === 9899 || x === 9917 || x === 9918 || x === 9924 || x === 9925 || x === 9934 || x === 9940 || x === 9962 || x === 9970 || x === 9971 || x === 9973 || x === 9978 || x === 9981 || x === 9989 || x === 9994 || x === 9995 || x === 10024 || x === 10060 || x === 10062 || x >= 10067 && x <= 10069 || x === 10071 || x >= 10133 && x <= 10135 || x === 10160 || x === 10175 || x === 11035 || x === 11036 || x === 11088 || x === 11093 || x >= 11904 && x <= 11929 || x >= 11931 && x <= 12019 || x >= 12032 && x <= 12245 || x >= 12272 && x <= 12287 || x >= 12289 && x <= 12350 || x >= 12353 && x <= 12438 || x >= 12441 && x <= 12543 || x >= 12549 && x <= 12591 || x >= 12593 && x <= 12686 || x >= 12688 && x <= 12773 || x >= 12783 && x <= 12830 || x >= 12832 && x <= 12871 || x >= 12880 && x <= 42124 || x >= 42128 && x <= 42182 || x >= 43360 && x <= 43388 || x >= 44032 && x <= 55203 || x >= 63744 && x <= 64255 || x >= 65040 && x <= 65049 || x >= 65072 && x <= 65106 || x >= 65108 && x <= 65126 || x >= 65128 && x <= 65131 || x >= 94176 && x <= 94180 || x === 94192 || x === 94193 || x >= 94208 && x <= 100343 || x >= 100352 && x <= 101589 || x >= 101631 && x <= 101640 || x >= 110576 && x <= 110579 || x >= 110581 && x <= 110587 || x === 110589 || x === 110590 || x >= 110592 && x <= 110882 || x === 110898 || x >= 110928 && x <= 110930 || x === 110933 || x >= 110948 && x <= 110951 || x >= 110960 && x <= 111355 || x >= 119552 && x <= 119638 || x >= 119648 && x <= 119670 || x === 126980 || x === 127183 || x === 127374 || x >= 127377 && x <= 127386 || x >= 127488 && x <= 127490 || x >= 127504 && x <= 127547 || x >= 127552 && x <= 127560 || x === 127568 || x === 127569 || x >= 127584 && x <= 127589 || x >= 127744 && x <= 127776 || x >= 127789 && x <= 127797 || x >= 127799 && x <= 127868 || x >= 127870 && x <= 127891 || x >= 127904 && x <= 127946 || x >= 127951 && x <= 127955 || x >= 127968 && x <= 127984 || x === 127988 || x >= 127992 && x <= 128062 || x === 128064 || x >= 128066 && x <= 128252 || x >= 128255 && x <= 128317 || x >= 128331 && x <= 128334 || x >= 128336 && x <= 128359 || x === 128378 || x === 128405 || x === 128406 || x === 128420 || x >= 128507 && x <= 128591 || x >= 128640 && x <= 128709 || x === 128716 || x >= 128720 && x <= 128722 || x >= 128725 && x <= 128727 || x >= 128732 && x <= 128735 || x === 128747 || x === 128748 || x >= 128756 && x <= 128764 || x >= 128992 && x <= 129003 || x === 129008 || x >= 129292 && x <= 129338 || x >= 129340 && x <= 129349 || x >= 129351 && x <= 129535 || x >= 129648 && x <= 129660 || x >= 129664 && x <= 129673 || x >= 129679 && x <= 129734 || x >= 129742 && x <= 129756 || x >= 129759 && x <= 129769 || x >= 129776 && x <= 129784 || x >= 131072 && x <= 196605 || x >= 196608 && x <= 262141;
3879
+ }
3880
+ function validate(codePoint) {
3881
+ if (!Number.isSafeInteger(codePoint)) throw new TypeError(`Expected a code point, got \`${typeof codePoint}\`.`);
3882
+ }
3883
+ function eastAsianWidth(codePoint, { ambiguousAsWide = false } = {}) {
3884
+ validate(codePoint);
3885
+ if (isFullWidth(codePoint) || isWide(codePoint) || ambiguousAsWide && isAmbiguous(codePoint)) return 2;
3886
+ return 1;
3887
+ }
3888
+ const emojiRegex = () => {
3889
+ return /[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE])))?))?|\uDC6F(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE89\uDE8F-\uDEC2\uDEC6\uDECE-\uDEDC\uDEDF-\uDEE9]|\uDD3C(?:\u200D[\u2640\u2642]\uFE0F?|\uD83C[\uDFFB-\uDFFF])?|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g;
3890
+ };
3891
+ const segmenter = globalThis.Intl?.Segmenter ? new Intl.Segmenter() : { segment: (str) => str.split("") };
3892
+ const defaultIgnorableCodePointRegex = /^\p{Default_Ignorable_Code_Point}$/u;
3893
+ function stringWidth$1(string, options$1 = {}) {
3894
+ if (typeof string !== "string" || string.length === 0) return 0;
3895
+ const { ambiguousIsNarrow = true, countAnsiEscapeCodes = false } = options$1;
3896
+ if (!countAnsiEscapeCodes) string = stripAnsi$1(string);
3897
+ if (string.length === 0) return 0;
3898
+ let width = 0;
3899
+ const eastAsianWidthOptions = { ambiguousAsWide: !ambiguousIsNarrow };
3900
+ for (const { segment: character } of segmenter.segment(string)) {
3901
+ const codePoint = character.codePointAt(0);
3902
+ if (codePoint <= 31 || codePoint >= 127 && codePoint <= 159) continue;
3903
+ if (codePoint >= 8203 && codePoint <= 8207 || codePoint === 65279) continue;
3904
+ if (codePoint >= 768 && codePoint <= 879 || codePoint >= 6832 && codePoint <= 6911 || codePoint >= 7616 && codePoint <= 7679 || codePoint >= 8400 && codePoint <= 8447 || codePoint >= 65056 && codePoint <= 65071) continue;
3905
+ if (codePoint >= 55296 && codePoint <= 57343) continue;
3906
+ if (codePoint >= 65024 && codePoint <= 65039) continue;
3907
+ if (defaultIgnorableCodePointRegex.test(character)) continue;
3908
+ if (emojiRegex().test(character)) {
3909
+ width += 2;
3910
+ continue;
3911
+ }
3912
+ width += eastAsianWidth(codePoint, eastAsianWidthOptions);
3913
+ }
3914
+ return width;
3915
+ }
3916
+ function isUnicodeSupported() {
3917
+ const { env: env$1 } = g$1;
3918
+ const { TERM, TERM_PROGRAM } = env$1;
3919
+ if (g$1.platform !== "win32") return TERM !== "linux";
3920
+ return Boolean(env$1.WT_SESSION) || Boolean(env$1.TERMINUS_SUBLIME) || env$1.ConEmuTask === "{cmd::Cmder}" || TERM_PROGRAM === "Terminus-Sublime" || TERM_PROGRAM === "vscode" || TERM === "xterm-256color" || TERM === "alacritty" || TERM === "rxvt-unicode" || TERM === "rxvt-unicode-256color" || env$1.TERMINAL_EMULATOR === "JetBrains-JediTerm";
3921
+ }
3922
+ const TYPE_COLOR_MAP = {
3923
+ info: "cyan",
3924
+ fail: "red",
3925
+ success: "green",
3926
+ ready: "green",
3927
+ start: "magenta"
3928
+ };
3929
+ const LEVEL_COLOR_MAP = {
3930
+ 0: "red",
3931
+ 1: "yellow"
3932
+ };
3933
+ const unicode = isUnicodeSupported();
3934
+ const s = (c$1, fallback) => unicode ? c$1 : fallback;
3935
+ const TYPE_ICONS = {
3936
+ error: s("✖", "×"),
3937
+ fatal: s("✖", "×"),
3938
+ ready: s("✔", "√"),
3939
+ warn: s("⚠", "‼"),
3940
+ info: s("ℹ", "i"),
3941
+ success: s("✔", "√"),
3942
+ debug: s("⚙", "D"),
3943
+ trace: s("→", "→"),
3944
+ fail: s("✖", "×"),
3945
+ start: s("◐", "o"),
3946
+ log: ""
3947
+ };
3948
+ function stringWidth(str) {
3949
+ if (!(typeof Intl === "object") || !Intl.Segmenter) return stripAnsi(str).length;
3950
+ return stringWidth$1(str);
3951
+ }
3952
+ var FancyReporter = class extends BasicReporter {
3953
+ formatStack(stack, message, opts) {
3954
+ const indent = " ".repeat((opts?.errorLevel || 0) + 1);
3955
+ return `
3956
+ ${indent}` + parseStack(stack, message).map((line) => " " + line.replace(/^at +/, (m) => colors.gray(m)).replace(/\((.+)\)/, (_$1, m) => `(${colors.cyan(m)})`)).join(`
3957
+ ${indent}`);
3958
+ }
3959
+ formatType(logObj, isBadge, opts) {
3960
+ const typeColor = TYPE_COLOR_MAP[logObj.type] || LEVEL_COLOR_MAP[logObj.level] || "gray";
3961
+ if (isBadge) return getBgColor(typeColor)(colors.black(` ${logObj.type.toUpperCase()} `));
3962
+ const _type = typeof TYPE_ICONS[logObj.type] === "string" ? TYPE_ICONS[logObj.type] : logObj.icon || logObj.type;
3963
+ return _type ? getColor(typeColor)(_type) : "";
3964
+ }
3965
+ formatLogObj(logObj, opts) {
3966
+ const [message, ...additional] = this.formatArgs(logObj.args, opts).split("\n");
3967
+ if (logObj.type === "box") return box(characterFormat(message + (additional.length > 0 ? "\n" + additional.join("\n") : "")), {
3968
+ title: logObj.title ? characterFormat(logObj.title) : void 0,
3969
+ style: logObj.style
3970
+ });
3971
+ const date = this.formatDate(logObj.date, opts);
3972
+ const coloredDate = date && colors.gray(date);
3973
+ const isBadge = logObj.badge ?? logObj.level < 2;
3974
+ const type = this.formatType(logObj, isBadge, opts);
3975
+ const tag = logObj.tag ? colors.gray(logObj.tag) : "";
3976
+ let line;
3977
+ const left = this.filterAndJoin([type, characterFormat(message)]);
3978
+ const right = this.filterAndJoin(opts.columns ? [tag, coloredDate] : [tag]);
3979
+ const space = (opts.columns || 0) - stringWidth(left) - stringWidth(right) - 2;
3980
+ line = space > 0 && (opts.columns || 0) >= 80 ? left + " ".repeat(space) + right : (right ? `${colors.gray(`[${right}]`)} ` : "") + left;
3981
+ line += characterFormat(additional.length > 0 ? "\n" + additional.join("\n") : "");
3982
+ if (logObj.type === "trace") {
3983
+ const _err = /* @__PURE__ */ new Error("Trace: " + logObj.message);
3984
+ line += this.formatStack(_err.stack || "", _err.message);
3985
+ }
3986
+ return isBadge ? "\n" + line + "\n" : line;
3987
+ }
3988
+ };
3989
+ function characterFormat(str) {
3990
+ return str.replace(/`([^`]+)`/gm, (_$1, m) => colors.cyan(m)).replace(/\s+_([^_]+)_\s+/gm, (_$1, m) => ` ${colors.underline(m)} `);
3991
+ }
3992
+ function getColor(color = "white") {
3993
+ return colors[color] || colors.white;
3994
+ }
3995
+ function getBgColor(color = "bgWhite") {
3996
+ return colors[`bg${color[0].toUpperCase()}${color.slice(1)}`] || colors.bgWhite;
3997
+ }
3998
+ function createConsola$1(options$1 = {}) {
3999
+ let level = _getDefaultLogLevel();
4000
+ if (process.env.CONSOLA_LEVEL) level = Number.parseInt(process.env.CONSOLA_LEVEL) ?? level;
4001
+ return createConsola({
4002
+ level,
4003
+ defaults: { level },
4004
+ stdout: process.stdout,
4005
+ stderr: process.stderr,
4006
+ prompt: (...args) => import("./prompt-DVcPfS2N.mjs").then((m) => m.prompt(...args)),
4007
+ reporters: options$1.reporters || [options$1.fancy ?? !(T || R) ? new FancyReporter() : new BasicReporter()],
4008
+ ...options$1
4009
+ });
4010
+ }
4011
+ function _getDefaultLogLevel() {
4012
+ if (g) return LogLevels.debug;
4013
+ if (R) return LogLevels.warn;
4014
+ return LogLevels.info;
4015
+ }
4016
+ const consola = createConsola$1();
4017
+
4018
+ //#endregion
4019
+ //#region scripts/migration/error.ts
4020
+ const getErrorMessage = (error) => {
4021
+ if (error instanceof Error) return error.message;
4022
+ if (typeof error === "string") return error;
4023
+ if (error && typeof error === "object" && "message" in error && typeof error.message === "string") return error.message;
4024
+ return "An unknown error occurred";
4025
+ };
4026
+
4027
+ //#endregion
4028
+ //#region scripts/migration/result.ts
4029
+ const RESULT_TYPE = {
4030
+ SUCCESS: "success",
4031
+ ERROR: "error"
4032
+ };
4033
+
4034
+ //#endregion
4035
+ //#region scripts/migration/exec-fix-command/index.ts
4036
+ const execEslintFixCommand = () => {
4037
+ try {
4038
+ execSync("npx eslint --fix", { stdio: "inherit" });
4039
+ return {
4040
+ type: RESULT_TYPE.SUCCESS,
4041
+ message: "ESLint fix completed successfully"
4042
+ };
4043
+ } catch (error) {
4044
+ if (!error) return {
4045
+ type: RESULT_TYPE.ERROR,
4046
+ message: `An unknown error occurred while running ESLint fix command
4047
+
4048
+ Please manually run 'npx eslint --fix' and check the configuration`
4049
+ };
4050
+ if (typeof error !== "object" || !("status" in error)) return {
4051
+ type: RESULT_TYPE.ERROR,
4052
+ message: `Failed to run ESLint fix command
4053
+ ${getErrorMessage(error)}
4054
+
4055
+ Please manually run 'npx eslint --fix' and check the configuration`
4056
+ };
4057
+ if (error.status === 1) return {
4058
+ type: RESULT_TYPE.SUCCESS,
4059
+ message: "ESLint fix found issues, some may require manual fixing"
4060
+ };
4061
+ return {
4062
+ type: RESULT_TYPE.ERROR,
4063
+ message: `Failed to run ESLint fix command
4064
+ ${getErrorMessage(error)}
4065
+
4066
+ Please manually run 'npx eslint --fix' and check the configuration`
4067
+ };
4068
+ }
4069
+ };
4070
+
4071
+ //#endregion
4072
+ //#region scripts/migration/migrate-eslint-config/index.ts
4073
+ const ESLINT_CONFIG_PATTERNS = [
4074
+ "eslint.config.mjs",
4075
+ "eslint.config.cjs",
4076
+ "eslint.config.js",
4077
+ "eslint.config.ts",
4078
+ "eslint.config.mts",
4079
+ "eslint.config.cts"
4080
+ ];
4081
+ const migrateEslintConfig = (projectRoot) => {
4082
+ const configFiles = findEslintConfigFiles(projectRoot);
4083
+ if (!configFiles.length) return {
4084
+ type: RESULT_TYPE.ERROR,
4085
+ message: "ESLint config files not found"
4086
+ };
4087
+ for (const configFile of configFiles) {
4088
+ const result = updateConfig(fs.readFileSync(configFile, "utf-8"));
4089
+ if (result.modified) fs.writeFileSync(configFile, result.content, "utf-8");
4090
+ }
4091
+ return { type: RESULT_TYPE.SUCCESS };
4092
+ };
4093
+ const findEslintConfigFiles = (projectRoot) => {
4094
+ return ESLINT_CONFIG_PATTERNS.reduce((acc, pattern) => {
4095
+ const filePath = path.join(projectRoot, pattern);
4096
+ return fs.existsSync(filePath) ? [...acc, filePath] : acc;
4097
+ }, []);
4098
+ };
4099
+ const updateConfig = (content) => {
4100
+ let modifiedContent = content;
4101
+ let modified = false;
4102
+ if (modifiedContent.includes("\"eslint-cdk-plugin\"")) {
4103
+ modifiedContent = modifiedContent.replace(/"eslint-cdk-plugin"/g, "\"eslint-plugin-awscdk\"");
4104
+ modified = true;
4105
+ }
4106
+ if (modifiedContent.includes("'eslint-cdk-plugin'")) {
4107
+ modifiedContent = modifiedContent.replace(/'eslint-cdk-plugin'/g, "'eslint-plugin-awscdk'");
4108
+ modified = true;
4109
+ }
4110
+ const pluginsPropertyRegex = /(\bplugins\s*:\s*\{[\s\S]*?\b)(cdk)(\s*:\s*[a-zA-Z_$])/g;
4111
+ if (modifiedContent.match(pluginsPropertyRegex)) {
4112
+ modifiedContent = modifiedContent.replace(pluginsPropertyRegex, "$1awscdk$3");
4113
+ modified = true;
4114
+ }
4115
+ if (modifiedContent.includes("\"cdk/")) {
4116
+ modifiedContent = modifiedContent.replace(/"cdk\//g, "\"awscdk/");
4117
+ modified = true;
4118
+ }
4119
+ if (modifiedContent.includes("'cdk/")) {
4120
+ modifiedContent = modifiedContent.replace(/'cdk\//g, "'awscdk/");
4121
+ modified = true;
4122
+ }
4123
+ return {
4124
+ content: modifiedContent,
4125
+ modified
4126
+ };
4127
+ };
4128
+
4129
+ //#endregion
4130
+ //#region scripts/migration/migrate-plugin/select-package-manager.ts
4131
+ const PACKAGE_MANGER = {
4132
+ NPM: "npm",
4133
+ YARN: "yarn",
4134
+ PNPM: "pnpm"
4135
+ };
4136
+ const PACKAGE_MANGER_VALUES = Object.values(PACKAGE_MANGER);
4137
+ /**
4138
+ * Select the package manager to use
4139
+ * - If options.packageManager is provided, validate it and return
4140
+ * - If not provided, prompt the user to select one
4141
+ */
4142
+ const selectPackageManager = async (options$1) => {
4143
+ if (!options$1.packageManager) {
4144
+ const res = await consola.prompt("Which package manager are you using?", {
4145
+ type: "select",
4146
+ options: [
4147
+ {
4148
+ label: PACKAGE_MANGER.NPM,
4149
+ value: PACKAGE_MANGER.NPM
4150
+ },
4151
+ {
4152
+ label: PACKAGE_MANGER.YARN,
4153
+ value: PACKAGE_MANGER.YARN
4154
+ },
4155
+ {
4156
+ label: PACKAGE_MANGER.PNPM,
4157
+ value: PACKAGE_MANGER.PNPM
4158
+ }
4159
+ ]
4160
+ });
4161
+ return {
4162
+ type: RESULT_TYPE.SUCCESS,
4163
+ value: res
4164
+ };
4165
+ }
4166
+ if (!PACKAGE_MANGER_VALUES.includes(options$1.packageManager)) return {
4167
+ type: RESULT_TYPE.ERROR,
4168
+ message: `Invalid package manager: ${options$1.packageManager}. Must be one of: ${PACKAGE_MANGER_VALUES.join(", ")}`
4169
+ };
4170
+ return {
4171
+ type: RESULT_TYPE.SUCCESS,
4172
+ value: options$1.packageManager
4173
+ };
4174
+ };
4175
+
4176
+ //#endregion
4177
+ //#region scripts/migration/migrate-plugin/install.ts
4178
+ const installPlugin = (packageManager) => {
4179
+ const command = (() => {
4180
+ switch (packageManager) {
4181
+ case PACKAGE_MANGER.NPM: return "npm install -D eslint-plugin-awscdk";
4182
+ case PACKAGE_MANGER.YARN: return "yarn add -D eslint-plugin-awscdk";
4183
+ case PACKAGE_MANGER.PNPM: return "pnpm install -D eslint-plugin-awscdk";
4184
+ }
4185
+ })();
4186
+ try {
4187
+ execSync(command, { stdio: "inherit" });
4188
+ return { type: RESULT_TYPE.SUCCESS };
4189
+ } catch (error) {
4190
+ return {
4191
+ type: RESULT_TYPE.ERROR,
4192
+ message: `Failed to install eslint-plugin-awscdk
4193
+ ${getErrorMessage(error)}`
4194
+ };
4195
+ }
4196
+ };
4197
+
4198
+ //#endregion
4199
+ //#region scripts/migration/migrate-plugin/uninstall.ts
4200
+ const uninstallPlugin = (packageManager, projectRoot) => {
4201
+ const packageJson = readPackageJson(projectRoot);
4202
+ if (packageJson.type === RESULT_TYPE.ERROR) return packageJson;
4203
+ const installTypes = checkPluginInstallation(packageJson.value);
4204
+ if (installTypes.type === RESULT_TYPE.ERROR) return installTypes;
4205
+ for (const installType of installTypes.value) {
4206
+ const result = uninstall(installType === "devDependencies", packageManager);
4207
+ if (result.type === RESULT_TYPE.ERROR) return result;
4208
+ }
4209
+ return { type: RESULT_TYPE.SUCCESS };
4210
+ };
4211
+ const uninstall = (isDev, packageManager) => {
4212
+ const command = (() => {
4213
+ const devFlag = isDev ? " -D" : "";
4214
+ switch (packageManager) {
4215
+ case PACKAGE_MANGER.NPM: return `npm uninstall${devFlag} eslint-cdk-plugin`;
4216
+ case PACKAGE_MANGER.YARN: return `yarn remove${devFlag} eslint-cdk-plugin`;
4217
+ case PACKAGE_MANGER.PNPM: return `pnpm remove${devFlag} eslint-cdk-plugin`;
4218
+ }
4219
+ })();
4220
+ try {
4221
+ execSync(command, { stdio: "inherit" });
4222
+ return { type: RESULT_TYPE.SUCCESS };
4223
+ } catch (error) {
4224
+ return {
4225
+ type: RESULT_TYPE.ERROR,
4226
+ message: `Failed to uninstall eslint-cdk-plugin
4227
+ ${getErrorMessage(error)}`
4228
+ };
4229
+ }
4230
+ };
4231
+ const readPackageJson = (projectRoot) => {
4232
+ const packageJsonPath = path.join(projectRoot, "package.json");
4233
+ if (!fs.existsSync(packageJsonPath)) return {
4234
+ type: RESULT_TYPE.ERROR,
4235
+ message: "package.json not found"
4236
+ };
4237
+ try {
4238
+ const content = fs.readFileSync(packageJsonPath, "utf-8");
4239
+ if (isPackageJson(JSON.parse(content))) return {
4240
+ type: RESULT_TYPE.SUCCESS,
4241
+ value: JSON.parse(content)
4242
+ };
4243
+ return {
4244
+ type: RESULT_TYPE.ERROR,
4245
+ message: "Invalid package.json format"
4246
+ };
4247
+ } catch (error) {
4248
+ return {
4249
+ type: RESULT_TYPE.ERROR,
4250
+ message: `Failed to read package.json
4251
+ ${getErrorMessage(error)}`
4252
+ };
4253
+ }
4254
+ };
4255
+ const checkPluginInstallation = (packageJson) => {
4256
+ const inDependencies = packageJson.dependencies?.["eslint-cdk-plugin"];
4257
+ const inDevDependencies = packageJson.devDependencies?.["eslint-cdk-plugin"];
4258
+ if (inDependencies && inDevDependencies) return {
4259
+ type: RESULT_TYPE.SUCCESS,
4260
+ value: ["devDependencies", "dependencies"]
4261
+ };
4262
+ if (inDevDependencies) return {
4263
+ type: RESULT_TYPE.SUCCESS,
4264
+ value: ["devDependencies"]
4265
+ };
4266
+ if (inDependencies) return {
4267
+ type: RESULT_TYPE.SUCCESS,
4268
+ value: ["dependencies"]
4269
+ };
4270
+ return {
4271
+ type: RESULT_TYPE.ERROR,
4272
+ message: "eslint-cdk-plugin is not installed"
4273
+ };
4274
+ };
4275
+ const isPackageJson = (arg) => {
4276
+ return typeof arg === "object" && arg !== null && ("dependencies" in arg && typeof arg.dependencies === "object" || "devDependencies" in arg && typeof arg.devDependencies === "object");
4277
+ };
4278
+
4279
+ //#endregion
4280
+ //#region scripts/migration/index.ts
4281
+ const program = new Command();
4282
+ program.name("migration").description("Migrate from eslint-cdk-plugin to eslint-plugin-awscdk").version("1.0.0").option("-p, --package-manager <manager>", `Specify package manager (${PACKAGE_MANGER_VALUES.join(", ")})`).parse(process.argv);
4283
+ const options = program.opts();
4284
+ const main = async () => {
4285
+ consola.box(`Starting migration from ${colorize("black", "eslint-cdk-plugin")} to ${colorize("green", "eslint-plugin-awscdk")}`);
4286
+ const projectRoot = process.cwd();
4287
+ const packageManager = await selectPackageManager(options);
4288
+ if (packageManager.type === RESULT_TYPE.ERROR) {
4289
+ consola.error(packageManager.message);
4290
+ process.exit(1);
4291
+ }
4292
+ const installResult = installPlugin(packageManager.value);
4293
+ if (installResult.type === RESULT_TYPE.ERROR) {
4294
+ consola.error(installResult.message);
4295
+ process.exit(1);
4296
+ }
4297
+ const migrateConfigResult = migrateEslintConfig(projectRoot);
4298
+ if (migrateConfigResult.type === RESULT_TYPE.ERROR) {
4299
+ consola.error(migrateConfigResult.message);
4300
+ process.exit(1);
4301
+ }
4302
+ const uninstallResult = uninstallPlugin(packageManager.value, projectRoot);
4303
+ if (uninstallResult.type === RESULT_TYPE.ERROR) {
4304
+ consola.error(uninstallResult.message);
4305
+ process.exit(1);
4306
+ }
4307
+ const migrateCommentsResult = execEslintFixCommand();
4308
+ if (migrateCommentsResult.type === RESULT_TYPE.ERROR) {
4309
+ consola.error(migrateCommentsResult.message);
4310
+ process.exit(1);
4311
+ }
4312
+ if (migrateCommentsResult.message) consola.warn(migrateCommentsResult.message);
4313
+ consola.success("All migration steps completed successfully!");
4314
+ };
4315
+ await main();
4316
+
4317
+ //#endregion
4318
+ export { };