@aaac/contracts 0.0.1 → 0.1.1

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