tidewave 0.5.0 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js CHANGED
@@ -29,6 +29,1845 @@ var __export = (target, all) => {
29
29
  var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
30
30
  var __require = /* @__PURE__ */ createRequire(import.meta.url);
31
31
 
32
+ // node_modules/commander/lib/error.js
33
+ var require_error = __commonJS((exports) => {
34
+ class CommanderError extends Error {
35
+ constructor(exitCode, code, message) {
36
+ super(message);
37
+ Error.captureStackTrace(this, this.constructor);
38
+ this.name = this.constructor.name;
39
+ this.code = code;
40
+ this.exitCode = exitCode;
41
+ this.nestedError = undefined;
42
+ }
43
+ }
44
+
45
+ class InvalidArgumentError extends CommanderError {
46
+ constructor(message) {
47
+ super(1, "commander.invalidArgument", message);
48
+ Error.captureStackTrace(this, this.constructor);
49
+ this.name = this.constructor.name;
50
+ }
51
+ }
52
+ exports.CommanderError = CommanderError;
53
+ exports.InvalidArgumentError = InvalidArgumentError;
54
+ });
55
+
56
+ // node_modules/commander/lib/argument.js
57
+ var require_argument = __commonJS((exports) => {
58
+ var { InvalidArgumentError } = require_error();
59
+
60
+ class Argument {
61
+ constructor(name, description) {
62
+ this.description = description || "";
63
+ this.variadic = false;
64
+ this.parseArg = undefined;
65
+ this.defaultValue = undefined;
66
+ this.defaultValueDescription = undefined;
67
+ this.argChoices = undefined;
68
+ switch (name[0]) {
69
+ case "<":
70
+ this.required = true;
71
+ this._name = name.slice(1, -1);
72
+ break;
73
+ case "[":
74
+ this.required = false;
75
+ this._name = name.slice(1, -1);
76
+ break;
77
+ default:
78
+ this.required = true;
79
+ this._name = name;
80
+ break;
81
+ }
82
+ if (this._name.length > 3 && this._name.slice(-3) === "...") {
83
+ this.variadic = true;
84
+ this._name = this._name.slice(0, -3);
85
+ }
86
+ }
87
+ name() {
88
+ return this._name;
89
+ }
90
+ _concatValue(value, previous) {
91
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
92
+ return [value];
93
+ }
94
+ return previous.concat(value);
95
+ }
96
+ default(value, description) {
97
+ this.defaultValue = value;
98
+ this.defaultValueDescription = description;
99
+ return this;
100
+ }
101
+ argParser(fn) {
102
+ this.parseArg = fn;
103
+ return this;
104
+ }
105
+ choices(values) {
106
+ this.argChoices = values.slice();
107
+ this.parseArg = (arg, previous) => {
108
+ if (!this.argChoices.includes(arg)) {
109
+ throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
110
+ }
111
+ if (this.variadic) {
112
+ return this._concatValue(arg, previous);
113
+ }
114
+ return arg;
115
+ };
116
+ return this;
117
+ }
118
+ argRequired() {
119
+ this.required = true;
120
+ return this;
121
+ }
122
+ argOptional() {
123
+ this.required = false;
124
+ return this;
125
+ }
126
+ }
127
+ function humanReadableArgName(arg) {
128
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
129
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
130
+ }
131
+ exports.Argument = Argument;
132
+ exports.humanReadableArgName = humanReadableArgName;
133
+ });
134
+
135
+ // node_modules/commander/lib/help.js
136
+ var require_help = __commonJS((exports) => {
137
+ var { humanReadableArgName } = require_argument();
138
+
139
+ class Help {
140
+ constructor() {
141
+ this.helpWidth = undefined;
142
+ this.sortSubcommands = false;
143
+ this.sortOptions = false;
144
+ this.showGlobalOptions = false;
145
+ }
146
+ visibleCommands(cmd) {
147
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
148
+ const helpCommand = cmd._getHelpCommand();
149
+ if (helpCommand && !helpCommand._hidden) {
150
+ visibleCommands.push(helpCommand);
151
+ }
152
+ if (this.sortSubcommands) {
153
+ visibleCommands.sort((a, b) => {
154
+ return a.name().localeCompare(b.name());
155
+ });
156
+ }
157
+ return visibleCommands;
158
+ }
159
+ compareOptions(a, b) {
160
+ const getSortKey = (option) => {
161
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
162
+ };
163
+ return getSortKey(a).localeCompare(getSortKey(b));
164
+ }
165
+ visibleOptions(cmd) {
166
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
167
+ const helpOption = cmd._getHelpOption();
168
+ if (helpOption && !helpOption.hidden) {
169
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
170
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
171
+ if (!removeShort && !removeLong) {
172
+ visibleOptions.push(helpOption);
173
+ } else if (helpOption.long && !removeLong) {
174
+ visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
175
+ } else if (helpOption.short && !removeShort) {
176
+ visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
177
+ }
178
+ }
179
+ if (this.sortOptions) {
180
+ visibleOptions.sort(this.compareOptions);
181
+ }
182
+ return visibleOptions;
183
+ }
184
+ visibleGlobalOptions(cmd) {
185
+ if (!this.showGlobalOptions)
186
+ return [];
187
+ const globalOptions = [];
188
+ for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
189
+ const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
190
+ globalOptions.push(...visibleOptions);
191
+ }
192
+ if (this.sortOptions) {
193
+ globalOptions.sort(this.compareOptions);
194
+ }
195
+ return globalOptions;
196
+ }
197
+ visibleArguments(cmd) {
198
+ if (cmd._argsDescription) {
199
+ cmd.registeredArguments.forEach((argument) => {
200
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
201
+ });
202
+ }
203
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
204
+ return cmd.registeredArguments;
205
+ }
206
+ return [];
207
+ }
208
+ subcommandTerm(cmd) {
209
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
210
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
211
+ }
212
+ optionTerm(option) {
213
+ return option.flags;
214
+ }
215
+ argumentTerm(argument) {
216
+ return argument.name();
217
+ }
218
+ longestSubcommandTermLength(cmd, helper) {
219
+ return helper.visibleCommands(cmd).reduce((max, command) => {
220
+ return Math.max(max, helper.subcommandTerm(command).length);
221
+ }, 0);
222
+ }
223
+ longestOptionTermLength(cmd, helper) {
224
+ return helper.visibleOptions(cmd).reduce((max, option) => {
225
+ return Math.max(max, helper.optionTerm(option).length);
226
+ }, 0);
227
+ }
228
+ longestGlobalOptionTermLength(cmd, helper) {
229
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
230
+ return Math.max(max, helper.optionTerm(option).length);
231
+ }, 0);
232
+ }
233
+ longestArgumentTermLength(cmd, helper) {
234
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
235
+ return Math.max(max, helper.argumentTerm(argument).length);
236
+ }, 0);
237
+ }
238
+ commandUsage(cmd) {
239
+ let cmdName = cmd._name;
240
+ if (cmd._aliases[0]) {
241
+ cmdName = cmdName + "|" + cmd._aliases[0];
242
+ }
243
+ let ancestorCmdNames = "";
244
+ for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
245
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
246
+ }
247
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
248
+ }
249
+ commandDescription(cmd) {
250
+ return cmd.description();
251
+ }
252
+ subcommandDescription(cmd) {
253
+ return cmd.summary() || cmd.description();
254
+ }
255
+ optionDescription(option) {
256
+ const extraInfo = [];
257
+ if (option.argChoices) {
258
+ extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
259
+ }
260
+ if (option.defaultValue !== undefined) {
261
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
262
+ if (showDefault) {
263
+ extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
264
+ }
265
+ }
266
+ if (option.presetArg !== undefined && option.optional) {
267
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
268
+ }
269
+ if (option.envVar !== undefined) {
270
+ extraInfo.push(`env: ${option.envVar}`);
271
+ }
272
+ if (extraInfo.length > 0) {
273
+ return `${option.description} (${extraInfo.join(", ")})`;
274
+ }
275
+ return option.description;
276
+ }
277
+ argumentDescription(argument) {
278
+ const extraInfo = [];
279
+ if (argument.argChoices) {
280
+ extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
281
+ }
282
+ if (argument.defaultValue !== undefined) {
283
+ extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
284
+ }
285
+ if (extraInfo.length > 0) {
286
+ const extraDescripton = `(${extraInfo.join(", ")})`;
287
+ if (argument.description) {
288
+ return `${argument.description} ${extraDescripton}`;
289
+ }
290
+ return extraDescripton;
291
+ }
292
+ return argument.description;
293
+ }
294
+ formatHelp(cmd, helper) {
295
+ const termWidth = helper.padWidth(cmd, helper);
296
+ const helpWidth = helper.helpWidth || 80;
297
+ const itemIndentWidth = 2;
298
+ const itemSeparatorWidth = 2;
299
+ function formatItem(term, description) {
300
+ if (description) {
301
+ const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;
302
+ return helper.wrap(fullText, helpWidth - itemIndentWidth, termWidth + itemSeparatorWidth);
303
+ }
304
+ return term;
305
+ }
306
+ function formatList(textArray) {
307
+ return textArray.join(`
308
+ `).replace(/^/gm, " ".repeat(itemIndentWidth));
309
+ }
310
+ let output = [`Usage: ${helper.commandUsage(cmd)}`, ""];
311
+ const commandDescription = helper.commandDescription(cmd);
312
+ if (commandDescription.length > 0) {
313
+ output = output.concat([
314
+ helper.wrap(commandDescription, helpWidth, 0),
315
+ ""
316
+ ]);
317
+ }
318
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
319
+ return formatItem(helper.argumentTerm(argument), helper.argumentDescription(argument));
320
+ });
321
+ if (argumentList.length > 0) {
322
+ output = output.concat(["Arguments:", formatList(argumentList), ""]);
323
+ }
324
+ const optionList = helper.visibleOptions(cmd).map((option) => {
325
+ return formatItem(helper.optionTerm(option), helper.optionDescription(option));
326
+ });
327
+ if (optionList.length > 0) {
328
+ output = output.concat(["Options:", formatList(optionList), ""]);
329
+ }
330
+ if (this.showGlobalOptions) {
331
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
332
+ return formatItem(helper.optionTerm(option), helper.optionDescription(option));
333
+ });
334
+ if (globalOptionList.length > 0) {
335
+ output = output.concat([
336
+ "Global Options:",
337
+ formatList(globalOptionList),
338
+ ""
339
+ ]);
340
+ }
341
+ }
342
+ const commandList = helper.visibleCommands(cmd).map((cmd2) => {
343
+ return formatItem(helper.subcommandTerm(cmd2), helper.subcommandDescription(cmd2));
344
+ });
345
+ if (commandList.length > 0) {
346
+ output = output.concat(["Commands:", formatList(commandList), ""]);
347
+ }
348
+ return output.join(`
349
+ `);
350
+ }
351
+ padWidth(cmd, helper) {
352
+ return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
353
+ }
354
+ wrap(str, width, indent, minColumnWidth = 40) {
355
+ const indents = " \\f\\t\\v   -    \uFEFF";
356
+ const manualIndent = new RegExp(`[\\n][${indents}]+`);
357
+ if (str.match(manualIndent))
358
+ return str;
359
+ const columnWidth = width - indent;
360
+ if (columnWidth < minColumnWidth)
361
+ return str;
362
+ const leadingStr = str.slice(0, indent);
363
+ const columnText = str.slice(indent).replace(`\r
364
+ `, `
365
+ `);
366
+ const indentString = " ".repeat(indent);
367
+ const zeroWidthSpace = "​";
368
+ const breaks = `\\s${zeroWidthSpace}`;
369
+ const regex = new RegExp(`
370
+ |.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`, "g");
371
+ const lines = columnText.match(regex) || [];
372
+ return leadingStr + lines.map((line, i) => {
373
+ if (line === `
374
+ `)
375
+ return "";
376
+ return (i > 0 ? indentString : "") + line.trimEnd();
377
+ }).join(`
378
+ `);
379
+ }
380
+ }
381
+ exports.Help = Help;
382
+ });
383
+
384
+ // node_modules/commander/lib/option.js
385
+ var require_option = __commonJS((exports) => {
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
+ function camelcase(str) {
514
+ return str.split("-").reduce((str2, word) => {
515
+ return str2 + word[0].toUpperCase() + word.slice(1);
516
+ });
517
+ }
518
+ function splitOptionFlags(flags) {
519
+ let shortFlag;
520
+ let longFlag;
521
+ const flagParts = flags.split(/[ |,]+/);
522
+ if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1]))
523
+ shortFlag = flagParts.shift();
524
+ longFlag = flagParts.shift();
525
+ if (!shortFlag && /^-[^-]$/.test(longFlag)) {
526
+ shortFlag = longFlag;
527
+ longFlag = undefined;
528
+ }
529
+ return { shortFlag, longFlag };
530
+ }
531
+ exports.Option = Option;
532
+ exports.DualOptions = DualOptions;
533
+ });
534
+
535
+ // node_modules/commander/lib/suggestSimilar.js
536
+ var require_suggestSimilar = __commonJS((exports) => {
537
+ var maxDistance = 3;
538
+ function editDistance(a, b) {
539
+ if (Math.abs(a.length - b.length) > maxDistance)
540
+ return Math.max(a.length, b.length);
541
+ const d = [];
542
+ for (let i = 0;i <= a.length; i++) {
543
+ d[i] = [i];
544
+ }
545
+ for (let j = 0;j <= b.length; j++) {
546
+ d[0][j] = j;
547
+ }
548
+ for (let j = 1;j <= b.length; j++) {
549
+ for (let i = 1;i <= a.length; i++) {
550
+ let cost = 1;
551
+ if (a[i - 1] === b[j - 1]) {
552
+ cost = 0;
553
+ } else {
554
+ cost = 1;
555
+ }
556
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
557
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
558
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
559
+ }
560
+ }
561
+ }
562
+ return d[a.length][b.length];
563
+ }
564
+ function suggestSimilar(word, candidates) {
565
+ if (!candidates || candidates.length === 0)
566
+ return "";
567
+ candidates = Array.from(new Set(candidates));
568
+ const searchingOptions = word.startsWith("--");
569
+ if (searchingOptions) {
570
+ word = word.slice(2);
571
+ candidates = candidates.map((candidate) => candidate.slice(2));
572
+ }
573
+ let similar = [];
574
+ let bestDistance = maxDistance;
575
+ const minSimilarity = 0.4;
576
+ candidates.forEach((candidate) => {
577
+ if (candidate.length <= 1)
578
+ return;
579
+ const distance = editDistance(word, candidate);
580
+ const length = Math.max(word.length, candidate.length);
581
+ const similarity = (length - distance) / length;
582
+ if (similarity > minSimilarity) {
583
+ if (distance < bestDistance) {
584
+ bestDistance = distance;
585
+ similar = [candidate];
586
+ } else if (distance === bestDistance) {
587
+ similar.push(candidate);
588
+ }
589
+ }
590
+ });
591
+ similar.sort((a, b) => a.localeCompare(b));
592
+ if (searchingOptions) {
593
+ similar = similar.map((candidate) => `--${candidate}`);
594
+ }
595
+ if (similar.length > 1) {
596
+ return `
597
+ (Did you mean one of ${similar.join(", ")}?)`;
598
+ }
599
+ if (similar.length === 1) {
600
+ return `
601
+ (Did you mean ${similar[0]}?)`;
602
+ }
603
+ return "";
604
+ }
605
+ exports.suggestSimilar = suggestSimilar;
606
+ });
607
+
608
+ // node_modules/commander/lib/command.js
609
+ var require_command = __commonJS((exports) => {
610
+ var EventEmitter = __require("node:events").EventEmitter;
611
+ var childProcess = __require("node:child_process");
612
+ var path = __require("node:path");
613
+ var fs = __require("node:fs");
614
+ var process2 = __require("node:process");
615
+ var { Argument, humanReadableArgName } = require_argument();
616
+ var { CommanderError } = require_error();
617
+ var { Help } = require_help();
618
+ var { Option, DualOptions } = require_option();
619
+ var { suggestSimilar } = require_suggestSimilar();
620
+
621
+ class Command extends EventEmitter {
622
+ constructor(name) {
623
+ super();
624
+ this.commands = [];
625
+ this.options = [];
626
+ this.parent = null;
627
+ this._allowUnknownOption = false;
628
+ this._allowExcessArguments = true;
629
+ this.registeredArguments = [];
630
+ this._args = this.registeredArguments;
631
+ this.args = [];
632
+ this.rawArgs = [];
633
+ this.processedArgs = [];
634
+ this._scriptPath = null;
635
+ this._name = name || "";
636
+ this._optionValues = {};
637
+ this._optionValueSources = {};
638
+ this._storeOptionsAsProperties = false;
639
+ this._actionHandler = null;
640
+ this._executableHandler = false;
641
+ this._executableFile = null;
642
+ this._executableDir = null;
643
+ this._defaultCommandName = null;
644
+ this._exitCallback = null;
645
+ this._aliases = [];
646
+ this._combineFlagAndOptionalValue = true;
647
+ this._description = "";
648
+ this._summary = "";
649
+ this._argsDescription = undefined;
650
+ this._enablePositionalOptions = false;
651
+ this._passThroughOptions = false;
652
+ this._lifeCycleHooks = {};
653
+ this._showHelpAfterError = false;
654
+ this._showSuggestionAfterError = true;
655
+ this._outputConfiguration = {
656
+ writeOut: (str) => process2.stdout.write(str),
657
+ writeErr: (str) => process2.stderr.write(str),
658
+ getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : undefined,
659
+ getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : undefined,
660
+ outputError: (str, write) => write(str)
661
+ };
662
+ this._hidden = false;
663
+ this._helpOption = undefined;
664
+ this._addImplicitHelpCommand = undefined;
665
+ this._helpCommand = undefined;
666
+ this._helpConfiguration = {};
667
+ }
668
+ copyInheritedSettings(sourceCommand) {
669
+ this._outputConfiguration = sourceCommand._outputConfiguration;
670
+ this._helpOption = sourceCommand._helpOption;
671
+ this._helpCommand = sourceCommand._helpCommand;
672
+ this._helpConfiguration = sourceCommand._helpConfiguration;
673
+ this._exitCallback = sourceCommand._exitCallback;
674
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
675
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
676
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
677
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
678
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
679
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
680
+ return this;
681
+ }
682
+ _getCommandAndAncestors() {
683
+ const result = [];
684
+ for (let command = this;command; command = command.parent) {
685
+ result.push(command);
686
+ }
687
+ return result;
688
+ }
689
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
690
+ let desc = actionOptsOrExecDesc;
691
+ let opts = execOpts;
692
+ if (typeof desc === "object" && desc !== null) {
693
+ opts = desc;
694
+ desc = null;
695
+ }
696
+ opts = opts || {};
697
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
698
+ const cmd = this.createCommand(name);
699
+ if (desc) {
700
+ cmd.description(desc);
701
+ cmd._executableHandler = true;
702
+ }
703
+ if (opts.isDefault)
704
+ this._defaultCommandName = cmd._name;
705
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
706
+ cmd._executableFile = opts.executableFile || null;
707
+ if (args)
708
+ cmd.arguments(args);
709
+ this._registerCommand(cmd);
710
+ cmd.parent = this;
711
+ cmd.copyInheritedSettings(this);
712
+ if (desc)
713
+ return this;
714
+ return cmd;
715
+ }
716
+ createCommand(name) {
717
+ return new Command(name);
718
+ }
719
+ createHelp() {
720
+ return Object.assign(new Help, this.configureHelp());
721
+ }
722
+ configureHelp(configuration) {
723
+ if (configuration === undefined)
724
+ return this._helpConfiguration;
725
+ this._helpConfiguration = configuration;
726
+ return this;
727
+ }
728
+ configureOutput(configuration) {
729
+ if (configuration === undefined)
730
+ return this._outputConfiguration;
731
+ Object.assign(this._outputConfiguration, configuration);
732
+ return this;
733
+ }
734
+ showHelpAfterError(displayHelp = true) {
735
+ if (typeof displayHelp !== "string")
736
+ displayHelp = !!displayHelp;
737
+ this._showHelpAfterError = displayHelp;
738
+ return this;
739
+ }
740
+ showSuggestionAfterError(displaySuggestion = true) {
741
+ this._showSuggestionAfterError = !!displaySuggestion;
742
+ return this;
743
+ }
744
+ addCommand(cmd, opts) {
745
+ if (!cmd._name) {
746
+ throw new Error(`Command passed to .addCommand() must have a name
747
+ - specify the name in Command constructor or using .name()`);
748
+ }
749
+ opts = opts || {};
750
+ if (opts.isDefault)
751
+ this._defaultCommandName = cmd._name;
752
+ if (opts.noHelp || opts.hidden)
753
+ cmd._hidden = true;
754
+ this._registerCommand(cmd);
755
+ cmd.parent = this;
756
+ cmd._checkForBrokenPassThrough();
757
+ return this;
758
+ }
759
+ createArgument(name, description) {
760
+ return new Argument(name, description);
761
+ }
762
+ argument(name, description, fn, defaultValue) {
763
+ const argument = this.createArgument(name, description);
764
+ if (typeof fn === "function") {
765
+ argument.default(defaultValue).argParser(fn);
766
+ } else {
767
+ argument.default(fn);
768
+ }
769
+ this.addArgument(argument);
770
+ return this;
771
+ }
772
+ arguments(names) {
773
+ names.trim().split(/ +/).forEach((detail) => {
774
+ this.argument(detail);
775
+ });
776
+ return this;
777
+ }
778
+ addArgument(argument) {
779
+ const previousArgument = this.registeredArguments.slice(-1)[0];
780
+ if (previousArgument && previousArgument.variadic) {
781
+ throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
782
+ }
783
+ if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {
784
+ throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
785
+ }
786
+ this.registeredArguments.push(argument);
787
+ return this;
788
+ }
789
+ helpCommand(enableOrNameAndArgs, description) {
790
+ if (typeof enableOrNameAndArgs === "boolean") {
791
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
792
+ return this;
793
+ }
794
+ enableOrNameAndArgs = enableOrNameAndArgs ?? "help [command]";
795
+ const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);
796
+ const helpDescription = description ?? "display help for command";
797
+ const helpCommand = this.createCommand(helpName);
798
+ helpCommand.helpOption(false);
799
+ if (helpArgs)
800
+ helpCommand.arguments(helpArgs);
801
+ if (helpDescription)
802
+ helpCommand.description(helpDescription);
803
+ this._addImplicitHelpCommand = true;
804
+ this._helpCommand = helpCommand;
805
+ return this;
806
+ }
807
+ addHelpCommand(helpCommand, deprecatedDescription) {
808
+ if (typeof helpCommand !== "object") {
809
+ this.helpCommand(helpCommand, deprecatedDescription);
810
+ return this;
811
+ }
812
+ this._addImplicitHelpCommand = true;
813
+ this._helpCommand = helpCommand;
814
+ return this;
815
+ }
816
+ _getHelpCommand() {
817
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
818
+ if (hasImplicitHelpCommand) {
819
+ if (this._helpCommand === undefined) {
820
+ this.helpCommand(undefined, undefined);
821
+ }
822
+ return this._helpCommand;
823
+ }
824
+ return null;
825
+ }
826
+ hook(event, listener) {
827
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
828
+ if (!allowedValues.includes(event)) {
829
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
830
+ Expecting one of '${allowedValues.join("', '")}'`);
831
+ }
832
+ if (this._lifeCycleHooks[event]) {
833
+ this._lifeCycleHooks[event].push(listener);
834
+ } else {
835
+ this._lifeCycleHooks[event] = [listener];
836
+ }
837
+ return this;
838
+ }
839
+ exitOverride(fn) {
840
+ if (fn) {
841
+ this._exitCallback = fn;
842
+ } else {
843
+ this._exitCallback = (err) => {
844
+ if (err.code !== "commander.executeSubCommandAsync") {
845
+ throw err;
846
+ } else {}
847
+ };
848
+ }
849
+ return this;
850
+ }
851
+ _exit(exitCode, code, message) {
852
+ if (this._exitCallback) {
853
+ this._exitCallback(new CommanderError(exitCode, code, message));
854
+ }
855
+ process2.exit(exitCode);
856
+ }
857
+ action(fn) {
858
+ const listener = (args) => {
859
+ const expectedArgsCount = this.registeredArguments.length;
860
+ const actionArgs = args.slice(0, expectedArgsCount);
861
+ if (this._storeOptionsAsProperties) {
862
+ actionArgs[expectedArgsCount] = this;
863
+ } else {
864
+ actionArgs[expectedArgsCount] = this.opts();
865
+ }
866
+ actionArgs.push(this);
867
+ return fn.apply(this, actionArgs);
868
+ };
869
+ this._actionHandler = listener;
870
+ return this;
871
+ }
872
+ createOption(flags, description) {
873
+ return new Option(flags, description);
874
+ }
875
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
876
+ try {
877
+ return target.parseArg(value, previous);
878
+ } catch (err) {
879
+ if (err.code === "commander.invalidArgument") {
880
+ const message = `${invalidArgumentMessage} ${err.message}`;
881
+ this.error(message, { exitCode: err.exitCode, code: err.code });
882
+ }
883
+ throw err;
884
+ }
885
+ }
886
+ _registerOption(option) {
887
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
888
+ if (matchingOption) {
889
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
890
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
891
+ - already used by option '${matchingOption.flags}'`);
892
+ }
893
+ this.options.push(option);
894
+ }
895
+ _registerCommand(command) {
896
+ const knownBy = (cmd) => {
897
+ return [cmd.name()].concat(cmd.aliases());
898
+ };
899
+ const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
900
+ if (alreadyUsed) {
901
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
902
+ const newCmd = knownBy(command).join("|");
903
+ throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
904
+ }
905
+ this.commands.push(command);
906
+ }
907
+ addOption(option) {
908
+ this._registerOption(option);
909
+ const oname = option.name();
910
+ const name = option.attributeName();
911
+ if (option.negate) {
912
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
913
+ if (!this._findOption(positiveLongFlag)) {
914
+ this.setOptionValueWithSource(name, option.defaultValue === undefined ? true : option.defaultValue, "default");
915
+ }
916
+ } else if (option.defaultValue !== undefined) {
917
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
918
+ }
919
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
920
+ if (val == null && option.presetArg !== undefined) {
921
+ val = option.presetArg;
922
+ }
923
+ const oldValue = this.getOptionValue(name);
924
+ if (val !== null && option.parseArg) {
925
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
926
+ } else if (val !== null && option.variadic) {
927
+ val = option._concatValue(val, oldValue);
928
+ }
929
+ if (val == null) {
930
+ if (option.negate) {
931
+ val = false;
932
+ } else if (option.isBoolean() || option.optional) {
933
+ val = true;
934
+ } else {
935
+ val = "";
936
+ }
937
+ }
938
+ this.setOptionValueWithSource(name, val, valueSource);
939
+ };
940
+ this.on("option:" + oname, (val) => {
941
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
942
+ handleOptionValue(val, invalidValueMessage, "cli");
943
+ });
944
+ if (option.envVar) {
945
+ this.on("optionEnv:" + oname, (val) => {
946
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
947
+ handleOptionValue(val, invalidValueMessage, "env");
948
+ });
949
+ }
950
+ return this;
951
+ }
952
+ _optionEx(config, flags, description, fn, defaultValue) {
953
+ if (typeof flags === "object" && flags instanceof Option) {
954
+ throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
955
+ }
956
+ const option = this.createOption(flags, description);
957
+ option.makeOptionMandatory(!!config.mandatory);
958
+ if (typeof fn === "function") {
959
+ option.default(defaultValue).argParser(fn);
960
+ } else if (fn instanceof RegExp) {
961
+ const regex = fn;
962
+ fn = (val, def) => {
963
+ const m = regex.exec(val);
964
+ return m ? m[0] : def;
965
+ };
966
+ option.default(defaultValue).argParser(fn);
967
+ } else {
968
+ option.default(fn);
969
+ }
970
+ return this.addOption(option);
971
+ }
972
+ option(flags, description, parseArg, defaultValue) {
973
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
974
+ }
975
+ requiredOption(flags, description, parseArg, defaultValue) {
976
+ return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
977
+ }
978
+ combineFlagAndOptionalValue(combine = true) {
979
+ this._combineFlagAndOptionalValue = !!combine;
980
+ return this;
981
+ }
982
+ allowUnknownOption(allowUnknown = true) {
983
+ this._allowUnknownOption = !!allowUnknown;
984
+ return this;
985
+ }
986
+ allowExcessArguments(allowExcess = true) {
987
+ this._allowExcessArguments = !!allowExcess;
988
+ return this;
989
+ }
990
+ enablePositionalOptions(positional = true) {
991
+ this._enablePositionalOptions = !!positional;
992
+ return this;
993
+ }
994
+ passThroughOptions(passThrough = true) {
995
+ this._passThroughOptions = !!passThrough;
996
+ this._checkForBrokenPassThrough();
997
+ return this;
998
+ }
999
+ _checkForBrokenPassThrough() {
1000
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
1001
+ throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
1002
+ }
1003
+ }
1004
+ storeOptionsAsProperties(storeAsProperties = true) {
1005
+ if (this.options.length) {
1006
+ throw new Error("call .storeOptionsAsProperties() before adding options");
1007
+ }
1008
+ if (Object.keys(this._optionValues).length) {
1009
+ throw new Error("call .storeOptionsAsProperties() before setting option values");
1010
+ }
1011
+ this._storeOptionsAsProperties = !!storeAsProperties;
1012
+ return this;
1013
+ }
1014
+ getOptionValue(key) {
1015
+ if (this._storeOptionsAsProperties) {
1016
+ return this[key];
1017
+ }
1018
+ return this._optionValues[key];
1019
+ }
1020
+ setOptionValue(key, value) {
1021
+ return this.setOptionValueWithSource(key, value, undefined);
1022
+ }
1023
+ setOptionValueWithSource(key, value, source) {
1024
+ if (this._storeOptionsAsProperties) {
1025
+ this[key] = value;
1026
+ } else {
1027
+ this._optionValues[key] = value;
1028
+ }
1029
+ this._optionValueSources[key] = source;
1030
+ return this;
1031
+ }
1032
+ getOptionValueSource(key) {
1033
+ return this._optionValueSources[key];
1034
+ }
1035
+ getOptionValueSourceWithGlobals(key) {
1036
+ let source;
1037
+ this._getCommandAndAncestors().forEach((cmd) => {
1038
+ if (cmd.getOptionValueSource(key) !== undefined) {
1039
+ source = cmd.getOptionValueSource(key);
1040
+ }
1041
+ });
1042
+ return source;
1043
+ }
1044
+ _prepareUserArgs(argv, parseOptions) {
1045
+ if (argv !== undefined && !Array.isArray(argv)) {
1046
+ throw new Error("first parameter to parse must be array or undefined");
1047
+ }
1048
+ parseOptions = parseOptions || {};
1049
+ if (argv === undefined && parseOptions.from === undefined) {
1050
+ if (process2.versions?.electron) {
1051
+ parseOptions.from = "electron";
1052
+ }
1053
+ const execArgv = process2.execArgv ?? [];
1054
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
1055
+ parseOptions.from = "eval";
1056
+ }
1057
+ }
1058
+ if (argv === undefined) {
1059
+ argv = process2.argv;
1060
+ }
1061
+ this.rawArgs = argv.slice();
1062
+ let userArgs;
1063
+ switch (parseOptions.from) {
1064
+ case undefined:
1065
+ case "node":
1066
+ this._scriptPath = argv[1];
1067
+ userArgs = argv.slice(2);
1068
+ break;
1069
+ case "electron":
1070
+ if (process2.defaultApp) {
1071
+ this._scriptPath = argv[1];
1072
+ userArgs = argv.slice(2);
1073
+ } else {
1074
+ userArgs = argv.slice(1);
1075
+ }
1076
+ break;
1077
+ case "user":
1078
+ userArgs = argv.slice(0);
1079
+ break;
1080
+ case "eval":
1081
+ userArgs = argv.slice(1);
1082
+ break;
1083
+ default:
1084
+ throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
1085
+ }
1086
+ if (!this._name && this._scriptPath)
1087
+ this.nameFromFilename(this._scriptPath);
1088
+ this._name = this._name || "program";
1089
+ return userArgs;
1090
+ }
1091
+ parse(argv, parseOptions) {
1092
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1093
+ this._parseCommand([], userArgs);
1094
+ return this;
1095
+ }
1096
+ async parseAsync(argv, parseOptions) {
1097
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1098
+ await this._parseCommand([], userArgs);
1099
+ return this;
1100
+ }
1101
+ _executeSubCommand(subcommand, args) {
1102
+ args = args.slice();
1103
+ let launchWithNode = false;
1104
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
1105
+ function findFile(baseDir, baseName) {
1106
+ const localBin = path.resolve(baseDir, baseName);
1107
+ if (fs.existsSync(localBin))
1108
+ return localBin;
1109
+ if (sourceExt.includes(path.extname(baseName)))
1110
+ return;
1111
+ const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
1112
+ if (foundExt)
1113
+ return `${localBin}${foundExt}`;
1114
+ return;
1115
+ }
1116
+ this._checkForMissingMandatoryOptions();
1117
+ this._checkForConflictingOptions();
1118
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1119
+ let executableDir = this._executableDir || "";
1120
+ if (this._scriptPath) {
1121
+ let resolvedScriptPath;
1122
+ try {
1123
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
1124
+ } catch (err) {
1125
+ resolvedScriptPath = this._scriptPath;
1126
+ }
1127
+ executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
1128
+ }
1129
+ if (executableDir) {
1130
+ let localFile = findFile(executableDir, executableFile);
1131
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1132
+ const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
1133
+ if (legacyName !== this._name) {
1134
+ localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
1135
+ }
1136
+ }
1137
+ executableFile = localFile || executableFile;
1138
+ }
1139
+ launchWithNode = sourceExt.includes(path.extname(executableFile));
1140
+ let proc;
1141
+ if (process2.platform !== "win32") {
1142
+ if (launchWithNode) {
1143
+ args.unshift(executableFile);
1144
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1145
+ proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
1146
+ } else {
1147
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1148
+ }
1149
+ } else {
1150
+ args.unshift(executableFile);
1151
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1152
+ proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
1153
+ }
1154
+ if (!proc.killed) {
1155
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
1156
+ signals.forEach((signal) => {
1157
+ process2.on(signal, () => {
1158
+ if (proc.killed === false && proc.exitCode === null) {
1159
+ proc.kill(signal);
1160
+ }
1161
+ });
1162
+ });
1163
+ }
1164
+ const exitCallback = this._exitCallback;
1165
+ proc.on("close", (code) => {
1166
+ code = code ?? 1;
1167
+ if (!exitCallback) {
1168
+ process2.exit(code);
1169
+ } else {
1170
+ exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
1171
+ }
1172
+ });
1173
+ proc.on("error", (err) => {
1174
+ if (err.code === "ENOENT") {
1175
+ 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";
1176
+ const executableMissing = `'${executableFile}' does not exist
1177
+ - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1178
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1179
+ - ${executableDirMessage}`;
1180
+ throw new Error(executableMissing);
1181
+ } else if (err.code === "EACCES") {
1182
+ throw new Error(`'${executableFile}' not executable`);
1183
+ }
1184
+ if (!exitCallback) {
1185
+ process2.exit(1);
1186
+ } else {
1187
+ const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
1188
+ wrappedError.nestedError = err;
1189
+ exitCallback(wrappedError);
1190
+ }
1191
+ });
1192
+ this.runningCommand = proc;
1193
+ }
1194
+ _dispatchSubcommand(commandName, operands, unknown) {
1195
+ const subCommand = this._findCommand(commandName);
1196
+ if (!subCommand)
1197
+ this.help({ error: true });
1198
+ let promiseChain;
1199
+ promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
1200
+ promiseChain = this._chainOrCall(promiseChain, () => {
1201
+ if (subCommand._executableHandler) {
1202
+ this._executeSubCommand(subCommand, operands.concat(unknown));
1203
+ } else {
1204
+ return subCommand._parseCommand(operands, unknown);
1205
+ }
1206
+ });
1207
+ return promiseChain;
1208
+ }
1209
+ _dispatchHelpCommand(subcommandName) {
1210
+ if (!subcommandName) {
1211
+ this.help();
1212
+ }
1213
+ const subCommand = this._findCommand(subcommandName);
1214
+ if (subCommand && !subCommand._executableHandler) {
1215
+ subCommand.help();
1216
+ }
1217
+ return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
1218
+ }
1219
+ _checkNumberOfArguments() {
1220
+ this.registeredArguments.forEach((arg, i) => {
1221
+ if (arg.required && this.args[i] == null) {
1222
+ this.missingArgument(arg.name());
1223
+ }
1224
+ });
1225
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
1226
+ return;
1227
+ }
1228
+ if (this.args.length > this.registeredArguments.length) {
1229
+ this._excessArguments(this.args);
1230
+ }
1231
+ }
1232
+ _processArguments() {
1233
+ const myParseArg = (argument, value, previous) => {
1234
+ let parsedValue = value;
1235
+ if (value !== null && argument.parseArg) {
1236
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
1237
+ parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
1238
+ }
1239
+ return parsedValue;
1240
+ };
1241
+ this._checkNumberOfArguments();
1242
+ const processedArgs = [];
1243
+ this.registeredArguments.forEach((declaredArg, index) => {
1244
+ let value = declaredArg.defaultValue;
1245
+ if (declaredArg.variadic) {
1246
+ if (index < this.args.length) {
1247
+ value = this.args.slice(index);
1248
+ if (declaredArg.parseArg) {
1249
+ value = value.reduce((processed, v) => {
1250
+ return myParseArg(declaredArg, v, processed);
1251
+ }, declaredArg.defaultValue);
1252
+ }
1253
+ } else if (value === undefined) {
1254
+ value = [];
1255
+ }
1256
+ } else if (index < this.args.length) {
1257
+ value = this.args[index];
1258
+ if (declaredArg.parseArg) {
1259
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
1260
+ }
1261
+ }
1262
+ processedArgs[index] = value;
1263
+ });
1264
+ this.processedArgs = processedArgs;
1265
+ }
1266
+ _chainOrCall(promise, fn) {
1267
+ if (promise && promise.then && typeof promise.then === "function") {
1268
+ return promise.then(() => fn());
1269
+ }
1270
+ return fn();
1271
+ }
1272
+ _chainOrCallHooks(promise, event) {
1273
+ let result = promise;
1274
+ const hooks = [];
1275
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== undefined).forEach((hookedCommand) => {
1276
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
1277
+ hooks.push({ hookedCommand, callback });
1278
+ });
1279
+ });
1280
+ if (event === "postAction") {
1281
+ hooks.reverse();
1282
+ }
1283
+ hooks.forEach((hookDetail) => {
1284
+ result = this._chainOrCall(result, () => {
1285
+ return hookDetail.callback(hookDetail.hookedCommand, this);
1286
+ });
1287
+ });
1288
+ return result;
1289
+ }
1290
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
1291
+ let result = promise;
1292
+ if (this._lifeCycleHooks[event] !== undefined) {
1293
+ this._lifeCycleHooks[event].forEach((hook) => {
1294
+ result = this._chainOrCall(result, () => {
1295
+ return hook(this, subCommand);
1296
+ });
1297
+ });
1298
+ }
1299
+ return result;
1300
+ }
1301
+ _parseCommand(operands, unknown) {
1302
+ const parsed = this.parseOptions(unknown);
1303
+ this._parseOptionsEnv();
1304
+ this._parseOptionsImplied();
1305
+ operands = operands.concat(parsed.operands);
1306
+ unknown = parsed.unknown;
1307
+ this.args = operands.concat(unknown);
1308
+ if (operands && this._findCommand(operands[0])) {
1309
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
1310
+ }
1311
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
1312
+ return this._dispatchHelpCommand(operands[1]);
1313
+ }
1314
+ if (this._defaultCommandName) {
1315
+ this._outputHelpIfRequested(unknown);
1316
+ return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
1317
+ }
1318
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
1319
+ this.help({ error: true });
1320
+ }
1321
+ this._outputHelpIfRequested(parsed.unknown);
1322
+ this._checkForMissingMandatoryOptions();
1323
+ this._checkForConflictingOptions();
1324
+ const checkForUnknownOptions = () => {
1325
+ if (parsed.unknown.length > 0) {
1326
+ this.unknownOption(parsed.unknown[0]);
1327
+ }
1328
+ };
1329
+ const commandEvent = `command:${this.name()}`;
1330
+ if (this._actionHandler) {
1331
+ checkForUnknownOptions();
1332
+ this._processArguments();
1333
+ let promiseChain;
1334
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
1335
+ promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
1336
+ if (this.parent) {
1337
+ promiseChain = this._chainOrCall(promiseChain, () => {
1338
+ this.parent.emit(commandEvent, operands, unknown);
1339
+ });
1340
+ }
1341
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
1342
+ return promiseChain;
1343
+ }
1344
+ if (this.parent && this.parent.listenerCount(commandEvent)) {
1345
+ checkForUnknownOptions();
1346
+ this._processArguments();
1347
+ this.parent.emit(commandEvent, operands, unknown);
1348
+ } else if (operands.length) {
1349
+ if (this._findCommand("*")) {
1350
+ return this._dispatchSubcommand("*", operands, unknown);
1351
+ }
1352
+ if (this.listenerCount("command:*")) {
1353
+ this.emit("command:*", operands, unknown);
1354
+ } else if (this.commands.length) {
1355
+ this.unknownCommand();
1356
+ } else {
1357
+ checkForUnknownOptions();
1358
+ this._processArguments();
1359
+ }
1360
+ } else if (this.commands.length) {
1361
+ checkForUnknownOptions();
1362
+ this.help({ error: true });
1363
+ } else {
1364
+ checkForUnknownOptions();
1365
+ this._processArguments();
1366
+ }
1367
+ }
1368
+ _findCommand(name) {
1369
+ if (!name)
1370
+ return;
1371
+ return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
1372
+ }
1373
+ _findOption(arg) {
1374
+ return this.options.find((option) => option.is(arg));
1375
+ }
1376
+ _checkForMissingMandatoryOptions() {
1377
+ this._getCommandAndAncestors().forEach((cmd) => {
1378
+ cmd.options.forEach((anOption) => {
1379
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === undefined) {
1380
+ cmd.missingMandatoryOptionValue(anOption);
1381
+ }
1382
+ });
1383
+ });
1384
+ }
1385
+ _checkForConflictingLocalOptions() {
1386
+ const definedNonDefaultOptions = this.options.filter((option) => {
1387
+ const optionKey = option.attributeName();
1388
+ if (this.getOptionValue(optionKey) === undefined) {
1389
+ return false;
1390
+ }
1391
+ return this.getOptionValueSource(optionKey) !== "default";
1392
+ });
1393
+ const optionsWithConflicting = definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0);
1394
+ optionsWithConflicting.forEach((option) => {
1395
+ const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
1396
+ if (conflictingAndDefined) {
1397
+ this._conflictingOption(option, conflictingAndDefined);
1398
+ }
1399
+ });
1400
+ }
1401
+ _checkForConflictingOptions() {
1402
+ this._getCommandAndAncestors().forEach((cmd) => {
1403
+ cmd._checkForConflictingLocalOptions();
1404
+ });
1405
+ }
1406
+ parseOptions(argv) {
1407
+ const operands = [];
1408
+ const unknown = [];
1409
+ let dest = operands;
1410
+ const args = argv.slice();
1411
+ function maybeOption(arg) {
1412
+ return arg.length > 1 && arg[0] === "-";
1413
+ }
1414
+ let activeVariadicOption = null;
1415
+ while (args.length) {
1416
+ const arg = args.shift();
1417
+ if (arg === "--") {
1418
+ if (dest === unknown)
1419
+ dest.push(arg);
1420
+ dest.push(...args);
1421
+ break;
1422
+ }
1423
+ if (activeVariadicOption && !maybeOption(arg)) {
1424
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
1425
+ continue;
1426
+ }
1427
+ activeVariadicOption = null;
1428
+ if (maybeOption(arg)) {
1429
+ const option = this._findOption(arg);
1430
+ if (option) {
1431
+ if (option.required) {
1432
+ const value = args.shift();
1433
+ if (value === undefined)
1434
+ this.optionMissingArgument(option);
1435
+ this.emit(`option:${option.name()}`, value);
1436
+ } else if (option.optional) {
1437
+ let value = null;
1438
+ if (args.length > 0 && !maybeOption(args[0])) {
1439
+ value = args.shift();
1440
+ }
1441
+ this.emit(`option:${option.name()}`, value);
1442
+ } else {
1443
+ this.emit(`option:${option.name()}`);
1444
+ }
1445
+ activeVariadicOption = option.variadic ? option : null;
1446
+ continue;
1447
+ }
1448
+ }
1449
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
1450
+ const option = this._findOption(`-${arg[1]}`);
1451
+ if (option) {
1452
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
1453
+ this.emit(`option:${option.name()}`, arg.slice(2));
1454
+ } else {
1455
+ this.emit(`option:${option.name()}`);
1456
+ args.unshift(`-${arg.slice(2)}`);
1457
+ }
1458
+ continue;
1459
+ }
1460
+ }
1461
+ if (/^--[^=]+=/.test(arg)) {
1462
+ const index = arg.indexOf("=");
1463
+ const option = this._findOption(arg.slice(0, index));
1464
+ if (option && (option.required || option.optional)) {
1465
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
1466
+ continue;
1467
+ }
1468
+ }
1469
+ if (maybeOption(arg)) {
1470
+ dest = unknown;
1471
+ }
1472
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
1473
+ if (this._findCommand(arg)) {
1474
+ operands.push(arg);
1475
+ if (args.length > 0)
1476
+ unknown.push(...args);
1477
+ break;
1478
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
1479
+ operands.push(arg);
1480
+ if (args.length > 0)
1481
+ operands.push(...args);
1482
+ break;
1483
+ } else if (this._defaultCommandName) {
1484
+ unknown.push(arg);
1485
+ if (args.length > 0)
1486
+ unknown.push(...args);
1487
+ break;
1488
+ }
1489
+ }
1490
+ if (this._passThroughOptions) {
1491
+ dest.push(arg);
1492
+ if (args.length > 0)
1493
+ dest.push(...args);
1494
+ break;
1495
+ }
1496
+ dest.push(arg);
1497
+ }
1498
+ return { operands, unknown };
1499
+ }
1500
+ opts() {
1501
+ if (this._storeOptionsAsProperties) {
1502
+ const result = {};
1503
+ const len = this.options.length;
1504
+ for (let i = 0;i < len; i++) {
1505
+ const key = this.options[i].attributeName();
1506
+ result[key] = key === this._versionOptionName ? this._version : this[key];
1507
+ }
1508
+ return result;
1509
+ }
1510
+ return this._optionValues;
1511
+ }
1512
+ optsWithGlobals() {
1513
+ return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
1514
+ }
1515
+ error(message, errorOptions) {
1516
+ this._outputConfiguration.outputError(`${message}
1517
+ `, this._outputConfiguration.writeErr);
1518
+ if (typeof this._showHelpAfterError === "string") {
1519
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
1520
+ `);
1521
+ } else if (this._showHelpAfterError) {
1522
+ this._outputConfiguration.writeErr(`
1523
+ `);
1524
+ this.outputHelp({ error: true });
1525
+ }
1526
+ const config = errorOptions || {};
1527
+ const exitCode = config.exitCode || 1;
1528
+ const code = config.code || "commander.error";
1529
+ this._exit(exitCode, code, message);
1530
+ }
1531
+ _parseOptionsEnv() {
1532
+ this.options.forEach((option) => {
1533
+ if (option.envVar && option.envVar in process2.env) {
1534
+ const optionKey = option.attributeName();
1535
+ if (this.getOptionValue(optionKey) === undefined || ["default", "config", "env"].includes(this.getOptionValueSource(optionKey))) {
1536
+ if (option.required || option.optional) {
1537
+ this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
1538
+ } else {
1539
+ this.emit(`optionEnv:${option.name()}`);
1540
+ }
1541
+ }
1542
+ }
1543
+ });
1544
+ }
1545
+ _parseOptionsImplied() {
1546
+ const dualHelper = new DualOptions(this.options);
1547
+ const hasCustomOptionValue = (optionKey) => {
1548
+ return this.getOptionValue(optionKey) !== undefined && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
1549
+ };
1550
+ this.options.filter((option) => option.implied !== undefined && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
1551
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
1552
+ this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
1553
+ });
1554
+ });
1555
+ }
1556
+ missingArgument(name) {
1557
+ const message = `error: missing required argument '${name}'`;
1558
+ this.error(message, { code: "commander.missingArgument" });
1559
+ }
1560
+ optionMissingArgument(option) {
1561
+ const message = `error: option '${option.flags}' argument missing`;
1562
+ this.error(message, { code: "commander.optionMissingArgument" });
1563
+ }
1564
+ missingMandatoryOptionValue(option) {
1565
+ const message = `error: required option '${option.flags}' not specified`;
1566
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
1567
+ }
1568
+ _conflictingOption(option, conflictingOption) {
1569
+ const findBestOptionFromValue = (option2) => {
1570
+ const optionKey = option2.attributeName();
1571
+ const optionValue = this.getOptionValue(optionKey);
1572
+ const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
1573
+ const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
1574
+ if (negativeOption && (negativeOption.presetArg === undefined && optionValue === false || negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)) {
1575
+ return negativeOption;
1576
+ }
1577
+ return positiveOption || option2;
1578
+ };
1579
+ const getErrorMessage = (option2) => {
1580
+ const bestOption = findBestOptionFromValue(option2);
1581
+ const optionKey = bestOption.attributeName();
1582
+ const source = this.getOptionValueSource(optionKey);
1583
+ if (source === "env") {
1584
+ return `environment variable '${bestOption.envVar}'`;
1585
+ }
1586
+ return `option '${bestOption.flags}'`;
1587
+ };
1588
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
1589
+ this.error(message, { code: "commander.conflictingOption" });
1590
+ }
1591
+ unknownOption(flag) {
1592
+ if (this._allowUnknownOption)
1593
+ return;
1594
+ let suggestion = "";
1595
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
1596
+ let candidateFlags = [];
1597
+ let command = this;
1598
+ do {
1599
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
1600
+ candidateFlags = candidateFlags.concat(moreFlags);
1601
+ command = command.parent;
1602
+ } while (command && !command._enablePositionalOptions);
1603
+ suggestion = suggestSimilar(flag, candidateFlags);
1604
+ }
1605
+ const message = `error: unknown option '${flag}'${suggestion}`;
1606
+ this.error(message, { code: "commander.unknownOption" });
1607
+ }
1608
+ _excessArguments(receivedArgs) {
1609
+ if (this._allowExcessArguments)
1610
+ return;
1611
+ const expected = this.registeredArguments.length;
1612
+ const s = expected === 1 ? "" : "s";
1613
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
1614
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
1615
+ this.error(message, { code: "commander.excessArguments" });
1616
+ }
1617
+ unknownCommand() {
1618
+ const unknownName = this.args[0];
1619
+ let suggestion = "";
1620
+ if (this._showSuggestionAfterError) {
1621
+ const candidateNames = [];
1622
+ this.createHelp().visibleCommands(this).forEach((command) => {
1623
+ candidateNames.push(command.name());
1624
+ if (command.alias())
1625
+ candidateNames.push(command.alias());
1626
+ });
1627
+ suggestion = suggestSimilar(unknownName, candidateNames);
1628
+ }
1629
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
1630
+ this.error(message, { code: "commander.unknownCommand" });
1631
+ }
1632
+ version(str, flags, description) {
1633
+ if (str === undefined)
1634
+ return this._version;
1635
+ this._version = str;
1636
+ flags = flags || "-V, --version";
1637
+ description = description || "output the version number";
1638
+ const versionOption = this.createOption(flags, description);
1639
+ this._versionOptionName = versionOption.attributeName();
1640
+ this._registerOption(versionOption);
1641
+ this.on("option:" + versionOption.name(), () => {
1642
+ this._outputConfiguration.writeOut(`${str}
1643
+ `);
1644
+ this._exit(0, "commander.version", str);
1645
+ });
1646
+ return this;
1647
+ }
1648
+ description(str, argsDescription) {
1649
+ if (str === undefined && argsDescription === undefined)
1650
+ return this._description;
1651
+ this._description = str;
1652
+ if (argsDescription) {
1653
+ this._argsDescription = argsDescription;
1654
+ }
1655
+ return this;
1656
+ }
1657
+ summary(str) {
1658
+ if (str === undefined)
1659
+ return this._summary;
1660
+ this._summary = str;
1661
+ return this;
1662
+ }
1663
+ alias(alias) {
1664
+ if (alias === undefined)
1665
+ return this._aliases[0];
1666
+ let command = this;
1667
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
1668
+ command = this.commands[this.commands.length - 1];
1669
+ }
1670
+ if (alias === command._name)
1671
+ throw new Error("Command alias can't be the same as its name");
1672
+ const matchingCommand = this.parent?._findCommand(alias);
1673
+ if (matchingCommand) {
1674
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
1675
+ throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
1676
+ }
1677
+ command._aliases.push(alias);
1678
+ return this;
1679
+ }
1680
+ aliases(aliases) {
1681
+ if (aliases === undefined)
1682
+ return this._aliases;
1683
+ aliases.forEach((alias) => this.alias(alias));
1684
+ return this;
1685
+ }
1686
+ usage(str) {
1687
+ if (str === undefined) {
1688
+ if (this._usage)
1689
+ return this._usage;
1690
+ const args = this.registeredArguments.map((arg) => {
1691
+ return humanReadableArgName(arg);
1692
+ });
1693
+ return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
1694
+ }
1695
+ this._usage = str;
1696
+ return this;
1697
+ }
1698
+ name(str) {
1699
+ if (str === undefined)
1700
+ return this._name;
1701
+ this._name = str;
1702
+ return this;
1703
+ }
1704
+ nameFromFilename(filename) {
1705
+ this._name = path.basename(filename, path.extname(filename));
1706
+ return this;
1707
+ }
1708
+ executableDir(path2) {
1709
+ if (path2 === undefined)
1710
+ return this._executableDir;
1711
+ this._executableDir = path2;
1712
+ return this;
1713
+ }
1714
+ helpInformation(contextOptions) {
1715
+ const helper = this.createHelp();
1716
+ if (helper.helpWidth === undefined) {
1717
+ helper.helpWidth = contextOptions && contextOptions.error ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();
1718
+ }
1719
+ return helper.formatHelp(this, helper);
1720
+ }
1721
+ _getHelpContext(contextOptions) {
1722
+ contextOptions = contextOptions || {};
1723
+ const context = { error: !!contextOptions.error };
1724
+ let write;
1725
+ if (context.error) {
1726
+ write = (arg) => this._outputConfiguration.writeErr(arg);
1727
+ } else {
1728
+ write = (arg) => this._outputConfiguration.writeOut(arg);
1729
+ }
1730
+ context.write = contextOptions.write || write;
1731
+ context.command = this;
1732
+ return context;
1733
+ }
1734
+ outputHelp(contextOptions) {
1735
+ let deprecatedCallback;
1736
+ if (typeof contextOptions === "function") {
1737
+ deprecatedCallback = contextOptions;
1738
+ contextOptions = undefined;
1739
+ }
1740
+ const context = this._getHelpContext(contextOptions);
1741
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", context));
1742
+ this.emit("beforeHelp", context);
1743
+ let helpInformation = this.helpInformation(context);
1744
+ if (deprecatedCallback) {
1745
+ helpInformation = deprecatedCallback(helpInformation);
1746
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
1747
+ throw new Error("outputHelp callback must return a string or a Buffer");
1748
+ }
1749
+ }
1750
+ context.write(helpInformation);
1751
+ if (this._getHelpOption()?.long) {
1752
+ this.emit(this._getHelpOption().long);
1753
+ }
1754
+ this.emit("afterHelp", context);
1755
+ this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", context));
1756
+ }
1757
+ helpOption(flags, description) {
1758
+ if (typeof flags === "boolean") {
1759
+ if (flags) {
1760
+ this._helpOption = this._helpOption ?? undefined;
1761
+ } else {
1762
+ this._helpOption = null;
1763
+ }
1764
+ return this;
1765
+ }
1766
+ flags = flags ?? "-h, --help";
1767
+ description = description ?? "display help for command";
1768
+ this._helpOption = this.createOption(flags, description);
1769
+ return this;
1770
+ }
1771
+ _getHelpOption() {
1772
+ if (this._helpOption === undefined) {
1773
+ this.helpOption(undefined, undefined);
1774
+ }
1775
+ return this._helpOption;
1776
+ }
1777
+ addHelpOption(option) {
1778
+ this._helpOption = option;
1779
+ return this;
1780
+ }
1781
+ help(contextOptions) {
1782
+ this.outputHelp(contextOptions);
1783
+ let exitCode = process2.exitCode || 0;
1784
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
1785
+ exitCode = 1;
1786
+ }
1787
+ this._exit(exitCode, "commander.help", "(outputHelp)");
1788
+ }
1789
+ addHelpText(position, text) {
1790
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
1791
+ if (!allowedValues.includes(position)) {
1792
+ throw new Error(`Unexpected value for position to addHelpText.
1793
+ Expecting one of '${allowedValues.join("', '")}'`);
1794
+ }
1795
+ const helpEvent = `${position}Help`;
1796
+ this.on(helpEvent, (context) => {
1797
+ let helpStr;
1798
+ if (typeof text === "function") {
1799
+ helpStr = text({ error: context.error, command: context.command });
1800
+ } else {
1801
+ helpStr = text;
1802
+ }
1803
+ if (helpStr) {
1804
+ context.write(`${helpStr}
1805
+ `);
1806
+ }
1807
+ });
1808
+ return this;
1809
+ }
1810
+ _outputHelpIfRequested(args) {
1811
+ const helpOption = this._getHelpOption();
1812
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
1813
+ if (helpRequested) {
1814
+ this.outputHelp();
1815
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
1816
+ }
1817
+ }
1818
+ }
1819
+ function incrementNodeInspectorPort(args) {
1820
+ return args.map((arg) => {
1821
+ if (!arg.startsWith("--inspect")) {
1822
+ return arg;
1823
+ }
1824
+ let debugOption;
1825
+ let debugHost = "127.0.0.1";
1826
+ let debugPort = "9229";
1827
+ let match;
1828
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
1829
+ debugOption = match[1];
1830
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
1831
+ debugOption = match[1];
1832
+ if (/^\d+$/.test(match[3])) {
1833
+ debugPort = match[3];
1834
+ } else {
1835
+ debugHost = match[3];
1836
+ }
1837
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
1838
+ debugOption = match[1];
1839
+ debugHost = match[3];
1840
+ debugPort = match[4];
1841
+ }
1842
+ if (debugOption && debugPort !== "0") {
1843
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
1844
+ }
1845
+ return arg;
1846
+ });
1847
+ }
1848
+ exports.Command = Command;
1849
+ });
1850
+
1851
+ // node_modules/commander/index.js
1852
+ var require_commander = __commonJS((exports) => {
1853
+ var { Argument } = require_argument();
1854
+ var { Command } = require_command();
1855
+ var { CommanderError, InvalidArgumentError } = require_error();
1856
+ var { Help } = require_help();
1857
+ var { Option } = require_option();
1858
+ exports.program = new Command;
1859
+ exports.createCommand = (name) => new Command(name);
1860
+ exports.createOption = (flags, description) => new Option(flags, description);
1861
+ exports.createArgument = (name, description) => new Argument(name, description);
1862
+ exports.Command = Command;
1863
+ exports.Option = Option;
1864
+ exports.Argument = Argument;
1865
+ exports.Help = Help;
1866
+ exports.CommanderError = CommanderError;
1867
+ exports.InvalidArgumentError = InvalidArgumentError;
1868
+ exports.InvalidOptionArgumentError = InvalidArgumentError;
1869
+ });
1870
+
32
1871
  // node_modules/zod/v3/helpers/util.js
33
1872
  var util, objectUtil, ZodParsedType, getParsedType = (data) => {
34
1873
  const t = typeof data;
@@ -4105,6 +5944,8 @@ Defaults to 30000 (30 seconds).`),
4105
5944
  });
4106
5945
 
4107
5946
  // src/core.ts
5947
+ import path from "path";
5948
+ import fs from "fs/promises";
4108
5949
  function isResolveError(result) {
4109
5950
  return result != null && "success" in result && result.success === false;
4110
5951
  }
@@ -4129,10 +5970,25 @@ function createExtractError(code, message, details) {
4129
5970
  }
4130
5971
  };
4131
5972
  }
5973
+ async function getProjectName(defaultName = "app") {
5974
+ if (typeof process === "undefined" || !process.cwd) {
5975
+ return defaultName;
5976
+ }
5977
+ const rootDir = process.cwd();
5978
+ const packageJsonPath = path.join(rootDir, "package.json");
5979
+ try {
5980
+ const packageJson = await fs.readFile(packageJsonPath, "utf8");
5981
+ const { name } = JSON.parse(packageJson);
5982
+ return name || defaultName;
5983
+ } catch {
5984
+ return defaultName;
5985
+ }
5986
+ }
5987
+ var init_core = () => {};
4132
5988
 
4133
5989
  // src/resolution/module-resolver.ts
4134
5990
  import ts from "typescript";
4135
- import path from "node:path";
5991
+ import path2 from "node:path";
4136
5992
  function loadTsConfig(prefix) {
4137
5993
  const projectPath = prefix || process.cwd();
4138
5994
  const configPath = ts.findConfigFile(projectPath, ts.sys.fileExists, "tsconfig.json");
@@ -4152,7 +6008,7 @@ function loadTsConfig(prefix) {
4152
6008
  if (configPath) {
4153
6009
  const configFile = ts.readConfigFile(configPath, ts.sys.readFile);
4154
6010
  if (configFile.config) {
4155
- const parsedConfig = ts.parseJsonConfigFileContent(configFile.config, ts.sys, path.dirname(configPath));
6011
+ const parsedConfig = ts.parseJsonConfigFileContent(configFile.config, ts.sys, path2.dirname(configPath));
4156
6012
  compilerOptions = { ...compilerOptions, ...parsedConfig.options };
4157
6013
  rootNames = parsedConfig.fileNames;
4158
6014
  }
@@ -4164,7 +6020,7 @@ function loadTsConfig(prefix) {
4164
6020
  }
4165
6021
  function resolveModule(moduleName, compilerOptions) {
4166
6022
  if (moduleName.startsWith("./") || moduleName.startsWith("../") || moduleName.includes(".") && !moduleName.includes("/")) {
4167
- const absolutePath = path.resolve(moduleName);
6023
+ const absolutePath = path2.resolve(moduleName);
4168
6024
  if (ts.sys.fileExists(absolutePath)) {
4169
6025
  const dedicatedProgram = ts.createProgram([absolutePath], compilerOptions);
4170
6026
  const sourceFile = dedicatedProgram.getSourceFile(absolutePath);
@@ -4173,7 +6029,7 @@ function resolveModule(moduleName, compilerOptions) {
4173
6029
  }
4174
6030
  }
4175
6031
  }
4176
- const moduleResolver = ts.resolveModuleName(moduleName, path.resolve("./index.ts"), compilerOptions, ts.sys);
6032
+ const moduleResolver = ts.resolveModuleName(moduleName, path2.resolve("./index.ts"), compilerOptions, ts.sys);
4177
6033
  if (moduleResolver.resolvedModule) {
4178
6034
  const { resolvedFileName } = moduleResolver.resolvedModule;
4179
6035
  const dedicatedProgram = ts.createProgram([resolvedFileName], compilerOptions);
@@ -4233,11 +6089,13 @@ function resolveNodeBuiltin(moduleName, compilerOptions) {
4233
6089
  }
4234
6090
  return resolveError(moduleName, process.cwd());
4235
6091
  }
4236
- var init_module_resolver = () => {};
6092
+ var init_module_resolver = __esm(() => {
6093
+ init_core();
6094
+ });
4237
6095
 
4238
6096
  // src/resolution/utils.ts
4239
6097
  import ts2 from "typescript";
4240
- import path2 from "node:path";
6098
+ import path3 from "node:path";
4241
6099
  function getLocation(symbol) {
4242
6100
  if (symbol.valueDeclaration) {
4243
6101
  const sourceFile = symbol.valueDeclaration.getSourceFile();
@@ -4245,7 +6103,7 @@ function getLocation(symbol) {
4245
6103
  let { fileName } = sourceFile;
4246
6104
  const cwd = process.cwd();
4247
6105
  if (fileName.startsWith(cwd)) {
4248
- fileName = path2.relative(cwd, fileName);
6106
+ fileName = path3.relative(cwd, fileName);
4249
6107
  }
4250
6108
  return `${fileName}:${line + 1}:${character + 1}`;
4251
6109
  }
@@ -4258,7 +6116,7 @@ function getLocation(symbol) {
4258
6116
  let fileName = sourceFile?.fileName;
4259
6117
  const cwd = process.cwd();
4260
6118
  if (fileName?.startsWith(cwd)) {
4261
- fileName = path2.relative(cwd, fileName);
6119
+ fileName = path3.relative(cwd, fileName);
4262
6120
  }
4263
6121
  return `${fileName}:${line + 1}:${character + 1}`;
4264
6122
  }
@@ -4605,13 +6463,14 @@ function getSymbolInfo(checker, symbol, member, isStatic) {
4605
6463
  };
4606
6464
  }
4607
6465
  var init_symbol_finder = __esm(() => {
6466
+ init_core();
4608
6467
  init_utils();
4609
6468
  init_formatters();
4610
6469
  });
4611
6470
 
4612
6471
  // src/resolution/index.ts
4613
6472
  import ts5 from "typescript";
4614
- import path3 from "node:path";
6473
+ import path4 from "node:path";
4615
6474
  function parseModulePath(modulePath) {
4616
6475
  let module;
4617
6476
  let symbolPath;
@@ -4664,8 +6523,8 @@ async function extractDocs(modulePath) {
4664
6523
  if (isResolveError(resolvedModule)) {
4665
6524
  return createExtractError("MODULE_NOT_FOUND", `Module '${module}' not found`);
4666
6525
  }
4667
- const { sourceFile, program } = resolvedModule;
4668
- const checker = program.getTypeChecker();
6526
+ const { sourceFile, program: program2 } = resolvedModule;
6527
+ const checker = program2.getTypeChecker();
4669
6528
  let targetSymbol;
4670
6529
  if (isGlobalModule) {
4671
6530
  const actualSymbolName = module.startsWith("node:") ? module.slice(5) : module;
@@ -4748,8 +6607,8 @@ async function getSourceLocation(reference) {
4748
6607
  }
4749
6608
  };
4750
6609
  }
4751
- const { sourceFile, program } = resolvedModule;
4752
- const checker = program.getTypeChecker();
6610
+ const { sourceFile, program: program2 } = resolvedModule;
6611
+ const checker = program2.getTypeChecker();
4753
6612
  let targetSymbol;
4754
6613
  if (isGlobalModule) {
4755
6614
  const actualSymbolName = module.startsWith("node:") ? module.slice(5) : module;
@@ -4816,12 +6675,12 @@ async function getSourceLocation(reference) {
4816
6675
  }
4817
6676
  const moduleName = reference;
4818
6677
  if (moduleName.startsWith("./") || moduleName.startsWith("../")) {
4819
- const absolutePath = path3.resolve(moduleName);
6678
+ const absolutePath = path4.resolve(moduleName);
4820
6679
  if (ts5.sys.fileExists(absolutePath)) {
4821
6680
  const cwd = process.cwd();
4822
6681
  let finalPath;
4823
6682
  if (absolutePath.startsWith(cwd)) {
4824
- const relativePath = path3.relative(cwd, absolutePath);
6683
+ const relativePath = path4.relative(cwd, absolutePath);
4825
6684
  finalPath = relativePath.startsWith("..") ? absolutePath : relativePath;
4826
6685
  } else {
4827
6686
  finalPath = absolutePath;
@@ -4830,13 +6689,13 @@ async function getSourceLocation(reference) {
4830
6689
  }
4831
6690
  }
4832
6691
  const config = loadTsConfig(options.prefix);
4833
- const moduleResolver = ts5.resolveModuleName(moduleName, path3.resolve("./index.ts"), config.options, ts5.sys);
6692
+ const moduleResolver = ts5.resolveModuleName(moduleName, path4.resolve("./index.ts"), config.options, ts5.sys);
4834
6693
  if (moduleResolver.resolvedModule) {
4835
6694
  const { resolvedFileName } = moduleResolver.resolvedModule;
4836
6695
  const cwd = process.cwd();
4837
6696
  let finalPath;
4838
6697
  if (resolvedFileName.startsWith(cwd)) {
4839
- const relativePath = path3.relative(cwd, resolvedFileName);
6698
+ const relativePath = path4.relative(cwd, resolvedFileName);
4840
6699
  finalPath = relativePath.startsWith("..") ? resolvedFileName : relativePath;
4841
6700
  } else {
4842
6701
  finalPath = resolvedFileName;
@@ -4846,6 +6705,7 @@ async function getSourceLocation(reference) {
4846
6705
  return resolveError(moduleName, process.cwd());
4847
6706
  }
4848
6707
  var init_resolution = __esm(() => {
6708
+ init_core();
4849
6709
  init_module_resolver();
4850
6710
  init_symbol_finder();
4851
6711
  init_formatters();
@@ -4924,7 +6784,7 @@ var init_src = __esm(() => {
4924
6784
  });
4925
6785
 
4926
6786
  // package.json
4927
- var name = "tidewave", version = "0.5.0", package_default;
6787
+ var name = "tidewave", version = "0.5.2", package_default;
4928
6788
  var init_package = __esm(() => {
4929
6789
  package_default = {
4930
6790
  name,
@@ -4982,7 +6842,7 @@ var init_package = __esm(() => {
4982
6842
  ],
4983
6843
  scripts: {
4984
6844
  dist: "bun run clean && bun run build:js && bun run build:types",
4985
- "build:js": "bun build --outdir dist --root src --external commander --external chalk --external typescript --external child_process --external module --external @opentelemetry/api --external @opentelemetry/api-logs --external @opentelemetry/core --external @opentelemetry/resources --external @opentelemetry/sdk-logs --external @opentelemetry/sdk-trace-base --external @opentelemetry/sdk-trace-node --external @opentelemetry/semantic-conventions src/next-js/handler.ts src/next-js/instrumentation.ts src/vite-plugin.ts src/evaluation/eval_worker.ts src/cli/index.ts --target node",
6845
+ "build:js": "bun build --outdir dist --root src --external typescript --external child_process --external module --external @opentelemetry/api --external @opentelemetry/sdk-logs --external @opentelemetry/sdk-trace-base src/next-js/handler.ts src/next-js/instrumentation.ts src/vite-plugin.ts src/evaluation/eval_worker.ts src/cli/index.ts --target node",
4986
6846
  "build:types": "tsc -p tsconfig.declarations.json",
4987
6847
  dev: "bun run src/cli/index.ts",
4988
6848
  test: "bun test",
@@ -4995,23 +6855,16 @@ var init_package = __esm(() => {
4995
6855
  },
4996
6856
  dependencies: {
4997
6857
  "@modelcontextprotocol/sdk": "^1.17.4",
4998
- "@opentelemetry/api": "^1.9.0",
4999
- "@opentelemetry/api-logs": "^0.206.0",
5000
- "@opentelemetry/core": "^2.1.0",
5001
- "@opentelemetry/resources": "^2.1.0",
5002
- "@opentelemetry/sdk-logs": "^0.206.0",
5003
- "@opentelemetry/sdk-trace-base": "^2.1.0",
5004
- "@opentelemetry/sdk-trace-node": "^2.1.0",
5005
- "@opentelemetry/semantic-conventions": "^1.37.0",
5006
6858
  "body-parser": "^2.2.0",
5007
- chalk: "^5.3.0",
5008
- commander: "^12.1.0",
5009
6859
  connect: "^3.7.0",
5010
6860
  typescript: "^5",
5011
6861
  zod: "3.25.76"
5012
6862
  },
5013
6863
  devDependencies: {
5014
6864
  "@eslint/js": "^9.16.0",
6865
+ "@opentelemetry/api": "^1.9.0",
6866
+ "@opentelemetry/sdk-logs": "^0.206.0",
6867
+ "@opentelemetry/sdk-trace-base": "^2.1.0",
5015
6868
  "@types/body-parser": "^1.19.6",
5016
6869
  "@types/bun": "latest",
5017
6870
  "@types/connect": "^3.4.38",
@@ -5021,6 +6874,8 @@ var init_package = __esm(() => {
5021
6874
  "@vercel/otel": "^2.0.1",
5022
6875
  "@vitest/ui": "^3.2.4",
5023
6876
  "bun-types": "latest",
6877
+ chalk: "^5.3.0",
6878
+ commander: "^12.1.0",
5024
6879
  eslint: "^9.16.0",
5025
6880
  globals: "^15.14.0",
5026
6881
  next: "^15.5.3",
@@ -6736,8 +8591,8 @@ var require_uri_all = __commonJS((exports, module) => {
6736
8591
  wsComponents.secure = undefined;
6737
8592
  }
6738
8593
  if (wsComponents.resourceName) {
6739
- var _wsComponents$resourc = wsComponents.resourceName.split("?"), _wsComponents$resourc2 = slicedToArray(_wsComponents$resourc, 2), path4 = _wsComponents$resourc2[0], query = _wsComponents$resourc2[1];
6740
- wsComponents.path = path4 && path4 !== "/" ? path4 : undefined;
8594
+ var _wsComponents$resourc = wsComponents.resourceName.split("?"), _wsComponents$resourc2 = slicedToArray(_wsComponents$resourc, 2), path5 = _wsComponents$resourc2[0], query = _wsComponents$resourc2[1];
8595
+ wsComponents.path = path5 && path5 !== "/" ? path5 : undefined;
6741
8596
  wsComponents.query = query;
6742
8597
  wsComponents.resourceName = undefined;
6743
8598
  }
@@ -7130,12 +8985,12 @@ var require_util = __commonJS((exports, module) => {
7130
8985
  return "'" + escapeQuotes(str) + "'";
7131
8986
  }
7132
8987
  function getPathExpr(currentPath, expr, jsonPointers, isNumber) {
7133
- var path4 = jsonPointers ? "'/' + " + expr + (isNumber ? "" : ".replace(/~/g, '~0').replace(/\\//g, '~1')") : isNumber ? "'[' + " + expr + " + ']'" : "'[\\'' + " + expr + " + '\\']'";
7134
- return joinPaths(currentPath, path4);
8988
+ var path5 = jsonPointers ? "'/' + " + expr + (isNumber ? "" : ".replace(/~/g, '~0').replace(/\\//g, '~1')") : isNumber ? "'[' + " + expr + " + ']'" : "'[\\'' + " + expr + " + '\\']'";
8989
+ return joinPaths(currentPath, path5);
7135
8990
  }
7136
8991
  function getPath(currentPath, prop, jsonPointers) {
7137
- var path4 = jsonPointers ? toQuotedString("/" + escapeJsonPointer(prop)) : toQuotedString(getProperty(prop));
7138
- return joinPaths(currentPath, path4);
8992
+ var path5 = jsonPointers ? toQuotedString("/" + escapeJsonPointer(prop)) : toQuotedString(getProperty(prop));
8993
+ return joinPaths(currentPath, path5);
7139
8994
  }
7140
8995
  var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
7141
8996
  var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
@@ -14448,9 +16303,9 @@ async function handleGetSourcePath({ reference }) {
14448
16303
  isError: true
14449
16304
  };
14450
16305
  }
14451
- const { path: path4, format } = sourceResult;
16306
+ const { path: path5, format } = sourceResult;
14452
16307
  return {
14453
- content: [{ type: "text", text: `${path4}(${format})` }],
16308
+ content: [{ type: "text", text: `${path5}(${format})` }],
14454
16309
  isError: false
14455
16310
  };
14456
16311
  }
@@ -14510,6 +16365,7 @@ var init_mcp2 = __esm(() => {
14510
16365
  init_mcp();
14511
16366
  init_tools();
14512
16367
  init_package();
16368
+ init_core();
14513
16369
  init_src();
14514
16370
  init_circular_buffer();
14515
16371
  ({
@@ -14520,15 +16376,519 @@ var init_mcp2 = __esm(() => {
14520
16376
  } = tools);
14521
16377
  });
14522
16378
 
16379
+ // node_modules/commander/esm.mjs
16380
+ var import__ = __toESM(require_commander(), 1);
16381
+ var {
16382
+ program,
16383
+ createCommand,
16384
+ createArgument,
16385
+ createOption,
16386
+ CommanderError,
16387
+ InvalidArgumentError,
16388
+ InvalidOptionArgumentError,
16389
+ Command,
16390
+ Argument,
16391
+ Option,
16392
+ Help
16393
+ } = import__.default;
16394
+
16395
+ // node_modules/chalk/source/vendor/ansi-styles/index.js
16396
+ var ANSI_BACKGROUND_OFFSET = 10;
16397
+ var wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`;
16398
+ var wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`;
16399
+ var wrapAnsi16m = (offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`;
16400
+ var styles = {
16401
+ modifier: {
16402
+ reset: [0, 0],
16403
+ bold: [1, 22],
16404
+ dim: [2, 22],
16405
+ italic: [3, 23],
16406
+ underline: [4, 24],
16407
+ overline: [53, 55],
16408
+ inverse: [7, 27],
16409
+ hidden: [8, 28],
16410
+ strikethrough: [9, 29]
16411
+ },
16412
+ color: {
16413
+ black: [30, 39],
16414
+ red: [31, 39],
16415
+ green: [32, 39],
16416
+ yellow: [33, 39],
16417
+ blue: [34, 39],
16418
+ magenta: [35, 39],
16419
+ cyan: [36, 39],
16420
+ white: [37, 39],
16421
+ blackBright: [90, 39],
16422
+ gray: [90, 39],
16423
+ grey: [90, 39],
16424
+ redBright: [91, 39],
16425
+ greenBright: [92, 39],
16426
+ yellowBright: [93, 39],
16427
+ blueBright: [94, 39],
16428
+ magentaBright: [95, 39],
16429
+ cyanBright: [96, 39],
16430
+ whiteBright: [97, 39]
16431
+ },
16432
+ bgColor: {
16433
+ bgBlack: [40, 49],
16434
+ bgRed: [41, 49],
16435
+ bgGreen: [42, 49],
16436
+ bgYellow: [43, 49],
16437
+ bgBlue: [44, 49],
16438
+ bgMagenta: [45, 49],
16439
+ bgCyan: [46, 49],
16440
+ bgWhite: [47, 49],
16441
+ bgBlackBright: [100, 49],
16442
+ bgGray: [100, 49],
16443
+ bgGrey: [100, 49],
16444
+ bgRedBright: [101, 49],
16445
+ bgGreenBright: [102, 49],
16446
+ bgYellowBright: [103, 49],
16447
+ bgBlueBright: [104, 49],
16448
+ bgMagentaBright: [105, 49],
16449
+ bgCyanBright: [106, 49],
16450
+ bgWhiteBright: [107, 49]
16451
+ }
16452
+ };
16453
+ var modifierNames = Object.keys(styles.modifier);
16454
+ var foregroundColorNames = Object.keys(styles.color);
16455
+ var backgroundColorNames = Object.keys(styles.bgColor);
16456
+ var colorNames = [...foregroundColorNames, ...backgroundColorNames];
16457
+ function assembleStyles() {
16458
+ const codes = new Map;
16459
+ for (const [groupName, group] of Object.entries(styles)) {
16460
+ for (const [styleName, style] of Object.entries(group)) {
16461
+ styles[styleName] = {
16462
+ open: `\x1B[${style[0]}m`,
16463
+ close: `\x1B[${style[1]}m`
16464
+ };
16465
+ group[styleName] = styles[styleName];
16466
+ codes.set(style[0], style[1]);
16467
+ }
16468
+ Object.defineProperty(styles, groupName, {
16469
+ value: group,
16470
+ enumerable: false
16471
+ });
16472
+ }
16473
+ Object.defineProperty(styles, "codes", {
16474
+ value: codes,
16475
+ enumerable: false
16476
+ });
16477
+ styles.color.close = "\x1B[39m";
16478
+ styles.bgColor.close = "\x1B[49m";
16479
+ styles.color.ansi = wrapAnsi16();
16480
+ styles.color.ansi256 = wrapAnsi256();
16481
+ styles.color.ansi16m = wrapAnsi16m();
16482
+ styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
16483
+ styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
16484
+ styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
16485
+ Object.defineProperties(styles, {
16486
+ rgbToAnsi256: {
16487
+ value(red, green, blue) {
16488
+ if (red === green && green === blue) {
16489
+ if (red < 8) {
16490
+ return 16;
16491
+ }
16492
+ if (red > 248) {
16493
+ return 231;
16494
+ }
16495
+ return Math.round((red - 8) / 247 * 24) + 232;
16496
+ }
16497
+ return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
16498
+ },
16499
+ enumerable: false
16500
+ },
16501
+ hexToRgb: {
16502
+ value(hex) {
16503
+ const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
16504
+ if (!matches) {
16505
+ return [0, 0, 0];
16506
+ }
16507
+ let [colorString] = matches;
16508
+ if (colorString.length === 3) {
16509
+ colorString = [...colorString].map((character) => character + character).join("");
16510
+ }
16511
+ const integer = Number.parseInt(colorString, 16);
16512
+ return [
16513
+ integer >> 16 & 255,
16514
+ integer >> 8 & 255,
16515
+ integer & 255
16516
+ ];
16517
+ },
16518
+ enumerable: false
16519
+ },
16520
+ hexToAnsi256: {
16521
+ value: (hex) => styles.rgbToAnsi256(...styles.hexToRgb(hex)),
16522
+ enumerable: false
16523
+ },
16524
+ ansi256ToAnsi: {
16525
+ value(code) {
16526
+ if (code < 8) {
16527
+ return 30 + code;
16528
+ }
16529
+ if (code < 16) {
16530
+ return 90 + (code - 8);
16531
+ }
16532
+ let red;
16533
+ let green;
16534
+ let blue;
16535
+ if (code >= 232) {
16536
+ red = ((code - 232) * 10 + 8) / 255;
16537
+ green = red;
16538
+ blue = red;
16539
+ } else {
16540
+ code -= 16;
16541
+ const remainder = code % 36;
16542
+ red = Math.floor(code / 36) / 5;
16543
+ green = Math.floor(remainder / 6) / 5;
16544
+ blue = remainder % 6 / 5;
16545
+ }
16546
+ const value = Math.max(red, green, blue) * 2;
16547
+ if (value === 0) {
16548
+ return 30;
16549
+ }
16550
+ let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
16551
+ if (value === 2) {
16552
+ result += 60;
16553
+ }
16554
+ return result;
16555
+ },
16556
+ enumerable: false
16557
+ },
16558
+ rgbToAnsi: {
16559
+ value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),
16560
+ enumerable: false
16561
+ },
16562
+ hexToAnsi: {
16563
+ value: (hex) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),
16564
+ enumerable: false
16565
+ }
16566
+ });
16567
+ return styles;
16568
+ }
16569
+ var ansiStyles = assembleStyles();
16570
+ var ansi_styles_default = ansiStyles;
16571
+
16572
+ // node_modules/chalk/source/vendor/supports-color/index.js
16573
+ import process2 from "node:process";
16574
+ import os from "node:os";
16575
+ import tty from "node:tty";
16576
+ function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process2.argv) {
16577
+ const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
16578
+ const position = argv.indexOf(prefix + flag);
16579
+ const terminatorPosition = argv.indexOf("--");
16580
+ return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
16581
+ }
16582
+ var { env } = process2;
16583
+ var flagForceColor;
16584
+ if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
16585
+ flagForceColor = 0;
16586
+ } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
16587
+ flagForceColor = 1;
16588
+ }
16589
+ function envForceColor() {
16590
+ if ("FORCE_COLOR" in env) {
16591
+ if (env.FORCE_COLOR === "true") {
16592
+ return 1;
16593
+ }
16594
+ if (env.FORCE_COLOR === "false") {
16595
+ return 0;
16596
+ }
16597
+ return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
16598
+ }
16599
+ }
16600
+ function translateLevel(level) {
16601
+ if (level === 0) {
16602
+ return false;
16603
+ }
16604
+ return {
16605
+ level,
16606
+ hasBasic: true,
16607
+ has256: level >= 2,
16608
+ has16m: level >= 3
16609
+ };
16610
+ }
16611
+ function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
16612
+ const noFlagForceColor = envForceColor();
16613
+ if (noFlagForceColor !== undefined) {
16614
+ flagForceColor = noFlagForceColor;
16615
+ }
16616
+ const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
16617
+ if (forceColor === 0) {
16618
+ return 0;
16619
+ }
16620
+ if (sniffFlags) {
16621
+ if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
16622
+ return 3;
16623
+ }
16624
+ if (hasFlag("color=256")) {
16625
+ return 2;
16626
+ }
16627
+ }
16628
+ if ("TF_BUILD" in env && "AGENT_NAME" in env) {
16629
+ return 1;
16630
+ }
16631
+ if (haveStream && !streamIsTTY && forceColor === undefined) {
16632
+ return 0;
16633
+ }
16634
+ const min = forceColor || 0;
16635
+ if (env.TERM === "dumb") {
16636
+ return min;
16637
+ }
16638
+ if (process2.platform === "win32") {
16639
+ const osRelease = os.release().split(".");
16640
+ if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
16641
+ return Number(osRelease[2]) >= 14931 ? 3 : 2;
16642
+ }
16643
+ return 1;
16644
+ }
16645
+ if ("CI" in env) {
16646
+ if (["GITHUB_ACTIONS", "GITEA_ACTIONS", "CIRCLECI"].some((key) => (key in env))) {
16647
+ return 3;
16648
+ }
16649
+ if (["TRAVIS", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => (sign in env)) || env.CI_NAME === "codeship") {
16650
+ return 1;
16651
+ }
16652
+ return min;
16653
+ }
16654
+ if ("TEAMCITY_VERSION" in env) {
16655
+ return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
16656
+ }
16657
+ if (env.COLORTERM === "truecolor") {
16658
+ return 3;
16659
+ }
16660
+ if (env.TERM === "xterm-kitty") {
16661
+ return 3;
16662
+ }
16663
+ if (env.TERM === "xterm-ghostty") {
16664
+ return 3;
16665
+ }
16666
+ if (env.TERM === "wezterm") {
16667
+ return 3;
16668
+ }
16669
+ if ("TERM_PROGRAM" in env) {
16670
+ const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
16671
+ switch (env.TERM_PROGRAM) {
16672
+ case "iTerm.app": {
16673
+ return version >= 3 ? 3 : 2;
16674
+ }
16675
+ case "Apple_Terminal": {
16676
+ return 2;
16677
+ }
16678
+ }
16679
+ }
16680
+ if (/-256(color)?$/i.test(env.TERM)) {
16681
+ return 2;
16682
+ }
16683
+ if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
16684
+ return 1;
16685
+ }
16686
+ if ("COLORTERM" in env) {
16687
+ return 1;
16688
+ }
16689
+ return min;
16690
+ }
16691
+ function createSupportsColor(stream, options = {}) {
16692
+ const level = _supportsColor(stream, {
16693
+ streamIsTTY: stream && stream.isTTY,
16694
+ ...options
16695
+ });
16696
+ return translateLevel(level);
16697
+ }
16698
+ var supportsColor = {
16699
+ stdout: createSupportsColor({ isTTY: tty.isatty(1) }),
16700
+ stderr: createSupportsColor({ isTTY: tty.isatty(2) })
16701
+ };
16702
+ var supports_color_default = supportsColor;
16703
+
16704
+ // node_modules/chalk/source/utilities.js
16705
+ function stringReplaceAll(string, substring, replacer) {
16706
+ let index = string.indexOf(substring);
16707
+ if (index === -1) {
16708
+ return string;
16709
+ }
16710
+ const substringLength = substring.length;
16711
+ let endIndex = 0;
16712
+ let returnValue = "";
16713
+ do {
16714
+ returnValue += string.slice(endIndex, index) + substring + replacer;
16715
+ endIndex = index + substringLength;
16716
+ index = string.indexOf(substring, endIndex);
16717
+ } while (index !== -1);
16718
+ returnValue += string.slice(endIndex);
16719
+ return returnValue;
16720
+ }
16721
+ function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
16722
+ let endIndex = 0;
16723
+ let returnValue = "";
16724
+ do {
16725
+ const gotCR = string[index - 1] === "\r";
16726
+ returnValue += string.slice(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? `\r
16727
+ ` : `
16728
+ `) + postfix;
16729
+ endIndex = index + 1;
16730
+ index = string.indexOf(`
16731
+ `, endIndex);
16732
+ } while (index !== -1);
16733
+ returnValue += string.slice(endIndex);
16734
+ return returnValue;
16735
+ }
16736
+
16737
+ // node_modules/chalk/source/index.js
16738
+ var { stdout: stdoutColor, stderr: stderrColor } = supports_color_default;
16739
+ var GENERATOR = Symbol("GENERATOR");
16740
+ var STYLER = Symbol("STYLER");
16741
+ var IS_EMPTY = Symbol("IS_EMPTY");
16742
+ var levelMapping = [
16743
+ "ansi",
16744
+ "ansi",
16745
+ "ansi256",
16746
+ "ansi16m"
16747
+ ];
16748
+ var styles2 = Object.create(null);
16749
+ var applyOptions = (object, options = {}) => {
16750
+ if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
16751
+ throw new Error("The `level` option should be an integer from 0 to 3");
16752
+ }
16753
+ const colorLevel = stdoutColor ? stdoutColor.level : 0;
16754
+ object.level = options.level === undefined ? colorLevel : options.level;
16755
+ };
16756
+ var chalkFactory = (options) => {
16757
+ const chalk = (...strings) => strings.join(" ");
16758
+ applyOptions(chalk, options);
16759
+ Object.setPrototypeOf(chalk, createChalk.prototype);
16760
+ return chalk;
16761
+ };
16762
+ function createChalk(options) {
16763
+ return chalkFactory(options);
16764
+ }
16765
+ Object.setPrototypeOf(createChalk.prototype, Function.prototype);
16766
+ for (const [styleName, style] of Object.entries(ansi_styles_default)) {
16767
+ styles2[styleName] = {
16768
+ get() {
16769
+ const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
16770
+ Object.defineProperty(this, styleName, { value: builder });
16771
+ return builder;
16772
+ }
16773
+ };
16774
+ }
16775
+ styles2.visible = {
16776
+ get() {
16777
+ const builder = createBuilder(this, this[STYLER], true);
16778
+ Object.defineProperty(this, "visible", { value: builder });
16779
+ return builder;
16780
+ }
16781
+ };
16782
+ var getModelAnsi = (model, level, type, ...arguments_) => {
16783
+ if (model === "rgb") {
16784
+ if (level === "ansi16m") {
16785
+ return ansi_styles_default[type].ansi16m(...arguments_);
16786
+ }
16787
+ if (level === "ansi256") {
16788
+ return ansi_styles_default[type].ansi256(ansi_styles_default.rgbToAnsi256(...arguments_));
16789
+ }
16790
+ return ansi_styles_default[type].ansi(ansi_styles_default.rgbToAnsi(...arguments_));
16791
+ }
16792
+ if (model === "hex") {
16793
+ return getModelAnsi("rgb", level, type, ...ansi_styles_default.hexToRgb(...arguments_));
16794
+ }
16795
+ return ansi_styles_default[type][model](...arguments_);
16796
+ };
16797
+ var usedModels = ["rgb", "hex", "ansi256"];
16798
+ for (const model of usedModels) {
16799
+ styles2[model] = {
16800
+ get() {
16801
+ const { level } = this;
16802
+ return function(...arguments_) {
16803
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "color", ...arguments_), ansi_styles_default.color.close, this[STYLER]);
16804
+ return createBuilder(this, styler, this[IS_EMPTY]);
16805
+ };
16806
+ }
16807
+ };
16808
+ const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
16809
+ styles2[bgModel] = {
16810
+ get() {
16811
+ const { level } = this;
16812
+ return function(...arguments_) {
16813
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_), ansi_styles_default.bgColor.close, this[STYLER]);
16814
+ return createBuilder(this, styler, this[IS_EMPTY]);
16815
+ };
16816
+ }
16817
+ };
16818
+ }
16819
+ var proto = Object.defineProperties(() => {}, {
16820
+ ...styles2,
16821
+ level: {
16822
+ enumerable: true,
16823
+ get() {
16824
+ return this[GENERATOR].level;
16825
+ },
16826
+ set(level) {
16827
+ this[GENERATOR].level = level;
16828
+ }
16829
+ }
16830
+ });
16831
+ var createStyler = (open, close, parent) => {
16832
+ let openAll;
16833
+ let closeAll;
16834
+ if (parent === undefined) {
16835
+ openAll = open;
16836
+ closeAll = close;
16837
+ } else {
16838
+ openAll = parent.openAll + open;
16839
+ closeAll = close + parent.closeAll;
16840
+ }
16841
+ return {
16842
+ open,
16843
+ close,
16844
+ openAll,
16845
+ closeAll,
16846
+ parent
16847
+ };
16848
+ };
16849
+ var createBuilder = (self, _styler, _isEmpty) => {
16850
+ const builder = (...arguments_) => applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" "));
16851
+ Object.setPrototypeOf(builder, proto);
16852
+ builder[GENERATOR] = self;
16853
+ builder[STYLER] = _styler;
16854
+ builder[IS_EMPTY] = _isEmpty;
16855
+ return builder;
16856
+ };
16857
+ var applyStyle = (self, string) => {
16858
+ if (self.level <= 0 || !string) {
16859
+ return self[IS_EMPTY] ? "" : string;
16860
+ }
16861
+ let styler = self[STYLER];
16862
+ if (styler === undefined) {
16863
+ return string;
16864
+ }
16865
+ const { openAll, closeAll } = styler;
16866
+ if (string.includes("\x1B")) {
16867
+ while (styler !== undefined) {
16868
+ string = stringReplaceAll(string, styler.close, styler.open);
16869
+ styler = styler.parent;
16870
+ }
16871
+ }
16872
+ const lfIndex = string.indexOf(`
16873
+ `);
16874
+ if (lfIndex !== -1) {
16875
+ string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
16876
+ }
16877
+ return openAll + string + closeAll;
16878
+ };
16879
+ Object.defineProperties(createChalk.prototype, styles2);
16880
+ var chalk = createChalk();
16881
+ var chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
16882
+ var source_default = chalk;
16883
+
14523
16884
  // src/cli/index.ts
14524
16885
  init_tools();
14525
16886
  init_src();
16887
+ init_core();
14526
16888
  init_package();
14527
- import { program } from "commander";
14528
- import chalk from "chalk";
14529
16889
 
14530
16890
  // node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js
14531
- import process2 from "node:process";
16891
+ import process3 from "node:process";
14532
16892
 
14533
16893
  // node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js
14534
16894
  init_types2();
@@ -14564,7 +16924,7 @@ function serializeMessage(message) {
14564
16924
 
14565
16925
  // node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js
14566
16926
  class StdioServerTransport {
14567
- constructor(_stdin = process2.stdin, _stdout = process2.stdout) {
16927
+ constructor(_stdin = process3.stdin, _stdout = process3.stdout) {
14568
16928
  this._stdin = _stdin;
14569
16929
  this._stdout = _stdout;
14570
16930
  this._readBuffer = new ReadBuffer;
@@ -14625,11 +16985,350 @@ class StdioServerTransport {
14625
16985
 
14626
16986
  // src/cli/index.ts
14627
16987
  init_mcp2();
14628
- function chdir(path4) {
16988
+
16989
+ // src/cli/install.ts
16990
+ import * as fs2 from "fs";
16991
+ import * as path5 from "path";
16992
+ import * as child_process from "child_process";
16993
+ import * as readline from "readline";
16994
+ async function handleInstall(options) {
16995
+ const targetDir = options.prefix || process.cwd();
16996
+ const dryRun = options.dryRun || false;
16997
+ const skipDeps = options.skipDeps || false;
16998
+ console.log(source_default.blue(`
16999
+ \uD83C\uDF0A Tidewave Installer
17000
+ `));
17001
+ console.log(source_default.gray(`Target directory: ${targetDir}`));
17002
+ if (dryRun) {
17003
+ console.log(source_default.yellow(`
17004
+ ⚠️ DRY RUN MODE - No files will be created
17005
+ `));
17006
+ }
17007
+ const nextVersion = await detectNextJsVersion(targetDir);
17008
+ if (!nextVersion) {
17009
+ console.error(source_default.red(`
17010
+ ❌ Could not find Next.js in node_modules.`));
17011
+ console.log(source_default.gray(`
17012
+ The installer only works for Next.js projects
17013
+ `));
17014
+ process.exit(1);
17015
+ }
17016
+ console.log(source_default.green(`✅ Detected Next.js ${nextVersion.raw} (v${nextVersion.major})`));
17017
+ if (!skipDeps) {
17018
+ await installDependencies(targetDir, dryRun);
17019
+ } else {
17020
+ console.log(source_default.gray("⏭️ Skipping dependency installation"));
17021
+ }
17022
+ const steps = [
17023
+ () => createApiHandler(targetDir, dryRun),
17024
+ () => createMiddleware(targetDir, nextVersion, dryRun),
17025
+ () => createInstrumentation(targetDir, dryRun)
17026
+ ];
17027
+ for (const step of steps) {
17028
+ await step();
17029
+ }
17030
+ console.log(source_default.green(`
17031
+ ✅ Tidewave setup complete!
17032
+ `));
17033
+ console.log(source_default.blue("Next steps:"));
17034
+ console.log(" 1. Start your Next.js dev server: npm run dev");
17035
+ console.log(" 2. Install the Tidewave app: https://hexdocs.pm/tidewave/");
17036
+ console.log(` 3. Connect to your app through Tidewave
17037
+ `);
17038
+ }
17039
+ async function detectNextJsVersion(dir) {
17040
+ try {
17041
+ const nextPackageJsonPath = path5.join(dir, "node_modules", "next", "package.json");
17042
+ if (!fs2.existsSync(nextPackageJsonPath)) {
17043
+ return null;
17044
+ }
17045
+ const nextPackageJson = JSON.parse(fs2.readFileSync(nextPackageJsonPath, "utf-8"));
17046
+ const { version: version2 } = nextPackageJson;
17047
+ const match = version2.match(/^(\d+)\.(\d+)\.(\d+)/);
17048
+ if (match) {
17049
+ return {
17050
+ major: parseInt(match[1]),
17051
+ minor: parseInt(match[2]),
17052
+ raw: version2
17053
+ };
17054
+ }
17055
+ return null;
17056
+ } catch {
17057
+ return null;
17058
+ }
17059
+ }
17060
+ function detectPackageManager(dir) {
17061
+ if (fs2.existsSync(path5.join(dir, "bun.lockb")))
17062
+ return "bun";
17063
+ if (fs2.existsSync(path5.join(dir, "pnpm-lock.yaml")))
17064
+ return "pnpm";
17065
+ if (fs2.existsSync(path5.join(dir, "yarn.lock")))
17066
+ return "yarn";
17067
+ if (fs2.existsSync(path5.join(dir, "package-lock.json")))
17068
+ return "npm";
17069
+ return "npm";
17070
+ }
17071
+ async function promptUser(question) {
17072
+ const rl = readline.createInterface({
17073
+ input: process.stdin,
17074
+ output: process.stdout
17075
+ });
17076
+ return new Promise((resolve) => {
17077
+ rl.question(question, (answer) => {
17078
+ rl.close();
17079
+ const normalized = answer.trim().toLowerCase();
17080
+ resolve(normalized === "" || normalized === "y" || normalized === "yes");
17081
+ });
17082
+ });
17083
+ }
17084
+ async function installDependencies(dir, dryRun) {
17085
+ console.log(source_default.yellow("\uD83D\uDCE6 Installing dependencies..."));
17086
+ if (dryRun) {
17087
+ console.log(source_default.gray("[DRY RUN] Would install: tidewave, @opentelemetry/sdk-node"));
17088
+ return;
17089
+ }
17090
+ const pm = detectPackageManager(dir);
17091
+ const devDepCommands = {
17092
+ npm: ["install", "-D", "tidewave", "@opentelemetry/sdk-trace-base", "@opentelemetry/sdk-logs"],
17093
+ yarn: ["add", "-D", "tidewave", "@opentelemetry/sdk-trace-base", "@opentelemetry/sdk-logs"],
17094
+ pnpm: [
17095
+ "add",
17096
+ "--save-dev",
17097
+ "tidewave",
17098
+ "@opentelemetry/sdk-trace-base",
17099
+ "@opentelemetry/sdk-logs"
17100
+ ],
17101
+ bun: ["add", "--dev", "tidewave", "@opentelemetry/sdk-trace-base", "@opentelemetry/sdk-logs"]
17102
+ };
17103
+ const depCommands = {
17104
+ npm: ["install", "@opentelemetry/sdk-node"],
17105
+ yarn: ["add", "@opentelemetry/sdk-node"],
17106
+ pnpm: ["add", "@opentelemetry/sdk-node"],
17107
+ bun: ["add", "@opentelemetry/sdk-node"]
17108
+ };
17109
+ const devCmds = devDepCommands[pm];
17110
+ const depCmds = depCommands[pm];
17111
+ if (!devCmds || !depCmds) {
17112
+ console.error(source_default.red(`
17113
+ ❌ Unknown package manager: ${pm}`));
17114
+ process.exit(1);
17115
+ }
17116
+ try {
17117
+ child_process.execSync(`${pm} ${devCmds.join(" ")}`, {
17118
+ cwd: dir,
17119
+ stdio: "inherit"
17120
+ });
17121
+ child_process.execSync(`${pm} ${depCmds.join(" ")}`, {
17122
+ cwd: dir,
17123
+ stdio: "inherit"
17124
+ });
17125
+ console.log(source_default.green("✅ Dependencies installed"));
17126
+ } catch (_error) {
17127
+ console.error(source_default.red(`
17128
+ ❌ Failed to install dependencies`));
17129
+ console.log(source_default.gray(`
17130
+ Please install manually:
17131
+ ${pm} ${devCmds.join(" ")}
17132
+ ${pm} ${depCmds.join(" ")}
17133
+ `));
17134
+ process.exit(1);
17135
+ }
17136
+ }
17137
+ async function createApiHandler(dir, dryRun) {
17138
+ const apiDir = path5.join(dir, "pages", "api");
17139
+ const handlerPath = path5.join(apiDir, "tidewave.ts");
17140
+ const handlerContent = `import type { NextApiRequest, NextApiResponse } from 'next';
17141
+
17142
+ export default async function handler(
17143
+ req: NextApiRequest,
17144
+ res: NextApiResponse,
17145
+ ) {
17146
+ if (process.env.NODE_ENV === 'development') {
17147
+ const { tidewaveHandler } = await import('tidewave/next-js/handler');
17148
+ const handler = await tidewaveHandler();
17149
+ return handler(req, res);
17150
+ } else {
17151
+ res.status(404).end();
17152
+ }
17153
+ }
17154
+
17155
+ export const config = {
17156
+ runtime: 'nodejs',
17157
+ api: {
17158
+ bodyParser: false, // Tidewave already parses the body internally
17159
+ },
17160
+ };
17161
+ `;
17162
+ if (fs2.existsSync(handlerPath)) {
17163
+ if (dryRun) {
17164
+ console.log(source_default.gray(`[DRY RUN] Would ask to overwrite: ${path5.relative(dir, handlerPath)}`));
17165
+ return;
17166
+ }
17167
+ const shouldOverwrite = await promptUser(source_default.yellow(`
17168
+ ⚠️ ${path5.relative(dir, handlerPath)} already exists. Overwrite? (Y/n): `));
17169
+ if (!shouldOverwrite) {
17170
+ console.log(source_default.gray(`⏭️ Skipping: ${path5.relative(dir, handlerPath)}`));
17171
+ return;
17172
+ }
17173
+ }
17174
+ if (dryRun) {
17175
+ console.log(source_default.gray(`[DRY RUN] Would create: ${path5.relative(dir, handlerPath)}`));
17176
+ return;
17177
+ }
17178
+ fs2.mkdirSync(apiDir, { recursive: true });
17179
+ fs2.writeFileSync(handlerPath, handlerContent, "utf-8");
17180
+ console.log(source_default.green(`✅ Created: ${path5.relative(dir, handlerPath)}`));
17181
+ }
17182
+ async function createMiddleware(dir, nextVersion, dryRun) {
17183
+ const isNext16Plus = nextVersion.major >= 16;
17184
+ const fileName = isNext16Plus ? "proxy.ts" : "middleware.ts";
17185
+ const filePath = path5.join(dir, fileName);
17186
+ if (fs2.existsSync(filePath)) {
17187
+ console.log(source_default.yellow(`⏭️ ${fileName} already exists`));
17188
+ const content = fs2.readFileSync(filePath, "utf-8");
17189
+ if (content.includes("/tidewave") && content.includes("/api/tidewave")) {
17190
+ console.log(source_default.green(`✅ ${fileName} already configured for Tidewave`));
17191
+ return;
17192
+ }
17193
+ console.log(source_default.gray(`
17194
+ Please manually add the following to your ${fileName}:
17195
+ `));
17196
+ printMiddlewareInstructions(isNext16Plus);
17197
+ return;
17198
+ }
17199
+ const middlewareContent = isNext16Plus ? `import { NextRequest, NextResponse } from 'next/server';
17200
+
17201
+ export function proxy(req: NextRequest): NextResponse {
17202
+ if (req.nextUrl.pathname.startsWith('/tidewave')) {
17203
+ return NextResponse.rewrite(new URL('/api/tidewave', req.url));
17204
+ }
17205
+
17206
+ // Here you could add your own logic or different middlewares.
17207
+ return NextResponse.next();
17208
+ }
17209
+ ` : `import { NextRequest, NextResponse } from 'next/server';
17210
+
17211
+ export function middleware(req: NextRequest): NextResponse {
17212
+ if (req.nextUrl.pathname.startsWith('/tidewave')) {
17213
+ return NextResponse.rewrite(new URL('/api/tidewave', req.url));
17214
+ }
17215
+
17216
+ // Here you could add your own logic or different middlewares.
17217
+ return NextResponse.next();
17218
+ }
17219
+
17220
+ export const config = {
17221
+ matcher: ['/tidewave/:path*'],
17222
+ };
17223
+ `;
17224
+ if (dryRun) {
17225
+ console.log(source_default.gray(`[DRY RUN] Would create: ${fileName}`));
17226
+ return;
17227
+ }
17228
+ fs2.writeFileSync(filePath, middlewareContent, "utf-8");
17229
+ console.log(source_default.green(`✅ Created: ${fileName}`));
17230
+ }
17231
+ function printMiddlewareInstructions(isNext16Plus) {
17232
+ if (isNext16Plus) {
17233
+ console.log(source_default.cyan(` if (req.nextUrl.pathname.startsWith('/tidewave')) {
17234
+ return NextResponse.rewrite(new URL('/api/tidewave', req.url));
17235
+ }`));
17236
+ } else {
17237
+ console.log(source_default.cyan(` if (req.nextUrl.pathname.startsWith('/tidewave')) {
17238
+ return NextResponse.rewrite(new URL('/api/tidewave', req.url));
17239
+ }
17240
+
17241
+ // Also add to config.matcher:
17242
+ export const config = {
17243
+ matcher: ['/tidewave/:path*'],
17244
+ };`));
17245
+ }
17246
+ console.log();
17247
+ }
17248
+ async function createInstrumentation(dir, dryRun) {
17249
+ const rootPath = path5.join(dir, "instrumentation.ts");
17250
+ const srcPath = path5.join(dir, "src", "instrumentation.ts");
17251
+ const hasSrcDir = fs2.existsSync(path5.join(dir, "src"));
17252
+ const instrumentationPath = hasSrcDir ? srcPath : rootPath;
17253
+ if (fs2.existsSync(rootPath) || fs2.existsSync(srcPath)) {
17254
+ const existingPath = fs2.existsSync(rootPath) ? rootPath : srcPath;
17255
+ const existingFile = fs2.existsSync(rootPath) ? "instrumentation.ts" : "src/instrumentation.ts";
17256
+ console.log(source_default.yellow(`⏭️ ${existingFile} already exists`));
17257
+ const content = fs2.readFileSync(existingPath, "utf-8");
17258
+ if (content.includes("TidewaveSpanProcessor") && content.includes("TidewaveLogRecordProcessor")) {
17259
+ console.log(source_default.green(`✅ ${existingFile} already configured for Tidewave`));
17260
+ return;
17261
+ }
17262
+ console.log(source_default.gray(`
17263
+ Please manually add the following to your instrumentation.ts:
17264
+ `));
17265
+ printInstrumentationInstructions();
17266
+ return;
17267
+ }
17268
+ const instrumentationContent = `// instrumentation.ts
17269
+ import { NodeSDK } from '@opentelemetry/sdk-node';
17270
+ import type { SpanProcessor } from '@opentelemetry/sdk-trace-base';
17271
+ import type { LogRecordProcessor } from '@opentelemetry/sdk-logs';
17272
+
17273
+ export async function register() {
17274
+ const runtime = process.env.NEXT_RUNTIME;
17275
+ const env = process.env.NODE_ENV;
17276
+
17277
+ // Add your app own processes here existing configuration
17278
+ const sdkConfig: {
17279
+ spanProcessors: SpanProcessor[];
17280
+ logRecordProcessors: LogRecordProcessor[];
17281
+ } = {
17282
+ spanProcessors: [],
17283
+ logRecordProcessors: [],
17284
+ };
17285
+
17286
+ // Conditionally add Tidewave processors in development
17287
+ if (runtime === 'nodejs' && env === 'development') {
17288
+ const { TidewaveSpanProcessor, TidewaveLogRecordProcessor } = await import(
17289
+ 'tidewave/next-js/instrumentation'
17290
+ );
17291
+
17292
+ sdkConfig.spanProcessors.push(new TidewaveSpanProcessor());
17293
+ sdkConfig.logRecordProcessors.push(new TidewaveLogRecordProcessor());
17294
+ }
17295
+
17296
+ const sdk = new NodeSDK(sdkConfig);
17297
+ sdk.start();
17298
+ }
17299
+ `;
17300
+ if (dryRun) {
17301
+ console.log(source_default.gray(`[DRY RUN] Would create: ${path5.relative(dir, instrumentationPath)}`));
17302
+ return;
17303
+ }
17304
+ if (hasSrcDir) {
17305
+ fs2.mkdirSync(path5.dirname(instrumentationPath), { recursive: true });
17306
+ }
17307
+ fs2.writeFileSync(instrumentationPath, instrumentationContent, "utf-8");
17308
+ console.log(source_default.green(`✅ Created: ${path5.relative(dir, instrumentationPath)}`));
17309
+ }
17310
+ function printInstrumentationInstructions() {
17311
+ console.log(source_default.cyan(` // Inside your register() function:
17312
+ const runtime = process.env.NEXT_RUNTIME;
17313
+ const env = process.env.NODE_ENV;
17314
+
17315
+ if (runtime === 'nodejs' && env === 'development') {
17316
+ const { TidewaveSpanProcessor, TidewaveLogRecordProcessor } = await import(
17317
+ 'tidewave/next-js/instrumentation'
17318
+ );
17319
+
17320
+ sdkConfig.spanProcessors.push(new TidewaveSpanProcessor());
17321
+ sdkConfig.logRecordProcessors.push(new TidewaveLogRecordProcessor());
17322
+ }`));
17323
+ console.log();
17324
+ }
17325
+
17326
+ // src/cli/index.ts
17327
+ function chdir(path6) {
14629
17328
  try {
14630
- process.chdir(path4);
17329
+ process.chdir(path6);
14631
17330
  } catch (e) {
14632
- console.error(chalk.red(`Failed to apply given prefix: ${e}`));
17331
+ console.error(source_default.red(`Failed to apply given prefix: ${e}`));
14633
17332
  }
14634
17333
  }
14635
17334
  program.name(name).description("Universal documentation and source extraction tool for TypeScript and JavaScript").version(version);
@@ -14638,7 +17337,7 @@ async function handleGetDocs2(modulePath, options) {
14638
17337
  chdir(options.prefix);
14639
17338
  const docsResult = await Tidewave.extractDocs(modulePath);
14640
17339
  if (isExtractError(docsResult)) {
14641
- console.error(chalk.red(`Error: ${docsResult.error.message}`));
17340
+ console.error(source_default.red(`Error: ${docsResult.error.message}`));
14642
17341
  process.exit(1);
14643
17342
  }
14644
17343
  if (options.json) {
@@ -14652,7 +17351,7 @@ async function handleGetSourcePath2(moduleName, options) {
14652
17351
  chdir(options.prefix);
14653
17352
  const sourceResult = await Tidewave.getSourceLocation(moduleName);
14654
17353
  if (isResolveError(sourceResult)) {
14655
- console.error(chalk.red(`Error: ${sourceResult.error.message}`));
17354
+ console.error(source_default.red(`Error: ${sourceResult.error.message}`));
14656
17355
  process.exit(1);
14657
17356
  }
14658
17357
  console.log(sourceResult.path);
@@ -14668,6 +17367,7 @@ var {
14668
17367
  docs: { cli: docsCli },
14669
17368
  source: { cli: sourceCli }
14670
17369
  } = tools;
17370
+ program.command("install").description("Install Tidewave in a Next.js project").option("--prefix <path>", "Specify the directory containing package.json").option("--dry-run", "Preview changes without creating files").action(handleInstall);
14671
17371
  program.command("mcp").description("Starts a MCP server for tidewave (stdio)").option(docsCli.options.prefix.flag, docsCli.options.prefix.desc).action(handleMcp);
14672
17372
  program.command(docsCli.command).description(docsCli.description).argument(docsCli.argument, docsCli.argumentDescription).option(docsCli.options.prefix.flag, docsCli.options.prefix.desc).option(docsCli.options.json.flag, docsCli.options.json.desc).action(handleGetDocs2);
14673
17373
  program.command(sourceCli.command).description(sourceCli.description).argument(sourceCli.argument, sourceCli.argumentDescription).option(sourceCli.options.prefix.flag, sourceCli.options.prefix.desc).action(handleGetSourcePath2);