@stacksjs/bun-router 0.0.27 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/dist/chunk-0gjq8ttx.js +14 -0
  2. package/dist/chunk-0t5vz87j.js +35 -0
  3. package/dist/chunk-30rkn2ym.js +2 -0
  4. package/dist/chunk-38cmrard.js +2 -0
  5. package/dist/chunk-3qna6dwd.js +2 -0
  6. package/dist/chunk-4d5fmta0.js +2 -0
  7. package/dist/chunk-4x3b4b4q.js +2 -0
  8. package/dist/chunk-5be9x5cq.js +3 -0
  9. package/dist/chunk-5mxby3fd.js +1654 -0
  10. package/dist/chunk-5n0ckcmc.js +3 -0
  11. package/dist/chunk-5ncn73tp.js +3 -0
  12. package/dist/chunk-5s0pnsd6.js +12 -0
  13. package/dist/chunk-5s1pr62n.js +3 -0
  14. package/dist/chunk-67wgad4f.js +60 -0
  15. package/dist/chunk-6bbmkwng.js +3 -0
  16. package/dist/chunk-6s1kbajm.js +7851 -0
  17. package/dist/chunk-6sjvhy5f.js +3 -0
  18. package/dist/chunk-6xed4va1.js +2 -0
  19. package/dist/chunk-73k79n7q.js +15413 -0
  20. package/dist/chunk-748n6ydj.js +2 -0
  21. package/dist/chunk-7qnxdedn.js +321 -0
  22. package/dist/chunk-7rsf8tes.js +898 -0
  23. package/dist/chunk-8aspmtf1.js +2 -0
  24. package/dist/chunk-8wpj3fqe.js +351 -0
  25. package/dist/chunk-8yfdg595.js +2 -0
  26. package/dist/chunk-90eze7av.js +3 -0
  27. package/dist/chunk-9805tt8n.js +341 -0
  28. package/dist/chunk-9dvwyej7.js +2 -0
  29. package/dist/chunk-9ght4n4r.js +216 -0
  30. package/dist/chunk-a2w45krb.js +2 -0
  31. package/dist/chunk-a3wahyg7.js +3 -0
  32. package/dist/chunk-a547f2ab.js +48 -0
  33. package/dist/chunk-bqdycvtc.js +2 -0
  34. package/dist/chunk-brpgjyqg.js +3 -0
  35. package/dist/chunk-cd03rk3x.js +2 -0
  36. package/dist/chunk-csfrpsp7.js +185 -0
  37. package/dist/chunk-ct0m17q5.js +2 -0
  38. package/dist/chunk-dhbvvr5h.js +2 -0
  39. package/dist/chunk-dhptcsya.js +943 -0
  40. package/dist/chunk-dq93zag9.js +2 -0
  41. package/dist/chunk-dxg045wj.js +5 -0
  42. package/dist/chunk-e3qej0jr.js +4 -0
  43. package/dist/chunk-edrtesh7.js +2 -0
  44. package/dist/chunk-ejcws37w.js +2 -0
  45. package/dist/chunk-ex5fkjah.js +397 -0
  46. package/dist/chunk-ex890p45.js +51 -0
  47. package/dist/chunk-f69cpnhw.js +2 -0
  48. package/dist/chunk-fjf53b44.js +2 -0
  49. package/dist/chunk-fjzye4qj.js +2 -0
  50. package/dist/chunk-gfd23b6t.js +2 -0
  51. package/dist/chunk-habv0vef.js +12 -0
  52. package/dist/chunk-hmgedrmr.js +11 -0
  53. package/dist/chunk-hz6fc788.js +2 -0
  54. package/dist/chunk-jff6j9y3.js +10 -0
  55. package/dist/chunk-jmeb7n8k.js +70 -0
  56. package/dist/chunk-jrf5a2ap.js +2 -0
  57. package/dist/chunk-jy2jhcpy.js +246 -0
  58. package/dist/chunk-kc659vhx.js +4 -0
  59. package/dist/chunk-kjtjbcq4.js +71 -0
  60. package/dist/chunk-krkchy8v.js +4 -0
  61. package/dist/chunk-kxp888dn.js +4540 -0
  62. package/dist/chunk-m249t3je.js +3 -0
  63. package/dist/chunk-m9yabnjx.js +2 -0
  64. package/dist/chunk-mekrq9wd.js +2 -0
  65. package/dist/chunk-mmxv535f.js +82 -0
  66. package/dist/chunk-mypn7jss.js +2 -0
  67. package/dist/chunk-n18x1k3c.js +2 -0
  68. package/dist/chunk-nkddjzsa.js +2 -0
  69. package/dist/chunk-pjmhqmr9.js +2 -0
  70. package/dist/chunk-qyrnsaq1.js +2 -0
  71. package/dist/chunk-r19ff2qm.js +62 -0
  72. package/dist/chunk-r338fssq.js +2 -0
  73. package/dist/chunk-s36z58x2.js +29 -0
  74. package/dist/chunk-s3dn1kwx.js +231 -0
  75. package/dist/chunk-s79dd325.js +471 -0
  76. package/dist/chunk-sw0chtw4.js +4 -0
  77. package/dist/chunk-ta38j9em.js +2 -0
  78. package/dist/chunk-tpfgntwj.js +4211 -0
  79. package/dist/chunk-vr10sbbh.js +3 -0
  80. package/dist/chunk-vsh4390q.js +358 -0
  81. package/dist/chunk-vv3gb1m5.js +84 -0
  82. package/dist/chunk-vw8rwv6e.js +2 -0
  83. package/dist/chunk-w4r464v5.js +288 -0
  84. package/dist/chunk-wcrqs5z9.js +2 -0
  85. package/dist/chunk-x6d1rmwa.js +2 -0
  86. package/dist/chunk-x7ft15zz.js +2 -0
  87. package/dist/chunk-x8trwn7j.js +3 -0
  88. package/dist/chunk-xg9xscqz.js +1 -0
  89. package/dist/chunk-xhepdj1f.js +2 -0
  90. package/dist/chunk-xv2em0q4.js +4 -0
  91. package/dist/chunk-ypw6g0te.js +2 -0
  92. package/dist/chunk-z8szsm21.js +2 -0
  93. package/dist/chunk-zetqzgf3.js +194 -0
  94. package/dist/chunk-zfbh14qe.js +2 -0
  95. package/dist/chunk-zhx0hxdd.js +28 -0
  96. package/dist/cli.js +67 -3240
  97. package/dist/container/index.js +1 -321
  98. package/dist/index.js +80 -13987
  99. package/package.json +1 -1
  100. package/dist/chunk-1ahs68ys.js +0 -18
  101. package/dist/chunk-cgptvjdf.js +0 -18131
  102. package/dist/chunk-g3ybefhg.js +0 -1923
package/dist/cli.js CHANGED
@@ -1,2197 +1,95 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- import {
4
- middleware
5
- } from "./chunk-cgptvjdf.js";
6
- import"./chunk-1ahs68ys.js";
7
-
8
- // src/cli/index.ts
9
- import process15 from "process";
10
-
11
- // ../../node_modules/@stacksjs/clapp/dist/index.js
12
- import { existsSync } from "fs";
13
- import fs from "fs/promises";
14
- import os from "os";
15
- import path from "path";
16
- import process from "process";
17
- import { EventEmitter } from "events";
18
- import process5 from "process";
19
- import process2 from "process";
20
- import process3 from "process";
21
- import process4 from "process";
22
- import process7 from "process";
23
- import tty from "tty";
24
- import process8, { stdin, stdout } from "process";
25
- import process9, { stdin as stdin2, stdout as stdout2 } from "process";
26
- import readline2 from "readline";
27
- class Telemetry {
28
- configPath;
29
- config = null;
30
- events = [];
31
- retryCount = 0;
32
- maxRetries = 3;
33
- retryDelayMs = 1000;
34
- constructor() {
35
- const homeDir = os.homedir();
36
- const configDir = path.join(homeDir, ".config", "clapp");
37
- this.configPath = path.join(configDir, "telemetry.json");
38
- }
39
- async isEnabled() {
40
- if (process.env.DO_NOT_TRACK === "1" || process.env.DO_NOT_TRACK === "true") {
41
- return false;
42
- }
43
- if (process.env.NO_TELEMETRY === "1" || process.env.NO_TELEMETRY === "true") {
44
- return false;
45
- }
46
- const config = await this.loadConfig();
47
- return config.enabled;
48
- }
49
- async enable() {
50
- const config = await this.loadConfig();
51
- config.enabled = true;
52
- if (!config.userId) {
53
- config.userId = this.generateUserId();
54
- }
55
- await this.saveConfig(config);
56
- }
57
- async disable() {
58
- const config = await this.loadConfig();
59
- config.enabled = false;
60
- await this.saveConfig(config);
61
- }
62
- async track(event, data) {
63
- const enabled = await this.isEnabled();
64
- if (!enabled) {
65
- return;
66
- }
67
- const telemetryEvent = {
68
- event,
69
- ...data,
70
- timestamp: Date.now(),
71
- platform: os.platform(),
72
- nodeVersion: process.version
73
- };
74
- this.events.push(telemetryEvent);
75
- if (this.events.length >= 10) {
76
- await this.send();
77
- }
78
- }
79
- async trackCommand(command, duration) {
80
- await this.track("command", {
81
- command,
82
- duration
83
- });
84
- }
85
- async trackError(error, command) {
86
- await this.track("error", {
87
- error,
88
- command
89
- });
90
- }
91
- async send() {
92
- const enabled = await this.isEnabled();
93
- if (!enabled || this.events.length === 0) {
94
- return true;
95
- }
96
- try {
97
- this.events = [];
98
- this.retryCount = 0;
99
- const config = await this.loadConfig();
100
- config.lastSent = Date.now();
101
- await this.saveConfig(config);
102
- return true;
103
- } catch {
104
- if (this.retryCount < this.maxRetries) {
105
- this.retryCount++;
106
- const delay = this.retryDelayMs * 2 ** (this.retryCount - 1);
107
- await this.sleep(delay);
108
- return this.send();
109
- }
110
- this.events = [];
111
- this.retryCount = 0;
112
- return false;
113
- }
114
- }
115
- async flush() {
116
- if (this.events.length === 0) {
117
- return true;
118
- }
119
- return this.send();
120
- }
121
- sleep(ms) {
122
- return new Promise((resolve) => setTimeout(resolve, ms));
123
- }
124
- async status() {
125
- const config = await this.loadConfig();
126
- return {
127
- enabled: config.enabled,
128
- doNotTrack: process.env.DO_NOT_TRACK === "1" || process.env.DO_NOT_TRACK === "true",
129
- eventsQueued: this.events.length,
130
- lastSent: config.lastSent
131
- };
132
- }
133
- async loadConfig() {
134
- if (this.config) {
135
- return this.config;
136
- }
137
- try {
138
- if (existsSync(this.configPath)) {
139
- const data = await fs.readFile(this.configPath, "utf-8");
140
- this.config = JSON.parse(data);
141
- return this.config;
142
- }
143
- } catch {}
144
- this.config = {
145
- enabled: false
146
- };
147
- return this.config;
148
- }
149
- async saveConfig(config) {
150
- this.config = config;
151
- try {
152
- const configDir = path.dirname(this.configPath);
153
- await fs.mkdir(configDir, { recursive: true });
154
- await fs.writeFile(this.configPath, JSON.stringify(config, null, 2), "utf-8");
155
- } catch {}
156
- }
157
- generateUserId() {
158
- const random = Math.random().toString(36).substring(2, 15);
159
- const timestamp = Date.now().toString(36);
160
- return `${random}-${timestamp}`;
161
- }
162
- }
163
- var telemetry = new Telemetry;
164
- function parseArgv(argv, opts = {}) {
165
- const result = { _: [] };
166
- const alias = opts.alias || {};
167
- const booleans = new Set(opts.boolean || []);
168
- const aliasOf = {};
169
- for (const key of Object.keys(alias)) {
170
- for (const a of alias[key]) {
171
- aliasOf[a] = key;
172
- }
173
- }
174
- for (const b of booleans) {
175
- if (alias[b]) {
176
- for (const a of alias[b])
177
- booleans.add(a);
178
- }
179
- }
180
- function setKey(key, value) {
181
- const canonical = aliasOf[key] || key;
182
- result[canonical] = value;
183
- if (alias[canonical]) {
184
- for (const a of alias[canonical])
185
- result[a] = value;
186
- }
187
- if (aliasOf[key] && alias[aliasOf[key]]) {
188
- for (const a of alias[aliasOf[key]])
189
- result[a] = value;
190
- }
191
- result[key] = value;
192
- }
193
- for (let i = 0;i < argv.length; i++) {
194
- const arg = argv[i];
195
- if (arg === "--") {
196
- result._.push(...argv.slice(i + 1));
197
- break;
198
- }
199
- if (arg.startsWith("--")) {
200
- const eqIdx = arg.indexOf("=");
201
- if (eqIdx !== -1) {
202
- const key = arg.slice(2, eqIdx);
203
- const value = arg.slice(eqIdx + 1);
204
- setKey(key, value);
205
- } else {
206
- const key = arg.slice(2);
207
- if (key.startsWith("no-")) {
208
- const actualKey = key.slice(3);
209
- setKey(actualKey, false);
210
- continue;
211
- }
212
- const canonical = aliasOf[key] || key;
213
- if (booleans.has(canonical) || booleans.has(key)) {
214
- setKey(key, true);
215
- } else {
216
- const next = argv[i + 1];
217
- if (next !== undefined && !next.startsWith("-")) {
218
- setKey(key, next);
219
- i++;
220
- } else {
221
- setKey(key, true);
222
- }
223
- }
224
- }
225
- } else if (arg.startsWith("-") && arg.length > 1) {
226
- const chars = arg.slice(1);
227
- for (let j = 0;j < chars.length; j++) {
228
- const ch = chars[j];
229
- const canonical = aliasOf[ch] || ch;
230
- if (j === chars.length - 1 && !booleans.has(canonical) && !booleans.has(ch)) {
231
- const next = argv[i + 1];
232
- if (next !== undefined && !next.startsWith("-")) {
233
- setKey(ch, next);
234
- i++;
235
- } else {
236
- setKey(ch, true);
237
- }
238
- } else {
239
- setKey(ch, true);
240
- }
241
- }
242
- } else {
243
- result._.push(arg);
244
- }
245
- }
246
- return result;
247
- }
248
- function removeBrackets(v) {
249
- return v.replace(/[<[].+/, "").trim();
250
- }
251
- function findAllBrackets(v) {
252
- const ANGLED_BRACKET_RE_GLOBAL = /<([^>]+)>/g;
253
- const SQUARE_BRACKET_RE_GLOBAL = /\[([^\]]+)\]/g;
254
- const res = [];
255
- const parse = (match) => {
256
- let variadic = false;
257
- let value = match[1];
258
- if (value.startsWith("...")) {
259
- value = value.slice(3);
260
- variadic = true;
261
- }
262
- return {
263
- required: match[0].startsWith("<"),
264
- value,
265
- variadic
266
- };
267
- };
268
- let angledMatch;
269
- while (angledMatch = ANGLED_BRACKET_RE_GLOBAL.exec(v)) {
270
- res.push(parse(angledMatch));
271
- }
272
- let squareMatch;
273
- while (squareMatch = SQUARE_BRACKET_RE_GLOBAL.exec(v)) {
274
- res.push(parse(squareMatch));
275
- }
276
- return res;
277
- }
278
- function getMriOptions(options) {
279
- const result = { alias: {}, boolean: [] };
280
- for (const [index, option] of options.entries()) {
281
- if (option.names.length > 1) {
282
- result.alias[option.names[0]] = option.names.slice(1);
283
- }
284
- if (option.isBoolean) {
285
- if (option.negated) {
286
- const hasStringTypeOption = options.some((o, i) => {
287
- return i !== index && o.names.some((name) => option.names.includes(name)) && typeof o.required === "boolean";
288
- });
289
- if (!hasStringTypeOption) {
290
- result.boolean.push(option.names[0]);
291
- }
292
- } else {
293
- result.boolean.push(option.names[0]);
294
- }
295
- }
296
- }
297
- return result;
298
- }
299
- function findLongest(arr) {
300
- return arr.reduce((a, b) => a.length >= b.length ? a : b, "");
301
- }
302
- function padRight(str, length) {
303
- return str.length >= length ? str : `${str}${" ".repeat(length - str.length)}`;
304
- }
305
- function camelcase(input) {
306
- return input.replace(/([a-z])-([a-z])/g, (_, p1, p2) => {
307
- return p1 + p2.toUpperCase();
308
- });
309
- }
310
- function setDotProp(obj, keys, val) {
311
- let i = 0;
312
- const length = keys.length;
313
- let t = obj;
314
- let x;
315
- for (;i < length; ++i) {
316
- x = t[keys[i]];
317
- t = t[keys[i]] = i === length - 1 ? val : x != null ? x : !!~keys[i + 1].indexOf(".") || !(+keys[i + 1] > -1) ? {} : [];
318
- }
319
- }
320
- function setByType(obj, transforms) {
321
- for (const key of Object.keys(transforms)) {
322
- const transform = transforms[key];
323
- if (transform.shouldTransform) {
324
- obj[key] = Array.prototype.concat.call([], obj[key]);
325
- if (typeof transform.transformFunction === "function") {
326
- obj[key] = obj[key].map(transform.transformFunction);
327
- }
328
- }
329
- }
330
- }
331
- function getFileName(input) {
332
- const m = /([^\\/]+)$/.exec(input);
333
- return m ? m[1] : "";
334
- }
335
- function camelcaseOptionName(name) {
336
- return name.split(".").map((v, i) => {
337
- return i === 0 ? camelcase(v) : v;
338
- }).join(".");
339
- }
340
-
341
- class ClappError extends Error {
342
- exitCode = 2;
343
- isUsageError = true;
344
- constructor(message) {
345
- super(message);
346
- this.name = this.constructor.name;
347
- if (typeof Error.captureStackTrace === "function") {
348
- Error.captureStackTrace(this, this.constructor);
349
- } else {
350
- this.stack = new Error(message).stack;
351
- }
352
- }
353
- format(showStack = false) {
354
- if (showStack && this.stack) {
355
- return `${this.message}
3
+ import{Rq as B6}from"./chunk-s79dd325.js";import"./chunk-a3wahyg7.js";import O from"process";import{existsSync as h6}from"fs";import p from"fs/promises";import X6 from"os";import l from"path";import b from"process";import{EventEmitter as m6}from"events";import E from"process";import q6 from"process";import t from"process";import _ from"process";import C from"process";import H6 from"tty";import Az,{stdin as b4,stdout as A4}from"process";import V6,{stdin as Cz,stdout as Rz}from"process";import vz from"readline";class W6{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let z=X6.homedir(),J=l.join(z,".config","clapp");this.configPath=l.join(J,"telemetry.json")}async isEnabled(){if(b.env.DO_NOT_TRACK==="1"||b.env.DO_NOT_TRACK==="true")return!1;if(b.env.NO_TELEMETRY==="1"||b.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let z=await this.loadConfig();if(z.enabled=!0,!z.userId)z.userId=this.generateUserId();await this.saveConfig(z)}async disable(){let z=await this.loadConfig();z.enabled=!1,await this.saveConfig(z)}async track(z,J){if(!await this.isEnabled())return;let $={event:z,...J,timestamp:Date.now(),platform:X6.platform(),nodeVersion:b.version};if(this.events.push($),this.events.length>=10)await this.send()}async trackCommand(z,J){await this.track("command",{command:z,duration:J})}async trackError(z,J){await this.track("error",{error:z,command:J})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let J=await this.loadConfig();return J.lastSent=Date.now(),await this.saveConfig(J),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let J=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep(J),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep(z){return new Promise((J)=>setTimeout(J,z))}async status(){let z=await this.loadConfig();return{enabled:z.enabled,doNotTrack:b.env.DO_NOT_TRACK==="1"||b.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:z.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(h6(this.configPath)){let z=await p.readFile(this.configPath,"utf-8");return this.config=JSON.parse(z),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig(z){this.config=z;try{let J=l.dirname(this.configPath);await p.mkdir(J,{recursive:!0}),await p.writeFile(this.configPath,JSON.stringify(z,null,2),"utf-8")}catch{}}generateUserId(){let z=Math.random().toString(36).substring(2,15),J=Date.now().toString(36);return`${z}-${J}`}}var F4=new W6;function d6(z,J={}){let Z={_:[]},$=J.alias||{},Q=new Set(J.boolean||[]),j={};for(let X of Object.keys($))for(let Y of $[X])j[Y]=X;for(let X of Q)if($[X])for(let Y of $[X])Q.add(Y);function q(X,Y){let G=j[X]||X;if(Z[G]=Y,$[G])for(let H of $[G])Z[H]=Y;if(j[X]&&$[j[X]])for(let H of $[j[X]])Z[H]=Y;Z[X]=Y}for(let X=0;X<z.length;X++){let Y=z[X];if(Y==="--"){Z._.push(...z.slice(X+1));break}if(Y.startsWith("--")){let G=Y.indexOf("=");if(G!==-1){let H=Y.slice(2,G),K=Y.slice(G+1);q(H,K)}else{let H=Y.slice(2);if(H.startsWith("no-")){let V=H.slice(3);q(V,!1);continue}let K=j[H]||H;if(Q.has(K)||Q.has(H))q(H,!0);else{let V=z[X+1];if(V!==void 0&&!V.startsWith("-"))q(H,V),X++;else q(H,!0)}}}else if(Y.startsWith("-")&&Y.length>1){let G=Y.slice(1);for(let H=0;H<G.length;H++){let K=G[H],V=j[K]||K;if(H===G.length-1&&!Q.has(V)&&!Q.has(K)){let W=z[X+1];if(W!==void 0&&!W.startsWith("-"))q(K,W),X++;else q(K,!0)}else q(K,!0)}}else Z._.push(Y)}return Z}function s(z){return z.replace(/[<[].+/,"").trim()}function u6(z){let J=/<([^>]+)>/g,Z=/\[([^\]]+)\]/g,$=[],Q=(X)=>{let Y=!1,G=X[1];if(G.startsWith("..."))G=G.slice(3),Y=!0;return{required:X[0].startsWith("<"),value:G,variadic:Y}},j;while(j=J.exec(z))$.push(Q(j));let q;while(q=Z.exec(z))$.push(Q(q));return $}function c6(z){let J={alias:{},boolean:[]};for(let[Z,$]of z.entries()){if($.names.length>1)J.alias[$.names[0]]=$.names.slice(1);if($.isBoolean)if($.negated){if(!z.some((j,q)=>{return q!==Z&&j.names.some((X)=>$.names.includes(X))&&typeof j.required==="boolean"}))J.boolean.push($.names[0])}else J.boolean.push($.names[0])}return J}function U6(z){return z.reduce((J,Z)=>J.length>=Z.length?J:Z,"")}function a(z,J){return z.length>=J?z:`${z}${" ".repeat(J-z.length)}`}function i6(z){return z.replace(/([a-z])-([a-z])/g,(J,Z,$)=>{return Z+$.toUpperCase()})}function n6(z,J,Z){let $=0,Q=J.length,j=z,q;for(;$<Q;++$)q=j[J[$]],j=j[J[$]]=$===Q-1?Z:q!=null?q:!!~J[$+1].indexOf(".")||!(+J[$+1]>-1)?{}:[]}function p6(z,J){for(let Z of Object.keys(J)){let $=J[Z];if($.shouldTransform){if(z[Z]=Array.prototype.concat.call([],z[Z]),typeof $.transformFunction==="function")z[Z]=z[Z].map($.transformFunction)}}}function l6(z){let J=/([^\\/]+)$/.exec(z);return J?J[1]:""}function D6(z){return z.split(".").map((J,Z)=>{return Z===0?i6(J):J}).join(".")}class y extends Error{exitCode=2;isUsageError=!0;constructor(z){super(z);if(this.name=this.constructor.name,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error(z).stack}format(z=!1){if(z&&this.stack)return`${this.message}
356
4
 
357
5
  Stack trace:
358
- ${this.stack}`;
359
- }
360
- return this.message;
361
- }
362
- }
363
- function isUnicodeSupported() {
364
- const { env } = process2;
365
- const { TERM, TERM_PROGRAM } = env;
366
- if (process2.platform !== "win32") {
367
- return TERM !== "linux";
368
- }
369
- return Boolean(env.WT_SESSION) || Boolean(env.TERMINUS_SUBLIME) || env.ConEmuTask === "{cmd::Cmder}" || TERM_PROGRAM === "Terminus-Sublime" || TERM_PROGRAM === "vscode" || TERM === "xterm-256color" || TERM === "alacritty" || TERM === "rxvt-unicode" || TERM === "rxvt-unicode-256color" || env.TERMINAL_EMULATOR === "JetBrains-JediTerm";
370
- }
371
- var ESC = "\x1B";
372
- var CSI = `${ESC}[`;
373
- var cursor = {
374
- to(x, y) {
375
- if (!y)
376
- return `${CSI}${x + 1}G`;
377
- return `${CSI}${y + 1};${x + 1}H`;
378
- },
379
- move(x, y) {
380
- let ret = "";
381
- if (x < 0)
382
- ret += `${CSI}${-x}D`;
383
- else if (x > 0)
384
- ret += `${CSI}${x}C`;
385
- if (y < 0)
386
- ret += `${CSI}${-y}A`;
387
- else if (y > 0)
388
- ret += `${CSI}${y}B`;
389
- return ret;
390
- },
391
- up: (count = 1) => `${CSI}${count}A`,
392
- down: (count = 1) => `${CSI}${count}B`,
393
- forward: (count = 1) => `${CSI}${count}C`,
394
- backward: (count = 1) => `${CSI}${count}D`,
395
- nextLine: (count = 1) => `${CSI}E`.repeat(count),
396
- prevLine: (count = 1) => `${CSI}F`.repeat(count),
397
- left: `${CSI}G`,
398
- hide: `${CSI}?25l`,
399
- show: `${CSI}?25h`,
400
- save: `${ESC}7`,
401
- restore: `${ESC}8`
402
- };
403
- var erase = {
404
- screen: `${CSI}2J`,
405
- up: (count = 1) => `${CSI}1J`.repeat(count),
406
- down: (count = 1) => `${CSI}J`.repeat(count),
407
- line: `${CSI}2K`,
408
- lineEnd: `${CSI}K`,
409
- lineStart: `${CSI}1K`,
410
- lines(count) {
411
- let clear = "";
412
- for (let i = 0;i < count; i++)
413
- clear += this.line + (i < count - 1 ? cursor.up() : "");
414
- if (count)
415
- clear += cursor.left;
416
- return clear;
417
- }
418
- };
419
- var clear = {
420
- screen: `${ESC}c`
421
- };
422
- function levenshteinDistance(a, b) {
423
- const matrix = [];
424
- for (let i = 0;i <= b.length; i++) {
425
- matrix[i] = [i];
426
- }
427
- for (let j = 0;j <= a.length; j++) {
428
- matrix[0][j] = j;
429
- }
430
- for (let i = 1;i <= b.length; i++) {
431
- for (let j = 1;j <= a.length; j++) {
432
- if (b.charAt(i - 1) === a.charAt(j - 1)) {
433
- matrix[i][j] = matrix[i - 1][j - 1];
434
- } else {
435
- matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j] + 1);
436
- }
437
- }
438
- }
439
- return matrix[b.length][a.length];
440
- }
441
- function findSimilarCommands(input, commands, maxDistance = 2, maxSuggestions = 3) {
442
- return commands.map((cmd) => ({ cmd, distance: levenshteinDistance(input, cmd) })).filter(({ distance }) => distance <= maxDistance).sort((a, b) => a.distance - b.distance).slice(0, maxSuggestions).map(({ cmd }) => cmd);
443
- }
444
-
445
- class Option {
446
- rawName;
447
- description;
448
- name;
449
- names;
450
- isBoolean;
451
- required;
452
- config;
453
- negated;
454
- constructor(rawName, description, config) {
455
- this.rawName = rawName;
456
- this.description = description;
457
- this.config = Object.assign({}, config);
458
- rawName = rawName.replace(/\.\*/g, "");
459
- this.negated = false;
460
- this.names = removeBrackets(rawName).split(",").map((v) => {
461
- let name = v.trim().replace(/^-{1,2}/, "");
462
- if (name.startsWith("no-")) {
463
- this.negated = true;
464
- name = name.replace(/^no-/, "");
465
- }
466
- return camelcaseOptionName(name);
467
- }).sort((a, b) => a.length > b.length ? 1 : -1);
468
- this.name = this.names[this.names.length - 1];
469
- if (this.negated && this.config.default == null) {
470
- this.config.default = true;
471
- }
472
- if (rawName.includes("<")) {
473
- this.required = true;
474
- } else if (rawName.includes("[")) {
475
- this.required = false;
476
- } else {
477
- this.isBoolean = true;
478
- }
479
- }
480
- }
481
- var processArgs = process3.argv;
482
- var platformInfo = `${process3.platform}-${process3.arch} bun-v${typeof Bun !== "undefined" ? Bun.version : "unknown"}`;
483
- var processArgs2 = process4.argv;
484
- var platformInfo2 = `${process4.platform}-${process4.arch} node-${process4.version}`;
485
-
486
- class Command {
487
- rawName;
488
- description;
489
- config;
490
- cli;
491
- options;
492
- aliasNames;
493
- name;
494
- namespace;
495
- args;
496
- commandAction;
497
- usageText;
498
- versionNumber;
499
- examples;
500
- helpCallback;
501
- globalCommand;
502
- beforeHooks;
503
- afterHooks;
504
- middleware;
505
- constructor(rawName, description, config, cli) {
506
- this.rawName = rawName;
507
- this.description = description;
508
- this.config = config;
509
- this.cli = cli;
510
- this.options = [];
511
- this.aliasNames = [];
512
- this.name = removeBrackets(rawName);
513
- const nameWithoutBrackets = removeBrackets(rawName);
514
- const colonIndex = nameWithoutBrackets.indexOf(":");
515
- if (colonIndex > 0) {
516
- this.namespace = nameWithoutBrackets.substring(0, colonIndex);
517
- this.name = nameWithoutBrackets.substring(colonIndex + 1);
518
- }
519
- this.args = findAllBrackets(rawName);
520
- this.examples = [];
521
- this.beforeHooks = [];
522
- this.afterHooks = [];
523
- this.middleware = [];
524
- if (!config) {
525
- this.config = {};
526
- }
527
- }
528
- usage(text) {
529
- this.usageText = text;
530
- return this;
531
- }
532
- allowUnknownOptions() {
533
- this.config.allowUnknownOptions = true;
534
- return this;
535
- }
536
- ignoreOptionDefaultValue() {
537
- this.config.ignoreOptionDefaultValue = true;
538
- return this;
539
- }
540
- version(version, customFlags = "-v, --version") {
541
- this.versionNumber = version;
542
- this.option(customFlags, "Display version number");
543
- return this;
544
- }
545
- example(example) {
546
- this.examples.push(example);
547
- return this;
548
- }
549
- option(rawName, description, config) {
550
- const option = new Option(rawName, description, config);
551
- this.options.push(option);
552
- return this;
553
- }
554
- alias(name) {
555
- this.aliasNames.push(name);
556
- return this;
557
- }
558
- action(callback) {
559
- this.commandAction = callback;
560
- return this;
561
- }
562
- before(handler) {
563
- this.beforeHooks.push(handler);
564
- return this;
565
- }
566
- after(handler) {
567
- this.afterHooks.push(handler);
568
- return this;
569
- }
570
- use(handler) {
571
- this.middleware.push(handler);
572
- return this;
573
- }
574
- isMatched(name) {
575
- if (this.aliasNames.includes(name))
576
- return true;
577
- if (this.namespace)
578
- return `${this.namespace}:${this.name}` === name;
579
- return this.name === name;
580
- }
581
- get isDefaultCommand() {
582
- return this.name === "" || this.aliasNames.includes("!");
583
- }
584
- get isGlobalCommand() {
585
- return this instanceof GlobalCommand;
586
- }
587
- get displayName() {
588
- return this.namespace ? `${this.namespace}:${this.name}` : this.name;
589
- }
590
- hasOption(name) {
591
- name = name.split(".")[0];
592
- return !!this.options.find((option) => {
593
- return option.names.includes(name);
594
- });
595
- }
596
- outputHelp() {
597
- const { name, commands } = this.cli;
598
- const {
599
- versionNumber,
600
- options: globalOptions,
601
- helpCallback
602
- } = this.cli.globalCommand;
603
- let sections = [
604
- {
605
- body: `${name}${versionNumber ? `/${versionNumber}` : ""}`
606
- }
607
- ];
608
- sections.push({
609
- title: "Usage",
610
- body: ` $ ${name} ${this.usageText || this.rawName}`
611
- });
612
- const showCommands = (this.isGlobalCommand || this.isDefaultCommand) && commands.length > 0;
613
- if (showCommands) {
614
- const longestCommandName = findLongest(commands.map((command) => command.rawName));
615
- const namespaceGroups = new Map;
616
- const noNamespaceCommands = [];
617
- for (const command of commands) {
618
- if (command.namespace) {
619
- if (!namespaceGroups.has(command.namespace)) {
620
- namespaceGroups.set(command.namespace, []);
621
- }
622
- namespaceGroups.get(command.namespace).push(command);
623
- } else {
624
- noNamespaceCommands.push(command);
625
- }
626
- }
627
- let commandBody = "";
628
- if (noNamespaceCommands.length > 0) {
629
- commandBody += noNamespaceCommands.map((command) => {
630
- return ` ${padRight(command.rawName, longestCommandName.length)} ${command.description}`;
631
- }).join(`
632
- `);
633
- }
634
- const sortedNamespaces = Array.from(namespaceGroups.keys()).sort();
635
- for (const namespace of sortedNamespaces) {
636
- const namespaceCommands = namespaceGroups.get(namespace);
637
- if (commandBody.length > 0) {
638
- commandBody += `
639
-
640
- `;
641
- }
642
- commandBody += ` ${namespace}:
643
- `;
644
- commandBody += namespaceCommands.map((command) => {
645
- return ` ${padRight(command.rawName, longestCommandName.length - 2)} ${command.description}`;
646
- }).join(`
647
- `);
648
- }
649
- sections.push({
650
- title: "Commands",
651
- body: commandBody
652
- });
653
- sections.push({
654
- title: `For more info, run any command with the \`--help\` flag`,
655
- body: commands.map((command) => ` $ ${name}${command.displayName === "" ? "" : ` ${command.displayName}`} --help`).join(`
656
- `)
657
- });
658
- }
659
- let options = this.isGlobalCommand ? globalOptions : [...this.options, ...globalOptions || []];
660
- if (!this.isGlobalCommand && !this.isDefaultCommand) {
661
- options = options.filter((option) => option.name !== "version");
662
- }
663
- if (options.length > 0) {
664
- const longestOptionName = findLongest(options.map((option) => option.rawName));
665
- sections.push({
666
- title: "Options",
667
- body: options.map((option) => {
668
- return ` ${padRight(option.rawName, longestOptionName.length)} ${option.description} ${option.config.default === undefined ? "" : `(default: ${option.config.default})`}`;
669
- }).join(`
670
- `)
671
- });
672
- }
673
- if (this.examples.length > 0) {
674
- sections.push({
675
- title: "Examples",
676
- body: this.examples.map((example) => {
677
- if (typeof example === "function") {
678
- return example(name);
679
- }
680
- return example;
681
- }).join(`
682
- `)
683
- });
684
- }
685
- if (helpCallback) {
686
- sections = helpCallback(sections) || sections;
687
- }
688
- console.log(sections.map((section) => {
689
- return section.title ? `${section.title}:
690
- ${section.body}` : section.body;
691
- }).join(`
692
-
693
- `));
694
- }
695
- outputVersion() {
696
- const { name } = this.cli;
697
- const { versionNumber } = this.cli.globalCommand;
698
- if (versionNumber) {
699
- const platformInfo3 = typeof Bun !== "undefined" ? platformInfo : platformInfo2;
700
- console.log(`${name}/${versionNumber} ${platformInfo3}`);
701
- }
702
- }
703
- checkRequiredArgs() {
704
- const minimalArgsCount = this.args.filter((arg) => arg.required).length;
705
- if (this.cli.args.length < minimalArgsCount) {
706
- const requiredArgs = this.args.filter((arg) => arg.required);
707
- const missingArgs = requiredArgs.slice(this.cli.args.length);
708
- const argNames = missingArgs.map((arg) => `<${arg.value}>`).join(" ");
709
- throw new ClappError(`Missing required argument${missingArgs.length > 1 ? "s" : ""}: ${argNames}
710
-
711
- ` + `Run \`${this.cli.name} ${this.rawName} --help\` for usage information.`);
712
- }
713
- }
714
- checkUnknownOptions() {
715
- const { options, globalCommand } = this.cli;
716
- if (!this.config.allowUnknownOptions) {
717
- for (const name of Object.keys(options)) {
718
- if (name !== "--" && !this.hasOption(name) && !globalCommand.hasOption(name)) {
719
- const allOptions = [...globalCommand.options, ...this.options];
720
- const allOptionNames = allOptions.flatMap((opt) => opt.names);
721
- const optionFlag = name.length > 1 ? `--${name}` : `-${name}`;
722
- const suggestions = findSimilarCommands(name, allOptionNames);
723
- let errorMsg = `Unknown option \`${optionFlag}\``;
724
- if (suggestions.length > 0) {
725
- errorMsg += `
726
-
727
- Did you mean one of these?`;
728
- suggestions.forEach((suggestion) => {
729
- const suggestedFlag = suggestion.length > 1 ? `--${suggestion}` : `-${suggestion}`;
730
- errorMsg += `
731
- \u2022 ${suggestedFlag}`;
732
- });
733
- }
734
- errorMsg += `
735
-
736
- Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`;
737
- throw new ClappError(errorMsg);
738
- }
739
- }
740
- }
741
- }
742
- checkOptionValue() {
743
- const { options: parsedOptions, globalCommand } = this.cli;
744
- const options = [...globalCommand.options, ...this.options];
745
- for (const option of options) {
746
- const value = parsedOptions[option.name.split(".")[0]];
747
- if (option.required) {
748
- const hasNegated = options.some((o) => o.negated && o.names.includes(option.name));
749
- if (value === true || value === false && !hasNegated) {
750
- throw new ClappError(`Option \`${option.rawName}\` requires a value.
751
-
752
- ` + `Example: ${this.cli.name} ${this.rawName} ${option.rawName} <value>`);
753
- }
754
- }
755
- }
756
- }
757
- }
758
-
759
- class GlobalCommand extends Command {
760
- constructor(cli) {
761
- super("@@global@@", "", {}, cli);
762
- }
763
- }
764
- var Command_default = Command;
765
- var codes = {
766
- red: ["\x1B[31m", "\x1B[39m"],
767
- green: ["\x1B[32m", "\x1B[39m"],
768
- blue: ["\x1B[34m", "\x1B[39m"],
769
- yellow: ["\x1B[33m", "\x1B[39m"],
770
- cyan: ["\x1B[36m", "\x1B[39m"],
771
- magenta: ["\x1B[35m", "\x1B[39m"],
772
- white: ["\x1B[37m", "\x1B[39m"],
773
- gray: ["\x1B[90m", "\x1B[39m"],
774
- bgRed: ["\x1B[41m", "\x1B[49m"],
775
- bgGreen: ["\x1B[42m", "\x1B[49m"],
776
- bgBlue: ["\x1B[44m", "\x1B[49m"],
777
- bgYellow: ["\x1B[43m", "\x1B[49m"],
778
- bgCyan: ["\x1B[46m", "\x1B[49m"],
779
- bgMagenta: ["\x1B[45m", "\x1B[49m"],
780
- bold: ["\x1B[1m", "\x1B[22m"],
781
- italic: ["\x1B[3m", "\x1B[23m"],
782
- underline: ["\x1B[4m", "\x1B[24m"],
783
- dim: ["\x1B[2m", "\x1B[22m"],
784
- inverse: ["\x1B[7m", "\x1B[27m"],
785
- hidden: ["\x1B[8m", "\x1B[28m"],
786
- strikethrough: ["\x1B[9m", "\x1B[29m"]
787
- };
788
- var theme = {
789
- primary: "blue",
790
- secondary: "cyan",
791
- success: "green",
792
- warning: "yellow",
793
- error: "red",
794
- info: "magenta",
795
- muted: "gray"
796
- };
797
- function detectColorSupport() {
798
- return true;
799
- }
800
- function createStyler() {
801
- const styler = {};
802
- styler.supportsColor = detectColorSupport();
803
- function createStyleFunction(styleName, styles = []) {
804
- const styleList = styleName === "" ? [] : [...styles, styleName];
805
- const fn = function(text) {
806
- if (!styler.supportsColor)
807
- return text;
808
- let openCodes = "";
809
- let closeCodes = "";
810
- for (const style of styleList) {
811
- if (style in theme && theme[style] in codes) {
812
- const themeStyle = theme[style];
813
- openCodes += codes[themeStyle][0];
814
- closeCodes = codes[themeStyle][1] + closeCodes;
815
- } else if (style in codes) {
816
- openCodes += codes[style][0];
817
- closeCodes = codes[style][1] + closeCodes;
818
- }
819
- }
820
- return openCodes + text + closeCodes;
821
- };
822
- const allStyles2 = [...Object.keys(codes), ...Object.keys(theme)];
823
- for (const style of allStyles2) {
824
- if (!(style in fn)) {
825
- Object.defineProperty(fn, style, {
826
- get() {
827
- return createStyleFunction(style, styleList);
828
- }
829
- });
830
- }
831
- }
832
- return fn;
833
- }
834
- const allStyles = [...Object.keys(codes), ...Object.keys(theme)];
835
- for (const style of allStyles) {
836
- if (!(style in styler)) {
837
- Object.defineProperty(styler, style, {
838
- get() {
839
- return createStyleFunction(style);
840
- }
841
- });
842
- }
843
- }
844
- return styler;
845
- }
846
- var style = createStyler();
847
- class CLI extends EventEmitter {
848
- name;
849
- commands;
850
- globalCommand;
851
- matchedCommand;
852
- matchedCommandName;
853
- rawArgs;
854
- args;
855
- options;
856
- showHelpOnExit;
857
- showVersionOnExit;
858
- enableDidYouMean = true;
859
- signalHandlersSet = false;
860
- isVerbose = false;
861
- isQuiet = false;
862
- isDebug = false;
863
- isNoInteraction = false;
864
- environment;
865
- isDryRun = false;
866
- isForce = false;
867
- useEmoji = true;
868
- theme;
869
- isNoCache = false;
870
- constructor(name = "") {
871
- super();
872
- this.name = name;
873
- this.commands = [];
874
- this.rawArgs = [];
875
- this.args = [];
876
- this.options = {};
877
- this.globalCommand = new GlobalCommand(this);
878
- this.globalCommand.usage("<command> [options]");
879
- }
880
- handleSignals(cleanup) {
881
- if (this.signalHandlersSet) {
882
- return this;
883
- }
884
- const handleSignal = async (signal) => {
885
- console.log(`
886
-
887
- Received ${signal}, cleaning up...`);
888
- if (cleanup) {
889
- try {
890
- await cleanup();
891
- } catch (error) {
892
- console.error("Error during cleanup:", error);
893
- }
894
- }
895
- process5.exit(0);
896
- };
897
- process5.on("SIGINT", () => handleSignal("SIGINT"));
898
- process5.on("SIGTERM", () => handleSignal("SIGTERM"));
899
- this.signalHandlersSet = true;
900
- return this;
901
- }
902
- didYouMean(enabled = true) {
903
- this.enableDidYouMean = enabled;
904
- return this;
905
- }
906
- verbose() {
907
- this.globalCommand.option("-v, --verbose", "Enable verbose output");
908
- return this;
909
- }
910
- quiet() {
911
- this.globalCommand.option("-q, --quiet", "Suppress non-essential output");
912
- return this;
913
- }
914
- debug() {
915
- this.globalCommand.option("--debug", "Enable debug mode with detailed error information");
916
- return this;
917
- }
918
- noInteraction() {
919
- this.globalCommand.option("-n, --no-interaction", "Do not ask any interactive questions (for CI/CD)");
920
- return this;
921
- }
922
- env() {
923
- this.globalCommand.option("--env <environment>", "Target environment (e.g., production, staging, local)");
924
- return this;
925
- }
926
- dryRun() {
927
- this.globalCommand.option("--dry-run", "Preview actions without executing them");
928
- return this;
929
- }
930
- force() {
931
- this.globalCommand.option("-f, --force", "Skip confirmation prompts");
932
- return this;
933
- }
934
- emoji() {
935
- this.globalCommand.option("--no-emoji", "Disable emoji in output");
936
- return this;
937
- }
938
- themes() {
939
- this.globalCommand.option("--theme <theme>", "Color theme (default, dracula, nord, solarized, monokai)");
940
- return this;
941
- }
942
- cache() {
943
- this.globalCommand.option("--no-cache", "Disable caching");
944
- return this;
945
- }
946
- usage(text) {
947
- this.globalCommand.usage(text);
948
- return this;
949
- }
950
- command(rawName, description, config) {
951
- if (!config) {
952
- config = {};
953
- }
954
- const command = new Command_default(rawName, description || "", config, this);
955
- command.globalCommand = this.globalCommand;
956
- this.commands.push(command);
957
- return command;
958
- }
959
- option(rawName, description, config) {
960
- this.globalCommand.option(rawName, description, config);
961
- return this;
962
- }
963
- help(callback) {
964
- this.globalCommand.option("-h, --help", "Display this message");
965
- this.globalCommand.helpCallback = callback;
966
- this.showHelpOnExit = true;
967
- return this;
968
- }
969
- version(version, customFlags = "-v, --version") {
970
- this.globalCommand.version(version, customFlags);
971
- this.showVersionOnExit = true;
972
- return this;
973
- }
974
- example(example) {
975
- this.globalCommand.example(example);
976
- return this;
977
- }
978
- outputHelp() {
979
- if (this.matchedCommand) {
980
- this.matchedCommand.outputHelp();
981
- } else {
982
- this.globalCommand.outputHelp();
983
- }
984
- }
985
- outputVersion() {
986
- this.globalCommand.outputVersion();
987
- }
988
- setParsedInfo({ args, options }, matchedCommand, matchedCommandName) {
989
- this.args = args;
990
- this.options = options;
991
- if (matchedCommand) {
992
- this.matchedCommand = matchedCommand;
993
- }
994
- if (matchedCommandName) {
995
- this.matchedCommandName = matchedCommandName;
996
- }
997
- return this;
998
- }
999
- unsetMatchedCommand() {
1000
- this.matchedCommand = undefined;
1001
- this.matchedCommandName = undefined;
1002
- }
1003
- showCommandNotFound(input) {
1004
- console.log(style.red(`
1005
- \u2717 Command "${input}" not found.
1006
- `));
1007
- if (this.enableDidYouMean) {
1008
- const allCommandNames = [];
1009
- for (const command of this.commands) {
1010
- if (command.displayName) {
1011
- allCommandNames.push(command.displayName);
1012
- }
1013
- if (command.aliasNames) {
1014
- allCommandNames.push(...command.aliasNames);
1015
- }
1016
- }
1017
- const suggestions = findSimilarCommands(input, allCommandNames);
1018
- if (suggestions.length > 0) {
1019
- console.log(style.yellow("Did you mean one of these?"));
1020
- suggestions.forEach((cmd) => console.log(` ${style.dim("\u2022")} ${this.name} ${cmd}`));
1021
- console.log("");
1022
- }
1023
- }
1024
- console.log(style.dim("Run"), `${this.name} --help`, style.dim("to see all available commands"));
1025
- process5.exit(1);
1026
- }
1027
- async parse(argv = processArgs2, options = {}) {
1028
- let { run = true, exitOnError = false } = options;
1029
- if (exitOnError) {
1030
- try {
1031
- return await this.parse(argv, { run });
1032
- } catch (err) {
1033
- this.handleUsageError(err);
1034
- throw err;
1035
- }
1036
- }
1037
- this.rawArgs = argv;
1038
- if (!this.name) {
1039
- this.name = argv[1] ? getFileName(argv[1]) : "cli";
1040
- }
1041
- let shouldParse = true;
1042
- const slicedArgv = argv.slice(2);
1043
- const candidateName = slicedArgv[0];
1044
- if (candidateName && !candidateName.startsWith("-")) {
1045
- for (const command of this.commands) {
1046
- if (command.isMatched(candidateName)) {
1047
- const parsed = this.mri(slicedArgv, command);
1048
- shouldParse = false;
1049
- const parsedInfo = {
1050
- ...parsed,
1051
- args: parsed.args.slice(1)
1052
- };
1053
- this.setParsedInfo(parsedInfo, command, candidateName);
1054
- this.emit(`command:${candidateName}`, command);
1055
- break;
1056
- }
1057
- }
1058
- }
1059
- if (shouldParse) {
1060
- for (const command of this.commands) {
1061
- if (command.name === "") {
1062
- shouldParse = false;
1063
- const parsed = this.mri(slicedArgv, command);
1064
- this.setParsedInfo(parsed, command);
1065
- this.emit(`command:!`, command);
1066
- break;
1067
- }
1068
- }
1069
- }
1070
- if (shouldParse) {
1071
- const parsed = this.mri(argv.slice(2));
1072
- this.setParsedInfo(parsed);
1073
- }
1074
- if (this.options.verbose) {
1075
- this.isVerbose = true;
1076
- }
1077
- if (this.options.quiet) {
1078
- this.isQuiet = true;
1079
- }
1080
- if (this.options.debug) {
1081
- this.isDebug = true;
1082
- }
1083
- if (this.options.noInteraction) {
1084
- this.isNoInteraction = true;
1085
- }
1086
- if (this.options.env) {
1087
- this.environment = String(this.options.env);
1088
- }
1089
- if (this.options.dryRun) {
1090
- this.isDryRun = true;
1091
- }
1092
- if (this.options.force) {
1093
- this.isForce = true;
1094
- }
1095
- if (this.options.noEmoji !== undefined) {
1096
- this.useEmoji = !this.options.noEmoji;
1097
- }
1098
- if (this.options.theme) {
1099
- this.theme = String(this.options.theme);
1100
- }
1101
- if (this.options.noCache !== undefined) {
1102
- this.isNoCache = Boolean(this.options.noCache);
1103
- }
1104
- if (this.options.help && this.showHelpOnExit) {
1105
- this.outputHelp();
1106
- run = false;
1107
- this.unsetMatchedCommand();
1108
- }
1109
- if (this.options.version && this.showVersionOnExit && this.matchedCommandName == null) {
1110
- this.outputVersion();
1111
- run = false;
1112
- this.unsetMatchedCommand();
1113
- }
1114
- const parsedArgv = { args: this.args, options: this.options };
1115
- if (run) {
1116
- await this.runMatchedCommand();
1117
- }
1118
- if (!this.matchedCommand && this.args[0]) {
1119
- this.emit("command:*");
1120
- const hasWildcardListener = this.listenerCount("command:*") > 0;
1121
- if (!hasWildcardListener) {
1122
- this.showCommandNotFound(this.args[0]);
1123
- }
1124
- }
1125
- return parsedArgv;
1126
- }
1127
- mri(argv, command) {
1128
- const cliOptions = [
1129
- ...this.globalCommand.options,
1130
- ...command ? command.options : []
1131
- ];
1132
- const mriOptions = getMriOptions(cliOptions);
1133
- let argsAfterDoubleDashes = [];
1134
- const doubleDashesIndex = argv.indexOf("--");
1135
- if (doubleDashesIndex > -1) {
1136
- argsAfterDoubleDashes = argv.slice(doubleDashesIndex + 1);
1137
- argv = argv.slice(0, doubleDashesIndex);
1138
- }
1139
- const raw = parseArgv(argv, mriOptions);
1140
- const parsed = { _: raw._ };
1141
- for (const name of Object.keys(raw)) {
1142
- if (name !== "_") {
1143
- parsed[camelcaseOptionName(name)] = raw[name];
1144
- }
1145
- }
1146
- const args = parsed._;
1147
- const options = {
1148
- "--": argsAfterDoubleDashes
1149
- };
1150
- const ignoreDefault = command && command.config.ignoreOptionDefaultValue ? command.config.ignoreOptionDefaultValue : this.globalCommand.config.ignoreOptionDefaultValue;
1151
- const transforms = Object.create(null);
1152
- for (const cliOption of cliOptions) {
1153
- if (!ignoreDefault && cliOption.config.default !== undefined) {
1154
- for (const name of cliOption.names) {
1155
- options[name] = cliOption.config.default;
1156
- }
1157
- }
1158
- if (Array.isArray(cliOption.config.type)) {
1159
- if (transforms[cliOption.name] === undefined) {
1160
- transforms[cliOption.name] = {
1161
- shouldTransform: true,
1162
- transformFunction: cliOption.config.type[0]
1163
- };
1164
- }
1165
- }
1166
- }
1167
- for (const key of Object.keys(parsed)) {
1168
- if (key !== "_") {
1169
- const keys = key.split(".");
1170
- setDotProp(options, keys, parsed[key]);
1171
- setByType(options, transforms);
1172
- }
1173
- }
1174
- return {
1175
- args,
1176
- options
1177
- };
1178
- }
1179
- async run(argv = processArgs2) {
1180
- return this.parse(argv, { run: true, exitOnError: true });
1181
- }
1182
- handleUsageError(err) {
1183
- const isClappError = !!err && typeof err === "object" && err.name === "ClappError";
1184
- const isUsage = isClappError && err.isUsageError !== false;
1185
- if (!isUsage)
1186
- return;
1187
- const e = err;
1188
- const raw = e.message ?? "command-line error";
1189
- const label = this.name ? `${this.name}: ` : "";
1190
- const suffix = /--help/.test(raw) ? "" : `
1191
- Run \`${this.name ?? "cli"} --help\` for usage.`;
1192
- process5.stderr.write(`${label}${raw}${suffix}
1193
- `);
1194
- process5.exit(e.exitCode ?? 2);
1195
- }
1196
- async runMatchedCommand() {
1197
- const { args, options, matchedCommand: command } = this;
1198
- if (!command || !command.commandAction)
1199
- return;
1200
- command.checkUnknownOptions();
1201
- command.checkOptionValue();
1202
- command.checkRequiredArgs();
1203
- const actionArgs = [];
1204
- command.args.forEach((arg, index) => {
1205
- if (arg.variadic) {
1206
- actionArgs.push(args.slice(index));
1207
- } else {
1208
- actionArgs.push(args[index]);
1209
- }
1210
- });
1211
- actionArgs.push(options);
1212
- const context = {
1213
- command,
1214
- args: actionArgs,
1215
- options
1216
- };
1217
- for (const hook of command.beforeHooks) {
1218
- await hook(context);
1219
- }
1220
- let actionResult;
1221
- const executeAction = async () => {
1222
- const result = command.commandAction.apply(this, actionArgs);
1223
- if (result instanceof Promise) {
1224
- actionResult = await result;
1225
- } else {
1226
- actionResult = result;
1227
- }
1228
- return actionResult;
1229
- };
1230
- if (command.middleware.length > 0) {
1231
- let index = 0;
1232
- const next = async () => {
1233
- if (index < command.middleware.length) {
1234
- const middleware2 = command.middleware[index++];
1235
- await middleware2({ ...context, next });
1236
- } else {
1237
- await executeAction();
1238
- }
1239
- };
1240
- await next();
1241
- } else {
1242
- await executeAction();
1243
- }
1244
- for (const hook of command.afterHooks) {
1245
- await hook(context);
1246
- }
1247
- return actionResult;
1248
- }
1249
- removeSignalHandlers() {
1250
- if (!this.signalHandlersSet) {
1251
- return this;
1252
- }
1253
- process5.removeAllListeners("SIGINT");
1254
- process5.removeAllListeners("SIGTERM");
1255
- this.signalHandlersSet = false;
1256
- return this;
1257
- }
1258
- destroy() {
1259
- this.removeSignalHandlers();
1260
- this.commands = [];
1261
- this.rawArgs = [];
1262
- this.args = [];
1263
- this.options = {};
1264
- this.matchedCommand = undefined;
1265
- this.matchedCommandName = undefined;
1266
- this.removeAllListeners();
1267
- }
1268
- }
1269
- class CLICache {
1270
- cache;
1271
- enabled;
1272
- cleanupInterval = null;
1273
- hits = 0;
1274
- misses = 0;
1275
- constructor() {
1276
- this.cache = new Map;
1277
- this.enabled = true;
1278
- this.startCleanupInterval();
1279
- }
1280
- startCleanupInterval() {
1281
- if (this.cleanupInterval) {
1282
- return;
1283
- }
1284
- this.cleanupInterval = setInterval(() => {
1285
- this.cleanup();
1286
- }, 30000);
1287
- this.cleanupInterval.unref();
1288
- }
1289
- stopCleanup() {
1290
- if (this.cleanupInterval) {
1291
- clearInterval(this.cleanupInterval);
1292
- this.cleanupInterval = null;
1293
- }
1294
- }
1295
- isEnabled() {
1296
- return this.enabled;
1297
- }
1298
- get(key) {
1299
- if (!this.enabled) {
1300
- this.misses++;
1301
- return;
1302
- }
1303
- const entry = this.cache.get(key);
1304
- if (!entry) {
1305
- this.misses++;
1306
- return;
1307
- }
1308
- const now = Date.now();
1309
- if (now - entry.timestamp > entry.ttl) {
1310
- this.cache.delete(key);
1311
- this.misses++;
1312
- return;
1313
- }
1314
- this.hits++;
1315
- return entry.value;
1316
- }
1317
- set(key, value, ttl = 5000) {
1318
- if (!this.enabled) {
1319
- return;
1320
- }
1321
- this.cache.set(key, {
1322
- value,
1323
- timestamp: Date.now(),
1324
- ttl
1325
- });
1326
- }
1327
- has(key) {
1328
- if (!this.enabled) {
1329
- return false;
1330
- }
1331
- const entry = this.cache.get(key);
1332
- if (!entry) {
1333
- return false;
1334
- }
1335
- const now = Date.now();
1336
- if (now - entry.timestamp > entry.ttl) {
1337
- this.cache.delete(key);
1338
- return false;
1339
- }
1340
- return true;
1341
- }
1342
- delete(key) {
1343
- this.cache.delete(key);
1344
- }
1345
- clear() {
1346
- this.cache.clear();
1347
- }
1348
- disable() {
1349
- this.enabled = false;
1350
- this.clear();
1351
- }
1352
- enable() {
1353
- this.enabled = true;
1354
- }
1355
- stats() {
1356
- return {
1357
- size: this.cache.size,
1358
- enabled: this.enabled,
1359
- hits: this.hits,
1360
- misses: this.misses
1361
- };
1362
- }
1363
- resetStats() {
1364
- this.hits = 0;
1365
- this.misses = 0;
1366
- }
1367
- keys() {
1368
- return Array.from(this.cache.keys());
1369
- }
1370
- cleanup() {
1371
- const now = Date.now();
1372
- for (const [key, entry] of this.cache.entries()) {
1373
- if (now - entry.timestamp > entry.ttl) {
1374
- this.cache.delete(key);
1375
- }
1376
- }
1377
- }
1378
- destroy() {
1379
- this.stopCleanup();
1380
- this.clear();
1381
- this.resetStats();
1382
- }
1383
- }
1384
- var cliCache = new CLICache;
1385
- function detectColorSupport2() {
1386
- if ("FORCE_COLOR" in process7.env) {
1387
- return process7.env.FORCE_COLOR !== "0";
1388
- }
1389
- if ("NO_COLOR" in process7.env || process7.env.TERM === "dumb") {
1390
- return false;
1391
- }
1392
- if (process7.platform === "win32") {
1393
- return true;
1394
- }
1395
- return tty.isatty(1) && tty.isatty(2);
1396
- }
1397
- var enabled = detectColorSupport2();
1398
- function wrap(open, close) {
1399
- if (!enabled)
1400
- return (text) => text;
1401
- return (text) => open + text + close;
1402
- }
1403
- var reset = wrap("\x1B[0m", "\x1B[0m");
1404
- var red = wrap("\x1B[31m", "\x1B[39m");
1405
- var green = wrap("\x1B[32m", "\x1B[39m");
1406
- var yellow = wrap("\x1B[33m", "\x1B[39m");
1407
- var blue = wrap("\x1B[34m", "\x1B[39m");
1408
- var magenta = wrap("\x1B[35m", "\x1B[39m");
1409
- var cyan = wrap("\x1B[36m", "\x1B[39m");
1410
- var white = wrap("\x1B[37m", "\x1B[39m");
1411
- var gray = wrap("\x1B[90m", "\x1B[39m");
1412
- var bold = wrap("\x1B[1m", "\x1B[22m");
1413
- var italic = wrap("\x1B[3m", "\x1B[23m");
1414
- var underline = wrap("\x1B[4m", "\x1B[24m");
1415
- var dim = wrap("\x1B[2m", "\x1B[22m");
1416
- var inverse = wrap("\x1B[7m", "\x1B[27m");
1417
- var hidden = wrap("\x1B[8m", "\x1B[28m");
1418
- var strikethrough = wrap("\x1B[9m", "\x1B[29m");
1419
- var bgRed = wrap("\x1B[41m", "\x1B[49m");
1420
- var bgGreen = wrap("\x1B[42m", "\x1B[49m");
1421
- var bgYellow = wrap("\x1B[43m", "\x1B[49m");
1422
- var bgBlue = wrap("\x1B[44m", "\x1B[49m");
1423
- var bgMagenta = wrap("\x1B[45m", "\x1B[49m");
1424
- var bgCyan = wrap("\x1B[46m", "\x1B[49m");
1425
- var bgWhite = wrap("\x1B[47m", "\x1B[49m");
1426
- var isColorSupported = enabled;
1427
- var colors = {
1428
- reset,
1429
- red,
1430
- green,
1431
- yellow,
1432
- blue,
1433
- magenta,
1434
- cyan,
1435
- white,
1436
- gray,
1437
- bold,
1438
- italic,
1439
- underline,
1440
- dim,
1441
- inverse,
1442
- hidden,
1443
- strikethrough,
1444
- bgRed,
1445
- bgGreen,
1446
- bgYellow,
1447
- bgBlue,
1448
- bgMagenta,
1449
- bgCyan,
1450
- bgWhite,
1451
- isColorSupported
1452
- };
1453
- var colors_default = colors;
1454
- var actions = ["up", "down", "left", "right", "space", "enter", "cancel"];
1455
- var settings = {
1456
- actions: new Set(actions),
1457
- aliases: new Map([
1458
- ["k", "up"],
1459
- ["j", "down"],
1460
- ["h", "left"],
1461
- ["l", "right"],
1462
- ["\x03", "cancel"],
1463
- ["escape", "cancel"]
1464
- ]),
1465
- messages: {
1466
- cancel: "Canceled",
1467
- error: "Something went wrong"
1468
- }
1469
- };
1470
- function isActionKey(key, action) {
1471
- if (typeof key === "string") {
1472
- return settings.aliases.get(key) === action;
1473
- }
1474
- for (const value of key) {
1475
- if (value === undefined)
1476
- continue;
1477
- if (isActionKey(value, action)) {
1478
- return true;
1479
- }
1480
- }
1481
- return false;
1482
- }
1483
- function diffLines(a, b) {
1484
- if (a === b)
1485
- return [];
1486
- const aLines = a.split(`
1487
- `);
1488
- const bLines = b.split(`
1489
- `);
1490
- const diff = [];
1491
- for (let i = 0;i < Math.max(aLines.length, bLines.length); i++) {
1492
- if (aLines[i] !== bLines[i])
1493
- diff.push(i);
1494
- }
1495
- return diff;
1496
- }
1497
- var isWindows = process8.platform.startsWith("win");
1498
- var CANCEL_SYMBOL = Symbol("clapp:cancel");
1499
- function setRawMode(input, value) {
1500
- const i = input;
1501
- if (i.isTTY)
1502
- i.setRawMode(value);
1503
- }
1504
- function stripAnsi(str) {
1505
- return str.replace(/\x1b\[[0-9;]*m/g, "");
1506
- }
1507
- function stringWidth(str) {
1508
- return stripAnsi(str).length;
1509
- }
1510
- function wrapAnsi(text, columns, options) {
1511
- if (!columns || columns < 1)
1512
- return text;
1513
- const hard = options?.hard ?? false;
1514
- const trim = options?.trim ?? true;
1515
- const lines = text.split(`
1516
- `);
1517
- const result = [];
1518
- for (const line of lines) {
1519
- if (stringWidth(line) <= columns) {
1520
- result.push(trim ? line.trimEnd() : line);
1521
- continue;
1522
- }
1523
- if (hard) {
1524
- let current = "";
1525
- let currentWidth = 0;
1526
- let i = 0;
1527
- while (i < line.length) {
1528
- const ansiMatch = line.slice(i).match(/^\x1b\[[0-9;]*m/);
1529
- if (ansiMatch) {
1530
- current += ansiMatch[0];
1531
- i += ansiMatch[0].length;
1532
- continue;
1533
- }
1534
- if (currentWidth >= columns) {
1535
- result.push(trim ? current.trimEnd() : current);
1536
- current = "";
1537
- currentWidth = 0;
1538
- }
1539
- current += line[i];
1540
- currentWidth++;
1541
- i++;
1542
- }
1543
- if (current) {
1544
- result.push(trim ? current.trimEnd() : current);
1545
- }
1546
- } else {
1547
- result.push(trim ? line.trimEnd() : line);
1548
- }
1549
- }
1550
- return result.join(`
1551
- `);
1552
- }
1553
-
1554
- class Prompt {
1555
- input;
1556
- output;
1557
- _abortSignal;
1558
- rl;
1559
- opts;
1560
- _render;
1561
- _track = false;
1562
- _prevFrame = "";
1563
- _subscribers = new Map;
1564
- _cursor = 0;
1565
- _manualLine = "";
1566
- state = "initial";
1567
- error = "";
1568
- value;
1569
- userInput = "";
1570
- constructor(options, trackValue = true) {
1571
- const { input = stdin2, output = stdout2, render, signal, ...opts } = options;
1572
- this.opts = opts;
1573
- this.onKeypress = this.onKeypress.bind(this);
1574
- this.close = this.close.bind(this);
1575
- this.render = this.render.bind(this);
1576
- this._render = render.bind(this);
1577
- this._track = trackValue;
1578
- this._abortSignal = signal;
1579
- this.input = input;
1580
- this.output = output;
1581
- }
1582
- unsubscribe() {
1583
- this._subscribers.clear();
1584
- }
1585
- setSubscriber(event, opts) {
1586
- const params = this._subscribers.get(event) ?? [];
1587
- params.push(opts);
1588
- this._subscribers.set(event, params);
1589
- }
1590
- on(event, cb) {
1591
- this.setSubscriber(event, { cb });
1592
- return this;
1593
- }
1594
- once(event, cb) {
1595
- this.setSubscriber(event, { cb, once: true });
1596
- return this;
1597
- }
1598
- emit(event, ...data) {
1599
- const cbs = this._subscribers.get(event) ?? [];
1600
- const cleanup = [];
1601
- for (const subscriber of cbs) {
1602
- subscriber.cb(...data);
1603
- if (subscriber.once) {
1604
- cleanup.push(() => cbs.splice(cbs.indexOf(subscriber), 1));
1605
- }
1606
- }
1607
- for (const cb of cleanup) {
1608
- cb();
1609
- }
1610
- return this;
1611
- }
1612
- prompt() {
1613
- return new Promise((resolve) => {
1614
- if (this._abortSignal) {
1615
- if (this._abortSignal.aborted) {
1616
- this.state = "cancel";
1617
- this.close();
1618
- return resolve(CANCEL_SYMBOL);
1619
- }
1620
- this._abortSignal.addEventListener("abort", () => {
1621
- this.state = "cancel";
1622
- this.close();
1623
- }, { once: true });
1624
- }
1625
- this.rl = readline2.createInterface({
1626
- input: this.input,
1627
- tabSize: 2,
1628
- prompt: "",
1629
- escapeCodeTimeout: 50,
1630
- terminal: true
1631
- });
1632
- this.rl.prompt();
1633
- if (this.opts.initialUserInput !== undefined) {
1634
- this._setUserInput(this.opts.initialUserInput, true);
1635
- }
1636
- this.input.on("keypress", this.onKeypress);
1637
- setRawMode(this.input, true);
1638
- this.output.on("resize", this.render);
1639
- this.render();
1640
- this.once("submit", () => {
1641
- this.output.write(cursor.show);
1642
- this.output.off("resize", this.render);
1643
- setRawMode(this.input, false);
1644
- resolve(this.value);
1645
- });
1646
- this.once("cancel", () => {
1647
- this.output.write(cursor.show);
1648
- this.output.off("resize", this.render);
1649
- setRawMode(this.input, false);
1650
- resolve(CANCEL_SYMBOL);
1651
- });
1652
- });
1653
- }
1654
- _isActionKey(char, _key) {
1655
- return char === "\t";
1656
- }
1657
- _setValue(value) {
1658
- this.value = value;
1659
- this.emit("value", this.value);
1660
- }
1661
- _setUserInput(value, write) {
1662
- this.userInput = value ?? "";
1663
- this.emit("userInput", this.userInput);
1664
- if (write && this._track && this.rl) {
1665
- this.rl.write(this.userInput);
1666
- this._cursor = this.rl.cursor;
1667
- }
1668
- }
1669
- onKeypress(char, key) {
1670
- if (this._track && key.name !== "return") {
1671
- if (key.name && this._isActionKey(char, key)) {
1672
- this.rl?.write(null, { ctrl: true, name: "h" });
1673
- }
1674
- this._cursor = this.rl?.cursor ?? 0;
1675
- const isSpecialKey = key.name === "tab" || key.name === "escape" || key.name === "backspace" || key.name === "delete" || key.name === "enter" || key.name === "return" || key.name && ["up", "down", "left", "right"].includes(key.name);
1676
- if (char && !isSpecialKey && char.length === 1 && char >= " ") {
1677
- this._manualLine += char;
1678
- } else if (key.name === "backspace" && this._manualLine.length > 0) {
1679
- this._manualLine = this._manualLine.slice(0, -1);
1680
- }
1681
- const effectiveLine = this._manualLine.length >= (this.rl?.line?.length || 0) ? this._manualLine : this.rl?.line;
1682
- this._setUserInput(effectiveLine);
1683
- }
1684
- if (this.state === "error") {
1685
- this.state = "active";
1686
- this.error = "";
1687
- }
1688
- if (key?.name) {
1689
- if (!this._track && settings.aliases.has(key.name)) {
1690
- this.emit("cursor", settings.aliases.get(key.name));
1691
- }
1692
- if (settings.actions.has(key.name)) {
1693
- this.emit("cursor", key.name);
1694
- }
1695
- }
1696
- if (char && (char.toLowerCase() === "y" || char.toLowerCase() === "n")) {
1697
- this.emit("confirm", char.toLowerCase() === "y");
1698
- }
1699
- this.emit("key", char?.toLowerCase(), key);
1700
- if (key?.name === "return") {
1701
- if (this.opts.validate) {
1702
- const problem = this.opts.validate(this.value);
1703
- if (problem) {
1704
- this.error = problem instanceof Error ? problem.message : problem;
1705
- this.state = "error";
1706
- }
1707
- }
1708
- if (this.state !== "error") {
1709
- this.state = "submit";
1710
- }
1711
- }
1712
- if (isActionKey([char, key?.name, key?.sequence], "cancel")) {
1713
- this.state = "cancel";
1714
- }
1715
- if (this.state === "submit" || this.state === "cancel") {
1716
- this.emit("finalize");
1717
- }
1718
- this.render();
1719
- if (this.state === "submit" || this.state === "cancel") {
1720
- this.close();
1721
- }
1722
- }
1723
- close() {
1724
- this.input.unpipe();
1725
- this.input.removeListener("keypress", this.onKeypress);
1726
- this.output.write(`
1727
- `);
1728
- setRawMode(this.input, false);
1729
- this.rl?.close();
1730
- this.rl = undefined;
1731
- this.emit(`${this.state}`, this.value);
1732
- if (this.state === "cancel") {
1733
- setTimeout(() => {
1734
- this.unsubscribe();
1735
- }, 10);
1736
- } else {
1737
- this.unsubscribe();
1738
- }
1739
- }
1740
- restoreCursor() {
1741
- const lines = wrapAnsi(this._prevFrame, process9.stdout.columns, { hard: true, trim: false }).split(`
1742
- `).length - 1;
1743
- this.output.write(cursor.move(-999, lines * -1));
1744
- }
1745
- render() {
1746
- const frame = wrapAnsi(this._render(this) ?? "", process9.stdout.columns, {
1747
- hard: true,
1748
- trim: false
1749
- });
1750
- if (frame === this._prevFrame) {
1751
- return;
1752
- }
1753
- if (this.state === "initial") {
1754
- this.output.write(cursor.hide);
1755
- } else {
1756
- const diff = diffLines(this._prevFrame, frame);
1757
- this.restoreCursor();
1758
- if (diff && diff?.length === 1) {
1759
- const diffLine = diff[0];
1760
- this.output.write(cursor.move(0, diffLine));
1761
- this.output.write(erase.lines(1));
1762
- const lines = frame.split(`
1763
- `);
1764
- this.output.write(lines[diffLine]);
1765
- this._prevFrame = frame;
1766
- this.output.write(cursor.move(0, lines.length - diffLine - 1));
1767
- return;
1768
- }
1769
- if (diff && diff?.length > 1) {
1770
- const diffLine = diff[0];
1771
- this.output.write(cursor.move(0, diffLine));
1772
- this.output.write(erase.down());
1773
- const lines = frame.split(`
1774
- `);
1775
- const newLines = lines.slice(diffLine);
1776
- this.output.write(newLines.join(`
1777
- `));
1778
- this._prevFrame = frame;
1779
- return;
1780
- }
1781
- this.output.write(erase.down());
1782
- }
1783
- this.output.write(frame);
1784
- if (this.state === "initial") {
1785
- this.state = "active";
1786
- }
1787
- this._prevFrame = frame;
1788
- }
1789
- }
1790
- function getCursorForValue(selected, items) {
1791
- if (selected === undefined) {
1792
- return 0;
1793
- }
1794
- const currLength = items.length;
1795
- if (currLength === 0) {
1796
- return 0;
1797
- }
1798
- const index = items.findIndex((item) => item.value === selected);
1799
- return index !== -1 ? index : 0;
1800
- }
1801
- function defaultFilter(input, option) {
1802
- const label = option.label ?? String(option.value);
1803
- return label.toLowerCase().includes(input.toLowerCase());
1804
- }
1805
- function normalisedValue(multiple, values) {
1806
- if (!values) {
1807
- return;
1808
- }
1809
- if (multiple) {
1810
- return values;
1811
- }
1812
- return values[0];
1813
- }
1814
-
1815
- class AutocompletePrompt extends Prompt {
1816
- filteredOptions;
1817
- multiple;
1818
- isNavigating = false;
1819
- selectedValues = [];
1820
- focusedValue;
1821
- #cursor = 0;
1822
- #lastUserInput = "";
1823
- #filterFn;
1824
- #options;
1825
- get cursor() {
1826
- return this.#cursor;
1827
- }
1828
- get userInputWithCursor() {
1829
- if (!this.userInput) {
1830
- return colors_default.inverse(colors_default.hidden("_"));
1831
- }
1832
- if (this._cursor >= this.userInput.length) {
1833
- return `${this.userInput}\u2588`;
1834
- }
1835
- const s1 = this.userInput.slice(0, this._cursor);
1836
- const [s2, ...s3] = this.userInput.slice(this._cursor);
1837
- return `${s1}${colors_default.inverse(s2)}${s3.join("")}`;
1838
- }
1839
- get options() {
1840
- if (typeof this.#options === "function") {
1841
- return this.#options();
1842
- }
1843
- return this.#options;
1844
- }
1845
- constructor(opts) {
1846
- super(opts);
1847
- this.#options = opts.options;
1848
- const options = this.options;
1849
- this.filteredOptions = [...options];
1850
- this.multiple = opts.multiple === true;
1851
- this.#filterFn = opts.filter ?? defaultFilter;
1852
- let initialValues;
1853
- if (opts.initialValue && Array.isArray(opts.initialValue)) {
1854
- if (this.multiple) {
1855
- initialValues = opts.initialValue;
1856
- } else {
1857
- initialValues = opts.initialValue.slice(0, 1);
1858
- }
1859
- } else {
1860
- if (!this.multiple && this.options.length > 0) {
1861
- initialValues = [this.options[0].value];
1862
- }
1863
- }
1864
- if (initialValues) {
1865
- for (const selectedValue of initialValues) {
1866
- const selectedIndex = options.findIndex((opt) => opt.value === selectedValue);
1867
- if (selectedIndex !== -1) {
1868
- this.toggleSelected(selectedValue);
1869
- this.#cursor = selectedIndex;
1870
- }
1871
- }
1872
- }
1873
- this.focusedValue = this.options[this.#cursor]?.value;
1874
- this.on("key", (char, key) => this.#onKey(char, key));
1875
- this.on("userInput", (value) => this.#onUserInputChanged(value));
1876
- }
1877
- _isActionKey(char, key) {
1878
- return char === "\t" || this.multiple && this.isNavigating && key.name === "space" && char !== undefined && char !== "";
1879
- }
1880
- #onKey(_char, key) {
1881
- const isUpKey = key.name === "up";
1882
- const isDownKey = key.name === "down";
1883
- const isReturnKey = key.name === "return";
1884
- if (isUpKey || isDownKey) {
1885
- this.#cursor = Math.max(0, Math.min(this.#cursor + (isUpKey ? -1 : 1), this.filteredOptions.length - 1));
1886
- this.focusedValue = this.filteredOptions[this.#cursor]?.value;
1887
- if (!this.multiple) {
1888
- this.selectedValues = [this.focusedValue];
1889
- }
1890
- this.isNavigating = true;
1891
- } else if (isReturnKey) {
1892
- this.value = normalisedValue(this.multiple, this.selectedValues);
1893
- } else {
1894
- if (this.multiple) {
1895
- if (this.focusedValue !== undefined && (key.name === "tab" || this.isNavigating && key.name === "space")) {
1896
- this.toggleSelected(this.focusedValue);
1897
- } else {
1898
- this.isNavigating = false;
1899
- }
1900
- } else {
1901
- if (this.focusedValue) {
1902
- this.selectedValues = [this.focusedValue];
1903
- }
1904
- this.isNavigating = false;
1905
- }
1906
- }
1907
- }
1908
- deselectAll() {
1909
- this.selectedValues = [];
1910
- }
1911
- toggleSelected(value) {
1912
- if (this.filteredOptions.length === 0) {
1913
- return;
1914
- }
1915
- if (this.multiple) {
1916
- if (this.selectedValues.includes(value)) {
1917
- this.selectedValues = this.selectedValues.filter((v) => v !== value);
1918
- } else {
1919
- this.selectedValues = [...this.selectedValues, value];
1920
- }
1921
- } else {
1922
- this.selectedValues = [value];
1923
- }
1924
- }
1925
- #onUserInputChanged(value) {
1926
- if (value !== this.#lastUserInput) {
1927
- this.#lastUserInput = value;
1928
- const options = this.options;
1929
- if (value) {
1930
- this.filteredOptions = options.filter((opt) => this.#filterFn(value, opt));
1931
- } else {
1932
- this.filteredOptions = [...options];
1933
- }
1934
- this.#cursor = getCursorForValue(this.focusedValue, this.filteredOptions);
1935
- this.focusedValue = this.filteredOptions[this.#cursor]?.value;
1936
- if (!this.multiple) {
1937
- if (this.focusedValue !== undefined) {
1938
- this.toggleSelected(this.focusedValue);
1939
- } else {
1940
- this.deselectAll();
1941
- }
1942
- }
1943
- }
1944
- }
1945
- }
1946
- class GroupMultiSelectPrompt extends Prompt {
1947
- options;
1948
- cursor = 0;
1949
- #selectableGroups;
1950
- getGroupItems(group) {
1951
- return this.options.filter((o) => o.group === group);
1952
- }
1953
- isGroupSelected(group) {
1954
- const items = this.getGroupItems(group);
1955
- const value = this.value;
1956
- if (value === undefined) {
1957
- return false;
1958
- }
1959
- return items.every((i) => value.includes(i.value));
1960
- }
1961
- toggleValue() {
1962
- const item = this.options[this.cursor];
1963
- if (this.value === undefined) {
1964
- this.value = [];
1965
- }
1966
- if (item.group === true) {
1967
- const group = String(item.value);
1968
- const groupedItems = this.getGroupItems(group);
1969
- if (this.isGroupSelected(group)) {
1970
- this.value = this.value.filter((v) => groupedItems.findIndex((i) => i.value === v) === -1);
1971
- } else {
1972
- this.value = [...this.value, ...groupedItems.map((i) => i.value)];
1973
- }
1974
- this.value = Array.from(new Set(this.value));
1975
- } else {
1976
- const selected = this.value.includes(item.value);
1977
- this.value = selected ? this.value.filter((v) => v !== item.value) : [...this.value, item.value];
1978
- }
1979
- }
1980
- constructor(opts) {
1981
- super(opts, false);
1982
- const { options } = opts;
1983
- this.#selectableGroups = opts.selectableGroups !== false;
1984
- this.options = Object.entries(options).flatMap(([key, option]) => [
1985
- { value: key, group: true, label: key },
1986
- ...option.map((opt) => ({ ...opt, group: key }))
1987
- ]);
1988
- this.value = [...opts.initialValues ?? []];
1989
- this.cursor = Math.max(this.options.findIndex(({ value }) => value === opts.cursorAt), this.#selectableGroups ? 0 : 1);
1990
- this.on("cursor", (key) => {
1991
- switch (key) {
1992
- case "left":
1993
- case "up": {
1994
- this.cursor = this.cursor === 0 ? this.options.length - 1 : this.cursor - 1;
1995
- const currentIsGroup = this.options[this.cursor]?.group === true;
1996
- if (!this.#selectableGroups && currentIsGroup) {
1997
- this.cursor = this.cursor === 0 ? this.options.length - 1 : this.cursor - 1;
1998
- }
1999
- break;
2000
- }
2001
- case "down":
2002
- case "right": {
2003
- this.cursor = this.cursor === this.options.length - 1 ? 0 : this.cursor + 1;
2004
- const currentIsGroup = this.options[this.cursor]?.group === true;
2005
- if (!this.#selectableGroups && currentIsGroup) {
2006
- this.cursor = this.cursor === this.options.length - 1 ? 0 : this.cursor + 1;
2007
- }
2008
- break;
2009
- }
2010
- case "space":
2011
- this.toggleValue();
2012
- break;
2013
- }
2014
- });
2015
- }
2016
- }
2017
- var unicode = isUnicodeSupported();
2018
- var unicodeOr = (c, fallback) => unicode ? c : fallback;
2019
- var S_STEP_ACTIVE = unicodeOr("\u25C6", "*");
2020
- var S_STEP_CANCEL = unicodeOr("\u25A0", "x");
2021
- var S_STEP_ERROR = unicodeOr("\u25B2", "x");
2022
- var S_STEP_SUBMIT = unicodeOr("\u25C7", "o");
2023
- var S_BAR_START = unicodeOr("\u250C", "T");
2024
- var S_BAR = unicodeOr("\u2502", "|");
2025
- var S_BAR_END = unicodeOr("\u2514", "\u2014");
2026
- var S_RADIO_ACTIVE = unicodeOr("\u25CF", ">");
2027
- var S_RADIO_INACTIVE = unicodeOr("\u25CB", " ");
2028
- var S_CHECKBOX_ACTIVE = unicodeOr("\u25FB", "[\u2022]");
2029
- var S_CHECKBOX_SELECTED = unicodeOr("\u25FC", "[+]");
2030
- var S_CHECKBOX_INACTIVE = unicodeOr("\u25FB", "[ ]");
2031
- var S_PASSWORD_MASK = unicodeOr("\u25AA", "\u2022");
2032
- var S_BAR_H = unicodeOr("\u2500", "-");
2033
- var S_CORNER_TOP_RIGHT = unicodeOr("\u256E", "+");
2034
- var S_CONNECT_LEFT = unicodeOr("\u251C", "+");
2035
- var S_CORNER_BOTTOM_RIGHT = unicodeOr("\u256F", "+");
2036
- var S_INFO = unicodeOr("\u25CF", "\u2022");
2037
- var S_SUCCESS = unicodeOr("\u25C6", "*");
2038
- var S_WARN = unicodeOr("\u25B2", "!");
2039
- var S_ERROR = unicodeOr("\u25A0", "x");
2040
- var S_PROGRESS_CHAR = {
2041
- light: unicodeOr("\u2500", "-"),
2042
- heavy: unicodeOr("\u2501", "="),
2043
- block: unicodeOr("\u2588", "#")
2044
- };
2045
- function getPrefix() {
2046
- return `${colors_default.gray(S_BAR)} `;
2047
- }
2048
- var prefix = getPrefix();
2049
- // package.json
2050
- var version = "0.0.27";
2051
-
2052
- // src/cli/middleware.ts
2053
- import fs2 from "fs/promises";
2054
- import path2 from "path";
2055
- import process6 from "process";
2056
-
2057
- // src/cli/colors.ts
2058
- var colors2 = {
2059
- reset: "\x1B[0m",
2060
- bold: "\x1B[1m",
2061
- dim: "\x1B[2m",
2062
- red: "\x1B[31m",
2063
- green: "\x1B[32m",
2064
- yellow: "\x1B[33m",
2065
- blue: "\x1B[34m",
2066
- cyan: "\x1B[36m",
2067
- white: "\x1B[37m",
2068
- gray: "\x1B[90m"
2069
- };
2070
- var chalk = {
2071
- red: (text) => `${colors2.red}${text}${colors2.reset}`,
2072
- green: (text) => `${colors2.green}${text}${colors2.reset}`,
2073
- yellow: (text) => `${colors2.yellow}${text}${colors2.reset}`,
2074
- blue: (text) => `${colors2.blue}${text}${colors2.reset}`,
2075
- cyan: (text) => `${colors2.cyan}${text}${colors2.reset}`,
2076
- white: (text) => `${colors2.white}${text}${colors2.reset}`,
2077
- gray: (text) => `${colors2.gray}${text}${colors2.reset}`,
2078
- bold: (text) => `${colors2.bold}${text}${colors2.reset}`,
2079
- dim: (text) => `${colors2.dim}${text}${colors2.reset}`,
2080
- hex: (_color) => (text) => text
2081
- };
2082
-
2083
- // src/cli/middleware.ts
2084
- async function generateMiddlewareTypes(outputPath) {
2085
- const middlewareInfo = Object.entries(middleware).map(([key, instance]) => ({
2086
- name: key,
2087
- className: instance.constructor.name
2088
- }));
2089
- const typeContent = `/**
6
+ ${this.stack}`;return this.message}}function a6(){let{env:z}=q6,{TERM:J,TERM_PROGRAM:Z}=z;if(q6.platform!=="win32")return J!=="linux";return Boolean(z.WT_SESSION)||Boolean(z.TERMINUS_SUBLIME)||z.ConEmuTask==="{cmd::Cmder}"||Z==="Terminus-Sublime"||Z==="vscode"||J==="xterm-256color"||J==="alacritty"||J==="rxvt-unicode"||J==="rxvt-unicode-256color"||z.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var h="\x1B",M=`${h}[`;var w={to(z,J){if(!J)return`${M}${z+1}G`;return`${M}${J+1};${z+1}H`},move(z,J){let Z="";if(z<0)Z+=`${M}${-z}D`;else if(z>0)Z+=`${M}${z}C`;if(J<0)Z+=`${M}${-J}A`;else if(J>0)Z+=`${M}${J}B`;return Z},up:(z=1)=>`${M}${z}A`,down:(z=1)=>`${M}${z}B`,forward:(z=1)=>`${M}${z}C`,backward:(z=1)=>`${M}${z}D`,nextLine:(z=1)=>`${M}E`.repeat(z),prevLine:(z=1)=>`${M}F`.repeat(z),left:`${M}G`,hide:`${M}?25l`,show:`${M}?25h`,save:`${h}7`,restore:`${h}8`};var r={screen:`${M}2J`,up:(z=1)=>`${M}1J`.repeat(z),down:(z=1)=>`${M}J`.repeat(z),line:`${M}2K`,lineEnd:`${M}K`,lineStart:`${M}1K`,lines(z){let J="";for(let Z=0;Z<z;Z++)J+=this.line+(Z<z-1?w.up():"");if(z)J+=w.left;return J}},M4={screen:`${h}c`};function r6(z,J){let Z=[];for(let $=0;$<=J.length;$++)Z[$]=[$];for(let $=0;$<=z.length;$++)Z[0][$]=$;for(let $=1;$<=J.length;$++)for(let Q=1;Q<=z.length;Q++)if(J.charAt($-1)===z.charAt(Q-1))Z[$][Q]=Z[$-1][Q-1];else Z[$][Q]=Math.min(Z[$-1][Q-1]+1,Z[$][Q-1]+1,Z[$-1][Q]+1);return Z[J.length][z.length]}function L6(z,J,Z=2,$=3){return J.map((Q)=>({cmd:Q,distance:r6(z,Q)})).filter(({distance:Q})=>Q<=Z).sort((Q,j)=>Q.distance-j.distance).slice(0,$).map(({cmd:Q})=>Q)}class M6{rawName;description;name;names;isBoolean;required;config;negated;constructor(z,J,Z){if(this.rawName=z,this.description=J,this.config=Object.assign({},Z),z=z.replace(/\.\*/g,""),this.negated=!1,this.names=s(z).split(",").map(($)=>{let Q=$.trim().replace(/^-{1,2}/,"");if(Q.startsWith("no-"))this.negated=!0,Q=Q.replace(/^no-/,"");return D6(Q)}).sort(($,Q)=>$.length>Q.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null)this.config.default=!0;if(z.includes("<"))this.required=!0;else if(z.includes("["))this.required=!1;else this.isBoolean=!0}}var O4=t.argv,s6=`${t.platform}-${t.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,G6=_.argv,t6=`${_.platform}-${_.arch} node-${_.version}`;class o{rawName;description;config;cli;options;aliasNames;name;namespace;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;beforeHooks;afterHooks;middleware;constructor(z,J,Z,$){this.rawName=z,this.description=J,this.config=Z,this.cli=$,this.options=[],this.aliasNames=[],this.name=s(z);let Q=s(z),j=Q.indexOf(":");if(j>0)this.namespace=Q.substring(0,j),this.name=Q.substring(j+1);if(this.args=u6(z),this.examples=[],this.beforeHooks=[],this.afterHooks=[],this.middleware=[],!Z)this.config={}}usage(z){return this.usageText=z,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version(z,J="-v, --version"){return this.versionNumber=z,this.option(J,"Display version number"),this}example(z){return this.examples.push(z),this}option(z,J,Z){let $=new M6(z,J,Z);return this.options.push($),this}alias(z){return this.aliasNames.push(z),this}action(z){return this.commandAction=z,this}before(z){return this.beforeHooks.push(z),this}after(z){return this.afterHooks.push(z),this}use(z){return this.middleware.push(z),this}isMatched(z){if(this.aliasNames.includes(z))return!0;if(this.namespace)return`${this.namespace}:${this.name}`===z;return this.name===z}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof e}get displayName(){return this.namespace?`${this.namespace}:${this.name}`:this.name}hasOption(z){return z=z.split(".")[0],!!this.options.find((J)=>{return J.names.includes(z)})}outputHelp(){let{name:z,commands:J}=this.cli,{versionNumber:Z,options:$,helpCallback:Q}=this.cli.globalCommand,j=[{body:`${z}${Z?`/${Z}`:""}`}];if(j.push({title:"Usage",body:` $ ${z} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&J.length>0){let Y=U6(J.map((W)=>W.rawName)),G=new Map,H=[];for(let W of J)if(W.namespace){if(!G.has(W.namespace))G.set(W.namespace,[]);G.get(W.namespace).push(W)}else H.push(W);let K="";if(H.length>0)K+=H.map((W)=>{return` ${a(W.rawName,Y.length)} ${W.description}`}).join(`
7
+ `);let V=Array.from(G.keys()).sort();for(let W of V){let f6=G.get(W);if(K.length>0)K+=`
8
+
9
+ `;K+=` ${W}:
10
+ `,K+=f6.map((j6)=>{return` ${a(j6.rawName,Y.length-2)} ${j6.description}`}).join(`
11
+ `)}j.push({title:"Commands",body:K}),j.push({title:"For more info, run any command with the `--help` flag",body:J.map((W)=>` $ ${z}${W.displayName===""?"":` ${W.displayName}`} --help`).join(`
12
+ `)})}let X=this.isGlobalCommand?$:[...this.options,...$||[]];if(!this.isGlobalCommand&&!this.isDefaultCommand)X=X.filter((Y)=>Y.name!=="version");if(X.length>0){let Y=U6(X.map((G)=>G.rawName));j.push({title:"Options",body:X.map((G)=>{return` ${a(G.rawName,Y.length)} ${G.description} ${G.config.default===void 0?"":`(default: ${G.config.default})`}`}).join(`
13
+ `)})}if(this.examples.length>0)j.push({title:"Examples",body:this.examples.map((Y)=>{if(typeof Y==="function")return Y(z);return Y}).join(`
14
+ `)});if(Q)j=Q(j)||j;console.log(j.map((Y)=>{return Y.title?`${Y.title}:
15
+ ${Y.body}`:Y.body}).join(`
16
+
17
+ `))}outputVersion(){let{name:z}=this.cli,{versionNumber:J}=this.cli.globalCommand;if(J)console.log(`${z}/${J} ${typeof Bun<"u"?s6:t6}`)}checkRequiredArgs(){let z=this.args.filter((J)=>J.required).length;if(this.cli.args.length<z){let Z=this.args.filter((Q)=>Q.required).slice(this.cli.args.length),$=Z.map((Q)=>`<${Q.value}>`).join(" ");throw new y(`Missing required argument${Z.length>1?"s":""}: ${$}
18
+
19
+ Run \`${this.cli.name} ${this.rawName} --help\` for usage information.`)}}checkUnknownOptions(){let{options:z,globalCommand:J}=this.cli;if(!this.config.allowUnknownOptions){for(let Z of Object.keys(z))if(Z!=="--"&&!this.hasOption(Z)&&!J.hasOption(Z)){let Q=[...J.options,...this.options].flatMap((Y)=>Y.names),j=Z.length>1?`--${Z}`:`-${Z}`,q=L6(Z,Q),X=`Unknown option \`${j}\``;if(q.length>0)X+=`
20
+
21
+ Did you mean one of these?`,q.forEach((Y)=>{let G=Y.length>1?`--${Y}`:`-${Y}`;X+=`
22
+ \u2022 ${G}`});throw X+=`
23
+
24
+ Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`,new y(X)}}}checkOptionValue(){let{options:z,globalCommand:J}=this.cli,Z=[...J.options,...this.options];for(let $ of Z){let Q=z[$.name.split(".")[0]];if($.required){let j=Z.some((q)=>q.negated&&q.names.includes($.name));if(Q===!0||Q===!1&&!j)throw new y(`Option \`${$.rawName}\` requires a value.
25
+
26
+ Example: ${this.cli.name} ${this.rawName} ${$.rawName} <value>`)}}}}class e extends o{constructor(z){super("@@global@@","",{},z)}}var o6=o,B={red:["\x1B[31m","\x1B[39m"],green:["\x1B[32m","\x1B[39m"],blue:["\x1B[34m","\x1B[39m"],yellow:["\x1B[33m","\x1B[39m"],cyan:["\x1B[36m","\x1B[39m"],magenta:["\x1B[35m","\x1B[39m"],white:["\x1B[37m","\x1B[39m"],gray:["\x1B[90m","\x1B[39m"],bgRed:["\x1B[41m","\x1B[49m"],bgGreen:["\x1B[42m","\x1B[49m"],bgBlue:["\x1B[44m","\x1B[49m"],bgYellow:["\x1B[43m","\x1B[49m"],bgCyan:["\x1B[46m","\x1B[49m"],bgMagenta:["\x1B[45m","\x1B[49m"],bold:["\x1B[1m","\x1B[22m"],italic:["\x1B[3m","\x1B[23m"],underline:["\x1B[4m","\x1B[24m"],dim:["\x1B[2m","\x1B[22m"],inverse:["\x1B[7m","\x1B[27m"],hidden:["\x1B[8m","\x1B[28m"],strikethrough:["\x1B[9m","\x1B[29m"]};var I={primary:"blue",secondary:"cyan",success:"green",warning:"yellow",error:"red",info:"magenta",muted:"gray"};function e6(){return!0}function zz(){let z={};z.supportsColor=e6();function J($,Q=[]){let j=$===""?[]:[...Q,$],q=function(Y){if(!z.supportsColor)return Y;let G="",H="";for(let K of j)if(K in I&&I[K]in B){let V=I[K];G+=B[V][0],H=B[V][1]+H}else if(K in B)G+=B[K][0],H=B[K][1]+H;return G+Y+H},X=[...Object.keys(B),...Object.keys(I)];for(let Y of X)if(!(Y in q))Object.defineProperty(q,Y,{get(){return J(Y,j)}});return q}let Z=[...Object.keys(B),...Object.keys(I)];for(let $ of Z)if(!($ in z))Object.defineProperty(z,$,{get(){return J($)}});return z}var P=zz();class z6 extends m6{name;commands;globalCommand;matchedCommand;matchedCommandName;rawArgs;args;options;showHelpOnExit;showVersionOnExit;enableDidYouMean=!0;signalHandlersSet=!1;isVerbose=!1;isQuiet=!1;isDebug=!1;isNoInteraction=!1;environment;isDryRun=!1;isForce=!1;useEmoji=!0;theme;isNoCache=!1;constructor(z=""){super();this.name=z,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new e(this),this.globalCommand.usage("<command> [options]")}handleSignals(z){if(this.signalHandlersSet)return this;let J=async(Z)=>{if(console.log(`
27
+
28
+ Received ${Z}, cleaning up...`),z)try{await z()}catch($){console.error("Error during cleanup:",$)}E.exit(0)};return E.on("SIGINT",()=>J("SIGINT")),E.on("SIGTERM",()=>J("SIGTERM")),this.signalHandlersSet=!0,this}didYouMean(z=!0){return this.enableDidYouMean=z,this}verbose(){return this.globalCommand.option("-v, --verbose","Enable verbose output"),this}quiet(){return this.globalCommand.option("-q, --quiet","Suppress non-essential output"),this}debug(){return this.globalCommand.option("--debug","Enable debug mode with detailed error information"),this}noInteraction(){return this.globalCommand.option("-n, --no-interaction","Do not ask any interactive questions (for CI/CD)"),this}env(){return this.globalCommand.option("--env <environment>","Target environment (e.g., production, staging, local)"),this}dryRun(){return this.globalCommand.option("--dry-run","Preview actions without executing them"),this}force(){return this.globalCommand.option("-f, --force","Skip confirmation prompts"),this}emoji(){return this.globalCommand.option("--no-emoji","Disable emoji in output"),this}themes(){return this.globalCommand.option("--theme <theme>","Color theme (default, dracula, nord, solarized, monokai)"),this}cache(){return this.globalCommand.option("--no-cache","Disable caching"),this}usage(z){return this.globalCommand.usage(z),this}command(z,J,Z){if(!Z)Z={};let $=new o6(z,J||"",Z,this);return $.globalCommand=this.globalCommand,this.commands.push($),$}option(z,J,Z){return this.globalCommand.option(z,J,Z),this}help(z){return this.globalCommand.option("-h, --help","Display this message"),this.globalCommand.helpCallback=z,this.showHelpOnExit=!0,this}version(z,J="-v, --version"){return this.globalCommand.version(z,J),this.showVersionOnExit=!0,this}example(z){return this.globalCommand.example(z),this}outputHelp(){if(this.matchedCommand)this.matchedCommand.outputHelp();else this.globalCommand.outputHelp()}outputVersion(){this.globalCommand.outputVersion()}setParsedInfo({args:z,options:J},Z,$){if(this.args=z,this.options=J,Z)this.matchedCommand=Z;if($)this.matchedCommandName=$;return this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}showCommandNotFound(z){if(console.log(P.red(`
29
+ \u2717 Command "${z}" not found.
30
+ `)),this.enableDidYouMean){let J=[];for(let $ of this.commands){if($.displayName)J.push($.displayName);if($.aliasNames)J.push(...$.aliasNames)}let Z=L6(z,J);if(Z.length>0)console.log(P.yellow("Did you mean one of these?")),Z.forEach(($)=>console.log(` ${P.dim("\u2022")} ${this.name} ${$}`)),console.log("")}console.log(P.dim("Run"),`${this.name} --help`,P.dim("to see all available commands")),E.exit(1)}async parse(z=G6,J={}){let{run:Z=!0,exitOnError:$=!1}=J;if($)try{return await this.parse(z,{run:Z})}catch(Y){throw this.handleUsageError(Y),Y}if(this.rawArgs=z,!this.name)this.name=z[1]?l6(z[1]):"cli";let Q=!0,j=z.slice(2),q=j[0];if(q&&!q.startsWith("-")){for(let Y of this.commands)if(Y.isMatched(q)){let G=this.mri(j,Y);Q=!1;let H={...G,args:G.args.slice(1)};this.setParsedInfo(H,Y,q),this.emit(`command:${q}`,Y);break}}if(Q){for(let Y of this.commands)if(Y.name===""){Q=!1;let G=this.mri(j,Y);this.setParsedInfo(G,Y),this.emit("command:!",Y);break}}if(Q){let Y=this.mri(z.slice(2));this.setParsedInfo(Y)}if(this.options.verbose)this.isVerbose=!0;if(this.options.quiet)this.isQuiet=!0;if(this.options.debug)this.isDebug=!0;if(this.options.noInteraction)this.isNoInteraction=!0;if(this.options.env)this.environment=String(this.options.env);if(this.options.dryRun)this.isDryRun=!0;if(this.options.force)this.isForce=!0;if(this.options.noEmoji!==void 0)this.useEmoji=!this.options.noEmoji;if(this.options.theme)this.theme=String(this.options.theme);if(this.options.noCache!==void 0)this.isNoCache=Boolean(this.options.noCache);if(this.options.help&&this.showHelpOnExit)this.outputHelp(),Z=!1,this.unsetMatchedCommand();if(this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null)this.outputVersion(),Z=!1,this.unsetMatchedCommand();let X={args:this.args,options:this.options};if(Z)await this.runMatchedCommand();if(!this.matchedCommand&&this.args[0]){if(this.emit("command:*"),!(this.listenerCount("command:*")>0))this.showCommandNotFound(this.args[0])}return X}mri(z,J){let Z=[...this.globalCommand.options,...J?J.options:[]],$=c6(Z),Q=[],j=z.indexOf("--");if(j>-1)Q=z.slice(j+1),z=z.slice(0,j);let q=d6(z,$),X={_:q._};for(let V of Object.keys(q))if(V!=="_")X[D6(V)]=q[V];let Y=X._,G={"--":Q},H=J&&J.config.ignoreOptionDefaultValue?J.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,K=Object.create(null);for(let V of Z){if(!H&&V.config.default!==void 0)for(let W of V.names)G[W]=V.config.default;if(Array.isArray(V.config.type)){if(K[V.name]===void 0)K[V.name]={shouldTransform:!0,transformFunction:V.config.type[0]}}}for(let V of Object.keys(X))if(V!=="_"){let W=V.split(".");n6(G,W,X[V]),p6(G,K)}return{args:Y,options:G}}async run(z=G6){return this.parse(z,{run:!0,exitOnError:!0})}handleUsageError(z){if(!(!!z&&typeof z==="object"&&z.name==="ClappError"&&z.isUsageError!==!1))return;let $=z,Q=$.message??"command-line error",j=this.name?`${this.name}: `:"",q=/--help/.test(Q)?"":`
31
+ Run \`${this.name??"cli"} --help\` for usage.`;E.stderr.write(`${j}${Q}${q}
32
+ `),E.exit($.exitCode??2)}async runMatchedCommand(){let{args:z,options:J,matchedCommand:Z}=this;if(!Z||!Z.commandAction)return;Z.checkUnknownOptions(),Z.checkOptionValue(),Z.checkRequiredArgs();let $=[];Z.args.forEach((X,Y)=>{if(X.variadic)$.push(z.slice(Y));else $.push(z[Y])}),$.push(J);let Q={command:Z,args:$,options:J};for(let X of Z.beforeHooks)await X(Q);let j,q=async()=>{let X=Z.commandAction.apply(this,$);if(X instanceof Promise)j=await X;else j=X;return j};if(Z.middleware.length>0){let X=0,Y=async()=>{if(X<Z.middleware.length){let G=Z.middleware[X++];await G({...Q,next:Y})}else await q()};await Y()}else await q();for(let X of Z.afterHooks)await X(Q);return j}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return E.removeAllListeners("SIGINT"),E.removeAllListeners("SIGTERM"),this.signalHandlersSet=!1,this}destroy(){this.removeSignalHandlers(),this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.matchedCommand=void 0,this.matchedCommandName=void 0,this.removeAllListeners()}}class N6{cache;enabled;cleanupInterval=null;hits=0;misses=0;constructor(){this.cache=new Map,this.enabled=!0,this.startCleanupInterval()}startCleanupInterval(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanup()},30000),this.cleanupInterval.unref()}stopCleanup(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}isEnabled(){return this.enabled}get(z){if(!this.enabled){this.misses++;return}let J=this.cache.get(z);if(!J){this.misses++;return}if(Date.now()-J.timestamp>J.ttl){this.cache.delete(z),this.misses++;return}return this.hits++,J.value}set(z,J,Z=5000){if(!this.enabled)return;this.cache.set(z,{value:J,timestamp:Date.now(),ttl:Z})}has(z){if(!this.enabled)return!1;let J=this.cache.get(z);if(!J)return!1;if(Date.now()-J.timestamp>J.ttl)return this.cache.delete(z),!1;return!0}delete(z){this.cache.delete(z)}clear(){this.cache.clear()}disable(){this.enabled=!1,this.clear()}enable(){this.enabled=!0}stats(){return{size:this.cache.size,enabled:this.enabled,hits:this.hits,misses:this.misses}}resetStats(){this.hits=0,this.misses=0}keys(){return Array.from(this.cache.keys())}cleanup(){let z=Date.now();for(let[J,Z]of this.cache.entries())if(z-Z.timestamp>Z.ttl)this.cache.delete(J)}destroy(){this.stopCleanup(),this.clear(),this.resetStats()}}var E4=new N6;function Jz(){if("FORCE_COLOR"in C.env)return C.env.FORCE_COLOR!=="0";if("NO_COLOR"in C.env||C.env.TERM==="dumb")return!1;if(C.platform==="win32")return!0;return H6.isatty(1)&&H6.isatty(2)}var O6=Jz();function L(z,J){if(!O6)return(Z)=>Z;return(Z)=>z+Z+J}var Zz=L("\x1B[0m","\x1B[0m"),$z=L("\x1B[31m","\x1B[39m"),Qz=L("\x1B[32m","\x1B[39m"),Yz=L("\x1B[33m","\x1B[39m"),jz=L("\x1B[34m","\x1B[39m"),Xz=L("\x1B[35m","\x1B[39m"),qz=L("\x1B[36m","\x1B[39m"),Uz=L("\x1B[37m","\x1B[39m"),Gz=L("\x1B[90m","\x1B[39m"),Hz=L("\x1B[1m","\x1B[22m"),Kz=L("\x1B[3m","\x1B[23m"),Vz=L("\x1B[4m","\x1B[24m"),Fz=L("\x1B[2m","\x1B[22m"),Wz=L("\x1B[7m","\x1B[27m"),Dz=L("\x1B[8m","\x1B[28m"),Lz=L("\x1B[9m","\x1B[29m"),Mz=L("\x1B[41m","\x1B[49m"),Nz=L("\x1B[42m","\x1B[49m"),Oz=L("\x1B[43m","\x1B[49m"),wz=L("\x1B[44m","\x1B[49m"),Ez=L("\x1B[45m","\x1B[49m"),Bz=L("\x1B[46m","\x1B[49m"),Tz=L("\x1B[47m","\x1B[49m"),xz=O6,bz={reset:Zz,red:$z,green:Qz,yellow:Yz,blue:jz,magenta:Xz,cyan:qz,white:Uz,gray:Gz,bold:Hz,italic:Kz,underline:Vz,dim:Fz,inverse:Wz,hidden:Dz,strikethrough:Lz,bgRed:Mz,bgGreen:Nz,bgYellow:Oz,bgBlue:wz,bgMagenta:Ez,bgCyan:Bz,bgWhite:Tz,isColorSupported:xz},g=bz,Iz=["up","down","left","right","space","enter","cancel"],f={actions:new Set(Iz),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};function w6(z,J){if(typeof z==="string")return f.aliases.get(z)===J;for(let Z of z){if(Z===void 0)continue;if(w6(Z,J))return!0}return!1}function Pz(z,J){if(z===J)return[];let Z=z.split(`
33
+ `),$=J.split(`
34
+ `),Q=[];for(let j=0;j<Math.max(Z.length,$.length);j++)if(Z[j]!==$[j])Q.push(j);return Q}var I4=Az.platform.startsWith("win"),K6=Symbol("clapp:cancel");function k(z,J){let Z=z;if(Z.isTTY)Z.setRawMode(J)}function Sz(z){return z.replace(/\x1b\[[0-9;]*m/g,"")}function kz(z){return Sz(z).length}function F6(z,J,Z){if(!J||J<1)return z;let $=Z?.hard??!1,Q=Z?.trim??!0,j=z.split(`
35
+ `),q=[];for(let X of j){if(kz(X)<=J){q.push(Q?X.trimEnd():X);continue}if($){let Y="",G=0,H=0;while(H<X.length){let K=X.slice(H).match(/^\x1b\[[0-9;]*m/);if(K){Y+=K[0],H+=K[0].length;continue}if(G>=J)q.push(Q?Y.trimEnd():Y),Y="",G=0;Y+=X[H],G++,H++}if(Y)q.push(Q?Y.trimEnd():Y)}else q.push(Q?X.trimEnd():X)}return q.join(`
36
+ `)}class J6{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;_manualLine="";state="initial";error="";value;userInput="";constructor(z,J=!0){let{input:Z=Cz,output:$=Rz,render:Q,signal:j,...q}=z;this.opts=q,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=Q.bind(this),this._track=J,this._abortSignal=j,this.input=Z,this.output=$}unsubscribe(){this._subscribers.clear()}setSubscriber(z,J){let Z=this._subscribers.get(z)??[];Z.push(J),this._subscribers.set(z,Z)}on(z,J){return this.setSubscriber(z,{cb:J}),this}once(z,J){return this.setSubscriber(z,{cb:J,once:!0}),this}emit(z,...J){let Z=this._subscribers.get(z)??[],$=[];for(let Q of Z)if(Q.cb(...J),Q.once)$.push(()=>Z.splice(Z.indexOf(Q),1));for(let Q of $)Q();return this}prompt(){return new Promise((z)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),z(K6);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}if(this.rl=vz.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0)this._setUserInput(this.opts.initialUserInput,!0);this.input.on("keypress",this.onKeypress),k(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(w.show),this.output.off("resize",this.render),k(this.input,!1),z(this.value)}),this.once("cancel",()=>{this.output.write(w.show),this.output.off("resize",this.render),k(this.input,!1),z(K6)})})}_isActionKey(z,J){return z==="\t"}_setValue(z){this.value=z,this.emit("value",this.value)}_setUserInput(z,J){if(this.userInput=z??"",this.emit("userInput",this.userInput),J&&this._track&&this.rl)this.rl.write(this.userInput),this._cursor=this.rl.cursor}onKeypress(z,J){if(this._track&&J.name!=="return"){if(J.name&&this._isActionKey(z,J))this.rl?.write(null,{ctrl:!0,name:"h"});this._cursor=this.rl?.cursor??0;let Z=J.name==="tab"||J.name==="escape"||J.name==="backspace"||J.name==="delete"||J.name==="enter"||J.name==="return"||J.name&&["up","down","left","right"].includes(J.name);if(z&&!Z&&z.length===1&&z>=" ")this._manualLine+=z;else if(J.name==="backspace"&&this._manualLine.length>0)this._manualLine=this._manualLine.slice(0,-1);let $=this._manualLine.length>=(this.rl?.line?.length||0)?this._manualLine:this.rl?.line;this._setUserInput($)}if(this.state==="error")this.state="active",this.error="";if(J?.name){if(!this._track&&f.aliases.has(J.name))this.emit("cursor",f.aliases.get(J.name));if(f.actions.has(J.name))this.emit("cursor",J.name)}if(z&&(z.toLowerCase()==="y"||z.toLowerCase()==="n"))this.emit("confirm",z.toLowerCase()==="y");if(this.emit("key",z?.toLowerCase(),J),J?.name==="return"){if(this.opts.validate){let Z=this.opts.validate(this.value);if(Z)this.error=Z instanceof Error?Z.message:Z,this.state="error"}if(this.state!=="error")this.state="submit"}if(w6([z,J?.name,J?.sequence],"cancel"))this.state="cancel";if(this.state==="submit"||this.state==="cancel")this.emit("finalize");if(this.render(),this.state==="submit"||this.state==="cancel")this.close()}close(){if(this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
37
+ `),k(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.state==="cancel")setTimeout(()=>{this.unsubscribe()},10);else this.unsubscribe()}restoreCursor(){let z=F6(this._prevFrame,V6.stdout.columns,{hard:!0,trim:!1}).split(`
38
+ `).length-1;this.output.write(w.move(-999,z*-1))}render(){let z=F6(this._render(this)??"",V6.stdout.columns,{hard:!0,trim:!1});if(z===this._prevFrame)return;if(this.state==="initial")this.output.write(w.hide);else{let J=Pz(this._prevFrame,z);if(this.restoreCursor(),J&&J?.length===1){let Z=J[0];this.output.write(w.move(0,Z)),this.output.write(r.lines(1));let $=z.split(`
39
+ `);this.output.write($[Z]),this._prevFrame=z,this.output.write(w.move(0,$.length-Z-1));return}if(J&&J?.length>1){let Z=J[0];this.output.write(w.move(0,Z)),this.output.write(r.down());let Q=z.split(`
40
+ `).slice(Z);this.output.write(Q.join(`
41
+ `)),this._prevFrame=z;return}this.output.write(r.down())}if(this.output.write(z),this.state==="initial")this.state="active";this._prevFrame=z}}function yz(z,J){if(z===void 0)return 0;if(J.length===0)return 0;let $=J.findIndex((Q)=>Q.value===z);return $!==-1?$:0}function _z(z,J){return(J.label??String(J.value)).toLowerCase().includes(z.toLowerCase())}function gz(z,J){if(!J)return;if(z)return J;return J[0]}class fz extends J6{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#z=0;#Z="";#$;#J;get cursor(){return this.#z}get userInputWithCursor(){if(!this.userInput)return g.inverse(g.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}\u2588`;let z=this.userInput.slice(0,this._cursor),[J,...Z]=this.userInput.slice(this._cursor);return`${z}${g.inverse(J)}${Z.join("")}`}get options(){if(typeof this.#J==="function")return this.#J();return this.#J}constructor(z){super(z);this.#J=z.options;let J=this.options;this.filteredOptions=[...J],this.multiple=z.multiple===!0,this.#$=z.filter??_z;let Z;if(z.initialValue&&Array.isArray(z.initialValue))if(this.multiple)Z=z.initialValue;else Z=z.initialValue.slice(0,1);else if(!this.multiple&&this.options.length>0)Z=[this.options[0].value];if(Z)for(let $ of Z){let Q=J.findIndex((j)=>j.value===$);if(Q!==-1)this.toggleSelected($),this.#z=Q}this.focusedValue=this.options[this.#z]?.value,this.on("key",($,Q)=>this.#Q($,Q)),this.on("userInput",($)=>this.#Y($))}_isActionKey(z,J){return z==="\t"||this.multiple&&this.isNavigating&&J.name==="space"&&z!==void 0&&z!==""}#Q(z,J){let Z=J.name==="up",$=J.name==="down",Q=J.name==="return";if(Z||$){if(this.#z=Math.max(0,Math.min(this.#z+(Z?-1:1),this.filteredOptions.length-1)),this.focusedValue=this.filteredOptions[this.#z]?.value,!this.multiple)this.selectedValues=[this.focusedValue];this.isNavigating=!0}else if(Q)this.value=gz(this.multiple,this.selectedValues);else if(this.multiple)if(this.focusedValue!==void 0&&(J.name==="tab"||this.isNavigating&&J.name==="space"))this.toggleSelected(this.focusedValue);else this.isNavigating=!1;else{if(this.focusedValue)this.selectedValues=[this.focusedValue];this.isNavigating=!1}}deselectAll(){this.selectedValues=[]}toggleSelected(z){if(this.filteredOptions.length===0)return;if(this.multiple)if(this.selectedValues.includes(z))this.selectedValues=this.selectedValues.filter((J)=>J!==z);else this.selectedValues=[...this.selectedValues,z];else this.selectedValues=[z]}#Y(z){if(z!==this.#Z){this.#Z=z;let J=this.options;if(z)this.filteredOptions=J.filter((Z)=>this.#$(z,Z));else this.filteredOptions=[...J];if(this.#z=yz(this.focusedValue,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#z]?.value,!this.multiple)if(this.focusedValue!==void 0)this.toggleSelected(this.focusedValue);else this.deselectAll()}}}class hz extends J6{options;cursor=0;#z;getGroupItems(z){return this.options.filter((J)=>J.group===z)}isGroupSelected(z){let J=this.getGroupItems(z),Z=this.value;if(Z===void 0)return!1;return J.every(($)=>Z.includes($.value))}toggleValue(){let z=this.options[this.cursor];if(this.value===void 0)this.value=[];if(z.group===!0){let J=String(z.value),Z=this.getGroupItems(J);if(this.isGroupSelected(J))this.value=this.value.filter(($)=>Z.findIndex((Q)=>Q.value===$)===-1);else this.value=[...this.value,...Z.map(($)=>$.value)];this.value=Array.from(new Set(this.value))}else{let J=this.value.includes(z.value);this.value=J?this.value.filter((Z)=>Z!==z.value):[...this.value,z.value]}}constructor(z){super(z,!1);let{options:J}=z;this.#z=z.selectableGroups!==!1,this.options=Object.entries(J).flatMap(([Z,$])=>[{value:Z,group:!0,label:Z},...$.map((Q)=>({...Q,group:Z}))]),this.value=[...z.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:Z})=>Z===z.cursorAt),this.#z?0:1),this.on("cursor",(Z)=>{switch(Z){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let $=this.options[this.cursor]?.group===!0;if(!this.#z&&$)this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let $=this.options[this.cursor]?.group===!0;if(!this.#z&&$)this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}case"space":this.toggleValue();break}})}}var mz=a6();var D=(z,J)=>mz?z:J,R4=D("\u25C6","*"),v4=D("\u25A0","x"),S4=D("\u25B2","x"),k4=D("\u25C7","o"),y4=D("\u250C","T"),dz=D("\u2502","|"),_4=D("\u2514","\u2014"),g4=D("\u25CF",">"),f4=D("\u25CB"," "),h4=D("\u25FB","[\u2022]"),m4=D("\u25FC","[+]"),d4=D("\u25FB","[ ]"),u4=D("\u25AA","\u2022"),c4=D("\u2500","-"),i4=D("\u256E","+"),n4=D("\u251C","+"),p4=D("\u256F","+"),l4=D("\u25CF","\u2022"),a4=D("\u25C6","*"),r4=D("\u25B2","!"),s4=D("\u25A0","x");var t4={light:D("\u2500","-"),heavy:D("\u2501","="),block:D("\u2588","#")};function uz(){return`${g.gray(dz)} `}var o4=uz();var E6="0.1.0";import T from"fs/promises";import Z6 from"path";import m from"process";var N={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m"},U={red:(z)=>`${N.red}${z}${N.reset}`,green:(z)=>`${N.green}${z}${N.reset}`,yellow:(z)=>`${N.yellow}${z}${N.reset}`,blue:(z)=>`${N.blue}${z}${N.reset}`,cyan:(z)=>`${N.cyan}${z}${N.reset}`,white:(z)=>`${N.white}${z}${N.reset}`,gray:(z)=>`${N.gray}${z}${N.reset}`,bold:(z)=>`${N.bold}${z}${N.reset}`,dim:(z)=>`${N.dim}${z}${N.reset}`,hex:(z)=>(J)=>J};async function d(z){let J=Object.entries(B6).map(([$,Q])=>({name:$,className:Q.constructor.name})),Z=`/**
2090
42
  * This file is auto-generated.
2091
43
  * DO NOT EDIT THIS FILE DIRECTLY.
2092
44
  * To update, run 'bun router middleware:types'
2093
45
  */
2094
- import type { ${middlewareInfo.map((m) => m.className).join(", ")} } from './middleware'
46
+ import type { ${J.map(($)=>$.className).join(", ")} } from './middleware'
2095
47
 
2096
48
  /**
2097
49
  * Available middleware map with middleware names as keys
2098
50
  */
2099
51
  export interface MiddlewareMap {
2100
- ${middlewareInfo.map((m) => ` '${m.name}': ${m.className}`).join(`
52
+ ${J.map(($)=>` '${$.name}': ${$.className}`).join(`
2101
53
  `)}
2102
54
  }
2103
55
 
2104
56
  /**
2105
57
  * String literal type of available middleware names
2106
58
  */
2107
- export type MiddlewareName = ${middlewareInfo.map((m) => `'${m.name}'`).join(" | ")}
59
+ export type MiddlewareName = ${J.map(($)=>`'${$.name}'`).join(" | ")}
2108
60
 
2109
61
  /**
2110
62
  * Middleware configuration type for router setup
2111
63
  */
2112
- export type MiddlewareConfig = MiddlewareName | ${middlewareInfo.map((m) => m.className).join(" | ")}
64
+ export type MiddlewareConfig = MiddlewareName | ${J.map(($)=>$.className).join(" | ")}
2113
65
 
2114
66
  /**
2115
67
  * Function to check if a middleware name is valid
2116
68
  */
2117
69
  export function isValidMiddleware(name: string): name is MiddlewareName {
2118
- return [${middlewareInfo.map((m) => `'${m.name}'`).join(", ")}].includes(name)
70
+ return [${J.map(($)=>`'${$.name}'`).join(", ")}].includes(name)
2119
71
  }
2120
- `;
2121
- await fs2.writeFile(outputPath, typeContent);
2122
- }
2123
- async function findTsFiles(dir) {
2124
- const files = [];
2125
- const entries = await fs2.readdir(dir, { withFileTypes: true });
2126
- for (const entry of entries) {
2127
- const fullPath = path2.join(dir, entry.name);
2128
- if (entry.isDirectory()) {
2129
- files.push(...await findTsFiles(fullPath));
2130
- } else if (entry.isFile() && entry.name.endsWith(".ts")) {
2131
- files.push(fullPath);
2132
- }
2133
- }
2134
- return files;
2135
- }
2136
- async function scanFileForMiddleware(filePath) {
2137
- const middlewareClasses = [];
2138
- try {
2139
- const content = await fs2.readFile(filePath, "utf-8");
2140
- const classRegex = /export\s+(?:default\s+)?class\s+(\w+)\s+(?:implements\s+Middleware|\{[\s\S]*?handle\s*\([\s\S]*?\))/g;
2141
- let match = null;
2142
- while (match = classRegex.exec(content)) {
2143
- const className = match[1];
2144
- if (className.includes("Middleware") || match[0].includes("implements Middleware")) {
2145
- const relativePath = path2.relative(process6.cwd(), filePath);
2146
- const importPath = relativePath.replace(/\.ts$/, "");
2147
- middlewareClasses.push({
2148
- name: className,
2149
- path: importPath
2150
- });
2151
- }
2152
- }
2153
- } catch (error) {
2154
- console.warn(chalk.yellow(`Error scanning file ${filePath}: ${error}`));
2155
- }
2156
- return middlewareClasses;
2157
- }
2158
- async function generateMiddlewareMap(directoryPath, outputPath) {
2159
- console.log(chalk.blue(`Scanning directory: ${directoryPath} for middleware classes...`));
2160
- try {
2161
- const tsFiles = await findTsFiles(directoryPath);
2162
- const allMiddleware = [];
2163
- for (const file of tsFiles) {
2164
- const middlewareInFile = await scanFileForMiddleware(file);
2165
- allMiddleware.push(...middlewareInFile);
2166
- }
2167
- if (allMiddleware.length === 0) {
2168
- console.warn(chalk.yellow("No middleware classes found in the specified directory."));
2169
- return;
2170
- }
2171
- const imports = allMiddleware.map((m) => `import { ${m.name} } from '${m.path}'`).join(`
2172
- `);
2173
- const interfaceMembers = allMiddleware.map((m) => ` ${m.name}: typeof ${m.name}`).join(`
2174
- `);
2175
- const typeNames = allMiddleware.map((m) => m.name).join(" | ");
2176
- const typeContent = `/**
72
+ `;await T.writeFile(z,Z)}async function T6(z){let J=[],Z=await T.readdir(z,{withFileTypes:!0});for(let $ of Z){let Q=Z6.join(z,$.name);if($.isDirectory())J.push(...await T6(Q));else if($.isFile()&&$.name.endsWith(".ts"))J.push(Q)}return J}async function iz(z){let J=[];try{let Z=await T.readFile(z,"utf-8"),$=/export\s+(?:default\s+)?class\s+(\w+)\s+(?:implements\s+Middleware|\{[\s\S]*?handle\s*\([\s\S]*?\))/g,Q=null;while(Q=$.exec(Z)){let j=Q[1];if(j.includes("Middleware")||Q[0].includes("implements Middleware")){let X=Z6.relative(m.cwd(),z).replace(/\.ts$/,"");J.push({name:j,path:X})}}}catch(Z){console.warn(U.yellow(`Error scanning file ${z}: ${Z}`))}return J}async function u(z,J){console.log(U.blue(`Scanning directory: ${z} for middleware classes...`));try{let Z=await T6(z),$=[];for(let Y of Z){let G=await iz(Y);$.push(...G)}if($.length===0){console.warn(U.yellow("No middleware classes found in the specified directory."));return}let Q=$.map((Y)=>`import { ${Y.name} } from '${Y.path}'`).join(`
73
+ `),j=$.map((Y)=>` ${Y.name}: typeof ${Y.name}`).join(`
74
+ `),q=$.map((Y)=>Y.name).join(" | "),X=`/**
2177
75
  * This file is auto-generated.
2178
76
  * DO NOT EDIT THIS FILE DIRECTLY.
2179
77
  * To update, run 'bun router middleware:map'
2180
78
  */
2181
79
 
2182
- ${imports}
80
+ ${Q}
2183
81
 
2184
82
  /**
2185
83
  * Map of all available middleware in the project
2186
84
  */
2187
85
  export interface MiddlewareMap {
2188
- ${interfaceMembers}
86
+ ${j}
2189
87
  }
2190
88
 
2191
89
  /**
2192
90
  * Type representing all available middleware classes in the project
2193
91
  */
2194
- export type MiddlewareType = ${typeNames}
92
+ export type MiddlewareType = ${q}
2195
93
 
2196
94
  /**
2197
95
  * Type for a middleware handler function
@@ -2202,377 +100,10 @@ export type MiddlewareHandler = (req: any, next: () => Promise<Response>) => Pro
2202
100
  * Ensure the middleware module exports all the middleware classes used in the project
2203
101
  */
2204
102
  export const middlewareMap: MiddlewareMap = {
2205
- ${allMiddleware.map((m) => ` ${m.name}: ${m.name}`).join(`,
103
+ ${$.map((Y)=>` ${Y.name}: ${Y.name}`).join(`,
2206
104
  `)}
2207
105
  }
2208
- `;
2209
- await fs2.writeFile(outputPath, typeContent);
2210
- console.log(chalk.green(`\u2728 Middleware map generated at ${outputPath} with ${allMiddleware.length} middleware classes`));
2211
- console.log(chalk.blue("Found middleware classes:"));
2212
- for (const m of allMiddleware) {
2213
- console.log(chalk.cyan(` - ${m.name} (${m.path})`));
2214
- }
2215
- } catch (error) {
2216
- console.error(chalk.red(`Error generating middleware map: ${error}`));
2217
- throw error;
2218
- }
2219
- }
2220
- async function watchDirectoryForMiddleware(directoryPath, outputPath) {
2221
- try {
2222
- await fs2.access(directoryPath);
2223
- } catch {
2224
- console.error(chalk.red(`Directory not found at ${directoryPath}`));
2225
- process6.exit(1);
2226
- }
2227
- await generateMiddlewareMap(directoryPath, outputPath);
2228
- console.log(chalk.blue(`Watching for changes in ${directoryPath}...`));
2229
- let timeoutId = null;
2230
- const watcher = fs2.watch(directoryPath, { recursive: true });
2231
- for await (const _event of watcher) {
2232
- if (timeoutId) {
2233
- clearTimeout(timeoutId);
2234
- }
2235
- timeoutId = setTimeout(async () => {
2236
- console.log(chalk.yellow(`Changes detected. Regenerating middleware map...`));
2237
- try {
2238
- await generateMiddlewareMap(directoryPath, outputPath);
2239
- } catch (error) {
2240
- console.error(chalk.red(`Error regenerating middleware map: ${error.message}`));
2241
- }
2242
- timeoutId = null;
2243
- }, 500);
2244
- }
2245
- }
2246
- async function watchMiddlewareDirectory(outputPath) {
2247
- const middlewarePath = path2.join(process6.cwd(), "src", "middleware");
2248
- try {
2249
- await fs2.access(middlewarePath);
2250
- } catch {
2251
- console.error(chalk.red(`Middleware directory not found at ${middlewarePath}`));
2252
- process6.exit(1);
2253
- }
2254
- await generateMiddlewareTypes(outputPath);
2255
- console.log(chalk.green(`\u2728 Middleware types generated at ${outputPath}`));
2256
- console.log(chalk.blue(`Watching for changes in ${middlewarePath}...`));
2257
- let timeoutId = null;
2258
- const watcher = fs2.watch(middlewarePath, { recursive: true });
2259
- for await (const _event of watcher) {
2260
- if (timeoutId) {
2261
- clearTimeout(timeoutId);
2262
- }
2263
- timeoutId = setTimeout(async () => {
2264
- console.log(chalk.yellow(`Changes detected in middleware directory. Regenerating types...`));
2265
- try {
2266
- await generateMiddlewareTypes(outputPath);
2267
- console.log(chalk.green(`\u2728 Middleware types regenerated at ${outputPath}`));
2268
- } catch (error) {
2269
- console.error(chalk.red(`Error regenerating types: ${error.message}`));
2270
- }
2271
- timeoutId = null;
2272
- }, 500);
2273
- }
2274
- }
2275
-
2276
- // src/cli/openapi.ts
2277
- import fs3 from "fs/promises";
2278
- import process10 from "process";
2279
- async function generateOpenAPISpec(options) {
2280
- try {
2281
- const routesFile = `${process10.cwd()}/routes/index.ts`;
2282
- const { router } = await import(routesFile);
2283
- if (!router) {
2284
- console.error(chalk.red(`Could not find router instance in ${routesFile}.`));
2285
- process10.exit(1);
2286
- }
2287
- const routes = router.routes || [];
2288
- if (routes.length === 0) {
2289
- console.log(chalk.yellow("No routes defined. Creating empty OpenAPI specification."));
2290
- }
2291
- const apiRoutes = routes.filter((route) => {
2292
- return route.type === "api" || route.path.startsWith("/api");
2293
- });
2294
- const openapi = {
2295
- openapi: "3.0.3",
2296
- info: {
2297
- title: options.title || "API Documentation",
2298
- version: options.version || "1.0.0",
2299
- description: options.description || "Generated API documentation"
2300
- },
2301
- servers: generateServers(options),
2302
- paths: {},
2303
- components: {
2304
- schemas: {},
2305
- securitySchemes: {}
2306
- },
2307
- tags: []
2308
- };
2309
- const uniqueTags = new Set;
2310
- for (const route of apiRoutes) {
2311
- const pathItem = openapi.paths[route.path] || {};
2312
- let tag = "";
2313
- if (options.tags !== false) {
2314
- tag = route.tag || extractTagFromPath(route.path);
2315
- uniqueTags.add(tag);
2316
- }
2317
- const operation = {
2318
- summary: route.summary || `${route.method.toUpperCase()} ${route.path}`,
2319
- description: route.description || "",
2320
- operationId: route.name || generateOperationId(route.method, route.path),
2321
- parameters: generateParameters(route),
2322
- responses: generateResponses(route)
2323
- };
2324
- if (tag) {
2325
- operation.tags = [tag];
2326
- }
2327
- if (["post", "put", "patch"].includes(route.method.toLowerCase())) {
2328
- operation.requestBody = generateRequestBody(route);
2329
- }
2330
- if (options.security !== false && route.middleware) {
2331
- const securityItems = extractSecurityFromMiddleware(route.middleware);
2332
- if (securityItems.length > 0) {
2333
- operation.security = securityItems;
2334
- }
2335
- }
2336
- pathItem[route.method.toLowerCase()] = operation;
2337
- openapi.paths[route.path] = pathItem;
2338
- }
2339
- if (options.tags !== false) {
2340
- openapi.tags = Array.from(uniqueTags).map((tag) => ({
2341
- name: tag,
2342
- description: `Operations related to ${tag}`
2343
- }));
2344
- }
2345
- const outputPath = options.output || "openapi.json";
2346
- await fs3.writeFile(outputPath, JSON.stringify(openapi, null, 2));
2347
- console.log(chalk.green(`\u2728 OpenAPI specification generated at ${outputPath}`));
2348
- console.log(chalk.blue(`Import this file into Postman, Swagger UI, or other API tools to explore your API.`));
2349
- } catch (error) {
2350
- if (error.code === "ERR_MODULE_NOT_FOUND") {
2351
- console.error(chalk.red(`Routes file not found at ${process10.cwd()}/routes/index.ts`));
2352
- console.error(chalk.yellow('Make sure your routes are defined and exported as "router" in routes/index.ts'));
2353
- } else {
2354
- console.error(chalk.red(`Error generating OpenAPI specification: ${error.message}`));
2355
- }
2356
- throw error;
2357
- }
2358
- }
2359
- function generateServers(options) {
2360
- const servers = [];
2361
- if (options.servers) {
2362
- const serverUrls = options.servers.split(",").map((url) => url.trim());
2363
- for (const url of serverUrls) {
2364
- servers.push({
2365
- url,
2366
- description: `Server ${servers.length + 1}`
2367
- });
2368
- }
2369
- }
2370
- if (servers.length === 0) {
2371
- servers.push({
2372
- url: options.basePath || "/",
2373
- description: "Default server"
2374
- });
2375
- }
2376
- return servers;
2377
- }
2378
- function extractTagFromPath(path3) {
2379
- const segments = path3.split("/").filter(Boolean);
2380
- if (segments.length > 0) {
2381
- if (segments[0].toLowerCase() === "api" && segments.length > 1) {
2382
- return segments[1];
2383
- }
2384
- return segments[0];
2385
- }
2386
- return "default";
2387
- }
2388
- function generateOperationId(method, path3) {
2389
- const pathWithoutParams = path3.replace(/\{([^}]+)\}/g, "_$1");
2390
- const segments = pathWithoutParams.split("/").filter(Boolean);
2391
- if (segments.length === 0) {
2392
- return method.toLowerCase();
2393
- }
2394
- let operationId = method.toLowerCase();
2395
- for (const segment of segments) {
2396
- operationId += segment.charAt(0).toUpperCase() + segment.slice(1);
2397
- }
2398
- return operationId;
2399
- }
2400
- function generateParameters(route) {
2401
- const parameters = [];
2402
- const pathParams = route.path.match(/\{([^}]+)\}/g);
2403
- if (pathParams) {
2404
- for (const param of pathParams) {
2405
- const paramName = param.slice(1, -1);
2406
- parameters.push({
2407
- name: paramName,
2408
- in: "path",
2409
- required: true,
2410
- schema: {
2411
- type: "string"
2412
- },
2413
- description: `Path parameter: ${paramName}`
2414
- });
2415
- }
2416
- }
2417
- if (route.params && route.params.query) {
2418
- for (const [name, schema] of Object.entries(route.params.query)) {
2419
- parameters.push({
2420
- name,
2421
- in: "query",
2422
- schema: mapSchemaType(schema),
2423
- required: schema.required === true,
2424
- description: schema.description || `Query parameter: ${name}`
2425
- });
2426
- }
2427
- }
2428
- return parameters;
2429
- }
2430
- function mapSchemaType(schema) {
2431
- if (!schema || typeof schema !== "object") {
2432
- return { type: "string" };
2433
- }
2434
- const openApiSchema = {};
2435
- if (schema.type) {
2436
- openApiSchema.type = schema.type;
2437
- }
2438
- if (schema.format) {
2439
- openApiSchema.format = schema.format;
2440
- }
2441
- if (schema.enum) {
2442
- openApiSchema.enum = schema.enum;
2443
- }
2444
- if (schema.default !== undefined) {
2445
- openApiSchema.default = schema.default;
2446
- }
2447
- return openApiSchema;
2448
- }
2449
- function generateResponses(route) {
2450
- const responses = {
2451
- 200: {
2452
- description: "Successful response",
2453
- content: {
2454
- "application/json": {
2455
- schema: {}
2456
- }
2457
- }
2458
- }
2459
- };
2460
- responses["400"] = {
2461
- description: "Bad request",
2462
- content: {
2463
- "application/json": {
2464
- schema: {
2465
- type: "object",
2466
- properties: {
2467
- error: { type: "string" }
2468
- }
2469
- }
2470
- }
2471
- }
2472
- };
2473
- responses["401"] = {
2474
- description: "Unauthorized",
2475
- content: {
2476
- "application/json": {
2477
- schema: {
2478
- type: "object",
2479
- properties: {
2480
- error: { type: "string" }
2481
- }
2482
- }
2483
- }
2484
- }
2485
- };
2486
- responses["404"] = {
2487
- description: "Not found",
2488
- content: {
2489
- "application/json": {
2490
- schema: {
2491
- type: "object",
2492
- properties: {
2493
- error: { type: "string" }
2494
- }
2495
- }
2496
- }
2497
- }
2498
- };
2499
- responses["500"] = {
2500
- description: "Server error",
2501
- content: {
2502
- "application/json": {
2503
- schema: {
2504
- type: "object",
2505
- properties: {
2506
- error: { type: "string" }
2507
- }
2508
- }
2509
- }
2510
- }
2511
- };
2512
- if (route.responses) {
2513
- for (const [status, response] of Object.entries(route.responses)) {
2514
- responses[status] = {
2515
- description: response.description || `Response with status ${status}`,
2516
- content: {
2517
- "application/json": {
2518
- schema: response.schema || {}
2519
- }
2520
- }
2521
- };
2522
- }
2523
- }
2524
- return responses;
2525
- }
2526
- function generateRequestBody(route) {
2527
- const requestBody = {
2528
- required: true,
2529
- content: {
2530
- "application/json": {
2531
- schema: {
2532
- type: "object"
2533
- }
2534
- }
2535
- }
2536
- };
2537
- if (route.params && route.params.body) {
2538
- requestBody.content["application/json"].schema = route.params.body;
2539
- }
2540
- return requestBody;
2541
- }
2542
- function extractSecurityFromMiddleware(middleware2) {
2543
- const securityItems = [];
2544
- for (const mw of middleware2) {
2545
- const name = typeof mw === "string" ? mw : mw.name;
2546
- if (name && name.toLowerCase().includes("auth")) {
2547
- if (name.toLowerCase().includes("jwt")) {
2548
- securityItems.push({ BearerAuth: [] });
2549
- } else if (name.toLowerCase().includes("apikey")) {
2550
- securityItems.push({ ApiKeyAuth: [] });
2551
- } else if (name.toLowerCase().includes("basic")) {
2552
- securityItems.push({ BasicAuth: [] });
2553
- } else {
2554
- securityItems.push({ [name]: [] });
2555
- }
2556
- }
2557
- }
2558
- return securityItems;
2559
- }
2560
-
2561
- // src/cli/router.ts
2562
- import fs4 from "fs/promises";
2563
- import path3 from "path";
2564
- import process12 from "process";
2565
- async function generateRouterTypes(outputPath) {
2566
- try {
2567
- const routesFile = `${process12.cwd()}/routes/index.ts`;
2568
- const { router } = await import(routesFile);
2569
- if (!router) {
2570
- console.error(chalk.red(`Could not find router instance in ${routesFile}.`));
2571
- process12.exit(1);
2572
- }
2573
- const routerMethods = Object.getOwnPropertyNames(Object.getPrototypeOf(router)).filter((method) => !method.startsWith("_") && method !== "constructor" && typeof router[method] === "function");
2574
- const extendedProperties = Object.keys(router).filter((prop) => !["routes", "middleware", "hooks", "config"].includes(prop) && typeof prop === "string" && !prop.startsWith("_"));
2575
- const typeContent = `/**
106
+ `;await T.writeFile(J,X),console.log(U.green(`\u2728 Middleware map generated at ${J} with ${$.length} middleware classes`)),console.log(U.blue("Found middleware classes:"));for(let Y of $)console.log(U.cyan(` - ${Y.name} (${Y.path})`))}catch(Z){throw console.error(U.red(`Error generating middleware map: ${Z}`)),Z}}async function x6(z,J){try{await T.access(z)}catch{console.error(U.red(`Directory not found at ${z}`)),m.exit(1)}await u(z,J),console.log(U.blue(`Watching for changes in ${z}...`));let Z=null,$=T.watch(z,{recursive:!0});for await(let Q of $){if(Z)clearTimeout(Z);Z=setTimeout(async()=>{console.log(U.yellow("Changes detected. Regenerating middleware map..."));try{await u(z,J)}catch(j){console.error(U.red(`Error regenerating middleware map: ${j.message}`))}Z=null},500)}}async function b6(z){let J=Z6.join(m.cwd(),"src","middleware");try{await T.access(J)}catch{console.error(U.red(`Middleware directory not found at ${J}`)),m.exit(1)}await d(z),console.log(U.green(`\u2728 Middleware types generated at ${z}`)),console.log(U.blue(`Watching for changes in ${J}...`));let Z=null,$=T.watch(J,{recursive:!0});for await(let Q of $){if(Z)clearTimeout(Z);Z=setTimeout(async()=>{console.log(U.yellow("Changes detected in middleware directory. Regenerating types..."));try{await d(z),console.log(U.green(`\u2728 Middleware types regenerated at ${z}`))}catch(j){console.error(U.red(`Error regenerating types: ${j.message}`))}Z=null},500)}}import nz from"fs/promises";import $6 from"process";async function A6(z){try{let J=`${$6.cwd()}/routes/index.ts`,{router:Z}=await import(J);if(!Z)console.error(U.red(`Could not find router instance in ${J}.`)),$6.exit(1);let $=Z.routes||[];if($.length===0)console.log(U.yellow("No routes defined. Creating empty OpenAPI specification."));let Q=$.filter((Y)=>{return Y.type==="api"||Y.path.startsWith("/api")}),j={openapi:"3.0.3",info:{title:z.title||"API Documentation",version:z.version||"1.0.0",description:z.description||"Generated API documentation"},servers:pz(z),paths:{},components:{schemas:{},securitySchemes:{}},tags:[]},q=new Set;for(let Y of Q){let G=j.paths[Y.path]||{},H="";if(z.tags!==!1)H=Y.tag||lz(Y.path),q.add(H);let K={summary:Y.summary||`${Y.method.toUpperCase()} ${Y.path}`,description:Y.description||"",operationId:Y.name||az(Y.method,Y.path),parameters:rz(Y),responses:tz(Y)};if(H)K.tags=[H];if(["post","put","patch"].includes(Y.method.toLowerCase()))K.requestBody=oz(Y);if(z.security!==!1&&Y.middleware){let V=ez(Y.middleware);if(V.length>0)K.security=V}G[Y.method.toLowerCase()]=K,j.paths[Y.path]=G}if(z.tags!==!1)j.tags=Array.from(q).map((Y)=>({name:Y,description:`Operations related to ${Y}`}));let X=z.output||"openapi.json";await nz.writeFile(X,JSON.stringify(j,null,2)),console.log(U.green(`\u2728 OpenAPI specification generated at ${X}`)),console.log(U.blue("Import this file into Postman, Swagger UI, or other API tools to explore your API."))}catch(J){if(J.code==="ERR_MODULE_NOT_FOUND")console.error(U.red(`Routes file not found at ${$6.cwd()}/routes/index.ts`)),console.error(U.yellow('Make sure your routes are defined and exported as "router" in routes/index.ts'));else console.error(U.red(`Error generating OpenAPI specification: ${J.message}`));throw J}}function pz(z){let J=[];if(z.servers){let Z=z.servers.split(",").map(($)=>$.trim());for(let $ of Z)J.push({url:$,description:`Server ${J.length+1}`})}if(J.length===0)J.push({url:z.basePath||"/",description:"Default server"});return J}function lz(z){let J=z.split("/").filter(Boolean);if(J.length>0){if(J[0].toLowerCase()==="api"&&J.length>1)return J[1];return J[0]}return"default"}function az(z,J){let $=J.replace(/\{([^}]+)\}/g,"_$1").split("/").filter(Boolean);if($.length===0)return z.toLowerCase();let Q=z.toLowerCase();for(let j of $)Q+=j.charAt(0).toUpperCase()+j.slice(1);return Q}function rz(z){let J=[],Z=z.path.match(/\{([^}]+)\}/g);if(Z)for(let $ of Z){let Q=$.slice(1,-1);J.push({name:Q,in:"path",required:!0,schema:{type:"string"},description:`Path parameter: ${Q}`})}if(z.params&&z.params.query)for(let[$,Q]of Object.entries(z.params.query))J.push({name:$,in:"query",schema:sz(Q),required:Q.required===!0,description:Q.description||`Query parameter: ${$}`});return J}function sz(z){if(!z||typeof z!=="object")return{type:"string"};let J={};if(z.type)J.type=z.type;if(z.format)J.format=z.format;if(z.enum)J.enum=z.enum;if(z.default!==void 0)J.default=z.default;return J}function tz(z){let J={200:{description:"Successful response",content:{"application/json":{schema:{}}}}};if(J["400"]={description:"Bad request",content:{"application/json":{schema:{type:"object",properties:{error:{type:"string"}}}}}},J["401"]={description:"Unauthorized",content:{"application/json":{schema:{type:"object",properties:{error:{type:"string"}}}}}},J["404"]={description:"Not found",content:{"application/json":{schema:{type:"object",properties:{error:{type:"string"}}}}}},J["500"]={description:"Server error",content:{"application/json":{schema:{type:"object",properties:{error:{type:"string"}}}}}},z.responses)for(let[Z,$]of Object.entries(z.responses))J[Z]={description:$.description||`Response with status ${Z}`,content:{"application/json":{schema:$.schema||{}}}};return J}function oz(z){let J={required:!0,content:{"application/json":{schema:{type:"object"}}}};if(z.params&&z.params.body)J.content["application/json"].schema=z.params.body;return J}function ez(z){let J=[];for(let Z of z){let $=typeof Z==="string"?Z:Z.name;if($&&$.toLowerCase().includes("auth"))if($.toLowerCase().includes("jwt"))J.push({BearerAuth:[]});else if($.toLowerCase().includes("apikey"))J.push({ApiKeyAuth:[]});else if($.toLowerCase().includes("basic"))J.push({BasicAuth:[]});else J.push({[$]:[]})}return J}import Q6 from"fs/promises";import I6 from"path";import A from"process";async function c(z){try{let J=`${A.cwd()}/routes/index.ts`,{router:Z}=await import(J);if(!Z)console.error(U.red(`Could not find router instance in ${J}.`)),A.exit(1);let $=Object.getOwnPropertyNames(Object.getPrototypeOf(Z)).filter((q)=>!q.startsWith("_")&&q!=="constructor"&&typeof Z[q]==="function"),Q=Object.keys(Z).filter((q)=>!["routes","middleware","hooks","config"].includes(q)&&typeof q==="string"&&!q.startsWith("_")),j=`/**
2576
107
  * This file is auto-generated.
2577
108
  * DO NOT EDIT THIS FILE DIRECTLY.
2578
109
  * To update, run 'bun router router:types'
@@ -2583,23 +114,10 @@ import type { Router, RouteHandler, MiddlewareHandler, RouteDefinition } from '.
2583
114
  * Extended Router interface with all available methods and properties
2584
115
  */
2585
116
  export interface ExtendedRouter extends Router {
2586
- ${routerMethods.map((method) => {
2587
- if (["get", "post", "put", "delete", "patch", "options", "head"].includes(method)) {
2588
- return `${method}(path: string, handler: RouteHandler, options?: any): Router`;
2589
- } else if (method === "use") {
2590
- return `${method}(middleware: MiddlewareHandler | MiddlewareHandler[]): Router`;
2591
- } else if (method === "group") {
2592
- return `${method}(prefix: string, callback: (router: Router) => void): Router`;
2593
- } else {
2594
- return `${method}: Function`;
2595
- }
2596
- }).join(`
117
+ ${$.map((q)=>{if(["get","post","put","delete","patch","options","head"].includes(q))return`${q}(path: string, handler: RouteHandler, options?: any): Router`;else if(q==="use")return`${q}(middleware: MiddlewareHandler | MiddlewareHandler[]): Router`;else if(q==="group")return`${q}(prefix: string, callback: (router: Router) => void): Router`;else return`${q}: Function`}).join(`
2597
118
  `)}
2598
119
 
2599
- ${extendedProperties.map((prop) => {
2600
- const propType = typeof router[prop];
2601
- return `${prop}: ${propType}`;
2602
- }).join(`
120
+ ${Q.map((q)=>{let X=typeof Z[q];return`${q}: ${X}`}).join(`
2603
121
  `)}
2604
122
  }
2605
123
 
@@ -2630,138 +148,9 @@ export type RouterExtension = {
2630
148
  * \`\`\`
2631
149
  */
2632
150
  export type ExtendRouter<T extends RouterExtension> = Router & T
2633
- `;
2634
- await fs4.writeFile(outputPath, typeContent);
2635
- console.log(chalk.green(`\u2728 Router types generated at ${outputPath}`));
2636
- } catch (error) {
2637
- if (error.code === "ERR_MODULE_NOT_FOUND") {
2638
- console.error(chalk.red(`Routes file not found at ${process12.cwd()}/routes/index.ts`));
2639
- console.error(chalk.yellow('Make sure your routes are defined and exported as "router" in routes/index.ts'));
2640
- } else {
2641
- console.error(chalk.red(`Error generating router types: ${error.message}`));
2642
- }
2643
- throw error;
2644
- }
2645
- }
2646
- async function watchRouterFiles(outputPath) {
2647
- const routerFiles = [
2648
- path3.join(process12.cwd(), "routes"),
2649
- path3.join(process12.cwd(), "src")
2650
- ];
2651
- let validPath = false;
2652
- for (const dirPath of routerFiles) {
2653
- try {
2654
- await fs4.access(dirPath);
2655
- validPath = true;
2656
- break;
2657
- } catch {}
2658
- }
2659
- if (!validPath) {
2660
- console.error(chalk.red(`No valid source directories found to watch.`));
2661
- process12.exit(1);
2662
- }
2663
- await generateRouterTypes(outputPath);
2664
- console.log(chalk.green(`\u2728 Router types generated at ${outputPath}`));
2665
- console.log(chalk.blue(`Watching for changes in router files...`));
2666
- let timeoutId = null;
2667
- for (const dirPath of routerFiles) {
2668
- try {
2669
- const watcher = fs4.watch(dirPath, { recursive: true });
2670
- (async () => {
2671
- for await (const _event of watcher) {
2672
- if (timeoutId) {
2673
- clearTimeout(timeoutId);
2674
- }
2675
- timeoutId = setTimeout(async () => {
2676
- console.log(chalk.yellow(`Changes detected in router files. Regenerating types...`));
2677
- try {
2678
- await generateRouterTypes(outputPath);
2679
- console.log(chalk.green(`\u2728 Router types regenerated at ${outputPath}`));
2680
- } catch (error) {
2681
- console.error(chalk.red(`Error regenerating types: ${error.message}`));
2682
- }
2683
- timeoutId = null;
2684
- }, 500);
2685
- }
2686
- })();
2687
- } catch {}
2688
- }
2689
- }
2690
-
2691
- // src/cli/routes.ts
2692
- import fs5 from "fs/promises";
2693
- import path4 from "path";
2694
- import process13 from "process";
2695
- async function displayRoutes(options) {
2696
- try {
2697
- const routesFile = `${process13.cwd()}/routes/index.ts`;
2698
- const { router } = await import(routesFile);
2699
- if (!router) {
2700
- console.error(chalk.red(`Could not find router instance in ${routesFile}.`));
2701
- process13.exit(1);
2702
- }
2703
- const routes = router.routes || [];
2704
- if (routes.length === 0) {
2705
- console.log(chalk.yellow("No routes defined."));
2706
- return;
2707
- }
2708
- let filteredRoutes = routes;
2709
- if (options.path) {
2710
- filteredRoutes = filteredRoutes.filter((route) => route.path.startsWith(options.path));
2711
- }
2712
- console.log(chalk.bold(`
2713
- Routes:`));
2714
- console.log(chalk.dim("+-----------------+-------------------------+------------------+----------------+"));
2715
- console.log(chalk.dim("| ") + chalk.bold("Method") + chalk.dim(" | ") + chalk.bold("URI") + chalk.dim(" | ") + chalk.bold("Name") + chalk.dim(" | ") + chalk.bold("Handler") + chalk.dim(" |"));
2716
- console.log(chalk.dim("+-----------------+-------------------------+------------------+----------------+"));
2717
- filteredRoutes.forEach((route) => {
2718
- const method = padString(route.method, 15);
2719
- const path5 = padString(route.path, 23);
2720
- const name = padString(route.name || "", 16);
2721
- let handler;
2722
- if (typeof route.handler === "string") {
2723
- handler = route.handler;
2724
- } else if (typeof route.handler === "function") {
2725
- handler = route.handler.name ? `${route.handler.name}()` : "Anonymous Function";
2726
- } else {
2727
- handler = "Class Handler";
2728
- }
2729
- handler = padString(handler, 14);
2730
- console.log(chalk.dim("| ") + getMethodColor(route.method)(method) + chalk.dim(" | ") + chalk.green(path5) + chalk.dim(" | ") + chalk.yellow(name) + chalk.dim(" | ") + chalk.blue(handler) + chalk.dim(" |"));
2731
- if (options.verbose && route.middleware && route.middleware.length > 0) {
2732
- console.log(chalk.dim("| | ") + chalk.dim("Middleware: ") + route.middleware.map((m) => typeof m === "string" ? m : m.name || "Anonymous").join(", ") + chalk.dim(" |"));
2733
- }
2734
- });
2735
- console.log(chalk.dim("+-----------------+-------------------------+------------------+----------------+"));
2736
- console.log(`
2737
- Showing ${filteredRoutes.length} routes`);
2738
- } catch (error) {
2739
- console.error(chalk.red(`Error: ${error.message}`));
2740
- console.error(chalk.yellow(`Make sure your routes are defined in ${process13.cwd()}/routes/index.ts and export a 'router' instance.`));
2741
- throw error;
2742
- }
2743
- }
2744
- async function generateRouteTypes(outputPath) {
2745
- try {
2746
- const routesFile = `${process13.cwd()}/routes/index.ts`;
2747
- const { router } = await import(routesFile);
2748
- if (!router) {
2749
- console.error(chalk.red(`Could not find router instance in ${routesFile}.`));
2750
- process13.exit(1);
2751
- }
2752
- const routes = router.routes || [];
2753
- if (routes.length === 0) {
2754
- console.log(chalk.yellow("No routes defined. Creating empty types file."));
2755
- }
2756
- const routeNames = routes.map((route) => {
2757
- if (route.name)
2758
- return route.name;
2759
- const methodLower = route.method.toLowerCase();
2760
- const pathFormatted = route.path.replace(/^\//, "").replace(/\//g, ".").replace(/\{([^}]+)\}/g, ":$1");
2761
- return pathFormatted ? `${methodLower}.${pathFormatted}` : methodLower;
2762
- });
2763
- const uniqueRouteNames = [...new Set(routeNames)];
2764
- const typeContent = `/**
151
+ `;await Q6.writeFile(z,j),console.log(U.green(`\u2728 Router types generated at ${z}`))}catch(J){if(J.code==="ERR_MODULE_NOT_FOUND")console.error(U.red(`Routes file not found at ${A.cwd()}/routes/index.ts`)),console.error(U.yellow('Make sure your routes are defined and exported as "router" in routes/index.ts'));else console.error(U.red(`Error generating router types: ${J.message}`));throw J}}async function P6(z){let J=[I6.join(A.cwd(),"routes"),I6.join(A.cwd(),"src")],Z=!1;for(let Q of J)try{await Q6.access(Q),Z=!0;break}catch{}if(!Z)console.error(U.red("No valid source directories found to watch.")),A.exit(1);await c(z),console.log(U.green(`\u2728 Router types generated at ${z}`)),console.log(U.blue("Watching for changes in router files..."));let $=null;for(let Q of J)try{let j=Q6.watch(Q,{recursive:!0});(async()=>{for await(let q of j){if($)clearTimeout($);$=setTimeout(async()=>{console.log(U.yellow("Changes detected in router files. Regenerating types..."));try{await c(z),console.log(U.green(`\u2728 Router types regenerated at ${z}`))}catch(X){console.error(U.red(`Error regenerating types: ${X.message}`))}$=null},500)}})()}catch{}}import Y6 from"fs/promises";import z4 from"path";import x from"process";async function C6(z){try{let J=`${x.cwd()}/routes/index.ts`,{router:Z}=await import(J);if(!Z)console.error(U.red(`Could not find router instance in ${J}.`)),x.exit(1);let $=Z.routes||[];if($.length===0){console.log(U.yellow("No routes defined."));return}let Q=$;if(z.path)Q=Q.filter((j)=>j.path.startsWith(z.path));console.log(U.bold(`
152
+ Routes:`)),console.log(U.dim("+-----------------+-------------------------+------------------+----------------+")),console.log(U.dim("| ")+U.bold("Method")+U.dim(" | ")+U.bold("URI")+U.dim(" | ")+U.bold("Name")+U.dim(" | ")+U.bold("Handler")+U.dim(" |")),console.log(U.dim("+-----------------+-------------------------+------------------+----------------+")),Q.forEach((j)=>{let q=i(j.method,15),X=i(j.path,23),Y=i(j.name||"",16),G;if(typeof j.handler==="string")G=j.handler;else if(typeof j.handler==="function")G=j.handler.name?`${j.handler.name}()`:"Anonymous Function";else G="Class Handler";if(G=i(G,14),console.log(U.dim("| ")+J4(j.method)(q)+U.dim(" | ")+U.green(X)+U.dim(" | ")+U.yellow(Y)+U.dim(" | ")+U.blue(G)+U.dim(" |")),z.verbose&&j.middleware&&j.middleware.length>0)console.log(U.dim("| | ")+U.dim("Middleware: ")+j.middleware.map((H)=>typeof H==="string"?H:H.name||"Anonymous").join(", ")+U.dim(" |"))}),console.log(U.dim("+-----------------+-------------------------+------------------+----------------+")),console.log(`
153
+ Showing ${Q.length} routes`)}catch(J){throw console.error(U.red(`Error: ${J.message}`)),console.error(U.yellow(`Make sure your routes are defined in ${x.cwd()}/routes/index.ts and export a 'router' instance.`)),J}}async function n(z){try{let J=`${x.cwd()}/routes/index.ts`,{router:Z}=await import(J);if(!Z)console.error(U.red(`Could not find router instance in ${J}.`)),x.exit(1);let $=Z.routes||[];if($.length===0)console.log(U.yellow("No routes defined. Creating empty types file."));let Q=$.map((X)=>{if(X.name)return X.name;let Y=X.method.toLowerCase(),G=X.path.replace(/^\//,"").replace(/\//g,".").replace(/\{([^}]+)\}/g,":$1");return G?`${Y}.${G}`:Y}),j=[...new Set(Q)],q=`/**
2765
154
  * This file is auto-generated.
2766
155
  * DO NOT EDIT THIS FILE DIRECTLY.
2767
156
  * To update, run 'bun router route:types'
@@ -2770,13 +159,13 @@ async function generateRouteTypes(outputPath) {
2770
159
  /**
2771
160
  * String literal type for all available route names
2772
161
  */
2773
- export type RouteName = ${uniqueRouteNames.length > 0 ? uniqueRouteNames.map((name) => `'${name}'`).join(" | ") : "string"}
162
+ export type RouteName = ${j.length>0?j.map((X)=>`'${X}'`).join(" | "):"string"}
2774
163
 
2775
164
  /**
2776
165
  * Object type with route names as keys and string (for path generation) as values
2777
166
  */
2778
167
  export interface RouteNameMap {
2779
- ${uniqueRouteNames.map((name) => ` '${name}': string`).join(`
168
+ ${j.map((X)=>` '${X}': string`).join(`
2780
169
  `)}
2781
170
  }
2782
171
 
@@ -2789,575 +178,13 @@ export type RouteFunction = <T extends RouteName>(name: T, params?: Record<strin
2789
178
  * Validate that a string is a valid route name
2790
179
  */
2791
180
  export function isValidRouteName(name: string): name is RouteName {
2792
- return [${uniqueRouteNames.map((name) => `'${name}'`).join(", ")}].includes(name)
2793
- }
2794
- `;
2795
- await fs5.writeFile(outputPath, typeContent);
2796
- console.log(chalk.green(`\u2728 Route types generated at ${outputPath}`));
2797
- } catch (error) {
2798
- if (error.code === "ERR_MODULE_NOT_FOUND") {
2799
- console.error(chalk.red(`Routes file not found at ${process13.cwd()}/routes/index.ts`));
2800
- console.error(chalk.yellow('Make sure your routes are defined and exported as "router" in routes/index.ts'));
2801
- } else {
2802
- console.error(chalk.red(`Error generating route types: ${error.message}`));
2803
- }
2804
- throw error;
2805
- }
2806
- }
2807
- async function watchRoutesDirectory(outputPath) {
2808
- const routesPath = path4.join(process13.cwd(), "routes");
2809
- try {
2810
- await fs5.access(routesPath);
2811
- } catch {
2812
- console.error(chalk.red(`Routes directory not found at ${routesPath}`));
2813
- process13.exit(1);
2814
- }
2815
- await generateRouteTypes(outputPath);
2816
- console.log(chalk.green(`\u2728 Route types generated at ${outputPath}`));
2817
- console.log(chalk.blue(`Watching for changes in ${routesPath}...`));
2818
- let timeoutId = null;
2819
- const watcher = fs5.watch(routesPath, { recursive: true });
2820
- for await (const _event of watcher) {
2821
- if (timeoutId) {
2822
- clearTimeout(timeoutId);
2823
- }
2824
- timeoutId = setTimeout(async () => {
2825
- console.log(chalk.yellow(`Changes detected in routes directory. Regenerating types...`));
2826
- try {
2827
- await generateRouteTypes(outputPath);
2828
- console.log(chalk.green(`\u2728 Route types regenerated at ${outputPath}`));
2829
- } catch (error) {
2830
- console.error(chalk.red(`Error regenerating types: ${error.message}`));
2831
- }
2832
- timeoutId = null;
2833
- }, 500);
2834
- }
2835
- }
2836
- function padString(str, length) {
2837
- return (str + " ".repeat(length)).substring(0, length);
2838
- }
2839
- function getMethodColor(method) {
2840
- switch (method.toUpperCase()) {
2841
- case "GET":
2842
- return chalk.cyan;
2843
- case "POST":
2844
- return chalk.green;
2845
- case "PUT":
2846
- return chalk.yellow;
2847
- case "PATCH":
2848
- return chalk.yellow;
2849
- case "DELETE":
2850
- return chalk.red;
2851
- case "OPTIONS":
2852
- return chalk.gray;
2853
- default:
2854
- return chalk.white;
2855
- }
2856
- }
2857
-
2858
- // src/cli/utils.ts
2859
- import process14 from "process";
2860
- var format = {
2861
- success: (message) => chalk.green(`\u2728 ${message}`),
2862
- info: (message) => chalk.blue(message),
2863
- warning: (message) => chalk.yellow(message),
2864
- error: (message) => chalk.red(message),
2865
- dim: (message) => chalk.dim(message),
2866
- bold: (message) => chalk.bold(message)
2867
- };
2868
- var logger = {
2869
- success: (message) => console.log(format.success(message)),
2870
- info: (message) => console.log(format.info(message)),
2871
- warning: (message) => console.log(format.warning(message)),
2872
- error: (message) => console.error(format.error(message)),
2873
- debug: (message) => console.debug(format.dim(message))
2874
- };
2875
- async function loadRouter() {
2876
- try {
2877
- const routesFile = `${process14.cwd()}/routes/index.ts`;
2878
- const { router } = await import(routesFile);
2879
- if (!router) {
2880
- logger.error(`Could not find router instance in ${routesFile}.`);
2881
- process14.exit(1);
2882
- }
2883
- return router;
2884
- } catch (error) {
2885
- if (error.code === "ERR_MODULE_NOT_FOUND") {
2886
- logger.error(`Routes file not found at ${process14.cwd()}/routes/index.ts`);
2887
- logger.warning('Make sure your routes are defined and exported as "router" in routes/index.ts');
2888
- } else {
2889
- logger.error(`Error loading router: ${error.message}`);
2890
- }
2891
- throw error;
2892
- }
2893
- }
2894
- function getMethodColor2(method) {
2895
- switch (method.toUpperCase()) {
2896
- case "GET":
2897
- return chalk.cyan.toString();
2898
- case "POST":
2899
- return chalk.green.toString();
2900
- case "PUT":
2901
- return chalk.yellow.toString();
2902
- case "PATCH":
2903
- return chalk.yellow.toString();
2904
- case "DELETE":
2905
- return chalk.red.toString();
2906
- case "OPTIONS":
2907
- return chalk.gray.toString();
2908
- default:
2909
- return chalk.white.toString();
2910
- }
2911
- }
2912
- async function checkRouterHealth(options) {
2913
- logger.info("\uD83D\uDD0D Checking router health...");
2914
- try {
2915
- const router = await loadRouter();
2916
- const routes = router.routes || [];
2917
- const globalMiddleware = router.globalMiddleware || [];
2918
- const namedRoutes = router.namedRoutes || new Map;
2919
- const health = {
2920
- totalRoutes: routes.length,
2921
- namedRoutes: namedRoutes.size,
2922
- globalMiddleware: globalMiddleware.length,
2923
- routesByMethod: {},
2924
- duplicateRoutes: [],
2925
- routesWithMiddleware: 0,
2926
- staticRoutes: 0,
2927
- dynamicRoutes: 0
2928
- };
2929
- const routeMap = new Map;
2930
- for (const route of routes) {
2931
- const key = `${route.method}:${route.path}`;
2932
- health.routesByMethod[route.method] = (health.routesByMethod[route.method] || 0) + 1;
2933
- if (!routeMap.has(key)) {
2934
- routeMap.set(key, []);
2935
- }
2936
- routeMap.get(key).push(route.path);
2937
- if (routeMap.get(key).length > 1) {
2938
- health.duplicateRoutes.push({ path: route.path, method: route.method });
2939
- }
2940
- if (route.middleware && route.middleware.length > 0) {
2941
- health.routesWithMiddleware++;
2942
- }
2943
- if (route.path.includes("{") || route.path.includes("*")) {
2944
- health.dynamicRoutes++;
2945
- } else {
2946
- health.staticRoutes++;
2947
- }
2948
- }
2949
- logger.success(`Router health check completed`);
2950
- console.log(`\uD83D\uDCCA Routes: ${health.totalRoutes} total (${health.staticRoutes} static, ${health.dynamicRoutes} dynamic)`);
2951
- console.log(`\uD83D\uDCDB Named routes: ${health.namedRoutes}`);
2952
- console.log(`\uD83D\uDEE1\uFE0F Global middleware: ${health.globalMiddleware}`);
2953
- console.log(`\uD83D\uDD27 Routes with middleware: ${health.routesWithMiddleware}`);
2954
- if (options.verbose) {
2955
- console.log(`
2956
- \uD83D\uDCC8 Routes by method:`);
2957
- for (const [method, count] of Object.entries(health.routesByMethod)) {
2958
- const color = getMethodColor2(method);
2959
- console.log(` ${chalk.hex(color)(method.padEnd(8))}: ${count}`);
2960
- }
2961
- if (health.duplicateRoutes.length > 0) {
2962
- logger.warning(`
2963
- \u26A0\uFE0F Found ${health.duplicateRoutes.length} duplicate route(s):`);
2964
- for (const duplicate of health.duplicateRoutes) {
2965
- console.log(` ${duplicate.method} ${duplicate.path}`);
2966
- }
2967
- }
2968
- const issues = [];
2969
- if (health.totalRoutes === 0) {
2970
- issues.push("No routes defined");
2971
- }
2972
- if (health.duplicateRoutes.length > 0) {
2973
- issues.push(`${health.duplicateRoutes.length} duplicate routes`);
2974
- }
2975
- if (health.routesWithMiddleware === 0 && health.globalMiddleware === 0) {
2976
- issues.push("No middleware configured");
2977
- }
2978
- if (issues.length > 0) {
2979
- logger.warning(`
2980
- \u26A0\uFE0F Potential issues:`);
2981
- for (const issue of issues) {
2982
- console.log(` \u2022 ${issue}`);
2983
- }
2984
- } else {
2985
- logger.success(`
2986
- \u2705 No issues detected`);
2987
- }
2988
- }
2989
- } catch (error) {
2990
- logger.error(`Health check failed: ${error.message}`);
2991
- throw error;
2992
- }
2993
- }
2994
- async function testRoutes(options) {
2995
- const baseUrl = options.baseUrl || "http://localhost:3000";
2996
- const timeout = options.timeout || 5000;
2997
- const allowedMethods = options.method ? options.method.split(",").map((m) => m.trim().toUpperCase()) : null;
2998
- logger.info(`\uD83E\uDDEA Testing routes at ${baseUrl}...`);
2999
- try {
3000
- const router = await loadRouter();
3001
- const routes = router.routes || [];
3002
- let filteredRoutes = routes;
3003
- if (options.filter) {
3004
- const pattern = new RegExp(options.filter.replace(/\*/g, ".*"));
3005
- filteredRoutes = routes.filter((route) => pattern.test(route.path));
3006
- }
3007
- if (allowedMethods) {
3008
- filteredRoutes = filteredRoutes.filter((route) => allowedMethods.includes(route.method));
3009
- }
3010
- if (filteredRoutes.length === 0) {
3011
- logger.warning("No routes match the specified filters");
3012
- return;
3013
- }
3014
- logger.info(`Testing ${filteredRoutes.length} routes...`);
3015
- const results = {
3016
- total: 0,
3017
- passed: 0,
3018
- failed: 0,
3019
- errors: []
3020
- };
3021
- for (const route of filteredRoutes) {
3022
- results.total++;
3023
- if (route.path.includes("{")) {
3024
- logger.debug(`Skipping parameterized route: ${route.method} ${route.path}`);
3025
- continue;
3026
- }
3027
- try {
3028
- const url = `${baseUrl}${route.path}`;
3029
- const response = await fetch(url, {
3030
- method: route.method,
3031
- signal: AbortSignal.timeout(timeout)
3032
- });
3033
- if (response.status < 500) {
3034
- results.passed++;
3035
- logger.debug(`\u2705 ${route.method} ${route.path} \u2192 ${response.status}`);
3036
- } else {
3037
- results.failed++;
3038
- results.errors.push({
3039
- route: `${route.method} ${route.path}`,
3040
- error: `HTTP ${response.status}`
3041
- });
3042
- }
3043
- } catch (error) {
3044
- results.failed++;
3045
- results.errors.push({
3046
- route: `${route.method} ${route.path}`,
3047
- error: error.message
3048
- });
3049
- }
3050
- }
3051
- console.log(`
3052
- \uD83D\uDCCA Test Results:`);
3053
- console.log(` Total: ${results.total}`);
3054
- console.log(` Passed: ${chalk.green(String(results.passed))}`);
3055
- console.log(` Failed: ${chalk.red(String(results.failed))}`);
3056
- if (results.errors.length > 0) {
3057
- console.log(`
3058
- \u274C Failures:`);
3059
- for (const error of results.errors) {
3060
- console.log(` ${error.route}: ${error.error}`);
3061
- }
3062
- }
3063
- if (results.failed > 0) {
3064
- process14.exit(1);
3065
- } else {
3066
- logger.success("All tests passed!");
3067
- }
3068
- } catch (error) {
3069
- logger.error(`Route testing failed: ${error.message}`);
3070
- throw error;
3071
- }
3072
- }
3073
- async function debugRoute(path5, options) {
3074
- const method = options.method?.toUpperCase() || "GET";
3075
- logger.info(`\uD83D\uDD0D Debugging route matching for: ${method} ${path5}`);
3076
- try {
3077
- const router = await loadRouter();
3078
- const match = router.matchRoute ? router.matchRoute(path5, method) : null;
3079
- if (match) {
3080
- logger.success(`\u2705 Route matched!`);
3081
- console.log(` Route: ${match.route.method} ${match.route.path}`);
3082
- console.log(` Handler: ${typeof match.route.handler}`);
3083
- if (Object.keys(match.params || {}).length > 0) {
3084
- console.log(` Parameters:`);
3085
- for (const [key, value] of Object.entries(match.params)) {
3086
- console.log(` ${key}: ${value}`);
3087
- }
3088
- }
3089
- if (match.route.middleware && match.route.middleware.length > 0) {
3090
- console.log(` Middleware: ${match.route.middleware.length} handler(s)`);
3091
- }
3092
- if (match.route.name) {
3093
- console.log(` Named route: ${match.route.name}`);
3094
- }
3095
- } else {
3096
- logger.error(`\u274C No route matched for ${method} ${path5}`);
3097
- if (options.verbose) {
3098
- console.log(`
3099
- \uD83D\uDCCB Available routes:`);
3100
- const routes = router.routes || [];
3101
- const methodRoutes = routes.filter((r) => r.method === method);
3102
- if (methodRoutes.length === 0) {
3103
- console.log(` No routes defined for ${method} method`);
3104
- } else {
3105
- for (const route of methodRoutes) {
3106
- console.log(` ${route.method} ${route.path}`);
3107
- }
3108
- }
3109
- }
3110
- }
3111
- } catch (error) {
3112
- logger.error(`Route debugging failed: ${error.message}`);
3113
- throw error;
3114
- }
3115
- }
3116
- async function clearCaches(options) {
3117
- logger.info("\uD83D\uDDD1\uFE0F Clearing route caches...");
3118
- try {
3119
- const router = await loadRouter();
3120
- if (options.stats) {
3121
- if (router.getCacheStats) {
3122
- const stats = router.getCacheStats();
3123
- console.log("\uD83D\uDCCA Cache statistics before clearing:");
3124
- console.log(` Hit rate: ${stats.hitRate}%`);
3125
- console.log(` Total hits: ${stats.hits}`);
3126
- console.log(` Total misses: ${stats.misses}`);
3127
- console.log(` Cache size: ${stats.size}`);
3128
- }
3129
- if (router.routeCache) {
3130
- console.log(` Route cache entries: ${router.routeCache.size}`);
3131
- }
3132
- if (router.templateCache) {
3133
- console.log(` Template cache entries: ${router.templateCache.size}`);
3134
- }
3135
- }
3136
- if (router.clearRouteCache) {
3137
- router.clearRouteCache();
3138
- }
3139
- if (router.routeCache && router.routeCache.clear) {
3140
- router.routeCache.clear();
3141
- }
3142
- if (router.templateCache && router.templateCache.clear) {
3143
- router.templateCache.clear();
3144
- }
3145
- if (router.clearModelCache) {
3146
- router.clearModelCache();
3147
- }
3148
- logger.success("\u2705 Caches cleared successfully");
3149
- } catch (error) {
3150
- logger.error(`Cache clearing failed: ${error.message}`);
3151
- throw error;
3152
- }
3153
- }
3154
- async function validateRoutes(options) {
3155
- logger.info("\uD83D\uDD0D Validating route definitions...");
3156
- try {
3157
- const router = await loadRouter();
3158
- const routes = router.routes || [];
3159
- const issues = [];
3160
- const warnings = [];
3161
- for (const route of routes) {
3162
- if (!route.method) {
3163
- issues.push(`Route missing method: ${route.path}`);
3164
- }
3165
- if (!route.path) {
3166
- issues.push(`Route missing path: ${route.method || "UNKNOWN"}`);
3167
- }
3168
- if (!route.handler) {
3169
- issues.push(`Route missing handler: ${route.method} ${route.path}`);
3170
- }
3171
- if (route.path && !route.path.startsWith("/")) {
3172
- issues.push(`Route path should start with '/': ${route.method} ${route.path}`);
3173
- }
3174
- if (route.path && route.path.includes("{")) {
3175
- const params = route.path.match(/\{[^}]+\}/g) || [];
3176
- for (const param of params) {
3177
- if (!param.match(/^\{[a-z_]\w*(\?|:[^}]+)?\}$/i)) {
3178
- issues.push(`Invalid parameter syntax in ${route.method} ${route.path}: ${param}`);
3179
- }
3180
- }
3181
- }
3182
- if (options.strict) {
3183
- if (!route.name && !route.path.includes("{") && route.path !== "/") {
3184
- warnings.push(`Consider adding a name to route: ${route.method} ${route.path}`);
3185
- }
3186
- if (route.path.includes("/admin") && (!route.middleware || route.middleware.length === 0)) {
3187
- warnings.push(`Admin route missing middleware: ${route.method} ${route.path}`);
3188
- }
3189
- }
3190
- }
3191
- const routeMap = new Map;
3192
- for (const route of routes) {
3193
- const key = `${route.method}:${route.path}`;
3194
- routeMap.set(key, (routeMap.get(key) || 0) + 1);
3195
- }
3196
- for (const [key, count] of routeMap.entries()) {
3197
- if (count > 1) {
3198
- issues.push(`Duplicate route detected: ${key} (${count} times)`);
3199
- }
3200
- }
3201
- if (issues.length === 0 && warnings.length === 0) {
3202
- logger.success("\u2705 All route definitions are valid");
3203
- return;
3204
- }
3205
- if (issues.length > 0) {
3206
- logger.error(`\u274C Found ${issues.length} validation error(s):`);
3207
- for (const issue of issues) {
3208
- console.log(` \u2022 ${issue}`);
3209
- }
3210
- }
3211
- if (warnings.length > 0) {
3212
- logger.warning(`\u26A0\uFE0F Found ${warnings.length} warning(s):`);
3213
- for (const warning of warnings) {
3214
- console.log(` \u2022 ${warning}`);
3215
- }
3216
- }
3217
- if (options.fix) {
3218
- logger.info("\uD83D\uDD27 Auto-fixing is not yet implemented");
3219
- }
3220
- if (issues.length > 0) {
3221
- process14.exit(1);
3222
- }
3223
- } catch (error) {
3224
- logger.error(`Route validation failed: ${error.message}`);
3225
- throw error;
3226
- }
3227
- }
3228
-
3229
- // src/cli/index.ts
3230
- function createCLI() {
3231
- const cli = new CLI("router");
3232
- cli.version(version);
3233
- registerRouteCommands(cli);
3234
- registerMiddlewareCommands(cli);
3235
- registerRouterCommands(cli);
3236
- registerOpenAPICommands(cli);
3237
- registerUtilityCommands(cli);
3238
- cli.help();
3239
- return cli;
3240
- }
3241
- function registerRouteCommands(cli) {
3242
- cli.command("route:list", "List all registered routes").option("-v, --verbose", "Show detailed information including middleware").option("-vv, --extra-verbose", "Show very detailed information").option("--path <path>", "Filter routes by path prefix").option("--except-vendor", "Exclude vendor routes").option("--only-vendor", "Show only vendor routes").example("router route:list").example("router route:list -v").example("router route:list --path=/api").action(async (options) => {
3243
- try {
3244
- await displayRoutes(options);
3245
- } catch (error) {
3246
- console.error(`Failed to list routes: ${error.message}`);
3247
- process15.exit(1);
3248
- }
3249
- });
3250
- cli.command("route:types", "Generate TypeScript types for route names").option("--output <file>", "Output file path", { default: "route-types.ts" }).option("--watch", "Watch for changes in routes directory").example("router route:types").example("router route:types --output src/types/routes.ts").example("router route:types --watch").action(async (options) => {
3251
- try {
3252
- const outputPath = options.output || "route-types.ts";
3253
- if (options.watch) {
3254
- await watchRoutesDirectory(outputPath);
3255
- } else {
3256
- await generateRouteTypes(outputPath);
3257
- }
3258
- } catch (error) {
3259
- console.error(`Failed to generate route types: ${error.message}`);
3260
- process15.exit(1);
3261
- }
3262
- });
3263
- }
3264
- function registerMiddlewareCommands(cli) {
3265
- cli.command("middleware:types", "Generate TypeScript types for middleware configurations").option("--output <file>", "Output file path", { default: "middleware-types.ts" }).option("--watch", "Watch for changes in middleware directory").example("router middleware:types").example("router middleware:types --output src/types/middleware.ts").example("router middleware:types --watch").action(async (options) => {
3266
- try {
3267
- const outputPath = options.output || "middleware-types.ts";
3268
- if (options.watch) {
3269
- await watchMiddlewareDirectory(outputPath);
3270
- } else {
3271
- await generateMiddlewareTypes(outputPath);
3272
- }
3273
- } catch (error) {
3274
- console.error(`Failed to generate middleware types: ${error.message}`);
3275
- process15.exit(1);
3276
- }
3277
- });
3278
- cli.command("middleware:map", "Generate TypeScript types for all middleware in the project").option("--dir <directory>", "Directory to scan for middleware classes", { default: "src" }).option("--output <file>", "Output file path", { default: "middleware-map.ts" }).option("--watch", "Watch for changes in the specified directory").example("router middleware:map").example("router middleware:map --dir app").example("router middleware:map --output src/types/project-middleware.ts").example("router middleware:map --watch").action(async (options) => {
3279
- try {
3280
- const outputPath = options.output || "middleware-map.ts";
3281
- const directoryPath = options.dir || "src";
3282
- if (options.watch) {
3283
- await watchDirectoryForMiddleware(directoryPath, outputPath);
3284
- } else {
3285
- await generateMiddlewareMap(directoryPath, outputPath);
3286
- }
3287
- } catch (error) {
3288
- console.error(`Failed to generate middleware map: ${error.message}`);
3289
- process15.exit(1);
3290
- }
3291
- });
3292
- }
3293
- function registerRouterCommands(cli) {
3294
- cli.command("router:types", "Generate TypeScript types for router extensions").option("--output <file>", "Output file path", { default: "router-types.ts" }).option("--watch", "Watch for changes in router files").example("router router:types").example("router router:types --output src/types/router.ts").example("router router:types --watch").action(async (options) => {
3295
- try {
3296
- const outputPath = options.output || "router-types.ts";
3297
- if (options.watch) {
3298
- await watchRouterFiles(outputPath);
3299
- } else {
3300
- await generateRouterTypes(outputPath);
3301
- }
3302
- } catch (error) {
3303
- console.error(`Failed to generate router types: ${error.message}`);
3304
- process15.exit(1);
3305
- }
3306
- });
3307
- }
3308
- function registerOpenAPICommands(cli) {
3309
- cli.command("openapi", "Generate OpenAPI specification for API routes").option("--output <file>", "Output file path", { default: "openapi.json" }).option("--title <title>", "API title", { default: "API Documentation" }).option("--version <version>", "API version", { default: "1.0.0" }).option("--description <description>", "API description").option("--base-path <path>", "Base API path", { default: "/" }).option("--servers <urls>", "Comma-separated list of server URLs").option("--tags", "Group endpoints by tags", { default: true }).option("--security", "Include security schemes if available", { default: true }).example("router openapi").example("router openapi --output api-spec.json").example('router openapi --title "My API" --version 2.0').example("router openapi --servers http://localhost:3000,https://api.example.com").action(async (options) => {
3310
- try {
3311
- await generateOpenAPISpec(options);
3312
- } catch (error) {
3313
- console.error(`Failed to generate OpenAPI specification: ${error.message}`);
3314
- process15.exit(1);
3315
- }
3316
- });
3317
- }
3318
- function registerUtilityCommands(cli) {
3319
- cli.command("health", "Check router health and configuration").option("--verbose", "Show detailed health information").example("router health").example("router health --verbose").action(async (options) => {
3320
- try {
3321
- await checkRouterHealth(options);
3322
- } catch (error) {
3323
- console.error(`Health check failed: ${error.message}`);
3324
- process15.exit(1);
3325
- }
3326
- });
3327
- cli.command("test:routes", "Test routes by making HTTP requests").option("--base-url <url>", "Base URL for testing", { default: "http://localhost:3000" }).option("--filter <pattern>", "Filter routes by path pattern").option("--method <methods>", "Test only specific HTTP methods (comma-separated)").option("--timeout <ms>", "Request timeout in milliseconds", { default: 5000 }).example("router test:routes").example("router test:routes --base-url http://localhost:8080").example('router test:routes --filter "/api/*"').example("router test:routes --method GET,POST").action(async (options) => {
3328
- try {
3329
- await testRoutes(options);
3330
- } catch (error) {
3331
- console.error(`Route testing failed: ${error.message}`);
3332
- process15.exit(1);
3333
- }
3334
- });
3335
- cli.command("debug:route <path>", "Debug route matching for a specific path").option("--method <method>", "HTTP method to test", { default: "GET" }).option("--verbose", "Show detailed matching information").example("router debug:route /api/users/123").example("router debug:route /api/users/123 --method POST --verbose").action(async (path5, options) => {
3336
- try {
3337
- await debugRoute(path5, options);
3338
- } catch (error) {
3339
- console.error(`Route debugging failed: ${error.message}`);
3340
- process15.exit(1);
3341
- }
3342
- });
3343
- cli.command("cache:clear", "Clear route caches").option("--stats", "Show cache statistics before clearing").example("router cache:clear").example("router cache:clear --stats").action(async (options) => {
3344
- try {
3345
- await clearCaches(options);
3346
- } catch (error) {
3347
- console.error(`Cache clearing failed: ${error.message}`);
3348
- process15.exit(1);
3349
- }
3350
- });
3351
- cli.command("validate", "Validate route definitions and configuration").option("--strict", "Use strict validation rules").option("--fix", "Automatically fix simple issues").example("router validate").example("router validate --strict --fix").action(async (options) => {
3352
- try {
3353
- await validateRoutes(options);
3354
- } catch (error) {
3355
- console.error(`Route validation failed: ${error.message}`);
3356
- process15.exit(1);
3357
- }
3358
- });
3359
- }
3360
-
3361
- // src/cli.ts
3362
- var cli = createCLI();
3363
- cli.parse();
181
+ return [${j.map((X)=>`'${X}'`).join(", ")}].includes(name)
182
+ }
183
+ `;await Y6.writeFile(z,q),console.log(U.green(`\u2728 Route types generated at ${z}`))}catch(J){if(J.code==="ERR_MODULE_NOT_FOUND")console.error(U.red(`Routes file not found at ${x.cwd()}/routes/index.ts`)),console.error(U.yellow('Make sure your routes are defined and exported as "router" in routes/index.ts'));else console.error(U.red(`Error generating route types: ${J.message}`));throw J}}async function R6(z){let J=z4.join(x.cwd(),"routes");try{await Y6.access(J)}catch{console.error(U.red(`Routes directory not found at ${J}`)),x.exit(1)}await n(z),console.log(U.green(`\u2728 Route types generated at ${z}`)),console.log(U.blue(`Watching for changes in ${J}...`));let Z=null,$=Y6.watch(J,{recursive:!0});for await(let Q of $){if(Z)clearTimeout(Z);Z=setTimeout(async()=>{console.log(U.yellow("Changes detected in routes directory. Regenerating types..."));try{await n(z),console.log(U.green(`\u2728 Route types regenerated at ${z}`))}catch(j){console.error(U.red(`Error regenerating types: ${j.message}`))}Z=null},500)}}function i(z,J){return(z+" ".repeat(J)).substring(0,J)}function J4(z){switch(z.toUpperCase()){case"GET":return U.cyan;case"POST":return U.green;case"PUT":return U.yellow;case"PATCH":return U.yellow;case"DELETE":return U.red;case"OPTIONS":return U.gray;default:return U.white}}import v from"process";var R={success:(z)=>U.green(`\u2728 ${z}`),info:(z)=>U.blue(z),warning:(z)=>U.yellow(z),error:(z)=>U.red(z),dim:(z)=>U.dim(z),bold:(z)=>U.bold(z)},F={success:(z)=>console.log(R.success(z)),info:(z)=>console.log(R.info(z)),warning:(z)=>console.log(R.warning(z)),error:(z)=>console.error(R.error(z)),debug:(z)=>console.debug(R.dim(z))};async function S(){try{let z=`${v.cwd()}/routes/index.ts`,{router:J}=await import(z);if(!J)F.error(`Could not find router instance in ${z}.`),v.exit(1);return J}catch(z){if(z.code==="ERR_MODULE_NOT_FOUND")F.error(`Routes file not found at ${v.cwd()}/routes/index.ts`),F.warning('Make sure your routes are defined and exported as "router" in routes/index.ts');else F.error(`Error loading router: ${z.message}`);throw z}}function Z4(z){switch(z.toUpperCase()){case"GET":return U.cyan.toString();case"POST":return U.green.toString();case"PUT":return U.yellow.toString();case"PATCH":return U.yellow.toString();case"DELETE":return U.red.toString();case"OPTIONS":return U.gray.toString();default:return U.white.toString()}}async function v6(z){F.info("\uD83D\uDD0D Checking router health...");try{let J=await S(),Z=J.routes||[],$=J.globalMiddleware||[],Q=J.namedRoutes||new Map,j={totalRoutes:Z.length,namedRoutes:Q.size,globalMiddleware:$.length,routesByMethod:{},duplicateRoutes:[],routesWithMiddleware:0,staticRoutes:0,dynamicRoutes:0},q=new Map;for(let X of Z){let Y=`${X.method}:${X.path}`;if(j.routesByMethod[X.method]=(j.routesByMethod[X.method]||0)+1,!q.has(Y))q.set(Y,[]);if(q.get(Y).push(X.path),q.get(Y).length>1)j.duplicateRoutes.push({path:X.path,method:X.method});if(X.middleware&&X.middleware.length>0)j.routesWithMiddleware++;if(X.path.includes("{")||X.path.includes("*"))j.dynamicRoutes++;else j.staticRoutes++}if(F.success("Router health check completed"),console.log(`\uD83D\uDCCA Routes: ${j.totalRoutes} total (${j.staticRoutes} static, ${j.dynamicRoutes} dynamic)`),console.log(`\uD83D\uDCDB Named routes: ${j.namedRoutes}`),console.log(`\uD83D\uDEE1\uFE0F Global middleware: ${j.globalMiddleware}`),console.log(`\uD83D\uDD27 Routes with middleware: ${j.routesWithMiddleware}`),z.verbose){console.log(`
184
+ \uD83D\uDCC8 Routes by method:`);for(let[Y,G]of Object.entries(j.routesByMethod)){let H=Z4(Y);console.log(` ${U.hex(H)(Y.padEnd(8))}: ${G}`)}if(j.duplicateRoutes.length>0){F.warning(`
185
+ \u26A0\uFE0F Found ${j.duplicateRoutes.length} duplicate route(s):`);for(let Y of j.duplicateRoutes)console.log(` ${Y.method} ${Y.path}`)}let X=[];if(j.totalRoutes===0)X.push("No routes defined");if(j.duplicateRoutes.length>0)X.push(`${j.duplicateRoutes.length} duplicate routes`);if(j.routesWithMiddleware===0&&j.globalMiddleware===0)X.push("No middleware configured");if(X.length>0){F.warning(`
186
+ \u26A0\uFE0F Potential issues:`);for(let Y of X)console.log(` \u2022 ${Y}`)}else F.success(`
187
+ \u2705 No issues detected`)}}catch(J){throw F.error(`Health check failed: ${J.message}`),J}}async function S6(z){let J=z.baseUrl||"http://localhost:3000",Z=z.timeout||5000,$=z.method?z.method.split(",").map((Q)=>Q.trim().toUpperCase()):null;F.info(`\uD83E\uDDEA Testing routes at ${J}...`);try{let j=(await S()).routes||[],q=j;if(z.filter){let Y=new RegExp(z.filter.replace(/\*/g,".*"));q=j.filter((G)=>Y.test(G.path))}if($)q=q.filter((Y)=>$.includes(Y.method));if(q.length===0){F.warning("No routes match the specified filters");return}F.info(`Testing ${q.length} routes...`);let X={total:0,passed:0,failed:0,errors:[]};for(let Y of q){if(X.total++,Y.path.includes("{")){F.debug(`Skipping parameterized route: ${Y.method} ${Y.path}`);continue}try{let G=`${J}${Y.path}`,H=await fetch(G,{method:Y.method,signal:AbortSignal.timeout(Z)});if(H.status<500)X.passed++,F.debug(`\u2705 ${Y.method} ${Y.path} \u2192 ${H.status}`);else X.failed++,X.errors.push({route:`${Y.method} ${Y.path}`,error:`HTTP ${H.status}`})}catch(G){X.failed++,X.errors.push({route:`${Y.method} ${Y.path}`,error:G.message})}}if(console.log(`
188
+ \uD83D\uDCCA Test Results:`),console.log(` Total: ${X.total}`),console.log(` Passed: ${U.green(String(X.passed))}`),console.log(` Failed: ${U.red(String(X.failed))}`),X.errors.length>0){console.log(`
189
+ \u274C Failures:`);for(let Y of X.errors)console.log(` ${Y.route}: ${Y.error}`)}if(X.failed>0)v.exit(1);else F.success("All tests passed!")}catch(Q){throw F.error(`Route testing failed: ${Q.message}`),Q}}async function k6(z,J){let Z=J.method?.toUpperCase()||"GET";F.info(`\uD83D\uDD0D Debugging route matching for: ${Z} ${z}`);try{let $=await S(),Q=$.matchRoute?$.matchRoute(z,Z):null;if(Q){if(F.success("\u2705 Route matched!"),console.log(` Route: ${Q.route.method} ${Q.route.path}`),console.log(` Handler: ${typeof Q.route.handler}`),Object.keys(Q.params||{}).length>0){console.log(" Parameters:");for(let[j,q]of Object.entries(Q.params))console.log(` ${j}: ${q}`)}if(Q.route.middleware&&Q.route.middleware.length>0)console.log(` Middleware: ${Q.route.middleware.length} handler(s)`);if(Q.route.name)console.log(` Named route: ${Q.route.name}`)}else if(F.error(`\u274C No route matched for ${Z} ${z}`),J.verbose){console.log(`
190
+ \uD83D\uDCCB Available routes:`);let q=($.routes||[]).filter((X)=>X.method===Z);if(q.length===0)console.log(` No routes defined for ${Z} method`);else for(let X of q)console.log(` ${X.method} ${X.path}`)}}catch($){throw F.error(`Route debugging failed: ${$.message}`),$}}async function y6(z){F.info("\uD83D\uDDD1\uFE0F Clearing route caches...");try{let J=await S();if(z.stats){if(J.getCacheStats){let Z=J.getCacheStats();console.log("\uD83D\uDCCA Cache statistics before clearing:"),console.log(` Hit rate: ${Z.hitRate}%`),console.log(` Total hits: ${Z.hits}`),console.log(` Total misses: ${Z.misses}`),console.log(` Cache size: ${Z.size}`)}if(J.routeCache)console.log(` Route cache entries: ${J.routeCache.size}`);if(J.templateCache)console.log(` Template cache entries: ${J.templateCache.size}`)}if(J.clearRouteCache)J.clearRouteCache();if(J.routeCache&&J.routeCache.clear)J.routeCache.clear();if(J.templateCache&&J.templateCache.clear)J.templateCache.clear();if(J.clearModelCache)J.clearModelCache();F.success("\u2705 Caches cleared successfully")}catch(J){throw F.error(`Cache clearing failed: ${J.message}`),J}}async function _6(z){F.info("\uD83D\uDD0D Validating route definitions...");try{let Z=(await S()).routes||[],$=[],Q=[];for(let q of Z){if(!q.method)$.push(`Route missing method: ${q.path}`);if(!q.path)$.push(`Route missing path: ${q.method||"UNKNOWN"}`);if(!q.handler)$.push(`Route missing handler: ${q.method} ${q.path}`);if(q.path&&!q.path.startsWith("/"))$.push(`Route path should start with '/': ${q.method} ${q.path}`);if(q.path&&q.path.includes("{")){let X=q.path.match(/\{[^}]+\}/g)||[];for(let Y of X)if(!Y.match(/^\{[a-z_]\w*(\?|:[^}]+)?\}$/i))$.push(`Invalid parameter syntax in ${q.method} ${q.path}: ${Y}`)}if(z.strict){if(!q.name&&!q.path.includes("{")&&q.path!=="/")Q.push(`Consider adding a name to route: ${q.method} ${q.path}`);if(q.path.includes("/admin")&&(!q.middleware||q.middleware.length===0))Q.push(`Admin route missing middleware: ${q.method} ${q.path}`)}}let j=new Map;for(let q of Z){let X=`${q.method}:${q.path}`;j.set(X,(j.get(X)||0)+1)}for(let[q,X]of j.entries())if(X>1)$.push(`Duplicate route detected: ${q} (${X} times)`);if($.length===0&&Q.length===0){F.success("\u2705 All route definitions are valid");return}if($.length>0){F.error(`\u274C Found ${$.length} validation error(s):`);for(let q of $)console.log(` \u2022 ${q}`)}if(Q.length>0){F.warning(`\u26A0\uFE0F Found ${Q.length} warning(s):`);for(let q of Q)console.log(` \u2022 ${q}`)}if(z.fix)F.info("\uD83D\uDD27 Auto-fixing is not yet implemented");if($.length>0)v.exit(1)}catch(J){throw F.error(`Route validation failed: ${J.message}`),J}}function g6(){let z=new z6("router");return z.version(E6),$4(z),Q4(z),Y4(z),j4(z),X4(z),z.help(),z}function $4(z){z.command("route:list","List all registered routes").option("-v, --verbose","Show detailed information including middleware").option("-vv, --extra-verbose","Show very detailed information").option("--path <path>","Filter routes by path prefix").option("--except-vendor","Exclude vendor routes").option("--only-vendor","Show only vendor routes").example("router route:list").example("router route:list -v").example("router route:list --path=/api").action(async(J)=>{try{await C6(J)}catch(Z){console.error(`Failed to list routes: ${Z.message}`),O.exit(1)}}),z.command("route:types","Generate TypeScript types for route names").option("--output <file>","Output file path",{default:"route-types.ts"}).option("--watch","Watch for changes in routes directory").example("router route:types").example("router route:types --output src/types/routes.ts").example("router route:types --watch").action(async(J)=>{try{let Z=J.output||"route-types.ts";if(J.watch)await R6(Z);else await n(Z)}catch(Z){console.error(`Failed to generate route types: ${Z.message}`),O.exit(1)}})}function Q4(z){z.command("middleware:types","Generate TypeScript types for middleware configurations").option("--output <file>","Output file path",{default:"middleware-types.ts"}).option("--watch","Watch for changes in middleware directory").example("router middleware:types").example("router middleware:types --output src/types/middleware.ts").example("router middleware:types --watch").action(async(J)=>{try{let Z=J.output||"middleware-types.ts";if(J.watch)await b6(Z);else await d(Z)}catch(Z){console.error(`Failed to generate middleware types: ${Z.message}`),O.exit(1)}}),z.command("middleware:map","Generate TypeScript types for all middleware in the project").option("--dir <directory>","Directory to scan for middleware classes",{default:"src"}).option("--output <file>","Output file path",{default:"middleware-map.ts"}).option("--watch","Watch for changes in the specified directory").example("router middleware:map").example("router middleware:map --dir app").example("router middleware:map --output src/types/project-middleware.ts").example("router middleware:map --watch").action(async(J)=>{try{let Z=J.output||"middleware-map.ts",$=J.dir||"src";if(J.watch)await x6($,Z);else await u($,Z)}catch(Z){console.error(`Failed to generate middleware map: ${Z.message}`),O.exit(1)}})}function Y4(z){z.command("router:types","Generate TypeScript types for router extensions").option("--output <file>","Output file path",{default:"router-types.ts"}).option("--watch","Watch for changes in router files").example("router router:types").example("router router:types --output src/types/router.ts").example("router router:types --watch").action(async(J)=>{try{let Z=J.output||"router-types.ts";if(J.watch)await P6(Z);else await c(Z)}catch(Z){console.error(`Failed to generate router types: ${Z.message}`),O.exit(1)}})}function j4(z){z.command("openapi","Generate OpenAPI specification for API routes").option("--output <file>","Output file path",{default:"openapi.json"}).option("--title <title>","API title",{default:"API Documentation"}).option("--version <version>","API version",{default:"1.0.0"}).option("--description <description>","API description").option("--base-path <path>","Base API path",{default:"/"}).option("--servers <urls>","Comma-separated list of server URLs").option("--tags","Group endpoints by tags",{default:!0}).option("--security","Include security schemes if available",{default:!0}).example("router openapi").example("router openapi --output api-spec.json").example('router openapi --title "My API" --version 2.0').example("router openapi --servers http://localhost:3000,https://api.example.com").action(async(J)=>{try{await A6(J)}catch(Z){console.error(`Failed to generate OpenAPI specification: ${Z.message}`),O.exit(1)}})}function X4(z){z.command("health","Check router health and configuration").option("--verbose","Show detailed health information").example("router health").example("router health --verbose").action(async(J)=>{try{await v6(J)}catch(Z){console.error(`Health check failed: ${Z.message}`),O.exit(1)}}),z.command("test:routes","Test routes by making HTTP requests").option("--base-url <url>","Base URL for testing",{default:"http://localhost:3000"}).option("--filter <pattern>","Filter routes by path pattern").option("--method <methods>","Test only specific HTTP methods (comma-separated)").option("--timeout <ms>","Request timeout in milliseconds",{default:5000}).example("router test:routes").example("router test:routes --base-url http://localhost:8080").example('router test:routes --filter "/api/*"').example("router test:routes --method GET,POST").action(async(J)=>{try{await S6(J)}catch(Z){console.error(`Route testing failed: ${Z.message}`),O.exit(1)}}),z.command("debug:route <path>","Debug route matching for a specific path").option("--method <method>","HTTP method to test",{default:"GET"}).option("--verbose","Show detailed matching information").example("router debug:route /api/users/123").example("router debug:route /api/users/123 --method POST --verbose").action(async(J,Z)=>{try{await k6(J,Z)}catch($){console.error(`Route debugging failed: ${$.message}`),O.exit(1)}}),z.command("cache:clear","Clear route caches").option("--stats","Show cache statistics before clearing").example("router cache:clear").example("router cache:clear --stats").action(async(J)=>{try{await y6(J)}catch(Z){console.error(`Cache clearing failed: ${Z.message}`),O.exit(1)}}),z.command("validate","Validate route definitions and configuration").option("--strict","Use strict validation rules").option("--fix","Automatically fix simple issues").example("router validate").example("router validate --strict --fix").action(async(J)=>{try{await _6(J)}catch(Z){console.error(`Route validation failed: ${Z.message}`),O.exit(1)}})}var q4=g6();q4.parse();