evalify-cli 0.1.0 → 0.1.2

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