@andresaya/edge-tts 1.0.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.
@@ -0,0 +1,2678 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __toESM = (mod, isNodeMode, target) => {
9
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
10
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
11
+ for (let key of __getOwnPropNames(mod))
12
+ if (!__hasOwnProp.call(to, key))
13
+ __defProp(to, key, {
14
+ get: () => mod[key],
15
+ enumerable: true
16
+ });
17
+ return to;
18
+ };
19
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
20
+
21
+ // node_modules/commander/lib/error.js
22
+ var require_error = __commonJS((exports) => {
23
+ class CommanderError extends Error {
24
+ constructor(exitCode, code, message) {
25
+ super(message);
26
+ Error.captureStackTrace(this, this.constructor);
27
+ this.name = this.constructor.name;
28
+ this.code = code;
29
+ this.exitCode = exitCode;
30
+ this.nestedError = undefined;
31
+ }
32
+ }
33
+
34
+ class InvalidArgumentError extends CommanderError {
35
+ constructor(message) {
36
+ super(1, "commander.invalidArgument", message);
37
+ Error.captureStackTrace(this, this.constructor);
38
+ this.name = this.constructor.name;
39
+ }
40
+ }
41
+ exports.CommanderError = CommanderError;
42
+ exports.InvalidArgumentError = InvalidArgumentError;
43
+ });
44
+
45
+ // node_modules/commander/lib/argument.js
46
+ var require_argument = __commonJS((exports) => {
47
+ var humanReadableArgName = function(arg) {
48
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
49
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
50
+ };
51
+ var { InvalidArgumentError } = require_error();
52
+
53
+ class Argument {
54
+ constructor(name, description) {
55
+ this.description = description || "";
56
+ this.variadic = false;
57
+ this.parseArg = undefined;
58
+ this.defaultValue = undefined;
59
+ this.defaultValueDescription = undefined;
60
+ this.argChoices = undefined;
61
+ switch (name[0]) {
62
+ case "<":
63
+ this.required = true;
64
+ this._name = name.slice(1, -1);
65
+ break;
66
+ case "[":
67
+ this.required = false;
68
+ this._name = name.slice(1, -1);
69
+ break;
70
+ default:
71
+ this.required = true;
72
+ this._name = name;
73
+ break;
74
+ }
75
+ if (this._name.length > 3 && this._name.slice(-3) === "...") {
76
+ this.variadic = true;
77
+ this._name = this._name.slice(0, -3);
78
+ }
79
+ }
80
+ name() {
81
+ return this._name;
82
+ }
83
+ _concatValue(value, previous) {
84
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
85
+ return [value];
86
+ }
87
+ return previous.concat(value);
88
+ }
89
+ default(value, description) {
90
+ this.defaultValue = value;
91
+ this.defaultValueDescription = description;
92
+ return this;
93
+ }
94
+ argParser(fn) {
95
+ this.parseArg = fn;
96
+ return this;
97
+ }
98
+ choices(values) {
99
+ this.argChoices = values.slice();
100
+ this.parseArg = (arg, previous) => {
101
+ if (!this.argChoices.includes(arg)) {
102
+ throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
103
+ }
104
+ if (this.variadic) {
105
+ return this._concatValue(arg, previous);
106
+ }
107
+ return arg;
108
+ };
109
+ return this;
110
+ }
111
+ argRequired() {
112
+ this.required = true;
113
+ return this;
114
+ }
115
+ argOptional() {
116
+ this.required = false;
117
+ return this;
118
+ }
119
+ }
120
+ exports.Argument = Argument;
121
+ exports.humanReadableArgName = humanReadableArgName;
122
+ });
123
+
124
+ // node_modules/commander/lib/help.js
125
+ var require_help = __commonJS((exports) => {
126
+ var { humanReadableArgName } = require_argument();
127
+
128
+ class Help {
129
+ constructor() {
130
+ this.helpWidth = undefined;
131
+ this.sortSubcommands = false;
132
+ this.sortOptions = false;
133
+ this.showGlobalOptions = false;
134
+ }
135
+ visibleCommands(cmd) {
136
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
137
+ const helpCommand = cmd._getHelpCommand();
138
+ if (helpCommand && !helpCommand._hidden) {
139
+ visibleCommands.push(helpCommand);
140
+ }
141
+ if (this.sortSubcommands) {
142
+ visibleCommands.sort((a, b) => {
143
+ return a.name().localeCompare(b.name());
144
+ });
145
+ }
146
+ return visibleCommands;
147
+ }
148
+ compareOptions(a, b) {
149
+ const getSortKey = (option) => {
150
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
151
+ };
152
+ return getSortKey(a).localeCompare(getSortKey(b));
153
+ }
154
+ visibleOptions(cmd) {
155
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
156
+ const helpOption = cmd._getHelpOption();
157
+ if (helpOption && !helpOption.hidden) {
158
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
159
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
160
+ if (!removeShort && !removeLong) {
161
+ visibleOptions.push(helpOption);
162
+ } else if (helpOption.long && !removeLong) {
163
+ visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
164
+ } else if (helpOption.short && !removeShort) {
165
+ visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
166
+ }
167
+ }
168
+ if (this.sortOptions) {
169
+ visibleOptions.sort(this.compareOptions);
170
+ }
171
+ return visibleOptions;
172
+ }
173
+ visibleGlobalOptions(cmd) {
174
+ if (!this.showGlobalOptions)
175
+ return [];
176
+ const globalOptions = [];
177
+ for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
178
+ const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
179
+ globalOptions.push(...visibleOptions);
180
+ }
181
+ if (this.sortOptions) {
182
+ globalOptions.sort(this.compareOptions);
183
+ }
184
+ return globalOptions;
185
+ }
186
+ visibleArguments(cmd) {
187
+ if (cmd._argsDescription) {
188
+ cmd.registeredArguments.forEach((argument) => {
189
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
190
+ });
191
+ }
192
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
193
+ return cmd.registeredArguments;
194
+ }
195
+ return [];
196
+ }
197
+ subcommandTerm(cmd) {
198
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
199
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
200
+ }
201
+ optionTerm(option) {
202
+ return option.flags;
203
+ }
204
+ argumentTerm(argument) {
205
+ return argument.name();
206
+ }
207
+ longestSubcommandTermLength(cmd, helper) {
208
+ return helper.visibleCommands(cmd).reduce((max, command) => {
209
+ return Math.max(max, helper.subcommandTerm(command).length);
210
+ }, 0);
211
+ }
212
+ longestOptionTermLength(cmd, helper) {
213
+ return helper.visibleOptions(cmd).reduce((max, option) => {
214
+ return Math.max(max, helper.optionTerm(option).length);
215
+ }, 0);
216
+ }
217
+ longestGlobalOptionTermLength(cmd, helper) {
218
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
219
+ return Math.max(max, helper.optionTerm(option).length);
220
+ }, 0);
221
+ }
222
+ longestArgumentTermLength(cmd, helper) {
223
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
224
+ return Math.max(max, helper.argumentTerm(argument).length);
225
+ }, 0);
226
+ }
227
+ commandUsage(cmd) {
228
+ let cmdName = cmd._name;
229
+ if (cmd._aliases[0]) {
230
+ cmdName = cmdName + "|" + cmd._aliases[0];
231
+ }
232
+ let ancestorCmdNames = "";
233
+ for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
234
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
235
+ }
236
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
237
+ }
238
+ commandDescription(cmd) {
239
+ return cmd.description();
240
+ }
241
+ subcommandDescription(cmd) {
242
+ return cmd.summary() || cmd.description();
243
+ }
244
+ optionDescription(option) {
245
+ const extraInfo = [];
246
+ if (option.argChoices) {
247
+ extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
248
+ }
249
+ if (option.defaultValue !== undefined) {
250
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
251
+ if (showDefault) {
252
+ extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
253
+ }
254
+ }
255
+ if (option.presetArg !== undefined && option.optional) {
256
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
257
+ }
258
+ if (option.envVar !== undefined) {
259
+ extraInfo.push(`env: ${option.envVar}`);
260
+ }
261
+ if (extraInfo.length > 0) {
262
+ return `${option.description} (${extraInfo.join(", ")})`;
263
+ }
264
+ return option.description;
265
+ }
266
+ argumentDescription(argument) {
267
+ const extraInfo = [];
268
+ if (argument.argChoices) {
269
+ extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
270
+ }
271
+ if (argument.defaultValue !== undefined) {
272
+ extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
273
+ }
274
+ if (extraInfo.length > 0) {
275
+ const extraDescripton = `(${extraInfo.join(", ")})`;
276
+ if (argument.description) {
277
+ return `${argument.description} ${extraDescripton}`;
278
+ }
279
+ return extraDescripton;
280
+ }
281
+ return argument.description;
282
+ }
283
+ formatHelp(cmd, helper) {
284
+ const termWidth = helper.padWidth(cmd, helper);
285
+ const helpWidth = helper.helpWidth || 80;
286
+ const itemIndentWidth = 2;
287
+ const itemSeparatorWidth = 2;
288
+ function formatItem(term, description) {
289
+ if (description) {
290
+ const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;
291
+ return helper.wrap(fullText, helpWidth - itemIndentWidth, termWidth + itemSeparatorWidth);
292
+ }
293
+ return term;
294
+ }
295
+ function formatList(textArray) {
296
+ return textArray.join("\n").replace(/^/gm, " ".repeat(itemIndentWidth));
297
+ }
298
+ let output = [`Usage: ${helper.commandUsage(cmd)}`, ""];
299
+ const commandDescription = helper.commandDescription(cmd);
300
+ if (commandDescription.length > 0) {
301
+ output = output.concat([
302
+ helper.wrap(commandDescription, helpWidth, 0),
303
+ ""
304
+ ]);
305
+ }
306
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
307
+ return formatItem(helper.argumentTerm(argument), helper.argumentDescription(argument));
308
+ });
309
+ if (argumentList.length > 0) {
310
+ output = output.concat(["Arguments:", formatList(argumentList), ""]);
311
+ }
312
+ const optionList = helper.visibleOptions(cmd).map((option) => {
313
+ return formatItem(helper.optionTerm(option), helper.optionDescription(option));
314
+ });
315
+ if (optionList.length > 0) {
316
+ output = output.concat(["Options:", formatList(optionList), ""]);
317
+ }
318
+ if (this.showGlobalOptions) {
319
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
320
+ return formatItem(helper.optionTerm(option), helper.optionDescription(option));
321
+ });
322
+ if (globalOptionList.length > 0) {
323
+ output = output.concat([
324
+ "Global Options:",
325
+ formatList(globalOptionList),
326
+ ""
327
+ ]);
328
+ }
329
+ }
330
+ const commandList = helper.visibleCommands(cmd).map((cmd2) => {
331
+ return formatItem(helper.subcommandTerm(cmd2), helper.subcommandDescription(cmd2));
332
+ });
333
+ if (commandList.length > 0) {
334
+ output = output.concat(["Commands:", formatList(commandList), ""]);
335
+ }
336
+ return output.join("\n");
337
+ }
338
+ padWidth(cmd, helper) {
339
+ return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
340
+ }
341
+ wrap(str, width, indent, minColumnWidth = 40) {
342
+ const indents = " \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF";
343
+ const manualIndent = new RegExp(`[\\n][${indents}]+`);
344
+ if (str.match(manualIndent))
345
+ return str;
346
+ const columnWidth = width - indent;
347
+ if (columnWidth < minColumnWidth)
348
+ return str;
349
+ const leadingStr = str.slice(0, indent);
350
+ const columnText = str.slice(indent).replace("\r\n", "\n");
351
+ const indentString = " ".repeat(indent);
352
+ const zeroWidthSpace = "\u200B";
353
+ const breaks = `\\s${zeroWidthSpace}`;
354
+ const regex = new RegExp(`\n|.{1,${columnWidth - 1}}([${breaks}]|\$)|[^${breaks}]+?([${breaks}]|\$)`, "g");
355
+ const lines = columnText.match(regex) || [];
356
+ return leadingStr + lines.map((line, i) => {
357
+ if (line === "\n")
358
+ return "";
359
+ return (i > 0 ? indentString : "") + line.trimEnd();
360
+ }).join("\n");
361
+ }
362
+ }
363
+ exports.Help = Help;
364
+ });
365
+
366
+ // node_modules/commander/lib/option.js
367
+ var require_option = __commonJS((exports) => {
368
+ var camelcase = function(str) {
369
+ return str.split("-").reduce((str2, word) => {
370
+ return str2 + word[0].toUpperCase() + word.slice(1);
371
+ });
372
+ };
373
+ var splitOptionFlags = function(flags) {
374
+ let shortFlag;
375
+ let longFlag;
376
+ const flagParts = flags.split(/[ |,]+/);
377
+ if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1]))
378
+ shortFlag = flagParts.shift();
379
+ longFlag = flagParts.shift();
380
+ if (!shortFlag && /^-[^-]$/.test(longFlag)) {
381
+ shortFlag = longFlag;
382
+ longFlag = undefined;
383
+ }
384
+ return { shortFlag, longFlag };
385
+ };
386
+ var { InvalidArgumentError } = require_error();
387
+
388
+ class Option {
389
+ constructor(flags, description) {
390
+ this.flags = flags;
391
+ this.description = description || "";
392
+ this.required = flags.includes("<");
393
+ this.optional = flags.includes("[");
394
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
395
+ this.mandatory = false;
396
+ const optionFlags = splitOptionFlags(flags);
397
+ this.short = optionFlags.shortFlag;
398
+ this.long = optionFlags.longFlag;
399
+ this.negate = false;
400
+ if (this.long) {
401
+ this.negate = this.long.startsWith("--no-");
402
+ }
403
+ this.defaultValue = undefined;
404
+ this.defaultValueDescription = undefined;
405
+ this.presetArg = undefined;
406
+ this.envVar = undefined;
407
+ this.parseArg = undefined;
408
+ this.hidden = false;
409
+ this.argChoices = undefined;
410
+ this.conflictsWith = [];
411
+ this.implied = undefined;
412
+ }
413
+ default(value, description) {
414
+ this.defaultValue = value;
415
+ this.defaultValueDescription = description;
416
+ return this;
417
+ }
418
+ preset(arg) {
419
+ this.presetArg = arg;
420
+ return this;
421
+ }
422
+ conflicts(names) {
423
+ this.conflictsWith = this.conflictsWith.concat(names);
424
+ return this;
425
+ }
426
+ implies(impliedOptionValues) {
427
+ let newImplied = impliedOptionValues;
428
+ if (typeof impliedOptionValues === "string") {
429
+ newImplied = { [impliedOptionValues]: true };
430
+ }
431
+ this.implied = Object.assign(this.implied || {}, newImplied);
432
+ return this;
433
+ }
434
+ env(name) {
435
+ this.envVar = name;
436
+ return this;
437
+ }
438
+ argParser(fn) {
439
+ this.parseArg = fn;
440
+ return this;
441
+ }
442
+ makeOptionMandatory(mandatory = true) {
443
+ this.mandatory = !!mandatory;
444
+ return this;
445
+ }
446
+ hideHelp(hide = true) {
447
+ this.hidden = !!hide;
448
+ return this;
449
+ }
450
+ _concatValue(value, previous) {
451
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
452
+ return [value];
453
+ }
454
+ return previous.concat(value);
455
+ }
456
+ choices(values) {
457
+ this.argChoices = values.slice();
458
+ this.parseArg = (arg, previous) => {
459
+ if (!this.argChoices.includes(arg)) {
460
+ throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
461
+ }
462
+ if (this.variadic) {
463
+ return this._concatValue(arg, previous);
464
+ }
465
+ return arg;
466
+ };
467
+ return this;
468
+ }
469
+ name() {
470
+ if (this.long) {
471
+ return this.long.replace(/^--/, "");
472
+ }
473
+ return this.short.replace(/^-/, "");
474
+ }
475
+ attributeName() {
476
+ return camelcase(this.name().replace(/^no-/, ""));
477
+ }
478
+ is(arg) {
479
+ return this.short === arg || this.long === arg;
480
+ }
481
+ isBoolean() {
482
+ return !this.required && !this.optional && !this.negate;
483
+ }
484
+ }
485
+
486
+ class DualOptions {
487
+ constructor(options) {
488
+ this.positiveOptions = new Map;
489
+ this.negativeOptions = new Map;
490
+ this.dualOptions = new Set;
491
+ options.forEach((option) => {
492
+ if (option.negate) {
493
+ this.negativeOptions.set(option.attributeName(), option);
494
+ } else {
495
+ this.positiveOptions.set(option.attributeName(), option);
496
+ }
497
+ });
498
+ this.negativeOptions.forEach((value, key) => {
499
+ if (this.positiveOptions.has(key)) {
500
+ this.dualOptions.add(key);
501
+ }
502
+ });
503
+ }
504
+ valueFromOption(value, option) {
505
+ const optionKey = option.attributeName();
506
+ if (!this.dualOptions.has(optionKey))
507
+ return true;
508
+ const preset = this.negativeOptions.get(optionKey).presetArg;
509
+ const negativeValue = preset !== undefined ? preset : false;
510
+ return option.negate === (negativeValue === value);
511
+ }
512
+ }
513
+ exports.Option = Option;
514
+ exports.DualOptions = DualOptions;
515
+ });
516
+
517
+ // node_modules/commander/lib/suggestSimilar.js
518
+ var require_suggestSimilar = __commonJS((exports) => {
519
+ var editDistance = function(a, b) {
520
+ if (Math.abs(a.length - b.length) > maxDistance)
521
+ return Math.max(a.length, b.length);
522
+ const d = [];
523
+ for (let i = 0;i <= a.length; i++) {
524
+ d[i] = [i];
525
+ }
526
+ for (let j = 0;j <= b.length; j++) {
527
+ d[0][j] = j;
528
+ }
529
+ for (let j = 1;j <= b.length; j++) {
530
+ for (let i = 1;i <= a.length; i++) {
531
+ let cost = 1;
532
+ if (a[i - 1] === b[j - 1]) {
533
+ cost = 0;
534
+ } else {
535
+ cost = 1;
536
+ }
537
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
538
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
539
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
540
+ }
541
+ }
542
+ }
543
+ return d[a.length][b.length];
544
+ };
545
+ var suggestSimilar = function(word, candidates) {
546
+ if (!candidates || candidates.length === 0)
547
+ return "";
548
+ candidates = Array.from(new Set(candidates));
549
+ const searchingOptions = word.startsWith("--");
550
+ if (searchingOptions) {
551
+ word = word.slice(2);
552
+ candidates = candidates.map((candidate) => candidate.slice(2));
553
+ }
554
+ let similar = [];
555
+ let bestDistance = maxDistance;
556
+ const minSimilarity = 0.4;
557
+ candidates.forEach((candidate) => {
558
+ if (candidate.length <= 1)
559
+ return;
560
+ const distance = editDistance(word, candidate);
561
+ const length = Math.max(word.length, candidate.length);
562
+ const similarity = (length - distance) / length;
563
+ if (similarity > minSimilarity) {
564
+ if (distance < bestDistance) {
565
+ bestDistance = distance;
566
+ similar = [candidate];
567
+ } else if (distance === bestDistance) {
568
+ similar.push(candidate);
569
+ }
570
+ }
571
+ });
572
+ similar.sort((a, b) => a.localeCompare(b));
573
+ if (searchingOptions) {
574
+ similar = similar.map((candidate) => `--${candidate}`);
575
+ }
576
+ if (similar.length > 1) {
577
+ return `\n(Did you mean one of ${similar.join(", ")}?)`;
578
+ }
579
+ if (similar.length === 1) {
580
+ return `\n(Did you mean ${similar[0]}?)`;
581
+ }
582
+ return "";
583
+ };
584
+ var maxDistance = 3;
585
+ exports.suggestSimilar = suggestSimilar;
586
+ });
587
+
588
+ // node_modules/commander/lib/command.js
589
+ var require_command = __commonJS((exports) => {
590
+ var incrementNodeInspectorPort = function(args) {
591
+ return args.map((arg) => {
592
+ if (!arg.startsWith("--inspect")) {
593
+ return arg;
594
+ }
595
+ let debugOption;
596
+ let debugHost = "127.0.0.1";
597
+ let debugPort = "9229";
598
+ let match;
599
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
600
+ debugOption = match[1];
601
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
602
+ debugOption = match[1];
603
+ if (/^\d+$/.test(match[3])) {
604
+ debugPort = match[3];
605
+ } else {
606
+ debugHost = match[3];
607
+ }
608
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
609
+ debugOption = match[1];
610
+ debugHost = match[3];
611
+ debugPort = match[4];
612
+ }
613
+ if (debugOption && debugPort !== "0") {
614
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
615
+ }
616
+ return arg;
617
+ });
618
+ };
619
+ var EventEmitter = import.meta.require("events").EventEmitter;
620
+ var childProcess = import.meta.require("child_process");
621
+ var path = import.meta.require("path");
622
+ var fs = import.meta.require("fs");
623
+ var process2 = import.meta.require("process");
624
+ var { Argument, humanReadableArgName } = require_argument();
625
+ var { CommanderError } = require_error();
626
+ var { Help } = require_help();
627
+ var { Option, DualOptions } = require_option();
628
+ var { suggestSimilar } = require_suggestSimilar();
629
+
630
+ class Command extends EventEmitter {
631
+ constructor(name) {
632
+ super();
633
+ this.commands = [];
634
+ this.options = [];
635
+ this.parent = null;
636
+ this._allowUnknownOption = false;
637
+ this._allowExcessArguments = true;
638
+ this.registeredArguments = [];
639
+ this._args = this.registeredArguments;
640
+ this.args = [];
641
+ this.rawArgs = [];
642
+ this.processedArgs = [];
643
+ this._scriptPath = null;
644
+ this._name = name || "";
645
+ this._optionValues = {};
646
+ this._optionValueSources = {};
647
+ this._storeOptionsAsProperties = false;
648
+ this._actionHandler = null;
649
+ this._executableHandler = false;
650
+ this._executableFile = null;
651
+ this._executableDir = null;
652
+ this._defaultCommandName = null;
653
+ this._exitCallback = null;
654
+ this._aliases = [];
655
+ this._combineFlagAndOptionalValue = true;
656
+ this._description = "";
657
+ this._summary = "";
658
+ this._argsDescription = undefined;
659
+ this._enablePositionalOptions = false;
660
+ this._passThroughOptions = false;
661
+ this._lifeCycleHooks = {};
662
+ this._showHelpAfterError = false;
663
+ this._showSuggestionAfterError = true;
664
+ this._outputConfiguration = {
665
+ writeOut: (str) => process2.stdout.write(str),
666
+ writeErr: (str) => process2.stderr.write(str),
667
+ getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : undefined,
668
+ getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : undefined,
669
+ outputError: (str, write) => write(str)
670
+ };
671
+ this._hidden = false;
672
+ this._helpOption = undefined;
673
+ this._addImplicitHelpCommand = undefined;
674
+ this._helpCommand = undefined;
675
+ this._helpConfiguration = {};
676
+ }
677
+ copyInheritedSettings(sourceCommand) {
678
+ this._outputConfiguration = sourceCommand._outputConfiguration;
679
+ this._helpOption = sourceCommand._helpOption;
680
+ this._helpCommand = sourceCommand._helpCommand;
681
+ this._helpConfiguration = sourceCommand._helpConfiguration;
682
+ this._exitCallback = sourceCommand._exitCallback;
683
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
684
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
685
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
686
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
687
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
688
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
689
+ return this;
690
+ }
691
+ _getCommandAndAncestors() {
692
+ const result = [];
693
+ for (let command = this;command; command = command.parent) {
694
+ result.push(command);
695
+ }
696
+ return result;
697
+ }
698
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
699
+ let desc = actionOptsOrExecDesc;
700
+ let opts = execOpts;
701
+ if (typeof desc === "object" && desc !== null) {
702
+ opts = desc;
703
+ desc = null;
704
+ }
705
+ opts = opts || {};
706
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
707
+ const cmd = this.createCommand(name);
708
+ if (desc) {
709
+ cmd.description(desc);
710
+ cmd._executableHandler = true;
711
+ }
712
+ if (opts.isDefault)
713
+ this._defaultCommandName = cmd._name;
714
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
715
+ cmd._executableFile = opts.executableFile || null;
716
+ if (args)
717
+ cmd.arguments(args);
718
+ this._registerCommand(cmd);
719
+ cmd.parent = this;
720
+ cmd.copyInheritedSettings(this);
721
+ if (desc)
722
+ return this;
723
+ return cmd;
724
+ }
725
+ createCommand(name) {
726
+ return new Command(name);
727
+ }
728
+ createHelp() {
729
+ return Object.assign(new Help, this.configureHelp());
730
+ }
731
+ configureHelp(configuration) {
732
+ if (configuration === undefined)
733
+ return this._helpConfiguration;
734
+ this._helpConfiguration = configuration;
735
+ return this;
736
+ }
737
+ configureOutput(configuration) {
738
+ if (configuration === undefined)
739
+ return this._outputConfiguration;
740
+ Object.assign(this._outputConfiguration, configuration);
741
+ return this;
742
+ }
743
+ showHelpAfterError(displayHelp = true) {
744
+ if (typeof displayHelp !== "string")
745
+ displayHelp = !!displayHelp;
746
+ this._showHelpAfterError = displayHelp;
747
+ return this;
748
+ }
749
+ showSuggestionAfterError(displaySuggestion = true) {
750
+ this._showSuggestionAfterError = !!displaySuggestion;
751
+ return this;
752
+ }
753
+ addCommand(cmd, opts) {
754
+ if (!cmd._name) {
755
+ throw new Error(`Command passed to .addCommand() must have a name
756
+ - specify the name in Command constructor or using .name()`);
757
+ }
758
+ opts = opts || {};
759
+ if (opts.isDefault)
760
+ this._defaultCommandName = cmd._name;
761
+ if (opts.noHelp || opts.hidden)
762
+ cmd._hidden = true;
763
+ this._registerCommand(cmd);
764
+ cmd.parent = this;
765
+ cmd._checkForBrokenPassThrough();
766
+ return this;
767
+ }
768
+ createArgument(name, description) {
769
+ return new Argument(name, description);
770
+ }
771
+ argument(name, description, fn, defaultValue) {
772
+ const argument = this.createArgument(name, description);
773
+ if (typeof fn === "function") {
774
+ argument.default(defaultValue).argParser(fn);
775
+ } else {
776
+ argument.default(fn);
777
+ }
778
+ this.addArgument(argument);
779
+ return this;
780
+ }
781
+ arguments(names) {
782
+ names.trim().split(/ +/).forEach((detail) => {
783
+ this.argument(detail);
784
+ });
785
+ return this;
786
+ }
787
+ addArgument(argument) {
788
+ const previousArgument = this.registeredArguments.slice(-1)[0];
789
+ if (previousArgument && previousArgument.variadic) {
790
+ throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
791
+ }
792
+ if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {
793
+ throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
794
+ }
795
+ this.registeredArguments.push(argument);
796
+ return this;
797
+ }
798
+ helpCommand(enableOrNameAndArgs, description) {
799
+ if (typeof enableOrNameAndArgs === "boolean") {
800
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
801
+ return this;
802
+ }
803
+ enableOrNameAndArgs = enableOrNameAndArgs ?? "help [command]";
804
+ const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);
805
+ const helpDescription = description ?? "display help for command";
806
+ const helpCommand = this.createCommand(helpName);
807
+ helpCommand.helpOption(false);
808
+ if (helpArgs)
809
+ helpCommand.arguments(helpArgs);
810
+ if (helpDescription)
811
+ helpCommand.description(helpDescription);
812
+ this._addImplicitHelpCommand = true;
813
+ this._helpCommand = helpCommand;
814
+ return this;
815
+ }
816
+ addHelpCommand(helpCommand, deprecatedDescription) {
817
+ if (typeof helpCommand !== "object") {
818
+ this.helpCommand(helpCommand, deprecatedDescription);
819
+ return this;
820
+ }
821
+ this._addImplicitHelpCommand = true;
822
+ this._helpCommand = helpCommand;
823
+ return this;
824
+ }
825
+ _getHelpCommand() {
826
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
827
+ if (hasImplicitHelpCommand) {
828
+ if (this._helpCommand === undefined) {
829
+ this.helpCommand(undefined, undefined);
830
+ }
831
+ return this._helpCommand;
832
+ }
833
+ return null;
834
+ }
835
+ hook(event, listener) {
836
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
837
+ if (!allowedValues.includes(event)) {
838
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
839
+ Expecting one of '${allowedValues.join("', '")}'`);
840
+ }
841
+ if (this._lifeCycleHooks[event]) {
842
+ this._lifeCycleHooks[event].push(listener);
843
+ } else {
844
+ this._lifeCycleHooks[event] = [listener];
845
+ }
846
+ return this;
847
+ }
848
+ exitOverride(fn) {
849
+ if (fn) {
850
+ this._exitCallback = fn;
851
+ } else {
852
+ this._exitCallback = (err) => {
853
+ if (err.code !== "commander.executeSubCommandAsync") {
854
+ throw err;
855
+ } else {
856
+ }
857
+ };
858
+ }
859
+ return this;
860
+ }
861
+ _exit(exitCode, code, message) {
862
+ if (this._exitCallback) {
863
+ this._exitCallback(new CommanderError(exitCode, code, message));
864
+ }
865
+ process2.exit(exitCode);
866
+ }
867
+ action(fn) {
868
+ const listener = (args) => {
869
+ const expectedArgsCount = this.registeredArguments.length;
870
+ const actionArgs = args.slice(0, expectedArgsCount);
871
+ if (this._storeOptionsAsProperties) {
872
+ actionArgs[expectedArgsCount] = this;
873
+ } else {
874
+ actionArgs[expectedArgsCount] = this.opts();
875
+ }
876
+ actionArgs.push(this);
877
+ return fn.apply(this, actionArgs);
878
+ };
879
+ this._actionHandler = listener;
880
+ return this;
881
+ }
882
+ createOption(flags, description) {
883
+ return new Option(flags, description);
884
+ }
885
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
886
+ try {
887
+ return target.parseArg(value, previous);
888
+ } catch (err) {
889
+ if (err.code === "commander.invalidArgument") {
890
+ const message = `${invalidArgumentMessage} ${err.message}`;
891
+ this.error(message, { exitCode: err.exitCode, code: err.code });
892
+ }
893
+ throw err;
894
+ }
895
+ }
896
+ _registerOption(option) {
897
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
898
+ if (matchingOption) {
899
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
900
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
901
+ - already used by option '${matchingOption.flags}'`);
902
+ }
903
+ this.options.push(option);
904
+ }
905
+ _registerCommand(command) {
906
+ const knownBy = (cmd) => {
907
+ return [cmd.name()].concat(cmd.aliases());
908
+ };
909
+ const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
910
+ if (alreadyUsed) {
911
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
912
+ const newCmd = knownBy(command).join("|");
913
+ throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
914
+ }
915
+ this.commands.push(command);
916
+ }
917
+ addOption(option) {
918
+ this._registerOption(option);
919
+ const oname = option.name();
920
+ const name = option.attributeName();
921
+ if (option.negate) {
922
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
923
+ if (!this._findOption(positiveLongFlag)) {
924
+ this.setOptionValueWithSource(name, option.defaultValue === undefined ? true : option.defaultValue, "default");
925
+ }
926
+ } else if (option.defaultValue !== undefined) {
927
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
928
+ }
929
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
930
+ if (val == null && option.presetArg !== undefined) {
931
+ val = option.presetArg;
932
+ }
933
+ const oldValue = this.getOptionValue(name);
934
+ if (val !== null && option.parseArg) {
935
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
936
+ } else if (val !== null && option.variadic) {
937
+ val = option._concatValue(val, oldValue);
938
+ }
939
+ if (val == null) {
940
+ if (option.negate) {
941
+ val = false;
942
+ } else if (option.isBoolean() || option.optional) {
943
+ val = true;
944
+ } else {
945
+ val = "";
946
+ }
947
+ }
948
+ this.setOptionValueWithSource(name, val, valueSource);
949
+ };
950
+ this.on("option:" + oname, (val) => {
951
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
952
+ handleOptionValue(val, invalidValueMessage, "cli");
953
+ });
954
+ if (option.envVar) {
955
+ this.on("optionEnv:" + oname, (val) => {
956
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
957
+ handleOptionValue(val, invalidValueMessage, "env");
958
+ });
959
+ }
960
+ return this;
961
+ }
962
+ _optionEx(config, flags, description, fn, defaultValue) {
963
+ if (typeof flags === "object" && flags instanceof Option) {
964
+ throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
965
+ }
966
+ const option = this.createOption(flags, description);
967
+ option.makeOptionMandatory(!!config.mandatory);
968
+ if (typeof fn === "function") {
969
+ option.default(defaultValue).argParser(fn);
970
+ } else if (fn instanceof RegExp) {
971
+ const regex = fn;
972
+ fn = (val, def) => {
973
+ const m = regex.exec(val);
974
+ return m ? m[0] : def;
975
+ };
976
+ option.default(defaultValue).argParser(fn);
977
+ } else {
978
+ option.default(fn);
979
+ }
980
+ return this.addOption(option);
981
+ }
982
+ option(flags, description, parseArg, defaultValue) {
983
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
984
+ }
985
+ requiredOption(flags, description, parseArg, defaultValue) {
986
+ return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
987
+ }
988
+ combineFlagAndOptionalValue(combine = true) {
989
+ this._combineFlagAndOptionalValue = !!combine;
990
+ return this;
991
+ }
992
+ allowUnknownOption(allowUnknown = true) {
993
+ this._allowUnknownOption = !!allowUnknown;
994
+ return this;
995
+ }
996
+ allowExcessArguments(allowExcess = true) {
997
+ this._allowExcessArguments = !!allowExcess;
998
+ return this;
999
+ }
1000
+ enablePositionalOptions(positional = true) {
1001
+ this._enablePositionalOptions = !!positional;
1002
+ return this;
1003
+ }
1004
+ passThroughOptions(passThrough = true) {
1005
+ this._passThroughOptions = !!passThrough;
1006
+ this._checkForBrokenPassThrough();
1007
+ return this;
1008
+ }
1009
+ _checkForBrokenPassThrough() {
1010
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
1011
+ throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
1012
+ }
1013
+ }
1014
+ storeOptionsAsProperties(storeAsProperties = true) {
1015
+ if (this.options.length) {
1016
+ throw new Error("call .storeOptionsAsProperties() before adding options");
1017
+ }
1018
+ if (Object.keys(this._optionValues).length) {
1019
+ throw new Error("call .storeOptionsAsProperties() before setting option values");
1020
+ }
1021
+ this._storeOptionsAsProperties = !!storeAsProperties;
1022
+ return this;
1023
+ }
1024
+ getOptionValue(key) {
1025
+ if (this._storeOptionsAsProperties) {
1026
+ return this[key];
1027
+ }
1028
+ return this._optionValues[key];
1029
+ }
1030
+ setOptionValue(key, value) {
1031
+ return this.setOptionValueWithSource(key, value, undefined);
1032
+ }
1033
+ setOptionValueWithSource(key, value, source) {
1034
+ if (this._storeOptionsAsProperties) {
1035
+ this[key] = value;
1036
+ } else {
1037
+ this._optionValues[key] = value;
1038
+ }
1039
+ this._optionValueSources[key] = source;
1040
+ return this;
1041
+ }
1042
+ getOptionValueSource(key) {
1043
+ return this._optionValueSources[key];
1044
+ }
1045
+ getOptionValueSourceWithGlobals(key) {
1046
+ let source;
1047
+ this._getCommandAndAncestors().forEach((cmd) => {
1048
+ if (cmd.getOptionValueSource(key) !== undefined) {
1049
+ source = cmd.getOptionValueSource(key);
1050
+ }
1051
+ });
1052
+ return source;
1053
+ }
1054
+ _prepareUserArgs(argv, parseOptions) {
1055
+ if (argv !== undefined && !Array.isArray(argv)) {
1056
+ throw new Error("first parameter to parse must be array or undefined");
1057
+ }
1058
+ parseOptions = parseOptions || {};
1059
+ if (argv === undefined && parseOptions.from === undefined) {
1060
+ if (process2.versions?.electron) {
1061
+ parseOptions.from = "electron";
1062
+ }
1063
+ const execArgv = process2.execArgv ?? [];
1064
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
1065
+ parseOptions.from = "eval";
1066
+ }
1067
+ }
1068
+ if (argv === undefined) {
1069
+ argv = process2.argv;
1070
+ }
1071
+ this.rawArgs = argv.slice();
1072
+ let userArgs;
1073
+ switch (parseOptions.from) {
1074
+ case undefined:
1075
+ case "node":
1076
+ this._scriptPath = argv[1];
1077
+ userArgs = argv.slice(2);
1078
+ break;
1079
+ case "electron":
1080
+ if (process2.defaultApp) {
1081
+ this._scriptPath = argv[1];
1082
+ userArgs = argv.slice(2);
1083
+ } else {
1084
+ userArgs = argv.slice(1);
1085
+ }
1086
+ break;
1087
+ case "user":
1088
+ userArgs = argv.slice(0);
1089
+ break;
1090
+ case "eval":
1091
+ userArgs = argv.slice(1);
1092
+ break;
1093
+ default:
1094
+ throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
1095
+ }
1096
+ if (!this._name && this._scriptPath)
1097
+ this.nameFromFilename(this._scriptPath);
1098
+ this._name = this._name || "program";
1099
+ return userArgs;
1100
+ }
1101
+ parse(argv, parseOptions) {
1102
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1103
+ this._parseCommand([], userArgs);
1104
+ return this;
1105
+ }
1106
+ async parseAsync(argv, parseOptions) {
1107
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1108
+ await this._parseCommand([], userArgs);
1109
+ return this;
1110
+ }
1111
+ _executeSubCommand(subcommand, args) {
1112
+ args = args.slice();
1113
+ let launchWithNode = false;
1114
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
1115
+ function findFile(baseDir, baseName) {
1116
+ const localBin = path.resolve(baseDir, baseName);
1117
+ if (fs.existsSync(localBin))
1118
+ return localBin;
1119
+ if (sourceExt.includes(path.extname(baseName)))
1120
+ return;
1121
+ const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
1122
+ if (foundExt)
1123
+ return `${localBin}${foundExt}`;
1124
+ return;
1125
+ }
1126
+ this._checkForMissingMandatoryOptions();
1127
+ this._checkForConflictingOptions();
1128
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1129
+ let executableDir = this._executableDir || "";
1130
+ if (this._scriptPath) {
1131
+ let resolvedScriptPath;
1132
+ try {
1133
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
1134
+ } catch (err) {
1135
+ resolvedScriptPath = this._scriptPath;
1136
+ }
1137
+ executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
1138
+ }
1139
+ if (executableDir) {
1140
+ let localFile = findFile(executableDir, executableFile);
1141
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1142
+ const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
1143
+ if (legacyName !== this._name) {
1144
+ localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
1145
+ }
1146
+ }
1147
+ executableFile = localFile || executableFile;
1148
+ }
1149
+ launchWithNode = sourceExt.includes(path.extname(executableFile));
1150
+ let proc;
1151
+ if (process2.platform !== "win32") {
1152
+ if (launchWithNode) {
1153
+ args.unshift(executableFile);
1154
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1155
+ proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
1156
+ } else {
1157
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1158
+ }
1159
+ } else {
1160
+ args.unshift(executableFile);
1161
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1162
+ proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
1163
+ }
1164
+ if (!proc.killed) {
1165
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
1166
+ signals.forEach((signal) => {
1167
+ process2.on(signal, () => {
1168
+ if (proc.killed === false && proc.exitCode === null) {
1169
+ proc.kill(signal);
1170
+ }
1171
+ });
1172
+ });
1173
+ }
1174
+ const exitCallback = this._exitCallback;
1175
+ proc.on("close", (code) => {
1176
+ code = code ?? 1;
1177
+ if (!exitCallback) {
1178
+ process2.exit(code);
1179
+ } else {
1180
+ exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
1181
+ }
1182
+ });
1183
+ proc.on("error", (err) => {
1184
+ if (err.code === "ENOENT") {
1185
+ 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";
1186
+ const executableMissing = `'${executableFile}' does not exist
1187
+ - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1188
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1189
+ - ${executableDirMessage}`;
1190
+ throw new Error(executableMissing);
1191
+ } else if (err.code === "EACCES") {
1192
+ throw new Error(`'${executableFile}' not executable`);
1193
+ }
1194
+ if (!exitCallback) {
1195
+ process2.exit(1);
1196
+ } else {
1197
+ const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
1198
+ wrappedError.nestedError = err;
1199
+ exitCallback(wrappedError);
1200
+ }
1201
+ });
1202
+ this.runningCommand = proc;
1203
+ }
1204
+ _dispatchSubcommand(commandName, operands, unknown) {
1205
+ const subCommand = this._findCommand(commandName);
1206
+ if (!subCommand)
1207
+ this.help({ error: true });
1208
+ let promiseChain;
1209
+ promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
1210
+ promiseChain = this._chainOrCall(promiseChain, () => {
1211
+ if (subCommand._executableHandler) {
1212
+ this._executeSubCommand(subCommand, operands.concat(unknown));
1213
+ } else {
1214
+ return subCommand._parseCommand(operands, unknown);
1215
+ }
1216
+ });
1217
+ return promiseChain;
1218
+ }
1219
+ _dispatchHelpCommand(subcommandName) {
1220
+ if (!subcommandName) {
1221
+ this.help();
1222
+ }
1223
+ const subCommand = this._findCommand(subcommandName);
1224
+ if (subCommand && !subCommand._executableHandler) {
1225
+ subCommand.help();
1226
+ }
1227
+ return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
1228
+ }
1229
+ _checkNumberOfArguments() {
1230
+ this.registeredArguments.forEach((arg, i) => {
1231
+ if (arg.required && this.args[i] == null) {
1232
+ this.missingArgument(arg.name());
1233
+ }
1234
+ });
1235
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
1236
+ return;
1237
+ }
1238
+ if (this.args.length > this.registeredArguments.length) {
1239
+ this._excessArguments(this.args);
1240
+ }
1241
+ }
1242
+ _processArguments() {
1243
+ const myParseArg = (argument, value, previous) => {
1244
+ let parsedValue = value;
1245
+ if (value !== null && argument.parseArg) {
1246
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
1247
+ parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
1248
+ }
1249
+ return parsedValue;
1250
+ };
1251
+ this._checkNumberOfArguments();
1252
+ const processedArgs = [];
1253
+ this.registeredArguments.forEach((declaredArg, index) => {
1254
+ let value = declaredArg.defaultValue;
1255
+ if (declaredArg.variadic) {
1256
+ if (index < this.args.length) {
1257
+ value = this.args.slice(index);
1258
+ if (declaredArg.parseArg) {
1259
+ value = value.reduce((processed, v) => {
1260
+ return myParseArg(declaredArg, v, processed);
1261
+ }, declaredArg.defaultValue);
1262
+ }
1263
+ } else if (value === undefined) {
1264
+ value = [];
1265
+ }
1266
+ } else if (index < this.args.length) {
1267
+ value = this.args[index];
1268
+ if (declaredArg.parseArg) {
1269
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
1270
+ }
1271
+ }
1272
+ processedArgs[index] = value;
1273
+ });
1274
+ this.processedArgs = processedArgs;
1275
+ }
1276
+ _chainOrCall(promise, fn) {
1277
+ if (promise && promise.then && typeof promise.then === "function") {
1278
+ return promise.then(() => fn());
1279
+ }
1280
+ return fn();
1281
+ }
1282
+ _chainOrCallHooks(promise, event) {
1283
+ let result = promise;
1284
+ const hooks = [];
1285
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== undefined).forEach((hookedCommand) => {
1286
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
1287
+ hooks.push({ hookedCommand, callback });
1288
+ });
1289
+ });
1290
+ if (event === "postAction") {
1291
+ hooks.reverse();
1292
+ }
1293
+ hooks.forEach((hookDetail) => {
1294
+ result = this._chainOrCall(result, () => {
1295
+ return hookDetail.callback(hookDetail.hookedCommand, this);
1296
+ });
1297
+ });
1298
+ return result;
1299
+ }
1300
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
1301
+ let result = promise;
1302
+ if (this._lifeCycleHooks[event] !== undefined) {
1303
+ this._lifeCycleHooks[event].forEach((hook) => {
1304
+ result = this._chainOrCall(result, () => {
1305
+ return hook(this, subCommand);
1306
+ });
1307
+ });
1308
+ }
1309
+ return result;
1310
+ }
1311
+ _parseCommand(operands, unknown) {
1312
+ const parsed = this.parseOptions(unknown);
1313
+ this._parseOptionsEnv();
1314
+ this._parseOptionsImplied();
1315
+ operands = operands.concat(parsed.operands);
1316
+ unknown = parsed.unknown;
1317
+ this.args = operands.concat(unknown);
1318
+ if (operands && this._findCommand(operands[0])) {
1319
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
1320
+ }
1321
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
1322
+ return this._dispatchHelpCommand(operands[1]);
1323
+ }
1324
+ if (this._defaultCommandName) {
1325
+ this._outputHelpIfRequested(unknown);
1326
+ return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
1327
+ }
1328
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
1329
+ this.help({ error: true });
1330
+ }
1331
+ this._outputHelpIfRequested(parsed.unknown);
1332
+ this._checkForMissingMandatoryOptions();
1333
+ this._checkForConflictingOptions();
1334
+ const checkForUnknownOptions = () => {
1335
+ if (parsed.unknown.length > 0) {
1336
+ this.unknownOption(parsed.unknown[0]);
1337
+ }
1338
+ };
1339
+ const commandEvent = `command:${this.name()}`;
1340
+ if (this._actionHandler) {
1341
+ checkForUnknownOptions();
1342
+ this._processArguments();
1343
+ let promiseChain;
1344
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
1345
+ promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
1346
+ if (this.parent) {
1347
+ promiseChain = this._chainOrCall(promiseChain, () => {
1348
+ this.parent.emit(commandEvent, operands, unknown);
1349
+ });
1350
+ }
1351
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
1352
+ return promiseChain;
1353
+ }
1354
+ if (this.parent && this.parent.listenerCount(commandEvent)) {
1355
+ checkForUnknownOptions();
1356
+ this._processArguments();
1357
+ this.parent.emit(commandEvent, operands, unknown);
1358
+ } else if (operands.length) {
1359
+ if (this._findCommand("*")) {
1360
+ return this._dispatchSubcommand("*", operands, unknown);
1361
+ }
1362
+ if (this.listenerCount("command:*")) {
1363
+ this.emit("command:*", operands, unknown);
1364
+ } else if (this.commands.length) {
1365
+ this.unknownCommand();
1366
+ } else {
1367
+ checkForUnknownOptions();
1368
+ this._processArguments();
1369
+ }
1370
+ } else if (this.commands.length) {
1371
+ checkForUnknownOptions();
1372
+ this.help({ error: true });
1373
+ } else {
1374
+ checkForUnknownOptions();
1375
+ this._processArguments();
1376
+ }
1377
+ }
1378
+ _findCommand(name) {
1379
+ if (!name)
1380
+ return;
1381
+ return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
1382
+ }
1383
+ _findOption(arg) {
1384
+ return this.options.find((option) => option.is(arg));
1385
+ }
1386
+ _checkForMissingMandatoryOptions() {
1387
+ this._getCommandAndAncestors().forEach((cmd) => {
1388
+ cmd.options.forEach((anOption) => {
1389
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === undefined) {
1390
+ cmd.missingMandatoryOptionValue(anOption);
1391
+ }
1392
+ });
1393
+ });
1394
+ }
1395
+ _checkForConflictingLocalOptions() {
1396
+ const definedNonDefaultOptions = this.options.filter((option) => {
1397
+ const optionKey = option.attributeName();
1398
+ if (this.getOptionValue(optionKey) === undefined) {
1399
+ return false;
1400
+ }
1401
+ return this.getOptionValueSource(optionKey) !== "default";
1402
+ });
1403
+ const optionsWithConflicting = definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0);
1404
+ optionsWithConflicting.forEach((option) => {
1405
+ const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
1406
+ if (conflictingAndDefined) {
1407
+ this._conflictingOption(option, conflictingAndDefined);
1408
+ }
1409
+ });
1410
+ }
1411
+ _checkForConflictingOptions() {
1412
+ this._getCommandAndAncestors().forEach((cmd) => {
1413
+ cmd._checkForConflictingLocalOptions();
1414
+ });
1415
+ }
1416
+ parseOptions(argv) {
1417
+ const operands = [];
1418
+ const unknown = [];
1419
+ let dest = operands;
1420
+ const args = argv.slice();
1421
+ function maybeOption(arg) {
1422
+ return arg.length > 1 && arg[0] === "-";
1423
+ }
1424
+ let activeVariadicOption = null;
1425
+ while (args.length) {
1426
+ const arg = args.shift();
1427
+ if (arg === "--") {
1428
+ if (dest === unknown)
1429
+ dest.push(arg);
1430
+ dest.push(...args);
1431
+ break;
1432
+ }
1433
+ if (activeVariadicOption && !maybeOption(arg)) {
1434
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
1435
+ continue;
1436
+ }
1437
+ activeVariadicOption = null;
1438
+ if (maybeOption(arg)) {
1439
+ const option = this._findOption(arg);
1440
+ if (option) {
1441
+ if (option.required) {
1442
+ const value = args.shift();
1443
+ if (value === undefined)
1444
+ this.optionMissingArgument(option);
1445
+ this.emit(`option:${option.name()}`, value);
1446
+ } else if (option.optional) {
1447
+ let value = null;
1448
+ if (args.length > 0 && !maybeOption(args[0])) {
1449
+ value = args.shift();
1450
+ }
1451
+ this.emit(`option:${option.name()}`, value);
1452
+ } else {
1453
+ this.emit(`option:${option.name()}`);
1454
+ }
1455
+ activeVariadicOption = option.variadic ? option : null;
1456
+ continue;
1457
+ }
1458
+ }
1459
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
1460
+ const option = this._findOption(`-${arg[1]}`);
1461
+ if (option) {
1462
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
1463
+ this.emit(`option:${option.name()}`, arg.slice(2));
1464
+ } else {
1465
+ this.emit(`option:${option.name()}`);
1466
+ args.unshift(`-${arg.slice(2)}`);
1467
+ }
1468
+ continue;
1469
+ }
1470
+ }
1471
+ if (/^--[^=]+=/.test(arg)) {
1472
+ const index = arg.indexOf("=");
1473
+ const option = this._findOption(arg.slice(0, index));
1474
+ if (option && (option.required || option.optional)) {
1475
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
1476
+ continue;
1477
+ }
1478
+ }
1479
+ if (maybeOption(arg)) {
1480
+ dest = unknown;
1481
+ }
1482
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
1483
+ if (this._findCommand(arg)) {
1484
+ operands.push(arg);
1485
+ if (args.length > 0)
1486
+ unknown.push(...args);
1487
+ break;
1488
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
1489
+ operands.push(arg);
1490
+ if (args.length > 0)
1491
+ operands.push(...args);
1492
+ break;
1493
+ } else if (this._defaultCommandName) {
1494
+ unknown.push(arg);
1495
+ if (args.length > 0)
1496
+ unknown.push(...args);
1497
+ break;
1498
+ }
1499
+ }
1500
+ if (this._passThroughOptions) {
1501
+ dest.push(arg);
1502
+ if (args.length > 0)
1503
+ dest.push(...args);
1504
+ break;
1505
+ }
1506
+ dest.push(arg);
1507
+ }
1508
+ return { operands, unknown };
1509
+ }
1510
+ opts() {
1511
+ if (this._storeOptionsAsProperties) {
1512
+ const result = {};
1513
+ const len = this.options.length;
1514
+ for (let i = 0;i < len; i++) {
1515
+ const key = this.options[i].attributeName();
1516
+ result[key] = key === this._versionOptionName ? this._version : this[key];
1517
+ }
1518
+ return result;
1519
+ }
1520
+ return this._optionValues;
1521
+ }
1522
+ optsWithGlobals() {
1523
+ return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
1524
+ }
1525
+ error(message, errorOptions) {
1526
+ this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);
1527
+ if (typeof this._showHelpAfterError === "string") {
1528
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);
1529
+ } else if (this._showHelpAfterError) {
1530
+ this._outputConfiguration.writeErr("\n");
1531
+ this.outputHelp({ error: true });
1532
+ }
1533
+ const config = errorOptions || {};
1534
+ const exitCode = config.exitCode || 1;
1535
+ const code = config.code || "commander.error";
1536
+ this._exit(exitCode, code, message);
1537
+ }
1538
+ _parseOptionsEnv() {
1539
+ this.options.forEach((option) => {
1540
+ if (option.envVar && option.envVar in process2.env) {
1541
+ const optionKey = option.attributeName();
1542
+ if (this.getOptionValue(optionKey) === undefined || ["default", "config", "env"].includes(this.getOptionValueSource(optionKey))) {
1543
+ if (option.required || option.optional) {
1544
+ this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
1545
+ } else {
1546
+ this.emit(`optionEnv:${option.name()}`);
1547
+ }
1548
+ }
1549
+ }
1550
+ });
1551
+ }
1552
+ _parseOptionsImplied() {
1553
+ const dualHelper = new DualOptions(this.options);
1554
+ const hasCustomOptionValue = (optionKey) => {
1555
+ return this.getOptionValue(optionKey) !== undefined && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
1556
+ };
1557
+ this.options.filter((option) => option.implied !== undefined && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
1558
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
1559
+ this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
1560
+ });
1561
+ });
1562
+ }
1563
+ missingArgument(name) {
1564
+ const message = `error: missing required argument '${name}'`;
1565
+ this.error(message, { code: "commander.missingArgument" });
1566
+ }
1567
+ optionMissingArgument(option) {
1568
+ const message = `error: option '${option.flags}' argument missing`;
1569
+ this.error(message, { code: "commander.optionMissingArgument" });
1570
+ }
1571
+ missingMandatoryOptionValue(option) {
1572
+ const message = `error: required option '${option.flags}' not specified`;
1573
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
1574
+ }
1575
+ _conflictingOption(option, conflictingOption) {
1576
+ const findBestOptionFromValue = (option2) => {
1577
+ const optionKey = option2.attributeName();
1578
+ const optionValue = this.getOptionValue(optionKey);
1579
+ const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
1580
+ const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
1581
+ if (negativeOption && (negativeOption.presetArg === undefined && optionValue === false || negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)) {
1582
+ return negativeOption;
1583
+ }
1584
+ return positiveOption || option2;
1585
+ };
1586
+ const getErrorMessage = (option2) => {
1587
+ const bestOption = findBestOptionFromValue(option2);
1588
+ const optionKey = bestOption.attributeName();
1589
+ const source = this.getOptionValueSource(optionKey);
1590
+ if (source === "env") {
1591
+ return `environment variable '${bestOption.envVar}'`;
1592
+ }
1593
+ return `option '${bestOption.flags}'`;
1594
+ };
1595
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
1596
+ this.error(message, { code: "commander.conflictingOption" });
1597
+ }
1598
+ unknownOption(flag) {
1599
+ if (this._allowUnknownOption)
1600
+ return;
1601
+ let suggestion = "";
1602
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
1603
+ let candidateFlags = [];
1604
+ let command = this;
1605
+ do {
1606
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
1607
+ candidateFlags = candidateFlags.concat(moreFlags);
1608
+ command = command.parent;
1609
+ } while (command && !command._enablePositionalOptions);
1610
+ suggestion = suggestSimilar(flag, candidateFlags);
1611
+ }
1612
+ const message = `error: unknown option '${flag}'${suggestion}`;
1613
+ this.error(message, { code: "commander.unknownOption" });
1614
+ }
1615
+ _excessArguments(receivedArgs) {
1616
+ if (this._allowExcessArguments)
1617
+ return;
1618
+ const expected = this.registeredArguments.length;
1619
+ const s = expected === 1 ? "" : "s";
1620
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
1621
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
1622
+ this.error(message, { code: "commander.excessArguments" });
1623
+ }
1624
+ unknownCommand() {
1625
+ const unknownName = this.args[0];
1626
+ let suggestion = "";
1627
+ if (this._showSuggestionAfterError) {
1628
+ const candidateNames = [];
1629
+ this.createHelp().visibleCommands(this).forEach((command) => {
1630
+ candidateNames.push(command.name());
1631
+ if (command.alias())
1632
+ candidateNames.push(command.alias());
1633
+ });
1634
+ suggestion = suggestSimilar(unknownName, candidateNames);
1635
+ }
1636
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
1637
+ this.error(message, { code: "commander.unknownCommand" });
1638
+ }
1639
+ version(str, flags, description) {
1640
+ if (str === undefined)
1641
+ return this._version;
1642
+ this._version = str;
1643
+ flags = flags || "-V, --version";
1644
+ description = description || "output the version number";
1645
+ const versionOption = this.createOption(flags, description);
1646
+ this._versionOptionName = versionOption.attributeName();
1647
+ this._registerOption(versionOption);
1648
+ this.on("option:" + versionOption.name(), () => {
1649
+ this._outputConfiguration.writeOut(`${str}\n`);
1650
+ this._exit(0, "commander.version", str);
1651
+ });
1652
+ return this;
1653
+ }
1654
+ description(str, argsDescription) {
1655
+ if (str === undefined && argsDescription === undefined)
1656
+ return this._description;
1657
+ this._description = str;
1658
+ if (argsDescription) {
1659
+ this._argsDescription = argsDescription;
1660
+ }
1661
+ return this;
1662
+ }
1663
+ summary(str) {
1664
+ if (str === undefined)
1665
+ return this._summary;
1666
+ this._summary = str;
1667
+ return this;
1668
+ }
1669
+ alias(alias) {
1670
+ if (alias === undefined)
1671
+ return this._aliases[0];
1672
+ let command = this;
1673
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
1674
+ command = this.commands[this.commands.length - 1];
1675
+ }
1676
+ if (alias === command._name)
1677
+ throw new Error("Command alias can't be the same as its name");
1678
+ const matchingCommand = this.parent?._findCommand(alias);
1679
+ if (matchingCommand) {
1680
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
1681
+ throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
1682
+ }
1683
+ command._aliases.push(alias);
1684
+ return this;
1685
+ }
1686
+ aliases(aliases) {
1687
+ if (aliases === undefined)
1688
+ return this._aliases;
1689
+ aliases.forEach((alias) => this.alias(alias));
1690
+ return this;
1691
+ }
1692
+ usage(str) {
1693
+ if (str === undefined) {
1694
+ if (this._usage)
1695
+ return this._usage;
1696
+ const args = this.registeredArguments.map((arg) => {
1697
+ return humanReadableArgName(arg);
1698
+ });
1699
+ return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
1700
+ }
1701
+ this._usage = str;
1702
+ return this;
1703
+ }
1704
+ name(str) {
1705
+ if (str === undefined)
1706
+ return this._name;
1707
+ this._name = str;
1708
+ return this;
1709
+ }
1710
+ nameFromFilename(filename) {
1711
+ this._name = path.basename(filename, path.extname(filename));
1712
+ return this;
1713
+ }
1714
+ executableDir(path2) {
1715
+ if (path2 === undefined)
1716
+ return this._executableDir;
1717
+ this._executableDir = path2;
1718
+ return this;
1719
+ }
1720
+ helpInformation(contextOptions) {
1721
+ const helper = this.createHelp();
1722
+ if (helper.helpWidth === undefined) {
1723
+ helper.helpWidth = contextOptions && contextOptions.error ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();
1724
+ }
1725
+ return helper.formatHelp(this, helper);
1726
+ }
1727
+ _getHelpContext(contextOptions) {
1728
+ contextOptions = contextOptions || {};
1729
+ const context = { error: !!contextOptions.error };
1730
+ let write;
1731
+ if (context.error) {
1732
+ write = (arg) => this._outputConfiguration.writeErr(arg);
1733
+ } else {
1734
+ write = (arg) => this._outputConfiguration.writeOut(arg);
1735
+ }
1736
+ context.write = contextOptions.write || write;
1737
+ context.command = this;
1738
+ return context;
1739
+ }
1740
+ outputHelp(contextOptions) {
1741
+ let deprecatedCallback;
1742
+ if (typeof contextOptions === "function") {
1743
+ deprecatedCallback = contextOptions;
1744
+ contextOptions = undefined;
1745
+ }
1746
+ const context = this._getHelpContext(contextOptions);
1747
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", context));
1748
+ this.emit("beforeHelp", context);
1749
+ let helpInformation = this.helpInformation(context);
1750
+ if (deprecatedCallback) {
1751
+ helpInformation = deprecatedCallback(helpInformation);
1752
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
1753
+ throw new Error("outputHelp callback must return a string or a Buffer");
1754
+ }
1755
+ }
1756
+ context.write(helpInformation);
1757
+ if (this._getHelpOption()?.long) {
1758
+ this.emit(this._getHelpOption().long);
1759
+ }
1760
+ this.emit("afterHelp", context);
1761
+ this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", context));
1762
+ }
1763
+ helpOption(flags, description) {
1764
+ if (typeof flags === "boolean") {
1765
+ if (flags) {
1766
+ this._helpOption = this._helpOption ?? undefined;
1767
+ } else {
1768
+ this._helpOption = null;
1769
+ }
1770
+ return this;
1771
+ }
1772
+ flags = flags ?? "-h, --help";
1773
+ description = description ?? "display help for command";
1774
+ this._helpOption = this.createOption(flags, description);
1775
+ return this;
1776
+ }
1777
+ _getHelpOption() {
1778
+ if (this._helpOption === undefined) {
1779
+ this.helpOption(undefined, undefined);
1780
+ }
1781
+ return this._helpOption;
1782
+ }
1783
+ addHelpOption(option) {
1784
+ this._helpOption = option;
1785
+ return this;
1786
+ }
1787
+ help(contextOptions) {
1788
+ this.outputHelp(contextOptions);
1789
+ let exitCode = process2.exitCode || 0;
1790
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
1791
+ exitCode = 1;
1792
+ }
1793
+ this._exit(exitCode, "commander.help", "(outputHelp)");
1794
+ }
1795
+ addHelpText(position, text) {
1796
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
1797
+ if (!allowedValues.includes(position)) {
1798
+ throw new Error(`Unexpected value for position to addHelpText.
1799
+ Expecting one of '${allowedValues.join("', '")}'`);
1800
+ }
1801
+ const helpEvent = `${position}Help`;
1802
+ this.on(helpEvent, (context) => {
1803
+ let helpStr;
1804
+ if (typeof text === "function") {
1805
+ helpStr = text({ error: context.error, command: context.command });
1806
+ } else {
1807
+ helpStr = text;
1808
+ }
1809
+ if (helpStr) {
1810
+ context.write(`${helpStr}\n`);
1811
+ }
1812
+ });
1813
+ return this;
1814
+ }
1815
+ _outputHelpIfRequested(args) {
1816
+ const helpOption = this._getHelpOption();
1817
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
1818
+ if (helpRequested) {
1819
+ this.outputHelp();
1820
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
1821
+ }
1822
+ }
1823
+ }
1824
+ exports.Command = Command;
1825
+ });
1826
+
1827
+ // node_modules/commander/index.js
1828
+ var require_commander = __commonJS((exports) => {
1829
+ var { Argument } = require_argument();
1830
+ var { Command } = require_command();
1831
+ var { CommanderError, InvalidArgumentError } = require_error();
1832
+ var { Help } = require_help();
1833
+ var { Option } = require_option();
1834
+ exports.program = new Command;
1835
+ exports.createCommand = (name) => new Command(name);
1836
+ exports.createOption = (flags, description) => new Option(flags, description);
1837
+ exports.createArgument = (name, description) => new Argument(name, description);
1838
+ exports.Command = Command;
1839
+ exports.Option = Option;
1840
+ exports.Argument = Argument;
1841
+ exports.Help = Help;
1842
+ exports.CommanderError = CommanderError;
1843
+ exports.InvalidArgumentError = InvalidArgumentError;
1844
+ exports.InvalidOptionArgumentError = InvalidArgumentError;
1845
+ });
1846
+
1847
+ // node_modules/uuid/dist/max.js
1848
+ var require_max = __commonJS((exports) => {
1849
+ Object.defineProperty(exports, "__esModule", {
1850
+ value: true
1851
+ });
1852
+ exports.default = undefined;
1853
+ var _default = exports.default = "ffffffff-ffff-ffff-ffff-ffffffffffff";
1854
+ });
1855
+
1856
+ // node_modules/uuid/dist/nil.js
1857
+ var require_nil = __commonJS((exports) => {
1858
+ Object.defineProperty(exports, "__esModule", {
1859
+ value: true
1860
+ });
1861
+ exports.default = undefined;
1862
+ var _default = exports.default = "00000000-0000-0000-0000-000000000000";
1863
+ });
1864
+
1865
+ // node_modules/uuid/dist/regex.js
1866
+ var require_regex = __commonJS((exports) => {
1867
+ Object.defineProperty(exports, "__esModule", {
1868
+ value: true
1869
+ });
1870
+ exports.default = undefined;
1871
+ var _default = exports.default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;
1872
+ });
1873
+
1874
+ // node_modules/uuid/dist/validate.js
1875
+ var require_validate = __commonJS((exports) => {
1876
+ var _interopRequireDefault = function(e) {
1877
+ return e && e.__esModule ? e : { default: e };
1878
+ };
1879
+ var validate = function(uuid) {
1880
+ return typeof uuid === "string" && _regex.default.test(uuid);
1881
+ };
1882
+ Object.defineProperty(exports, "__esModule", {
1883
+ value: true
1884
+ });
1885
+ exports.default = undefined;
1886
+ var _regex = _interopRequireDefault(require_regex());
1887
+ var _default = exports.default = validate;
1888
+ });
1889
+
1890
+ // node_modules/uuid/dist/parse.js
1891
+ var require_parse = __commonJS((exports) => {
1892
+ var _interopRequireDefault = function(e) {
1893
+ return e && e.__esModule ? e : { default: e };
1894
+ };
1895
+ var parse = function(uuid) {
1896
+ if (!(0, _validate.default)(uuid)) {
1897
+ throw TypeError("Invalid UUID");
1898
+ }
1899
+ let v;
1900
+ const arr = new Uint8Array(16);
1901
+ arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;
1902
+ arr[1] = v >>> 16 & 255;
1903
+ arr[2] = v >>> 8 & 255;
1904
+ arr[3] = v & 255;
1905
+ arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;
1906
+ arr[5] = v & 255;
1907
+ arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;
1908
+ arr[7] = v & 255;
1909
+ arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;
1910
+ arr[9] = v & 255;
1911
+ arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 1099511627776 & 255;
1912
+ arr[11] = v / 4294967296 & 255;
1913
+ arr[12] = v >>> 24 & 255;
1914
+ arr[13] = v >>> 16 & 255;
1915
+ arr[14] = v >>> 8 & 255;
1916
+ arr[15] = v & 255;
1917
+ return arr;
1918
+ };
1919
+ Object.defineProperty(exports, "__esModule", {
1920
+ value: true
1921
+ });
1922
+ exports.default = undefined;
1923
+ var _validate = _interopRequireDefault(require_validate());
1924
+ var _default = exports.default = parse;
1925
+ });
1926
+
1927
+ // node_modules/uuid/dist/stringify.js
1928
+ var require_stringify = __commonJS((exports) => {
1929
+ var _interopRequireDefault = function(e) {
1930
+ return e && e.__esModule ? e : { default: e };
1931
+ };
1932
+ var unsafeStringify = function(arr, offset = 0) {
1933
+ return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
1934
+ };
1935
+ var stringify = function(arr, offset = 0) {
1936
+ const uuid = unsafeStringify(arr, offset);
1937
+ if (!(0, _validate.default)(uuid)) {
1938
+ throw TypeError("Stringified UUID is invalid");
1939
+ }
1940
+ return uuid;
1941
+ };
1942
+ Object.defineProperty(exports, "__esModule", {
1943
+ value: true
1944
+ });
1945
+ exports.default = undefined;
1946
+ exports.unsafeStringify = unsafeStringify;
1947
+ var _validate = _interopRequireDefault(require_validate());
1948
+ var byteToHex = [];
1949
+ for (let i = 0;i < 256; ++i) {
1950
+ byteToHex.push((i + 256).toString(16).slice(1));
1951
+ }
1952
+ var _default = exports.default = stringify;
1953
+ });
1954
+
1955
+ // node_modules/uuid/dist/rng.js
1956
+ var require_rng = __commonJS((exports) => {
1957
+ var _interopRequireDefault = function(e) {
1958
+ return e && e.__esModule ? e : { default: e };
1959
+ };
1960
+ var rng = function() {
1961
+ if (poolPtr > rnds8Pool.length - 16) {
1962
+ _nodeCrypto.default.randomFillSync(rnds8Pool);
1963
+ poolPtr = 0;
1964
+ }
1965
+ return rnds8Pool.slice(poolPtr, poolPtr += 16);
1966
+ };
1967
+ Object.defineProperty(exports, "__esModule", {
1968
+ value: true
1969
+ });
1970
+ exports.default = rng;
1971
+ var _nodeCrypto = _interopRequireDefault(import.meta.require("crypto"));
1972
+ var rnds8Pool = new Uint8Array(256);
1973
+ var poolPtr = rnds8Pool.length;
1974
+ });
1975
+
1976
+ // node_modules/uuid/dist/v1.js
1977
+ var require_v1 = __commonJS((exports) => {
1978
+ var _interopRequireDefault = function(e) {
1979
+ return e && e.__esModule ? e : { default: e };
1980
+ };
1981
+ var v1 = function(options, buf, offset) {
1982
+ let i = buf && offset || 0;
1983
+ const b = buf || new Array(16);
1984
+ options = options || {};
1985
+ let node = options.node;
1986
+ let clockseq = options.clockseq;
1987
+ if (!options._v6) {
1988
+ if (!node) {
1989
+ node = _nodeId;
1990
+ }
1991
+ if (clockseq == null) {
1992
+ clockseq = _clockseq;
1993
+ }
1994
+ }
1995
+ if (node == null || clockseq == null) {
1996
+ const seedBytes = options.random || (options.rng || _rng.default)();
1997
+ if (node == null) {
1998
+ node = [seedBytes[0], seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];
1999
+ if (!_nodeId && !options._v6) {
2000
+ node[0] |= 1;
2001
+ _nodeId = node;
2002
+ }
2003
+ }
2004
+ if (clockseq == null) {
2005
+ clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 16383;
2006
+ if (_clockseq === undefined && !options._v6) {
2007
+ _clockseq = clockseq;
2008
+ }
2009
+ }
2010
+ }
2011
+ let msecs = options.msecs !== undefined ? options.msecs : Date.now();
2012
+ let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;
2013
+ const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 1e4;
2014
+ if (dt < 0 && options.clockseq === undefined) {
2015
+ clockseq = clockseq + 1 & 16383;
2016
+ }
2017
+ if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
2018
+ nsecs = 0;
2019
+ }
2020
+ if (nsecs >= 1e4) {
2021
+ throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");
2022
+ }
2023
+ _lastMSecs = msecs;
2024
+ _lastNSecs = nsecs;
2025
+ _clockseq = clockseq;
2026
+ msecs += 12219292800000;
2027
+ const tl = ((msecs & 268435455) * 1e4 + nsecs) % 4294967296;
2028
+ b[i++] = tl >>> 24 & 255;
2029
+ b[i++] = tl >>> 16 & 255;
2030
+ b[i++] = tl >>> 8 & 255;
2031
+ b[i++] = tl & 255;
2032
+ const tmh = msecs / 4294967296 * 1e4 & 268435455;
2033
+ b[i++] = tmh >>> 8 & 255;
2034
+ b[i++] = tmh & 255;
2035
+ b[i++] = tmh >>> 24 & 15 | 16;
2036
+ b[i++] = tmh >>> 16 & 255;
2037
+ b[i++] = clockseq >>> 8 | 128;
2038
+ b[i++] = clockseq & 255;
2039
+ for (let n = 0;n < 6; ++n) {
2040
+ b[i + n] = node[n];
2041
+ }
2042
+ return buf || (0, _stringify.unsafeStringify)(b);
2043
+ };
2044
+ Object.defineProperty(exports, "__esModule", {
2045
+ value: true
2046
+ });
2047
+ exports.default = undefined;
2048
+ var _rng = _interopRequireDefault(require_rng());
2049
+ var _stringify = require_stringify();
2050
+ var _nodeId;
2051
+ var _clockseq;
2052
+ var _lastMSecs = 0;
2053
+ var _lastNSecs = 0;
2054
+ var _default = exports.default = v1;
2055
+ });
2056
+
2057
+ // node_modules/uuid/dist/v1ToV6.js
2058
+ var require_v1ToV6 = __commonJS((exports) => {
2059
+ var _interopRequireDefault = function(e) {
2060
+ return e && e.__esModule ? e : { default: e };
2061
+ };
2062
+ var v1ToV6 = function(uuid) {
2063
+ const v1Bytes = typeof uuid === "string" ? (0, _parse.default)(uuid) : uuid;
2064
+ const v6Bytes = _v1ToV6(v1Bytes);
2065
+ return typeof uuid === "string" ? (0, _stringify.unsafeStringify)(v6Bytes) : v6Bytes;
2066
+ };
2067
+ var _v1ToV6 = function(v1Bytes, randomize = false) {
2068
+ return Uint8Array.of((v1Bytes[6] & 15) << 4 | v1Bytes[7] >> 4 & 15, (v1Bytes[7] & 15) << 4 | (v1Bytes[4] & 240) >> 4, (v1Bytes[4] & 15) << 4 | (v1Bytes[5] & 240) >> 4, (v1Bytes[5] & 15) << 4 | (v1Bytes[0] & 240) >> 4, (v1Bytes[0] & 15) << 4 | (v1Bytes[1] & 240) >> 4, (v1Bytes[1] & 15) << 4 | (v1Bytes[2] & 240) >> 4, 96 | v1Bytes[2] & 15, v1Bytes[3], v1Bytes[8], v1Bytes[9], v1Bytes[10], v1Bytes[11], v1Bytes[12], v1Bytes[13], v1Bytes[14], v1Bytes[15]);
2069
+ };
2070
+ Object.defineProperty(exports, "__esModule", {
2071
+ value: true
2072
+ });
2073
+ exports.default = v1ToV6;
2074
+ var _parse = _interopRequireDefault(require_parse());
2075
+ var _stringify = require_stringify();
2076
+ });
2077
+
2078
+ // node_modules/uuid/dist/v35.js
2079
+ var require_v35 = __commonJS((exports) => {
2080
+ var _interopRequireDefault = function(e) {
2081
+ return e && e.__esModule ? e : { default: e };
2082
+ };
2083
+ var stringToBytes = function(str) {
2084
+ str = unescape(encodeURIComponent(str));
2085
+ const bytes = [];
2086
+ for (let i = 0;i < str.length; ++i) {
2087
+ bytes.push(str.charCodeAt(i));
2088
+ }
2089
+ return bytes;
2090
+ };
2091
+ var v35 = function(name, version, hashfunc) {
2092
+ function generateUUID(value, namespace, buf, offset) {
2093
+ var _namespace;
2094
+ if (typeof value === "string") {
2095
+ value = stringToBytes(value);
2096
+ }
2097
+ if (typeof namespace === "string") {
2098
+ namespace = (0, _parse.default)(namespace);
2099
+ }
2100
+ if (((_namespace = namespace) === null || _namespace === undefined ? undefined : _namespace.length) !== 16) {
2101
+ throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");
2102
+ }
2103
+ let bytes = new Uint8Array(16 + value.length);
2104
+ bytes.set(namespace);
2105
+ bytes.set(value, namespace.length);
2106
+ bytes = hashfunc(bytes);
2107
+ bytes[6] = bytes[6] & 15 | version;
2108
+ bytes[8] = bytes[8] & 63 | 128;
2109
+ if (buf) {
2110
+ offset = offset || 0;
2111
+ for (let i = 0;i < 16; ++i) {
2112
+ buf[offset + i] = bytes[i];
2113
+ }
2114
+ return buf;
2115
+ }
2116
+ return (0, _stringify.unsafeStringify)(bytes);
2117
+ }
2118
+ try {
2119
+ generateUUID.name = name;
2120
+ } catch (err) {
2121
+ }
2122
+ generateUUID.DNS = DNS;
2123
+ generateUUID.URL = URL;
2124
+ return generateUUID;
2125
+ };
2126
+ Object.defineProperty(exports, "__esModule", {
2127
+ value: true
2128
+ });
2129
+ exports.URL = exports.DNS = undefined;
2130
+ exports.default = v35;
2131
+ var _stringify = require_stringify();
2132
+ var _parse = _interopRequireDefault(require_parse());
2133
+ var DNS = exports.DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
2134
+ var URL = exports.URL = "6ba7b811-9dad-11d1-80b4-00c04fd430c8";
2135
+ });
2136
+
2137
+ // node_modules/uuid/dist/md5.js
2138
+ var require_md5 = __commonJS((exports) => {
2139
+ var _interopRequireDefault = function(e) {
2140
+ return e && e.__esModule ? e : { default: e };
2141
+ };
2142
+ var md5 = function(bytes) {
2143
+ if (Array.isArray(bytes)) {
2144
+ bytes = Buffer.from(bytes);
2145
+ } else if (typeof bytes === "string") {
2146
+ bytes = Buffer.from(bytes, "utf8");
2147
+ }
2148
+ return _nodeCrypto.default.createHash("md5").update(bytes).digest();
2149
+ };
2150
+ Object.defineProperty(exports, "__esModule", {
2151
+ value: true
2152
+ });
2153
+ exports.default = undefined;
2154
+ var _nodeCrypto = _interopRequireDefault(import.meta.require("crypto"));
2155
+ var _default = exports.default = md5;
2156
+ });
2157
+
2158
+ // node_modules/uuid/dist/v3.js
2159
+ var require_v3 = __commonJS((exports) => {
2160
+ var _interopRequireDefault = function(e) {
2161
+ return e && e.__esModule ? e : { default: e };
2162
+ };
2163
+ Object.defineProperty(exports, "__esModule", {
2164
+ value: true
2165
+ });
2166
+ exports.default = undefined;
2167
+ var _v = _interopRequireDefault(require_v35());
2168
+ var _md = _interopRequireDefault(require_md5());
2169
+ var v3 = (0, _v.default)("v3", 48, _md.default);
2170
+ var _default = exports.default = v3;
2171
+ });
2172
+
2173
+ // node_modules/uuid/dist/native.js
2174
+ var require_native = __commonJS((exports) => {
2175
+ var _interopRequireDefault = function(e) {
2176
+ return e && e.__esModule ? e : { default: e };
2177
+ };
2178
+ Object.defineProperty(exports, "__esModule", {
2179
+ value: true
2180
+ });
2181
+ exports.default = undefined;
2182
+ var _nodeCrypto = _interopRequireDefault(import.meta.require("crypto"));
2183
+ var _default = exports.default = {
2184
+ randomUUID: _nodeCrypto.default.randomUUID
2185
+ };
2186
+ });
2187
+
2188
+ // node_modules/uuid/dist/v4.js
2189
+ var require_v4 = __commonJS((exports) => {
2190
+ var _interopRequireDefault = function(e) {
2191
+ return e && e.__esModule ? e : { default: e };
2192
+ };
2193
+ var v4 = function(options, buf, offset) {
2194
+ if (_native.default.randomUUID && !buf && !options) {
2195
+ return _native.default.randomUUID();
2196
+ }
2197
+ options = options || {};
2198
+ const rnds = options.random || (options.rng || _rng.default)();
2199
+ rnds[6] = rnds[6] & 15 | 64;
2200
+ rnds[8] = rnds[8] & 63 | 128;
2201
+ if (buf) {
2202
+ offset = offset || 0;
2203
+ for (let i = 0;i < 16; ++i) {
2204
+ buf[offset + i] = rnds[i];
2205
+ }
2206
+ return buf;
2207
+ }
2208
+ return (0, _stringify.unsafeStringify)(rnds);
2209
+ };
2210
+ Object.defineProperty(exports, "__esModule", {
2211
+ value: true
2212
+ });
2213
+ exports.default = undefined;
2214
+ var _native = _interopRequireDefault(require_native());
2215
+ var _rng = _interopRequireDefault(require_rng());
2216
+ var _stringify = require_stringify();
2217
+ var _default = exports.default = v4;
2218
+ });
2219
+
2220
+ // node_modules/uuid/dist/sha1.js
2221
+ var require_sha1 = __commonJS((exports) => {
2222
+ var _interopRequireDefault = function(e) {
2223
+ return e && e.__esModule ? e : { default: e };
2224
+ };
2225
+ var sha1 = function(bytes) {
2226
+ if (Array.isArray(bytes)) {
2227
+ bytes = Buffer.from(bytes);
2228
+ } else if (typeof bytes === "string") {
2229
+ bytes = Buffer.from(bytes, "utf8");
2230
+ }
2231
+ return _nodeCrypto.default.createHash("sha1").update(bytes).digest();
2232
+ };
2233
+ Object.defineProperty(exports, "__esModule", {
2234
+ value: true
2235
+ });
2236
+ exports.default = undefined;
2237
+ var _nodeCrypto = _interopRequireDefault(import.meta.require("crypto"));
2238
+ var _default = exports.default = sha1;
2239
+ });
2240
+
2241
+ // node_modules/uuid/dist/v5.js
2242
+ var require_v5 = __commonJS((exports) => {
2243
+ var _interopRequireDefault = function(e) {
2244
+ return e && e.__esModule ? e : { default: e };
2245
+ };
2246
+ Object.defineProperty(exports, "__esModule", {
2247
+ value: true
2248
+ });
2249
+ exports.default = undefined;
2250
+ var _v = _interopRequireDefault(require_v35());
2251
+ var _sha = _interopRequireDefault(require_sha1());
2252
+ var v5 = (0, _v.default)("v5", 80, _sha.default);
2253
+ var _default = exports.default = v5;
2254
+ });
2255
+
2256
+ // node_modules/uuid/dist/v6.js
2257
+ var require_v6 = __commonJS((exports) => {
2258
+ var _interopRequireDefault = function(e) {
2259
+ return e && e.__esModule ? e : { default: e };
2260
+ };
2261
+ var v6 = function(options = {}, buf, offset = 0) {
2262
+ let bytes = (0, _v.default)({
2263
+ ...options,
2264
+ _v6: true
2265
+ }, new Uint8Array(16));
2266
+ bytes = (0, _v1ToV.default)(bytes);
2267
+ if (buf) {
2268
+ for (let i = 0;i < 16; i++) {
2269
+ buf[offset + i] = bytes[i];
2270
+ }
2271
+ return buf;
2272
+ }
2273
+ return (0, _stringify.unsafeStringify)(bytes);
2274
+ };
2275
+ Object.defineProperty(exports, "__esModule", {
2276
+ value: true
2277
+ });
2278
+ exports.default = v6;
2279
+ var _stringify = require_stringify();
2280
+ var _v = _interopRequireDefault(require_v1());
2281
+ var _v1ToV = _interopRequireDefault(require_v1ToV6());
2282
+ });
2283
+
2284
+ // node_modules/uuid/dist/v6ToV1.js
2285
+ var require_v6ToV1 = __commonJS((exports) => {
2286
+ var _interopRequireDefault = function(e) {
2287
+ return e && e.__esModule ? e : { default: e };
2288
+ };
2289
+ var v6ToV1 = function(uuid) {
2290
+ const v6Bytes = typeof uuid === "string" ? (0, _parse.default)(uuid) : uuid;
2291
+ const v1Bytes = _v6ToV1(v6Bytes);
2292
+ return typeof uuid === "string" ? (0, _stringify.unsafeStringify)(v1Bytes) : v1Bytes;
2293
+ };
2294
+ var _v6ToV1 = function(v6Bytes) {
2295
+ return Uint8Array.of((v6Bytes[3] & 15) << 4 | v6Bytes[4] >> 4 & 15, (v6Bytes[4] & 15) << 4 | (v6Bytes[5] & 240) >> 4, (v6Bytes[5] & 15) << 4 | v6Bytes[6] & 15, v6Bytes[7], (v6Bytes[1] & 15) << 4 | (v6Bytes[2] & 240) >> 4, (v6Bytes[2] & 15) << 4 | (v6Bytes[3] & 240) >> 4, 16 | (v6Bytes[0] & 240) >> 4, (v6Bytes[0] & 15) << 4 | (v6Bytes[1] & 240) >> 4, v6Bytes[8], v6Bytes[9], v6Bytes[10], v6Bytes[11], v6Bytes[12], v6Bytes[13], v6Bytes[14], v6Bytes[15]);
2296
+ };
2297
+ Object.defineProperty(exports, "__esModule", {
2298
+ value: true
2299
+ });
2300
+ exports.default = v6ToV1;
2301
+ var _parse = _interopRequireDefault(require_parse());
2302
+ var _stringify = require_stringify();
2303
+ });
2304
+
2305
+ // node_modules/uuid/dist/v7.js
2306
+ var require_v7 = __commonJS((exports) => {
2307
+ var _interopRequireDefault = function(e) {
2308
+ return e && e.__esModule ? e : { default: e };
2309
+ };
2310
+ var v7 = function(options, buf, offset) {
2311
+ options = options || {};
2312
+ let i = buf && offset || 0;
2313
+ const b = buf || new Uint8Array(16);
2314
+ const rnds = options.random || (options.rng || _rng.default)();
2315
+ const msecs = options.msecs !== undefined ? options.msecs : Date.now();
2316
+ let seq = options.seq !== undefined ? options.seq : null;
2317
+ let seqHigh = _seqHigh;
2318
+ let seqLow = _seqLow;
2319
+ if (msecs > _msecs && options.msecs === undefined) {
2320
+ _msecs = msecs;
2321
+ if (seq !== null) {
2322
+ seqHigh = null;
2323
+ seqLow = null;
2324
+ }
2325
+ }
2326
+ if (seq !== null) {
2327
+ if (seq > 2147483647) {
2328
+ seq = 2147483647;
2329
+ }
2330
+ seqHigh = seq >>> 19 & 4095;
2331
+ seqLow = seq & 524287;
2332
+ }
2333
+ if (seqHigh === null || seqLow === null) {
2334
+ seqHigh = rnds[6] & 127;
2335
+ seqHigh = seqHigh << 8 | rnds[7];
2336
+ seqLow = rnds[8] & 63;
2337
+ seqLow = seqLow << 8 | rnds[9];
2338
+ seqLow = seqLow << 5 | rnds[10] >>> 3;
2339
+ }
2340
+ if (msecs + 1e4 > _msecs && seq === null) {
2341
+ if (++seqLow > 524287) {
2342
+ seqLow = 0;
2343
+ if (++seqHigh > 4095) {
2344
+ seqHigh = 0;
2345
+ _msecs++;
2346
+ }
2347
+ }
2348
+ } else {
2349
+ _msecs = msecs;
2350
+ }
2351
+ _seqHigh = seqHigh;
2352
+ _seqLow = seqLow;
2353
+ b[i++] = _msecs / 1099511627776 & 255;
2354
+ b[i++] = _msecs / 4294967296 & 255;
2355
+ b[i++] = _msecs / 16777216 & 255;
2356
+ b[i++] = _msecs / 65536 & 255;
2357
+ b[i++] = _msecs / 256 & 255;
2358
+ b[i++] = _msecs & 255;
2359
+ b[i++] = seqHigh >>> 4 & 15 | 112;
2360
+ b[i++] = seqHigh & 255;
2361
+ b[i++] = seqLow >>> 13 & 63 | 128;
2362
+ b[i++] = seqLow >>> 5 & 255;
2363
+ b[i++] = seqLow << 3 & 255 | rnds[10] & 7;
2364
+ b[i++] = rnds[11];
2365
+ b[i++] = rnds[12];
2366
+ b[i++] = rnds[13];
2367
+ b[i++] = rnds[14];
2368
+ b[i++] = rnds[15];
2369
+ return buf || (0, _stringify.unsafeStringify)(b);
2370
+ };
2371
+ Object.defineProperty(exports, "__esModule", {
2372
+ value: true
2373
+ });
2374
+ exports.default = undefined;
2375
+ var _rng = _interopRequireDefault(require_rng());
2376
+ var _stringify = require_stringify();
2377
+ var _seqLow = null;
2378
+ var _seqHigh = null;
2379
+ var _msecs = 0;
2380
+ var _default = exports.default = v7;
2381
+ });
2382
+
2383
+ // node_modules/uuid/dist/version.js
2384
+ var require_version = __commonJS((exports) => {
2385
+ var _interopRequireDefault = function(e) {
2386
+ return e && e.__esModule ? e : { default: e };
2387
+ };
2388
+ var version = function(uuid) {
2389
+ if (!(0, _validate.default)(uuid)) {
2390
+ throw TypeError("Invalid UUID");
2391
+ }
2392
+ return parseInt(uuid.slice(14, 15), 16);
2393
+ };
2394
+ Object.defineProperty(exports, "__esModule", {
2395
+ value: true
2396
+ });
2397
+ exports.default = undefined;
2398
+ var _validate = _interopRequireDefault(require_validate());
2399
+ var _default = exports.default = version;
2400
+ });
2401
+
2402
+ // node_modules/uuid/dist/index.js
2403
+ var require_dist = __commonJS((exports) => {
2404
+ var _interopRequireDefault = function(e) {
2405
+ return e && e.__esModule ? e : { default: e };
2406
+ };
2407
+ Object.defineProperty(exports, "__esModule", {
2408
+ value: true
2409
+ });
2410
+ Object.defineProperty(exports, "MAX", {
2411
+ enumerable: true,
2412
+ get: function() {
2413
+ return _max.default;
2414
+ }
2415
+ });
2416
+ Object.defineProperty(exports, "NIL", {
2417
+ enumerable: true,
2418
+ get: function() {
2419
+ return _nil.default;
2420
+ }
2421
+ });
2422
+ Object.defineProperty(exports, "parse", {
2423
+ enumerable: true,
2424
+ get: function() {
2425
+ return _parse.default;
2426
+ }
2427
+ });
2428
+ Object.defineProperty(exports, "stringify", {
2429
+ enumerable: true,
2430
+ get: function() {
2431
+ return _stringify.default;
2432
+ }
2433
+ });
2434
+ Object.defineProperty(exports, "v1", {
2435
+ enumerable: true,
2436
+ get: function() {
2437
+ return _v.default;
2438
+ }
2439
+ });
2440
+ Object.defineProperty(exports, "v1ToV6", {
2441
+ enumerable: true,
2442
+ get: function() {
2443
+ return _v1ToV.default;
2444
+ }
2445
+ });
2446
+ Object.defineProperty(exports, "v3", {
2447
+ enumerable: true,
2448
+ get: function() {
2449
+ return _v2.default;
2450
+ }
2451
+ });
2452
+ Object.defineProperty(exports, "v4", {
2453
+ enumerable: true,
2454
+ get: function() {
2455
+ return _v3.default;
2456
+ }
2457
+ });
2458
+ Object.defineProperty(exports, "v5", {
2459
+ enumerable: true,
2460
+ get: function() {
2461
+ return _v4.default;
2462
+ }
2463
+ });
2464
+ Object.defineProperty(exports, "v6", {
2465
+ enumerable: true,
2466
+ get: function() {
2467
+ return _v5.default;
2468
+ }
2469
+ });
2470
+ Object.defineProperty(exports, "v6ToV1", {
2471
+ enumerable: true,
2472
+ get: function() {
2473
+ return _v6ToV.default;
2474
+ }
2475
+ });
2476
+ Object.defineProperty(exports, "v7", {
2477
+ enumerable: true,
2478
+ get: function() {
2479
+ return _v6.default;
2480
+ }
2481
+ });
2482
+ Object.defineProperty(exports, "validate", {
2483
+ enumerable: true,
2484
+ get: function() {
2485
+ return _validate.default;
2486
+ }
2487
+ });
2488
+ Object.defineProperty(exports, "version", {
2489
+ enumerable: true,
2490
+ get: function() {
2491
+ return _version.default;
2492
+ }
2493
+ });
2494
+ var _max = _interopRequireDefault(require_max());
2495
+ var _nil = _interopRequireDefault(require_nil());
2496
+ var _parse = _interopRequireDefault(require_parse());
2497
+ var _stringify = _interopRequireDefault(require_stringify());
2498
+ var _v = _interopRequireDefault(require_v1());
2499
+ var _v1ToV = _interopRequireDefault(require_v1ToV6());
2500
+ var _v2 = _interopRequireDefault(require_v3());
2501
+ var _v3 = _interopRequireDefault(require_v4());
2502
+ var _v4 = _interopRequireDefault(require_v5());
2503
+ var _v5 = _interopRequireDefault(require_v6());
2504
+ var _v6ToV = _interopRequireDefault(require_v6ToV1());
2505
+ var _v6 = _interopRequireDefault(require_v7());
2506
+ var _validate = _interopRequireDefault(require_validate());
2507
+ var _version = _interopRequireDefault(require_version());
2508
+ });
2509
+
2510
+ // node_modules/commander/esm.mjs
2511
+ var import_ = __toESM(require_commander(), 1);
2512
+ var {
2513
+ program,
2514
+ createCommand,
2515
+ createArgument,
2516
+ createOption,
2517
+ CommanderError,
2518
+ InvalidArgumentError,
2519
+ InvalidOptionArgumentError,
2520
+ Command,
2521
+ Argument,
2522
+ Option,
2523
+ Help
2524
+ } = import_.default;
2525
+
2526
+ // node_modules/uuid/wrapper.mjs
2527
+ var dist = __toESM(require_dist(), 1);
2528
+ var v1 = dist.default.v1;
2529
+ var v1ToV6 = dist.default.v1ToV6;
2530
+ var v3 = dist.default.v3;
2531
+ var v4 = dist.default.v4;
2532
+ var v5 = dist.default.v5;
2533
+ var v6 = dist.default.v6;
2534
+ var v6ToV1 = dist.default.v6ToV1;
2535
+ var v7 = dist.default.v7;
2536
+ var NIL = dist.default.NIL;
2537
+ var MAX = dist.default.MAX;
2538
+ var version = dist.default.version;
2539
+ var validate = dist.default.validate;
2540
+ var stringify = dist.default.stringify;
2541
+ var parse = dist.default.parse;
2542
+
2543
+ // src/services/EdgeTTS.ts
2544
+ import WebSocket from "ws";
2545
+
2546
+ // src/config/constants.ts
2547
+ var Constants = {
2548
+ TRUSTED_CLIENT_TOKEN: "6A5AA1D4EAFF4E9FB37E23D68491D6F4",
2549
+ WSS_URL: "wss://speech.platform.bing.com/consumer/speech/synthesize/readaloud/edge/v1",
2550
+ VOICES_URL: "https://speech.platform.bing.com/consumer/speech/synthesize/readaloud/voices/list"
2551
+ };
2552
+
2553
+ // src/services/EdgeTTS.ts
2554
+ class EdgeTTS {
2555
+ audio_stream = [];
2556
+ audio_format = "mp3";
2557
+ ws;
2558
+ async getVoices() {
2559
+ const response = await fetch(`${Constants.VOICES_URL}?trustedclienttoken=${Constants.TRUSTED_CLIENT_TOKEN}`);
2560
+ const data = await response.json();
2561
+ return data.map((voice) => {
2562
+ delete voice.VoiceTag;
2563
+ delete voice.SuggestedCodec;
2564
+ delete voice.Status;
2565
+ return voice;
2566
+ });
2567
+ }
2568
+ validatePitch(pitch) {
2569
+ if (!/^(-?\d{1,3}Hz)$/.test(pitch)) {
2570
+ throw new Error("Invalid pitch format. Expected format: '-100Hz to 100Hz'.");
2571
+ }
2572
+ return pitch;
2573
+ }
2574
+ validateRate(rate) {
2575
+ if (!/^(-?\d{1,3}%)$/.test(rate)) {
2576
+ throw new Error("Invalid rate format. Expected format: '-100% to 100%'.");
2577
+ }
2578
+ return rate;
2579
+ }
2580
+ validateVolume(volume) {
2581
+ if (!/^(-?\d{1,3}%)$/.test(volume)) {
2582
+ throw new Error("Invalid volume format. Expected format: '-100% to 100%'.");
2583
+ }
2584
+ return volume;
2585
+ }
2586
+ async synthesize(text, voice = "en-US-AnaNeural", options = {}) {
2587
+ return new Promise((resolve, reject) => {
2588
+ const req_id = v4();
2589
+ this.ws = new WebSocket(`${Constants.WSS_URL}?trustedclienttoken=${Constants.TRUSTED_CLIENT_TOKEN}&ConnectionId=${req_id}`);
2590
+ const SSML_text = this.getSSML(text, voice, options);
2591
+ this.ws.on("open", () => {
2592
+ const message = this.buildTTSConfigMessage();
2593
+ this.ws.send(message);
2594
+ const speechMessage = `X-RequestId:${req_id}\r\nContent-Type:application/ssml+xml\r\nX-Timestamp:${new Date().toISOString()}Z\r\nPath:ssml\r\n\r\n${SSML_text}`;
2595
+ this.ws.send(speechMessage);
2596
+ });
2597
+ this.ws.on("message", (data) => {
2598
+ this.processAudioData(data);
2599
+ });
2600
+ this.ws.on("close", () => {
2601
+ resolve();
2602
+ });
2603
+ this.ws.on("error", (err) => {
2604
+ reject(err);
2605
+ });
2606
+ });
2607
+ }
2608
+ getSSML(text, voice, options = {}) {
2609
+ options.pitch = options.pitch.replace("hz", "Hz");
2610
+ const pitch = this.validatePitch(options.pitch || "0Hz");
2611
+ const rate = this.validateRate(options.rate || "0%");
2612
+ const volume = this.validateVolume(options.volume || "0%");
2613
+ return `<speak version='1.0' xml:lang='en-US'><voice name='${voice}'><prosody pitch='${pitch}' rate='${rate}' volume='${volume}'>${text}</prosody></voice></speak>`;
2614
+ }
2615
+ buildTTSConfigMessage() {
2616
+ return `X-Timestamp:${new Date().toISOString()}Z\r\nContent-Type:application/json; charset=utf-8\r\nPath:speech.config\r\n\r\n` + `{"context":{"synthesis":{"audio":{"metadataoptions":{"sentenceBoundaryEnabled":false,"wordBoundaryEnabled":true},"outputFormat":"audio-24khz-48kbitrate-mono-mp3"}}}}`;
2617
+ }
2618
+ processAudioData(data) {
2619
+ if (Buffer.isBuffer(data)) {
2620
+ const needle = Buffer.from("Path:audio\r\n");
2621
+ const uint8Data = new Uint8Array(data);
2622
+ const start_ind = uint8Data.indexOf(needle[0]);
2623
+ if (start_ind !== -1) {
2624
+ const audioData = data.subarray(start_ind + needle.length);
2625
+ this.audio_stream.push(audioData);
2626
+ }
2627
+ if (data.includes("Path:turn.end")) {
2628
+ this.ws.close();
2629
+ }
2630
+ }
2631
+ }
2632
+ async toFile(outputPath) {
2633
+ if (this.audio_stream.length) {
2634
+ const audioBuffer = Buffer.concat(this.audio_stream);
2635
+ const uint8Array = new Uint8Array(audioBuffer);
2636
+ await Bun.write(`${outputPath}.${this.audio_format}`, uint8Array);
2637
+ } else {
2638
+ throw new Error("No audio data available to save.");
2639
+ }
2640
+ }
2641
+ toBase64() {
2642
+ const audioBuffer = Buffer.concat(this.audio_stream);
2643
+ return audioBuffer.toString("base64");
2644
+ }
2645
+ }
2646
+
2647
+ // src/commands/SynthesizeCommand.ts
2648
+ var SynthesizeCommand = new Command("synthesize").description("Edge TTS: synthesize text to audio").option("-t, --text <text>", "Text to convert to audio").option("-v, --voice [voice]", "Voice to use for the audio synthesis", "en-US-AriaNeural").option("-r, --rate [rate]", "Rate of speech", "0%").option("-l, --volume [volume]", "Volume of speech", "0%").option("-p, --pitch [pitch]", "Pitch of speech", "0Hz").option("-o, --output [output]", "Output file name", `output_${Date.now()}`).action(async (options) => {
2649
+ const { text, voice, pitch, rate, volume, output } = options;
2650
+ if (!text) {
2651
+ console.error("Text is required");
2652
+ process.exit(1);
2653
+ }
2654
+ const tts = new EdgeTTS;
2655
+ await tts.synthesize(text, voice, { pitch, rate, volume });
2656
+ await tts.toFile(`${output}`);
2657
+ console.log(`Audio file generated: ${output}.mp3`);
2658
+ });
2659
+
2660
+ // src/commands/VoiceListCommand.ts
2661
+ var VoiceListCommand = new Command("voice-list").description("Get the list of available voices").action(async () => {
2662
+ const tts = new EdgeTTS;
2663
+ const voices = await tts.getVoices();
2664
+ console.log("Lista de voces disponibles:");
2665
+ voices.forEach((voice) => {
2666
+ console.log(` - ${voice.ShortName}`);
2667
+ });
2668
+ });
2669
+
2670
+ // src/cli/edge-tts.ts
2671
+ var program2 = new Command;
2672
+ program2.version("1.1.1").addCommand(SynthesizeCommand).addCommand(VoiceListCommand);
2673
+ try {
2674
+ program2.parse();
2675
+ } catch (error) {
2676
+ console.error(`Error: ${error.message}`);
2677
+ process.exit(1);
2678
+ }