@seedcord/cli 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs ADDED
@@ -0,0 +1,4198 @@
1
+ import { createRequire } from 'node:module';
2
+ import { relative, dirname, basename, extname, resolve, isAbsolute, join } from 'path';
3
+ import { pathToFileURL } from 'url';
4
+ import { SeedcordError, SeedcordErrorCode, isSeedcordError, Logger } from '@seedcord/services';
5
+ import { existsSync } from 'fs';
6
+ import { mkdir, writeFile, readdir, readFile } from 'fs/promises';
7
+ import { build } from 'tsup';
8
+ import ts2 from 'typescript';
9
+ import { createJiti } from 'jiti';
10
+ import { tsImport } from 'tsx/esm/api';
11
+
12
+ const require$1 = createRequire(import.meta.url);
13
+ var __create = Object.create;
14
+ var __defProp = Object.defineProperty;
15
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
16
+ var __getOwnPropNames = Object.getOwnPropertyNames;
17
+ var __getProtoOf = Object.getPrototypeOf;
18
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
19
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
20
+ var __require = /* @__PURE__ */ ((x) => typeof require$1 !== "undefined" ? require$1 : typeof Proxy !== "undefined" ? new Proxy(x, {
21
+ get: (a, b) => (typeof require$1 !== "undefined" ? require$1 : a)[b]
22
+ }) : x)(function(x) {
23
+ if (typeof require$1 !== "undefined") return require$1.apply(this, arguments);
24
+ throw Error('Dynamic require of "' + x + '" is not supported');
25
+ });
26
+ var __esm = (fn, res) => function __init() {
27
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
28
+ };
29
+ var __commonJS = (cb, mod) => function __require2() {
30
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
31
+ };
32
+ var __copyProps = (to, from, except, desc) => {
33
+ if (from && typeof from === "object" || typeof from === "function") {
34
+ for (let key of __getOwnPropNames(from))
35
+ if (!__hasOwnProp.call(to, key) && key !== except)
36
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
37
+ }
38
+ return to;
39
+ };
40
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
41
+ // If the importer is in node compatibility mode or this is not an ESM
42
+ // file that has been converted to a CommonJS file using a Babel-
43
+ // compatible transform (i.e. "__esModule" has not been set), then set
44
+ // "default" to the CommonJS "module.exports" for node compatibility.
45
+ __defProp(target, "default", { value: mod, enumerable: true }) ,
46
+ mod
47
+ ));
48
+ var init_esm_shims = __esm({
49
+ "../../node_modules/.pnpm/tsup@8.5.1_@swc+core@1.15.3_jiti@2.6.1_postcss@8.5.6_tsx@4.20.6_typescript@5.9.3_yaml@2.8.2/node_modules/tsup/assets/esm_shims.js"() {
50
+ }
51
+ });
52
+
53
+ // ../../node_modules/.pnpm/commander@14.0.2/node_modules/commander/lib/error.js
54
+ var require_error = __commonJS({
55
+ "../../node_modules/.pnpm/commander@14.0.2/node_modules/commander/lib/error.js"(exports$1) {
56
+ init_esm_shims();
57
+ var CommanderError = class CommanderError extends Error {
58
+ static {
59
+ __name(this, "CommanderError");
60
+ }
61
+ /**
62
+ * Constructs the CommanderError class
63
+ * @param {number} exitCode suggested exit code which could be used with process.exit
64
+ * @param {string} code an id string representing the error
65
+ * @param {string} message human-readable description of the error
66
+ */
67
+ constructor(exitCode, code, message) {
68
+ super(message);
69
+ Error.captureStackTrace(this, this.constructor);
70
+ this.name = this.constructor.name;
71
+ this.code = code;
72
+ this.exitCode = exitCode;
73
+ this.nestedError = void 0;
74
+ }
75
+ };
76
+ var InvalidArgumentError = class InvalidArgumentError extends CommanderError {
77
+ static {
78
+ __name(this, "InvalidArgumentError");
79
+ }
80
+ /**
81
+ * Constructs the InvalidArgumentError class
82
+ * @param {string} [message] explanation of why argument is invalid
83
+ */
84
+ constructor(message) {
85
+ super(1, "commander.invalidArgument", message);
86
+ Error.captureStackTrace(this, this.constructor);
87
+ this.name = this.constructor.name;
88
+ }
89
+ };
90
+ exports$1.CommanderError = CommanderError;
91
+ exports$1.InvalidArgumentError = InvalidArgumentError;
92
+ }
93
+ });
94
+
95
+ // ../../node_modules/.pnpm/commander@14.0.2/node_modules/commander/lib/argument.js
96
+ var require_argument = __commonJS({
97
+ "../../node_modules/.pnpm/commander@14.0.2/node_modules/commander/lib/argument.js"(exports$1) {
98
+ init_esm_shims();
99
+ var { InvalidArgumentError } = require_error();
100
+ var Argument = class Argument {
101
+ static {
102
+ __name(this, "Argument");
103
+ }
104
+ /**
105
+ * Initialize a new command argument with the given name and description.
106
+ * The default is that the argument is required, and you can explicitly
107
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
108
+ *
109
+ * @param {string} name
110
+ * @param {string} [description]
111
+ */
112
+ constructor(name, description) {
113
+ this.description = description || "";
114
+ this.variadic = false;
115
+ this.parseArg = void 0;
116
+ this.defaultValue = void 0;
117
+ this.defaultValueDescription = void 0;
118
+ this.argChoices = void 0;
119
+ switch (name[0]) {
120
+ case "<":
121
+ this.required = true;
122
+ this._name = name.slice(1, -1);
123
+ break;
124
+ case "[":
125
+ this.required = false;
126
+ this._name = name.slice(1, -1);
127
+ break;
128
+ default:
129
+ this.required = true;
130
+ this._name = name;
131
+ break;
132
+ }
133
+ if (this._name.endsWith("...")) {
134
+ this.variadic = true;
135
+ this._name = this._name.slice(0, -3);
136
+ }
137
+ }
138
+ /**
139
+ * Return argument name.
140
+ *
141
+ * @return {string}
142
+ */
143
+ name() {
144
+ return this._name;
145
+ }
146
+ /**
147
+ * @package
148
+ */
149
+ _collectValue(value, previous) {
150
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
151
+ return [
152
+ value
153
+ ];
154
+ }
155
+ previous.push(value);
156
+ return previous;
157
+ }
158
+ /**
159
+ * Set the default value, and optionally supply the description to be displayed in the help.
160
+ *
161
+ * @param {*} value
162
+ * @param {string} [description]
163
+ * @return {Argument}
164
+ */
165
+ default(value, description) {
166
+ this.defaultValue = value;
167
+ this.defaultValueDescription = description;
168
+ return this;
169
+ }
170
+ /**
171
+ * Set the custom handler for processing CLI command arguments into argument values.
172
+ *
173
+ * @param {Function} [fn]
174
+ * @return {Argument}
175
+ */
176
+ argParser(fn) {
177
+ this.parseArg = fn;
178
+ return this;
179
+ }
180
+ /**
181
+ * Only allow argument value to be one of choices.
182
+ *
183
+ * @param {string[]} values
184
+ * @return {Argument}
185
+ */
186
+ choices(values) {
187
+ this.argChoices = values.slice();
188
+ this.parseArg = (arg, previous) => {
189
+ if (!this.argChoices.includes(arg)) {
190
+ throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
191
+ }
192
+ if (this.variadic) {
193
+ return this._collectValue(arg, previous);
194
+ }
195
+ return arg;
196
+ };
197
+ return this;
198
+ }
199
+ /**
200
+ * Make argument required.
201
+ *
202
+ * @returns {Argument}
203
+ */
204
+ argRequired() {
205
+ this.required = true;
206
+ return this;
207
+ }
208
+ /**
209
+ * Make argument optional.
210
+ *
211
+ * @returns {Argument}
212
+ */
213
+ argOptional() {
214
+ this.required = false;
215
+ return this;
216
+ }
217
+ };
218
+ function humanReadableArgName(arg) {
219
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
220
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
221
+ }
222
+ __name(humanReadableArgName, "humanReadableArgName");
223
+ exports$1.Argument = Argument;
224
+ exports$1.humanReadableArgName = humanReadableArgName;
225
+ }
226
+ });
227
+
228
+ // ../../node_modules/.pnpm/commander@14.0.2/node_modules/commander/lib/help.js
229
+ var require_help = __commonJS({
230
+ "../../node_modules/.pnpm/commander@14.0.2/node_modules/commander/lib/help.js"(exports$1) {
231
+ init_esm_shims();
232
+ var { humanReadableArgName } = require_argument();
233
+ var Help = class Help {
234
+ static {
235
+ __name(this, "Help");
236
+ }
237
+ constructor() {
238
+ this.helpWidth = void 0;
239
+ this.minWidthToWrap = 40;
240
+ this.sortSubcommands = false;
241
+ this.sortOptions = false;
242
+ this.showGlobalOptions = false;
243
+ }
244
+ /**
245
+ * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
246
+ * and just before calling `formatHelp()`.
247
+ *
248
+ * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
249
+ *
250
+ * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
251
+ */
252
+ prepareContext(contextOptions) {
253
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
254
+ }
255
+ /**
256
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
257
+ *
258
+ * @param {Command} cmd
259
+ * @returns {Command[]}
260
+ */
261
+ visibleCommands(cmd) {
262
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
263
+ const helpCommand = cmd._getHelpCommand();
264
+ if (helpCommand && !helpCommand._hidden) {
265
+ visibleCommands.push(helpCommand);
266
+ }
267
+ if (this.sortSubcommands) {
268
+ visibleCommands.sort((a, b) => {
269
+ return a.name().localeCompare(b.name());
270
+ });
271
+ }
272
+ return visibleCommands;
273
+ }
274
+ /**
275
+ * Compare options for sort.
276
+ *
277
+ * @param {Option} a
278
+ * @param {Option} b
279
+ * @returns {number}
280
+ */
281
+ compareOptions(a, b) {
282
+ const getSortKey = /* @__PURE__ */ __name((option) => {
283
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
284
+ }, "getSortKey");
285
+ return getSortKey(a).localeCompare(getSortKey(b));
286
+ }
287
+ /**
288
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
289
+ *
290
+ * @param {Command} cmd
291
+ * @returns {Option[]}
292
+ */
293
+ visibleOptions(cmd) {
294
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
295
+ const helpOption = cmd._getHelpOption();
296
+ if (helpOption && !helpOption.hidden) {
297
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
298
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
299
+ if (!removeShort && !removeLong) {
300
+ visibleOptions.push(helpOption);
301
+ } else if (helpOption.long && !removeLong) {
302
+ visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
303
+ } else if (helpOption.short && !removeShort) {
304
+ visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
305
+ }
306
+ }
307
+ if (this.sortOptions) {
308
+ visibleOptions.sort(this.compareOptions);
309
+ }
310
+ return visibleOptions;
311
+ }
312
+ /**
313
+ * Get an array of the visible global options. (Not including help.)
314
+ *
315
+ * @param {Command} cmd
316
+ * @returns {Option[]}
317
+ */
318
+ visibleGlobalOptions(cmd) {
319
+ if (!this.showGlobalOptions) return [];
320
+ const globalOptions = [];
321
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
322
+ const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
323
+ globalOptions.push(...visibleOptions);
324
+ }
325
+ if (this.sortOptions) {
326
+ globalOptions.sort(this.compareOptions);
327
+ }
328
+ return globalOptions;
329
+ }
330
+ /**
331
+ * Get an array of the arguments if any have a description.
332
+ *
333
+ * @param {Command} cmd
334
+ * @returns {Argument[]}
335
+ */
336
+ visibleArguments(cmd) {
337
+ if (cmd._argsDescription) {
338
+ cmd.registeredArguments.forEach((argument) => {
339
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
340
+ });
341
+ }
342
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
343
+ return cmd.registeredArguments;
344
+ }
345
+ return [];
346
+ }
347
+ /**
348
+ * Get the command term to show in the list of subcommands.
349
+ *
350
+ * @param {Command} cmd
351
+ * @returns {string}
352
+ */
353
+ subcommandTerm(cmd) {
354
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
355
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
356
+ (args ? " " + args : "");
357
+ }
358
+ /**
359
+ * Get the option term to show in the list of options.
360
+ *
361
+ * @param {Option} option
362
+ * @returns {string}
363
+ */
364
+ optionTerm(option) {
365
+ return option.flags;
366
+ }
367
+ /**
368
+ * Get the argument term to show in the list of arguments.
369
+ *
370
+ * @param {Argument} argument
371
+ * @returns {string}
372
+ */
373
+ argumentTerm(argument) {
374
+ return argument.name();
375
+ }
376
+ /**
377
+ * Get the longest command term length.
378
+ *
379
+ * @param {Command} cmd
380
+ * @param {Help} helper
381
+ * @returns {number}
382
+ */
383
+ longestSubcommandTermLength(cmd, helper) {
384
+ return helper.visibleCommands(cmd).reduce((max, command) => {
385
+ return Math.max(max, this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command))));
386
+ }, 0);
387
+ }
388
+ /**
389
+ * Get the longest option term length.
390
+ *
391
+ * @param {Command} cmd
392
+ * @param {Help} helper
393
+ * @returns {number}
394
+ */
395
+ longestOptionTermLength(cmd, helper) {
396
+ return helper.visibleOptions(cmd).reduce((max, option) => {
397
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
398
+ }, 0);
399
+ }
400
+ /**
401
+ * Get the longest global option term length.
402
+ *
403
+ * @param {Command} cmd
404
+ * @param {Help} helper
405
+ * @returns {number}
406
+ */
407
+ longestGlobalOptionTermLength(cmd, helper) {
408
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
409
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
410
+ }, 0);
411
+ }
412
+ /**
413
+ * Get the longest argument term length.
414
+ *
415
+ * @param {Command} cmd
416
+ * @param {Help} helper
417
+ * @returns {number}
418
+ */
419
+ longestArgumentTermLength(cmd, helper) {
420
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
421
+ return Math.max(max, this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument))));
422
+ }, 0);
423
+ }
424
+ /**
425
+ * Get the command usage to be displayed at the top of the built-in help.
426
+ *
427
+ * @param {Command} cmd
428
+ * @returns {string}
429
+ */
430
+ commandUsage(cmd) {
431
+ let cmdName = cmd._name;
432
+ if (cmd._aliases[0]) {
433
+ cmdName = cmdName + "|" + cmd._aliases[0];
434
+ }
435
+ let ancestorCmdNames = "";
436
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
437
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
438
+ }
439
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
440
+ }
441
+ /**
442
+ * Get the description for the command.
443
+ *
444
+ * @param {Command} cmd
445
+ * @returns {string}
446
+ */
447
+ commandDescription(cmd) {
448
+ return cmd.description();
449
+ }
450
+ /**
451
+ * Get the subcommand summary to show in the list of subcommands.
452
+ * (Fallback to description for backwards compatibility.)
453
+ *
454
+ * @param {Command} cmd
455
+ * @returns {string}
456
+ */
457
+ subcommandDescription(cmd) {
458
+ return cmd.summary() || cmd.description();
459
+ }
460
+ /**
461
+ * Get the option description to show in the list of options.
462
+ *
463
+ * @param {Option} option
464
+ * @return {string}
465
+ */
466
+ optionDescription(option) {
467
+ const extraInfo = [];
468
+ if (option.argChoices) {
469
+ extraInfo.push(
470
+ // use stringify to match the display of the default value
471
+ `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
472
+ );
473
+ }
474
+ if (option.defaultValue !== void 0) {
475
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
476
+ if (showDefault) {
477
+ extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
478
+ }
479
+ }
480
+ if (option.presetArg !== void 0 && option.optional) {
481
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
482
+ }
483
+ if (option.envVar !== void 0) {
484
+ extraInfo.push(`env: ${option.envVar}`);
485
+ }
486
+ if (extraInfo.length > 0) {
487
+ const extraDescription = `(${extraInfo.join(", ")})`;
488
+ if (option.description) {
489
+ return `${option.description} ${extraDescription}`;
490
+ }
491
+ return extraDescription;
492
+ }
493
+ return option.description;
494
+ }
495
+ /**
496
+ * Get the argument description to show in the list of arguments.
497
+ *
498
+ * @param {Argument} argument
499
+ * @return {string}
500
+ */
501
+ argumentDescription(argument) {
502
+ const extraInfo = [];
503
+ if (argument.argChoices) {
504
+ extraInfo.push(
505
+ // use stringify to match the display of the default value
506
+ `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
507
+ );
508
+ }
509
+ if (argument.defaultValue !== void 0) {
510
+ extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
511
+ }
512
+ if (extraInfo.length > 0) {
513
+ const extraDescription = `(${extraInfo.join(", ")})`;
514
+ if (argument.description) {
515
+ return `${argument.description} ${extraDescription}`;
516
+ }
517
+ return extraDescription;
518
+ }
519
+ return argument.description;
520
+ }
521
+ /**
522
+ * Format a list of items, given a heading and an array of formatted items.
523
+ *
524
+ * @param {string} heading
525
+ * @param {string[]} items
526
+ * @param {Help} helper
527
+ * @returns string[]
528
+ */
529
+ formatItemList(heading, items, helper) {
530
+ if (items.length === 0) return [];
531
+ return [
532
+ helper.styleTitle(heading),
533
+ ...items,
534
+ ""
535
+ ];
536
+ }
537
+ /**
538
+ * Group items by their help group heading.
539
+ *
540
+ * @param {Command[] | Option[]} unsortedItems
541
+ * @param {Command[] | Option[]} visibleItems
542
+ * @param {Function} getGroup
543
+ * @returns {Map<string, Command[] | Option[]>}
544
+ */
545
+ groupItems(unsortedItems, visibleItems, getGroup) {
546
+ const result = /* @__PURE__ */ new Map();
547
+ unsortedItems.forEach((item) => {
548
+ const group = getGroup(item);
549
+ if (!result.has(group)) result.set(group, []);
550
+ });
551
+ visibleItems.forEach((item) => {
552
+ const group = getGroup(item);
553
+ if (!result.has(group)) {
554
+ result.set(group, []);
555
+ }
556
+ result.get(group).push(item);
557
+ });
558
+ return result;
559
+ }
560
+ /**
561
+ * Generate the built-in help text.
562
+ *
563
+ * @param {Command} cmd
564
+ * @param {Help} helper
565
+ * @returns {string}
566
+ */
567
+ formatHelp(cmd, helper) {
568
+ const termWidth = helper.padWidth(cmd, helper);
569
+ const helpWidth = helper.helpWidth ?? 80;
570
+ function callFormatItem(term, description) {
571
+ return helper.formatItem(term, termWidth, description, helper);
572
+ }
573
+ __name(callFormatItem, "callFormatItem");
574
+ let output = [
575
+ `${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
576
+ ""
577
+ ];
578
+ const commandDescription = helper.commandDescription(cmd);
579
+ if (commandDescription.length > 0) {
580
+ output = output.concat([
581
+ helper.boxWrap(helper.styleCommandDescription(commandDescription), helpWidth),
582
+ ""
583
+ ]);
584
+ }
585
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
586
+ return callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)), helper.styleArgumentDescription(helper.argumentDescription(argument)));
587
+ });
588
+ output = output.concat(this.formatItemList("Arguments:", argumentList, helper));
589
+ const optionGroups = this.groupItems(cmd.options, helper.visibleOptions(cmd), (option) => option.helpGroupHeading ?? "Options:");
590
+ optionGroups.forEach((options, group) => {
591
+ const optionList = options.map((option) => {
592
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
593
+ });
594
+ output = output.concat(this.formatItemList(group, optionList, helper));
595
+ });
596
+ if (helper.showGlobalOptions) {
597
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
598
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
599
+ });
600
+ output = output.concat(this.formatItemList("Global Options:", globalOptionList, helper));
601
+ }
602
+ const commandGroups = this.groupItems(cmd.commands, helper.visibleCommands(cmd), (sub) => sub.helpGroup() || "Commands:");
603
+ commandGroups.forEach((commands, group) => {
604
+ const commandList = commands.map((sub) => {
605
+ return callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(sub)), helper.styleSubcommandDescription(helper.subcommandDescription(sub)));
606
+ });
607
+ output = output.concat(this.formatItemList(group, commandList, helper));
608
+ });
609
+ return output.join("\n");
610
+ }
611
+ /**
612
+ * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
613
+ *
614
+ * @param {string} str
615
+ * @returns {number}
616
+ */
617
+ displayWidth(str) {
618
+ return stripColor(str).length;
619
+ }
620
+ /**
621
+ * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
622
+ *
623
+ * @param {string} str
624
+ * @returns {string}
625
+ */
626
+ styleTitle(str) {
627
+ return str;
628
+ }
629
+ styleUsage(str) {
630
+ return str.split(" ").map((word) => {
631
+ if (word === "[options]") return this.styleOptionText(word);
632
+ if (word === "[command]") return this.styleSubcommandText(word);
633
+ if (word[0] === "[" || word[0] === "<") return this.styleArgumentText(word);
634
+ return this.styleCommandText(word);
635
+ }).join(" ");
636
+ }
637
+ styleCommandDescription(str) {
638
+ return this.styleDescriptionText(str);
639
+ }
640
+ styleOptionDescription(str) {
641
+ return this.styleDescriptionText(str);
642
+ }
643
+ styleSubcommandDescription(str) {
644
+ return this.styleDescriptionText(str);
645
+ }
646
+ styleArgumentDescription(str) {
647
+ return this.styleDescriptionText(str);
648
+ }
649
+ styleDescriptionText(str) {
650
+ return str;
651
+ }
652
+ styleOptionTerm(str) {
653
+ return this.styleOptionText(str);
654
+ }
655
+ styleSubcommandTerm(str) {
656
+ return str.split(" ").map((word) => {
657
+ if (word === "[options]") return this.styleOptionText(word);
658
+ if (word[0] === "[" || word[0] === "<") return this.styleArgumentText(word);
659
+ return this.styleSubcommandText(word);
660
+ }).join(" ");
661
+ }
662
+ styleArgumentTerm(str) {
663
+ return this.styleArgumentText(str);
664
+ }
665
+ styleOptionText(str) {
666
+ return str;
667
+ }
668
+ styleArgumentText(str) {
669
+ return str;
670
+ }
671
+ styleSubcommandText(str) {
672
+ return str;
673
+ }
674
+ styleCommandText(str) {
675
+ return str;
676
+ }
677
+ /**
678
+ * Calculate the pad width from the maximum term length.
679
+ *
680
+ * @param {Command} cmd
681
+ * @param {Help} helper
682
+ * @returns {number}
683
+ */
684
+ padWidth(cmd, helper) {
685
+ return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
686
+ }
687
+ /**
688
+ * Detect manually wrapped and indented strings by checking for line break followed by whitespace.
689
+ *
690
+ * @param {string} str
691
+ * @returns {boolean}
692
+ */
693
+ preformatted(str) {
694
+ return /\n[^\S\r\n]/.test(str);
695
+ }
696
+ /**
697
+ * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
698
+ *
699
+ * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
700
+ * TTT DDD DDDD
701
+ * DD DDD
702
+ *
703
+ * @param {string} term
704
+ * @param {number} termWidth
705
+ * @param {string} description
706
+ * @param {Help} helper
707
+ * @returns {string}
708
+ */
709
+ formatItem(term, termWidth, description, helper) {
710
+ const itemIndent = 2;
711
+ const itemIndentStr = " ".repeat(itemIndent);
712
+ if (!description) return itemIndentStr + term;
713
+ const paddedTerm = term.padEnd(termWidth + term.length - helper.displayWidth(term));
714
+ const spacerWidth = 2;
715
+ const helpWidth = this.helpWidth ?? 80;
716
+ const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
717
+ let formattedDescription;
718
+ if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
719
+ formattedDescription = description;
720
+ } else {
721
+ const wrappedDescription = helper.boxWrap(description, remainingWidth);
722
+ formattedDescription = wrappedDescription.replace(/\n/g, "\n" + " ".repeat(termWidth + spacerWidth));
723
+ }
724
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
725
+ ${itemIndentStr}`);
726
+ }
727
+ /**
728
+ * Wrap a string at whitespace, preserving existing line breaks.
729
+ * Wrapping is skipped if the width is less than `minWidthToWrap`.
730
+ *
731
+ * @param {string} str
732
+ * @param {number} width
733
+ * @returns {string}
734
+ */
735
+ boxWrap(str, width) {
736
+ if (width < this.minWidthToWrap) return str;
737
+ const rawLines = str.split(/\r\n|\n/);
738
+ const chunkPattern = /[\s]*[^\s]+/g;
739
+ const wrappedLines = [];
740
+ rawLines.forEach((line) => {
741
+ const chunks = line.match(chunkPattern);
742
+ if (chunks === null) {
743
+ wrappedLines.push("");
744
+ return;
745
+ }
746
+ let sumChunks = [
747
+ chunks.shift()
748
+ ];
749
+ let sumWidth = this.displayWidth(sumChunks[0]);
750
+ chunks.forEach((chunk) => {
751
+ const visibleWidth = this.displayWidth(chunk);
752
+ if (sumWidth + visibleWidth <= width) {
753
+ sumChunks.push(chunk);
754
+ sumWidth += visibleWidth;
755
+ return;
756
+ }
757
+ wrappedLines.push(sumChunks.join(""));
758
+ const nextChunk = chunk.trimStart();
759
+ sumChunks = [
760
+ nextChunk
761
+ ];
762
+ sumWidth = this.displayWidth(nextChunk);
763
+ });
764
+ wrappedLines.push(sumChunks.join(""));
765
+ });
766
+ return wrappedLines.join("\n");
767
+ }
768
+ };
769
+ function stripColor(str) {
770
+ const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
771
+ return str.replace(sgrPattern, "");
772
+ }
773
+ __name(stripColor, "stripColor");
774
+ exports$1.Help = Help;
775
+ exports$1.stripColor = stripColor;
776
+ }
777
+ });
778
+
779
+ // ../../node_modules/.pnpm/commander@14.0.2/node_modules/commander/lib/option.js
780
+ var require_option = __commonJS({
781
+ "../../node_modules/.pnpm/commander@14.0.2/node_modules/commander/lib/option.js"(exports$1) {
782
+ init_esm_shims();
783
+ var { InvalidArgumentError } = require_error();
784
+ var Option = class Option {
785
+ static {
786
+ __name(this, "Option");
787
+ }
788
+ /**
789
+ * Initialize a new `Option` with the given `flags` and `description`.
790
+ *
791
+ * @param {string} flags
792
+ * @param {string} [description]
793
+ */
794
+ constructor(flags, description) {
795
+ this.flags = flags;
796
+ this.description = description || "";
797
+ this.required = flags.includes("<");
798
+ this.optional = flags.includes("[");
799
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
800
+ this.mandatory = false;
801
+ const optionFlags = splitOptionFlags(flags);
802
+ this.short = optionFlags.shortFlag;
803
+ this.long = optionFlags.longFlag;
804
+ this.negate = false;
805
+ if (this.long) {
806
+ this.negate = this.long.startsWith("--no-");
807
+ }
808
+ this.defaultValue = void 0;
809
+ this.defaultValueDescription = void 0;
810
+ this.presetArg = void 0;
811
+ this.envVar = void 0;
812
+ this.parseArg = void 0;
813
+ this.hidden = false;
814
+ this.argChoices = void 0;
815
+ this.conflictsWith = [];
816
+ this.implied = void 0;
817
+ this.helpGroupHeading = void 0;
818
+ }
819
+ /**
820
+ * Set the default value, and optionally supply the description to be displayed in the help.
821
+ *
822
+ * @param {*} value
823
+ * @param {string} [description]
824
+ * @return {Option}
825
+ */
826
+ default(value, description) {
827
+ this.defaultValue = value;
828
+ this.defaultValueDescription = description;
829
+ return this;
830
+ }
831
+ /**
832
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
833
+ * The custom processing (parseArg) is called.
834
+ *
835
+ * @example
836
+ * new Option('--color').default('GREYSCALE').preset('RGB');
837
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
838
+ *
839
+ * @param {*} arg
840
+ * @return {Option}
841
+ */
842
+ preset(arg) {
843
+ this.presetArg = arg;
844
+ return this;
845
+ }
846
+ /**
847
+ * Add option name(s) that conflict with this option.
848
+ * An error will be displayed if conflicting options are found during parsing.
849
+ *
850
+ * @example
851
+ * new Option('--rgb').conflicts('cmyk');
852
+ * new Option('--js').conflicts(['ts', 'jsx']);
853
+ *
854
+ * @param {(string | string[])} names
855
+ * @return {Option}
856
+ */
857
+ conflicts(names) {
858
+ this.conflictsWith = this.conflictsWith.concat(names);
859
+ return this;
860
+ }
861
+ /**
862
+ * Specify implied option values for when this option is set and the implied options are not.
863
+ *
864
+ * The custom processing (parseArg) is not called on the implied values.
865
+ *
866
+ * @example
867
+ * program
868
+ * .addOption(new Option('--log', 'write logging information to file'))
869
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
870
+ *
871
+ * @param {object} impliedOptionValues
872
+ * @return {Option}
873
+ */
874
+ implies(impliedOptionValues) {
875
+ let newImplied = impliedOptionValues;
876
+ if (typeof impliedOptionValues === "string") {
877
+ newImplied = {
878
+ [impliedOptionValues]: true
879
+ };
880
+ }
881
+ this.implied = Object.assign(this.implied || {}, newImplied);
882
+ return this;
883
+ }
884
+ /**
885
+ * Set environment variable to check for option value.
886
+ *
887
+ * An environment variable is only used if when processed the current option value is
888
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
889
+ *
890
+ * @param {string} name
891
+ * @return {Option}
892
+ */
893
+ env(name) {
894
+ this.envVar = name;
895
+ return this;
896
+ }
897
+ /**
898
+ * Set the custom handler for processing CLI option arguments into option values.
899
+ *
900
+ * @param {Function} [fn]
901
+ * @return {Option}
902
+ */
903
+ argParser(fn) {
904
+ this.parseArg = fn;
905
+ return this;
906
+ }
907
+ /**
908
+ * Whether the option is mandatory and must have a value after parsing.
909
+ *
910
+ * @param {boolean} [mandatory=true]
911
+ * @return {Option}
912
+ */
913
+ makeOptionMandatory(mandatory = true) {
914
+ this.mandatory = !!mandatory;
915
+ return this;
916
+ }
917
+ /**
918
+ * Hide option in help.
919
+ *
920
+ * @param {boolean} [hide=true]
921
+ * @return {Option}
922
+ */
923
+ hideHelp(hide = true) {
924
+ this.hidden = !!hide;
925
+ return this;
926
+ }
927
+ /**
928
+ * @package
929
+ */
930
+ _collectValue(value, previous) {
931
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
932
+ return [
933
+ value
934
+ ];
935
+ }
936
+ previous.push(value);
937
+ return previous;
938
+ }
939
+ /**
940
+ * Only allow option value to be one of choices.
941
+ *
942
+ * @param {string[]} values
943
+ * @return {Option}
944
+ */
945
+ choices(values) {
946
+ this.argChoices = values.slice();
947
+ this.parseArg = (arg, previous) => {
948
+ if (!this.argChoices.includes(arg)) {
949
+ throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
950
+ }
951
+ if (this.variadic) {
952
+ return this._collectValue(arg, previous);
953
+ }
954
+ return arg;
955
+ };
956
+ return this;
957
+ }
958
+ /**
959
+ * Return option name.
960
+ *
961
+ * @return {string}
962
+ */
963
+ name() {
964
+ if (this.long) {
965
+ return this.long.replace(/^--/, "");
966
+ }
967
+ return this.short.replace(/^-/, "");
968
+ }
969
+ /**
970
+ * Return option name, in a camelcase format that can be used
971
+ * as an object attribute key.
972
+ *
973
+ * @return {string}
974
+ */
975
+ attributeName() {
976
+ if (this.negate) {
977
+ return camelcase(this.name().replace(/^no-/, ""));
978
+ }
979
+ return camelcase(this.name());
980
+ }
981
+ /**
982
+ * Set the help group heading.
983
+ *
984
+ * @param {string} heading
985
+ * @return {Option}
986
+ */
987
+ helpGroup(heading) {
988
+ this.helpGroupHeading = heading;
989
+ return this;
990
+ }
991
+ /**
992
+ * Check if `arg` matches the short or long flag.
993
+ *
994
+ * @param {string} arg
995
+ * @return {boolean}
996
+ * @package
997
+ */
998
+ is(arg) {
999
+ return this.short === arg || this.long === arg;
1000
+ }
1001
+ /**
1002
+ * Return whether a boolean option.
1003
+ *
1004
+ * Options are one of boolean, negated, required argument, or optional argument.
1005
+ *
1006
+ * @return {boolean}
1007
+ * @package
1008
+ */
1009
+ isBoolean() {
1010
+ return !this.required && !this.optional && !this.negate;
1011
+ }
1012
+ };
1013
+ var DualOptions = class DualOptions {
1014
+ static {
1015
+ __name(this, "DualOptions");
1016
+ }
1017
+ /**
1018
+ * @param {Option[]} options
1019
+ */
1020
+ constructor(options) {
1021
+ this.positiveOptions = /* @__PURE__ */ new Map();
1022
+ this.negativeOptions = /* @__PURE__ */ new Map();
1023
+ this.dualOptions = /* @__PURE__ */ new Set();
1024
+ options.forEach((option) => {
1025
+ if (option.negate) {
1026
+ this.negativeOptions.set(option.attributeName(), option);
1027
+ } else {
1028
+ this.positiveOptions.set(option.attributeName(), option);
1029
+ }
1030
+ });
1031
+ this.negativeOptions.forEach((value, key) => {
1032
+ if (this.positiveOptions.has(key)) {
1033
+ this.dualOptions.add(key);
1034
+ }
1035
+ });
1036
+ }
1037
+ /**
1038
+ * Did the value come from the option, and not from possible matching dual option?
1039
+ *
1040
+ * @param {*} value
1041
+ * @param {Option} option
1042
+ * @returns {boolean}
1043
+ */
1044
+ valueFromOption(value, option) {
1045
+ const optionKey = option.attributeName();
1046
+ if (!this.dualOptions.has(optionKey)) return true;
1047
+ const preset = this.negativeOptions.get(optionKey).presetArg;
1048
+ const negativeValue = preset !== void 0 ? preset : false;
1049
+ return option.negate === (negativeValue === value);
1050
+ }
1051
+ };
1052
+ function camelcase(str) {
1053
+ return str.split("-").reduce((str2, word) => {
1054
+ return str2 + word[0].toUpperCase() + word.slice(1);
1055
+ });
1056
+ }
1057
+ __name(camelcase, "camelcase");
1058
+ function splitOptionFlags(flags) {
1059
+ let shortFlag;
1060
+ let longFlag;
1061
+ const shortFlagExp = /^-[^-]$/;
1062
+ const longFlagExp = /^--[^-]/;
1063
+ const flagParts = flags.split(/[ |,]+/).concat("guard");
1064
+ if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
1065
+ if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
1066
+ if (!shortFlag && shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
1067
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
1068
+ shortFlag = longFlag;
1069
+ longFlag = flagParts.shift();
1070
+ }
1071
+ if (flagParts[0].startsWith("-")) {
1072
+ const unsupportedFlag = flagParts[0];
1073
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
1074
+ if (/^-[^-][^-]/.test(unsupportedFlag)) throw new Error(`${baseError}
1075
+ - a short flag is a single dash and a single character
1076
+ - either use a single dash and a single character (for a short flag)
1077
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);
1078
+ if (shortFlagExp.test(unsupportedFlag)) throw new Error(`${baseError}
1079
+ - too many short flags`);
1080
+ if (longFlagExp.test(unsupportedFlag)) throw new Error(`${baseError}
1081
+ - too many long flags`);
1082
+ throw new Error(`${baseError}
1083
+ - unrecognised flag format`);
1084
+ }
1085
+ if (shortFlag === void 0 && longFlag === void 0) throw new Error(`option creation failed due to no flags found in '${flags}'.`);
1086
+ return {
1087
+ shortFlag,
1088
+ longFlag
1089
+ };
1090
+ }
1091
+ __name(splitOptionFlags, "splitOptionFlags");
1092
+ exports$1.Option = Option;
1093
+ exports$1.DualOptions = DualOptions;
1094
+ }
1095
+ });
1096
+
1097
+ // ../../node_modules/.pnpm/commander@14.0.2/node_modules/commander/lib/suggestSimilar.js
1098
+ var require_suggestSimilar = __commonJS({
1099
+ "../../node_modules/.pnpm/commander@14.0.2/node_modules/commander/lib/suggestSimilar.js"(exports$1) {
1100
+ init_esm_shims();
1101
+ var maxDistance = 3;
1102
+ function editDistance(a, b) {
1103
+ if (Math.abs(a.length - b.length) > maxDistance) return Math.max(a.length, b.length);
1104
+ const d = [];
1105
+ for (let i = 0; i <= a.length; i++) {
1106
+ d[i] = [
1107
+ i
1108
+ ];
1109
+ }
1110
+ for (let j = 0; j <= b.length; j++) {
1111
+ d[0][j] = j;
1112
+ }
1113
+ for (let j = 1; j <= b.length; j++) {
1114
+ for (let i = 1; i <= a.length; i++) {
1115
+ let cost = 1;
1116
+ if (a[i - 1] === b[j - 1]) {
1117
+ cost = 0;
1118
+ } else {
1119
+ cost = 1;
1120
+ }
1121
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
1122
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
1123
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
1124
+ }
1125
+ }
1126
+ }
1127
+ return d[a.length][b.length];
1128
+ }
1129
+ __name(editDistance, "editDistance");
1130
+ function suggestSimilar(word, candidates) {
1131
+ if (!candidates || candidates.length === 0) return "";
1132
+ candidates = Array.from(new Set(candidates));
1133
+ const searchingOptions = word.startsWith("--");
1134
+ if (searchingOptions) {
1135
+ word = word.slice(2);
1136
+ candidates = candidates.map((candidate) => candidate.slice(2));
1137
+ }
1138
+ let similar = [];
1139
+ let bestDistance = maxDistance;
1140
+ const minSimilarity = 0.4;
1141
+ candidates.forEach((candidate) => {
1142
+ if (candidate.length <= 1) return;
1143
+ const distance = editDistance(word, candidate);
1144
+ const length = Math.max(word.length, candidate.length);
1145
+ const similarity = (length - distance) / length;
1146
+ if (similarity > minSimilarity) {
1147
+ if (distance < bestDistance) {
1148
+ bestDistance = distance;
1149
+ similar = [
1150
+ candidate
1151
+ ];
1152
+ } else if (distance === bestDistance) {
1153
+ similar.push(candidate);
1154
+ }
1155
+ }
1156
+ });
1157
+ similar.sort((a, b) => a.localeCompare(b));
1158
+ if (searchingOptions) {
1159
+ similar = similar.map((candidate) => `--${candidate}`);
1160
+ }
1161
+ if (similar.length > 1) {
1162
+ return `
1163
+ (Did you mean one of ${similar.join(", ")}?)`;
1164
+ }
1165
+ if (similar.length === 1) {
1166
+ return `
1167
+ (Did you mean ${similar[0]}?)`;
1168
+ }
1169
+ return "";
1170
+ }
1171
+ __name(suggestSimilar, "suggestSimilar");
1172
+ exports$1.suggestSimilar = suggestSimilar;
1173
+ }
1174
+ });
1175
+
1176
+ // ../../node_modules/.pnpm/commander@14.0.2/node_modules/commander/lib/command.js
1177
+ var require_command = __commonJS({
1178
+ "../../node_modules/.pnpm/commander@14.0.2/node_modules/commander/lib/command.js"(exports$1) {
1179
+ init_esm_shims();
1180
+ var EventEmitter = __require("events").EventEmitter;
1181
+ var childProcess = __require("child_process");
1182
+ var path2 = __require("path");
1183
+ var fs = __require("fs");
1184
+ var process2 = __require("process");
1185
+ var { Argument, humanReadableArgName } = require_argument();
1186
+ var { CommanderError } = require_error();
1187
+ var { Help, stripColor } = require_help();
1188
+ var { Option, DualOptions } = require_option();
1189
+ var { suggestSimilar } = require_suggestSimilar();
1190
+ var Command2 = class Command3 extends EventEmitter {
1191
+ static {
1192
+ __name(this, "Command");
1193
+ }
1194
+ /**
1195
+ * Initialize a new `Command`.
1196
+ *
1197
+ * @param {string} [name]
1198
+ */
1199
+ constructor(name) {
1200
+ super();
1201
+ this.commands = [];
1202
+ this.options = [];
1203
+ this.parent = null;
1204
+ this._allowUnknownOption = false;
1205
+ this._allowExcessArguments = false;
1206
+ this.registeredArguments = [];
1207
+ this._args = this.registeredArguments;
1208
+ this.args = [];
1209
+ this.rawArgs = [];
1210
+ this.processedArgs = [];
1211
+ this._scriptPath = null;
1212
+ this._name = name || "";
1213
+ this._optionValues = {};
1214
+ this._optionValueSources = {};
1215
+ this._storeOptionsAsProperties = false;
1216
+ this._actionHandler = null;
1217
+ this._executableHandler = false;
1218
+ this._executableFile = null;
1219
+ this._executableDir = null;
1220
+ this._defaultCommandName = null;
1221
+ this._exitCallback = null;
1222
+ this._aliases = [];
1223
+ this._combineFlagAndOptionalValue = true;
1224
+ this._description = "";
1225
+ this._summary = "";
1226
+ this._argsDescription = void 0;
1227
+ this._enablePositionalOptions = false;
1228
+ this._passThroughOptions = false;
1229
+ this._lifeCycleHooks = {};
1230
+ this._showHelpAfterError = false;
1231
+ this._showSuggestionAfterError = true;
1232
+ this._savedState = null;
1233
+ this._outputConfiguration = {
1234
+ writeOut: /* @__PURE__ */ __name((str) => process2.stdout.write(str), "writeOut"),
1235
+ writeErr: /* @__PURE__ */ __name((str) => process2.stderr.write(str), "writeErr"),
1236
+ outputError: /* @__PURE__ */ __name((str, write) => write(str), "outputError"),
1237
+ getOutHelpWidth: /* @__PURE__ */ __name(() => process2.stdout.isTTY ? process2.stdout.columns : void 0, "getOutHelpWidth"),
1238
+ getErrHelpWidth: /* @__PURE__ */ __name(() => process2.stderr.isTTY ? process2.stderr.columns : void 0, "getErrHelpWidth"),
1239
+ getOutHasColors: /* @__PURE__ */ __name(() => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()), "getOutHasColors"),
1240
+ getErrHasColors: /* @__PURE__ */ __name(() => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()), "getErrHasColors"),
1241
+ stripColor: /* @__PURE__ */ __name((str) => stripColor(str), "stripColor")
1242
+ };
1243
+ this._hidden = false;
1244
+ this._helpOption = void 0;
1245
+ this._addImplicitHelpCommand = void 0;
1246
+ this._helpCommand = void 0;
1247
+ this._helpConfiguration = {};
1248
+ this._helpGroupHeading = void 0;
1249
+ this._defaultCommandGroup = void 0;
1250
+ this._defaultOptionGroup = void 0;
1251
+ }
1252
+ /**
1253
+ * Copy settings that are useful to have in common across root command and subcommands.
1254
+ *
1255
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1256
+ *
1257
+ * @param {Command} sourceCommand
1258
+ * @return {Command} `this` command for chaining
1259
+ */
1260
+ copyInheritedSettings(sourceCommand) {
1261
+ this._outputConfiguration = sourceCommand._outputConfiguration;
1262
+ this._helpOption = sourceCommand._helpOption;
1263
+ this._helpCommand = sourceCommand._helpCommand;
1264
+ this._helpConfiguration = sourceCommand._helpConfiguration;
1265
+ this._exitCallback = sourceCommand._exitCallback;
1266
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1267
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1268
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
1269
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1270
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
1271
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1272
+ return this;
1273
+ }
1274
+ /**
1275
+ * @returns {Command[]}
1276
+ * @private
1277
+ */
1278
+ _getCommandAndAncestors() {
1279
+ const result = [];
1280
+ for (let command = this; command; command = command.parent) {
1281
+ result.push(command);
1282
+ }
1283
+ return result;
1284
+ }
1285
+ /**
1286
+ * Define a command.
1287
+ *
1288
+ * There are two styles of command: pay attention to where to put the description.
1289
+ *
1290
+ * @example
1291
+ * // Command implemented using action handler (description is supplied separately to `.command`)
1292
+ * program
1293
+ * .command('clone <source> [destination]')
1294
+ * .description('clone a repository into a newly created directory')
1295
+ * .action((source, destination) => {
1296
+ * console.log('clone command called');
1297
+ * });
1298
+ *
1299
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
1300
+ * program
1301
+ * .command('start <service>', 'start named service')
1302
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
1303
+ *
1304
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1305
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1306
+ * @param {object} [execOpts] - configuration options (for executable)
1307
+ * @return {Command} returns new command for action handler, or `this` for executable command
1308
+ */
1309
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1310
+ let desc = actionOptsOrExecDesc;
1311
+ let opts = execOpts;
1312
+ if (typeof desc === "object" && desc !== null) {
1313
+ opts = desc;
1314
+ desc = null;
1315
+ }
1316
+ opts = opts || {};
1317
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1318
+ const cmd = this.createCommand(name);
1319
+ if (desc) {
1320
+ cmd.description(desc);
1321
+ cmd._executableHandler = true;
1322
+ }
1323
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1324
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
1325
+ cmd._executableFile = opts.executableFile || null;
1326
+ if (args) cmd.arguments(args);
1327
+ this._registerCommand(cmd);
1328
+ cmd.parent = this;
1329
+ cmd.copyInheritedSettings(this);
1330
+ if (desc) return this;
1331
+ return cmd;
1332
+ }
1333
+ /**
1334
+ * Factory routine to create a new unattached command.
1335
+ *
1336
+ * See .command() for creating an attached subcommand, which uses this routine to
1337
+ * create the command. You can override createCommand to customise subcommands.
1338
+ *
1339
+ * @param {string} [name]
1340
+ * @return {Command} new command
1341
+ */
1342
+ createCommand(name) {
1343
+ return new Command3(name);
1344
+ }
1345
+ /**
1346
+ * You can customise the help with a subclass of Help by overriding createHelp,
1347
+ * or by overriding Help properties using configureHelp().
1348
+ *
1349
+ * @return {Help}
1350
+ */
1351
+ createHelp() {
1352
+ return Object.assign(new Help(), this.configureHelp());
1353
+ }
1354
+ /**
1355
+ * You can customise the help by overriding Help properties using configureHelp(),
1356
+ * or with a subclass of Help by overriding createHelp().
1357
+ *
1358
+ * @param {object} [configuration] - configuration options
1359
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1360
+ */
1361
+ configureHelp(configuration) {
1362
+ if (configuration === void 0) return this._helpConfiguration;
1363
+ this._helpConfiguration = configuration;
1364
+ return this;
1365
+ }
1366
+ /**
1367
+ * The default output goes to stdout and stderr. You can customise this for special
1368
+ * applications. You can also customise the display of errors by overriding outputError.
1369
+ *
1370
+ * The configuration properties are all functions:
1371
+ *
1372
+ * // change how output being written, defaults to stdout and stderr
1373
+ * writeOut(str)
1374
+ * writeErr(str)
1375
+ * // change how output being written for errors, defaults to writeErr
1376
+ * outputError(str, write) // used for displaying errors and not used for displaying help
1377
+ * // specify width for wrapping help
1378
+ * getOutHelpWidth()
1379
+ * getErrHelpWidth()
1380
+ * // color support, currently only used with Help
1381
+ * getOutHasColors()
1382
+ * getErrHasColors()
1383
+ * stripColor() // used to remove ANSI escape codes if output does not have colors
1384
+ *
1385
+ * @param {object} [configuration] - configuration options
1386
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1387
+ */
1388
+ configureOutput(configuration) {
1389
+ if (configuration === void 0) return this._outputConfiguration;
1390
+ this._outputConfiguration = {
1391
+ ...this._outputConfiguration,
1392
+ ...configuration
1393
+ };
1394
+ return this;
1395
+ }
1396
+ /**
1397
+ * Display the help or a custom message after an error occurs.
1398
+ *
1399
+ * @param {(boolean|string)} [displayHelp]
1400
+ * @return {Command} `this` command for chaining
1401
+ */
1402
+ showHelpAfterError(displayHelp = true) {
1403
+ if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
1404
+ this._showHelpAfterError = displayHelp;
1405
+ return this;
1406
+ }
1407
+ /**
1408
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
1409
+ *
1410
+ * @param {boolean} [displaySuggestion]
1411
+ * @return {Command} `this` command for chaining
1412
+ */
1413
+ showSuggestionAfterError(displaySuggestion = true) {
1414
+ this._showSuggestionAfterError = !!displaySuggestion;
1415
+ return this;
1416
+ }
1417
+ /**
1418
+ * Add a prepared subcommand.
1419
+ *
1420
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
1421
+ *
1422
+ * @param {Command} cmd - new subcommand
1423
+ * @param {object} [opts] - configuration options
1424
+ * @return {Command} `this` command for chaining
1425
+ */
1426
+ addCommand(cmd, opts) {
1427
+ if (!cmd._name) {
1428
+ throw new Error(`Command passed to .addCommand() must have a name
1429
+ - specify the name in Command constructor or using .name()`);
1430
+ }
1431
+ opts = opts || {};
1432
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1433
+ if (opts.noHelp || opts.hidden) cmd._hidden = true;
1434
+ this._registerCommand(cmd);
1435
+ cmd.parent = this;
1436
+ cmd._checkForBrokenPassThrough();
1437
+ return this;
1438
+ }
1439
+ /**
1440
+ * Factory routine to create a new unattached argument.
1441
+ *
1442
+ * See .argument() for creating an attached argument, which uses this routine to
1443
+ * create the argument. You can override createArgument to return a custom argument.
1444
+ *
1445
+ * @param {string} name
1446
+ * @param {string} [description]
1447
+ * @return {Argument} new argument
1448
+ */
1449
+ createArgument(name, description) {
1450
+ return new Argument(name, description);
1451
+ }
1452
+ /**
1453
+ * Define argument syntax for command.
1454
+ *
1455
+ * The default is that the argument is required, and you can explicitly
1456
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
1457
+ *
1458
+ * @example
1459
+ * program.argument('<input-file>');
1460
+ * program.argument('[output-file]');
1461
+ *
1462
+ * @param {string} name
1463
+ * @param {string} [description]
1464
+ * @param {(Function|*)} [parseArg] - custom argument processing function or default value
1465
+ * @param {*} [defaultValue]
1466
+ * @return {Command} `this` command for chaining
1467
+ */
1468
+ argument(name, description, parseArg, defaultValue) {
1469
+ const argument = this.createArgument(name, description);
1470
+ if (typeof parseArg === "function") {
1471
+ argument.default(defaultValue).argParser(parseArg);
1472
+ } else {
1473
+ argument.default(parseArg);
1474
+ }
1475
+ this.addArgument(argument);
1476
+ return this;
1477
+ }
1478
+ /**
1479
+ * Define argument syntax for command, adding multiple at once (without descriptions).
1480
+ *
1481
+ * See also .argument().
1482
+ *
1483
+ * @example
1484
+ * program.arguments('<cmd> [env]');
1485
+ *
1486
+ * @param {string} names
1487
+ * @return {Command} `this` command for chaining
1488
+ */
1489
+ arguments(names) {
1490
+ names.trim().split(/ +/).forEach((detail) => {
1491
+ this.argument(detail);
1492
+ });
1493
+ return this;
1494
+ }
1495
+ /**
1496
+ * Define argument syntax for command, adding a prepared argument.
1497
+ *
1498
+ * @param {Argument} argument
1499
+ * @return {Command} `this` command for chaining
1500
+ */
1501
+ addArgument(argument) {
1502
+ const previousArgument = this.registeredArguments.slice(-1)[0];
1503
+ if (previousArgument?.variadic) {
1504
+ throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
1505
+ }
1506
+ if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
1507
+ throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
1508
+ }
1509
+ this.registeredArguments.push(argument);
1510
+ return this;
1511
+ }
1512
+ /**
1513
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
1514
+ *
1515
+ * @example
1516
+ * program.helpCommand('help [cmd]');
1517
+ * program.helpCommand('help [cmd]', 'show help');
1518
+ * program.helpCommand(false); // suppress default help command
1519
+ * program.helpCommand(true); // add help command even if no subcommands
1520
+ *
1521
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
1522
+ * @param {string} [description] - custom description
1523
+ * @return {Command} `this` command for chaining
1524
+ */
1525
+ helpCommand(enableOrNameAndArgs, description) {
1526
+ if (typeof enableOrNameAndArgs === "boolean") {
1527
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
1528
+ if (enableOrNameAndArgs && this._defaultCommandGroup) {
1529
+ this._initCommandGroup(this._getHelpCommand());
1530
+ }
1531
+ return this;
1532
+ }
1533
+ const nameAndArgs = enableOrNameAndArgs ?? "help [command]";
1534
+ const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);
1535
+ const helpDescription = description ?? "display help for command";
1536
+ const helpCommand = this.createCommand(helpName);
1537
+ helpCommand.helpOption(false);
1538
+ if (helpArgs) helpCommand.arguments(helpArgs);
1539
+ if (helpDescription) helpCommand.description(helpDescription);
1540
+ this._addImplicitHelpCommand = true;
1541
+ this._helpCommand = helpCommand;
1542
+ if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);
1543
+ return this;
1544
+ }
1545
+ /**
1546
+ * Add prepared custom help command.
1547
+ *
1548
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
1549
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
1550
+ * @return {Command} `this` command for chaining
1551
+ */
1552
+ addHelpCommand(helpCommand, deprecatedDescription) {
1553
+ if (typeof helpCommand !== "object") {
1554
+ this.helpCommand(helpCommand, deprecatedDescription);
1555
+ return this;
1556
+ }
1557
+ this._addImplicitHelpCommand = true;
1558
+ this._helpCommand = helpCommand;
1559
+ this._initCommandGroup(helpCommand);
1560
+ return this;
1561
+ }
1562
+ /**
1563
+ * Lazy create help command.
1564
+ *
1565
+ * @return {(Command|null)}
1566
+ * @package
1567
+ */
1568
+ _getHelpCommand() {
1569
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
1570
+ if (hasImplicitHelpCommand) {
1571
+ if (this._helpCommand === void 0) {
1572
+ this.helpCommand(void 0, void 0);
1573
+ }
1574
+ return this._helpCommand;
1575
+ }
1576
+ return null;
1577
+ }
1578
+ /**
1579
+ * Add hook for life cycle event.
1580
+ *
1581
+ * @param {string} event
1582
+ * @param {Function} listener
1583
+ * @return {Command} `this` command for chaining
1584
+ */
1585
+ hook(event, listener) {
1586
+ const allowedValues = [
1587
+ "preSubcommand",
1588
+ "preAction",
1589
+ "postAction"
1590
+ ];
1591
+ if (!allowedValues.includes(event)) {
1592
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
1593
+ Expecting one of '${allowedValues.join("', '")}'`);
1594
+ }
1595
+ if (this._lifeCycleHooks[event]) {
1596
+ this._lifeCycleHooks[event].push(listener);
1597
+ } else {
1598
+ this._lifeCycleHooks[event] = [
1599
+ listener
1600
+ ];
1601
+ }
1602
+ return this;
1603
+ }
1604
+ /**
1605
+ * Register callback to use as replacement for calling process.exit.
1606
+ *
1607
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
1608
+ * @return {Command} `this` command for chaining
1609
+ */
1610
+ exitOverride(fn) {
1611
+ if (fn) {
1612
+ this._exitCallback = fn;
1613
+ } else {
1614
+ this._exitCallback = (err) => {
1615
+ if (err.code !== "commander.executeSubCommandAsync") {
1616
+ throw err;
1617
+ }
1618
+ };
1619
+ }
1620
+ return this;
1621
+ }
1622
+ /**
1623
+ * Call process.exit, and _exitCallback if defined.
1624
+ *
1625
+ * @param {number} exitCode exit code for using with process.exit
1626
+ * @param {string} code an id string representing the error
1627
+ * @param {string} message human-readable description of the error
1628
+ * @return never
1629
+ * @private
1630
+ */
1631
+ _exit(exitCode, code, message) {
1632
+ if (this._exitCallback) {
1633
+ this._exitCallback(new CommanderError(exitCode, code, message));
1634
+ }
1635
+ process2.exit(exitCode);
1636
+ }
1637
+ /**
1638
+ * Register callback `fn` for the command.
1639
+ *
1640
+ * @example
1641
+ * program
1642
+ * .command('serve')
1643
+ * .description('start service')
1644
+ * .action(function() {
1645
+ * // do work here
1646
+ * });
1647
+ *
1648
+ * @param {Function} fn
1649
+ * @return {Command} `this` command for chaining
1650
+ */
1651
+ action(fn) {
1652
+ const listener = /* @__PURE__ */ __name((args) => {
1653
+ const expectedArgsCount = this.registeredArguments.length;
1654
+ const actionArgs = args.slice(0, expectedArgsCount);
1655
+ if (this._storeOptionsAsProperties) {
1656
+ actionArgs[expectedArgsCount] = this;
1657
+ } else {
1658
+ actionArgs[expectedArgsCount] = this.opts();
1659
+ }
1660
+ actionArgs.push(this);
1661
+ return fn.apply(this, actionArgs);
1662
+ }, "listener");
1663
+ this._actionHandler = listener;
1664
+ return this;
1665
+ }
1666
+ /**
1667
+ * Factory routine to create a new unattached option.
1668
+ *
1669
+ * See .option() for creating an attached option, which uses this routine to
1670
+ * create the option. You can override createOption to return a custom option.
1671
+ *
1672
+ * @param {string} flags
1673
+ * @param {string} [description]
1674
+ * @return {Option} new option
1675
+ */
1676
+ createOption(flags, description) {
1677
+ return new Option(flags, description);
1678
+ }
1679
+ /**
1680
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
1681
+ *
1682
+ * @param {(Option | Argument)} target
1683
+ * @param {string} value
1684
+ * @param {*} previous
1685
+ * @param {string} invalidArgumentMessage
1686
+ * @private
1687
+ */
1688
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
1689
+ try {
1690
+ return target.parseArg(value, previous);
1691
+ } catch (err) {
1692
+ if (err.code === "commander.invalidArgument") {
1693
+ const message = `${invalidArgumentMessage} ${err.message}`;
1694
+ this.error(message, {
1695
+ exitCode: err.exitCode,
1696
+ code: err.code
1697
+ });
1698
+ }
1699
+ throw err;
1700
+ }
1701
+ }
1702
+ /**
1703
+ * Check for option flag conflicts.
1704
+ * Register option if no conflicts found, or throw on conflict.
1705
+ *
1706
+ * @param {Option} option
1707
+ * @private
1708
+ */
1709
+ _registerOption(option) {
1710
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1711
+ if (matchingOption) {
1712
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1713
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1714
+ - already used by option '${matchingOption.flags}'`);
1715
+ }
1716
+ this._initOptionGroup(option);
1717
+ this.options.push(option);
1718
+ }
1719
+ /**
1720
+ * Check for command name and alias conflicts with existing commands.
1721
+ * Register command if no conflicts found, or throw on conflict.
1722
+ *
1723
+ * @param {Command} command
1724
+ * @private
1725
+ */
1726
+ _registerCommand(command) {
1727
+ const knownBy = /* @__PURE__ */ __name((cmd) => {
1728
+ return [
1729
+ cmd.name()
1730
+ ].concat(cmd.aliases());
1731
+ }, "knownBy");
1732
+ const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
1733
+ if (alreadyUsed) {
1734
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1735
+ const newCmd = knownBy(command).join("|");
1736
+ throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
1737
+ }
1738
+ this._initCommandGroup(command);
1739
+ this.commands.push(command);
1740
+ }
1741
+ /**
1742
+ * Add an option.
1743
+ *
1744
+ * @param {Option} option
1745
+ * @return {Command} `this` command for chaining
1746
+ */
1747
+ addOption(option) {
1748
+ this._registerOption(option);
1749
+ const oname = option.name();
1750
+ const name = option.attributeName();
1751
+ if (option.negate) {
1752
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1753
+ if (!this._findOption(positiveLongFlag)) {
1754
+ this.setOptionValueWithSource(name, option.defaultValue === void 0 ? true : option.defaultValue, "default");
1755
+ }
1756
+ } else if (option.defaultValue !== void 0) {
1757
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
1758
+ }
1759
+ const handleOptionValue = /* @__PURE__ */ __name((val, invalidValueMessage, valueSource) => {
1760
+ if (val == null && option.presetArg !== void 0) {
1761
+ val = option.presetArg;
1762
+ }
1763
+ const oldValue = this.getOptionValue(name);
1764
+ if (val !== null && option.parseArg) {
1765
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1766
+ } else if (val !== null && option.variadic) {
1767
+ val = option._collectValue(val, oldValue);
1768
+ }
1769
+ if (val == null) {
1770
+ if (option.negate) {
1771
+ val = false;
1772
+ } else if (option.isBoolean() || option.optional) {
1773
+ val = true;
1774
+ } else {
1775
+ val = "";
1776
+ }
1777
+ }
1778
+ this.setOptionValueWithSource(name, val, valueSource);
1779
+ }, "handleOptionValue");
1780
+ this.on("option:" + oname, (val) => {
1781
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1782
+ handleOptionValue(val, invalidValueMessage, "cli");
1783
+ });
1784
+ if (option.envVar) {
1785
+ this.on("optionEnv:" + oname, (val) => {
1786
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1787
+ handleOptionValue(val, invalidValueMessage, "env");
1788
+ });
1789
+ }
1790
+ return this;
1791
+ }
1792
+ /**
1793
+ * Internal implementation shared by .option() and .requiredOption()
1794
+ *
1795
+ * @return {Command} `this` command for chaining
1796
+ * @private
1797
+ */
1798
+ _optionEx(config, flags, description, fn, defaultValue) {
1799
+ if (typeof flags === "object" && flags instanceof Option) {
1800
+ throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
1801
+ }
1802
+ const option = this.createOption(flags, description);
1803
+ option.makeOptionMandatory(!!config.mandatory);
1804
+ if (typeof fn === "function") {
1805
+ option.default(defaultValue).argParser(fn);
1806
+ } else if (fn instanceof RegExp) {
1807
+ const regex = fn;
1808
+ fn = /* @__PURE__ */ __name((val, def) => {
1809
+ const m = regex.exec(val);
1810
+ return m ? m[0] : def;
1811
+ }, "fn");
1812
+ option.default(defaultValue).argParser(fn);
1813
+ } else {
1814
+ option.default(fn);
1815
+ }
1816
+ return this.addOption(option);
1817
+ }
1818
+ /**
1819
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
1820
+ *
1821
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
1822
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
1823
+ *
1824
+ * See the README for more details, and see also addOption() and requiredOption().
1825
+ *
1826
+ * @example
1827
+ * program
1828
+ * .option('-p, --pepper', 'add pepper')
1829
+ * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
1830
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
1831
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
1832
+ *
1833
+ * @param {string} flags
1834
+ * @param {string} [description]
1835
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1836
+ * @param {*} [defaultValue]
1837
+ * @return {Command} `this` command for chaining
1838
+ */
1839
+ option(flags, description, parseArg, defaultValue) {
1840
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1841
+ }
1842
+ /**
1843
+ * Add a required option which must have a value after parsing. This usually means
1844
+ * the option must be specified on the command line. (Otherwise the same as .option().)
1845
+ *
1846
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1847
+ *
1848
+ * @param {string} flags
1849
+ * @param {string} [description]
1850
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1851
+ * @param {*} [defaultValue]
1852
+ * @return {Command} `this` command for chaining
1853
+ */
1854
+ requiredOption(flags, description, parseArg, defaultValue) {
1855
+ return this._optionEx({
1856
+ mandatory: true
1857
+ }, flags, description, parseArg, defaultValue);
1858
+ }
1859
+ /**
1860
+ * Alter parsing of short flags with optional values.
1861
+ *
1862
+ * @example
1863
+ * // for `.option('-f,--flag [value]'):
1864
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
1865
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
1866
+ *
1867
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
1868
+ * @return {Command} `this` command for chaining
1869
+ */
1870
+ combineFlagAndOptionalValue(combine = true) {
1871
+ this._combineFlagAndOptionalValue = !!combine;
1872
+ return this;
1873
+ }
1874
+ /**
1875
+ * Allow unknown options on the command line.
1876
+ *
1877
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
1878
+ * @return {Command} `this` command for chaining
1879
+ */
1880
+ allowUnknownOption(allowUnknown = true) {
1881
+ this._allowUnknownOption = !!allowUnknown;
1882
+ return this;
1883
+ }
1884
+ /**
1885
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1886
+ *
1887
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
1888
+ * @return {Command} `this` command for chaining
1889
+ */
1890
+ allowExcessArguments(allowExcess = true) {
1891
+ this._allowExcessArguments = !!allowExcess;
1892
+ return this;
1893
+ }
1894
+ /**
1895
+ * Enable positional options. Positional means global options are specified before subcommands which lets
1896
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1897
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
1898
+ *
1899
+ * @param {boolean} [positional]
1900
+ * @return {Command} `this` command for chaining
1901
+ */
1902
+ enablePositionalOptions(positional = true) {
1903
+ this._enablePositionalOptions = !!positional;
1904
+ return this;
1905
+ }
1906
+ /**
1907
+ * Pass through options that come after command-arguments rather than treat them as command-options,
1908
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
1909
+ * positional options to have been enabled on the program (parent commands).
1910
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
1911
+ *
1912
+ * @param {boolean} [passThrough] for unknown options.
1913
+ * @return {Command} `this` command for chaining
1914
+ */
1915
+ passThroughOptions(passThrough = true) {
1916
+ this._passThroughOptions = !!passThrough;
1917
+ this._checkForBrokenPassThrough();
1918
+ return this;
1919
+ }
1920
+ /**
1921
+ * @private
1922
+ */
1923
+ _checkForBrokenPassThrough() {
1924
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
1925
+ throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
1926
+ }
1927
+ }
1928
+ /**
1929
+ * Whether to store option values as properties on command object,
1930
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
1931
+ *
1932
+ * @param {boolean} [storeAsProperties=true]
1933
+ * @return {Command} `this` command for chaining
1934
+ */
1935
+ storeOptionsAsProperties(storeAsProperties = true) {
1936
+ if (this.options.length) {
1937
+ throw new Error("call .storeOptionsAsProperties() before adding options");
1938
+ }
1939
+ if (Object.keys(this._optionValues).length) {
1940
+ throw new Error("call .storeOptionsAsProperties() before setting option values");
1941
+ }
1942
+ this._storeOptionsAsProperties = !!storeAsProperties;
1943
+ return this;
1944
+ }
1945
+ /**
1946
+ * Retrieve option value.
1947
+ *
1948
+ * @param {string} key
1949
+ * @return {object} value
1950
+ */
1951
+ getOptionValue(key) {
1952
+ if (this._storeOptionsAsProperties) {
1953
+ return this[key];
1954
+ }
1955
+ return this._optionValues[key];
1956
+ }
1957
+ /**
1958
+ * Store option value.
1959
+ *
1960
+ * @param {string} key
1961
+ * @param {object} value
1962
+ * @return {Command} `this` command for chaining
1963
+ */
1964
+ setOptionValue(key, value) {
1965
+ return this.setOptionValueWithSource(key, value, void 0);
1966
+ }
1967
+ /**
1968
+ * Store option value and where the value came from.
1969
+ *
1970
+ * @param {string} key
1971
+ * @param {object} value
1972
+ * @param {string} source - expected values are default/config/env/cli/implied
1973
+ * @return {Command} `this` command for chaining
1974
+ */
1975
+ setOptionValueWithSource(key, value, source) {
1976
+ if (this._storeOptionsAsProperties) {
1977
+ this[key] = value;
1978
+ } else {
1979
+ this._optionValues[key] = value;
1980
+ }
1981
+ this._optionValueSources[key] = source;
1982
+ return this;
1983
+ }
1984
+ /**
1985
+ * Get source of option value.
1986
+ * Expected values are default | config | env | cli | implied
1987
+ *
1988
+ * @param {string} key
1989
+ * @return {string}
1990
+ */
1991
+ getOptionValueSource(key) {
1992
+ return this._optionValueSources[key];
1993
+ }
1994
+ /**
1995
+ * Get source of option value. See also .optsWithGlobals().
1996
+ * Expected values are default | config | env | cli | implied
1997
+ *
1998
+ * @param {string} key
1999
+ * @return {string}
2000
+ */
2001
+ getOptionValueSourceWithGlobals(key) {
2002
+ let source;
2003
+ this._getCommandAndAncestors().forEach((cmd) => {
2004
+ if (cmd.getOptionValueSource(key) !== void 0) {
2005
+ source = cmd.getOptionValueSource(key);
2006
+ }
2007
+ });
2008
+ return source;
2009
+ }
2010
+ /**
2011
+ * Get user arguments from implied or explicit arguments.
2012
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
2013
+ *
2014
+ * @private
2015
+ */
2016
+ _prepareUserArgs(argv, parseOptions) {
2017
+ if (argv !== void 0 && !Array.isArray(argv)) {
2018
+ throw new Error("first parameter to parse must be array or undefined");
2019
+ }
2020
+ parseOptions = parseOptions || {};
2021
+ if (argv === void 0 && parseOptions.from === void 0) {
2022
+ if (process2.versions?.electron) {
2023
+ parseOptions.from = "electron";
2024
+ }
2025
+ const execArgv = process2.execArgv ?? [];
2026
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
2027
+ parseOptions.from = "eval";
2028
+ }
2029
+ }
2030
+ if (argv === void 0) {
2031
+ argv = process2.argv;
2032
+ }
2033
+ this.rawArgs = argv.slice();
2034
+ let userArgs;
2035
+ switch (parseOptions.from) {
2036
+ case void 0:
2037
+ case "node":
2038
+ this._scriptPath = argv[1];
2039
+ userArgs = argv.slice(2);
2040
+ break;
2041
+ case "electron":
2042
+ if (process2.defaultApp) {
2043
+ this._scriptPath = argv[1];
2044
+ userArgs = argv.slice(2);
2045
+ } else {
2046
+ userArgs = argv.slice(1);
2047
+ }
2048
+ break;
2049
+ case "user":
2050
+ userArgs = argv.slice(0);
2051
+ break;
2052
+ case "eval":
2053
+ userArgs = argv.slice(1);
2054
+ break;
2055
+ default:
2056
+ throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
2057
+ }
2058
+ if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath);
2059
+ this._name = this._name || "program";
2060
+ return userArgs;
2061
+ }
2062
+ /**
2063
+ * Parse `argv`, setting options and invoking commands when defined.
2064
+ *
2065
+ * Use parseAsync instead of parse if any of your action handlers are async.
2066
+ *
2067
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
2068
+ *
2069
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
2070
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
2071
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
2072
+ * - `'user'`: just user arguments
2073
+ *
2074
+ * @example
2075
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
2076
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
2077
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2078
+ *
2079
+ * @param {string[]} [argv] - optional, defaults to process.argv
2080
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
2081
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
2082
+ * @return {Command} `this` command for chaining
2083
+ */
2084
+ parse(argv, parseOptions) {
2085
+ this._prepareForParse();
2086
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
2087
+ this._parseCommand([], userArgs);
2088
+ return this;
2089
+ }
2090
+ /**
2091
+ * Parse `argv`, setting options and invoking commands when defined.
2092
+ *
2093
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
2094
+ *
2095
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
2096
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
2097
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
2098
+ * - `'user'`: just user arguments
2099
+ *
2100
+ * @example
2101
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
2102
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
2103
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2104
+ *
2105
+ * @param {string[]} [argv]
2106
+ * @param {object} [parseOptions]
2107
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
2108
+ * @return {Promise}
2109
+ */
2110
+ async parseAsync(argv, parseOptions) {
2111
+ this._prepareForParse();
2112
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
2113
+ await this._parseCommand([], userArgs);
2114
+ return this;
2115
+ }
2116
+ _prepareForParse() {
2117
+ if (this._savedState === null) {
2118
+ this.saveStateBeforeParse();
2119
+ } else {
2120
+ this.restoreStateBeforeParse();
2121
+ }
2122
+ }
2123
+ /**
2124
+ * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
2125
+ * Not usually called directly, but available for subclasses to save their custom state.
2126
+ *
2127
+ * This is called in a lazy way. Only commands used in parsing chain will have state saved.
2128
+ */
2129
+ saveStateBeforeParse() {
2130
+ this._savedState = {
2131
+ // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing
2132
+ _name: this._name,
2133
+ // option values before parse have default values (including false for negated options)
2134
+ // shallow clones
2135
+ _optionValues: {
2136
+ ...this._optionValues
2137
+ },
2138
+ _optionValueSources: {
2139
+ ...this._optionValueSources
2140
+ }
2141
+ };
2142
+ }
2143
+ /**
2144
+ * Restore state before parse for calls after the first.
2145
+ * Not usually called directly, but available for subclasses to save their custom state.
2146
+ *
2147
+ * This is called in a lazy way. Only commands used in parsing chain will have state restored.
2148
+ */
2149
+ restoreStateBeforeParse() {
2150
+ if (this._storeOptionsAsProperties) throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
2151
+ - either make a new Command for each call to parse, or stop storing options as properties`);
2152
+ this._name = this._savedState._name;
2153
+ this._scriptPath = null;
2154
+ this.rawArgs = [];
2155
+ this._optionValues = {
2156
+ ...this._savedState._optionValues
2157
+ };
2158
+ this._optionValueSources = {
2159
+ ...this._savedState._optionValueSources
2160
+ };
2161
+ this.args = [];
2162
+ this.processedArgs = [];
2163
+ }
2164
+ /**
2165
+ * Throw if expected executable is missing. Add lots of help for author.
2166
+ *
2167
+ * @param {string} executableFile
2168
+ * @param {string} executableDir
2169
+ * @param {string} subcommandName
2170
+ */
2171
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
2172
+ if (fs.existsSync(executableFile)) return;
2173
+ const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory";
2174
+ const executableMissing = `'${executableFile}' does not exist
2175
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
2176
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
2177
+ - ${executableDirMessage}`;
2178
+ throw new Error(executableMissing);
2179
+ }
2180
+ /**
2181
+ * Execute a sub-command executable.
2182
+ *
2183
+ * @private
2184
+ */
2185
+ _executeSubCommand(subcommand, args) {
2186
+ args = args.slice();
2187
+ let launchWithNode = false;
2188
+ const sourceExt = [
2189
+ ".js",
2190
+ ".ts",
2191
+ ".tsx",
2192
+ ".mjs",
2193
+ ".cjs"
2194
+ ];
2195
+ function findFile(baseDir, baseName) {
2196
+ const localBin = path2.resolve(baseDir, baseName);
2197
+ if (fs.existsSync(localBin)) return localBin;
2198
+ if (sourceExt.includes(path2.extname(baseName))) return void 0;
2199
+ const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
2200
+ if (foundExt) return `${localBin}${foundExt}`;
2201
+ return void 0;
2202
+ }
2203
+ __name(findFile, "findFile");
2204
+ this._checkForMissingMandatoryOptions();
2205
+ this._checkForConflictingOptions();
2206
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
2207
+ let executableDir = this._executableDir || "";
2208
+ if (this._scriptPath) {
2209
+ let resolvedScriptPath;
2210
+ try {
2211
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
2212
+ } catch {
2213
+ resolvedScriptPath = this._scriptPath;
2214
+ }
2215
+ executableDir = path2.resolve(path2.dirname(resolvedScriptPath), executableDir);
2216
+ }
2217
+ if (executableDir) {
2218
+ let localFile = findFile(executableDir, executableFile);
2219
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
2220
+ const legacyName = path2.basename(this._scriptPath, path2.extname(this._scriptPath));
2221
+ if (legacyName !== this._name) {
2222
+ localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
2223
+ }
2224
+ }
2225
+ executableFile = localFile || executableFile;
2226
+ }
2227
+ launchWithNode = sourceExt.includes(path2.extname(executableFile));
2228
+ let proc;
2229
+ if (process2.platform !== "win32") {
2230
+ if (launchWithNode) {
2231
+ args.unshift(executableFile);
2232
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
2233
+ proc = childProcess.spawn(process2.argv[0], args, {
2234
+ stdio: "inherit"
2235
+ });
2236
+ } else {
2237
+ proc = childProcess.spawn(executableFile, args, {
2238
+ stdio: "inherit"
2239
+ });
2240
+ }
2241
+ } else {
2242
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
2243
+ args.unshift(executableFile);
2244
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
2245
+ proc = childProcess.spawn(process2.execPath, args, {
2246
+ stdio: "inherit"
2247
+ });
2248
+ }
2249
+ if (!proc.killed) {
2250
+ const signals = [
2251
+ "SIGUSR1",
2252
+ "SIGUSR2",
2253
+ "SIGTERM",
2254
+ "SIGINT",
2255
+ "SIGHUP"
2256
+ ];
2257
+ signals.forEach((signal) => {
2258
+ process2.on(signal, () => {
2259
+ if (proc.killed === false && proc.exitCode === null) {
2260
+ proc.kill(signal);
2261
+ }
2262
+ });
2263
+ });
2264
+ }
2265
+ const exitCallback = this._exitCallback;
2266
+ proc.on("close", (code) => {
2267
+ code = code ?? 1;
2268
+ if (!exitCallback) {
2269
+ process2.exit(code);
2270
+ } else {
2271
+ exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
2272
+ }
2273
+ });
2274
+ proc.on("error", (err) => {
2275
+ if (err.code === "ENOENT") {
2276
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
2277
+ } else if (err.code === "EACCES") {
2278
+ throw new Error(`'${executableFile}' not executable`);
2279
+ }
2280
+ if (!exitCallback) {
2281
+ process2.exit(1);
2282
+ } else {
2283
+ const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
2284
+ wrappedError.nestedError = err;
2285
+ exitCallback(wrappedError);
2286
+ }
2287
+ });
2288
+ this.runningCommand = proc;
2289
+ }
2290
+ /**
2291
+ * @private
2292
+ */
2293
+ _dispatchSubcommand(commandName, operands, unknown) {
2294
+ const subCommand = this._findCommand(commandName);
2295
+ if (!subCommand) this.help({
2296
+ error: true
2297
+ });
2298
+ subCommand._prepareForParse();
2299
+ let promiseChain;
2300
+ promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
2301
+ promiseChain = this._chainOrCall(promiseChain, () => {
2302
+ if (subCommand._executableHandler) {
2303
+ this._executeSubCommand(subCommand, operands.concat(unknown));
2304
+ } else {
2305
+ return subCommand._parseCommand(operands, unknown);
2306
+ }
2307
+ });
2308
+ return promiseChain;
2309
+ }
2310
+ /**
2311
+ * Invoke help directly if possible, or dispatch if necessary.
2312
+ * e.g. help foo
2313
+ *
2314
+ * @private
2315
+ */
2316
+ _dispatchHelpCommand(subcommandName) {
2317
+ if (!subcommandName) {
2318
+ this.help();
2319
+ }
2320
+ const subCommand = this._findCommand(subcommandName);
2321
+ if (subCommand && !subCommand._executableHandler) {
2322
+ subCommand.help();
2323
+ }
2324
+ return this._dispatchSubcommand(subcommandName, [], [
2325
+ this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"
2326
+ ]);
2327
+ }
2328
+ /**
2329
+ * Check this.args against expected this.registeredArguments.
2330
+ *
2331
+ * @private
2332
+ */
2333
+ _checkNumberOfArguments() {
2334
+ this.registeredArguments.forEach((arg, i) => {
2335
+ if (arg.required && this.args[i] == null) {
2336
+ this.missingArgument(arg.name());
2337
+ }
2338
+ });
2339
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
2340
+ return;
2341
+ }
2342
+ if (this.args.length > this.registeredArguments.length) {
2343
+ this._excessArguments(this.args);
2344
+ }
2345
+ }
2346
+ /**
2347
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
2348
+ *
2349
+ * @private
2350
+ */
2351
+ _processArguments() {
2352
+ const myParseArg = /* @__PURE__ */ __name((argument, value, previous) => {
2353
+ let parsedValue = value;
2354
+ if (value !== null && argument.parseArg) {
2355
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
2356
+ parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
2357
+ }
2358
+ return parsedValue;
2359
+ }, "myParseArg");
2360
+ this._checkNumberOfArguments();
2361
+ const processedArgs = [];
2362
+ this.registeredArguments.forEach((declaredArg, index) => {
2363
+ let value = declaredArg.defaultValue;
2364
+ if (declaredArg.variadic) {
2365
+ if (index < this.args.length) {
2366
+ value = this.args.slice(index);
2367
+ if (declaredArg.parseArg) {
2368
+ value = value.reduce((processed, v) => {
2369
+ return myParseArg(declaredArg, v, processed);
2370
+ }, declaredArg.defaultValue);
2371
+ }
2372
+ } else if (value === void 0) {
2373
+ value = [];
2374
+ }
2375
+ } else if (index < this.args.length) {
2376
+ value = this.args[index];
2377
+ if (declaredArg.parseArg) {
2378
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
2379
+ }
2380
+ }
2381
+ processedArgs[index] = value;
2382
+ });
2383
+ this.processedArgs = processedArgs;
2384
+ }
2385
+ /**
2386
+ * Once we have a promise we chain, but call synchronously until then.
2387
+ *
2388
+ * @param {(Promise|undefined)} promise
2389
+ * @param {Function} fn
2390
+ * @return {(Promise|undefined)}
2391
+ * @private
2392
+ */
2393
+ _chainOrCall(promise, fn) {
2394
+ if (promise?.then && typeof promise.then === "function") {
2395
+ return promise.then(() => fn());
2396
+ }
2397
+ return fn();
2398
+ }
2399
+ /**
2400
+ *
2401
+ * @param {(Promise|undefined)} promise
2402
+ * @param {string} event
2403
+ * @return {(Promise|undefined)}
2404
+ * @private
2405
+ */
2406
+ _chainOrCallHooks(promise, event) {
2407
+ let result = promise;
2408
+ const hooks = [];
2409
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
2410
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
2411
+ hooks.push({
2412
+ hookedCommand,
2413
+ callback
2414
+ });
2415
+ });
2416
+ });
2417
+ if (event === "postAction") {
2418
+ hooks.reverse();
2419
+ }
2420
+ hooks.forEach((hookDetail) => {
2421
+ result = this._chainOrCall(result, () => {
2422
+ return hookDetail.callback(hookDetail.hookedCommand, this);
2423
+ });
2424
+ });
2425
+ return result;
2426
+ }
2427
+ /**
2428
+ *
2429
+ * @param {(Promise|undefined)} promise
2430
+ * @param {Command} subCommand
2431
+ * @param {string} event
2432
+ * @return {(Promise|undefined)}
2433
+ * @private
2434
+ */
2435
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
2436
+ let result = promise;
2437
+ if (this._lifeCycleHooks[event] !== void 0) {
2438
+ this._lifeCycleHooks[event].forEach((hook) => {
2439
+ result = this._chainOrCall(result, () => {
2440
+ return hook(this, subCommand);
2441
+ });
2442
+ });
2443
+ }
2444
+ return result;
2445
+ }
2446
+ /**
2447
+ * Process arguments in context of this command.
2448
+ * Returns action result, in case it is a promise.
2449
+ *
2450
+ * @private
2451
+ */
2452
+ _parseCommand(operands, unknown) {
2453
+ const parsed = this.parseOptions(unknown);
2454
+ this._parseOptionsEnv();
2455
+ this._parseOptionsImplied();
2456
+ operands = operands.concat(parsed.operands);
2457
+ unknown = parsed.unknown;
2458
+ this.args = operands.concat(unknown);
2459
+ if (operands && this._findCommand(operands[0])) {
2460
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2461
+ }
2462
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
2463
+ return this._dispatchHelpCommand(operands[1]);
2464
+ }
2465
+ if (this._defaultCommandName) {
2466
+ this._outputHelpIfRequested(unknown);
2467
+ return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
2468
+ }
2469
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
2470
+ this.help({
2471
+ error: true
2472
+ });
2473
+ }
2474
+ this._outputHelpIfRequested(parsed.unknown);
2475
+ this._checkForMissingMandatoryOptions();
2476
+ this._checkForConflictingOptions();
2477
+ const checkForUnknownOptions = /* @__PURE__ */ __name(() => {
2478
+ if (parsed.unknown.length > 0) {
2479
+ this.unknownOption(parsed.unknown[0]);
2480
+ }
2481
+ }, "checkForUnknownOptions");
2482
+ const commandEvent = `command:${this.name()}`;
2483
+ if (this._actionHandler) {
2484
+ checkForUnknownOptions();
2485
+ this._processArguments();
2486
+ let promiseChain;
2487
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
2488
+ promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
2489
+ if (this.parent) {
2490
+ promiseChain = this._chainOrCall(promiseChain, () => {
2491
+ this.parent.emit(commandEvent, operands, unknown);
2492
+ });
2493
+ }
2494
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
2495
+ return promiseChain;
2496
+ }
2497
+ if (this.parent?.listenerCount(commandEvent)) {
2498
+ checkForUnknownOptions();
2499
+ this._processArguments();
2500
+ this.parent.emit(commandEvent, operands, unknown);
2501
+ } else if (operands.length) {
2502
+ if (this._findCommand("*")) {
2503
+ return this._dispatchSubcommand("*", operands, unknown);
2504
+ }
2505
+ if (this.listenerCount("command:*")) {
2506
+ this.emit("command:*", operands, unknown);
2507
+ } else if (this.commands.length) {
2508
+ this.unknownCommand();
2509
+ } else {
2510
+ checkForUnknownOptions();
2511
+ this._processArguments();
2512
+ }
2513
+ } else if (this.commands.length) {
2514
+ checkForUnknownOptions();
2515
+ this.help({
2516
+ error: true
2517
+ });
2518
+ } else {
2519
+ checkForUnknownOptions();
2520
+ this._processArguments();
2521
+ }
2522
+ }
2523
+ /**
2524
+ * Find matching command.
2525
+ *
2526
+ * @private
2527
+ * @return {Command | undefined}
2528
+ */
2529
+ _findCommand(name) {
2530
+ if (!name) return void 0;
2531
+ return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
2532
+ }
2533
+ /**
2534
+ * Return an option matching `arg` if any.
2535
+ *
2536
+ * @param {string} arg
2537
+ * @return {Option}
2538
+ * @package
2539
+ */
2540
+ _findOption(arg) {
2541
+ return this.options.find((option) => option.is(arg));
2542
+ }
2543
+ /**
2544
+ * Display an error message if a mandatory option does not have a value.
2545
+ * Called after checking for help flags in leaf subcommand.
2546
+ *
2547
+ * @private
2548
+ */
2549
+ _checkForMissingMandatoryOptions() {
2550
+ this._getCommandAndAncestors().forEach((cmd) => {
2551
+ cmd.options.forEach((anOption) => {
2552
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
2553
+ cmd.missingMandatoryOptionValue(anOption);
2554
+ }
2555
+ });
2556
+ });
2557
+ }
2558
+ /**
2559
+ * Display an error message if conflicting options are used together in this.
2560
+ *
2561
+ * @private
2562
+ */
2563
+ _checkForConflictingLocalOptions() {
2564
+ const definedNonDefaultOptions = this.options.filter((option) => {
2565
+ const optionKey = option.attributeName();
2566
+ if (this.getOptionValue(optionKey) === void 0) {
2567
+ return false;
2568
+ }
2569
+ return this.getOptionValueSource(optionKey) !== "default";
2570
+ });
2571
+ const optionsWithConflicting = definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0);
2572
+ optionsWithConflicting.forEach((option) => {
2573
+ const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
2574
+ if (conflictingAndDefined) {
2575
+ this._conflictingOption(option, conflictingAndDefined);
2576
+ }
2577
+ });
2578
+ }
2579
+ /**
2580
+ * Display an error message if conflicting options are used together.
2581
+ * Called after checking for help flags in leaf subcommand.
2582
+ *
2583
+ * @private
2584
+ */
2585
+ _checkForConflictingOptions() {
2586
+ this._getCommandAndAncestors().forEach((cmd) => {
2587
+ cmd._checkForConflictingLocalOptions();
2588
+ });
2589
+ }
2590
+ /**
2591
+ * Parse options from `argv` removing known options,
2592
+ * and return argv split into operands and unknown arguments.
2593
+ *
2594
+ * Side effects: modifies command by storing options. Does not reset state if called again.
2595
+ *
2596
+ * Examples:
2597
+ *
2598
+ * argv => operands, unknown
2599
+ * --known kkk op => [op], []
2600
+ * op --known kkk => [op], []
2601
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
2602
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
2603
+ *
2604
+ * @param {string[]} args
2605
+ * @return {{operands: string[], unknown: string[]}}
2606
+ */
2607
+ parseOptions(args) {
2608
+ const operands = [];
2609
+ const unknown = [];
2610
+ let dest = operands;
2611
+ function maybeOption(arg) {
2612
+ return arg.length > 1 && arg[0] === "-";
2613
+ }
2614
+ __name(maybeOption, "maybeOption");
2615
+ const negativeNumberArg = /* @__PURE__ */ __name((arg) => {
2616
+ if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)) return false;
2617
+ return !this._getCommandAndAncestors().some((cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short)));
2618
+ }, "negativeNumberArg");
2619
+ let activeVariadicOption = null;
2620
+ let activeGroup = null;
2621
+ let i = 0;
2622
+ while (i < args.length || activeGroup) {
2623
+ const arg = activeGroup ?? args[i++];
2624
+ activeGroup = null;
2625
+ if (arg === "--") {
2626
+ if (dest === unknown) dest.push(arg);
2627
+ dest.push(...args.slice(i));
2628
+ break;
2629
+ }
2630
+ if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
2631
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
2632
+ continue;
2633
+ }
2634
+ activeVariadicOption = null;
2635
+ if (maybeOption(arg)) {
2636
+ const option = this._findOption(arg);
2637
+ if (option) {
2638
+ if (option.required) {
2639
+ const value = args[i++];
2640
+ if (value === void 0) this.optionMissingArgument(option);
2641
+ this.emit(`option:${option.name()}`, value);
2642
+ } else if (option.optional) {
2643
+ let value = null;
2644
+ if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) {
2645
+ value = args[i++];
2646
+ }
2647
+ this.emit(`option:${option.name()}`, value);
2648
+ } else {
2649
+ this.emit(`option:${option.name()}`);
2650
+ }
2651
+ activeVariadicOption = option.variadic ? option : null;
2652
+ continue;
2653
+ }
2654
+ }
2655
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
2656
+ const option = this._findOption(`-${arg[1]}`);
2657
+ if (option) {
2658
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
2659
+ this.emit(`option:${option.name()}`, arg.slice(2));
2660
+ } else {
2661
+ this.emit(`option:${option.name()}`);
2662
+ activeGroup = `-${arg.slice(2)}`;
2663
+ }
2664
+ continue;
2665
+ }
2666
+ }
2667
+ if (/^--[^=]+=/.test(arg)) {
2668
+ const index = arg.indexOf("=");
2669
+ const option = this._findOption(arg.slice(0, index));
2670
+ if (option && (option.required || option.optional)) {
2671
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
2672
+ continue;
2673
+ }
2674
+ }
2675
+ if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) {
2676
+ dest = unknown;
2677
+ }
2678
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
2679
+ if (this._findCommand(arg)) {
2680
+ operands.push(arg);
2681
+ unknown.push(...args.slice(i));
2682
+ break;
2683
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
2684
+ operands.push(arg, ...args.slice(i));
2685
+ break;
2686
+ } else if (this._defaultCommandName) {
2687
+ unknown.push(arg, ...args.slice(i));
2688
+ break;
2689
+ }
2690
+ }
2691
+ if (this._passThroughOptions) {
2692
+ dest.push(arg, ...args.slice(i));
2693
+ break;
2694
+ }
2695
+ dest.push(arg);
2696
+ }
2697
+ return {
2698
+ operands,
2699
+ unknown
2700
+ };
2701
+ }
2702
+ /**
2703
+ * Return an object containing local option values as key-value pairs.
2704
+ *
2705
+ * @return {object}
2706
+ */
2707
+ opts() {
2708
+ if (this._storeOptionsAsProperties) {
2709
+ const result = {};
2710
+ const len = this.options.length;
2711
+ for (let i = 0; i < len; i++) {
2712
+ const key = this.options[i].attributeName();
2713
+ result[key] = key === this._versionOptionName ? this._version : this[key];
2714
+ }
2715
+ return result;
2716
+ }
2717
+ return this._optionValues;
2718
+ }
2719
+ /**
2720
+ * Return an object containing merged local and global option values as key-value pairs.
2721
+ *
2722
+ * @return {object}
2723
+ */
2724
+ optsWithGlobals() {
2725
+ return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
2726
+ }
2727
+ /**
2728
+ * Display error message and exit (or call exitOverride).
2729
+ *
2730
+ * @param {string} message
2731
+ * @param {object} [errorOptions]
2732
+ * @param {string} [errorOptions.code] - an id string representing the error
2733
+ * @param {number} [errorOptions.exitCode] - used with process.exit
2734
+ */
2735
+ error(message, errorOptions) {
2736
+ this._outputConfiguration.outputError(`${message}
2737
+ `, this._outputConfiguration.writeErr);
2738
+ if (typeof this._showHelpAfterError === "string") {
2739
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
2740
+ `);
2741
+ } else if (this._showHelpAfterError) {
2742
+ this._outputConfiguration.writeErr("\n");
2743
+ this.outputHelp({
2744
+ error: true
2745
+ });
2746
+ }
2747
+ const config = errorOptions || {};
2748
+ const exitCode = config.exitCode || 1;
2749
+ const code = config.code || "commander.error";
2750
+ this._exit(exitCode, code, message);
2751
+ }
2752
+ /**
2753
+ * Apply any option related environment variables, if option does
2754
+ * not have a value from cli or client code.
2755
+ *
2756
+ * @private
2757
+ */
2758
+ _parseOptionsEnv() {
2759
+ this.options.forEach((option) => {
2760
+ if (option.envVar && option.envVar in process2.env) {
2761
+ const optionKey = option.attributeName();
2762
+ if (this.getOptionValue(optionKey) === void 0 || [
2763
+ "default",
2764
+ "config",
2765
+ "env"
2766
+ ].includes(this.getOptionValueSource(optionKey))) {
2767
+ if (option.required || option.optional) {
2768
+ this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
2769
+ } else {
2770
+ this.emit(`optionEnv:${option.name()}`);
2771
+ }
2772
+ }
2773
+ }
2774
+ });
2775
+ }
2776
+ /**
2777
+ * Apply any implied option values, if option is undefined or default value.
2778
+ *
2779
+ * @private
2780
+ */
2781
+ _parseOptionsImplied() {
2782
+ const dualHelper = new DualOptions(this.options);
2783
+ const hasCustomOptionValue = /* @__PURE__ */ __name((optionKey) => {
2784
+ return this.getOptionValue(optionKey) !== void 0 && ![
2785
+ "default",
2786
+ "implied"
2787
+ ].includes(this.getOptionValueSource(optionKey));
2788
+ }, "hasCustomOptionValue");
2789
+ this.options.filter((option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
2790
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
2791
+ this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
2792
+ });
2793
+ });
2794
+ }
2795
+ /**
2796
+ * Argument `name` is missing.
2797
+ *
2798
+ * @param {string} name
2799
+ * @private
2800
+ */
2801
+ missingArgument(name) {
2802
+ const message = `error: missing required argument '${name}'`;
2803
+ this.error(message, {
2804
+ code: "commander.missingArgument"
2805
+ });
2806
+ }
2807
+ /**
2808
+ * `Option` is missing an argument.
2809
+ *
2810
+ * @param {Option} option
2811
+ * @private
2812
+ */
2813
+ optionMissingArgument(option) {
2814
+ const message = `error: option '${option.flags}' argument missing`;
2815
+ this.error(message, {
2816
+ code: "commander.optionMissingArgument"
2817
+ });
2818
+ }
2819
+ /**
2820
+ * `Option` does not have a value, and is a mandatory option.
2821
+ *
2822
+ * @param {Option} option
2823
+ * @private
2824
+ */
2825
+ missingMandatoryOptionValue(option) {
2826
+ const message = `error: required option '${option.flags}' not specified`;
2827
+ this.error(message, {
2828
+ code: "commander.missingMandatoryOptionValue"
2829
+ });
2830
+ }
2831
+ /**
2832
+ * `Option` conflicts with another option.
2833
+ *
2834
+ * @param {Option} option
2835
+ * @param {Option} conflictingOption
2836
+ * @private
2837
+ */
2838
+ _conflictingOption(option, conflictingOption) {
2839
+ const findBestOptionFromValue = /* @__PURE__ */ __name((option2) => {
2840
+ const optionKey = option2.attributeName();
2841
+ const optionValue = this.getOptionValue(optionKey);
2842
+ const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
2843
+ const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
2844
+ if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
2845
+ return negativeOption;
2846
+ }
2847
+ return positiveOption || option2;
2848
+ }, "findBestOptionFromValue");
2849
+ const getErrorMessage = /* @__PURE__ */ __name((option2) => {
2850
+ const bestOption = findBestOptionFromValue(option2);
2851
+ const optionKey = bestOption.attributeName();
2852
+ const source = this.getOptionValueSource(optionKey);
2853
+ if (source === "env") {
2854
+ return `environment variable '${bestOption.envVar}'`;
2855
+ }
2856
+ return `option '${bestOption.flags}'`;
2857
+ }, "getErrorMessage");
2858
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2859
+ this.error(message, {
2860
+ code: "commander.conflictingOption"
2861
+ });
2862
+ }
2863
+ /**
2864
+ * Unknown option `flag`.
2865
+ *
2866
+ * @param {string} flag
2867
+ * @private
2868
+ */
2869
+ unknownOption(flag) {
2870
+ if (this._allowUnknownOption) return;
2871
+ let suggestion = "";
2872
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
2873
+ let candidateFlags = [];
2874
+ let command = this;
2875
+ do {
2876
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
2877
+ candidateFlags = candidateFlags.concat(moreFlags);
2878
+ command = command.parent;
2879
+ } while (command && !command._enablePositionalOptions);
2880
+ suggestion = suggestSimilar(flag, candidateFlags);
2881
+ }
2882
+ const message = `error: unknown option '${flag}'${suggestion}`;
2883
+ this.error(message, {
2884
+ code: "commander.unknownOption"
2885
+ });
2886
+ }
2887
+ /**
2888
+ * Excess arguments, more than expected.
2889
+ *
2890
+ * @param {string[]} receivedArgs
2891
+ * @private
2892
+ */
2893
+ _excessArguments(receivedArgs) {
2894
+ if (this._allowExcessArguments) return;
2895
+ const expected = this.registeredArguments.length;
2896
+ const s = expected === 1 ? "" : "s";
2897
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
2898
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
2899
+ this.error(message, {
2900
+ code: "commander.excessArguments"
2901
+ });
2902
+ }
2903
+ /**
2904
+ * Unknown command.
2905
+ *
2906
+ * @private
2907
+ */
2908
+ unknownCommand() {
2909
+ const unknownName = this.args[0];
2910
+ let suggestion = "";
2911
+ if (this._showSuggestionAfterError) {
2912
+ const candidateNames = [];
2913
+ this.createHelp().visibleCommands(this).forEach((command) => {
2914
+ candidateNames.push(command.name());
2915
+ if (command.alias()) candidateNames.push(command.alias());
2916
+ });
2917
+ suggestion = suggestSimilar(unknownName, candidateNames);
2918
+ }
2919
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
2920
+ this.error(message, {
2921
+ code: "commander.unknownCommand"
2922
+ });
2923
+ }
2924
+ /**
2925
+ * Get or set the program version.
2926
+ *
2927
+ * This method auto-registers the "-V, --version" option which will print the version number.
2928
+ *
2929
+ * You can optionally supply the flags and description to override the defaults.
2930
+ *
2931
+ * @param {string} [str]
2932
+ * @param {string} [flags]
2933
+ * @param {string} [description]
2934
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
2935
+ */
2936
+ version(str, flags, description) {
2937
+ if (str === void 0) return this._version;
2938
+ this._version = str;
2939
+ flags = flags || "-V, --version";
2940
+ description = description || "output the version number";
2941
+ const versionOption = this.createOption(flags, description);
2942
+ this._versionOptionName = versionOption.attributeName();
2943
+ this._registerOption(versionOption);
2944
+ this.on("option:" + versionOption.name(), () => {
2945
+ this._outputConfiguration.writeOut(`${str}
2946
+ `);
2947
+ this._exit(0, "commander.version", str);
2948
+ });
2949
+ return this;
2950
+ }
2951
+ /**
2952
+ * Set the description.
2953
+ *
2954
+ * @param {string} [str]
2955
+ * @param {object} [argsDescription]
2956
+ * @return {(string|Command)}
2957
+ */
2958
+ description(str, argsDescription) {
2959
+ if (str === void 0 && argsDescription === void 0) return this._description;
2960
+ this._description = str;
2961
+ if (argsDescription) {
2962
+ this._argsDescription = argsDescription;
2963
+ }
2964
+ return this;
2965
+ }
2966
+ /**
2967
+ * Set the summary. Used when listed as subcommand of parent.
2968
+ *
2969
+ * @param {string} [str]
2970
+ * @return {(string|Command)}
2971
+ */
2972
+ summary(str) {
2973
+ if (str === void 0) return this._summary;
2974
+ this._summary = str;
2975
+ return this;
2976
+ }
2977
+ /**
2978
+ * Set an alias for the command.
2979
+ *
2980
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
2981
+ *
2982
+ * @param {string} [alias]
2983
+ * @return {(string|Command)}
2984
+ */
2985
+ alias(alias) {
2986
+ if (alias === void 0) return this._aliases[0];
2987
+ let command = this;
2988
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
2989
+ command = this.commands[this.commands.length - 1];
2990
+ }
2991
+ if (alias === command._name) throw new Error("Command alias can't be the same as its name");
2992
+ const matchingCommand = this.parent?._findCommand(alias);
2993
+ if (matchingCommand) {
2994
+ const existingCmd = [
2995
+ matchingCommand.name()
2996
+ ].concat(matchingCommand.aliases()).join("|");
2997
+ throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
2998
+ }
2999
+ command._aliases.push(alias);
3000
+ return this;
3001
+ }
3002
+ /**
3003
+ * Set aliases for the command.
3004
+ *
3005
+ * Only the first alias is shown in the auto-generated help.
3006
+ *
3007
+ * @param {string[]} [aliases]
3008
+ * @return {(string[]|Command)}
3009
+ */
3010
+ aliases(aliases) {
3011
+ if (aliases === void 0) return this._aliases;
3012
+ aliases.forEach((alias) => this.alias(alias));
3013
+ return this;
3014
+ }
3015
+ /**
3016
+ * Set / get the command usage `str`.
3017
+ *
3018
+ * @param {string} [str]
3019
+ * @return {(string|Command)}
3020
+ */
3021
+ usage(str) {
3022
+ if (str === void 0) {
3023
+ if (this._usage) return this._usage;
3024
+ const args = this.registeredArguments.map((arg) => {
3025
+ return humanReadableArgName(arg);
3026
+ });
3027
+ return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
3028
+ }
3029
+ this._usage = str;
3030
+ return this;
3031
+ }
3032
+ /**
3033
+ * Get or set the name of the command.
3034
+ *
3035
+ * @param {string} [str]
3036
+ * @return {(string|Command)}
3037
+ */
3038
+ name(str) {
3039
+ if (str === void 0) return this._name;
3040
+ this._name = str;
3041
+ return this;
3042
+ }
3043
+ /**
3044
+ * Set/get the help group heading for this subcommand in parent command's help.
3045
+ *
3046
+ * @param {string} [heading]
3047
+ * @return {Command | string}
3048
+ */
3049
+ helpGroup(heading) {
3050
+ if (heading === void 0) return this._helpGroupHeading ?? "";
3051
+ this._helpGroupHeading = heading;
3052
+ return this;
3053
+ }
3054
+ /**
3055
+ * Set/get the default help group heading for subcommands added to this command.
3056
+ * (This does not override a group set directly on the subcommand using .helpGroup().)
3057
+ *
3058
+ * @example
3059
+ * program.commandsGroup('Development Commands:);
3060
+ * program.command('watch')...
3061
+ * program.command('lint')...
3062
+ * ...
3063
+ *
3064
+ * @param {string} [heading]
3065
+ * @returns {Command | string}
3066
+ */
3067
+ commandsGroup(heading) {
3068
+ if (heading === void 0) return this._defaultCommandGroup ?? "";
3069
+ this._defaultCommandGroup = heading;
3070
+ return this;
3071
+ }
3072
+ /**
3073
+ * Set/get the default help group heading for options added to this command.
3074
+ * (This does not override a group set directly on the option using .helpGroup().)
3075
+ *
3076
+ * @example
3077
+ * program
3078
+ * .optionsGroup('Development Options:')
3079
+ * .option('-d, --debug', 'output extra debugging')
3080
+ * .option('-p, --profile', 'output profiling information')
3081
+ *
3082
+ * @param {string} [heading]
3083
+ * @returns {Command | string}
3084
+ */
3085
+ optionsGroup(heading) {
3086
+ if (heading === void 0) return this._defaultOptionGroup ?? "";
3087
+ this._defaultOptionGroup = heading;
3088
+ return this;
3089
+ }
3090
+ /**
3091
+ * @param {Option} option
3092
+ * @private
3093
+ */
3094
+ _initOptionGroup(option) {
3095
+ if (this._defaultOptionGroup && !option.helpGroupHeading) option.helpGroup(this._defaultOptionGroup);
3096
+ }
3097
+ /**
3098
+ * @param {Command} cmd
3099
+ * @private
3100
+ */
3101
+ _initCommandGroup(cmd) {
3102
+ if (this._defaultCommandGroup && !cmd.helpGroup()) cmd.helpGroup(this._defaultCommandGroup);
3103
+ }
3104
+ /**
3105
+ * Set the name of the command from script filename, such as process.argv[1],
3106
+ * or require.main.filename, or __filename.
3107
+ *
3108
+ * (Used internally and public although not documented in README.)
3109
+ *
3110
+ * @example
3111
+ * program.nameFromFilename(require.main.filename);
3112
+ *
3113
+ * @param {string} filename
3114
+ * @return {Command}
3115
+ */
3116
+ nameFromFilename(filename) {
3117
+ this._name = path2.basename(filename, path2.extname(filename));
3118
+ return this;
3119
+ }
3120
+ /**
3121
+ * Get or set the directory for searching for executable subcommands of this command.
3122
+ *
3123
+ * @example
3124
+ * program.executableDir(__dirname);
3125
+ * // or
3126
+ * program.executableDir('subcommands');
3127
+ *
3128
+ * @param {string} [path]
3129
+ * @return {(string|null|Command)}
3130
+ */
3131
+ executableDir(path3) {
3132
+ if (path3 === void 0) return this._executableDir;
3133
+ this._executableDir = path3;
3134
+ return this;
3135
+ }
3136
+ /**
3137
+ * Return program help documentation.
3138
+ *
3139
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
3140
+ * @return {string}
3141
+ */
3142
+ helpInformation(contextOptions) {
3143
+ const helper = this.createHelp();
3144
+ const context = this._getOutputContext(contextOptions);
3145
+ helper.prepareContext({
3146
+ error: context.error,
3147
+ helpWidth: context.helpWidth,
3148
+ outputHasColors: context.hasColors
3149
+ });
3150
+ const text = helper.formatHelp(this, helper);
3151
+ if (context.hasColors) return text;
3152
+ return this._outputConfiguration.stripColor(text);
3153
+ }
3154
+ /**
3155
+ * @typedef HelpContext
3156
+ * @type {object}
3157
+ * @property {boolean} error
3158
+ * @property {number} helpWidth
3159
+ * @property {boolean} hasColors
3160
+ * @property {function} write - includes stripColor if needed
3161
+ *
3162
+ * @returns {HelpContext}
3163
+ * @private
3164
+ */
3165
+ _getOutputContext(contextOptions) {
3166
+ contextOptions = contextOptions || {};
3167
+ const error = !!contextOptions.error;
3168
+ let baseWrite;
3169
+ let hasColors;
3170
+ let helpWidth;
3171
+ if (error) {
3172
+ baseWrite = /* @__PURE__ */ __name((str) => this._outputConfiguration.writeErr(str), "baseWrite");
3173
+ hasColors = this._outputConfiguration.getErrHasColors();
3174
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
3175
+ } else {
3176
+ baseWrite = /* @__PURE__ */ __name((str) => this._outputConfiguration.writeOut(str), "baseWrite");
3177
+ hasColors = this._outputConfiguration.getOutHasColors();
3178
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
3179
+ }
3180
+ const write = /* @__PURE__ */ __name((str) => {
3181
+ if (!hasColors) str = this._outputConfiguration.stripColor(str);
3182
+ return baseWrite(str);
3183
+ }, "write");
3184
+ return {
3185
+ error,
3186
+ write,
3187
+ hasColors,
3188
+ helpWidth
3189
+ };
3190
+ }
3191
+ /**
3192
+ * Output help information for this command.
3193
+ *
3194
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
3195
+ *
3196
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
3197
+ */
3198
+ outputHelp(contextOptions) {
3199
+ let deprecatedCallback;
3200
+ if (typeof contextOptions === "function") {
3201
+ deprecatedCallback = contextOptions;
3202
+ contextOptions = void 0;
3203
+ }
3204
+ const outputContext = this._getOutputContext(contextOptions);
3205
+ const eventContext = {
3206
+ error: outputContext.error,
3207
+ write: outputContext.write,
3208
+ command: this
3209
+ };
3210
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
3211
+ this.emit("beforeHelp", eventContext);
3212
+ let helpInformation = this.helpInformation({
3213
+ error: outputContext.error
3214
+ });
3215
+ if (deprecatedCallback) {
3216
+ helpInformation = deprecatedCallback(helpInformation);
3217
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
3218
+ throw new Error("outputHelp callback must return a string or a Buffer");
3219
+ }
3220
+ }
3221
+ outputContext.write(helpInformation);
3222
+ if (this._getHelpOption()?.long) {
3223
+ this.emit(this._getHelpOption().long);
3224
+ }
3225
+ this.emit("afterHelp", eventContext);
3226
+ this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", eventContext));
3227
+ }
3228
+ /**
3229
+ * You can pass in flags and a description to customise the built-in help option.
3230
+ * Pass in false to disable the built-in help option.
3231
+ *
3232
+ * @example
3233
+ * program.helpOption('-?, --help' 'show help'); // customise
3234
+ * program.helpOption(false); // disable
3235
+ *
3236
+ * @param {(string | boolean)} flags
3237
+ * @param {string} [description]
3238
+ * @return {Command} `this` command for chaining
3239
+ */
3240
+ helpOption(flags, description) {
3241
+ if (typeof flags === "boolean") {
3242
+ if (flags) {
3243
+ if (this._helpOption === null) this._helpOption = void 0;
3244
+ if (this._defaultOptionGroup) {
3245
+ this._initOptionGroup(this._getHelpOption());
3246
+ }
3247
+ } else {
3248
+ this._helpOption = null;
3249
+ }
3250
+ return this;
3251
+ }
3252
+ this._helpOption = this.createOption(flags ?? "-h, --help", description ?? "display help for command");
3253
+ if (flags || description) this._initOptionGroup(this._helpOption);
3254
+ return this;
3255
+ }
3256
+ /**
3257
+ * Lazy create help option.
3258
+ * Returns null if has been disabled with .helpOption(false).
3259
+ *
3260
+ * @returns {(Option | null)} the help option
3261
+ * @package
3262
+ */
3263
+ _getHelpOption() {
3264
+ if (this._helpOption === void 0) {
3265
+ this.helpOption(void 0, void 0);
3266
+ }
3267
+ return this._helpOption;
3268
+ }
3269
+ /**
3270
+ * Supply your own option to use for the built-in help option.
3271
+ * This is an alternative to using helpOption() to customise the flags and description etc.
3272
+ *
3273
+ * @param {Option} option
3274
+ * @return {Command} `this` command for chaining
3275
+ */
3276
+ addHelpOption(option) {
3277
+ this._helpOption = option;
3278
+ this._initOptionGroup(option);
3279
+ return this;
3280
+ }
3281
+ /**
3282
+ * Output help information and exit.
3283
+ *
3284
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
3285
+ *
3286
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
3287
+ */
3288
+ help(contextOptions) {
3289
+ this.outputHelp(contextOptions);
3290
+ let exitCode = Number(process2.exitCode ?? 0);
3291
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
3292
+ exitCode = 1;
3293
+ }
3294
+ this._exit(exitCode, "commander.help", "(outputHelp)");
3295
+ }
3296
+ /**
3297
+ * // Do a little typing to coordinate emit and listener for the help text events.
3298
+ * @typedef HelpTextEventContext
3299
+ * @type {object}
3300
+ * @property {boolean} error
3301
+ * @property {Command} command
3302
+ * @property {function} write
3303
+ */
3304
+ /**
3305
+ * Add additional text to be displayed with the built-in help.
3306
+ *
3307
+ * Position is 'before' or 'after' to affect just this command,
3308
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
3309
+ *
3310
+ * @param {string} position - before or after built-in help
3311
+ * @param {(string | Function)} text - string to add, or a function returning a string
3312
+ * @return {Command} `this` command for chaining
3313
+ */
3314
+ addHelpText(position, text) {
3315
+ const allowedValues = [
3316
+ "beforeAll",
3317
+ "before",
3318
+ "after",
3319
+ "afterAll"
3320
+ ];
3321
+ if (!allowedValues.includes(position)) {
3322
+ throw new Error(`Unexpected value for position to addHelpText.
3323
+ Expecting one of '${allowedValues.join("', '")}'`);
3324
+ }
3325
+ const helpEvent = `${position}Help`;
3326
+ this.on(helpEvent, (context) => {
3327
+ let helpStr;
3328
+ if (typeof text === "function") {
3329
+ helpStr = text({
3330
+ error: context.error,
3331
+ command: context.command
3332
+ });
3333
+ } else {
3334
+ helpStr = text;
3335
+ }
3336
+ if (helpStr) {
3337
+ context.write(`${helpStr}
3338
+ `);
3339
+ }
3340
+ });
3341
+ return this;
3342
+ }
3343
+ /**
3344
+ * Output help information if help flags specified
3345
+ *
3346
+ * @param {Array} args - array of options to search for help flags
3347
+ * @private
3348
+ */
3349
+ _outputHelpIfRequested(args) {
3350
+ const helpOption = this._getHelpOption();
3351
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
3352
+ if (helpRequested) {
3353
+ this.outputHelp();
3354
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
3355
+ }
3356
+ }
3357
+ };
3358
+ function incrementNodeInspectorPort(args) {
3359
+ return args.map((arg) => {
3360
+ if (!arg.startsWith("--inspect")) {
3361
+ return arg;
3362
+ }
3363
+ let debugOption;
3364
+ let debugHost = "127.0.0.1";
3365
+ let debugPort = "9229";
3366
+ let match;
3367
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
3368
+ debugOption = match[1];
3369
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
3370
+ debugOption = match[1];
3371
+ if (/^\d+$/.test(match[3])) {
3372
+ debugPort = match[3];
3373
+ } else {
3374
+ debugHost = match[3];
3375
+ }
3376
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
3377
+ debugOption = match[1];
3378
+ debugHost = match[3];
3379
+ debugPort = match[4];
3380
+ }
3381
+ if (debugOption && debugPort !== "0") {
3382
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
3383
+ }
3384
+ return arg;
3385
+ });
3386
+ }
3387
+ __name(incrementNodeInspectorPort, "incrementNodeInspectorPort");
3388
+ function useColor() {
3389
+ if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false") return false;
3390
+ if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== void 0) return true;
3391
+ return void 0;
3392
+ }
3393
+ __name(useColor, "useColor");
3394
+ exports$1.Command = Command2;
3395
+ exports$1.useColor = useColor;
3396
+ }
3397
+ });
3398
+
3399
+ // ../../node_modules/.pnpm/commander@14.0.2/node_modules/commander/index.js
3400
+ var require_commander = __commonJS({
3401
+ "../../node_modules/.pnpm/commander@14.0.2/node_modules/commander/index.js"(exports$1) {
3402
+ init_esm_shims();
3403
+ var { Argument } = require_argument();
3404
+ var { Command: Command2 } = require_command();
3405
+ var { CommanderError, InvalidArgumentError } = require_error();
3406
+ var { Help } = require_help();
3407
+ var { Option } = require_option();
3408
+ exports$1.program = new Command2();
3409
+ exports$1.createCommand = (name) => new Command2(name);
3410
+ exports$1.createOption = (flags, description) => new Option(flags, description);
3411
+ exports$1.createArgument = (name, description) => new Argument(name, description);
3412
+ exports$1.Command = Command2;
3413
+ exports$1.Option = Option;
3414
+ exports$1.Argument = Argument;
3415
+ exports$1.Help = Help;
3416
+ exports$1.CommanderError = CommanderError;
3417
+ exports$1.InvalidArgumentError = InvalidArgumentError;
3418
+ exports$1.InvalidOptionArgumentError = InvalidArgumentError;
3419
+ }
3420
+ });
3421
+
3422
+ // ../../node_modules/.pnpm/@commander-js+extra-typings@14.0.0_commander@14.0.2/node_modules/@commander-js/extra-typings/index.js
3423
+ var require_extra_typings = __commonJS({
3424
+ "../../node_modules/.pnpm/@commander-js+extra-typings@14.0.0_commander@14.0.2/node_modules/@commander-js/extra-typings/index.js"(exports$1, module) {
3425
+ init_esm_shims();
3426
+ var commander = require_commander();
3427
+ exports$1 = module.exports = {};
3428
+ exports$1.program = new commander.Command();
3429
+ exports$1.Argument = commander.Argument;
3430
+ exports$1.Command = commander.Command;
3431
+ exports$1.CommanderError = commander.CommanderError;
3432
+ exports$1.Help = commander.Help;
3433
+ exports$1.InvalidArgumentError = commander.InvalidArgumentError;
3434
+ exports$1.InvalidOptionArgumentError = commander.InvalidArgumentError;
3435
+ exports$1.Option = commander.Option;
3436
+ exports$1.createCommand = (name) => new commander.Command(name);
3437
+ exports$1.createOption = (flags, description) => new commander.Option(flags, description);
3438
+ exports$1.createArgument = (name, description) => new commander.Argument(name, description);
3439
+ }
3440
+ });
3441
+
3442
+ // src/cli.ts
3443
+ init_esm_shims();
3444
+ var import_commander = __toESM(require_extra_typings());
3445
+
3446
+ // src/commands/BuildCommand.ts
3447
+ init_esm_shims();
3448
+
3449
+ // src/runtime/SeedcordBuildRunner.ts
3450
+ init_esm_shims();
3451
+
3452
+ // src/builder/BootstrapWriter.ts
3453
+ init_esm_shims();
3454
+ var BootstrapWriter = class {
3455
+ static {
3456
+ __name(this, "BootstrapWriter");
3457
+ }
3458
+ logger;
3459
+ constructor(logger) {
3460
+ this.logger = logger;
3461
+ }
3462
+ async write(config, emittedEntry) {
3463
+ const target = config.build.bootstrap;
3464
+ const relativeImport = this.formatImportPath(relative(dirname(target), emittedEntry));
3465
+ const contents = `import '${relativeImport}';
3466
+ `;
3467
+ try {
3468
+ await mkdir(dirname(target), {
3469
+ recursive: true
3470
+ });
3471
+ await writeFile(target, contents, "utf8");
3472
+ } catch (error) {
3473
+ const reason = error instanceof Error ? error.message : "Unknown error";
3474
+ throw new SeedcordError(SeedcordErrorCode.CliBootstrapWriteFailed, [
3475
+ target,
3476
+ reason
3477
+ ]);
3478
+ }
3479
+ this.logger.info(`Bootstrap file created at ${target}`);
3480
+ }
3481
+ formatImportPath(fragment) {
3482
+ let normalized = fragment.replace(/\\/g, "/");
3483
+ if (!normalized.startsWith(".")) normalized = `./${normalized}`;
3484
+ return normalized;
3485
+ }
3486
+ };
3487
+
3488
+ // src/builder/TypeScriptProjectBuilder.ts
3489
+ init_esm_shims();
3490
+
3491
+ // src/builder/EntryPointCollector.ts
3492
+ init_esm_shims();
3493
+ var EntryPointCollector = class {
3494
+ static {
3495
+ __name(this, "EntryPointCollector");
3496
+ }
3497
+ collect(config, tsconfigPath) {
3498
+ const parsed = this.parseTsconfig(tsconfigPath);
3499
+ const entries = /* @__PURE__ */ new Map();
3500
+ for (const filePath of parsed.fileNames) {
3501
+ if (!this.shouldEmitFile(config, filePath)) continue;
3502
+ entries.set(this.createEntryKey(config, filePath), filePath);
3503
+ }
3504
+ const entryKey = this.createEntryKey(config, config.entry);
3505
+ if (!entries.size || !entries.has(entryKey)) entries.set(entryKey, config.entry);
3506
+ return {
3507
+ entryMap: Object.fromEntries(entries),
3508
+ primaryKey: entryKey
3509
+ };
3510
+ }
3511
+ parseTsconfig(tsconfigPath) {
3512
+ const configFile = ts2.readConfigFile(tsconfigPath, (filePath) => ts2.sys.readFile(filePath));
3513
+ if (configFile.error) {
3514
+ const reason = this.formatDiagnostics([
3515
+ configFile.error
3516
+ ]);
3517
+ throw new SeedcordError(SeedcordErrorCode.CliBuildTsconfigInvalid, [
3518
+ tsconfigPath,
3519
+ reason
3520
+ ]);
3521
+ }
3522
+ const parsed = ts2.parseJsonConfigFileContent(configFile.config, ts2.sys, dirname(tsconfigPath), void 0, tsconfigPath);
3523
+ if (parsed.errors.length) {
3524
+ const reason = this.formatDiagnostics(parsed.errors);
3525
+ throw new SeedcordError(SeedcordErrorCode.CliBuildTsconfigInvalid, [
3526
+ tsconfigPath,
3527
+ reason
3528
+ ]);
3529
+ }
3530
+ return parsed;
3531
+ }
3532
+ shouldEmitFile(config, filePath) {
3533
+ if (!this.isWithinRoot(config.root, filePath)) return false;
3534
+ if (/\.d\.[cm]?ts$/i.test(filePath)) return false;
3535
+ return /\.[cm]?tsx?$/i.test(filePath);
3536
+ }
3537
+ isWithinRoot(root, target) {
3538
+ const relativePath = relative(root, target);
3539
+ return relativePath === "" || !relativePath.startsWith("..") && !relativePath.startsWith("..\\");
3540
+ }
3541
+ createEntryKey(config, filePath) {
3542
+ const relativePath = relative(config.root, filePath);
3543
+ const fallback = this.createEntryFallback(filePath);
3544
+ if (relativePath.startsWith("..")) return fallback;
3545
+ const sanitized = relativePath.replace(/\\/g, "/").replace(/^\.\//, "").replace(/\.[^.]+$/, "").replace(/[^a-zA-Z0-9\-/_]/g, "-");
3546
+ return sanitized || fallback;
3547
+ }
3548
+ createEntryFallback(filePath) {
3549
+ const base = basename(filePath, extname(filePath)) || "seedcord-entry";
3550
+ return base.replace(/[^a-zA-Z0-9-_]/g, "-");
3551
+ }
3552
+ formatDiagnostics(diagnostics) {
3553
+ return diagnostics.map((diagnostic) => {
3554
+ const message = ts2.flattenDiagnosticMessageText(diagnostic.messageText, "\n");
3555
+ if (diagnostic.file && typeof diagnostic.start === "number") {
3556
+ const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
3557
+ return `${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`;
3558
+ }
3559
+ return message;
3560
+ }).join("\n");
3561
+ }
3562
+ };
3563
+
3564
+ // src/builder/RelativeSpecifierTransformer.ts
3565
+ init_esm_shims();
3566
+ var RelativeSpecifierTransformer = class {
3567
+ static {
3568
+ __name(this, "RelativeSpecifierTransformer");
3569
+ }
3570
+ async transform(outDir) {
3571
+ const files = await this.collectJavaScriptFiles(outDir);
3572
+ for (const filePath of files) {
3573
+ await this.rewriteFile(filePath);
3574
+ }
3575
+ }
3576
+ async collectJavaScriptFiles(rootDir) {
3577
+ const pending = [
3578
+ rootDir
3579
+ ];
3580
+ const files = [];
3581
+ while (pending.length) {
3582
+ const current = pending.pop();
3583
+ if (!current) continue;
3584
+ const entries = await readdir(current, {
3585
+ withFileTypes: true
3586
+ });
3587
+ for (const entry of entries) {
3588
+ const fullPath = resolve(current, entry.name);
3589
+ if (entry.isDirectory()) pending.push(fullPath);
3590
+ else if (entry.isFile() && entry.name.endsWith(".js")) files.push(fullPath);
3591
+ }
3592
+ }
3593
+ return files;
3594
+ }
3595
+ async rewriteFile(filePath) {
3596
+ const source = await readFile(filePath, "utf8");
3597
+ const replacements = this.extractSpecifierReplacements(source);
3598
+ if (!replacements.length) return;
3599
+ let mutated = source;
3600
+ for (const replacement of replacements.sort((a, b) => b.start - a.start)) {
3601
+ mutated = `${mutated.slice(0, replacement.start)}${replacement.text}${mutated.slice(replacement.end)}`;
3602
+ }
3603
+ await writeFile(filePath, mutated, "utf8");
3604
+ }
3605
+ extractSpecifierReplacements(sourceText) {
3606
+ const sourceFile = ts2.createSourceFile("generated.js", sourceText, ts2.ScriptTarget.ES2022, true, ts2.ScriptKind.JS);
3607
+ const replacements = [];
3608
+ const visit = /* @__PURE__ */ __name((node) => {
3609
+ if (ts2.isImportDeclaration(node) && ts2.isStringLiteralLike(node.moduleSpecifier)) {
3610
+ this.scheduleReplacement(sourceFile, node.moduleSpecifier, replacements);
3611
+ } else if (ts2.isExportDeclaration(node) && node.moduleSpecifier && ts2.isStringLiteralLike(node.moduleSpecifier)) {
3612
+ this.scheduleReplacement(sourceFile, node.moduleSpecifier, replacements);
3613
+ } else if (ts2.isCallExpression(node) && node.expression.kind === ts2.SyntaxKind.ImportKeyword && node.arguments.length === 1) {
3614
+ const [arg] = node.arguments;
3615
+ if (arg && ts2.isStringLiteralLike(arg)) {
3616
+ this.scheduleReplacement(sourceFile, arg, replacements);
3617
+ }
3618
+ }
3619
+ ts2.forEachChild(node, visit);
3620
+ }, "visit");
3621
+ visit(sourceFile);
3622
+ return replacements;
3623
+ }
3624
+ scheduleReplacement(sourceFile, literal, replacements) {
3625
+ const updated = this.appendJsExtension(literal.text);
3626
+ if (updated === literal.text) return;
3627
+ const literalText = literal.getText(sourceFile);
3628
+ const quote = literalText.startsWith("`") ? "`" : literalText.startsWith("'") ? "'" : '"';
3629
+ replacements.push({
3630
+ start: literal.getStart(sourceFile),
3631
+ end: literal.getEnd(),
3632
+ text: `${quote}${updated}${quote}`
3633
+ });
3634
+ }
3635
+ appendJsExtension(specifier) {
3636
+ if (!specifier.startsWith("./") && !specifier.startsWith("../")) return specifier;
3637
+ if (/\.(?:[cm]?js|json)$/i.test(specifier)) return specifier;
3638
+ return `${specifier}.js`;
3639
+ }
3640
+ };
3641
+
3642
+ // src/builder/TypeScriptProjectBuilder.ts
3643
+ var TypeScriptProjectBuilder = class {
3644
+ static {
3645
+ __name(this, "TypeScriptProjectBuilder");
3646
+ }
3647
+ logger;
3648
+ entries;
3649
+ specifierTransformer;
3650
+ constructor(logger, entries = new EntryPointCollector(), specifierTransformer = new RelativeSpecifierTransformer()) {
3651
+ this.logger = logger;
3652
+ this.entries = entries;
3653
+ this.specifierTransformer = specifierTransformer;
3654
+ }
3655
+ async build(config) {
3656
+ const tsconfigPath = this.resolveTsconfig(config);
3657
+ const { entryMap, primaryKey } = this.entries.collect(config, tsconfigPath);
3658
+ this.logger.info(`Building Seedcord project via ${tsconfigPath}`);
3659
+ try {
3660
+ await build({
3661
+ entry: entryMap,
3662
+ outDir: config.build.outDir,
3663
+ format: [
3664
+ "esm"
3665
+ ],
3666
+ outExtension: /* @__PURE__ */ __name(() => ({
3667
+ js: ".js"
3668
+ }), "outExtension"),
3669
+ shims: false,
3670
+ splitting: false,
3671
+ sourcemap: true,
3672
+ clean: false,
3673
+ skipNodeModulesBundle: true,
3674
+ minify: false,
3675
+ bundle: false,
3676
+ dts: false,
3677
+ target: "node22",
3678
+ platform: "node",
3679
+ keepNames: true,
3680
+ treeshake: false,
3681
+ tsconfig: tsconfigPath,
3682
+ silent: true
3683
+ });
3684
+ await this.specifierTransformer.transform(config.build.outDir);
3685
+ } catch (error) {
3686
+ const reason = error instanceof Error ? error.message : "Unknown build error";
3687
+ throw new SeedcordError(SeedcordErrorCode.CliBuildFailed, [
3688
+ reason
3689
+ ]);
3690
+ }
3691
+ const emittedEntry = this.resolveEmittedEntry(config.build.outDir, primaryKey);
3692
+ if (!existsSync(emittedEntry)) {
3693
+ throw new SeedcordError(SeedcordErrorCode.CliBuildFailed, [
3694
+ `Expected output file ${emittedEntry} missing after build`
3695
+ ]);
3696
+ }
3697
+ this.logger.info(`Emitted entry: ${emittedEntry}`);
3698
+ return {
3699
+ emittedEntry
3700
+ };
3701
+ }
3702
+ resolveTsconfig(config) {
3703
+ if (config.build.tsconfig) {
3704
+ if (!existsSync(config.build.tsconfig)) {
3705
+ throw new SeedcordError(SeedcordErrorCode.CliBuildTsconfigNotFound, [
3706
+ config.build.tsconfig
3707
+ ]);
3708
+ }
3709
+ return config.build.tsconfig;
3710
+ }
3711
+ const configDir = dirname(config.configFile);
3712
+ const candidates = [
3713
+ "tsconfig.build.json",
3714
+ "tsconfig.json"
3715
+ ].map((file) => resolve(configDir, file)).filter((candidate) => existsSync(candidate));
3716
+ const [firstCandidate] = candidates;
3717
+ if (firstCandidate) return firstCandidate;
3718
+ throw new SeedcordError(SeedcordErrorCode.CliBuildTsconfigNotFound, [
3719
+ configDir
3720
+ ]);
3721
+ }
3722
+ resolveEmittedEntry(outDir, entryKey) {
3723
+ return resolve(outDir, `${entryKey}.js`);
3724
+ }
3725
+ };
3726
+
3727
+ // src/config/ConfigLoader.ts
3728
+ init_esm_shims();
3729
+
3730
+ // src/utils/resolveDefaultExport.ts
3731
+ init_esm_shims();
3732
+ function resolveDefaultExport(moduleExport) {
3733
+ let current = moduleExport;
3734
+ const visited = /* @__PURE__ */ new Set();
3735
+ while (isObjectWithDefault(current) && !visited.has(current)) {
3736
+ visited.add(current);
3737
+ current = current.default;
3738
+ }
3739
+ return current;
3740
+ }
3741
+ __name(resolveDefaultExport, "resolveDefaultExport");
3742
+ function isObjectWithDefault(value) {
3743
+ return Boolean(value && typeof value === "object" && "default" in value);
3744
+ }
3745
+ __name(isObjectWithDefault, "isObjectWithDefault");
3746
+
3747
+ // src/config/ConfigLoader.ts
3748
+ var ConfigLoader = class {
3749
+ static {
3750
+ __name(this, "ConfigLoader");
3751
+ }
3752
+ modules;
3753
+ logger;
3754
+ constructor(modules, logger) {
3755
+ this.modules = modules;
3756
+ this.logger = logger;
3757
+ }
3758
+ async load(configPath) {
3759
+ const loadedModule = await this.modules.importModule(configPath);
3760
+ const rawExport = resolveDefaultExport(loadedModule);
3761
+ const config = await this.unwrapConfig(rawExport);
3762
+ const configDir = dirname(configPath);
3763
+ const root = resolve(configDir, config.root ?? ".");
3764
+ const instance = this.resolveWithinRoot(root, config.instance);
3765
+ const entry = this.resolveWithinRoot(root, config.entry);
3766
+ this.assertEntryWithinRoot(root, entry);
3767
+ const build = this.resolveBuildOptions(configDir, config.build);
3768
+ this.logger.info(`Loaded configuration from ${configPath}`);
3769
+ this.logger.debug(`Resolved root: ${root}`);
3770
+ this.logger.debug(`Resolved instance: ${instance}`);
3771
+ this.logger.debug(`Resolved entry: ${entry}`);
3772
+ this.logger.debug(`Resolved build outDir: ${build.outDir}`);
3773
+ if (build.tsconfig) this.logger.debug(`Resolved build tsconfig: ${build.tsconfig}`);
3774
+ this.logger.debug(`Resolved bootstrap: ${build.bootstrap}`);
3775
+ return {
3776
+ instance,
3777
+ root,
3778
+ configFile: configPath,
3779
+ entry,
3780
+ build
3781
+ };
3782
+ }
3783
+ // eslint-disable-next-line complexity
3784
+ async unwrapConfig(raw) {
3785
+ const resolved = await Promise.resolve(raw);
3786
+ if (!resolved || typeof resolved !== "object") {
3787
+ throw new SeedcordError(SeedcordErrorCode.CliConfigInvalidExport);
3788
+ }
3789
+ const cfg = resolved;
3790
+ if (!cfg.instance || typeof cfg.instance !== "string") {
3791
+ throw new SeedcordError(SeedcordErrorCode.CliConfigMissingInstance);
3792
+ }
3793
+ if (!cfg.entry || typeof cfg.entry !== "string") {
3794
+ throw new SeedcordError(SeedcordErrorCode.CliConfigMissingEntry);
3795
+ }
3796
+ if (typeof cfg.root !== "undefined" && typeof cfg.root !== "string") {
3797
+ throw new SeedcordError(SeedcordErrorCode.CliConfigInvalidRoot);
3798
+ }
3799
+ if (typeof cfg.build !== "undefined" && typeof cfg.build !== "object") {
3800
+ throw new SeedcordError(SeedcordErrorCode.CliConfigInvalidBuild);
3801
+ }
3802
+ if (cfg.build) {
3803
+ const { outDir, tsconfig, bootstrap } = cfg.build;
3804
+ if (typeof outDir !== "undefined" && typeof outDir !== "string") {
3805
+ throw new SeedcordError(SeedcordErrorCode.CliConfigInvalidBuildOutDir);
3806
+ }
3807
+ if (typeof tsconfig !== "undefined" && typeof tsconfig !== "string") {
3808
+ throw new SeedcordError(SeedcordErrorCode.CliConfigInvalidBuildTsconfig);
3809
+ }
3810
+ if (typeof bootstrap !== "undefined" && typeof bootstrap !== "string") {
3811
+ throw new SeedcordError(SeedcordErrorCode.CliConfigInvalidBuildBootstrap);
3812
+ }
3813
+ }
3814
+ const normalized = {
3815
+ instance: cfg.instance,
3816
+ entry: cfg.entry
3817
+ };
3818
+ if (typeof cfg.root === "string") normalized.root = cfg.root;
3819
+ if (cfg.build) normalized.build = cfg.build;
3820
+ return normalized;
3821
+ }
3822
+ resolveWithinRoot(root, target) {
3823
+ if (isAbsolute(target)) return target;
3824
+ return resolve(root, target);
3825
+ }
3826
+ assertEntryWithinRoot(root, entry) {
3827
+ const relativePath = relative(root, entry);
3828
+ if (relativePath.startsWith("..") || isAbsolute(relativePath)) {
3829
+ throw new SeedcordError(SeedcordErrorCode.CliConfigEntryOutsideRoot, [
3830
+ entry,
3831
+ root
3832
+ ]);
3833
+ }
3834
+ }
3835
+ resolveBuildOptions(configDir, build) {
3836
+ const outDir = resolve(configDir, build?.outDir ?? "dist");
3837
+ const bootstrapValue = build?.bootstrap;
3838
+ const bootstrap = bootstrapValue ? this.resolveBootstrap(outDir, bootstrapValue) : resolve(outDir, "index.mjs");
3839
+ const tsconfig = build?.tsconfig ? resolve(configDir, build.tsconfig) : void 0;
3840
+ const resolvedBuild = tsconfig ? {
3841
+ outDir,
3842
+ bootstrap,
3843
+ tsconfig
3844
+ } : {
3845
+ outDir,
3846
+ bootstrap
3847
+ };
3848
+ return resolvedBuild;
3849
+ }
3850
+ resolveBootstrap(outDir, bootstrap) {
3851
+ if (isAbsolute(bootstrap)) return bootstrap;
3852
+ return resolve(outDir, bootstrap);
3853
+ }
3854
+ };
3855
+
3856
+ // src/config/ConfigLocator.ts
3857
+ init_esm_shims();
3858
+
3859
+ // src/config/schema.ts
3860
+ init_esm_shims();
3861
+ var SEEDCORD_CONFIG_FILENAMES = [
3862
+ "seedcord.config.ts",
3863
+ "seedcord.config.mts"
3864
+ ];
3865
+
3866
+ // src/config/ConfigLocator.ts
3867
+ var ConfigLocator = class {
3868
+ static {
3869
+ __name(this, "ConfigLocator");
3870
+ }
3871
+ logger;
3872
+ constructor(logger) {
3873
+ this.logger = logger;
3874
+ }
3875
+ locate(baseDir = process.cwd()) {
3876
+ const normalizedBase = resolve(baseDir);
3877
+ for (const candidate of SEEDCORD_CONFIG_FILENAMES) {
3878
+ const fullPath = join(normalizedBase, candidate);
3879
+ if (existsSync(fullPath)) {
3880
+ this.logger.debug(`Found config at ${fullPath}`);
3881
+ return fullPath;
3882
+ }
3883
+ }
3884
+ throw new SeedcordError(SeedcordErrorCode.CliConfigNotFound, [
3885
+ normalizedBase,
3886
+ SEEDCORD_CONFIG_FILENAMES
3887
+ ]);
3888
+ }
3889
+ };
3890
+
3891
+ // src/modules/RuntimeModuleLoader.ts
3892
+ init_esm_shims();
3893
+ var TS_EXTENSIONS = /* @__PURE__ */ new Set([
3894
+ ".ts",
3895
+ ".tsx",
3896
+ ".mts",
3897
+ ".cts"
3898
+ ]);
3899
+ var RuntimeModuleLoader = class {
3900
+ static {
3901
+ __name(this, "RuntimeModuleLoader");
3902
+ }
3903
+ options;
3904
+ jiti = createJiti(import.meta.url, {
3905
+ cache: false,
3906
+ interopDefault: true,
3907
+ extensions: [
3908
+ ".ts",
3909
+ ".tsx",
3910
+ ".mts",
3911
+ ".cts",
3912
+ ".js",
3913
+ ".mjs",
3914
+ ".cjs"
3915
+ ]
3916
+ });
3917
+ constructor(options = {}) {
3918
+ this.options = options;
3919
+ }
3920
+ async importModule(entryPath) {
3921
+ const normalized = resolve(entryPath);
3922
+ if (!existsSync(normalized)) {
3923
+ throw new SeedcordError(SeedcordErrorCode.CliEntryNotFound, [
3924
+ normalized
3925
+ ]);
3926
+ }
3927
+ if (this.shouldUseTsx(normalized)) {
3928
+ return this.importWithTsx(normalized);
3929
+ }
3930
+ return this.importWithNode(normalized);
3931
+ }
3932
+ shouldUseTsx(filePath) {
3933
+ if (this.options.forceTsx) return true;
3934
+ return TS_EXTENSIONS.has(extname(filePath).toLowerCase());
3935
+ }
3936
+ async importWithTsx(entryPath) {
3937
+ const specifier = pathToFileURL(entryPath).href;
3938
+ const tsconfig = this.resolveTsconfig(entryPath);
3939
+ try {
3940
+ return await tsImport(specifier, {
3941
+ parentURL: import.meta.url,
3942
+ tsconfig
3943
+ });
3944
+ } catch (error) {
3945
+ const reason = error instanceof Error ? error.message : "Unknown tsx error";
3946
+ throw new SeedcordError(SeedcordErrorCode.CliTsxImportFailed, [
3947
+ entryPath,
3948
+ reason
3949
+ ]);
3950
+ }
3951
+ }
3952
+ async importWithNode(entryPath) {
3953
+ const specifier = pathToFileURL(entryPath).href;
3954
+ try {
3955
+ return await import(specifier);
3956
+ } catch (nativeError) {
3957
+ try {
3958
+ return await this.jiti.import(entryPath);
3959
+ } catch (fallbackError) {
3960
+ const nativeReason = nativeError instanceof Error ? nativeError.message : "Unknown ESM import error";
3961
+ const fallbackReason = fallbackError instanceof Error ? fallbackError.message : "Unknown jiti error";
3962
+ throw new SeedcordError(SeedcordErrorCode.CliImportFailed, [
3963
+ entryPath,
3964
+ nativeReason,
3965
+ fallbackReason
3966
+ ]);
3967
+ }
3968
+ }
3969
+ }
3970
+ resolveTsconfig(entryPath) {
3971
+ if (typeof this.options.tsconfig !== "undefined") {
3972
+ return this.options.tsconfig;
3973
+ }
3974
+ return this.findNearestTsconfig(dirname(entryPath)) ?? false;
3975
+ }
3976
+ findNearestTsconfig(startDir) {
3977
+ const candidate = resolve(startDir, "tsconfig.json");
3978
+ if (existsSync(candidate)) return candidate;
3979
+ const parent = dirname(startDir);
3980
+ if (parent === startDir) return void 0;
3981
+ return this.findNearestTsconfig(parent);
3982
+ }
3983
+ };
3984
+
3985
+ // src/runtime/SeedcordBuildRunner.ts
3986
+ var SeedcordBuildRunner = class _SeedcordBuildRunner {
3987
+ static {
3988
+ __name(this, "SeedcordBuildRunner");
3989
+ }
3990
+ locator;
3991
+ configLoader;
3992
+ builder;
3993
+ bootstrapWriter;
3994
+ logger;
3995
+ constructor(locator, configLoader, builder, bootstrapWriter, logger) {
3996
+ this.locator = locator;
3997
+ this.configLoader = configLoader;
3998
+ this.builder = builder;
3999
+ this.bootstrapWriter = bootstrapWriter;
4000
+ this.logger = logger;
4001
+ }
4002
+ static create(logger) {
4003
+ const moduleLoader = new RuntimeModuleLoader();
4004
+ const locator = new ConfigLocator(logger);
4005
+ const configLoader = new ConfigLoader(moduleLoader, logger);
4006
+ const builder = new TypeScriptProjectBuilder(logger);
4007
+ const bootstrapWriter = new BootstrapWriter(logger);
4008
+ return new _SeedcordBuildRunner(locator, configLoader, builder, bootstrapWriter, logger);
4009
+ }
4010
+ async run() {
4011
+ const config = await this.loadConfig();
4012
+ this.assertEntryExists(config.entry);
4013
+ const { emittedEntry } = await this.builder.build(config);
4014
+ await this.bootstrapWriter.write(config, emittedEntry);
4015
+ this.logger.info("Seedcord build finished successfully.");
4016
+ }
4017
+ async loadConfig() {
4018
+ const configPath = this.locator.locate();
4019
+ return this.configLoader.load(configPath);
4020
+ }
4021
+ assertEntryExists(entryPath) {
4022
+ if (!existsSync(entryPath)) {
4023
+ throw new SeedcordError(SeedcordErrorCode.CliEntryNotFound, [
4024
+ entryPath
4025
+ ]);
4026
+ }
4027
+ }
4028
+ };
4029
+
4030
+ // src/commands/BuildCommand.ts
4031
+ var BuildCommand = class _BuildCommand {
4032
+ static {
4033
+ __name(this, "BuildCommand");
4034
+ }
4035
+ runner;
4036
+ logger;
4037
+ constructor(runner, logger) {
4038
+ this.runner = runner;
4039
+ this.logger = logger;
4040
+ }
4041
+ register(program) {
4042
+ program.command("build").description("Compile a Seedcord project using seedcord.config.ts").action(async () => {
4043
+ try {
4044
+ await this.runner.run();
4045
+ } catch (error) {
4046
+ this.logger.error("Seedcord build failed", error);
4047
+ if (isSeedcordError(error)) process.exitCode = 1;
4048
+ else process.exit(1);
4049
+ }
4050
+ });
4051
+ }
4052
+ static create(logger) {
4053
+ return new _BuildCommand(SeedcordBuildRunner.create(logger), logger);
4054
+ }
4055
+ };
4056
+
4057
+ // src/commands/DevCommand.ts
4058
+ init_esm_shims();
4059
+
4060
+ // src/runtime/SeedcordDevRunner.ts
4061
+ init_esm_shims();
4062
+
4063
+ // src/runtime/SeedcordInstanceLoader.ts
4064
+ init_esm_shims();
4065
+ var SeedcordInstanceLoader = class {
4066
+ static {
4067
+ __name(this, "SeedcordInstanceLoader");
4068
+ }
4069
+ modules;
4070
+ logger;
4071
+ constructor(modules, logger) {
4072
+ this.modules = modules;
4073
+ this.logger = logger;
4074
+ }
4075
+ async load(instancePath) {
4076
+ const loadedModule = await this.modules.importModule(instancePath);
4077
+ const exported = resolveDefaultExport(loadedModule);
4078
+ const instance = await Promise.resolve(exported);
4079
+ if (!this.isSeedcordLike(instance)) {
4080
+ throw new SeedcordError(SeedcordErrorCode.CliInstanceInvalid);
4081
+ }
4082
+ this.logger.info(`Loaded Seedcord instance from ${instancePath}`);
4083
+ return instance;
4084
+ }
4085
+ isSeedcordLike(candidate) {
4086
+ return Boolean(candidate) && typeof candidate.start === "function";
4087
+ }
4088
+ };
4089
+
4090
+ // src/runtime/SeedcordDevRunner.ts
4091
+ var SeedcordDevSession = class SeedcordDevSession2 {
4092
+ static {
4093
+ __name(this, "SeedcordDevSession");
4094
+ }
4095
+ config;
4096
+ instanceLoader;
4097
+ logger;
4098
+ constructor(config, instanceLoader, logger) {
4099
+ this.config = config;
4100
+ this.instanceLoader = instanceLoader;
4101
+ this.logger = logger;
4102
+ }
4103
+ async start() {
4104
+ const instance = await this.instanceLoader.load(this.config.instance);
4105
+ try {
4106
+ this.logger.info("Starting Seedcord instance...");
4107
+ await instance.start();
4108
+ this.logger.info("Seedcord is running.");
4109
+ } catch (error) {
4110
+ const reason = error instanceof Error ? error.message : "Unknown error";
4111
+ throw new SeedcordError(SeedcordErrorCode.CliStartFailed, [
4112
+ this.config.instance,
4113
+ reason
4114
+ ]);
4115
+ }
4116
+ }
4117
+ };
4118
+ var SeedcordDevRunner = class _SeedcordDevRunner {
4119
+ static {
4120
+ __name(this, "SeedcordDevRunner");
4121
+ }
4122
+ locator;
4123
+ configLoader;
4124
+ instanceLoader;
4125
+ logger;
4126
+ constructor(locator, configLoader, instanceLoader, logger) {
4127
+ this.locator = locator;
4128
+ this.configLoader = configLoader;
4129
+ this.instanceLoader = instanceLoader;
4130
+ this.logger = logger;
4131
+ }
4132
+ static create(logger) {
4133
+ const moduleLoader = new RuntimeModuleLoader();
4134
+ const locator = new ConfigLocator(logger);
4135
+ const configLoader = new ConfigLoader(moduleLoader, logger);
4136
+ const instanceLoader = new SeedcordInstanceLoader(moduleLoader, logger);
4137
+ return new _SeedcordDevRunner(locator, configLoader, instanceLoader, logger);
4138
+ }
4139
+ async run() {
4140
+ const config = await this.loadConfig();
4141
+ const session = new SeedcordDevSession(config, this.instanceLoader, this.logger);
4142
+ await session.start();
4143
+ }
4144
+ async loadConfig() {
4145
+ const configPath = this.locator.locate();
4146
+ return this.configLoader.load(configPath);
4147
+ }
4148
+ };
4149
+
4150
+ // src/commands/DevCommand.ts
4151
+ var DevCommand = class _DevCommand {
4152
+ static {
4153
+ __name(this, "DevCommand");
4154
+ }
4155
+ runner;
4156
+ logger;
4157
+ constructor(runner, logger) {
4158
+ this.runner = runner;
4159
+ this.logger = logger;
4160
+ }
4161
+ register(program) {
4162
+ program.command("dev").description("Run a Seedcord instance from seedcord.config.ts").action(async () => {
4163
+ try {
4164
+ await this.runner.run();
4165
+ } catch (error) {
4166
+ this.logger.error("Seedcord dev failed", error);
4167
+ if (isSeedcordError(error)) process.exitCode = 1;
4168
+ else process.exit(1);
4169
+ }
4170
+ });
4171
+ }
4172
+ static create(logger) {
4173
+ return new _DevCommand(SeedcordDevRunner.create(logger), logger);
4174
+ }
4175
+ };
4176
+
4177
+ // src/index.ts
4178
+ init_esm_shims();
4179
+ var version = "0.0.1";
4180
+
4181
+ // src/cli.ts
4182
+ var LOGGER_LABEL = "Seedcord CLI";
4183
+ async function main() {
4184
+ process.env.NODE_ENV ??= "development";
4185
+ const logger = new Logger(LOGGER_LABEL);
4186
+ const program = new import_commander.Command().name("seedcord").description("Seedcord CLI").version(version);
4187
+ DevCommand.create(logger).register(program);
4188
+ BuildCommand.create(logger).register(program);
4189
+ await program.parseAsync(process.argv);
4190
+ }
4191
+ __name(main, "main");
4192
+ void main().catch((error) => {
4193
+ const logger = new Logger(LOGGER_LABEL);
4194
+ logger.error("Unexpected CLI error", error);
4195
+ process.exit(1);
4196
+ });
4197
+ //# sourceMappingURL=cli.mjs.map
4198
+ //# sourceMappingURL=cli.mjs.map