create-tulip-app 0.6.1 → 0.8.2

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