@eventcatalog/core 2.7.16 → 2.8.0

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