vector-framework 0.9.9 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js CHANGED
@@ -43,7 +43,6 @@ const { values, positionals } = parseArgs({
43
43
  const command = positionals[0] || "dev";
44
44
  async function runDev() {
45
45
  const isDev = command === "dev";
46
- console.log(`\n→ Starting Vector ${isDev ? "development" : "production"} server\n`);
47
46
  let server = null;
48
47
  let vector = null;
49
48
  async function startServer() {
@@ -58,7 +57,6 @@ async function runDev() {
58
57
  // Load configuration using ConfigLoader
59
58
  const configLoader = new ConfigLoader(values.config);
60
59
  const config = await configLoader.load();
61
- const configSource = configLoader.getConfigSource();
62
60
  // Merge CLI options with loaded config
63
61
  // Only use CLI values if config doesn't have them
64
62
  config.port = config.port ?? Number.parseInt(values.port);
@@ -96,18 +94,9 @@ async function runDev() {
96
94
  if (!server || !server.port) {
97
95
  throw new Error("Server started but is not responding correctly");
98
96
  }
99
- const gray = "\x1b[90m";
100
- const reset = "\x1b[0m";
101
97
  const cyan = "\x1b[36m";
102
- const green = "\x1b[32m";
103
- console.log(` ${gray}Config${reset} ${configSource === "user" ? "User config loaded" : "Using defaults"}`);
104
- console.log(` ${gray}Routes${reset} ${config.routesDir}`);
105
- if (isDev && values.watch) {
106
- console.log(` ${gray}Watching${reset} All project files`);
107
- }
108
- console.log(` ${gray}CORS${reset} ${config.cors ? "Enabled" : "Disabled"}`);
109
- console.log(` ${gray}Mode${reset} ${config.development ? "Development" : "Production"}\n`);
110
- console.log(` ${green}Ready${reset} → ${cyan}http://${config.hostname}:${config.port}${reset}\n`);
98
+ const reset = "\x1b[0m";
99
+ console.log(`\nListening on ${cyan}http://${config.hostname}:${config.port}${reset}\n`);
111
100
  return { server, vector, config };
112
101
  })();
113
102
  // Race between server startup and timeout
@@ -190,64 +179,74 @@ async function runDev() {
190
179
  });
191
180
  }
192
181
  catch {
193
- console.warn(" ⚠️ File watching not available");
182
+ const yellow = "\x1b[33m";
183
+ const reset = "\x1b[0m";
184
+ console.warn(`${yellow}Warning: File watching not available${reset}`);
194
185
  }
195
186
  }
196
187
  }
197
188
  catch (error) {
198
189
  const red = "\x1b[31m";
199
190
  const reset = "\x1b[0m";
200
- console.error(`\n${red}[ERROR] Failed to start server${reset}\n`);
201
- // Always show the error message and stack trace
202
- if (error.message) {
203
- console.error(`Message: ${error.message}`);
204
- }
205
- if (error.stack) {
206
- console.error(`\nStack trace:`);
191
+ console.error(`\n${red}Error: ${error.message || error}${reset}\n`);
192
+ if (error.stack && process.env.NODE_ENV === "development") {
207
193
  console.error(error.stack);
208
194
  }
209
- else if (!error.message) {
210
- // If no message or stack, show the raw error
211
- console.error(`Raw error:`, error);
212
- }
213
- // Ensure we exit with error code
214
195
  process.exit(1);
215
196
  }
216
197
  }
217
198
  async function runBuild() {
218
- console.log("\n→ Building Vector application\n");
219
199
  try {
220
200
  const { RouteScanner } = await import("../dev/route-scanner");
221
201
  const { RouteGenerator } = await import("../dev/route-generator");
202
+ // Step 1: Scan and generate routes
222
203
  const scanner = new RouteScanner(values.routes);
223
204
  const generator = new RouteGenerator();
224
205
  const routes = await scanner.scan();
225
206
  await generator.generate(routes);
226
- console.log(` Generated ${routes.length} routes`);
227
- // Use spawn based on runtime
207
+ // Step 2: Build the application with Bun
228
208
  if (typeof Bun !== "undefined") {
209
+ // Build the CLI as an executable
229
210
  const buildProcess = Bun.spawn([
230
211
  "bun",
231
212
  "build",
232
- "src/index.ts",
233
- "--outdir",
234
- "dist",
213
+ "src/cli/index.ts",
214
+ "--target",
215
+ "bun",
216
+ "--outfile",
217
+ "dist/server.js",
235
218
  "--minify",
236
219
  ]);
237
- await buildProcess.exited;
220
+ const exitCode = await buildProcess.exited;
221
+ if (exitCode !== 0) {
222
+ throw new Error(`Build failed with exit code ${exitCode}`);
223
+ }
238
224
  }
239
225
  else {
240
226
  // For Node.js, use child_process
241
227
  const { spawnSync } = await import("child_process");
242
- spawnSync("bun", ["build", "src/index.ts", "--outdir", "dist", "--minify"], {
228
+ const result = spawnSync("bun", [
229
+ "build",
230
+ "src/cli/index.ts",
231
+ "--target",
232
+ "bun",
233
+ "--outfile",
234
+ "dist/server.js",
235
+ "--minify",
236
+ ], {
243
237
  stdio: "inherit",
244
238
  shell: true,
245
239
  });
240
+ if (result.status !== 0) {
241
+ throw new Error(`Build failed with exit code ${result.status}`);
242
+ }
246
243
  }
247
- console.log("\n ✓ Build complete\n");
244
+ console.log("\nBuild complete: dist/server.js\n");
248
245
  }
249
246
  catch (error) {
250
- console.error("[ERROR] Build failed:", error);
247
+ const red = "\x1b[31m";
248
+ const reset = "\x1b[0m";
249
+ console.error(`\n${red}Error: ${error.message || error}${reset}\n`);
251
250
  process.exit(1);
252
251
  }
253
252
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/cli/index.ts"],"names":[],"mappings":";AAEA,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAChC,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AACnD,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAErD,4CAA4C;AAC5C,MAAM,IAAI,GACR,OAAO,GAAG,KAAK,WAAW,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AAEzE,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,GAAG,SAAS,CAAC;IACxC,IAAI;IACJ,OAAO,EAAE;QACP,IAAI,EAAE;YACJ,IAAI,EAAE,QAAQ;YACd,KAAK,EAAE,GAAG;YACV,OAAO,EAAE,MAAM;SAChB;QACD,IAAI,EAAE;YACJ,IAAI,EAAE,QAAQ;YACd,KAAK,EAAE,GAAG;YACV,OAAO,EAAE,WA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,CACF,CAAC;YAEF,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;gBACxB,MAAM,IAAI,KAAK,CAAC,+BAA+B,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC;YAClE,CAAC;QACH,CAAC;QAED,OAAO,CAAC,GAAG,CAAC,oCAAoC,CAAC,CAAC;IACpD,CAAC;IAAC,OAAO,KAAU,EAAE,CAAC;QACpB,MAAM,GAAG,GAAG,UAAU,CAAC;QACvB,MAAM,KAAK,GAAG,SAAS,CAAC;QACxB,OAAO,CAAC,KAAK,CAAC,KAAK,GAAG,UAAU,KAAK,CAAC,OAAO,IAAI,KAAK,GAAG,KAAK,IAAI,CAAC,CAAC;QACpE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;AACH,CAAC;AAED,QAAQ,OAAO,EAAE,CAAC;IAChB,KAAK,KAAK;QACR,MAAM,MAAM,EAAE,CAAC;QACf,MAAM;IACR,KAAK,OAAO;QACV,MAAM,QAAQ,EAAE,CAAC;QACjB,MAAM;IACR,KAAK,OAAO;QACV,OAAO,CAAC,GAAG,CAAC,QAAQ,GAAG,YAAY,CAAC;QACpC,MAAM,MAAM,EAAE,CAAC;QACf,MAAM;IACR;QACE,OAAO,CAAC,KAAK,CAAC,oBAAoB,OAAO,EAAE,CAAC,CAAC;QAC7C,OAAO,CAAC,GAAG,CAAC;;;;;;;;;;;;;;;CAef,CAAC,CAAC;QACC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC"}
package/dist/cli.js CHANGED
@@ -888,7 +888,6 @@ class VectorServer {
888
888
  if (!this.server || !this.server.port) {
889
889
  throw new Error(`Failed to start server on ${hostname}:${port} - server object is invalid`);
890
890
  }
891
- console.log(`\u2192 Vector server running at http://${hostname}:${port}`);
892
891
  return this.server;
893
892
  } catch (error) {
894
893
  if (error.code === "EADDRINUSE" || error.message?.includes("address already in use")) {
@@ -1093,20 +1092,17 @@ class ConfigLoader {
1093
1092
  async load() {
1094
1093
  if (existsSync2(this.configPath)) {
1095
1094
  try {
1096
- console.log(`\u2192 Loading config from: ${this.configPath}`);
1097
1095
  const userConfigPath = toFileUrl(this.configPath);
1098
1096
  const userConfig = await import(userConfigPath);
1099
1097
  this.config = userConfig.default || userConfig;
1100
1098
  this.configSource = "user";
1101
- console.log(" \u2713 User config loaded successfully");
1102
1099
  } catch (error) {
1103
- console.error(` \u2717 Failed to load config from ${this.configPath}:`, error);
1104
- console.log(" \u2192 Using default configuration");
1100
+ const red = "\x1B[31m";
1101
+ const reset = "\x1B[0m";
1102
+ console.error(`${red}Error loading config: ${error.message || error}${reset}`);
1105
1103
  this.config = {};
1106
1104
  }
1107
1105
  } else {
1108
- console.log(` \u2192 No config file found at: ${this.configPath}`);
1109
- console.log(" \u2192 Using default configuration");
1110
1106
  this.config = {};
1111
1107
  }
1112
1108
  return await this.buildLegacyConfig();
@@ -1198,9 +1194,6 @@ var { values, positionals } = parseArgs({
1198
1194
  var command = positionals[0] || "dev";
1199
1195
  async function runDev() {
1200
1196
  const isDev = command === "dev";
1201
- console.log(`
1202
- \u2192 Starting Vector ${isDev ? "development" : "production"} server
1203
- `);
1204
1197
  let server = null;
1205
1198
  let vector = null;
1206
1199
  async function startServer() {
@@ -1212,7 +1205,6 @@ async function runDev() {
1212
1205
  const serverStartPromise = (async () => {
1213
1206
  const configLoader = new ConfigLoader(values.config);
1214
1207
  const config = await configLoader.load();
1215
- const configSource = configLoader.getConfigSource();
1216
1208
  config.port = config.port ?? Number.parseInt(values.port);
1217
1209
  config.hostname = config.hostname ?? values.host;
1218
1210
  config.routesDir = config.routesDir ?? values.routes;
@@ -1241,19 +1233,10 @@ async function runDev() {
1241
1233
  if (!server || !server.port) {
1242
1234
  throw new Error("Server started but is not responding correctly");
1243
1235
  }
1244
- const gray = "\x1B[90m";
1245
- const reset = "\x1B[0m";
1246
1236
  const cyan = "\x1B[36m";
1247
- const green = "\x1B[32m";
1248
- console.log(` ${gray}Config${reset} ${configSource === "user" ? "User config loaded" : "Using defaults"}`);
1249
- console.log(` ${gray}Routes${reset} ${config.routesDir}`);
1250
- if (isDev && values.watch) {
1251
- console.log(` ${gray}Watching${reset} All project files`);
1252
- }
1253
- console.log(` ${gray}CORS${reset} ${config.cors ? "Enabled" : "Disabled"}`);
1254
- console.log(` ${gray}Mode${reset} ${config.development ? "Development" : "Production"}
1255
- `);
1256
- console.log(` ${green}Ready${reset} \u2192 ${cyan}http://${config.hostname}:${config.port}${reset}
1237
+ const reset = "\x1B[0m";
1238
+ console.log(`
1239
+ Listening on ${cyan}http://${config.hostname}:${config.port}${reset}
1257
1240
  `);
1258
1241
  return { server, vector, config };
1259
1242
  })();
@@ -1308,32 +1291,24 @@ async function runDev() {
1308
1291
  }
1309
1292
  });
1310
1293
  } catch {
1311
- console.warn(" \u26A0\uFE0F File watching not available");
1294
+ const yellow = "\x1B[33m";
1295
+ const reset = "\x1B[0m";
1296
+ console.warn(`${yellow}Warning: File watching not available${reset}`);
1312
1297
  }
1313
1298
  }
1314
1299
  } catch (error) {
1315
1300
  const red = "\x1B[31m";
1316
1301
  const reset = "\x1B[0m";
1317
1302
  console.error(`
1318
- ${red}[ERROR] Failed to start server${reset}
1303
+ ${red}Error: ${error.message || error}${reset}
1319
1304
  `);
1320
- if (error.message) {
1321
- console.error(`Message: ${error.message}`);
1322
- }
1323
- if (error.stack) {
1324
- console.error(`
1325
- Stack trace:`);
1305
+ if (error.stack && true) {
1326
1306
  console.error(error.stack);
1327
- } else if (!error.message) {
1328
- console.error(`Raw error:`, error);
1329
1307
  }
1330
1308
  process.exit(1);
1331
1309
  }
1332
1310
  }
1333
1311
  async function runBuild() {
1334
- console.log(`
1335
- \u2192 Building Vector application
1336
- `);
1337
1312
  try {
1338
1313
  const { RouteScanner: RouteScanner2 } = await Promise.resolve().then(() => (init_route_scanner(), exports_route_scanner));
1339
1314
  const { RouteGenerator: RouteGenerator2 } = await Promise.resolve().then(() => (init_route_generator(), exports_route_generator));
@@ -1341,29 +1316,48 @@ async function runBuild() {
1341
1316
  const generator = new RouteGenerator2;
1342
1317
  const routes = await scanner.scan();
1343
1318
  await generator.generate(routes);
1344
- console.log(` Generated ${routes.length} routes`);
1345
1319
  if (typeof Bun !== "undefined") {
1346
1320
  const buildProcess = Bun.spawn([
1347
1321
  "bun",
1348
1322
  "build",
1349
- "src/index.ts",
1350
- "--outdir",
1351
- "dist",
1323
+ "src/cli/index.ts",
1324
+ "--target",
1325
+ "bun",
1326
+ "--outfile",
1327
+ "dist/server.js",
1352
1328
  "--minify"
1353
1329
  ]);
1354
- await buildProcess.exited;
1330
+ const exitCode = await buildProcess.exited;
1331
+ if (exitCode !== 0) {
1332
+ throw new Error(`Build failed with exit code ${exitCode}`);
1333
+ }
1355
1334
  } else {
1356
1335
  const { spawnSync } = await import("child_process");
1357
- spawnSync("bun", ["build", "src/index.ts", "--outdir", "dist", "--minify"], {
1336
+ const result = spawnSync("bun", [
1337
+ "build",
1338
+ "src/cli/index.ts",
1339
+ "--target",
1340
+ "bun",
1341
+ "--outfile",
1342
+ "dist/server.js",
1343
+ "--minify"
1344
+ ], {
1358
1345
  stdio: "inherit",
1359
1346
  shell: true
1360
1347
  });
1348
+ if (result.status !== 0) {
1349
+ throw new Error(`Build failed with exit code ${result.status}`);
1350
+ }
1361
1351
  }
1362
1352
  console.log(`
1363
- \u2713 Build complete
1353
+ Build complete: dist/server.js
1364
1354
  `);
1365
1355
  } catch (error) {
1366
- console.error("[ERROR] Build failed:", error);
1356
+ const red = "\x1B[31m";
1357
+ const reset = "\x1B[0m";
1358
+ console.error(`
1359
+ ${red}Error: ${error.message || error}${reset}
1360
+ `);
1367
1361
  process.exit(1);
1368
1362
  }
1369
1363
  }
@@ -1 +1 @@
1
- {"version":3,"file":"config-loader.d.ts","sourceRoot":"","sources":["../../src/core/config-loader.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACV,YAAY,EAEZ,kBAAkB,EAClB,gBAAgB,EAChB,YAAY,E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IAAI;CAG/C"}
@@ -17,24 +17,21 @@ export class ConfigLoader {
17
17
  // Check if config file exists before attempting to load
18
18
  if (existsSync(this.configPath)) {
19
19
  try {
20
- console.log(`→ Loading config from: ${this.configPath}`);
21
20
  // Use explicit file:// URL to ensure correct resolution
22
21
  const userConfigPath = toFileUrl(this.configPath);
23
22
  const userConfig = await import(userConfigPath);
24
23
  this.config = userConfig.default || userConfig;
25
24
  this.configSource = "user";
26
- console.log(" ✓ User config loaded successfully");
27
25
  }
28
26
  catch (error) {
29
- console.error(` ✗ Failed to load config from ${this.configPath}:`, error);
30
- console.log(" → Using default configuration");
27
+ const red = "\x1b[31m";
28
+ const reset = "\x1b[0m";
29
+ console.error(`${red}Error loading config: ${error.message || error}${reset}`);
31
30
  this.config = {};
32
31
  }
33
32
  }
34
33
  else {
35
34
  // Config file doesn't exist, use defaults
36
- console.log(` → No config file found at: ${this.configPath}`);
37
- console.log(" → Using default configuration");
38
35
  this.config = {};
39
36
  }
40
37
  // Convert new config schema to legacy VectorConfig format
@@ -1 +1 @@
1
- {"version":3,"file":"config-loader.js","sourceRoot":"","sources":["../../src/core/config-loader.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAW1C,MAAM,OAAO,YAAY;IACf,UAAU,CAAS;IACnB,MAAM,GAAsC,IAAI,CAAC;IACjD,YAAY,GAAuB,SAAS,CAAC;IAErD,YAAY,UAAmB;QAC7B,0DAA0D;QAC1D,MAAM,IAAI,GAAG,UAAU,IAAI,kBAAkB,CAAC;QAE9C,oCAAoC;QACpC,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC,IAAI,CAAC;YAChC,CAAC,CAAC,IAAI;YACN,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,IAAI,CAA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AAG,IAAI;IAI1B,OAAO,IAAI,MAAM;IAIjB,WAAW,IAAI,MAAM;IAIrB,MAAM,IAAI,MAAM;CAKjB"}
@@ -66,8 +66,7 @@ export class VectorServer {
66
66
  if (!this.server || !this.server.port) {
67
67
  throw new Error(`Failed to start server on ${hostname}:${port} - server object is invalid`);
68
68
  }
69
- // Server logs are handled by CLI, keep this minimal
70
- console.log(`→ Vector server running at http://${hostname}:${port}`);
69
+ // Server logs are handled by CLI
71
70
  return this.server;
72
71
  }
73
72
  catch (error) {
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/core/server.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAC;AASnC,MAAM,OAAO,YAAY;IACf,MAAM,GAAkB,IAAI,CAAC;IAC7B,MAAM,CAAuB;IAC7B,MAAM,CAAuB;IAC7B,WAAW,CAAM;IAEzB,YAAY,MAA4B,EAAE,MAA4B;QACpE,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QAErB,IAAI,MAAM,CAAC,IAAI,EAAE,CAAC;YAChB,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,GAAG,IAAI,CACjC,IAAI,CAAC,oBAAoB,CAAC,MAAM,CAAC,IAAI,CAAC,CACvC,CAAC;YACF,IAAI,CAAC,WAAW,GAAG,EAAE,SAAS,EAAE,OAAO,EAAE,CAAC;QAC5C,CAAC;IACH,CAAC;IAEO,oBAAoB,CAAC,OAAoB;QAC/C,OAAO;YACL,MAAM,EAAE,OAAO,CAAC,MAAM,IAAI,GAAG;YAC7B,WAAW,EAAE,OAAO,CAAC,WAAW,KAAK,KAAK;YAC1C,YAAY,EAAE,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,YAAY,CAAC;gBAC/C,CAAC,CAAC,OAAO,CAAC,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC;gBACjC,CAAC,CAAC,O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ED,IAAI;QACF,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;YAChB,IAAI,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC;YACnB,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;YACnB,OAAO,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC;QAChC,CAAC;IACH,CAAC;IAED,SAAS;QACP,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;IAED,OAAO;QACL,OAAO,IAAI,CAAC,MAAM,EAAE,IAAI,IAAI,IAAI,CAAC,MAAM,CAAC,IAAI,IAAI,IAAI,CAAC;IACvD,CAAC;IAED,WAAW;QACT,OAAO,IAAI,CAAC,MAAM,EAAE,QAAQ,IAAI,IAAI,CAAC,MAAM,CAAC,QAAQ,IAAI,WAAW,CAAC;IACtE,CAAC;IAED,MAAM;QACJ,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,EAAE,CAAC;QAC5B,MAAM,QAAQ,GAAG,IAAI,CAAC,WAAW,EAAE,CAAC;QACpC,OAAO,UAAU,QAAQ,IAAI,IAAI,EAAE,CAAC;IACtC,CAAC;CACF"}
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- var{defineProperty:z,getOwnPropertyNames:n,getOwnPropertyDescriptor:s}=Object,p=Object.prototype.hasOwnProperty;var T=new WeakMap,r=(i)=>{var f=T.get(i),l;if(f)return f;if(f=z({},"__esModule",{value:!0}),i&&typeof i==="object"||typeof i==="function")n(i).map((E)=>!p.call(f,E)&&z(f,E,{get:()=>i[E],enumerable:!(l=s(i,E))||l.enumerable}));return T.set(i,f),f};var o=(i,f)=>{for(var l in f)z(i,l,{get:f[l],enumerable:!0,configurable:!0,set:(E)=>f[l]=()=>E})};var Li={};o(Li,{route:()=>y,createResponse:()=>P,APIError:()=>S});module.exports=r(Li);var G=(i="text/plain; charset=utf-8",f)=>(l,E={})=>{if(l===void 0||l instanceof Response)return l;let _=new Response(f?.(l)??l,E.url?void 0:E);return _.headers.set("content-type",i),_},$i=G("application/json; charset=utf-8",JSON.stringify);var wi=G("text/plain; charset=utf-8",String),Ci=G("text/html"),Si=G("image/jpeg"),bi=G("image/png"),Ri=G("image/webp"),k=async(i)=>{i.content=i.body?await i.clone().json().catch(()=>i.clone().formData()).catch(()=>i.text()):void 0},g=(i)=>{i.cookies=(i.headers.get("Cookie")||"").split(/;\s*/).map((f)=>f.split(/=(.+)/)).reduce((f,[l,E])=>E?(f[l]=E,f):f,{})},H=(i={})=>{let{origin:f="*",credentials:l=!1,allowMethods:E="*",allowHeaders:_,exposeHeaders:A,maxAge:N}=i,O=(D)=>{let I=D?.headers.get("origin");return f===!0?I:f instanceof RegExp?f.test(I)?I:void 0:Array.isArray(f)?f.includes(I)?I:void 0:f instanceof Function?f(I):f=="*"&&l?I:f},U=(D,I)=>{for(let[$,w]of Object.entries(I))w&&D.headers.append($,w);return D};return{corsify:(D,I)=>D?.headers?.get("access-control-allow-origin")||D.status==101?D:U(D.clone(),{"access-control-allow-origin":O(I),"access-control-allow-credentials":l}),preflight:(D)=>{if(D.method=="OPTIONS"){let I=new Response(null,{status:204});return U(I,{"access-control-allow-origin":O(D),"access-control-allow-methods":E?.join?.(",")??E,"access-control-expose-headers":A?.join?.(",")??A,"access-control-allow-headers":_?.join?.(",")??_??D.headers.get("access-control-request-headers"),"access-control-max-age":N,"access-control-allow-credentials":l})}}}};var C={OK:200,CREATED:201,ACCEPTED:202,NON_AUTHORITATIVE_INFORMATION:203,NO_CONTENT:204,RESET_CONTENT:205,PARTIAL_CONTENT:206,MULTI_STATUS:207,ALREADY_REPORTED:208,IM_USED:226,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,USE_PROXY:305,TEMPORARY_REDIRECT:307,PERMANENT_REDIRECT:308,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,IM_A_TEAPOT:418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511},J={PORT:3000,HOSTNAME:"localhost",ROUTES_DIR:"./routes",CACHE_TTL:0,CORS_MAX_AGE:86400},F={JSON:"application/json",TEXT:"text/plain",HTML:"text/html",FORM_URLENCODED:"application/x-www-form-urlencoded",MULTIPART:"multipart/form-data"};class W{protectedHandler=null;setProtectedHandler(i){this.protectedHandler=i}async authenticate(i){if(!this.protectedHandler)throw new Error("Protected handler not configured. Use vector.protected() to set authentication handler.");try{let f=await this.protectedHandler(i);return i.authUser=f,f}catch(f){throw new Error(`Authentication failed: ${f instanceof Error?f.message:String(f)}`)}}isAuthenticated(i){return!!i.authUser}getUser(i){return i.authUser||null}}class h{cacheHandler=null;memoryCache=new Map;cleanupInterval=null;setCacheHandler(i){this.cacheHandler=i}async get(i,f,l=J.CACHE_TTL){if(l<=0)return f();if(this.cacheHandler)return this.cacheHandler(i,f,l);return this.getFromMemoryCache(i,f,l)}async getFromMemoryCache(i,f,l){let E=Date.now(),_=this.memoryCache.get(i);if(this.isCacheValid(_,E))return _.value;let A=await f();return this.setInMemoryCache(i,A,l),A}isCacheValid(i,f){return i!==void 0&&i.expires>f}setInMemoryCache(i,f,l){let E=Date.now()+l*1000;this.memoryCache.set(i,{value:f,expires:E}),this.scheduleCleanup()}scheduleCleanup(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanupExpired()},60000)}cleanupExpired(){let i=Date.now();for(let[f,l]of this.memoryCache.entries())if(l.expires<=i)this.memoryCache.delete(f);if(this.memoryCache.size===0&&this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}clear(){if(this.memoryCache.clear(),this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}async set(i,f,l=J.CACHE_TTL){if(l<=0)return;if(this.cacheHandler){await this.cacheHandler(i,async()=>f,l);return}this.setInMemoryCache(i,f,l)}delete(i){return this.memoryCache.delete(i)}has(i){let f=this.memoryCache.get(i);if(!f)return!1;if(f.expires<=Date.now())return this.memoryCache.delete(i),!1;return!0}generateKey(i,f){let l=new URL(i.url);return[i.method,l.pathname,l.search,f?.authUser?.id||"anonymous"].join(":")}}var V=(()=>({}));function b(i){if(typeof i!=="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(i))}function c(i,f){var l="",E=0,_=-1,A=0,N;for(var O=0;O<=i.length;++O){if(O<i.length)N=i.charCodeAt(O);else if(N===47)break;else N=47;if(N===47){if(_===O-1||A===1);else if(_!==O-1&&A===2){if(l.length<2||E!==2||l.charCodeAt(l.length-1)!==46||l.charCodeAt(l.length-2)!==46){if(l.length>2){var U=l.lastIndexOf("/");if(U!==l.length-1){if(U===-1)l="",E=0;else l=l.slice(0,U),E=l.length-1-l.lastIndexOf("/");_=O,A=0;continue}}else if(l.length===2||l.length===1){l="",E=0,_=O,A=0;continue}}if(f){if(l.length>0)l+="/..";else l="..";E=2}}else{if(l.length>0)l+="/"+i.slice(_+1,O);else l=i.slice(_+1,O);E=O-_-1}_=O,A=0}else if(N===46&&A!==-1)++A;else A=-1}return l}function t(i,f){var l=f.dir||f.root,E=f.base||(f.name||"")+(f.ext||"");if(!l)return E;if(l===f.root)return l+E;return l+i+E}function j(){var i="",f=!1,l;for(var E=arguments.length-1;E>=-1&&!f;E--){var _;if(E>=0)_=arguments[E];else{if(l===void 0)l=process.cwd();_=l}if(b(_),_.length===0)continue;i=_+"/"+i,f=_.charCodeAt(0)===47}if(i=c(i,!f),f)if(i.length>0)return"/"+i;else return"/";else if(i.length>0)return i;else return"."}function m(i){if(b(i),i.length===0)return".";var f=i.charCodeAt(0)===47,l=i.charCodeAt(i.length-1)===47;if(i=c(i,!f),i.length===0&&!f)i=".";if(i.length>0&&l)i+="/";if(f)return"/"+i;return i}function e(i){return b(i),i.length>0&&i.charCodeAt(0)===47}function M(){if(arguments.length===0)return".";var i;for(var f=0;f<arguments.length;++f){var l=arguments[f];if(b(l),l.length>0)if(i===void 0)i=l;else i+="/"+l}if(i===void 0)return".";return m(i)}function a(i,f){if(b(i),b(f),i===f)return"";if(i=j(i),f=j(f),i===f)return"";var l=1;for(;l<i.length;++l)if(i.charCodeAt(l)!==47)break;var E=i.length,_=E-l,A=1;for(;A<f.length;++A)if(f.charCodeAt(A)!==47)break;var N=f.length,O=N-A,U=_<O?_:O,D=-1,I=0;for(;I<=U;++I){if(I===U){if(O>U){if(f.charCodeAt(A+I)===47)return f.slice(A+I+1);else if(I===0)return f.slice(A+I)}else if(_>U){if(i.charCodeAt(l+I)===47)D=I;else if(I===0)D=0}break}var $=i.charCodeAt(l+I),w=f.charCodeAt(A+I);if($!==w)break;else if($===47)D=I}var R="";for(I=l+D+1;I<=E;++I)if(I===E||i.charCodeAt(I)===47)if(R.length===0)R+="..";else R+="/..";if(R.length>0)return R+f.slice(A+D);else{if(A+=D,f.charCodeAt(A)===47)++A;return f.slice(A)}}function ii(i){return i}function Y(i){if(b(i),i.length===0)return".";var f=i.charCodeAt(0),l=f===47,E=-1,_=!0;for(var A=i.length-1;A>=1;--A)if(f=i.charCodeAt(A),f===47){if(!_){E=A;break}}else _=!1;if(E===-1)return l?"/":".";if(l&&E===1)return"//";return i.slice(0,E)}function fi(i,f){if(f!==void 0&&typeof f!=="string")throw new TypeError('"ext" argument must be a string');b(i);var l=0,E=-1,_=!0,A;if(f!==void 0&&f.length>0&&f.length<=i.length){if(f.length===i.length&&f===i)return"";var N=f.length-1,O=-1;for(A=i.length-1;A>=0;--A){var U=i.charCodeAt(A);if(U===47){if(!_){l=A+1;break}}else{if(O===-1)_=!1,O=A+1;if(N>=0)if(U===f.charCodeAt(N)){if(--N===-1)E=A}else N=-1,E=O}}if(l===E)E=O;else if(E===-1)E=i.length;return i.slice(l,E)}else{for(A=i.length-1;A>=0;--A)if(i.charCodeAt(A)===47){if(!_){l=A+1;break}}else if(E===-1)_=!1,E=A+1;if(E===-1)return"";return i.slice(l,E)}}function li(i){b(i);var f=-1,l=0,E=-1,_=!0,A=0;for(var N=i.length-1;N>=0;--N){var O=i.charCodeAt(N);if(O===47){if(!_){l=N+1;break}continue}if(E===-1)_=!1,E=N+1;if(O===46){if(f===-1)f=N;else if(A!==1)A=1}else if(f!==-1)A=-1}if(f===-1||E===-1||A===0||A===1&&f===E-1&&f===l+1)return"";return i.slice(f,E)}function Ei(i){if(i===null||typeof i!=="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof i);return t("/",i)}function Ai(i){b(i);var f={root:"",dir:"",base:"",ext:"",name:""};if(i.length===0)return f;var l=i.charCodeAt(0),E=l===47,_;if(E)f.root="/",_=1;else _=0;var A=-1,N=0,O=-1,U=!0,D=i.length-1,I=0;for(;D>=_;--D){if(l=i.charCodeAt(D),l===47){if(!U){N=D+1;break}continue}if(O===-1)U=!1,O=D+1;if(l===46){if(A===-1)A=D;else if(I!==1)I=1}else if(A!==-1)I=-1}if(A===-1||O===-1||I===0||I===1&&A===O-1&&A===N+1){if(O!==-1)if(N===0&&E)f.base=f.name=i.slice(1,O);else f.base=f.name=i.slice(N,O)}else{if(N===0&&E)f.name=i.slice(1,A),f.base=i.slice(1,O);else f.name=i.slice(N,A),f.base=i.slice(N,O);f.ext=i.slice(A,O)}if(N>0)f.dir=i.slice(0,N-1);else if(E)f.dir="/";return f}var Q="/",_i=":",xi=((i)=>(i.posix=i,i))({resolve:j,normalize:m,isAbsolute:e,join:M,relative:a,_makeLong:ii,dirname:Y,basename:fi,extname:li,format:Ei,parse:Ai,sep:Q,delimiter:_i,win32:null,posix:null});class K{outputPath;constructor(i="./.vector/routes.generated.ts"){this.outputPath=i}async generate(i){let f=Y(this.outputPath);await V.promises.mkdir(f,{recursive:!0});let l=[],E=new Map;for(let O of i){if(!E.has(O.path))E.set(O.path,[]);E.get(O.path).push(O)}let _=0,A=[];for(let[O,U]of E){let D=a(Y(this.outputPath),O).replace(/\\/g,"/").replace(/\.(ts|js)$/,""),I=`route_${_++}`,$=U.filter((w)=>w.name!=="default").map((w)=>w.name);if(U.some((w)=>w.name==="default"))if($.length>0)l.push(`import ${I}, { ${$.join(", ")} } from '${D}';`);else l.push(`import ${I} from '${D}';`);else if($.length>0)l.push(`import { ${$.join(", ")} } from '${D}';`);for(let w of U){let R=w.name==="default"?I:w.name;A.push(` ${R},`)}}let N=`// This file is auto-generated. Do not edit manually.
1
+ var{defineProperty:h,getOwnPropertyNames:n,getOwnPropertyDescriptor:s}=Object,p=Object.prototype.hasOwnProperty;var T=new WeakMap,r=(i)=>{var f=T.get(i),l;if(f)return f;if(f=h({},"__esModule",{value:!0}),i&&typeof i==="object"||typeof i==="function")n(i).map((E)=>!p.call(f,E)&&h(f,E,{get:()=>i[E],enumerable:!(l=s(i,E))||l.enumerable}));return T.set(i,f),f};var o=(i,f)=>{for(var l in f)h(i,l,{get:f[l],enumerable:!0,configurable:!0,set:(E)=>f[l]=()=>E})};var Li={};o(Li,{route:()=>y,createResponse:()=>P,APIError:()=>S});module.exports=r(Li);var G=(i="text/plain; charset=utf-8",f)=>(l,E={})=>{if(l===void 0||l instanceof Response)return l;let _=new Response(f?.(l)??l,E.url?void 0:E);return _.headers.set("content-type",i),_},$i=G("application/json; charset=utf-8",JSON.stringify);var wi=G("text/plain; charset=utf-8",String),Ci=G("text/html"),Si=G("image/jpeg"),bi=G("image/png"),Ri=G("image/webp"),k=async(i)=>{i.content=i.body?await i.clone().json().catch(()=>i.clone().formData()).catch(()=>i.text()):void 0},g=(i)=>{i.cookies=(i.headers.get("Cookie")||"").split(/;\s*/).map((f)=>f.split(/=(.+)/)).reduce((f,[l,E])=>E?(f[l]=E,f):f,{})},H=(i={})=>{let{origin:f="*",credentials:l=!1,allowMethods:E="*",allowHeaders:_,exposeHeaders:A,maxAge:N}=i,O=(D)=>{let I=D?.headers.get("origin");return f===!0?I:f instanceof RegExp?f.test(I)?I:void 0:Array.isArray(f)?f.includes(I)?I:void 0:f instanceof Function?f(I):f=="*"&&l?I:f},U=(D,I)=>{for(let[$,w]of Object.entries(I))w&&D.headers.append($,w);return D};return{corsify:(D,I)=>D?.headers?.get("access-control-allow-origin")||D.status==101?D:U(D.clone(),{"access-control-allow-origin":O(I),"access-control-allow-credentials":l}),preflight:(D)=>{if(D.method=="OPTIONS"){let I=new Response(null,{status:204});return U(I,{"access-control-allow-origin":O(D),"access-control-allow-methods":E?.join?.(",")??E,"access-control-expose-headers":A?.join?.(",")??A,"access-control-allow-headers":_?.join?.(",")??_??D.headers.get("access-control-request-headers"),"access-control-max-age":N,"access-control-allow-credentials":l})}}}};var C={OK:200,CREATED:201,ACCEPTED:202,NON_AUTHORITATIVE_INFORMATION:203,NO_CONTENT:204,RESET_CONTENT:205,PARTIAL_CONTENT:206,MULTI_STATUS:207,ALREADY_REPORTED:208,IM_USED:226,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,USE_PROXY:305,TEMPORARY_REDIRECT:307,PERMANENT_REDIRECT:308,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,IM_A_TEAPOT:418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511},z={PORT:3000,HOSTNAME:"localhost",ROUTES_DIR:"./routes",CACHE_TTL:0,CORS_MAX_AGE:86400},F={JSON:"application/json",TEXT:"text/plain",HTML:"text/html",FORM_URLENCODED:"application/x-www-form-urlencoded",MULTIPART:"multipart/form-data"};class J{protectedHandler=null;setProtectedHandler(i){this.protectedHandler=i}async authenticate(i){if(!this.protectedHandler)throw new Error("Protected handler not configured. Use vector.protected() to set authentication handler.");try{let f=await this.protectedHandler(i);return i.authUser=f,f}catch(f){throw new Error(`Authentication failed: ${f instanceof Error?f.message:String(f)}`)}}isAuthenticated(i){return!!i.authUser}getUser(i){return i.authUser||null}}class W{cacheHandler=null;memoryCache=new Map;cleanupInterval=null;setCacheHandler(i){this.cacheHandler=i}async get(i,f,l=z.CACHE_TTL){if(l<=0)return f();if(this.cacheHandler)return this.cacheHandler(i,f,l);return this.getFromMemoryCache(i,f,l)}async getFromMemoryCache(i,f,l){let E=Date.now(),_=this.memoryCache.get(i);if(this.isCacheValid(_,E))return _.value;let A=await f();return this.setInMemoryCache(i,A,l),A}isCacheValid(i,f){return i!==void 0&&i.expires>f}setInMemoryCache(i,f,l){let E=Date.now()+l*1000;this.memoryCache.set(i,{value:f,expires:E}),this.scheduleCleanup()}scheduleCleanup(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanupExpired()},60000)}cleanupExpired(){let i=Date.now();for(let[f,l]of this.memoryCache.entries())if(l.expires<=i)this.memoryCache.delete(f);if(this.memoryCache.size===0&&this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}clear(){if(this.memoryCache.clear(),this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}async set(i,f,l=z.CACHE_TTL){if(l<=0)return;if(this.cacheHandler){await this.cacheHandler(i,async()=>f,l);return}this.setInMemoryCache(i,f,l)}delete(i){return this.memoryCache.delete(i)}has(i){let f=this.memoryCache.get(i);if(!f)return!1;if(f.expires<=Date.now())return this.memoryCache.delete(i),!1;return!0}generateKey(i,f){let l=new URL(i.url);return[i.method,l.pathname,l.search,f?.authUser?.id||"anonymous"].join(":")}}var V=(()=>({}));function b(i){if(typeof i!=="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(i))}function c(i,f){var l="",E=0,_=-1,A=0,N;for(var O=0;O<=i.length;++O){if(O<i.length)N=i.charCodeAt(O);else if(N===47)break;else N=47;if(N===47){if(_===O-1||A===1);else if(_!==O-1&&A===2){if(l.length<2||E!==2||l.charCodeAt(l.length-1)!==46||l.charCodeAt(l.length-2)!==46){if(l.length>2){var U=l.lastIndexOf("/");if(U!==l.length-1){if(U===-1)l="",E=0;else l=l.slice(0,U),E=l.length-1-l.lastIndexOf("/");_=O,A=0;continue}}else if(l.length===2||l.length===1){l="",E=0,_=O,A=0;continue}}if(f){if(l.length>0)l+="/..";else l="..";E=2}}else{if(l.length>0)l+="/"+i.slice(_+1,O);else l=i.slice(_+1,O);E=O-_-1}_=O,A=0}else if(N===46&&A!==-1)++A;else A=-1}return l}function t(i,f){var l=f.dir||f.root,E=f.base||(f.name||"")+(f.ext||"");if(!l)return E;if(l===f.root)return l+E;return l+i+E}function j(){var i="",f=!1,l;for(var E=arguments.length-1;E>=-1&&!f;E--){var _;if(E>=0)_=arguments[E];else{if(l===void 0)l=process.cwd();_=l}if(b(_),_.length===0)continue;i=_+"/"+i,f=_.charCodeAt(0)===47}if(i=c(i,!f),f)if(i.length>0)return"/"+i;else return"/";else if(i.length>0)return i;else return"."}function m(i){if(b(i),i.length===0)return".";var f=i.charCodeAt(0)===47,l=i.charCodeAt(i.length-1)===47;if(i=c(i,!f),i.length===0&&!f)i=".";if(i.length>0&&l)i+="/";if(f)return"/"+i;return i}function e(i){return b(i),i.length>0&&i.charCodeAt(0)===47}function M(){if(arguments.length===0)return".";var i;for(var f=0;f<arguments.length;++f){var l=arguments[f];if(b(l),l.length>0)if(i===void 0)i=l;else i+="/"+l}if(i===void 0)return".";return m(i)}function a(i,f){if(b(i),b(f),i===f)return"";if(i=j(i),f=j(f),i===f)return"";var l=1;for(;l<i.length;++l)if(i.charCodeAt(l)!==47)break;var E=i.length,_=E-l,A=1;for(;A<f.length;++A)if(f.charCodeAt(A)!==47)break;var N=f.length,O=N-A,U=_<O?_:O,D=-1,I=0;for(;I<=U;++I){if(I===U){if(O>U){if(f.charCodeAt(A+I)===47)return f.slice(A+I+1);else if(I===0)return f.slice(A+I)}else if(_>U){if(i.charCodeAt(l+I)===47)D=I;else if(I===0)D=0}break}var $=i.charCodeAt(l+I),w=f.charCodeAt(A+I);if($!==w)break;else if($===47)D=I}var R="";for(I=l+D+1;I<=E;++I)if(I===E||i.charCodeAt(I)===47)if(R.length===0)R+="..";else R+="/..";if(R.length>0)return R+f.slice(A+D);else{if(A+=D,f.charCodeAt(A)===47)++A;return f.slice(A)}}function ii(i){return i}function Y(i){if(b(i),i.length===0)return".";var f=i.charCodeAt(0),l=f===47,E=-1,_=!0;for(var A=i.length-1;A>=1;--A)if(f=i.charCodeAt(A),f===47){if(!_){E=A;break}}else _=!1;if(E===-1)return l?"/":".";if(l&&E===1)return"//";return i.slice(0,E)}function fi(i,f){if(f!==void 0&&typeof f!=="string")throw new TypeError('"ext" argument must be a string');b(i);var l=0,E=-1,_=!0,A;if(f!==void 0&&f.length>0&&f.length<=i.length){if(f.length===i.length&&f===i)return"";var N=f.length-1,O=-1;for(A=i.length-1;A>=0;--A){var U=i.charCodeAt(A);if(U===47){if(!_){l=A+1;break}}else{if(O===-1)_=!1,O=A+1;if(N>=0)if(U===f.charCodeAt(N)){if(--N===-1)E=A}else N=-1,E=O}}if(l===E)E=O;else if(E===-1)E=i.length;return i.slice(l,E)}else{for(A=i.length-1;A>=0;--A)if(i.charCodeAt(A)===47){if(!_){l=A+1;break}}else if(E===-1)_=!1,E=A+1;if(E===-1)return"";return i.slice(l,E)}}function li(i){b(i);var f=-1,l=0,E=-1,_=!0,A=0;for(var N=i.length-1;N>=0;--N){var O=i.charCodeAt(N);if(O===47){if(!_){l=N+1;break}continue}if(E===-1)_=!1,E=N+1;if(O===46){if(f===-1)f=N;else if(A!==1)A=1}else if(f!==-1)A=-1}if(f===-1||E===-1||A===0||A===1&&f===E-1&&f===l+1)return"";return i.slice(f,E)}function Ei(i){if(i===null||typeof i!=="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof i);return t("/",i)}function Ai(i){b(i);var f={root:"",dir:"",base:"",ext:"",name:""};if(i.length===0)return f;var l=i.charCodeAt(0),E=l===47,_;if(E)f.root="/",_=1;else _=0;var A=-1,N=0,O=-1,U=!0,D=i.length-1,I=0;for(;D>=_;--D){if(l=i.charCodeAt(D),l===47){if(!U){N=D+1;break}continue}if(O===-1)U=!1,O=D+1;if(l===46){if(A===-1)A=D;else if(I!==1)I=1}else if(A!==-1)I=-1}if(A===-1||O===-1||I===0||I===1&&A===O-1&&A===N+1){if(O!==-1)if(N===0&&E)f.base=f.name=i.slice(1,O);else f.base=f.name=i.slice(N,O)}else{if(N===0&&E)f.name=i.slice(1,A),f.base=i.slice(1,O);else f.name=i.slice(N,A),f.base=i.slice(N,O);f.ext=i.slice(A,O)}if(N>0)f.dir=i.slice(0,N-1);else if(E)f.dir="/";return f}var Q="/",_i=":",xi=((i)=>(i.posix=i,i))({resolve:j,normalize:m,isAbsolute:e,join:M,relative:a,_makeLong:ii,dirname:Y,basename:fi,extname:li,format:Ei,parse:Ai,sep:Q,delimiter:_i,win32:null,posix:null});class K{outputPath;constructor(i="./.vector/routes.generated.ts"){this.outputPath=i}async generate(i){let f=Y(this.outputPath);await V.promises.mkdir(f,{recursive:!0});let l=[],E=new Map;for(let O of i){if(!E.has(O.path))E.set(O.path,[]);E.get(O.path).push(O)}let _=0,A=[];for(let[O,U]of E){let D=a(Y(this.outputPath),O).replace(/\\/g,"/").replace(/\.(ts|js)$/,""),I=`route_${_++}`,$=U.filter((w)=>w.name!=="default").map((w)=>w.name);if(U.some((w)=>w.name==="default"))if($.length>0)l.push(`import ${I}, { ${$.join(", ")} } from '${D}';`);else l.push(`import ${I} from '${D}';`);else if($.length>0)l.push(`import { ${$.join(", ")} } from '${D}';`);for(let w of U){let R=w.name==="default"?I:w.name;A.push(` ${R},`)}}let N=`// This file is auto-generated. Do not edit manually.
2
2
  // Generated at: ${new Date().toISOString()}
3
3
 
4
4
  ${l.join(`
@@ -18,4 +18,4 @@ export default routes;
18
18
  ${f.join(`,
19
19
  `)}
20
20
  ]);
21
- };`}}var x=(()=>({}));class B{routesDir;excludePatterns;static DEFAULT_EXCLUDE_PATTERNS=["*.test.ts","*.test.js","*.test.tsx","*.test.jsx","*.spec.ts","*.spec.js","*.spec.tsx","*.spec.jsx","*.tests.ts","*.tests.js","**/__tests__/**","*.interface.ts","*.type.ts","*.d.ts"];constructor(i="./routes",f){this.routesDir=j(process.cwd(),i),this.excludePatterns=f||B.DEFAULT_EXCLUDE_PATTERNS}async scan(){let i=[];if(!x.existsSync(this.routesDir))return[];try{await this.scanDirectory(this.routesDir,i)}catch(f){if(f.code==="ENOENT")return console.warn(` ✗ Routes directory not accessible: ${this.routesDir}`),[];throw f}return i}isExcluded(i){let f=a(this.routesDir,i);for(let l of this.excludePatterns){let E=l.replace(/\./g,"\\.").replace(/\*/g,"[^/]*").replace(/\*\*/g,".*").replace(/\?/g,"."),_=new RegExp(`^${E}$`),A=f.split(Q).pop()||"";if(_.test(f)||_.test(A))return!0}return!1}async scanDirectory(i,f,l=""){let E=await x.promises.readdir(i);for(let _ of E){let A=M(i,_);if((await x.promises.stat(A)).isDirectory()){let O=l?`${l}/${_}`:_;await this.scanDirectory(A,f,O)}else if(_.endsWith(".ts")||_.endsWith(".js")){if(this.isExcluded(A))continue;let O=a(this.routesDir,A).replace(/\.(ts|js)$/,"").split(Q).join("/");try{let D=await import(process.platform==="win32"?`file:///${A.replace(/\\/g,"/")}`:A);if(D.default&&typeof D.default==="function")f.push({name:"default",path:A,method:"GET",options:{method:"GET",path:`/${O}`,expose:!0}});for(let[I,$]of Object.entries(D)){if(I==="default")continue;if($&&typeof $==="object"&&"entry"in $&&"options"in $&&"handler"in $){let w=$;f.push({name:I,path:A,method:w.options.method,options:w.options})}else if(Array.isArray($)&&$.length>=4){let[w,,,R]=$;f.push({name:I,path:A,method:w,options:{method:w,path:R,expose:!0}})}}}catch(U){console.error(`Failed to load route from ${A}:`,U)}}}}enableWatch(i){if(typeof Bun!=="undefined"&&Bun.env.NODE_ENV==="development")console.log(`Watching for route changes in ${this.routesDir}`),setInterval(async()=>{await i()},1000)}}class X{beforeHandlers=[];finallyHandlers=[];addBefore(...i){this.beforeHandlers.push(...i)}addFinally(...i){this.finallyHandlers.push(...i)}async executeBefore(i){let f=i;for(let l of this.beforeHandlers){let E=await l(f);if(E instanceof Response)return E;f=E}return f}async executeFinally(i,f){let l=i;for(let E of this.finallyHandlers)try{l=await E(l,f)}catch(_){console.error("After middleware error:",_)}return l}clone(){let i=new X;return i.beforeHandlers=[...this.beforeHandlers],i.finallyHandlers=[...this.finallyHandlers],i}clear(){this.beforeHandlers=[],this.finallyHandlers=[]}}function u(i){return process.platform==="win32"?`file:///${i.replace(/\\/g,"/")}`:i}class Z{middlewareManager;authManager;cacheManager;routes=[];constructor(i,f,l){this.middlewareManager=i,this.authManager=f,this.cacheManager=l}getRouteSpecificity(i){let A=0,N=i.split("/").filter(Boolean);for(let O of N)if(this.isStaticSegment(O))A+=1000;else if(this.isParamSegment(O))A+=10;else if(this.isWildcardSegment(O))A+=1;if(A+=i.length,this.isExactPath(i))A+=1e4;return A}isStaticSegment(i){return!i.startsWith(":")&&!i.includes("*")}isParamSegment(i){return i.startsWith(":")}isWildcardSegment(i){return i.includes("*")}isExactPath(i){return!i.includes(":")&&!i.includes("*")}sortRoutes(){this.routes.sort((i,f)=>{let l=this.extractPath(i),E=this.extractPath(f),_=this.getRouteSpecificity(l);return this.getRouteSpecificity(E)-_})}extractPath(i){return i[3]||""}route(i,f){let l=this.wrapHandler(i,f),E=[i.method.toUpperCase(),this.createRouteRegex(i.path),[l],i.path];return this.routes.push(E),this.sortRoutes(),E}createRouteRegex(i){return RegExp(`^${i.replace(/\/+(\/|$)/g,"$1").replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`)}prepareRequest(i,f){if(!i.context)i.context={};if(f?.params!==void 0)i.params=f.params;if(f?.route!==void 0)i.route=f.route;if(f?.metadata!==void 0)i.metadata=f.metadata;if(!i.query&&i.url){let l=new URL(i.url),E={};for(let[_,A]of l.searchParams)if(_ in E)if(Array.isArray(E[_]))E[_].push(A);else E[_]=[E[_],A];else E[_]=A;i.query=E}if(!i.cookies)g(i)}wrapHandler(i,f){return async(l)=>{let E=l;this.prepareRequest(E,{metadata:i.metadata}),l=E;try{if(i.expose===!1)return S.forbidden("Forbidden");let _=await this.middlewareManager.executeBefore(l);if(_ instanceof Response)return _;if(l=_,i.auth)try{await this.authManager.authenticate(l)}catch(D){return S.unauthorized(D instanceof Error?D.message:"Authentication failed",i.responseContentType)}if(!i.rawRequest&&l.method!=="GET"&&l.method!=="HEAD")try{let D=l.headers.get("content-type");if(D?.includes("application/json"))l.content=await l.json();else if(D?.includes("application/x-www-form-urlencoded"))l.content=Object.fromEntries(await l.formData());else if(D?.includes("multipart/form-data"))l.content=await l.formData();else l.content=await l.text()}catch{l.content=null}let A,N=i.cache,O=async()=>{let D=await f(l);if(D instanceof Response)return{_isResponse:!0,body:await D.text(),status:D.status,headers:Object.fromEntries(D.headers.entries())};return D};if(N&&typeof N==="number"&&N>0){let D=this.cacheManager.generateKey(l,{authUser:l.authUser});A=await this.cacheManager.get(D,O,N)}else if(N&&typeof N==="object"&&N.ttl){let D=N.key||this.cacheManager.generateKey(l,{authUser:l.authUser});A=await this.cacheManager.get(D,O,N.ttl)}else A=await f(l);if(A&&typeof A==="object"&&A._isResponse===!0)A=new Response(A.body,{status:A.status,headers:A.headers});let U;if(i.rawResponse||A instanceof Response)U=A instanceof Response?A:new Response(A);else U=P(200,A,i.responseContentType);return U=await this.middlewareManager.executeFinally(U,l),U}catch(_){if(_ instanceof Response)return _;return console.error("Route handler error:",_),S.internalServerError(_ instanceof Error?_.message:String(_),i.responseContentType)}}}addRoute(i){this.routes.push(i),this.sortRoutes()}getRoutes(){return this.routes}async handle(i){let l=new URL(i.url).pathname;for(let[E,_,A,N]of this.routes)if(i.method==="OPTIONS"||i.method===E){let O=l.match(_);if(O){let U=i;this.prepareRequest(U,{params:O.groups||{},route:N||l});for(let D of A){let I=await D(U);if(I)return I}}}return S.notFound("Route not found")}clearRoutes(){this.routes=[]}}class v{server=null;router;config;corsHandler;constructor(i,f){if(this.router=i,this.config=f,f.cors){let{preflight:l,corsify:E}=H(this.normalizeCorsOptions(f.cors));this.corsHandler={preflight:l,corsify:E}}}normalizeCorsOptions(i){return{origin:i.origin||"*",credentials:i.credentials!==!1,allowHeaders:Array.isArray(i.allowHeaders)?i.allowHeaders.join(", "):i.allowHeaders||"Content-Type, Authorization",allowMethods:Array.isArray(i.allowMethods)?i.allowMethods.join(", "):i.allowMethods||"GET, POST, PUT, PATCH, DELETE, OPTIONS",exposeHeaders:Array.isArray(i.exposeHeaders)?i.exposeHeaders.join(", "):i.exposeHeaders||"Authorization",maxAge:i.maxAge||86400}}async start(){let i=this.config.port||3000,f=this.config.hostname||"localhost",l=async(E)=>{try{if(this.corsHandler&&E.method==="OPTIONS")return this.corsHandler.preflight(E);let _=await this.router.handle(E);if(this.corsHandler)_=this.corsHandler.corsify(_,E);return _}catch(_){return console.error("Server error:",_),new Response("Internal Server Error",{status:500})}};try{if(this.server=Bun.serve({port:i,hostname:f,reusePort:this.config.reusePort!==!1,fetch:l,idleTimeout:this.config.idleTimeout||60,error:(E)=>{return console.error("[ERROR] Server error:",E),new Response("Internal Server Error",{status:500})}}),!this.server||!this.server.port)throw new Error(`Failed to start server on ${f}:${i} - server object is invalid`);return console.log(`→ Vector server running at http://${f}:${i}`),this.server}catch(E){if(E.code==="EADDRINUSE"||E.message?.includes("address already in use"))E.message=`Port ${i} is already in use`,E.port=i;else if(E.code==="EACCES"||E.message?.includes("permission denied"))E.message=`Permission denied to bind to port ${i}`,E.port=i;else if(E.message?.includes("EADDRNOTAVAIL"))E.message=`Cannot bind to hostname ${f}`,E.hostname=f;throw E}}stop(){if(this.server)this.server.stop(),this.server=null,console.log("Server stopped")}getServer(){return this.server}getPort(){return this.server?.port||this.config.port||3000}getHostname(){return this.server?.hostname||this.config.hostname||"localhost"}getUrl(){let i=this.getPort();return`http://${this.getHostname()}:${i}`}}class d{static instance;router;server=null;middlewareManager;authManager;cacheManager;config={};routeScanner=null;routeGenerator=null;_protectedHandler=null;_cacheHandler=null;constructor(){this.middlewareManager=new X,this.authManager=new W,this.cacheManager=new h,this.router=new Z(this.middlewareManager,this.authManager,this.cacheManager)}static getInstance(){if(!d.instance)d.instance=new d;return d.instance}setProtectedHandler(i){this._protectedHandler=i,this.authManager.setProtectedHandler(i)}getProtectedHandler(){return this._protectedHandler}setCacheHandler(i){this._cacheHandler=i,this.cacheManager.setCacheHandler(i)}getCacheHandler(){return this._cacheHandler}addRoute(i,f){return this.router.route(i,f)}async startServer(i){if(this.config={...this.config,...i},this.middlewareManager.clear(),this.config.autoDiscover!==!1)this.router.clearRoutes();if(i?.before)this.middlewareManager.addBefore(...i.before);if(i?.finally)this.middlewareManager.addFinally(...i.finally);if(this.config.autoDiscover!==!1)await this.discoverRoutes();return this.server=new v(this.router,this.config),await this.server.start()}async discoverRoutes(){let i=this.config.routesDir||"./routes",f=this.config.routeExcludePatterns;if(this.routeScanner=new B(i,f),!this.routeGenerator)this.routeGenerator=new K;try{let l=await this.routeScanner.scan();if(l.length>0){if(this.config.development)await this.routeGenerator.generate(l);for(let E of l)try{let A=await import(u(E.path)),N=E.name==="default"?A.default:A[E.name];if(N){if(this.isRouteDefinition(N)){let O=N;this.router.route(O.options,O.handler),this.logRouteLoaded(O.options)}else if(this.isRouteEntry(N))this.router.addRoute(N),this.logRouteLoaded(N);else if(typeof N==="function")this.router.route(E.options,N),this.logRouteLoaded(E.options)}}catch(_){console.error(`Failed to load route ${E.name} from ${E.path}:`,_)}this.router.sortRoutes()}}catch(l){if(l.code!=="ENOENT"&&l.code!=="ENOTDIR")console.error("Failed to discover routes:",l)}}async loadRoute(i){if(typeof i==="function"){let f=i();if(Array.isArray(f))this.router.addRoute(f)}else if(i&&typeof i==="object"){for(let[,f]of Object.entries(i))if(typeof f==="function"){let l=f();if(Array.isArray(l))this.router.addRoute(l)}}}isRouteEntry(i){return Array.isArray(i)&&i.length>=3}isRouteDefinition(i){return i&&typeof i==="object"&&"entry"in i&&"options"in i&&"handler"in i}logRouteLoaded(i){}stop(){if(this.server)this.server.stop(),this.server=null}getServer(){return this.server}getRouter(){return this.router}getCacheManager(){return this.cacheManager}getAuthManager(){return this.authManager}static resetInstance(){d.instance=null}}var q=d.getInstance;var{preflight:si,corsify:pi}=H({origin:"*",credentials:!0,allowHeaders:"Content-Type, Authorization",allowMethods:"GET, POST, PUT, PATCH, DELETE, OPTIONS",exposeHeaders:"Authorization",maxAge:86400});function y(i,f){let l=Ii(i,f);return{entry:[i.method.toUpperCase(),RegExp(`^${i.path.replace(/\/+(\/|$)/g,"$1").replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`),[l],i.path],options:i,handler:f}}function Oi(i){return JSON.stringify(i??null,(f,l)=>typeof l==="bigint"?l.toString():l)}var Ni={success:(i,f)=>P(C.OK,i,f),created:(i,f)=>P(C.CREATED,i,f)};function L(i,f,l){let E={error:!0,message:f,statusCode:i,timestamp:new Date().toISOString()};return P(i,E,l)}var S={badRequest:(i="Bad Request",f)=>L(C.BAD_REQUEST,i,f),unauthorized:(i="Unauthorized",f)=>L(C.UNAUTHORIZED,i,f),paymentRequired:(i="Payment Required",f)=>L(402,i,f),forbidden:(i="Forbidden",f)=>L(C.FORBIDDEN,i,f),notFound:(i="Not Found",f)=>L(C.NOT_FOUND,i,f),methodNotAllowed:(i="Method Not Allowed",f)=>L(405,i,f),notAcceptable:(i="Not Acceptable",f)=>L(406,i,f),requestTimeout:(i="Request Timeout",f)=>L(408,i,f),conflict:(i="Conflict",f)=>L(C.CONFLICT,i,f),gone:(i="Gone",f)=>L(410,i,f),lengthRequired:(i="Length Required",f)=>L(411,i,f),preconditionFailed:(i="Precondition Failed",f)=>L(412,i,f),payloadTooLarge:(i="Payload Too Large",f)=>L(413,i,f),uriTooLong:(i="URI Too Long",f)=>L(414,i,f),unsupportedMediaType:(i="Unsupported Media Type",f)=>L(415,i,f),rangeNotSatisfiable:(i="Range Not Satisfiable",f)=>L(416,i,f),expectationFailed:(i="Expectation Failed",f)=>L(417,i,f),imATeapot:(i="I'm a teapot",f)=>L(418,i,f),misdirectedRequest:(i="Misdirected Request",f)=>L(421,i,f),unprocessableEntity:(i="Unprocessable Entity",f)=>L(C.UNPROCESSABLE_ENTITY,i,f),locked:(i="Locked",f)=>L(423,i,f),failedDependency:(i="Failed Dependency",f)=>L(424,i,f),tooEarly:(i="Too Early",f)=>L(425,i,f),upgradeRequired:(i="Upgrade Required",f)=>L(426,i,f),preconditionRequired:(i="Precondition Required",f)=>L(428,i,f),tooManyRequests:(i="Too Many Requests",f)=>L(429,i,f),requestHeaderFieldsTooLarge:(i="Request Header Fields Too Large",f)=>L(431,i,f),unavailableForLegalReasons:(i="Unavailable For Legal Reasons",f)=>L(451,i,f),internalServerError:(i="Internal Server Error",f)=>L(C.INTERNAL_SERVER_ERROR,i,f),notImplemented:(i="Not Implemented",f)=>L(501,i,f),badGateway:(i="Bad Gateway",f)=>L(502,i,f),serviceUnavailable:(i="Service Unavailable",f)=>L(503,i,f),gatewayTimeout:(i="Gateway Timeout",f)=>L(504,i,f),httpVersionNotSupported:(i="HTTP Version Not Supported",f)=>L(505,i,f),variantAlsoNegotiates:(i="Variant Also Negotiates",f)=>L(506,i,f),insufficientStorage:(i="Insufficient Storage",f)=>L(507,i,f),loopDetected:(i="Loop Detected",f)=>L(508,i,f),notExtended:(i="Not Extended",f)=>L(510,i,f),networkAuthenticationRequired:(i="Network Authentication Required",f)=>L(511,i,f),invalidArgument:(i="Invalid Argument",f)=>L(C.UNPROCESSABLE_ENTITY,i,f),rateLimitExceeded:(i="Rate Limit Exceeded",f)=>L(429,i,f),maintenance:(i="Service Under Maintenance",f)=>L(503,i,f),custom:(i,f,l)=>L(i,f,l)};function P(i,f,l=F.JSON){let E=l===F.JSON?Oi(f):f;return new Response(E,{status:i,headers:{"content-type":l}})}var Di=async(i,f)=>{let E=q().getProtectedHandler();if(!E)throw S.unauthorized("Authentication not configured",f);try{let _=await E(i);i.authUser=_}catch(_){throw S.unauthorized(_ instanceof Error?_.message:"Authentication failed",f)}};function Ii(i,f){let{auth:l=!1,expose:E=!1,rawRequest:_=!1,rawResponse:A=!1,responseContentType:N=F.JSON}=i;return async(O)=>{if(!E)return S.forbidden("Forbidden");try{if(l)await Di(O,N);if(!_)await k(O);let U=await f(O);return A?U:Ni.success(U,N)}catch(U){if(U instanceof Response)return U;return S.internalServerError(String(U),N)}}}
21
+ };`}}var x=(()=>({}));class B{routesDir;excludePatterns;static DEFAULT_EXCLUDE_PATTERNS=["*.test.ts","*.test.js","*.test.tsx","*.test.jsx","*.spec.ts","*.spec.js","*.spec.tsx","*.spec.jsx","*.tests.ts","*.tests.js","**/__tests__/**","*.interface.ts","*.type.ts","*.d.ts"];constructor(i="./routes",f){this.routesDir=j(process.cwd(),i),this.excludePatterns=f||B.DEFAULT_EXCLUDE_PATTERNS}async scan(){let i=[];if(!x.existsSync(this.routesDir))return[];try{await this.scanDirectory(this.routesDir,i)}catch(f){if(f.code==="ENOENT")return console.warn(` ✗ Routes directory not accessible: ${this.routesDir}`),[];throw f}return i}isExcluded(i){let f=a(this.routesDir,i);for(let l of this.excludePatterns){let E=l.replace(/\./g,"\\.").replace(/\*/g,"[^/]*").replace(/\*\*/g,".*").replace(/\?/g,"."),_=new RegExp(`^${E}$`),A=f.split(Q).pop()||"";if(_.test(f)||_.test(A))return!0}return!1}async scanDirectory(i,f,l=""){let E=await x.promises.readdir(i);for(let _ of E){let A=M(i,_);if((await x.promises.stat(A)).isDirectory()){let O=l?`${l}/${_}`:_;await this.scanDirectory(A,f,O)}else if(_.endsWith(".ts")||_.endsWith(".js")){if(this.isExcluded(A))continue;let O=a(this.routesDir,A).replace(/\.(ts|js)$/,"").split(Q).join("/");try{let D=await import(process.platform==="win32"?`file:///${A.replace(/\\/g,"/")}`:A);if(D.default&&typeof D.default==="function")f.push({name:"default",path:A,method:"GET",options:{method:"GET",path:`/${O}`,expose:!0}});for(let[I,$]of Object.entries(D)){if(I==="default")continue;if($&&typeof $==="object"&&"entry"in $&&"options"in $&&"handler"in $){let w=$;f.push({name:I,path:A,method:w.options.method,options:w.options})}else if(Array.isArray($)&&$.length>=4){let[w,,,R]=$;f.push({name:I,path:A,method:w,options:{method:w,path:R,expose:!0}})}}}catch(U){console.error(`Failed to load route from ${A}:`,U)}}}}enableWatch(i){if(typeof Bun!=="undefined"&&Bun.env.NODE_ENV==="development")console.log(`Watching for route changes in ${this.routesDir}`),setInterval(async()=>{await i()},1000)}}class X{beforeHandlers=[];finallyHandlers=[];addBefore(...i){this.beforeHandlers.push(...i)}addFinally(...i){this.finallyHandlers.push(...i)}async executeBefore(i){let f=i;for(let l of this.beforeHandlers){let E=await l(f);if(E instanceof Response)return E;f=E}return f}async executeFinally(i,f){let l=i;for(let E of this.finallyHandlers)try{l=await E(l,f)}catch(_){console.error("After middleware error:",_)}return l}clone(){let i=new X;return i.beforeHandlers=[...this.beforeHandlers],i.finallyHandlers=[...this.finallyHandlers],i}clear(){this.beforeHandlers=[],this.finallyHandlers=[]}}function u(i){return process.platform==="win32"?`file:///${i.replace(/\\/g,"/")}`:i}class Z{middlewareManager;authManager;cacheManager;routes=[];constructor(i,f,l){this.middlewareManager=i,this.authManager=f,this.cacheManager=l}getRouteSpecificity(i){let A=0,N=i.split("/").filter(Boolean);for(let O of N)if(this.isStaticSegment(O))A+=1000;else if(this.isParamSegment(O))A+=10;else if(this.isWildcardSegment(O))A+=1;if(A+=i.length,this.isExactPath(i))A+=1e4;return A}isStaticSegment(i){return!i.startsWith(":")&&!i.includes("*")}isParamSegment(i){return i.startsWith(":")}isWildcardSegment(i){return i.includes("*")}isExactPath(i){return!i.includes(":")&&!i.includes("*")}sortRoutes(){this.routes.sort((i,f)=>{let l=this.extractPath(i),E=this.extractPath(f),_=this.getRouteSpecificity(l);return this.getRouteSpecificity(E)-_})}extractPath(i){return i[3]||""}route(i,f){let l=this.wrapHandler(i,f),E=[i.method.toUpperCase(),this.createRouteRegex(i.path),[l],i.path];return this.routes.push(E),this.sortRoutes(),E}createRouteRegex(i){return RegExp(`^${i.replace(/\/+(\/|$)/g,"$1").replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`)}prepareRequest(i,f){if(!i.context)i.context={};if(f?.params!==void 0)i.params=f.params;if(f?.route!==void 0)i.route=f.route;if(f?.metadata!==void 0)i.metadata=f.metadata;if(!i.query&&i.url){let l=new URL(i.url),E={};for(let[_,A]of l.searchParams)if(_ in E)if(Array.isArray(E[_]))E[_].push(A);else E[_]=[E[_],A];else E[_]=A;i.query=E}if(!i.cookies)g(i)}wrapHandler(i,f){return async(l)=>{let E=l;this.prepareRequest(E,{metadata:i.metadata}),l=E;try{if(i.expose===!1)return S.forbidden("Forbidden");let _=await this.middlewareManager.executeBefore(l);if(_ instanceof Response)return _;if(l=_,i.auth)try{await this.authManager.authenticate(l)}catch(D){return S.unauthorized(D instanceof Error?D.message:"Authentication failed",i.responseContentType)}if(!i.rawRequest&&l.method!=="GET"&&l.method!=="HEAD")try{let D=l.headers.get("content-type");if(D?.includes("application/json"))l.content=await l.json();else if(D?.includes("application/x-www-form-urlencoded"))l.content=Object.fromEntries(await l.formData());else if(D?.includes("multipart/form-data"))l.content=await l.formData();else l.content=await l.text()}catch{l.content=null}let A,N=i.cache,O=async()=>{let D=await f(l);if(D instanceof Response)return{_isResponse:!0,body:await D.text(),status:D.status,headers:Object.fromEntries(D.headers.entries())};return D};if(N&&typeof N==="number"&&N>0){let D=this.cacheManager.generateKey(l,{authUser:l.authUser});A=await this.cacheManager.get(D,O,N)}else if(N&&typeof N==="object"&&N.ttl){let D=N.key||this.cacheManager.generateKey(l,{authUser:l.authUser});A=await this.cacheManager.get(D,O,N.ttl)}else A=await f(l);if(A&&typeof A==="object"&&A._isResponse===!0)A=new Response(A.body,{status:A.status,headers:A.headers});let U;if(i.rawResponse||A instanceof Response)U=A instanceof Response?A:new Response(A);else U=P(200,A,i.responseContentType);return U=await this.middlewareManager.executeFinally(U,l),U}catch(_){if(_ instanceof Response)return _;return console.error("Route handler error:",_),S.internalServerError(_ instanceof Error?_.message:String(_),i.responseContentType)}}}addRoute(i){this.routes.push(i),this.sortRoutes()}getRoutes(){return this.routes}async handle(i){let l=new URL(i.url).pathname;for(let[E,_,A,N]of this.routes)if(i.method==="OPTIONS"||i.method===E){let O=l.match(_);if(O){let U=i;this.prepareRequest(U,{params:O.groups||{},route:N||l});for(let D of A){let I=await D(U);if(I)return I}}}return S.notFound("Route not found")}clearRoutes(){this.routes=[]}}class v{server=null;router;config;corsHandler;constructor(i,f){if(this.router=i,this.config=f,f.cors){let{preflight:l,corsify:E}=H(this.normalizeCorsOptions(f.cors));this.corsHandler={preflight:l,corsify:E}}}normalizeCorsOptions(i){return{origin:i.origin||"*",credentials:i.credentials!==!1,allowHeaders:Array.isArray(i.allowHeaders)?i.allowHeaders.join(", "):i.allowHeaders||"Content-Type, Authorization",allowMethods:Array.isArray(i.allowMethods)?i.allowMethods.join(", "):i.allowMethods||"GET, POST, PUT, PATCH, DELETE, OPTIONS",exposeHeaders:Array.isArray(i.exposeHeaders)?i.exposeHeaders.join(", "):i.exposeHeaders||"Authorization",maxAge:i.maxAge||86400}}async start(){let i=this.config.port||3000,f=this.config.hostname||"localhost",l=async(E)=>{try{if(this.corsHandler&&E.method==="OPTIONS")return this.corsHandler.preflight(E);let _=await this.router.handle(E);if(this.corsHandler)_=this.corsHandler.corsify(_,E);return _}catch(_){return console.error("Server error:",_),new Response("Internal Server Error",{status:500})}};try{if(this.server=Bun.serve({port:i,hostname:f,reusePort:this.config.reusePort!==!1,fetch:l,idleTimeout:this.config.idleTimeout||60,error:(E)=>{return console.error("[ERROR] Server error:",E),new Response("Internal Server Error",{status:500})}}),!this.server||!this.server.port)throw new Error(`Failed to start server on ${f}:${i} - server object is invalid`);return this.server}catch(E){if(E.code==="EADDRINUSE"||E.message?.includes("address already in use"))E.message=`Port ${i} is already in use`,E.port=i;else if(E.code==="EACCES"||E.message?.includes("permission denied"))E.message=`Permission denied to bind to port ${i}`,E.port=i;else if(E.message?.includes("EADDRNOTAVAIL"))E.message=`Cannot bind to hostname ${f}`,E.hostname=f;throw E}}stop(){if(this.server)this.server.stop(),this.server=null,console.log("Server stopped")}getServer(){return this.server}getPort(){return this.server?.port||this.config.port||3000}getHostname(){return this.server?.hostname||this.config.hostname||"localhost"}getUrl(){let i=this.getPort();return`http://${this.getHostname()}:${i}`}}class d{static instance;router;server=null;middlewareManager;authManager;cacheManager;config={};routeScanner=null;routeGenerator=null;_protectedHandler=null;_cacheHandler=null;constructor(){this.middlewareManager=new X,this.authManager=new J,this.cacheManager=new W,this.router=new Z(this.middlewareManager,this.authManager,this.cacheManager)}static getInstance(){if(!d.instance)d.instance=new d;return d.instance}setProtectedHandler(i){this._protectedHandler=i,this.authManager.setProtectedHandler(i)}getProtectedHandler(){return this._protectedHandler}setCacheHandler(i){this._cacheHandler=i,this.cacheManager.setCacheHandler(i)}getCacheHandler(){return this._cacheHandler}addRoute(i,f){return this.router.route(i,f)}async startServer(i){if(this.config={...this.config,...i},this.middlewareManager.clear(),this.config.autoDiscover!==!1)this.router.clearRoutes();if(i?.before)this.middlewareManager.addBefore(...i.before);if(i?.finally)this.middlewareManager.addFinally(...i.finally);if(this.config.autoDiscover!==!1)await this.discoverRoutes();return this.server=new v(this.router,this.config),await this.server.start()}async discoverRoutes(){let i=this.config.routesDir||"./routes",f=this.config.routeExcludePatterns;if(this.routeScanner=new B(i,f),!this.routeGenerator)this.routeGenerator=new K;try{let l=await this.routeScanner.scan();if(l.length>0){if(this.config.development)await this.routeGenerator.generate(l);for(let E of l)try{let A=await import(u(E.path)),N=E.name==="default"?A.default:A[E.name];if(N){if(this.isRouteDefinition(N)){let O=N;this.router.route(O.options,O.handler),this.logRouteLoaded(O.options)}else if(this.isRouteEntry(N))this.router.addRoute(N),this.logRouteLoaded(N);else if(typeof N==="function")this.router.route(E.options,N),this.logRouteLoaded(E.options)}}catch(_){console.error(`Failed to load route ${E.name} from ${E.path}:`,_)}this.router.sortRoutes()}}catch(l){if(l.code!=="ENOENT"&&l.code!=="ENOTDIR")console.error("Failed to discover routes:",l)}}async loadRoute(i){if(typeof i==="function"){let f=i();if(Array.isArray(f))this.router.addRoute(f)}else if(i&&typeof i==="object"){for(let[,f]of Object.entries(i))if(typeof f==="function"){let l=f();if(Array.isArray(l))this.router.addRoute(l)}}}isRouteEntry(i){return Array.isArray(i)&&i.length>=3}isRouteDefinition(i){return i&&typeof i==="object"&&"entry"in i&&"options"in i&&"handler"in i}logRouteLoaded(i){}stop(){if(this.server)this.server.stop(),this.server=null}getServer(){return this.server}getRouter(){return this.router}getCacheManager(){return this.cacheManager}getAuthManager(){return this.authManager}static resetInstance(){d.instance=null}}var q=d.getInstance;var{preflight:si,corsify:pi}=H({origin:"*",credentials:!0,allowHeaders:"Content-Type, Authorization",allowMethods:"GET, POST, PUT, PATCH, DELETE, OPTIONS",exposeHeaders:"Authorization",maxAge:86400});function y(i,f){let l=Ii(i,f);return{entry:[i.method.toUpperCase(),RegExp(`^${i.path.replace(/\/+(\/|$)/g,"$1").replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`),[l],i.path],options:i,handler:f}}function Oi(i){return JSON.stringify(i??null,(f,l)=>typeof l==="bigint"?l.toString():l)}var Ni={success:(i,f)=>P(C.OK,i,f),created:(i,f)=>P(C.CREATED,i,f)};function L(i,f,l){let E={error:!0,message:f,statusCode:i,timestamp:new Date().toISOString()};return P(i,E,l)}var S={badRequest:(i="Bad Request",f)=>L(C.BAD_REQUEST,i,f),unauthorized:(i="Unauthorized",f)=>L(C.UNAUTHORIZED,i,f),paymentRequired:(i="Payment Required",f)=>L(402,i,f),forbidden:(i="Forbidden",f)=>L(C.FORBIDDEN,i,f),notFound:(i="Not Found",f)=>L(C.NOT_FOUND,i,f),methodNotAllowed:(i="Method Not Allowed",f)=>L(405,i,f),notAcceptable:(i="Not Acceptable",f)=>L(406,i,f),requestTimeout:(i="Request Timeout",f)=>L(408,i,f),conflict:(i="Conflict",f)=>L(C.CONFLICT,i,f),gone:(i="Gone",f)=>L(410,i,f),lengthRequired:(i="Length Required",f)=>L(411,i,f),preconditionFailed:(i="Precondition Failed",f)=>L(412,i,f),payloadTooLarge:(i="Payload Too Large",f)=>L(413,i,f),uriTooLong:(i="URI Too Long",f)=>L(414,i,f),unsupportedMediaType:(i="Unsupported Media Type",f)=>L(415,i,f),rangeNotSatisfiable:(i="Range Not Satisfiable",f)=>L(416,i,f),expectationFailed:(i="Expectation Failed",f)=>L(417,i,f),imATeapot:(i="I'm a teapot",f)=>L(418,i,f),misdirectedRequest:(i="Misdirected Request",f)=>L(421,i,f),unprocessableEntity:(i="Unprocessable Entity",f)=>L(C.UNPROCESSABLE_ENTITY,i,f),locked:(i="Locked",f)=>L(423,i,f),failedDependency:(i="Failed Dependency",f)=>L(424,i,f),tooEarly:(i="Too Early",f)=>L(425,i,f),upgradeRequired:(i="Upgrade Required",f)=>L(426,i,f),preconditionRequired:(i="Precondition Required",f)=>L(428,i,f),tooManyRequests:(i="Too Many Requests",f)=>L(429,i,f),requestHeaderFieldsTooLarge:(i="Request Header Fields Too Large",f)=>L(431,i,f),unavailableForLegalReasons:(i="Unavailable For Legal Reasons",f)=>L(451,i,f),internalServerError:(i="Internal Server Error",f)=>L(C.INTERNAL_SERVER_ERROR,i,f),notImplemented:(i="Not Implemented",f)=>L(501,i,f),badGateway:(i="Bad Gateway",f)=>L(502,i,f),serviceUnavailable:(i="Service Unavailable",f)=>L(503,i,f),gatewayTimeout:(i="Gateway Timeout",f)=>L(504,i,f),httpVersionNotSupported:(i="HTTP Version Not Supported",f)=>L(505,i,f),variantAlsoNegotiates:(i="Variant Also Negotiates",f)=>L(506,i,f),insufficientStorage:(i="Insufficient Storage",f)=>L(507,i,f),loopDetected:(i="Loop Detected",f)=>L(508,i,f),notExtended:(i="Not Extended",f)=>L(510,i,f),networkAuthenticationRequired:(i="Network Authentication Required",f)=>L(511,i,f),invalidArgument:(i="Invalid Argument",f)=>L(C.UNPROCESSABLE_ENTITY,i,f),rateLimitExceeded:(i="Rate Limit Exceeded",f)=>L(429,i,f),maintenance:(i="Service Under Maintenance",f)=>L(503,i,f),custom:(i,f,l)=>L(i,f,l)};function P(i,f,l=F.JSON){let E=l===F.JSON?Oi(f):f;return new Response(E,{status:i,headers:{"content-type":l}})}var Di=async(i,f)=>{let E=q().getProtectedHandler();if(!E)throw S.unauthorized("Authentication not configured",f);try{let _=await E(i);i.authUser=_}catch(_){throw S.unauthorized(_ instanceof Error?_.message:"Authentication failed",f)}};function Ii(i,f){let{auth:l=!1,expose:E=!1,rawRequest:_=!1,rawResponse:A=!1,responseContentType:N=F.JSON}=i;return async(O)=>{if(!E)return S.forbidden("Forbidden");try{if(l)await Di(O,N);if(!_)await k(O);let U=await f(O);return A?U:Ni.success(U,N)}catch(U){if(U instanceof Response)return U;return S.internalServerError(String(U),N)}}}
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- var d=(i="text/plain; charset=utf-8",f)=>(l,E={})=>{if(l===void 0||l instanceof Response)return l;let _=new Response(f?.(l)??l,E.url?void 0:E);return _.headers.set("content-type",i),_},Ai=d("application/json; charset=utf-8",JSON.stringify);var _i=d("text/plain; charset=utf-8",String),Oi=d("text/html"),Ni=d("image/jpeg"),Di=d("image/png"),Ii=d("image/webp"),K=async(i)=>{i.content=i.body?await i.clone().json().catch(()=>i.clone().formData()).catch(()=>i.text()):void 0},Z=(i)=>{i.cookies=(i.headers.get("Cookie")||"").split(/;\s*/).map((f)=>f.split(/=(.+)/)).reduce((f,[l,E])=>E?(f[l]=E,f):f,{})},x=(i={})=>{let{origin:f="*",credentials:l=!1,allowMethods:E="*",allowHeaders:_,exposeHeaders:A,maxAge:N}=i,O=(D)=>{let I=D?.headers.get("origin");return f===!0?I:f instanceof RegExp?f.test(I)?I:void 0:Array.isArray(f)?f.includes(I)?I:void 0:f instanceof Function?f(I):f=="*"&&l?I:f},U=(D,I)=>{for(let[$,w]of Object.entries(I))w&&D.headers.append($,w);return D};return{corsify:(D,I)=>D?.headers?.get("access-control-allow-origin")||D.status==101?D:U(D.clone(),{"access-control-allow-origin":O(I),"access-control-allow-credentials":l}),preflight:(D)=>{if(D.method=="OPTIONS"){let I=new Response(null,{status:204});return U(I,{"access-control-allow-origin":O(D),"access-control-allow-methods":E?.join?.(",")??E,"access-control-expose-headers":A?.join?.(",")??A,"access-control-allow-headers":_?.join?.(",")??_??D.headers.get("access-control-request-headers"),"access-control-max-age":N,"access-control-allow-credentials":l})}}}};var C={OK:200,CREATED:201,ACCEPTED:202,NON_AUTHORITATIVE_INFORMATION:203,NO_CONTENT:204,RESET_CONTENT:205,PARTIAL_CONTENT:206,MULTI_STATUS:207,ALREADY_REPORTED:208,IM_USED:226,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,USE_PROXY:305,TEMPORARY_REDIRECT:307,PERMANENT_REDIRECT:308,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,IM_A_TEAPOT:418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511},X={PORT:3000,HOSTNAME:"localhost",ROUTES_DIR:"./routes",CACHE_TTL:0,CORS_MAX_AGE:86400},H={JSON:"application/json",TEXT:"text/plain",HTML:"text/html",FORM_URLENCODED:"application/x-www-form-urlencoded",MULTIPART:"multipart/form-data"};class z{protectedHandler=null;setProtectedHandler(i){this.protectedHandler=i}async authenticate(i){if(!this.protectedHandler)throw new Error("Protected handler not configured. Use vector.protected() to set authentication handler.");try{let f=await this.protectedHandler(i);return i.authUser=f,f}catch(f){throw new Error(`Authentication failed: ${f instanceof Error?f.message:String(f)}`)}}isAuthenticated(i){return!!i.authUser}getUser(i){return i.authUser||null}}class J{cacheHandler=null;memoryCache=new Map;cleanupInterval=null;setCacheHandler(i){this.cacheHandler=i}async get(i,f,l=X.CACHE_TTL){if(l<=0)return f();if(this.cacheHandler)return this.cacheHandler(i,f,l);return this.getFromMemoryCache(i,f,l)}async getFromMemoryCache(i,f,l){let E=Date.now(),_=this.memoryCache.get(i);if(this.isCacheValid(_,E))return _.value;let A=await f();return this.setInMemoryCache(i,A,l),A}isCacheValid(i,f){return i!==void 0&&i.expires>f}setInMemoryCache(i,f,l){let E=Date.now()+l*1000;this.memoryCache.set(i,{value:f,expires:E}),this.scheduleCleanup()}scheduleCleanup(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanupExpired()},60000)}cleanupExpired(){let i=Date.now();for(let[f,l]of this.memoryCache.entries())if(l.expires<=i)this.memoryCache.delete(f);if(this.memoryCache.size===0&&this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}clear(){if(this.memoryCache.clear(),this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}async set(i,f,l=X.CACHE_TTL){if(l<=0)return;if(this.cacheHandler){await this.cacheHandler(i,async()=>f,l);return}this.setInMemoryCache(i,f,l)}delete(i){return this.memoryCache.delete(i)}has(i){let f=this.memoryCache.get(i);if(!f)return!1;if(f.expires<=Date.now())return this.memoryCache.delete(i),!1;return!0}generateKey(i,f){let l=new URL(i.url);return[i.method,l.pathname,l.search,f?.authUser?.id||"anonymous"].join(":")}}var{promises:k}=(()=>({}));function S(i){if(typeof i!=="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(i))}function v(i,f){var l="",E=0,_=-1,A=0,N;for(var O=0;O<=i.length;++O){if(O<i.length)N=i.charCodeAt(O);else if(N===47)break;else N=47;if(N===47){if(_===O-1||A===1);else if(_!==O-1&&A===2){if(l.length<2||E!==2||l.charCodeAt(l.length-1)!==46||l.charCodeAt(l.length-2)!==46){if(l.length>2){var U=l.lastIndexOf("/");if(U!==l.length-1){if(U===-1)l="",E=0;else l=l.slice(0,U),E=l.length-1-l.lastIndexOf("/");_=O,A=0;continue}}else if(l.length===2||l.length===1){l="",E=0,_=O,A=0;continue}}if(f){if(l.length>0)l+="/..";else l="..";E=2}}else{if(l.length>0)l+="/"+i.slice(_+1,O);else l=i.slice(_+1,O);E=O-_-1}_=O,A=0}else if(N===46&&A!==-1)++A;else A=-1}return l}function u(i,f){var l=f.dir||f.root,E=f.base||(f.name||"")+(f.ext||"");if(!l)return E;if(l===f.root)return l+E;return l+i+E}function j(){var i="",f=!1,l;for(var E=arguments.length-1;E>=-1&&!f;E--){var _;if(E>=0)_=arguments[E];else{if(l===void 0)l=process.cwd();_=l}if(S(_),_.length===0)continue;i=_+"/"+i,f=_.charCodeAt(0)===47}if(i=v(i,!f),f)if(i.length>0)return"/"+i;else return"/";else if(i.length>0)return i;else return"."}function T(i){if(S(i),i.length===0)return".";var f=i.charCodeAt(0)===47,l=i.charCodeAt(i.length-1)===47;if(i=v(i,!f),i.length===0&&!f)i=".";if(i.length>0&&l)i+="/";if(f)return"/"+i;return i}function q(i){return S(i),i.length>0&&i.charCodeAt(0)===47}function W(){if(arguments.length===0)return".";var i;for(var f=0;f<arguments.length;++f){var l=arguments[f];if(S(l),l.length>0)if(i===void 0)i=l;else i+="/"+l}if(i===void 0)return".";return T(i)}function G(i,f){if(S(i),S(f),i===f)return"";if(i=j(i),f=j(f),i===f)return"";var l=1;for(;l<i.length;++l)if(i.charCodeAt(l)!==47)break;var E=i.length,_=E-l,A=1;for(;A<f.length;++A)if(f.charCodeAt(A)!==47)break;var N=f.length,O=N-A,U=_<O?_:O,D=-1,I=0;for(;I<=U;++I){if(I===U){if(O>U){if(f.charCodeAt(A+I)===47)return f.slice(A+I+1);else if(I===0)return f.slice(A+I)}else if(_>U){if(i.charCodeAt(l+I)===47)D=I;else if(I===0)D=0}break}var $=i.charCodeAt(l+I),w=f.charCodeAt(A+I);if($!==w)break;else if($===47)D=I}var R="";for(I=l+D+1;I<=E;++I)if(I===E||i.charCodeAt(I)===47)if(R.length===0)R+="..";else R+="/..";if(R.length>0)return R+f.slice(A+D);else{if(A+=D,f.charCodeAt(A)===47)++A;return f.slice(A)}}function y(i){return i}function F(i){if(S(i),i.length===0)return".";var f=i.charCodeAt(0),l=f===47,E=-1,_=!0;for(var A=i.length-1;A>=1;--A)if(f=i.charCodeAt(A),f===47){if(!_){E=A;break}}else _=!1;if(E===-1)return l?"/":".";if(l&&E===1)return"//";return i.slice(0,E)}function n(i,f){if(f!==void 0&&typeof f!=="string")throw new TypeError('"ext" argument must be a string');S(i);var l=0,E=-1,_=!0,A;if(f!==void 0&&f.length>0&&f.length<=i.length){if(f.length===i.length&&f===i)return"";var N=f.length-1,O=-1;for(A=i.length-1;A>=0;--A){var U=i.charCodeAt(A);if(U===47){if(!_){l=A+1;break}}else{if(O===-1)_=!1,O=A+1;if(N>=0)if(U===f.charCodeAt(N)){if(--N===-1)E=A}else N=-1,E=O}}if(l===E)E=O;else if(E===-1)E=i.length;return i.slice(l,E)}else{for(A=i.length-1;A>=0;--A)if(i.charCodeAt(A)===47){if(!_){l=A+1;break}}else if(E===-1)_=!1,E=A+1;if(E===-1)return"";return i.slice(l,E)}}function s(i){S(i);var f=-1,l=0,E=-1,_=!0,A=0;for(var N=i.length-1;N>=0;--N){var O=i.charCodeAt(N);if(O===47){if(!_){l=N+1;break}continue}if(E===-1)_=!1,E=N+1;if(O===46){if(f===-1)f=N;else if(A!==1)A=1}else if(f!==-1)A=-1}if(f===-1||E===-1||A===0||A===1&&f===E-1&&f===l+1)return"";return i.slice(f,E)}function p(i){if(i===null||typeof i!=="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof i);return u("/",i)}function r(i){S(i);var f={root:"",dir:"",base:"",ext:"",name:""};if(i.length===0)return f;var l=i.charCodeAt(0),E=l===47,_;if(E)f.root="/",_=1;else _=0;var A=-1,N=0,O=-1,U=!0,D=i.length-1,I=0;for(;D>=_;--D){if(l=i.charCodeAt(D),l===47){if(!U){N=D+1;break}continue}if(O===-1)U=!1,O=D+1;if(l===46){if(A===-1)A=D;else if(I!==1)I=1}else if(A!==-1)I=-1}if(A===-1||O===-1||I===0||I===1&&A===O-1&&A===N+1){if(O!==-1)if(N===0&&E)f.base=f.name=i.slice(1,O);else f.base=f.name=i.slice(N,O)}else{if(N===0&&E)f.name=i.slice(1,A),f.base=i.slice(1,O);else f.name=i.slice(N,A),f.base=i.slice(N,O);f.ext=i.slice(A,O)}if(N>0)f.dir=i.slice(0,N-1);else if(E)f.dir="/";return f}var Y="/",o=":",Si=((i)=>(i.posix=i,i))({resolve:j,normalize:T,isAbsolute:q,join:W,relative:G,_makeLong:y,dirname:F,basename:n,extname:s,format:p,parse:r,sep:Y,delimiter:o,win32:null,posix:null});class h{outputPath;constructor(i="./.vector/routes.generated.ts"){this.outputPath=i}async generate(i){let f=F(this.outputPath);await k.mkdir(f,{recursive:!0});let l=[],E=new Map;for(let O of i){if(!E.has(O.path))E.set(O.path,[]);E.get(O.path).push(O)}let _=0,A=[];for(let[O,U]of E){let D=G(F(this.outputPath),O).replace(/\\/g,"/").replace(/\.(ts|js)$/,""),I=`route_${_++}`,$=U.filter((w)=>w.name!=="default").map((w)=>w.name);if(U.some((w)=>w.name==="default"))if($.length>0)l.push(`import ${I}, { ${$.join(", ")} } from '${D}';`);else l.push(`import ${I} from '${D}';`);else if($.length>0)l.push(`import { ${$.join(", ")} } from '${D}';`);for(let w of U){let R=w.name==="default"?I:w.name;A.push(` ${R},`)}}let N=`// This file is auto-generated. Do not edit manually.
1
+ var d=(i="text/plain; charset=utf-8",f)=>(l,E={})=>{if(l===void 0||l instanceof Response)return l;let _=new Response(f?.(l)??l,E.url?void 0:E);return _.headers.set("content-type",i),_},Ai=d("application/json; charset=utf-8",JSON.stringify);var _i=d("text/plain; charset=utf-8",String),Oi=d("text/html"),Ni=d("image/jpeg"),Di=d("image/png"),Ii=d("image/webp"),K=async(i)=>{i.content=i.body?await i.clone().json().catch(()=>i.clone().formData()).catch(()=>i.text()):void 0},Z=(i)=>{i.cookies=(i.headers.get("Cookie")||"").split(/;\s*/).map((f)=>f.split(/=(.+)/)).reduce((f,[l,E])=>E?(f[l]=E,f):f,{})},x=(i={})=>{let{origin:f="*",credentials:l=!1,allowMethods:E="*",allowHeaders:_,exposeHeaders:A,maxAge:N}=i,O=(D)=>{let I=D?.headers.get("origin");return f===!0?I:f instanceof RegExp?f.test(I)?I:void 0:Array.isArray(f)?f.includes(I)?I:void 0:f instanceof Function?f(I):f=="*"&&l?I:f},U=(D,I)=>{for(let[$,w]of Object.entries(I))w&&D.headers.append($,w);return D};return{corsify:(D,I)=>D?.headers?.get("access-control-allow-origin")||D.status==101?D:U(D.clone(),{"access-control-allow-origin":O(I),"access-control-allow-credentials":l}),preflight:(D)=>{if(D.method=="OPTIONS"){let I=new Response(null,{status:204});return U(I,{"access-control-allow-origin":O(D),"access-control-allow-methods":E?.join?.(",")??E,"access-control-expose-headers":A?.join?.(",")??A,"access-control-allow-headers":_?.join?.(",")??_??D.headers.get("access-control-request-headers"),"access-control-max-age":N,"access-control-allow-credentials":l})}}}};var C={OK:200,CREATED:201,ACCEPTED:202,NON_AUTHORITATIVE_INFORMATION:203,NO_CONTENT:204,RESET_CONTENT:205,PARTIAL_CONTENT:206,MULTI_STATUS:207,ALREADY_REPORTED:208,IM_USED:226,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,USE_PROXY:305,TEMPORARY_REDIRECT:307,PERMANENT_REDIRECT:308,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,IM_A_TEAPOT:418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511},X={PORT:3000,HOSTNAME:"localhost",ROUTES_DIR:"./routes",CACHE_TTL:0,CORS_MAX_AGE:86400},H={JSON:"application/json",TEXT:"text/plain",HTML:"text/html",FORM_URLENCODED:"application/x-www-form-urlencoded",MULTIPART:"multipart/form-data"};class h{protectedHandler=null;setProtectedHandler(i){this.protectedHandler=i}async authenticate(i){if(!this.protectedHandler)throw new Error("Protected handler not configured. Use vector.protected() to set authentication handler.");try{let f=await this.protectedHandler(i);return i.authUser=f,f}catch(f){throw new Error(`Authentication failed: ${f instanceof Error?f.message:String(f)}`)}}isAuthenticated(i){return!!i.authUser}getUser(i){return i.authUser||null}}class z{cacheHandler=null;memoryCache=new Map;cleanupInterval=null;setCacheHandler(i){this.cacheHandler=i}async get(i,f,l=X.CACHE_TTL){if(l<=0)return f();if(this.cacheHandler)return this.cacheHandler(i,f,l);return this.getFromMemoryCache(i,f,l)}async getFromMemoryCache(i,f,l){let E=Date.now(),_=this.memoryCache.get(i);if(this.isCacheValid(_,E))return _.value;let A=await f();return this.setInMemoryCache(i,A,l),A}isCacheValid(i,f){return i!==void 0&&i.expires>f}setInMemoryCache(i,f,l){let E=Date.now()+l*1000;this.memoryCache.set(i,{value:f,expires:E}),this.scheduleCleanup()}scheduleCleanup(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanupExpired()},60000)}cleanupExpired(){let i=Date.now();for(let[f,l]of this.memoryCache.entries())if(l.expires<=i)this.memoryCache.delete(f);if(this.memoryCache.size===0&&this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}clear(){if(this.memoryCache.clear(),this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}async set(i,f,l=X.CACHE_TTL){if(l<=0)return;if(this.cacheHandler){await this.cacheHandler(i,async()=>f,l);return}this.setInMemoryCache(i,f,l)}delete(i){return this.memoryCache.delete(i)}has(i){let f=this.memoryCache.get(i);if(!f)return!1;if(f.expires<=Date.now())return this.memoryCache.delete(i),!1;return!0}generateKey(i,f){let l=new URL(i.url);return[i.method,l.pathname,l.search,f?.authUser?.id||"anonymous"].join(":")}}var{promises:k}=(()=>({}));function S(i){if(typeof i!=="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(i))}function v(i,f){var l="",E=0,_=-1,A=0,N;for(var O=0;O<=i.length;++O){if(O<i.length)N=i.charCodeAt(O);else if(N===47)break;else N=47;if(N===47){if(_===O-1||A===1);else if(_!==O-1&&A===2){if(l.length<2||E!==2||l.charCodeAt(l.length-1)!==46||l.charCodeAt(l.length-2)!==46){if(l.length>2){var U=l.lastIndexOf("/");if(U!==l.length-1){if(U===-1)l="",E=0;else l=l.slice(0,U),E=l.length-1-l.lastIndexOf("/");_=O,A=0;continue}}else if(l.length===2||l.length===1){l="",E=0,_=O,A=0;continue}}if(f){if(l.length>0)l+="/..";else l="..";E=2}}else{if(l.length>0)l+="/"+i.slice(_+1,O);else l=i.slice(_+1,O);E=O-_-1}_=O,A=0}else if(N===46&&A!==-1)++A;else A=-1}return l}function u(i,f){var l=f.dir||f.root,E=f.base||(f.name||"")+(f.ext||"");if(!l)return E;if(l===f.root)return l+E;return l+i+E}function j(){var i="",f=!1,l;for(var E=arguments.length-1;E>=-1&&!f;E--){var _;if(E>=0)_=arguments[E];else{if(l===void 0)l=process.cwd();_=l}if(S(_),_.length===0)continue;i=_+"/"+i,f=_.charCodeAt(0)===47}if(i=v(i,!f),f)if(i.length>0)return"/"+i;else return"/";else if(i.length>0)return i;else return"."}function T(i){if(S(i),i.length===0)return".";var f=i.charCodeAt(0)===47,l=i.charCodeAt(i.length-1)===47;if(i=v(i,!f),i.length===0&&!f)i=".";if(i.length>0&&l)i+="/";if(f)return"/"+i;return i}function q(i){return S(i),i.length>0&&i.charCodeAt(0)===47}function J(){if(arguments.length===0)return".";var i;for(var f=0;f<arguments.length;++f){var l=arguments[f];if(S(l),l.length>0)if(i===void 0)i=l;else i+="/"+l}if(i===void 0)return".";return T(i)}function G(i,f){if(S(i),S(f),i===f)return"";if(i=j(i),f=j(f),i===f)return"";var l=1;for(;l<i.length;++l)if(i.charCodeAt(l)!==47)break;var E=i.length,_=E-l,A=1;for(;A<f.length;++A)if(f.charCodeAt(A)!==47)break;var N=f.length,O=N-A,U=_<O?_:O,D=-1,I=0;for(;I<=U;++I){if(I===U){if(O>U){if(f.charCodeAt(A+I)===47)return f.slice(A+I+1);else if(I===0)return f.slice(A+I)}else if(_>U){if(i.charCodeAt(l+I)===47)D=I;else if(I===0)D=0}break}var $=i.charCodeAt(l+I),w=f.charCodeAt(A+I);if($!==w)break;else if($===47)D=I}var R="";for(I=l+D+1;I<=E;++I)if(I===E||i.charCodeAt(I)===47)if(R.length===0)R+="..";else R+="/..";if(R.length>0)return R+f.slice(A+D);else{if(A+=D,f.charCodeAt(A)===47)++A;return f.slice(A)}}function y(i){return i}function F(i){if(S(i),i.length===0)return".";var f=i.charCodeAt(0),l=f===47,E=-1,_=!0;for(var A=i.length-1;A>=1;--A)if(f=i.charCodeAt(A),f===47){if(!_){E=A;break}}else _=!1;if(E===-1)return l?"/":".";if(l&&E===1)return"//";return i.slice(0,E)}function n(i,f){if(f!==void 0&&typeof f!=="string")throw new TypeError('"ext" argument must be a string');S(i);var l=0,E=-1,_=!0,A;if(f!==void 0&&f.length>0&&f.length<=i.length){if(f.length===i.length&&f===i)return"";var N=f.length-1,O=-1;for(A=i.length-1;A>=0;--A){var U=i.charCodeAt(A);if(U===47){if(!_){l=A+1;break}}else{if(O===-1)_=!1,O=A+1;if(N>=0)if(U===f.charCodeAt(N)){if(--N===-1)E=A}else N=-1,E=O}}if(l===E)E=O;else if(E===-1)E=i.length;return i.slice(l,E)}else{for(A=i.length-1;A>=0;--A)if(i.charCodeAt(A)===47){if(!_){l=A+1;break}}else if(E===-1)_=!1,E=A+1;if(E===-1)return"";return i.slice(l,E)}}function s(i){S(i);var f=-1,l=0,E=-1,_=!0,A=0;for(var N=i.length-1;N>=0;--N){var O=i.charCodeAt(N);if(O===47){if(!_){l=N+1;break}continue}if(E===-1)_=!1,E=N+1;if(O===46){if(f===-1)f=N;else if(A!==1)A=1}else if(f!==-1)A=-1}if(f===-1||E===-1||A===0||A===1&&f===E-1&&f===l+1)return"";return i.slice(f,E)}function p(i){if(i===null||typeof i!=="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof i);return u("/",i)}function r(i){S(i);var f={root:"",dir:"",base:"",ext:"",name:""};if(i.length===0)return f;var l=i.charCodeAt(0),E=l===47,_;if(E)f.root="/",_=1;else _=0;var A=-1,N=0,O=-1,U=!0,D=i.length-1,I=0;for(;D>=_;--D){if(l=i.charCodeAt(D),l===47){if(!U){N=D+1;break}continue}if(O===-1)U=!1,O=D+1;if(l===46){if(A===-1)A=D;else if(I!==1)I=1}else if(A!==-1)I=-1}if(A===-1||O===-1||I===0||I===1&&A===O-1&&A===N+1){if(O!==-1)if(N===0&&E)f.base=f.name=i.slice(1,O);else f.base=f.name=i.slice(N,O)}else{if(N===0&&E)f.name=i.slice(1,A),f.base=i.slice(1,O);else f.name=i.slice(N,A),f.base=i.slice(N,O);f.ext=i.slice(A,O)}if(N>0)f.dir=i.slice(0,N-1);else if(E)f.dir="/";return f}var Y="/",o=":",Si=((i)=>(i.posix=i,i))({resolve:j,normalize:T,isAbsolute:q,join:J,relative:G,_makeLong:y,dirname:F,basename:n,extname:s,format:p,parse:r,sep:Y,delimiter:o,win32:null,posix:null});class W{outputPath;constructor(i="./.vector/routes.generated.ts"){this.outputPath=i}async generate(i){let f=F(this.outputPath);await k.mkdir(f,{recursive:!0});let l=[],E=new Map;for(let O of i){if(!E.has(O.path))E.set(O.path,[]);E.get(O.path).push(O)}let _=0,A=[];for(let[O,U]of E){let D=G(F(this.outputPath),O).replace(/\\/g,"/").replace(/\.(ts|js)$/,""),I=`route_${_++}`,$=U.filter((w)=>w.name!=="default").map((w)=>w.name);if(U.some((w)=>w.name==="default"))if($.length>0)l.push(`import ${I}, { ${$.join(", ")} } from '${D}';`);else l.push(`import ${I} from '${D}';`);else if($.length>0)l.push(`import { ${$.join(", ")} } from '${D}';`);for(let w of U){let R=w.name==="default"?I:w.name;A.push(` ${R},`)}}let N=`// This file is auto-generated. Do not edit manually.
2
2
  // Generated at: ${new Date().toISOString()}
3
3
 
4
4
  ${l.join(`
@@ -18,4 +18,4 @@ export default routes;
18
18
  ${f.join(`,
19
19
  `)}
20
20
  ]);
21
- };`}}var{existsSync:t,promises:g}=(()=>({}));class Q{routesDir;excludePatterns;static DEFAULT_EXCLUDE_PATTERNS=["*.test.ts","*.test.js","*.test.tsx","*.test.jsx","*.spec.ts","*.spec.js","*.spec.tsx","*.spec.jsx","*.tests.ts","*.tests.js","**/__tests__/**","*.interface.ts","*.type.ts","*.d.ts"];constructor(i="./routes",f){this.routesDir=j(process.cwd(),i),this.excludePatterns=f||Q.DEFAULT_EXCLUDE_PATTERNS}async scan(){let i=[];if(!t(this.routesDir))return[];try{await this.scanDirectory(this.routesDir,i)}catch(f){if(f.code==="ENOENT")return console.warn(` ✗ Routes directory not accessible: ${this.routesDir}`),[];throw f}return i}isExcluded(i){let f=G(this.routesDir,i);for(let l of this.excludePatterns){let E=l.replace(/\./g,"\\.").replace(/\*/g,"[^/]*").replace(/\*\*/g,".*").replace(/\?/g,"."),_=new RegExp(`^${E}$`),A=f.split(Y).pop()||"";if(_.test(f)||_.test(A))return!0}return!1}async scanDirectory(i,f,l=""){let E=await g.readdir(i);for(let _ of E){let A=W(i,_);if((await g.stat(A)).isDirectory()){let O=l?`${l}/${_}`:_;await this.scanDirectory(A,f,O)}else if(_.endsWith(".ts")||_.endsWith(".js")){if(this.isExcluded(A))continue;let O=G(this.routesDir,A).replace(/\.(ts|js)$/,"").split(Y).join("/");try{let D=await import(process.platform==="win32"?`file:///${A.replace(/\\/g,"/")}`:A);if(D.default&&typeof D.default==="function")f.push({name:"default",path:A,method:"GET",options:{method:"GET",path:`/${O}`,expose:!0}});for(let[I,$]of Object.entries(D)){if(I==="default")continue;if($&&typeof $==="object"&&"entry"in $&&"options"in $&&"handler"in $){let w=$;f.push({name:I,path:A,method:w.options.method,options:w.options})}else if(Array.isArray($)&&$.length>=4){let[w,,,R]=$;f.push({name:I,path:A,method:w,options:{method:w,path:R,expose:!0}})}}}catch(U){console.error(`Failed to load route from ${A}:`,U)}}}}enableWatch(i){if(typeof Bun!=="undefined"&&Bun.env.NODE_ENV==="development")console.log(`Watching for route changes in ${this.routesDir}`),setInterval(async()=>{await i()},1000)}}class B{beforeHandlers=[];finallyHandlers=[];addBefore(...i){this.beforeHandlers.push(...i)}addFinally(...i){this.finallyHandlers.push(...i)}async executeBefore(i){let f=i;for(let l of this.beforeHandlers){let E=await l(f);if(E instanceof Response)return E;f=E}return f}async executeFinally(i,f){let l=i;for(let E of this.finallyHandlers)try{l=await E(l,f)}catch(_){console.error("After middleware error:",_)}return l}clone(){let i=new B;return i.beforeHandlers=[...this.beforeHandlers],i.finallyHandlers=[...this.finallyHandlers],i}clear(){this.beforeHandlers=[],this.finallyHandlers=[]}}function c(i){return process.platform==="win32"?`file:///${i.replace(/\\/g,"/")}`:i}class M{middlewareManager;authManager;cacheManager;routes=[];constructor(i,f,l){this.middlewareManager=i,this.authManager=f,this.cacheManager=l}getRouteSpecificity(i){let A=0,N=i.split("/").filter(Boolean);for(let O of N)if(this.isStaticSegment(O))A+=1000;else if(this.isParamSegment(O))A+=10;else if(this.isWildcardSegment(O))A+=1;if(A+=i.length,this.isExactPath(i))A+=1e4;return A}isStaticSegment(i){return!i.startsWith(":")&&!i.includes("*")}isParamSegment(i){return i.startsWith(":")}isWildcardSegment(i){return i.includes("*")}isExactPath(i){return!i.includes(":")&&!i.includes("*")}sortRoutes(){this.routes.sort((i,f)=>{let l=this.extractPath(i),E=this.extractPath(f),_=this.getRouteSpecificity(l);return this.getRouteSpecificity(E)-_})}extractPath(i){return i[3]||""}route(i,f){let l=this.wrapHandler(i,f),E=[i.method.toUpperCase(),this.createRouteRegex(i.path),[l],i.path];return this.routes.push(E),this.sortRoutes(),E}createRouteRegex(i){return RegExp(`^${i.replace(/\/+(\/|$)/g,"$1").replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`)}prepareRequest(i,f){if(!i.context)i.context={};if(f?.params!==void 0)i.params=f.params;if(f?.route!==void 0)i.route=f.route;if(f?.metadata!==void 0)i.metadata=f.metadata;if(!i.query&&i.url){let l=new URL(i.url),E={};for(let[_,A]of l.searchParams)if(_ in E)if(Array.isArray(E[_]))E[_].push(A);else E[_]=[E[_],A];else E[_]=A;i.query=E}if(!i.cookies)Z(i)}wrapHandler(i,f){return async(l)=>{let E=l;this.prepareRequest(E,{metadata:i.metadata}),l=E;try{if(i.expose===!1)return b.forbidden("Forbidden");let _=await this.middlewareManager.executeBefore(l);if(_ instanceof Response)return _;if(l=_,i.auth)try{await this.authManager.authenticate(l)}catch(D){return b.unauthorized(D instanceof Error?D.message:"Authentication failed",i.responseContentType)}if(!i.rawRequest&&l.method!=="GET"&&l.method!=="HEAD")try{let D=l.headers.get("content-type");if(D?.includes("application/json"))l.content=await l.json();else if(D?.includes("application/x-www-form-urlencoded"))l.content=Object.fromEntries(await l.formData());else if(D?.includes("multipart/form-data"))l.content=await l.formData();else l.content=await l.text()}catch{l.content=null}let A,N=i.cache,O=async()=>{let D=await f(l);if(D instanceof Response)return{_isResponse:!0,body:await D.text(),status:D.status,headers:Object.fromEntries(D.headers.entries())};return D};if(N&&typeof N==="number"&&N>0){let D=this.cacheManager.generateKey(l,{authUser:l.authUser});A=await this.cacheManager.get(D,O,N)}else if(N&&typeof N==="object"&&N.ttl){let D=N.key||this.cacheManager.generateKey(l,{authUser:l.authUser});A=await this.cacheManager.get(D,O,N.ttl)}else A=await f(l);if(A&&typeof A==="object"&&A._isResponse===!0)A=new Response(A.body,{status:A.status,headers:A.headers});let U;if(i.rawResponse||A instanceof Response)U=A instanceof Response?A:new Response(A);else U=a(200,A,i.responseContentType);return U=await this.middlewareManager.executeFinally(U,l),U}catch(_){if(_ instanceof Response)return _;return console.error("Route handler error:",_),b.internalServerError(_ instanceof Error?_.message:String(_),i.responseContentType)}}}addRoute(i){this.routes.push(i),this.sortRoutes()}getRoutes(){return this.routes}async handle(i){let l=new URL(i.url).pathname;for(let[E,_,A,N]of this.routes)if(i.method==="OPTIONS"||i.method===E){let O=l.match(_);if(O){let U=i;this.prepareRequest(U,{params:O.groups||{},route:N||l});for(let D of A){let I=await D(U);if(I)return I}}}return b.notFound("Route not found")}clearRoutes(){this.routes=[]}}class V{server=null;router;config;corsHandler;constructor(i,f){if(this.router=i,this.config=f,f.cors){let{preflight:l,corsify:E}=x(this.normalizeCorsOptions(f.cors));this.corsHandler={preflight:l,corsify:E}}}normalizeCorsOptions(i){return{origin:i.origin||"*",credentials:i.credentials!==!1,allowHeaders:Array.isArray(i.allowHeaders)?i.allowHeaders.join(", "):i.allowHeaders||"Content-Type, Authorization",allowMethods:Array.isArray(i.allowMethods)?i.allowMethods.join(", "):i.allowMethods||"GET, POST, PUT, PATCH, DELETE, OPTIONS",exposeHeaders:Array.isArray(i.exposeHeaders)?i.exposeHeaders.join(", "):i.exposeHeaders||"Authorization",maxAge:i.maxAge||86400}}async start(){let i=this.config.port||3000,f=this.config.hostname||"localhost",l=async(E)=>{try{if(this.corsHandler&&E.method==="OPTIONS")return this.corsHandler.preflight(E);let _=await this.router.handle(E);if(this.corsHandler)_=this.corsHandler.corsify(_,E);return _}catch(_){return console.error("Server error:",_),new Response("Internal Server Error",{status:500})}};try{if(this.server=Bun.serve({port:i,hostname:f,reusePort:this.config.reusePort!==!1,fetch:l,idleTimeout:this.config.idleTimeout||60,error:(E)=>{return console.error("[ERROR] Server error:",E),new Response("Internal Server Error",{status:500})}}),!this.server||!this.server.port)throw new Error(`Failed to start server on ${f}:${i} - server object is invalid`);return console.log(`→ Vector server running at http://${f}:${i}`),this.server}catch(E){if(E.code==="EADDRINUSE"||E.message?.includes("address already in use"))E.message=`Port ${i} is already in use`,E.port=i;else if(E.code==="EACCES"||E.message?.includes("permission denied"))E.message=`Permission denied to bind to port ${i}`,E.port=i;else if(E.message?.includes("EADDRNOTAVAIL"))E.message=`Cannot bind to hostname ${f}`,E.hostname=f;throw E}}stop(){if(this.server)this.server.stop(),this.server=null,console.log("Server stopped")}getServer(){return this.server}getPort(){return this.server?.port||this.config.port||3000}getHostname(){return this.server?.hostname||this.config.hostname||"localhost"}getUrl(){let i=this.getPort();return`http://${this.getHostname()}:${i}`}}class P{static instance;router;server=null;middlewareManager;authManager;cacheManager;config={};routeScanner=null;routeGenerator=null;_protectedHandler=null;_cacheHandler=null;constructor(){this.middlewareManager=new B,this.authManager=new z,this.cacheManager=new J,this.router=new M(this.middlewareManager,this.authManager,this.cacheManager)}static getInstance(){if(!P.instance)P.instance=new P;return P.instance}setProtectedHandler(i){this._protectedHandler=i,this.authManager.setProtectedHandler(i)}getProtectedHandler(){return this._protectedHandler}setCacheHandler(i){this._cacheHandler=i,this.cacheManager.setCacheHandler(i)}getCacheHandler(){return this._cacheHandler}addRoute(i,f){return this.router.route(i,f)}async startServer(i){if(this.config={...this.config,...i},this.middlewareManager.clear(),this.config.autoDiscover!==!1)this.router.clearRoutes();if(i?.before)this.middlewareManager.addBefore(...i.before);if(i?.finally)this.middlewareManager.addFinally(...i.finally);if(this.config.autoDiscover!==!1)await this.discoverRoutes();return this.server=new V(this.router,this.config),await this.server.start()}async discoverRoutes(){let i=this.config.routesDir||"./routes",f=this.config.routeExcludePatterns;if(this.routeScanner=new Q(i,f),!this.routeGenerator)this.routeGenerator=new h;try{let l=await this.routeScanner.scan();if(l.length>0){if(this.config.development)await this.routeGenerator.generate(l);for(let E of l)try{let A=await import(c(E.path)),N=E.name==="default"?A.default:A[E.name];if(N){if(this.isRouteDefinition(N)){let O=N;this.router.route(O.options,O.handler),this.logRouteLoaded(O.options)}else if(this.isRouteEntry(N))this.router.addRoute(N),this.logRouteLoaded(N);else if(typeof N==="function")this.router.route(E.options,N),this.logRouteLoaded(E.options)}}catch(_){console.error(`Failed to load route ${E.name} from ${E.path}:`,_)}this.router.sortRoutes()}}catch(l){if(l.code!=="ENOENT"&&l.code!=="ENOTDIR")console.error("Failed to discover routes:",l)}}async loadRoute(i){if(typeof i==="function"){let f=i();if(Array.isArray(f))this.router.addRoute(f)}else if(i&&typeof i==="object"){for(let[,f]of Object.entries(i))if(typeof f==="function"){let l=f();if(Array.isArray(l))this.router.addRoute(l)}}}isRouteEntry(i){return Array.isArray(i)&&i.length>=3}isRouteDefinition(i){return i&&typeof i==="object"&&"entry"in i&&"options"in i&&"handler"in i}logRouteLoaded(i){}stop(){if(this.server)this.server.stop(),this.server=null}getServer(){return this.server}getRouter(){return this.router}getCacheManager(){return this.cacheManager}getAuthManager(){return this.authManager}static resetInstance(){P.instance=null}}var m=P.getInstance;var{preflight:ci,corsify:mi}=x({origin:"*",credentials:!0,allowHeaders:"Content-Type, Authorization",allowMethods:"GET, POST, PUT, PATCH, DELETE, OPTIONS",exposeHeaders:"Authorization",maxAge:86400});function e(i,f){let l=Ei(i,f);return{entry:[i.method.toUpperCase(),RegExp(`^${i.path.replace(/\/+(\/|$)/g,"$1").replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`),[l],i.path],options:i,handler:f}}function ii(i){return JSON.stringify(i??null,(f,l)=>typeof l==="bigint"?l.toString():l)}var fi={success:(i,f)=>a(C.OK,i,f),created:(i,f)=>a(C.CREATED,i,f)};function L(i,f,l){let E={error:!0,message:f,statusCode:i,timestamp:new Date().toISOString()};return a(i,E,l)}var b={badRequest:(i="Bad Request",f)=>L(C.BAD_REQUEST,i,f),unauthorized:(i="Unauthorized",f)=>L(C.UNAUTHORIZED,i,f),paymentRequired:(i="Payment Required",f)=>L(402,i,f),forbidden:(i="Forbidden",f)=>L(C.FORBIDDEN,i,f),notFound:(i="Not Found",f)=>L(C.NOT_FOUND,i,f),methodNotAllowed:(i="Method Not Allowed",f)=>L(405,i,f),notAcceptable:(i="Not Acceptable",f)=>L(406,i,f),requestTimeout:(i="Request Timeout",f)=>L(408,i,f),conflict:(i="Conflict",f)=>L(C.CONFLICT,i,f),gone:(i="Gone",f)=>L(410,i,f),lengthRequired:(i="Length Required",f)=>L(411,i,f),preconditionFailed:(i="Precondition Failed",f)=>L(412,i,f),payloadTooLarge:(i="Payload Too Large",f)=>L(413,i,f),uriTooLong:(i="URI Too Long",f)=>L(414,i,f),unsupportedMediaType:(i="Unsupported Media Type",f)=>L(415,i,f),rangeNotSatisfiable:(i="Range Not Satisfiable",f)=>L(416,i,f),expectationFailed:(i="Expectation Failed",f)=>L(417,i,f),imATeapot:(i="I'm a teapot",f)=>L(418,i,f),misdirectedRequest:(i="Misdirected Request",f)=>L(421,i,f),unprocessableEntity:(i="Unprocessable Entity",f)=>L(C.UNPROCESSABLE_ENTITY,i,f),locked:(i="Locked",f)=>L(423,i,f),failedDependency:(i="Failed Dependency",f)=>L(424,i,f),tooEarly:(i="Too Early",f)=>L(425,i,f),upgradeRequired:(i="Upgrade Required",f)=>L(426,i,f),preconditionRequired:(i="Precondition Required",f)=>L(428,i,f),tooManyRequests:(i="Too Many Requests",f)=>L(429,i,f),requestHeaderFieldsTooLarge:(i="Request Header Fields Too Large",f)=>L(431,i,f),unavailableForLegalReasons:(i="Unavailable For Legal Reasons",f)=>L(451,i,f),internalServerError:(i="Internal Server Error",f)=>L(C.INTERNAL_SERVER_ERROR,i,f),notImplemented:(i="Not Implemented",f)=>L(501,i,f),badGateway:(i="Bad Gateway",f)=>L(502,i,f),serviceUnavailable:(i="Service Unavailable",f)=>L(503,i,f),gatewayTimeout:(i="Gateway Timeout",f)=>L(504,i,f),httpVersionNotSupported:(i="HTTP Version Not Supported",f)=>L(505,i,f),variantAlsoNegotiates:(i="Variant Also Negotiates",f)=>L(506,i,f),insufficientStorage:(i="Insufficient Storage",f)=>L(507,i,f),loopDetected:(i="Loop Detected",f)=>L(508,i,f),notExtended:(i="Not Extended",f)=>L(510,i,f),networkAuthenticationRequired:(i="Network Authentication Required",f)=>L(511,i,f),invalidArgument:(i="Invalid Argument",f)=>L(C.UNPROCESSABLE_ENTITY,i,f),rateLimitExceeded:(i="Rate Limit Exceeded",f)=>L(429,i,f),maintenance:(i="Service Under Maintenance",f)=>L(503,i,f),custom:(i,f,l)=>L(i,f,l)};function a(i,f,l=H.JSON){let E=l===H.JSON?ii(f):f;return new Response(E,{status:i,headers:{"content-type":l}})}var li=async(i,f)=>{let E=m().getProtectedHandler();if(!E)throw b.unauthorized("Authentication not configured",f);try{let _=await E(i);i.authUser=_}catch(_){throw b.unauthorized(_ instanceof Error?_.message:"Authentication failed",f)}};function Ei(i,f){let{auth:l=!1,expose:E=!1,rawRequest:_=!1,rawResponse:A=!1,responseContentType:N=H.JSON}=i;return async(O)=>{if(!E)return b.forbidden("Forbidden");try{if(l)await li(O,N);if(!_)await K(O);let U=await f(O);return A?U:fi.success(U,N)}catch(U){if(U instanceof Response)return U;return b.internalServerError(String(U),N)}}}export{e as route,a as createResponse,b as APIError};
21
+ };`}}var{existsSync:t,promises:g}=(()=>({}));class Q{routesDir;excludePatterns;static DEFAULT_EXCLUDE_PATTERNS=["*.test.ts","*.test.js","*.test.tsx","*.test.jsx","*.spec.ts","*.spec.js","*.spec.tsx","*.spec.jsx","*.tests.ts","*.tests.js","**/__tests__/**","*.interface.ts","*.type.ts","*.d.ts"];constructor(i="./routes",f){this.routesDir=j(process.cwd(),i),this.excludePatterns=f||Q.DEFAULT_EXCLUDE_PATTERNS}async scan(){let i=[];if(!t(this.routesDir))return[];try{await this.scanDirectory(this.routesDir,i)}catch(f){if(f.code==="ENOENT")return console.warn(` ✗ Routes directory not accessible: ${this.routesDir}`),[];throw f}return i}isExcluded(i){let f=G(this.routesDir,i);for(let l of this.excludePatterns){let E=l.replace(/\./g,"\\.").replace(/\*/g,"[^/]*").replace(/\*\*/g,".*").replace(/\?/g,"."),_=new RegExp(`^${E}$`),A=f.split(Y).pop()||"";if(_.test(f)||_.test(A))return!0}return!1}async scanDirectory(i,f,l=""){let E=await g.readdir(i);for(let _ of E){let A=J(i,_);if((await g.stat(A)).isDirectory()){let O=l?`${l}/${_}`:_;await this.scanDirectory(A,f,O)}else if(_.endsWith(".ts")||_.endsWith(".js")){if(this.isExcluded(A))continue;let O=G(this.routesDir,A).replace(/\.(ts|js)$/,"").split(Y).join("/");try{let D=await import(process.platform==="win32"?`file:///${A.replace(/\\/g,"/")}`:A);if(D.default&&typeof D.default==="function")f.push({name:"default",path:A,method:"GET",options:{method:"GET",path:`/${O}`,expose:!0}});for(let[I,$]of Object.entries(D)){if(I==="default")continue;if($&&typeof $==="object"&&"entry"in $&&"options"in $&&"handler"in $){let w=$;f.push({name:I,path:A,method:w.options.method,options:w.options})}else if(Array.isArray($)&&$.length>=4){let[w,,,R]=$;f.push({name:I,path:A,method:w,options:{method:w,path:R,expose:!0}})}}}catch(U){console.error(`Failed to load route from ${A}:`,U)}}}}enableWatch(i){if(typeof Bun!=="undefined"&&Bun.env.NODE_ENV==="development")console.log(`Watching for route changes in ${this.routesDir}`),setInterval(async()=>{await i()},1000)}}class B{beforeHandlers=[];finallyHandlers=[];addBefore(...i){this.beforeHandlers.push(...i)}addFinally(...i){this.finallyHandlers.push(...i)}async executeBefore(i){let f=i;for(let l of this.beforeHandlers){let E=await l(f);if(E instanceof Response)return E;f=E}return f}async executeFinally(i,f){let l=i;for(let E of this.finallyHandlers)try{l=await E(l,f)}catch(_){console.error("After middleware error:",_)}return l}clone(){let i=new B;return i.beforeHandlers=[...this.beforeHandlers],i.finallyHandlers=[...this.finallyHandlers],i}clear(){this.beforeHandlers=[],this.finallyHandlers=[]}}function c(i){return process.platform==="win32"?`file:///${i.replace(/\\/g,"/")}`:i}class M{middlewareManager;authManager;cacheManager;routes=[];constructor(i,f,l){this.middlewareManager=i,this.authManager=f,this.cacheManager=l}getRouteSpecificity(i){let A=0,N=i.split("/").filter(Boolean);for(let O of N)if(this.isStaticSegment(O))A+=1000;else if(this.isParamSegment(O))A+=10;else if(this.isWildcardSegment(O))A+=1;if(A+=i.length,this.isExactPath(i))A+=1e4;return A}isStaticSegment(i){return!i.startsWith(":")&&!i.includes("*")}isParamSegment(i){return i.startsWith(":")}isWildcardSegment(i){return i.includes("*")}isExactPath(i){return!i.includes(":")&&!i.includes("*")}sortRoutes(){this.routes.sort((i,f)=>{let l=this.extractPath(i),E=this.extractPath(f),_=this.getRouteSpecificity(l);return this.getRouteSpecificity(E)-_})}extractPath(i){return i[3]||""}route(i,f){let l=this.wrapHandler(i,f),E=[i.method.toUpperCase(),this.createRouteRegex(i.path),[l],i.path];return this.routes.push(E),this.sortRoutes(),E}createRouteRegex(i){return RegExp(`^${i.replace(/\/+(\/|$)/g,"$1").replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`)}prepareRequest(i,f){if(!i.context)i.context={};if(f?.params!==void 0)i.params=f.params;if(f?.route!==void 0)i.route=f.route;if(f?.metadata!==void 0)i.metadata=f.metadata;if(!i.query&&i.url){let l=new URL(i.url),E={};for(let[_,A]of l.searchParams)if(_ in E)if(Array.isArray(E[_]))E[_].push(A);else E[_]=[E[_],A];else E[_]=A;i.query=E}if(!i.cookies)Z(i)}wrapHandler(i,f){return async(l)=>{let E=l;this.prepareRequest(E,{metadata:i.metadata}),l=E;try{if(i.expose===!1)return b.forbidden("Forbidden");let _=await this.middlewareManager.executeBefore(l);if(_ instanceof Response)return _;if(l=_,i.auth)try{await this.authManager.authenticate(l)}catch(D){return b.unauthorized(D instanceof Error?D.message:"Authentication failed",i.responseContentType)}if(!i.rawRequest&&l.method!=="GET"&&l.method!=="HEAD")try{let D=l.headers.get("content-type");if(D?.includes("application/json"))l.content=await l.json();else if(D?.includes("application/x-www-form-urlencoded"))l.content=Object.fromEntries(await l.formData());else if(D?.includes("multipart/form-data"))l.content=await l.formData();else l.content=await l.text()}catch{l.content=null}let A,N=i.cache,O=async()=>{let D=await f(l);if(D instanceof Response)return{_isResponse:!0,body:await D.text(),status:D.status,headers:Object.fromEntries(D.headers.entries())};return D};if(N&&typeof N==="number"&&N>0){let D=this.cacheManager.generateKey(l,{authUser:l.authUser});A=await this.cacheManager.get(D,O,N)}else if(N&&typeof N==="object"&&N.ttl){let D=N.key||this.cacheManager.generateKey(l,{authUser:l.authUser});A=await this.cacheManager.get(D,O,N.ttl)}else A=await f(l);if(A&&typeof A==="object"&&A._isResponse===!0)A=new Response(A.body,{status:A.status,headers:A.headers});let U;if(i.rawResponse||A instanceof Response)U=A instanceof Response?A:new Response(A);else U=a(200,A,i.responseContentType);return U=await this.middlewareManager.executeFinally(U,l),U}catch(_){if(_ instanceof Response)return _;return console.error("Route handler error:",_),b.internalServerError(_ instanceof Error?_.message:String(_),i.responseContentType)}}}addRoute(i){this.routes.push(i),this.sortRoutes()}getRoutes(){return this.routes}async handle(i){let l=new URL(i.url).pathname;for(let[E,_,A,N]of this.routes)if(i.method==="OPTIONS"||i.method===E){let O=l.match(_);if(O){let U=i;this.prepareRequest(U,{params:O.groups||{},route:N||l});for(let D of A){let I=await D(U);if(I)return I}}}return b.notFound("Route not found")}clearRoutes(){this.routes=[]}}class V{server=null;router;config;corsHandler;constructor(i,f){if(this.router=i,this.config=f,f.cors){let{preflight:l,corsify:E}=x(this.normalizeCorsOptions(f.cors));this.corsHandler={preflight:l,corsify:E}}}normalizeCorsOptions(i){return{origin:i.origin||"*",credentials:i.credentials!==!1,allowHeaders:Array.isArray(i.allowHeaders)?i.allowHeaders.join(", "):i.allowHeaders||"Content-Type, Authorization",allowMethods:Array.isArray(i.allowMethods)?i.allowMethods.join(", "):i.allowMethods||"GET, POST, PUT, PATCH, DELETE, OPTIONS",exposeHeaders:Array.isArray(i.exposeHeaders)?i.exposeHeaders.join(", "):i.exposeHeaders||"Authorization",maxAge:i.maxAge||86400}}async start(){let i=this.config.port||3000,f=this.config.hostname||"localhost",l=async(E)=>{try{if(this.corsHandler&&E.method==="OPTIONS")return this.corsHandler.preflight(E);let _=await this.router.handle(E);if(this.corsHandler)_=this.corsHandler.corsify(_,E);return _}catch(_){return console.error("Server error:",_),new Response("Internal Server Error",{status:500})}};try{if(this.server=Bun.serve({port:i,hostname:f,reusePort:this.config.reusePort!==!1,fetch:l,idleTimeout:this.config.idleTimeout||60,error:(E)=>{return console.error("[ERROR] Server error:",E),new Response("Internal Server Error",{status:500})}}),!this.server||!this.server.port)throw new Error(`Failed to start server on ${f}:${i} - server object is invalid`);return this.server}catch(E){if(E.code==="EADDRINUSE"||E.message?.includes("address already in use"))E.message=`Port ${i} is already in use`,E.port=i;else if(E.code==="EACCES"||E.message?.includes("permission denied"))E.message=`Permission denied to bind to port ${i}`,E.port=i;else if(E.message?.includes("EADDRNOTAVAIL"))E.message=`Cannot bind to hostname ${f}`,E.hostname=f;throw E}}stop(){if(this.server)this.server.stop(),this.server=null,console.log("Server stopped")}getServer(){return this.server}getPort(){return this.server?.port||this.config.port||3000}getHostname(){return this.server?.hostname||this.config.hostname||"localhost"}getUrl(){let i=this.getPort();return`http://${this.getHostname()}:${i}`}}class P{static instance;router;server=null;middlewareManager;authManager;cacheManager;config={};routeScanner=null;routeGenerator=null;_protectedHandler=null;_cacheHandler=null;constructor(){this.middlewareManager=new B,this.authManager=new h,this.cacheManager=new z,this.router=new M(this.middlewareManager,this.authManager,this.cacheManager)}static getInstance(){if(!P.instance)P.instance=new P;return P.instance}setProtectedHandler(i){this._protectedHandler=i,this.authManager.setProtectedHandler(i)}getProtectedHandler(){return this._protectedHandler}setCacheHandler(i){this._cacheHandler=i,this.cacheManager.setCacheHandler(i)}getCacheHandler(){return this._cacheHandler}addRoute(i,f){return this.router.route(i,f)}async startServer(i){if(this.config={...this.config,...i},this.middlewareManager.clear(),this.config.autoDiscover!==!1)this.router.clearRoutes();if(i?.before)this.middlewareManager.addBefore(...i.before);if(i?.finally)this.middlewareManager.addFinally(...i.finally);if(this.config.autoDiscover!==!1)await this.discoverRoutes();return this.server=new V(this.router,this.config),await this.server.start()}async discoverRoutes(){let i=this.config.routesDir||"./routes",f=this.config.routeExcludePatterns;if(this.routeScanner=new Q(i,f),!this.routeGenerator)this.routeGenerator=new W;try{let l=await this.routeScanner.scan();if(l.length>0){if(this.config.development)await this.routeGenerator.generate(l);for(let E of l)try{let A=await import(c(E.path)),N=E.name==="default"?A.default:A[E.name];if(N){if(this.isRouteDefinition(N)){let O=N;this.router.route(O.options,O.handler),this.logRouteLoaded(O.options)}else if(this.isRouteEntry(N))this.router.addRoute(N),this.logRouteLoaded(N);else if(typeof N==="function")this.router.route(E.options,N),this.logRouteLoaded(E.options)}}catch(_){console.error(`Failed to load route ${E.name} from ${E.path}:`,_)}this.router.sortRoutes()}}catch(l){if(l.code!=="ENOENT"&&l.code!=="ENOTDIR")console.error("Failed to discover routes:",l)}}async loadRoute(i){if(typeof i==="function"){let f=i();if(Array.isArray(f))this.router.addRoute(f)}else if(i&&typeof i==="object"){for(let[,f]of Object.entries(i))if(typeof f==="function"){let l=f();if(Array.isArray(l))this.router.addRoute(l)}}}isRouteEntry(i){return Array.isArray(i)&&i.length>=3}isRouteDefinition(i){return i&&typeof i==="object"&&"entry"in i&&"options"in i&&"handler"in i}logRouteLoaded(i){}stop(){if(this.server)this.server.stop(),this.server=null}getServer(){return this.server}getRouter(){return this.router}getCacheManager(){return this.cacheManager}getAuthManager(){return this.authManager}static resetInstance(){P.instance=null}}var m=P.getInstance;var{preflight:ci,corsify:mi}=x({origin:"*",credentials:!0,allowHeaders:"Content-Type, Authorization",allowMethods:"GET, POST, PUT, PATCH, DELETE, OPTIONS",exposeHeaders:"Authorization",maxAge:86400});function e(i,f){let l=Ei(i,f);return{entry:[i.method.toUpperCase(),RegExp(`^${i.path.replace(/\/+(\/|$)/g,"$1").replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`),[l],i.path],options:i,handler:f}}function ii(i){return JSON.stringify(i??null,(f,l)=>typeof l==="bigint"?l.toString():l)}var fi={success:(i,f)=>a(C.OK,i,f),created:(i,f)=>a(C.CREATED,i,f)};function L(i,f,l){let E={error:!0,message:f,statusCode:i,timestamp:new Date().toISOString()};return a(i,E,l)}var b={badRequest:(i="Bad Request",f)=>L(C.BAD_REQUEST,i,f),unauthorized:(i="Unauthorized",f)=>L(C.UNAUTHORIZED,i,f),paymentRequired:(i="Payment Required",f)=>L(402,i,f),forbidden:(i="Forbidden",f)=>L(C.FORBIDDEN,i,f),notFound:(i="Not Found",f)=>L(C.NOT_FOUND,i,f),methodNotAllowed:(i="Method Not Allowed",f)=>L(405,i,f),notAcceptable:(i="Not Acceptable",f)=>L(406,i,f),requestTimeout:(i="Request Timeout",f)=>L(408,i,f),conflict:(i="Conflict",f)=>L(C.CONFLICT,i,f),gone:(i="Gone",f)=>L(410,i,f),lengthRequired:(i="Length Required",f)=>L(411,i,f),preconditionFailed:(i="Precondition Failed",f)=>L(412,i,f),payloadTooLarge:(i="Payload Too Large",f)=>L(413,i,f),uriTooLong:(i="URI Too Long",f)=>L(414,i,f),unsupportedMediaType:(i="Unsupported Media Type",f)=>L(415,i,f),rangeNotSatisfiable:(i="Range Not Satisfiable",f)=>L(416,i,f),expectationFailed:(i="Expectation Failed",f)=>L(417,i,f),imATeapot:(i="I'm a teapot",f)=>L(418,i,f),misdirectedRequest:(i="Misdirected Request",f)=>L(421,i,f),unprocessableEntity:(i="Unprocessable Entity",f)=>L(C.UNPROCESSABLE_ENTITY,i,f),locked:(i="Locked",f)=>L(423,i,f),failedDependency:(i="Failed Dependency",f)=>L(424,i,f),tooEarly:(i="Too Early",f)=>L(425,i,f),upgradeRequired:(i="Upgrade Required",f)=>L(426,i,f),preconditionRequired:(i="Precondition Required",f)=>L(428,i,f),tooManyRequests:(i="Too Many Requests",f)=>L(429,i,f),requestHeaderFieldsTooLarge:(i="Request Header Fields Too Large",f)=>L(431,i,f),unavailableForLegalReasons:(i="Unavailable For Legal Reasons",f)=>L(451,i,f),internalServerError:(i="Internal Server Error",f)=>L(C.INTERNAL_SERVER_ERROR,i,f),notImplemented:(i="Not Implemented",f)=>L(501,i,f),badGateway:(i="Bad Gateway",f)=>L(502,i,f),serviceUnavailable:(i="Service Unavailable",f)=>L(503,i,f),gatewayTimeout:(i="Gateway Timeout",f)=>L(504,i,f),httpVersionNotSupported:(i="HTTP Version Not Supported",f)=>L(505,i,f),variantAlsoNegotiates:(i="Variant Also Negotiates",f)=>L(506,i,f),insufficientStorage:(i="Insufficient Storage",f)=>L(507,i,f),loopDetected:(i="Loop Detected",f)=>L(508,i,f),notExtended:(i="Not Extended",f)=>L(510,i,f),networkAuthenticationRequired:(i="Network Authentication Required",f)=>L(511,i,f),invalidArgument:(i="Invalid Argument",f)=>L(C.UNPROCESSABLE_ENTITY,i,f),rateLimitExceeded:(i="Rate Limit Exceeded",f)=>L(429,i,f),maintenance:(i="Service Under Maintenance",f)=>L(503,i,f),custom:(i,f,l)=>L(i,f,l)};function a(i,f,l=H.JSON){let E=l===H.JSON?ii(f):f;return new Response(E,{status:i,headers:{"content-type":l}})}var li=async(i,f)=>{let E=m().getProtectedHandler();if(!E)throw b.unauthorized("Authentication not configured",f);try{let _=await E(i);i.authUser=_}catch(_){throw b.unauthorized(_ instanceof Error?_.message:"Authentication failed",f)}};function Ei(i,f){let{auth:l=!1,expose:E=!1,rawRequest:_=!1,rawResponse:A=!1,responseContentType:N=H.JSON}=i;return async(O)=>{if(!E)return b.forbidden("Forbidden");try{if(l)await li(O,N);if(!_)await K(O);let U=await f(O);return A?U:fi.success(U,N)}catch(U){if(U instanceof Response)return U;return b.internalServerError(String(U),N)}}}export{e as route,a as createResponse,b as APIError};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "vector-framework",
3
- "version": "0.9.9",
4
- "author": "",
3
+ "version": "1.0.0",
4
+ "author": "webhie-com",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "https://github.com/webhie-com/vector.git"
@@ -76,6 +76,7 @@
76
76
  "dev": "bun run src/cli/index.ts dev",
77
77
  "start": "bun run src/cli/index.ts start",
78
78
  "build": "bun run src/cli/index.ts build",
79
+ "build:app": "bun run src/cli/index.ts build",
79
80
  "build:lib": "bun run build:clean && bun run build:ts && bun run build:bundle && bun run build:cli",
80
81
  "build:clean": "rm -rf dist",
81
82
  "build:ts": "tsc",
package/src/cli/index.ts CHANGED
@@ -49,9 +49,6 @@ const command = positionals[0] || "dev";
49
49
 
50
50
  async function runDev() {
51
51
  const isDev = command === "dev";
52
- console.log(
53
- `\n→ Starting Vector ${isDev ? "development" : "production"} server\n`
54
- );
55
52
 
56
53
  let server: any = null;
57
54
  let vector: any = null;
@@ -69,7 +66,6 @@ async function runDev() {
69
66
  // Load configuration using ConfigLoader
70
67
  const configLoader = new ConfigLoader(values.config as string | undefined);
71
68
  const config = await configLoader.load();
72
- const configSource = configLoader.getConfigSource();
73
69
 
74
70
  // Merge CLI options with loaded config
75
71
  // Only use CLI values if config doesn't have them
@@ -115,28 +111,11 @@ async function runDev() {
115
111
  throw new Error("Server started but is not responding correctly");
116
112
  }
117
113
 
118
- const gray = "\x1b[90m";
119
- const reset = "\x1b[0m";
120
114
  const cyan = "\x1b[36m";
121
- const green = "\x1b[32m";
115
+ const reset = "\x1b[0m";
122
116
 
123
117
  console.log(
124
- ` ${gray}Config${reset} ${
125
- configSource === "user" ? "User config loaded" : "Using defaults"
126
- }`
127
- );
128
- console.log(` ${gray}Routes${reset} ${config.routesDir}`);
129
- if (isDev && values.watch) {
130
- console.log(` ${gray}Watching${reset} All project files`);
131
- }
132
- console.log(
133
- ` ${gray}CORS${reset} ${config.cors ? "Enabled" : "Disabled"}`
134
- );
135
- console.log(
136
- ` ${gray}Mode${reset} ${config.development ? "Development" : "Production"}\n`
137
- );
138
- console.log(
139
- ` ${green}Ready${reset} → ${cyan}http://${config.hostname}:${config.port}${reset}\n`
118
+ `\nListening on ${cyan}http://${config.hostname}:${config.port}${reset}\n`
140
119
  );
141
120
 
142
121
  return { server, vector, config };
@@ -230,75 +209,85 @@ async function runDev() {
230
209
  }
231
210
  });
232
211
  } catch {
233
- console.warn(" ⚠️ File watching not available");
212
+ const yellow = "\x1b[33m";
213
+ const reset = "\x1b[0m";
214
+ console.warn(`${yellow}Warning: File watching not available${reset}`);
234
215
  }
235
216
  }
236
217
  } catch (error: any) {
237
218
  const red = "\x1b[31m";
238
219
  const reset = "\x1b[0m";
239
220
 
240
- console.error(`\n${red}[ERROR] Failed to start server${reset}\n`);
241
-
242
- // Always show the error message and stack trace
243
- if (error.message) {
244
- console.error(`Message: ${error.message}`);
245
- }
221
+ console.error(`\n${red}Error: ${error.message || error}${reset}\n`);
246
222
 
247
- if (error.stack) {
248
- console.error(`\nStack trace:`);
223
+ if (error.stack && process.env.NODE_ENV === "development") {
249
224
  console.error(error.stack);
250
- } else if (!error.message) {
251
- // If no message or stack, show the raw error
252
- console.error(`Raw error:`, error);
253
225
  }
254
226
 
255
- // Ensure we exit with error code
256
227
  process.exit(1);
257
228
  }
258
229
  }
259
230
 
260
231
  async function runBuild() {
261
- console.log("\n→ Building Vector application\n");
262
-
263
232
  try {
264
233
  const { RouteScanner } = await import("../dev/route-scanner");
265
234
  const { RouteGenerator } = await import("../dev/route-generator");
266
235
 
236
+ // Step 1: Scan and generate routes
267
237
  const scanner = new RouteScanner(values.routes as string);
268
238
  const generator = new RouteGenerator();
269
239
 
270
240
  const routes = await scanner.scan();
271
241
  await generator.generate(routes);
272
242
 
273
- console.log(` Generated ${routes.length} routes`);
274
-
275
- // Use spawn based on runtime
243
+ // Step 2: Build the application with Bun
276
244
  if (typeof Bun !== "undefined") {
245
+ // Build the CLI as an executable
277
246
  const buildProcess = Bun.spawn([
278
247
  "bun",
279
248
  "build",
280
- "src/index.ts",
281
- "--outdir",
282
- "dist",
249
+ "src/cli/index.ts",
250
+ "--target",
251
+ "bun",
252
+ "--outfile",
253
+ "dist/server.js",
283
254
  "--minify",
284
255
  ]);
285
- await buildProcess.exited;
256
+
257
+ const exitCode = await buildProcess.exited;
258
+ if (exitCode !== 0) {
259
+ throw new Error(`Build failed with exit code ${exitCode}`);
260
+ }
286
261
  } else {
287
262
  // For Node.js, use child_process
288
263
  const { spawnSync } = await import("child_process");
289
- spawnSync(
264
+ const result = spawnSync(
290
265
  "bun",
291
- ["build", "src/index.ts", "--outdir", "dist", "--minify"],
266
+ [
267
+ "build",
268
+ "src/cli/index.ts",
269
+ "--target",
270
+ "bun",
271
+ "--outfile",
272
+ "dist/server.js",
273
+ "--minify",
274
+ ],
292
275
  {
293
276
  stdio: "inherit",
294
277
  shell: true,
295
278
  }
296
279
  );
280
+
281
+ if (result.status !== 0) {
282
+ throw new Error(`Build failed with exit code ${result.status}`);
283
+ }
297
284
  }
298
285
 
299
- console.log("\n ✓ Build complete\n");
300
- } catch (error) {
301
- console.error("[ERROR] Build failed:", error);
286
+ console.log("\nBuild complete: dist/server.js\n");
287
+ } catch (error: any) {
288
+ const red = "\x1b[31m";
289
+ const reset = "\x1b[0m";
290
+ console.error(`\n${red}Error: ${error.message || error}${reset}\n`);
302
291
  process.exit(1);
303
292
  }
304
293
  }
@@ -30,27 +30,21 @@ export class ConfigLoader<TTypes extends VectorTypes = DefaultVectorTypes> {
30
30
  // Check if config file exists before attempting to load
31
31
  if (existsSync(this.configPath)) {
32
32
  try {
33
- console.log(`→ Loading config from: ${this.configPath}`);
34
-
35
33
  // Use explicit file:// URL to ensure correct resolution
36
34
  const userConfigPath = toFileUrl(this.configPath);
37
35
  const userConfig = await import(userConfigPath);
38
36
  this.config = userConfig.default || userConfig;
39
37
  this.configSource = "user";
40
-
41
- console.log(" ✓ User config loaded successfully");
42
- } catch (error) {
38
+ } catch (error: any) {
39
+ const red = "\x1b[31m";
40
+ const reset = "\x1b[0m";
43
41
  console.error(
44
- ` ✗ Failed to load config from ${this.configPath}:`,
45
- error
42
+ `${red}Error loading config: ${error.message || error}${reset}`
46
43
  );
47
- console.log(" → Using default configuration");
48
44
  this.config = {};
49
45
  }
50
46
  } else {
51
47
  // Config file doesn't exist, use defaults
52
- console.log(` → No config file found at: ${this.configPath}`);
53
- console.log(" → Using default configuration");
54
48
  this.config = {};
55
49
  }
56
50
 
@@ -87,8 +87,7 @@ export class VectorServer<TTypes extends VectorTypes = DefaultVectorTypes> {
87
87
  throw new Error(`Failed to start server on ${hostname}:${port} - server object is invalid`);
88
88
  }
89
89
 
90
- // Server logs are handled by CLI, keep this minimal
91
- console.log(`→ Vector server running at http://${hostname}:${port}`);
90
+ // Server logs are handled by CLI
92
91
 
93
92
  return this.server;
94
93
  } catch (error: any) {