vector-framework 0.9.1 → 0.9.3
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 +27 -13
- package/dist/cli/index.js.map +1 -1
- package/dist/cli.js +90 -240
- package/dist/core/config-loader.d.ts.map +1 -1
- package/dist/core/config-loader.js +7 -1
- package/dist/core/config-loader.js.map +1 -1
- package/dist/core/vector.js +3 -3
- package/dist/core/vector.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +2 -2
- package/src/cli/index.ts +27 -13
- package/src/core/config-loader.ts +6 -1
- package/src/core/vector.ts +3 -3
package/dist/cli/index.js
CHANGED
|
@@ -3,8 +3,10 @@ import { watch } from "node:fs";
|
|
|
3
3
|
import { parseArgs } from "node:util";
|
|
4
4
|
import { getVectorInstance } from "../core/vector";
|
|
5
5
|
import { ConfigLoader } from "../core/config-loader";
|
|
6
|
+
// Compatibility layer for both Node and Bun
|
|
7
|
+
const args = typeof Bun !== 'undefined' ? Bun.argv.slice(2) : process.argv.slice(2);
|
|
6
8
|
const { values, positionals } = parseArgs({
|
|
7
|
-
args
|
|
9
|
+
args,
|
|
8
10
|
options: {
|
|
9
11
|
port: {
|
|
10
12
|
type: "string",
|
|
@@ -47,9 +49,10 @@ async function runDev() {
|
|
|
47
49
|
const config = await configLoader.load();
|
|
48
50
|
const configSource = configLoader.getConfigSource();
|
|
49
51
|
// Merge CLI options with loaded config
|
|
50
|
-
|
|
51
|
-
config.
|
|
52
|
-
config.
|
|
52
|
+
// Only use CLI values if config doesn't have them
|
|
53
|
+
config.port = config.port ?? Number.parseInt(values.port);
|
|
54
|
+
config.hostname = config.hostname ?? values.host;
|
|
55
|
+
config.routesDir = config.routesDir ?? values.routes;
|
|
53
56
|
config.development = isDev;
|
|
54
57
|
config.autoDiscover = true;
|
|
55
58
|
// Apply CLI CORS option if not set in config
|
|
@@ -161,15 +164,26 @@ async function runBuild() {
|
|
|
161
164
|
const routes = await scanner.scan();
|
|
162
165
|
await generator.generate(routes);
|
|
163
166
|
console.log(` Generated ${routes.length} routes`);
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
167
|
+
// Use spawn based on runtime
|
|
168
|
+
if (typeof Bun !== 'undefined') {
|
|
169
|
+
const buildProcess = Bun.spawn([
|
|
170
|
+
"bun",
|
|
171
|
+
"build",
|
|
172
|
+
"src/index.ts",
|
|
173
|
+
"--outdir",
|
|
174
|
+
"dist",
|
|
175
|
+
"--minify",
|
|
176
|
+
]);
|
|
177
|
+
await buildProcess.exited;
|
|
178
|
+
}
|
|
179
|
+
else {
|
|
180
|
+
// For Node.js, use child_process
|
|
181
|
+
const { spawnSync } = await import('child_process');
|
|
182
|
+
spawnSync('bun', ['build', 'src/index.ts', '--outdir', 'dist', '--minify'], {
|
|
183
|
+
stdio: 'inherit',
|
|
184
|
+
shell: true
|
|
185
|
+
});
|
|
186
|
+
}
|
|
173
187
|
console.log("\n ✓ Build complete\n");
|
|
174
188
|
}
|
|
175
189
|
catch (error) {
|
package/dist/cli/index.js.map
CHANGED
|
@@ -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,MAAM,
|
|
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;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IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC"}
|
package/dist/cli.js
CHANGED
|
@@ -1,7 +1,21 @@
|
|
|
1
|
-
#!/usr/bin/env
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
|
|
3
|
+
var __create = Object.create;
|
|
4
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
4
5
|
var __defProp = Object.defineProperty;
|
|
6
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __toESM = (mod, isNodeMode, target) => {
|
|
9
|
+
target = mod != null ? __create(__getProtoOf(mod)) : {};
|
|
10
|
+
const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
|
|
11
|
+
for (let key of __getOwnPropNames(mod))
|
|
12
|
+
if (!__hasOwnProp.call(to, key))
|
|
13
|
+
__defProp(to, key, {
|
|
14
|
+
get: () => mod[key],
|
|
15
|
+
enumerable: true
|
|
16
|
+
});
|
|
17
|
+
return to;
|
|
18
|
+
};
|
|
5
19
|
var __export = (target, all) => {
|
|
6
20
|
for (var name in all)
|
|
7
21
|
__defProp(target, name, {
|
|
@@ -12,7 +26,7 @@ var __export = (target, all) => {
|
|
|
12
26
|
});
|
|
13
27
|
};
|
|
14
28
|
var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
|
|
15
|
-
var __require =
|
|
29
|
+
var __require = import.meta.require;
|
|
16
30
|
|
|
17
31
|
// src/auth/protected.ts
|
|
18
32
|
class AuthManager {
|
|
@@ -219,8 +233,12 @@ var init_manager = __esm(() => {
|
|
|
219
233
|
});
|
|
220
234
|
|
|
221
235
|
// src/dev/route-generator.ts
|
|
222
|
-
|
|
223
|
-
|
|
236
|
+
var exports_route_generator = {};
|
|
237
|
+
__export(exports_route_generator, {
|
|
238
|
+
RouteGenerator: () => RouteGenerator
|
|
239
|
+
});
|
|
240
|
+
import { promises as fs } from "fs";
|
|
241
|
+
import { dirname, relative } from "path";
|
|
224
242
|
|
|
225
243
|
class RouteGenerator {
|
|
226
244
|
outputPath;
|
|
@@ -298,8 +316,12 @@ ${routeEntries.join(`,
|
|
|
298
316
|
var init_route_generator = () => {};
|
|
299
317
|
|
|
300
318
|
// src/dev/route-scanner.ts
|
|
301
|
-
|
|
302
|
-
|
|
319
|
+
var exports_route_scanner = {};
|
|
320
|
+
__export(exports_route_scanner, {
|
|
321
|
+
RouteScanner: () => RouteScanner
|
|
322
|
+
});
|
|
323
|
+
import { existsSync, promises as fs2 } from "fs";
|
|
324
|
+
import { join, relative as relative2, resolve, sep } from "path";
|
|
303
325
|
|
|
304
326
|
class RouteScanner {
|
|
305
327
|
routesDir;
|
|
@@ -309,19 +331,19 @@ class RouteScanner {
|
|
|
309
331
|
async scan() {
|
|
310
332
|
const routes = [];
|
|
311
333
|
if (!existsSync(this.routesDir)) {
|
|
312
|
-
console.log(`
|
|
313
|
-
console.log("
|
|
334
|
+
console.log(` \u2192 Routes directory not found: ${this.routesDir}`);
|
|
335
|
+
console.log(" \u2192 No routes will be auto-discovered");
|
|
314
336
|
return [];
|
|
315
337
|
}
|
|
316
338
|
try {
|
|
317
|
-
console.log(`
|
|
339
|
+
console.log(` \u2192 Scanning routes from: ${this.routesDir}`);
|
|
318
340
|
await this.scanDirectory(this.routesDir, routes);
|
|
319
341
|
if (routes.length > 0) {
|
|
320
|
-
console.log(`
|
|
342
|
+
console.log(` \u2713 Found ${routes.length} route${routes.length === 1 ? "" : "s"}`);
|
|
321
343
|
}
|
|
322
344
|
} catch (error) {
|
|
323
345
|
if (error.code === "ENOENT") {
|
|
324
|
-
console.warn(`
|
|
346
|
+
console.warn(` \u2717 Routes directory not accessible: ${this.routesDir}`);
|
|
325
347
|
return [];
|
|
326
348
|
}
|
|
327
349
|
throw error;
|
|
@@ -794,7 +816,7 @@ class VectorServer {
|
|
|
794
816
|
return new Response("Internal Server Error", { status: 500 });
|
|
795
817
|
}
|
|
796
818
|
});
|
|
797
|
-
console.log(
|
|
819
|
+
console.log(`\u2192 Vector server running at http://${hostname}:${port}`);
|
|
798
820
|
return this.server;
|
|
799
821
|
}
|
|
800
822
|
stop() {
|
|
@@ -823,202 +845,7 @@ var init_server = __esm(() => {
|
|
|
823
845
|
init_itty_router();
|
|
824
846
|
});
|
|
825
847
|
|
|
826
|
-
// src/dev/route-scanner.ts
|
|
827
|
-
var exports_route_scanner = {};
|
|
828
|
-
__export(exports_route_scanner, {
|
|
829
|
-
RouteScanner: () => RouteScanner2
|
|
830
|
-
});
|
|
831
|
-
import { existsSync as existsSync3, promises as fs3 } from "node:fs";
|
|
832
|
-
import { join as join2, relative as relative3, resolve as resolve3, sep as sep2 } from "node:path";
|
|
833
|
-
|
|
834
|
-
class RouteScanner2 {
|
|
835
|
-
routesDir;
|
|
836
|
-
constructor(routesDir = "./routes") {
|
|
837
|
-
this.routesDir = resolve3(process.cwd(), routesDir);
|
|
838
|
-
}
|
|
839
|
-
async scan() {
|
|
840
|
-
const routes = [];
|
|
841
|
-
if (!existsSync3(this.routesDir)) {
|
|
842
|
-
console.log(` → Routes directory not found: ${this.routesDir}`);
|
|
843
|
-
console.log(" → No routes will be auto-discovered");
|
|
844
|
-
return [];
|
|
845
|
-
}
|
|
846
|
-
try {
|
|
847
|
-
console.log(` → Scanning routes from: ${this.routesDir}`);
|
|
848
|
-
await this.scanDirectory(this.routesDir, routes);
|
|
849
|
-
if (routes.length > 0) {
|
|
850
|
-
console.log(` ✓ Found ${routes.length} route${routes.length === 1 ? "" : "s"}`);
|
|
851
|
-
}
|
|
852
|
-
} catch (error) {
|
|
853
|
-
if (error.code === "ENOENT") {
|
|
854
|
-
console.warn(` ✗ Routes directory not accessible: ${this.routesDir}`);
|
|
855
|
-
return [];
|
|
856
|
-
}
|
|
857
|
-
throw error;
|
|
858
|
-
}
|
|
859
|
-
return routes;
|
|
860
|
-
}
|
|
861
|
-
async scanDirectory(dir, routes, basePath = "") {
|
|
862
|
-
const entries = await fs3.readdir(dir);
|
|
863
|
-
for (const entry of entries) {
|
|
864
|
-
const fullPath = join2(dir, entry);
|
|
865
|
-
const stats = await fs3.stat(fullPath);
|
|
866
|
-
if (stats.isDirectory()) {
|
|
867
|
-
const newBasePath = basePath ? `${basePath}/${entry}` : entry;
|
|
868
|
-
await this.scanDirectory(fullPath, routes, newBasePath);
|
|
869
|
-
} else if (entry.endsWith(".ts") || entry.endsWith(".js")) {
|
|
870
|
-
const routePath = relative3(this.routesDir, fullPath).replace(/\.(ts|js)$/, "").split(sep2).join("/");
|
|
871
|
-
try {
|
|
872
|
-
const importPath = process.platform === "win32" ? `file:///${fullPath.replace(/\\/g, "/")}` : fullPath;
|
|
873
|
-
const module = await import(importPath);
|
|
874
|
-
if (module.default && typeof module.default === "function") {
|
|
875
|
-
routes.push({
|
|
876
|
-
name: "default",
|
|
877
|
-
path: fullPath,
|
|
878
|
-
method: "GET",
|
|
879
|
-
options: {
|
|
880
|
-
method: "GET",
|
|
881
|
-
path: `/${routePath}`,
|
|
882
|
-
expose: true
|
|
883
|
-
}
|
|
884
|
-
});
|
|
885
|
-
}
|
|
886
|
-
for (const [name, value] of Object.entries(module)) {
|
|
887
|
-
if (name === "default")
|
|
888
|
-
continue;
|
|
889
|
-
if (value && typeof value === "object" && "entry" in value && "options" in value && "handler" in value) {
|
|
890
|
-
const routeDef = value;
|
|
891
|
-
routes.push({
|
|
892
|
-
name,
|
|
893
|
-
path: fullPath,
|
|
894
|
-
method: routeDef.options.method,
|
|
895
|
-
options: routeDef.options
|
|
896
|
-
});
|
|
897
|
-
} else if (Array.isArray(value) && value.length >= 4) {
|
|
898
|
-
const [method, , , path] = value;
|
|
899
|
-
routes.push({
|
|
900
|
-
name,
|
|
901
|
-
path: fullPath,
|
|
902
|
-
method,
|
|
903
|
-
options: {
|
|
904
|
-
method,
|
|
905
|
-
path,
|
|
906
|
-
expose: true
|
|
907
|
-
}
|
|
908
|
-
});
|
|
909
|
-
}
|
|
910
|
-
}
|
|
911
|
-
} catch (error) {
|
|
912
|
-
console.error(`Failed to load route from ${fullPath}:`, error);
|
|
913
|
-
}
|
|
914
|
-
}
|
|
915
|
-
}
|
|
916
|
-
}
|
|
917
|
-
enableWatch(callback) {
|
|
918
|
-
if (typeof Bun !== "undefined" && Bun.env.NODE_ENV === "development") {
|
|
919
|
-
console.log(`Watching for route changes in ${this.routesDir}`);
|
|
920
|
-
setInterval(async () => {
|
|
921
|
-
await callback();
|
|
922
|
-
}, 1000);
|
|
923
|
-
}
|
|
924
|
-
}
|
|
925
|
-
}
|
|
926
|
-
var init_route_scanner2 = () => {};
|
|
927
|
-
|
|
928
|
-
// src/dev/route-generator.ts
|
|
929
|
-
var exports_route_generator = {};
|
|
930
|
-
__export(exports_route_generator, {
|
|
931
|
-
RouteGenerator: () => RouteGenerator2
|
|
932
|
-
});
|
|
933
|
-
import { promises as fs4 } from "node:fs";
|
|
934
|
-
import { dirname as dirname2, relative as relative4 } from "node:path";
|
|
935
|
-
|
|
936
|
-
class RouteGenerator2 {
|
|
937
|
-
outputPath;
|
|
938
|
-
constructor(outputPath = "./.vector/routes.generated.ts") {
|
|
939
|
-
this.outputPath = outputPath;
|
|
940
|
-
}
|
|
941
|
-
async generate(routes) {
|
|
942
|
-
const outputDir = dirname2(this.outputPath);
|
|
943
|
-
await fs4.mkdir(outputDir, { recursive: true });
|
|
944
|
-
const imports = [];
|
|
945
|
-
const groupedByFile = new Map;
|
|
946
|
-
for (const route of routes) {
|
|
947
|
-
if (!groupedByFile.has(route.path)) {
|
|
948
|
-
groupedByFile.set(route.path, []);
|
|
949
|
-
}
|
|
950
|
-
groupedByFile.get(route.path).push(route);
|
|
951
|
-
}
|
|
952
|
-
let importIndex = 0;
|
|
953
|
-
const routeEntries = [];
|
|
954
|
-
for (const [filePath, fileRoutes] of groupedByFile) {
|
|
955
|
-
const relativePath = relative4(dirname2(this.outputPath), filePath).replace(/\\/g, "/").replace(/\.(ts|js)$/, "");
|
|
956
|
-
const importName = `route_${importIndex++}`;
|
|
957
|
-
const namedImports = fileRoutes.filter((r2) => r2.name !== "default").map((r2) => r2.name);
|
|
958
|
-
if (fileRoutes.some((r2) => r2.name === "default")) {
|
|
959
|
-
if (namedImports.length > 0) {
|
|
960
|
-
imports.push(`import ${importName}, { ${namedImports.join(", ")} } from '${relativePath}';`);
|
|
961
|
-
} else {
|
|
962
|
-
imports.push(`import ${importName} from '${relativePath}';`);
|
|
963
|
-
}
|
|
964
|
-
} else if (namedImports.length > 0) {
|
|
965
|
-
imports.push(`import { ${namedImports.join(", ")} } from '${relativePath}';`);
|
|
966
|
-
}
|
|
967
|
-
for (const route of fileRoutes) {
|
|
968
|
-
const routeVar = route.name === "default" ? importName : route.name;
|
|
969
|
-
routeEntries.push(` ${routeVar},`);
|
|
970
|
-
}
|
|
971
|
-
}
|
|
972
|
-
const content = `// This file is auto-generated. Do not edit manually.
|
|
973
|
-
// Generated at: ${new Date().toISOString()}
|
|
974
|
-
|
|
975
|
-
${imports.join(`
|
|
976
|
-
`)}
|
|
977
|
-
|
|
978
|
-
export const routes = [
|
|
979
|
-
${routeEntries.join(`
|
|
980
|
-
`)}
|
|
981
|
-
];
|
|
982
|
-
|
|
983
|
-
export default routes;
|
|
984
|
-
`;
|
|
985
|
-
await fs4.writeFile(this.outputPath, content, "utf-8");
|
|
986
|
-
console.log(`Generated routes file: ${this.outputPath}`);
|
|
987
|
-
}
|
|
988
|
-
async generateDynamic(routes) {
|
|
989
|
-
const routeEntries = [];
|
|
990
|
-
for (const route of routes) {
|
|
991
|
-
const routeObj = JSON.stringify({
|
|
992
|
-
method: route.method,
|
|
993
|
-
path: route.options.path,
|
|
994
|
-
options: route.options
|
|
995
|
-
});
|
|
996
|
-
routeEntries.push(` await import('${route.path}').then(m => ({
|
|
997
|
-
...${routeObj},
|
|
998
|
-
handler: m.${route.name === "default" ? "default" : route.name}
|
|
999
|
-
}))`);
|
|
1000
|
-
}
|
|
1001
|
-
return `export const loadRoutes = async () => {
|
|
1002
|
-
return Promise.all([
|
|
1003
|
-
${routeEntries.join(`,
|
|
1004
|
-
`)}
|
|
1005
|
-
]);
|
|
1006
|
-
};`;
|
|
1007
|
-
}
|
|
1008
|
-
}
|
|
1009
|
-
var init_route_generator2 = () => {};
|
|
1010
|
-
|
|
1011
|
-
// src/cli/index.ts
|
|
1012
|
-
import { watch } from "fs";
|
|
1013
|
-
import { parseArgs } from "util";
|
|
1014
|
-
|
|
1015
848
|
// src/core/vector.ts
|
|
1016
|
-
init_manager();
|
|
1017
|
-
init_route_generator();
|
|
1018
|
-
init_route_scanner();
|
|
1019
|
-
init_router();
|
|
1020
|
-
init_server();
|
|
1021
|
-
|
|
1022
849
|
class Vector {
|
|
1023
850
|
static instance;
|
|
1024
851
|
router;
|
|
@@ -1078,9 +905,7 @@ class Vector {
|
|
|
1078
905
|
}
|
|
1079
906
|
async discoverRoutes() {
|
|
1080
907
|
const routesDir = this.config.routesDir || "./routes";
|
|
1081
|
-
|
|
1082
|
-
this.routeScanner = new RouteScanner(routesDir);
|
|
1083
|
-
}
|
|
908
|
+
this.routeScanner = new RouteScanner(routesDir);
|
|
1084
909
|
if (!this.routeGenerator) {
|
|
1085
910
|
this.routeGenerator = new RouteGenerator;
|
|
1086
911
|
}
|
|
@@ -1113,7 +938,7 @@ class Vector {
|
|
|
1113
938
|
}
|
|
1114
939
|
}
|
|
1115
940
|
this.router.sortRoutes();
|
|
1116
|
-
console.log(
|
|
941
|
+
console.log(`\u2705 Loaded ${routes.length} routes from ${routesDir}`);
|
|
1117
942
|
}
|
|
1118
943
|
} catch (error) {
|
|
1119
944
|
if (error.code !== "ENOENT" && error.code !== "ENOTDIR") {
|
|
@@ -1146,9 +971,9 @@ class Vector {
|
|
|
1146
971
|
}
|
|
1147
972
|
logRouteLoaded(route) {
|
|
1148
973
|
if (Array.isArray(route)) {
|
|
1149
|
-
console.log(`
|
|
974
|
+
console.log(` \u2713 Loaded route: ${route[0]} ${route[3] || route[1]}`);
|
|
1150
975
|
} else {
|
|
1151
|
-
console.log(`
|
|
976
|
+
console.log(` \u2713 Loaded route: ${route.method} ${route.path}`);
|
|
1152
977
|
}
|
|
1153
978
|
}
|
|
1154
979
|
stop() {
|
|
@@ -1174,11 +999,24 @@ class Vector {
|
|
|
1174
999
|
Vector.instance = null;
|
|
1175
1000
|
}
|
|
1176
1001
|
}
|
|
1177
|
-
var getVectorInstance
|
|
1002
|
+
var getVectorInstance;
|
|
1003
|
+
var init_vector = __esm(() => {
|
|
1004
|
+
init_manager();
|
|
1005
|
+
init_route_generator();
|
|
1006
|
+
init_route_scanner();
|
|
1007
|
+
init_router();
|
|
1008
|
+
init_server();
|
|
1009
|
+
getVectorInstance = Vector.getInstance;
|
|
1010
|
+
});
|
|
1011
|
+
|
|
1012
|
+
// src/cli/index.ts
|
|
1013
|
+
init_vector();
|
|
1014
|
+
import { watch } from "fs";
|
|
1015
|
+
import { parseArgs } from "util";
|
|
1178
1016
|
|
|
1179
1017
|
// src/core/config-loader.ts
|
|
1180
|
-
import { existsSync as existsSync2 } from "
|
|
1181
|
-
import { resolve as resolve2 } from "
|
|
1018
|
+
import { existsSync as existsSync2 } from "fs";
|
|
1019
|
+
import { resolve as resolve2 } from "path";
|
|
1182
1020
|
|
|
1183
1021
|
class ConfigLoader {
|
|
1184
1022
|
configPath;
|
|
@@ -1190,20 +1028,20 @@ class ConfigLoader {
|
|
|
1190
1028
|
async load() {
|
|
1191
1029
|
if (existsSync2(this.configPath)) {
|
|
1192
1030
|
try {
|
|
1193
|
-
console.log(
|
|
1031
|
+
console.log(`\u2192 Loading config from: ${this.configPath}`);
|
|
1194
1032
|
const userConfigPath = toFileUrl(this.configPath);
|
|
1195
1033
|
const userConfig = await import(userConfigPath);
|
|
1196
1034
|
this.config = userConfig.default || userConfig;
|
|
1197
1035
|
this.configSource = "user";
|
|
1198
|
-
console.log("
|
|
1036
|
+
console.log(" \u2713 User config loaded successfully");
|
|
1199
1037
|
} catch (error) {
|
|
1200
|
-
console.error(`
|
|
1201
|
-
console.log("
|
|
1038
|
+
console.error(` \u2717 Failed to load config from ${this.configPath}:`, error);
|
|
1039
|
+
console.log(" \u2192 Using default configuration");
|
|
1202
1040
|
this.config = {};
|
|
1203
1041
|
}
|
|
1204
1042
|
} else {
|
|
1205
|
-
console.log(`
|
|
1206
|
-
console.log("
|
|
1043
|
+
console.log(` \u2192 No config file found at: ${this.configPath}`);
|
|
1044
|
+
console.log(" \u2192 Using default configuration");
|
|
1207
1045
|
this.config = {};
|
|
1208
1046
|
}
|
|
1209
1047
|
return await this.buildLegacyConfig();
|
|
@@ -1222,6 +1060,9 @@ class ConfigLoader {
|
|
|
1222
1060
|
if (this.config?.routes) {
|
|
1223
1061
|
config.routesDir = this.config.routes.dir || "./routes";
|
|
1224
1062
|
config.autoDiscover = this.config.routes.autoDiscover !== false;
|
|
1063
|
+
} else if (this.config?.routesDir) {
|
|
1064
|
+
config.routesDir = this.config.routesDir;
|
|
1065
|
+
config.autoDiscover = this.config.autoDiscover !== false;
|
|
1225
1066
|
} else {
|
|
1226
1067
|
config.routesDir = "./routes";
|
|
1227
1068
|
config.autoDiscover = true;
|
|
@@ -1331,8 +1172,9 @@ class ConfigLoader {
|
|
|
1331
1172
|
}
|
|
1332
1173
|
|
|
1333
1174
|
// src/cli/index.ts
|
|
1175
|
+
var args = typeof Bun !== "undefined" ? Bun.argv.slice(2) : process.argv.slice(2);
|
|
1334
1176
|
var { values, positionals } = parseArgs({
|
|
1335
|
-
args
|
|
1177
|
+
args,
|
|
1336
1178
|
options: {
|
|
1337
1179
|
port: {
|
|
1338
1180
|
type: "string",
|
|
@@ -1375,9 +1217,9 @@ async function runDev() {
|
|
|
1375
1217
|
const configLoader = new ConfigLoader;
|
|
1376
1218
|
const config = await configLoader.load();
|
|
1377
1219
|
const configSource = configLoader.getConfigSource();
|
|
1378
|
-
config.port = config.port
|
|
1379
|
-
config.hostname = config.hostname
|
|
1380
|
-
config.routesDir = config.routesDir
|
|
1220
|
+
config.port = config.port ?? Number.parseInt(values.port);
|
|
1221
|
+
config.hostname = config.hostname ?? values.host;
|
|
1222
|
+
config.routesDir = config.routesDir ?? values.routes;
|
|
1381
1223
|
config.development = isDev;
|
|
1382
1224
|
config.autoDiscover = true;
|
|
1383
1225
|
if (!config.cors && values.cors) {
|
|
@@ -1467,22 +1309,30 @@ async function runBuild() {
|
|
|
1467
1309
|
\u2192 Building Vector application
|
|
1468
1310
|
`);
|
|
1469
1311
|
try {
|
|
1470
|
-
const { RouteScanner:
|
|
1471
|
-
const { RouteGenerator:
|
|
1472
|
-
const scanner = new
|
|
1473
|
-
const generator = new
|
|
1312
|
+
const { RouteScanner: RouteScanner2 } = await Promise.resolve().then(() => (init_route_scanner(), exports_route_scanner));
|
|
1313
|
+
const { RouteGenerator: RouteGenerator2 } = await Promise.resolve().then(() => (init_route_generator(), exports_route_generator));
|
|
1314
|
+
const scanner = new RouteScanner2(values.routes);
|
|
1315
|
+
const generator = new RouteGenerator2;
|
|
1474
1316
|
const routes = await scanner.scan();
|
|
1475
1317
|
await generator.generate(routes);
|
|
1476
1318
|
console.log(` Generated ${routes.length} routes`);
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1319
|
+
if (typeof Bun !== "undefined") {
|
|
1320
|
+
const buildProcess = Bun.spawn([
|
|
1321
|
+
"bun",
|
|
1322
|
+
"build",
|
|
1323
|
+
"src/index.ts",
|
|
1324
|
+
"--outdir",
|
|
1325
|
+
"dist",
|
|
1326
|
+
"--minify"
|
|
1327
|
+
]);
|
|
1328
|
+
await buildProcess.exited;
|
|
1329
|
+
} else {
|
|
1330
|
+
const { spawnSync } = await import("child_process");
|
|
1331
|
+
spawnSync("bun", ["build", "src/index.ts", "--outdir", "dist", "--minify"], {
|
|
1332
|
+
stdio: "inherit",
|
|
1333
|
+
shell: true
|
|
1334
|
+
});
|
|
1335
|
+
}
|
|
1486
1336
|
console.log(`
|
|
1487
1337
|
\u2713 Build complete
|
|
1488
1338
|
`);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config-loader.d.ts","sourceRoot":"","sources":["../../src/core/config-loader.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAGV,YAAY,EAEZ,kBAAkB,EAClB,gBAAgB,EAChB,YAAY,EACZ,kBAAkB,EAClB,WAAW,EACZ,MAAM,UAAU,CAAC;AAElB,qBAAa,YAAY,CAAC,MAAM,SAAS,WAAW,GAAG,kBAAkB;IACvE,OAAO,CAAC,UAAU,CAAS;IAC3B,OAAO,CAAC,MAAM,CAA2C;IACzD,OAAO,CAAC,YAAY,CAAiC;gBAEzC,UAAU,SAAqB;IAKrC,IAAI,IAAI,OAAO,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC;IA6B3C,eAAe,IAAI,MAAM,GAAG,SAAS;YAIvB,iBAAiB;
|
|
1
|
+
{"version":3,"file":"config-loader.d.ts","sourceRoot":"","sources":["../../src/core/config-loader.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAGV,YAAY,EAEZ,kBAAkB,EAClB,gBAAgB,EAChB,YAAY,EACZ,kBAAkB,EAClB,WAAW,EACZ,MAAM,UAAU,CAAC;AAElB,qBAAa,YAAY,CAAC,MAAM,SAAS,WAAW,GAAG,kBAAkB;IACvE,OAAO,CAAC,UAAU,CAAS;IAC3B,OAAO,CAAC,MAAM,CAA2C;IACzD,OAAO,CAAC,YAAY,CAAiC;gBAEzC,UAAU,SAAqB;IAKrC,IAAI,IAAI,OAAO,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC;IA6B3C,eAAe,IAAI,MAAM,GAAG,SAAS;YAIvB,iBAAiB;YAyEjB,cAAc;IAuBtB,eAAe,IAAI,OAAO,CAAC,gBAAgB,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC;IA8B3D,gBAAgB,IAAI,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC;IA8BtD,SAAS,IAAI,kBAAkB,CAAC,MAAM,CAAC,GAAG,IAAI;CAG/C"}
|
|
@@ -48,11 +48,17 @@ export class ConfigLoader {
|
|
|
48
48
|
config.reusePort = this.config.server.reusePort;
|
|
49
49
|
config.development = this.config.server.development;
|
|
50
50
|
}
|
|
51
|
-
// Routes configuration
|
|
51
|
+
// Routes configuration - support both new and legacy formats
|
|
52
52
|
if (this.config?.routes) {
|
|
53
|
+
// New format: { routes: { dir: string } }
|
|
53
54
|
config.routesDir = this.config.routes.dir || './routes';
|
|
54
55
|
config.autoDiscover = this.config.routes.autoDiscover !== false;
|
|
55
56
|
}
|
|
57
|
+
else if (this.config?.routesDir) {
|
|
58
|
+
// Legacy format: { routesDir: string }
|
|
59
|
+
config.routesDir = this.config.routesDir;
|
|
60
|
+
config.autoDiscover = this.config.autoDiscover !== false;
|
|
61
|
+
}
|
|
56
62
|
else {
|
|
57
63
|
config.routesDir = './routes';
|
|
58
64
|
config.autoDiscover = true;
|
|
@@ -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,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAa1C,MAAM,OAAO,YAAY;IACf,UAAU,CAAS;IACnB,MAAM,GAAsC,IAAI,CAAC;IACjD,YAAY,GAAuB,SAAS,CAAC;IAErD,YAAY,UAAU,GAAG,kBAAkB;QACzC,qEAAqE;QACrE,IAAI,CAAC,UAAU,GAAG,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,UAAU,CAAC,CAAC;IACvD,CAAC;IAED,KAAK,CAAC,IAAI;QACR,wDAAwD;QACxD,IAAI,UAAU,CAAC,IAAI,CAAC,UAAU,CAAC,EAAE,CAAC;YAChC,IAAI,C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,CAAC,KAAK,6BAA6B,CAAC,CAAC;gBAC1F,OAAO,IAAI,CAAC;YACd,CAAC;QACH,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,qCAAqC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,GAAG,EAAE,KAAK,CAAC,CAAC;YACzF,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IAED,SAAS;QACP,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;CACF"}
|
package/dist/core/vector.js
CHANGED
|
@@ -72,9 +72,9 @@ export class Vector {
|
|
|
72
72
|
}
|
|
73
73
|
async discoverRoutes() {
|
|
74
74
|
const routesDir = this.config.routesDir || './routes';
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
75
|
+
// Always create a new RouteScanner with the current config's routesDir
|
|
76
|
+
// to ensure we're using the correct path from the user's config
|
|
77
|
+
this.routeScanner = new RouteScanner(routesDir);
|
|
78
78
|
if (!this.routeGenerator) {
|
|
79
79
|
this.routeGenerator = new RouteGenerator();
|
|
80
80
|
}
|
package/dist/core/vector.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vector.js","sourceRoot":"","sources":["../../src/core/vector.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAChD,OAAO,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AACxD,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAC1D,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAU1C,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AACxC,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAExC,6CAA6C;AAC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AO,CAAC,GAAG,CAAC,qBAAqB,KAAK,CAAC,MAAM,IAAI,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC;QACjE,CAAC;IACH,CAAC;IAED,IAAI;QACF,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;YAChB,IAAI,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC;YACnB,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;QACrB,CAAC;QACD,+DAA+D;QAC/D,4CAA4C;QAC5C,IAAI,CAAC,MAAM,CAAC,WAAW,EAAE,CAAC;IAC5B,CAAC;IAED,SAAS;QACP,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;IAED,SAAS;QACP,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;IAED,eAAe;QACb,OAAO,IAAI,CAAC,YAAY,CAAC;IAC3B,CAAC;IAED,cAAc;QACZ,OAAO,IAAI,CAAC,WAAW,CAAC;IAC1B,CAAC;IAED,2CAA2C;IAC3C,MAAM,CAAC,aAAa;QAClB,MAAM,CAAC,QAAQ,GAAG,IAAW,CAAC;IAChC,CAAC;CACF;AAED,+BAA+B;AAC/B,MAAM,CAAC,MAAM,iBAAiB,GAAG,MAAM,CAAC,WAAW,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -18,4 +18,4 @@ export default routes;
|
|
|
18
18
|
${f.join(`,
|
|
19
19
|
`)}
|
|
20
20
|
]);
|
|
21
|
-
};`}}var v;var p=U(()=>{v=(()=>({}));Z()});class k{routesDir;constructor(i="./routes"){this.routesDir=x(process.cwd(),i)}async scan(){let i=[];if(!F.existsSync(this.routesDir))return console.log(` → Routes directory not found: ${this.routesDir}`),console.log(" → No routes will be auto-discovered"),[];try{if(console.log(` → Scanning routes from: ${this.routesDir}`),await this.scanDirectory(this.routesDir,i),i.length>0)console.log(` ✓ Found ${i.length} route${i.length===1?"":"s"}`)}catch(f){if(f.code==="ENOENT")return console.warn(` ✗ Routes directory not accessible: ${this.routesDir}`),[];throw f}return i}async scanDirectory(i,f,l=""){let a=await F.promises.readdir(i);for(let A of a){let E=z(i,A);if((await F.promises.stat(E)).isDirectory()){let _=l?`${l}/${A}`:A;await this.scanDirectory(E,f,_)}else if(A.endsWith(".ts")||A.endsWith(".js")){let _=G(this.routesDir,E).replace(/\.(ts|js)$/,"").split(K).join("/");try{let w=await import(process.platform==="win32"?`file:///${E.replace(/\\/g,"/")}`:E);if(w.default&&typeof w.default==="function")f.push({name:"default",path:E,method:"GET",options:{method:"GET",path:`/${_}`,expose:!0}});for(let[O,I]of Object.entries(w)){if(O==="default")continue;if(I&&typeof I==="object"&&"entry"in I&&"options"in I&&"handler"in I){let L=I;f.push({name:O,path:E,method:L.options.method,options:L.options})}else if(Array.isArray(I)&&I.length>=4){let[L,,,P]=I;f.push({name:O,path:E,method:L,options:{method:L,path:P,expose:!0}})}}}catch(N){console.error(`Failed to load route from ${E}:`,N)}}}}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)}}var F;var e=U(()=>{F=(()=>({}));Z()});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 a=await l(f);if(a instanceof Response)return a;f=a}return f}async executeFinally(i,f){let l=i;for(let a of this.finallyHandlers)l=await a(l,f);return l}clone(){let i=new B;return i.beforeHandlers=[...this.beforeHandlers],i.finallyHandlers=[...this.finallyHandlers],i}clear(){this.beforeHandlers=[],this.finallyHandlers=[]}}function ii(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 E=0,d=i.split("/").filter(Boolean);for(let _ of d)if(this.isStaticSegment(_))E+=1000;else if(this.isParamSegment(_))E+=10;else if(this.isWildcardSegment(_))E+=1;if(E+=i.length,this.isExactPath(i))E+=1e4;return E}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),a=this.extractPath(f),A=this.getRouteSpecificity(l);return this.getRouteSpecificity(a)-A})}extractPath(i){return i[3]||""}route(i,f){let l=this.wrapHandler(i,f),a=[i.method.toUpperCase(),this.createRouteRegex(i.path),[l],i.path];return this.routes.push(a),this.sortRoutes(),a}createRouteRegex(i){return RegExp(`^${i.replace(/\/+(\/|$)/g,"$1").replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`)}wrapHandler(i,f){return async(l)=>{let a=l;if(!a.context)a.context={};if(!a.query&&a.url){let A=new URL(a.url),E={};for(let[d,_]of A.searchParams)E[d]=E[d]?[].concat(E[d],_):_;a.query=E}if(i.metadata)a.metadata=i.metadata;l=a;try{if(i.expose===!1)return R.forbidden("Forbidden");let A=await this.middlewareManager.executeBefore(l);if(A instanceof Response)return A;if(l=A,i.auth)try{await this.authManager.authenticate(l)}catch(N){return R.unauthorized(N instanceof Error?N.message:"Authentication failed",i.responseContentType)}if(!i.rawRequest&&l.method!=="GET"&&l.method!=="HEAD")try{let N=l.headers.get("content-type");if(N?.includes("application/json"))l.content=await l.json();else if(N?.includes("application/x-www-form-urlencoded"))l.content=Object.fromEntries(await l.formData());else if(N?.includes("multipart/form-data"))l.content=await l.formData();else l.content=await l.text()}catch{l.content=null}let E,d=i.cache;if(d&&typeof d==="number"&&d>0){let N=this.cacheManager.generateKey(l,{authUser:l.authUser});E=await this.cacheManager.get(N,()=>f(l),d)}else if(d&&typeof d==="object"&&d.ttl){let N=d.key||this.cacheManager.generateKey(l,{authUser:l.authUser});E=await this.cacheManager.get(N,()=>f(l),d.ttl)}else E=await f(l);let _;if(i.rawResponse||E instanceof Response)_=E instanceof Response?E:new Response(E);else _=H(200,E,i.responseContentType);return _=await this.middlewareManager.executeFinally(_,l),_}catch(A){if(A instanceof Response)return A;return console.error("Route handler error:",A),R.internalServerError(A instanceof Error?A.message:String(A),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[a,A,E]of this.routes)if(i.method==="OPTIONS"||i.method===a){let d=l.match(A);if(d){let _=i;if(!_.context)_.context={};_.params=d.groups||{};for(let N of E){let w=await N(_);if(w)return w}}}return R.notFound("Route not found")}clearRoutes(){this.routes=[]}}var fi=U(()=>{Y()});class u{server=null;router;config;corsHandler;constructor(i,f){if(this.router=i,this.config=f,f.cors){let{preflight:l,corsify:a}=j(this.normalizeCorsOptions(f.cors));this.corsHandler={preflight:l,corsify:a}}}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(a)=>{try{if(this.corsHandler&&a.method==="OPTIONS")return this.corsHandler.preflight(a);let A=await this.router.handle(a);if(this.corsHandler)A=this.corsHandler.corsify(A,a);return A}catch(A){return console.error("Server error:",A),new Response("Internal Server Error",{status:500})}};return this.server=Bun.serve({port:i,hostname:f,reusePort:this.config.reusePort!==!1,fetch:l,error:(a)=>{return console.error("[ERROR] Server error:",a),new Response("Internal Server Error",{status:500})}}),console.log(`→ Vector server running at http://${f}:${i}`),this.server}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}`}}var li=U(()=>{V()});var ai={};r(ai,{getVectorInstance:()=>Pi,Vector:()=>h});class h{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 J,this.cacheManager=new W,this.router=new m(this.middlewareManager,this.authManager,this.cacheManager)}static getInstance(){if(!h.instance)h.instance=new h;return h.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(),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 u(this.router,this.config),await this.server.start()}async discoverRoutes(){let i=this.config.routesDir||"./routes";if(!this.routeScanner)this.routeScanner=new k(i);if(!this.routeGenerator)this.routeGenerator=new g;try{let f=await this.routeScanner.scan();if(f.length>0){if(this.config.development)await this.routeGenerator.generate(f);for(let l of f)try{let A=await import(ii(l.path)),E=l.name==="default"?A.default:A[l.name];if(E){if(this.isRouteDefinition(E)){let d=E;this.router.route(d.options,d.handler),this.logRouteLoaded(d.options)}else if(this.isRouteEntry(E))this.router.addRoute(E),this.logRouteLoaded(E);else if(typeof E==="function")this.router.route(l.options,E),this.logRouteLoaded(l.options)}}catch(a){console.error(`Failed to load route ${l.name} from ${l.path}:`,a)}this.router.sortRoutes(),console.log(`✅ Loaded ${f.length} routes from ${i}`)}}catch(f){if(f.code!=="ENOENT"&&f.code!=="ENOTDIR")console.error("Failed to discover routes:",f)}}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){if(Array.isArray(i))console.log(` ✓ Loaded route: ${i[0]} ${i[3]||i[1]}`);else console.log(` ✓ Loaded route: ${i.method} ${i.path}`)}stop(){if(this.server)this.server.stop(),this.server=null;this.router.clearRoutes()}getServer(){return this.server}getRouter(){return this.router}getCacheManager(){return this.cacheManager}getAuthManager(){return this.authManager}static resetInstance(){h.instance=null}}var Pi;var Ei=U(()=>{q();p();e();fi();li();Pi=h.getInstance});function Ai(i,f){let l=Si(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 hi(i){return JSON.stringify(i??null,(f,l)=>typeof l==="bigint"?l.toString():l)}function D(i,f,l){let a={error:!0,message:f,statusCode:i,timestamp:new Date().toISOString()};return H(i,a,l)}function H(i,f,l=M.JSON){let a=l===M.JSON?hi(f):f;return new Response(a,{status:i,headers:{"content-type":l}})}function Si(i,f){let{auth:l=!1,expose:a=!1,rawRequest:A=!1,rawResponse:E=!1,responseContentType:d=M.JSON}=i;return async(_)=>{if(!a)return R.forbidden("Forbidden");try{if(l)await bi(_,d);if(!A)await s(_);y(_);let N=await f(_);return E?N:Hi.success(N,d)}catch(N){if(N instanceof Response)return N;return R.internalServerError(String(N),d)}}}var Af,_f,Hi,R,bi=async(i,f)=>{let{getVectorInstance:l}=await Promise.resolve().then(() => (Ei(),ai)),A=l().getProtectedHandler();if(!A)throw R.unauthorized("Authentication not configured",f);try{let E=await A(i);i.authUser=E}catch(E){throw R.unauthorized(E instanceof Error?E.message:"Authentication failed",f)}};var Y=U(()=>{V();X();({preflight:Af,corsify:_f}=j({origin:"*",credentials:!0,allowHeaders:"Content-Type, Authorization",allowMethods:"GET, POST, PUT, PATCH, DELETE, OPTIONS",exposeHeaders:"Authorization",maxAge:86400}));Hi={success:(i,f)=>H($.OK,i,f),created:(i,f)=>H($.CREATED,i,f)};R={badRequest:(i="Bad Request",f)=>D($.BAD_REQUEST,i,f),unauthorized:(i="Unauthorized",f)=>D($.UNAUTHORIZED,i,f),paymentRequired:(i="Payment Required",f)=>D(402,i,f),forbidden:(i="Forbidden",f)=>D($.FORBIDDEN,i,f),notFound:(i="Not Found",f)=>D($.NOT_FOUND,i,f),methodNotAllowed:(i="Method Not Allowed",f)=>D(405,i,f),notAcceptable:(i="Not Acceptable",f)=>D(406,i,f),requestTimeout:(i="Request Timeout",f)=>D(408,i,f),conflict:(i="Conflict",f)=>D($.CONFLICT,i,f),gone:(i="Gone",f)=>D(410,i,f),lengthRequired:(i="Length Required",f)=>D(411,i,f),preconditionFailed:(i="Precondition Failed",f)=>D(412,i,f),payloadTooLarge:(i="Payload Too Large",f)=>D(413,i,f),uriTooLong:(i="URI Too Long",f)=>D(414,i,f),unsupportedMediaType:(i="Unsupported Media Type",f)=>D(415,i,f),rangeNotSatisfiable:(i="Range Not Satisfiable",f)=>D(416,i,f),expectationFailed:(i="Expectation Failed",f)=>D(417,i,f),imATeapot:(i="I'm a teapot",f)=>D(418,i,f),misdirectedRequest:(i="Misdirected Request",f)=>D(421,i,f),unprocessableEntity:(i="Unprocessable Entity",f)=>D($.UNPROCESSABLE_ENTITY,i,f),locked:(i="Locked",f)=>D(423,i,f),failedDependency:(i="Failed Dependency",f)=>D(424,i,f),tooEarly:(i="Too Early",f)=>D(425,i,f),upgradeRequired:(i="Upgrade Required",f)=>D(426,i,f),preconditionRequired:(i="Precondition Required",f)=>D(428,i,f),tooManyRequests:(i="Too Many Requests",f)=>D(429,i,f),requestHeaderFieldsTooLarge:(i="Request Header Fields Too Large",f)=>D(431,i,f),unavailableForLegalReasons:(i="Unavailable For Legal Reasons",f)=>D(451,i,f),internalServerError:(i="Internal Server Error",f)=>D($.INTERNAL_SERVER_ERROR,i,f),notImplemented:(i="Not Implemented",f)=>D(501,i,f),badGateway:(i="Bad Gateway",f)=>D(502,i,f),serviceUnavailable:(i="Service Unavailable",f)=>D(503,i,f),gatewayTimeout:(i="Gateway Timeout",f)=>D(504,i,f),httpVersionNotSupported:(i="HTTP Version Not Supported",f)=>D(505,i,f),variantAlsoNegotiates:(i="Variant Also Negotiates",f)=>D(506,i,f),insufficientStorage:(i="Insufficient Storage",f)=>D(507,i,f),loopDetected:(i="Loop Detected",f)=>D(508,i,f),notExtended:(i="Not Extended",f)=>D(510,i,f),networkAuthenticationRequired:(i="Network Authentication Required",f)=>D(511,i,f),invalidArgument:(i="Invalid Argument",f)=>D($.UNPROCESSABLE_ENTITY,i,f),rateLimitExceeded:(i="Rate Limit Exceeded",f)=>D(429,i,f),maintenance:(i="Service Under Maintenance",f)=>D(503,i,f),custom:(i,f,l)=>D(i,f,l)}});var xi={};r(xi,{route:()=>Ai,createResponse:()=>H,APIError:()=>R});module.exports=Ni(xi);Y();Y();
|
|
21
|
+
};`}}var v;var p=U(()=>{v=(()=>({}));Z()});class k{routesDir;constructor(i="./routes"){this.routesDir=x(process.cwd(),i)}async scan(){let i=[];if(!F.existsSync(this.routesDir))return console.log(` → Routes directory not found: ${this.routesDir}`),console.log(" → No routes will be auto-discovered"),[];try{if(console.log(` → Scanning routes from: ${this.routesDir}`),await this.scanDirectory(this.routesDir,i),i.length>0)console.log(` ✓ Found ${i.length} route${i.length===1?"":"s"}`)}catch(f){if(f.code==="ENOENT")return console.warn(` ✗ Routes directory not accessible: ${this.routesDir}`),[];throw f}return i}async scanDirectory(i,f,l=""){let a=await F.promises.readdir(i);for(let A of a){let E=z(i,A);if((await F.promises.stat(E)).isDirectory()){let _=l?`${l}/${A}`:A;await this.scanDirectory(E,f,_)}else if(A.endsWith(".ts")||A.endsWith(".js")){let _=G(this.routesDir,E).replace(/\.(ts|js)$/,"").split(K).join("/");try{let w=await import(process.platform==="win32"?`file:///${E.replace(/\\/g,"/")}`:E);if(w.default&&typeof w.default==="function")f.push({name:"default",path:E,method:"GET",options:{method:"GET",path:`/${_}`,expose:!0}});for(let[O,I]of Object.entries(w)){if(O==="default")continue;if(I&&typeof I==="object"&&"entry"in I&&"options"in I&&"handler"in I){let L=I;f.push({name:O,path:E,method:L.options.method,options:L.options})}else if(Array.isArray(I)&&I.length>=4){let[L,,,P]=I;f.push({name:O,path:E,method:L,options:{method:L,path:P,expose:!0}})}}}catch(N){console.error(`Failed to load route from ${E}:`,N)}}}}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)}}var F;var e=U(()=>{F=(()=>({}));Z()});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 a=await l(f);if(a instanceof Response)return a;f=a}return f}async executeFinally(i,f){let l=i;for(let a of this.finallyHandlers)l=await a(l,f);return l}clone(){let i=new B;return i.beforeHandlers=[...this.beforeHandlers],i.finallyHandlers=[...this.finallyHandlers],i}clear(){this.beforeHandlers=[],this.finallyHandlers=[]}}function ii(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 E=0,d=i.split("/").filter(Boolean);for(let _ of d)if(this.isStaticSegment(_))E+=1000;else if(this.isParamSegment(_))E+=10;else if(this.isWildcardSegment(_))E+=1;if(E+=i.length,this.isExactPath(i))E+=1e4;return E}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),a=this.extractPath(f),A=this.getRouteSpecificity(l);return this.getRouteSpecificity(a)-A})}extractPath(i){return i[3]||""}route(i,f){let l=this.wrapHandler(i,f),a=[i.method.toUpperCase(),this.createRouteRegex(i.path),[l],i.path];return this.routes.push(a),this.sortRoutes(),a}createRouteRegex(i){return RegExp(`^${i.replace(/\/+(\/|$)/g,"$1").replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`)}wrapHandler(i,f){return async(l)=>{let a=l;if(!a.context)a.context={};if(!a.query&&a.url){let A=new URL(a.url),E={};for(let[d,_]of A.searchParams)E[d]=E[d]?[].concat(E[d],_):_;a.query=E}if(i.metadata)a.metadata=i.metadata;l=a;try{if(i.expose===!1)return R.forbidden("Forbidden");let A=await this.middlewareManager.executeBefore(l);if(A instanceof Response)return A;if(l=A,i.auth)try{await this.authManager.authenticate(l)}catch(N){return R.unauthorized(N instanceof Error?N.message:"Authentication failed",i.responseContentType)}if(!i.rawRequest&&l.method!=="GET"&&l.method!=="HEAD")try{let N=l.headers.get("content-type");if(N?.includes("application/json"))l.content=await l.json();else if(N?.includes("application/x-www-form-urlencoded"))l.content=Object.fromEntries(await l.formData());else if(N?.includes("multipart/form-data"))l.content=await l.formData();else l.content=await l.text()}catch{l.content=null}let E,d=i.cache;if(d&&typeof d==="number"&&d>0){let N=this.cacheManager.generateKey(l,{authUser:l.authUser});E=await this.cacheManager.get(N,()=>f(l),d)}else if(d&&typeof d==="object"&&d.ttl){let N=d.key||this.cacheManager.generateKey(l,{authUser:l.authUser});E=await this.cacheManager.get(N,()=>f(l),d.ttl)}else E=await f(l);let _;if(i.rawResponse||E instanceof Response)_=E instanceof Response?E:new Response(E);else _=H(200,E,i.responseContentType);return _=await this.middlewareManager.executeFinally(_,l),_}catch(A){if(A instanceof Response)return A;return console.error("Route handler error:",A),R.internalServerError(A instanceof Error?A.message:String(A),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[a,A,E]of this.routes)if(i.method==="OPTIONS"||i.method===a){let d=l.match(A);if(d){let _=i;if(!_.context)_.context={};_.params=d.groups||{};for(let N of E){let w=await N(_);if(w)return w}}}return R.notFound("Route not found")}clearRoutes(){this.routes=[]}}var fi=U(()=>{Y()});class u{server=null;router;config;corsHandler;constructor(i,f){if(this.router=i,this.config=f,f.cors){let{preflight:l,corsify:a}=j(this.normalizeCorsOptions(f.cors));this.corsHandler={preflight:l,corsify:a}}}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(a)=>{try{if(this.corsHandler&&a.method==="OPTIONS")return this.corsHandler.preflight(a);let A=await this.router.handle(a);if(this.corsHandler)A=this.corsHandler.corsify(A,a);return A}catch(A){return console.error("Server error:",A),new Response("Internal Server Error",{status:500})}};return this.server=Bun.serve({port:i,hostname:f,reusePort:this.config.reusePort!==!1,fetch:l,error:(a)=>{return console.error("[ERROR] Server error:",a),new Response("Internal Server Error",{status:500})}}),console.log(`→ Vector server running at http://${f}:${i}`),this.server}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}`}}var li=U(()=>{V()});var ai={};r(ai,{getVectorInstance:()=>Pi,Vector:()=>h});class h{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 J,this.cacheManager=new W,this.router=new m(this.middlewareManager,this.authManager,this.cacheManager)}static getInstance(){if(!h.instance)h.instance=new h;return h.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(),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 u(this.router,this.config),await this.server.start()}async discoverRoutes(){let i=this.config.routesDir||"./routes";if(this.routeScanner=new k(i),!this.routeGenerator)this.routeGenerator=new g;try{let f=await this.routeScanner.scan();if(f.length>0){if(this.config.development)await this.routeGenerator.generate(f);for(let l of f)try{let A=await import(ii(l.path)),E=l.name==="default"?A.default:A[l.name];if(E){if(this.isRouteDefinition(E)){let d=E;this.router.route(d.options,d.handler),this.logRouteLoaded(d.options)}else if(this.isRouteEntry(E))this.router.addRoute(E),this.logRouteLoaded(E);else if(typeof E==="function")this.router.route(l.options,E),this.logRouteLoaded(l.options)}}catch(a){console.error(`Failed to load route ${l.name} from ${l.path}:`,a)}this.router.sortRoutes(),console.log(`✅ Loaded ${f.length} routes from ${i}`)}}catch(f){if(f.code!=="ENOENT"&&f.code!=="ENOTDIR")console.error("Failed to discover routes:",f)}}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){if(Array.isArray(i))console.log(` ✓ Loaded route: ${i[0]} ${i[3]||i[1]}`);else console.log(` ✓ Loaded route: ${i.method} ${i.path}`)}stop(){if(this.server)this.server.stop(),this.server=null;this.router.clearRoutes()}getServer(){return this.server}getRouter(){return this.router}getCacheManager(){return this.cacheManager}getAuthManager(){return this.authManager}static resetInstance(){h.instance=null}}var Pi;var Ei=U(()=>{q();p();e();fi();li();Pi=h.getInstance});function Ai(i,f){let l=Si(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 hi(i){return JSON.stringify(i??null,(f,l)=>typeof l==="bigint"?l.toString():l)}function D(i,f,l){let a={error:!0,message:f,statusCode:i,timestamp:new Date().toISOString()};return H(i,a,l)}function H(i,f,l=M.JSON){let a=l===M.JSON?hi(f):f;return new Response(a,{status:i,headers:{"content-type":l}})}function Si(i,f){let{auth:l=!1,expose:a=!1,rawRequest:A=!1,rawResponse:E=!1,responseContentType:d=M.JSON}=i;return async(_)=>{if(!a)return R.forbidden("Forbidden");try{if(l)await bi(_,d);if(!A)await s(_);y(_);let N=await f(_);return E?N:Hi.success(N,d)}catch(N){if(N instanceof Response)return N;return R.internalServerError(String(N),d)}}}var Af,_f,Hi,R,bi=async(i,f)=>{let{getVectorInstance:l}=await Promise.resolve().then(() => (Ei(),ai)),A=l().getProtectedHandler();if(!A)throw R.unauthorized("Authentication not configured",f);try{let E=await A(i);i.authUser=E}catch(E){throw R.unauthorized(E instanceof Error?E.message:"Authentication failed",f)}};var Y=U(()=>{V();X();({preflight:Af,corsify:_f}=j({origin:"*",credentials:!0,allowHeaders:"Content-Type, Authorization",allowMethods:"GET, POST, PUT, PATCH, DELETE, OPTIONS",exposeHeaders:"Authorization",maxAge:86400}));Hi={success:(i,f)=>H($.OK,i,f),created:(i,f)=>H($.CREATED,i,f)};R={badRequest:(i="Bad Request",f)=>D($.BAD_REQUEST,i,f),unauthorized:(i="Unauthorized",f)=>D($.UNAUTHORIZED,i,f),paymentRequired:(i="Payment Required",f)=>D(402,i,f),forbidden:(i="Forbidden",f)=>D($.FORBIDDEN,i,f),notFound:(i="Not Found",f)=>D($.NOT_FOUND,i,f),methodNotAllowed:(i="Method Not Allowed",f)=>D(405,i,f),notAcceptable:(i="Not Acceptable",f)=>D(406,i,f),requestTimeout:(i="Request Timeout",f)=>D(408,i,f),conflict:(i="Conflict",f)=>D($.CONFLICT,i,f),gone:(i="Gone",f)=>D(410,i,f),lengthRequired:(i="Length Required",f)=>D(411,i,f),preconditionFailed:(i="Precondition Failed",f)=>D(412,i,f),payloadTooLarge:(i="Payload Too Large",f)=>D(413,i,f),uriTooLong:(i="URI Too Long",f)=>D(414,i,f),unsupportedMediaType:(i="Unsupported Media Type",f)=>D(415,i,f),rangeNotSatisfiable:(i="Range Not Satisfiable",f)=>D(416,i,f),expectationFailed:(i="Expectation Failed",f)=>D(417,i,f),imATeapot:(i="I'm a teapot",f)=>D(418,i,f),misdirectedRequest:(i="Misdirected Request",f)=>D(421,i,f),unprocessableEntity:(i="Unprocessable Entity",f)=>D($.UNPROCESSABLE_ENTITY,i,f),locked:(i="Locked",f)=>D(423,i,f),failedDependency:(i="Failed Dependency",f)=>D(424,i,f),tooEarly:(i="Too Early",f)=>D(425,i,f),upgradeRequired:(i="Upgrade Required",f)=>D(426,i,f),preconditionRequired:(i="Precondition Required",f)=>D(428,i,f),tooManyRequests:(i="Too Many Requests",f)=>D(429,i,f),requestHeaderFieldsTooLarge:(i="Request Header Fields Too Large",f)=>D(431,i,f),unavailableForLegalReasons:(i="Unavailable For Legal Reasons",f)=>D(451,i,f),internalServerError:(i="Internal Server Error",f)=>D($.INTERNAL_SERVER_ERROR,i,f),notImplemented:(i="Not Implemented",f)=>D(501,i,f),badGateway:(i="Bad Gateway",f)=>D(502,i,f),serviceUnavailable:(i="Service Unavailable",f)=>D(503,i,f),gatewayTimeout:(i="Gateway Timeout",f)=>D(504,i,f),httpVersionNotSupported:(i="HTTP Version Not Supported",f)=>D(505,i,f),variantAlsoNegotiates:(i="Variant Also Negotiates",f)=>D(506,i,f),insufficientStorage:(i="Insufficient Storage",f)=>D(507,i,f),loopDetected:(i="Loop Detected",f)=>D(508,i,f),notExtended:(i="Not Extended",f)=>D(510,i,f),networkAuthenticationRequired:(i="Network Authentication Required",f)=>D(511,i,f),invalidArgument:(i="Invalid Argument",f)=>D($.UNPROCESSABLE_ENTITY,i,f),rateLimitExceeded:(i="Rate Limit Exceeded",f)=>D(429,i,f),maintenance:(i="Service Under Maintenance",f)=>D(503,i,f),custom:(i,f,l)=>D(i,f,l)}});var xi={};r(xi,{route:()=>Ai,createResponse:()=>H,APIError:()=>R});module.exports=Ni(xi);Y();Y();
|
package/dist/index.mjs
CHANGED
|
@@ -18,4 +18,4 @@ export default routes;
|
|
|
18
18
|
${f.join(`,
|
|
19
19
|
`)}
|
|
20
20
|
]);
|
|
21
|
-
};`}}var y=R(()=>{z()});var{existsSync:Ii,promises:q}=(()=>({}));class Z{routesDir;constructor(i="./routes"){this.routesDir=x(process.cwd(),i)}async scan(){let i=[];if(!Ii(this.routesDir))return console.log(` → Routes directory not found: ${this.routesDir}`),console.log(" → No routes will be auto-discovered"),[];try{if(console.log(` → Scanning routes from: ${this.routesDir}`),await this.scanDirectory(this.routesDir,i),i.length>0)console.log(` ✓ Found ${i.length} route${i.length===1?"":"s"}`)}catch(f){if(f.code==="ENOENT")return console.warn(` ✗ Routes directory not accessible: ${this.routesDir}`),[];throw f}return i}async scanDirectory(i,f,l=""){let E=await q.readdir(i);for(let A of E){let a=J(i,A);if((await q.stat(a)).isDirectory()){let _=l?`${l}/${A}`:A;await this.scanDirectory(a,f,_)}else if(A.endsWith(".ts")||A.endsWith(".js")){let _=G(this.routesDir,a).replace(/\.(ts|js)$/,"").split(W).join("/");try{let w=await import(process.platform==="win32"?`file:///${a.replace(/\\/g,"/")}`:a);if(w.default&&typeof w.default==="function")f.push({name:"default",path:a,method:"GET",options:{method:"GET",path:`/${_}`,expose:!0}});for(let[O,I]of Object.entries(w)){if(O==="default")continue;if(I&&typeof I==="object"&&"entry"in I&&"options"in I&&"handler"in I){let L=I;f.push({name:O,path:a,method:L.options.method,options:L.options})}else if(Array.isArray(I)&&I.length>=4){let[L,,,P]=I;f.push({name:O,path:a,method:L,options:{method:L,path:P,expose:!0}})}}}catch(N){console.error(`Failed to load route from ${a}:`,N)}}}}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)}}var t=R(()=>{z()});class T{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)l=await E(l,f);return l}clone(){let i=new T;return i.beforeHandlers=[...this.beforeHandlers],i.finallyHandlers=[...this.finallyHandlers],i}clear(){this.beforeHandlers=[],this.finallyHandlers=[]}}function o(i){return process.platform==="win32"?`file:///${i.replace(/\\/g,"/")}`:i}class v{middlewareManager;authManager;cacheManager;routes=[];constructor(i,f,l){this.middlewareManager=i,this.authManager=f,this.cacheManager=l}getRouteSpecificity(i){let a=0,d=i.split("/").filter(Boolean);for(let _ of d)if(this.isStaticSegment(_))a+=1000;else if(this.isParamSegment(_))a+=10;else if(this.isWildcardSegment(_))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),A=this.getRouteSpecificity(l);return this.getRouteSpecificity(E)-A})}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.*)?")}/*$`)}wrapHandler(i,f){return async(l)=>{let E=l;if(!E.context)E.context={};if(!E.query&&E.url){let A=new URL(E.url),a={};for(let[d,_]of A.searchParams)a[d]=a[d]?[].concat(a[d],_):_;E.query=a}if(i.metadata)E.metadata=i.metadata;l=E;try{if(i.expose===!1)return C.forbidden("Forbidden");let A=await this.middlewareManager.executeBefore(l);if(A instanceof Response)return A;if(l=A,i.auth)try{await this.authManager.authenticate(l)}catch(N){return C.unauthorized(N instanceof Error?N.message:"Authentication failed",i.responseContentType)}if(!i.rawRequest&&l.method!=="GET"&&l.method!=="HEAD")try{let N=l.headers.get("content-type");if(N?.includes("application/json"))l.content=await l.json();else if(N?.includes("application/x-www-form-urlencoded"))l.content=Object.fromEntries(await l.formData());else if(N?.includes("multipart/form-data"))l.content=await l.formData();else l.content=await l.text()}catch{l.content=null}let a,d=i.cache;if(d&&typeof d==="number"&&d>0){let N=this.cacheManager.generateKey(l,{authUser:l.authUser});a=await this.cacheManager.get(N,()=>f(l),d)}else if(d&&typeof d==="object"&&d.ttl){let N=d.key||this.cacheManager.generateKey(l,{authUser:l.authUser});a=await this.cacheManager.get(N,()=>f(l),d.ttl)}else a=await f(l);let _;if(i.rawResponse||a instanceof Response)_=a instanceof Response?a:new Response(a);else _=b(200,a,i.responseContentType);return _=await this.middlewareManager.executeFinally(_,l),_}catch(A){if(A instanceof Response)return A;return console.error("Route handler error:",A),C.internalServerError(A instanceof Error?A.message:String(A),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,a]of this.routes)if(i.method==="OPTIONS"||i.method===E){let d=l.match(A);if(d){let _=i;if(!_.context)_.context={};_.params=d.groups||{};for(let N of a){let w=await N(_);if(w)return w}}}return C.notFound("Route not found")}clearRoutes(){this.routes=[]}}var p=R(()=>{B()});class g{server=null;router;config;corsHandler;constructor(i,f){if(this.router=i,this.config=f,f.cors){let{preflight:l,corsify:E}=F(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 A=await this.router.handle(E);if(this.corsHandler)A=this.corsHandler.corsify(A,E);return A}catch(A){return console.error("Server error:",A),new Response("Internal Server Error",{status:500})}};return this.server=Bun.serve({port:i,hostname:f,reusePort:this.config.reusePort!==!1,fetch:l,error:(E)=>{return console.error("[ERROR] Server error:",E),new Response("Internal Server Error",{status:500})}}),console.log(`→ Vector server running at http://${f}:${i}`),this.server}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}`}}var e=R(()=>{Y()});var ii={};ai(ii,{getVectorInstance:()=>Li,Vector:()=>h});class h{static instance;router;server=null;middlewareManager;authManager;cacheManager;config={};routeScanner=null;routeGenerator=null;_protectedHandler=null;_cacheHandler=null;constructor(){this.middlewareManager=new T,this.authManager=new c,this.cacheManager=new X,this.router=new v(this.middlewareManager,this.authManager,this.cacheManager)}static getInstance(){if(!h.instance)h.instance=new h;return h.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(),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 g(this.router,this.config),await this.server.start()}async discoverRoutes(){let i=this.config.routesDir||"./routes";if(!this.routeScanner)this.routeScanner=new Z(i);if(!this.routeGenerator)this.routeGenerator=new K;try{let f=await this.routeScanner.scan();if(f.length>0){if(this.config.development)await this.routeGenerator.generate(f);for(let l of f)try{let A=await import(o(l.path)),a=l.name==="default"?A.default:A[l.name];if(a){if(this.isRouteDefinition(a)){let d=a;this.router.route(d.options,d.handler),this.logRouteLoaded(d.options)}else if(this.isRouteEntry(a))this.router.addRoute(a),this.logRouteLoaded(a);else if(typeof a==="function")this.router.route(l.options,a),this.logRouteLoaded(l.options)}}catch(E){console.error(`Failed to load route ${l.name} from ${l.path}:`,E)}this.router.sortRoutes(),console.log(`✅ Loaded ${f.length} routes from ${i}`)}}catch(f){if(f.code!=="ENOENT"&&f.code!=="ENOTDIR")console.error("Failed to discover routes:",f)}}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){if(Array.isArray(i))console.log(` ✓ Loaded route: ${i[0]} ${i[3]||i[1]}`);else console.log(` ✓ Loaded route: ${i.method} ${i.path}`)}stop(){if(this.server)this.server.stop(),this.server=null;this.router.clearRoutes()}getServer(){return this.server}getRouter(){return this.router}getCacheManager(){return this.cacheManager}getAuthManager(){return this.authManager}static resetInstance(){h.instance=null}}var Li;var fi=R(()=>{u();y();t();p();e();Li=h.getInstance});function $i(i,f){let l=Pi(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 Ri(i){return JSON.stringify(i??null,(f,l)=>typeof l==="bigint"?l.toString():l)}function D(i,f,l){let E={error:!0,message:f,statusCode:i,timestamp:new Date().toISOString()};return b(i,E,l)}function b(i,f,l=j.JSON){let E=l===j.JSON?Ri(f):f;return new Response(E,{status:i,headers:{"content-type":l}})}function Pi(i,f){let{auth:l=!1,expose:E=!1,rawRequest:A=!1,rawResponse:a=!1,responseContentType:d=j.JSON}=i;return async(_)=>{if(!E)return C.forbidden("Forbidden");try{if(l)await Ci(_,d);if(!A)await k(_);m(_);let N=await f(_);return a?N:Ui.success(N,d)}catch(N){if(N instanceof Response)return N;return C.internalServerError(String(N),d)}}}var lf,af,Ui,C,Ci=async(i,f)=>{let{getVectorInstance:l}=await Promise.resolve().then(() => (fi(),ii)),A=l().getProtectedHandler();if(!A)throw C.unauthorized("Authentication not configured",f);try{let a=await A(i);i.authUser=a}catch(a){throw C.unauthorized(a instanceof Error?a.message:"Authentication failed",f)}};var B=R(()=>{Y();V();({preflight:lf,corsify:af}=F({origin:"*",credentials:!0,allowHeaders:"Content-Type, Authorization",allowMethods:"GET, POST, PUT, PATCH, DELETE, OPTIONS",exposeHeaders:"Authorization",maxAge:86400}));Ui={success:(i,f)=>b($.OK,i,f),created:(i,f)=>b($.CREATED,i,f)};C={badRequest:(i="Bad Request",f)=>D($.BAD_REQUEST,i,f),unauthorized:(i="Unauthorized",f)=>D($.UNAUTHORIZED,i,f),paymentRequired:(i="Payment Required",f)=>D(402,i,f),forbidden:(i="Forbidden",f)=>D($.FORBIDDEN,i,f),notFound:(i="Not Found",f)=>D($.NOT_FOUND,i,f),methodNotAllowed:(i="Method Not Allowed",f)=>D(405,i,f),notAcceptable:(i="Not Acceptable",f)=>D(406,i,f),requestTimeout:(i="Request Timeout",f)=>D(408,i,f),conflict:(i="Conflict",f)=>D($.CONFLICT,i,f),gone:(i="Gone",f)=>D(410,i,f),lengthRequired:(i="Length Required",f)=>D(411,i,f),preconditionFailed:(i="Precondition Failed",f)=>D(412,i,f),payloadTooLarge:(i="Payload Too Large",f)=>D(413,i,f),uriTooLong:(i="URI Too Long",f)=>D(414,i,f),unsupportedMediaType:(i="Unsupported Media Type",f)=>D(415,i,f),rangeNotSatisfiable:(i="Range Not Satisfiable",f)=>D(416,i,f),expectationFailed:(i="Expectation Failed",f)=>D(417,i,f),imATeapot:(i="I'm a teapot",f)=>D(418,i,f),misdirectedRequest:(i="Misdirected Request",f)=>D(421,i,f),unprocessableEntity:(i="Unprocessable Entity",f)=>D($.UNPROCESSABLE_ENTITY,i,f),locked:(i="Locked",f)=>D(423,i,f),failedDependency:(i="Failed Dependency",f)=>D(424,i,f),tooEarly:(i="Too Early",f)=>D(425,i,f),upgradeRequired:(i="Upgrade Required",f)=>D(426,i,f),preconditionRequired:(i="Precondition Required",f)=>D(428,i,f),tooManyRequests:(i="Too Many Requests",f)=>D(429,i,f),requestHeaderFieldsTooLarge:(i="Request Header Fields Too Large",f)=>D(431,i,f),unavailableForLegalReasons:(i="Unavailable For Legal Reasons",f)=>D(451,i,f),internalServerError:(i="Internal Server Error",f)=>D($.INTERNAL_SERVER_ERROR,i,f),notImplemented:(i="Not Implemented",f)=>D(501,i,f),badGateway:(i="Bad Gateway",f)=>D(502,i,f),serviceUnavailable:(i="Service Unavailable",f)=>D(503,i,f),gatewayTimeout:(i="Gateway Timeout",f)=>D(504,i,f),httpVersionNotSupported:(i="HTTP Version Not Supported",f)=>D(505,i,f),variantAlsoNegotiates:(i="Variant Also Negotiates",f)=>D(506,i,f),insufficientStorage:(i="Insufficient Storage",f)=>D(507,i,f),loopDetected:(i="Loop Detected",f)=>D(508,i,f),notExtended:(i="Not Extended",f)=>D(510,i,f),networkAuthenticationRequired:(i="Network Authentication Required",f)=>D(511,i,f),invalidArgument:(i="Invalid Argument",f)=>D($.UNPROCESSABLE_ENTITY,i,f),rateLimitExceeded:(i="Rate Limit Exceeded",f)=>D(429,i,f),maintenance:(i="Service Under Maintenance",f)=>D(503,i,f),custom:(i,f,l)=>D(i,f,l)}});B();B();export{$i as route,b as createResponse,C as APIError};
|
|
21
|
+
};`}}var y=R(()=>{z()});var{existsSync:Ii,promises:q}=(()=>({}));class Z{routesDir;constructor(i="./routes"){this.routesDir=x(process.cwd(),i)}async scan(){let i=[];if(!Ii(this.routesDir))return console.log(` → Routes directory not found: ${this.routesDir}`),console.log(" → No routes will be auto-discovered"),[];try{if(console.log(` → Scanning routes from: ${this.routesDir}`),await this.scanDirectory(this.routesDir,i),i.length>0)console.log(` ✓ Found ${i.length} route${i.length===1?"":"s"}`)}catch(f){if(f.code==="ENOENT")return console.warn(` ✗ Routes directory not accessible: ${this.routesDir}`),[];throw f}return i}async scanDirectory(i,f,l=""){let E=await q.readdir(i);for(let A of E){let a=J(i,A);if((await q.stat(a)).isDirectory()){let _=l?`${l}/${A}`:A;await this.scanDirectory(a,f,_)}else if(A.endsWith(".ts")||A.endsWith(".js")){let _=G(this.routesDir,a).replace(/\.(ts|js)$/,"").split(W).join("/");try{let w=await import(process.platform==="win32"?`file:///${a.replace(/\\/g,"/")}`:a);if(w.default&&typeof w.default==="function")f.push({name:"default",path:a,method:"GET",options:{method:"GET",path:`/${_}`,expose:!0}});for(let[O,I]of Object.entries(w)){if(O==="default")continue;if(I&&typeof I==="object"&&"entry"in I&&"options"in I&&"handler"in I){let L=I;f.push({name:O,path:a,method:L.options.method,options:L.options})}else if(Array.isArray(I)&&I.length>=4){let[L,,,P]=I;f.push({name:O,path:a,method:L,options:{method:L,path:P,expose:!0}})}}}catch(N){console.error(`Failed to load route from ${a}:`,N)}}}}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)}}var t=R(()=>{z()});class T{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)l=await E(l,f);return l}clone(){let i=new T;return i.beforeHandlers=[...this.beforeHandlers],i.finallyHandlers=[...this.finallyHandlers],i}clear(){this.beforeHandlers=[],this.finallyHandlers=[]}}function o(i){return process.platform==="win32"?`file:///${i.replace(/\\/g,"/")}`:i}class v{middlewareManager;authManager;cacheManager;routes=[];constructor(i,f,l){this.middlewareManager=i,this.authManager=f,this.cacheManager=l}getRouteSpecificity(i){let a=0,d=i.split("/").filter(Boolean);for(let _ of d)if(this.isStaticSegment(_))a+=1000;else if(this.isParamSegment(_))a+=10;else if(this.isWildcardSegment(_))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),A=this.getRouteSpecificity(l);return this.getRouteSpecificity(E)-A})}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.*)?")}/*$`)}wrapHandler(i,f){return async(l)=>{let E=l;if(!E.context)E.context={};if(!E.query&&E.url){let A=new URL(E.url),a={};for(let[d,_]of A.searchParams)a[d]=a[d]?[].concat(a[d],_):_;E.query=a}if(i.metadata)E.metadata=i.metadata;l=E;try{if(i.expose===!1)return C.forbidden("Forbidden");let A=await this.middlewareManager.executeBefore(l);if(A instanceof Response)return A;if(l=A,i.auth)try{await this.authManager.authenticate(l)}catch(N){return C.unauthorized(N instanceof Error?N.message:"Authentication failed",i.responseContentType)}if(!i.rawRequest&&l.method!=="GET"&&l.method!=="HEAD")try{let N=l.headers.get("content-type");if(N?.includes("application/json"))l.content=await l.json();else if(N?.includes("application/x-www-form-urlencoded"))l.content=Object.fromEntries(await l.formData());else if(N?.includes("multipart/form-data"))l.content=await l.formData();else l.content=await l.text()}catch{l.content=null}let a,d=i.cache;if(d&&typeof d==="number"&&d>0){let N=this.cacheManager.generateKey(l,{authUser:l.authUser});a=await this.cacheManager.get(N,()=>f(l),d)}else if(d&&typeof d==="object"&&d.ttl){let N=d.key||this.cacheManager.generateKey(l,{authUser:l.authUser});a=await this.cacheManager.get(N,()=>f(l),d.ttl)}else a=await f(l);let _;if(i.rawResponse||a instanceof Response)_=a instanceof Response?a:new Response(a);else _=b(200,a,i.responseContentType);return _=await this.middlewareManager.executeFinally(_,l),_}catch(A){if(A instanceof Response)return A;return console.error("Route handler error:",A),C.internalServerError(A instanceof Error?A.message:String(A),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,a]of this.routes)if(i.method==="OPTIONS"||i.method===E){let d=l.match(A);if(d){let _=i;if(!_.context)_.context={};_.params=d.groups||{};for(let N of a){let w=await N(_);if(w)return w}}}return C.notFound("Route not found")}clearRoutes(){this.routes=[]}}var p=R(()=>{B()});class g{server=null;router;config;corsHandler;constructor(i,f){if(this.router=i,this.config=f,f.cors){let{preflight:l,corsify:E}=F(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 A=await this.router.handle(E);if(this.corsHandler)A=this.corsHandler.corsify(A,E);return A}catch(A){return console.error("Server error:",A),new Response("Internal Server Error",{status:500})}};return this.server=Bun.serve({port:i,hostname:f,reusePort:this.config.reusePort!==!1,fetch:l,error:(E)=>{return console.error("[ERROR] Server error:",E),new Response("Internal Server Error",{status:500})}}),console.log(`→ Vector server running at http://${f}:${i}`),this.server}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}`}}var e=R(()=>{Y()});var ii={};ai(ii,{getVectorInstance:()=>Li,Vector:()=>h});class h{static instance;router;server=null;middlewareManager;authManager;cacheManager;config={};routeScanner=null;routeGenerator=null;_protectedHandler=null;_cacheHandler=null;constructor(){this.middlewareManager=new T,this.authManager=new c,this.cacheManager=new X,this.router=new v(this.middlewareManager,this.authManager,this.cacheManager)}static getInstance(){if(!h.instance)h.instance=new h;return h.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(),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 g(this.router,this.config),await this.server.start()}async discoverRoutes(){let i=this.config.routesDir||"./routes";if(this.routeScanner=new Z(i),!this.routeGenerator)this.routeGenerator=new K;try{let f=await this.routeScanner.scan();if(f.length>0){if(this.config.development)await this.routeGenerator.generate(f);for(let l of f)try{let A=await import(o(l.path)),a=l.name==="default"?A.default:A[l.name];if(a){if(this.isRouteDefinition(a)){let d=a;this.router.route(d.options,d.handler),this.logRouteLoaded(d.options)}else if(this.isRouteEntry(a))this.router.addRoute(a),this.logRouteLoaded(a);else if(typeof a==="function")this.router.route(l.options,a),this.logRouteLoaded(l.options)}}catch(E){console.error(`Failed to load route ${l.name} from ${l.path}:`,E)}this.router.sortRoutes(),console.log(`✅ Loaded ${f.length} routes from ${i}`)}}catch(f){if(f.code!=="ENOENT"&&f.code!=="ENOTDIR")console.error("Failed to discover routes:",f)}}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){if(Array.isArray(i))console.log(` ✓ Loaded route: ${i[0]} ${i[3]||i[1]}`);else console.log(` ✓ Loaded route: ${i.method} ${i.path}`)}stop(){if(this.server)this.server.stop(),this.server=null;this.router.clearRoutes()}getServer(){return this.server}getRouter(){return this.router}getCacheManager(){return this.cacheManager}getAuthManager(){return this.authManager}static resetInstance(){h.instance=null}}var Li;var fi=R(()=>{u();y();t();p();e();Li=h.getInstance});function $i(i,f){let l=Pi(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 Ri(i){return JSON.stringify(i??null,(f,l)=>typeof l==="bigint"?l.toString():l)}function D(i,f,l){let E={error:!0,message:f,statusCode:i,timestamp:new Date().toISOString()};return b(i,E,l)}function b(i,f,l=j.JSON){let E=l===j.JSON?Ri(f):f;return new Response(E,{status:i,headers:{"content-type":l}})}function Pi(i,f){let{auth:l=!1,expose:E=!1,rawRequest:A=!1,rawResponse:a=!1,responseContentType:d=j.JSON}=i;return async(_)=>{if(!E)return C.forbidden("Forbidden");try{if(l)await Ci(_,d);if(!A)await k(_);m(_);let N=await f(_);return a?N:Ui.success(N,d)}catch(N){if(N instanceof Response)return N;return C.internalServerError(String(N),d)}}}var lf,af,Ui,C,Ci=async(i,f)=>{let{getVectorInstance:l}=await Promise.resolve().then(() => (fi(),ii)),A=l().getProtectedHandler();if(!A)throw C.unauthorized("Authentication not configured",f);try{let a=await A(i);i.authUser=a}catch(a){throw C.unauthorized(a instanceof Error?a.message:"Authentication failed",f)}};var B=R(()=>{Y();V();({preflight:lf,corsify:af}=F({origin:"*",credentials:!0,allowHeaders:"Content-Type, Authorization",allowMethods:"GET, POST, PUT, PATCH, DELETE, OPTIONS",exposeHeaders:"Authorization",maxAge:86400}));Ui={success:(i,f)=>b($.OK,i,f),created:(i,f)=>b($.CREATED,i,f)};C={badRequest:(i="Bad Request",f)=>D($.BAD_REQUEST,i,f),unauthorized:(i="Unauthorized",f)=>D($.UNAUTHORIZED,i,f),paymentRequired:(i="Payment Required",f)=>D(402,i,f),forbidden:(i="Forbidden",f)=>D($.FORBIDDEN,i,f),notFound:(i="Not Found",f)=>D($.NOT_FOUND,i,f),methodNotAllowed:(i="Method Not Allowed",f)=>D(405,i,f),notAcceptable:(i="Not Acceptable",f)=>D(406,i,f),requestTimeout:(i="Request Timeout",f)=>D(408,i,f),conflict:(i="Conflict",f)=>D($.CONFLICT,i,f),gone:(i="Gone",f)=>D(410,i,f),lengthRequired:(i="Length Required",f)=>D(411,i,f),preconditionFailed:(i="Precondition Failed",f)=>D(412,i,f),payloadTooLarge:(i="Payload Too Large",f)=>D(413,i,f),uriTooLong:(i="URI Too Long",f)=>D(414,i,f),unsupportedMediaType:(i="Unsupported Media Type",f)=>D(415,i,f),rangeNotSatisfiable:(i="Range Not Satisfiable",f)=>D(416,i,f),expectationFailed:(i="Expectation Failed",f)=>D(417,i,f),imATeapot:(i="I'm a teapot",f)=>D(418,i,f),misdirectedRequest:(i="Misdirected Request",f)=>D(421,i,f),unprocessableEntity:(i="Unprocessable Entity",f)=>D($.UNPROCESSABLE_ENTITY,i,f),locked:(i="Locked",f)=>D(423,i,f),failedDependency:(i="Failed Dependency",f)=>D(424,i,f),tooEarly:(i="Too Early",f)=>D(425,i,f),upgradeRequired:(i="Upgrade Required",f)=>D(426,i,f),preconditionRequired:(i="Precondition Required",f)=>D(428,i,f),tooManyRequests:(i="Too Many Requests",f)=>D(429,i,f),requestHeaderFieldsTooLarge:(i="Request Header Fields Too Large",f)=>D(431,i,f),unavailableForLegalReasons:(i="Unavailable For Legal Reasons",f)=>D(451,i,f),internalServerError:(i="Internal Server Error",f)=>D($.INTERNAL_SERVER_ERROR,i,f),notImplemented:(i="Not Implemented",f)=>D(501,i,f),badGateway:(i="Bad Gateway",f)=>D(502,i,f),serviceUnavailable:(i="Service Unavailable",f)=>D(503,i,f),gatewayTimeout:(i="Gateway Timeout",f)=>D(504,i,f),httpVersionNotSupported:(i="HTTP Version Not Supported",f)=>D(505,i,f),variantAlsoNegotiates:(i="Variant Also Negotiates",f)=>D(506,i,f),insufficientStorage:(i="Insufficient Storage",f)=>D(507,i,f),loopDetected:(i="Loop Detected",f)=>D(508,i,f),notExtended:(i="Not Extended",f)=>D(510,i,f),networkAuthenticationRequired:(i="Network Authentication Required",f)=>D(511,i,f),invalidArgument:(i="Invalid Argument",f)=>D($.UNPROCESSABLE_ENTITY,i,f),rateLimitExceeded:(i="Rate Limit Exceeded",f)=>D(429,i,f),maintenance:(i="Service Under Maintenance",f)=>D(503,i,f),custom:(i,f,l)=>D(i,f,l)}});B();B();export{$i as route,b as createResponse,C as APIError};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "vector-framework",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.3",
|
|
4
4
|
"author": "",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -81,7 +81,7 @@
|
|
|
81
81
|
"build:clean": "rm -rf dist",
|
|
82
82
|
"build:ts": "tsc",
|
|
83
83
|
"build:bundle": "bun build src/index.ts --format esm --minify --outfile dist/index.mjs && bun build src/index.ts --format cjs --minify --outfile dist/index.js",
|
|
84
|
-
"build:cli": "bun build src/cli/index.ts --target
|
|
84
|
+
"build:cli": "bun build src/cli/index.ts --target bun --outfile dist/cli.js",
|
|
85
85
|
"test": "bun test tests/api-error.test.ts tests/cache.test.ts tests/middleware.test.ts tests/middleware-integration.test.ts tests/router.test.ts",
|
|
86
86
|
"test:unit": "bun test tests/*.test.ts",
|
|
87
87
|
"test:watch": "bun test --watch tests/*.test.ts",
|
package/src/cli/index.ts
CHANGED
|
@@ -5,8 +5,11 @@ import { parseArgs } from "node:util";
|
|
|
5
5
|
import { getVectorInstance } from "../core/vector";
|
|
6
6
|
import { ConfigLoader } from "../core/config-loader";
|
|
7
7
|
|
|
8
|
+
// Compatibility layer for both Node and Bun
|
|
9
|
+
const args = typeof Bun !== 'undefined' ? Bun.argv.slice(2) : process.argv.slice(2);
|
|
10
|
+
|
|
8
11
|
const { values, positionals } = parseArgs({
|
|
9
|
-
args
|
|
12
|
+
args,
|
|
10
13
|
options: {
|
|
11
14
|
port: {
|
|
12
15
|
type: "string",
|
|
@@ -56,9 +59,10 @@ async function runDev() {
|
|
|
56
59
|
const configSource = configLoader.getConfigSource();
|
|
57
60
|
|
|
58
61
|
// Merge CLI options with loaded config
|
|
59
|
-
|
|
60
|
-
config.
|
|
61
|
-
config.
|
|
62
|
+
// Only use CLI values if config doesn't have them
|
|
63
|
+
config.port = config.port ?? Number.parseInt(values.port as string);
|
|
64
|
+
config.hostname = config.hostname ?? (values.host as string);
|
|
65
|
+
config.routesDir = config.routesDir ?? (values.routes as string);
|
|
62
66
|
config.development = isDev;
|
|
63
67
|
config.autoDiscover = true;
|
|
64
68
|
|
|
@@ -195,15 +199,25 @@ async function runBuild() {
|
|
|
195
199
|
|
|
196
200
|
console.log(` Generated ${routes.length} routes`);
|
|
197
201
|
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
202
|
+
// Use spawn based on runtime
|
|
203
|
+
if (typeof Bun !== 'undefined') {
|
|
204
|
+
const buildProcess = Bun.spawn([
|
|
205
|
+
"bun",
|
|
206
|
+
"build",
|
|
207
|
+
"src/index.ts",
|
|
208
|
+
"--outdir",
|
|
209
|
+
"dist",
|
|
210
|
+
"--minify",
|
|
211
|
+
]);
|
|
212
|
+
await buildProcess.exited;
|
|
213
|
+
} else {
|
|
214
|
+
// For Node.js, use child_process
|
|
215
|
+
const { spawnSync } = await import('child_process');
|
|
216
|
+
spawnSync('bun', ['build', 'src/index.ts', '--outdir', 'dist', '--minify'], {
|
|
217
|
+
stdio: 'inherit',
|
|
218
|
+
shell: true
|
|
219
|
+
});
|
|
220
|
+
}
|
|
207
221
|
|
|
208
222
|
console.log("\n ✓ Build complete\n");
|
|
209
223
|
} catch (error) {
|
|
@@ -67,10 +67,15 @@ export class ConfigLoader<TTypes extends VectorTypes = DefaultVectorTypes> {
|
|
|
67
67
|
config.development = this.config.server.development;
|
|
68
68
|
}
|
|
69
69
|
|
|
70
|
-
// Routes configuration
|
|
70
|
+
// Routes configuration - support both new and legacy formats
|
|
71
71
|
if (this.config?.routes) {
|
|
72
|
+
// New format: { routes: { dir: string } }
|
|
72
73
|
config.routesDir = this.config.routes.dir || './routes';
|
|
73
74
|
config.autoDiscover = this.config.routes.autoDiscover !== false;
|
|
75
|
+
} else if ((this.config as any)?.routesDir) {
|
|
76
|
+
// Legacy format: { routesDir: string }
|
|
77
|
+
config.routesDir = (this.config as any).routesDir;
|
|
78
|
+
config.autoDiscover = (this.config as any).autoDiscover !== false;
|
|
74
79
|
} else {
|
|
75
80
|
config.routesDir = './routes';
|
|
76
81
|
config.autoDiscover = true;
|
package/src/core/vector.ts
CHANGED
|
@@ -104,9 +104,9 @@ export class Vector<TTypes extends VectorTypes = DefaultVectorTypes> {
|
|
|
104
104
|
private async discoverRoutes() {
|
|
105
105
|
const routesDir = this.config.routesDir || './routes';
|
|
106
106
|
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
107
|
+
// Always create a new RouteScanner with the current config's routesDir
|
|
108
|
+
// to ensure we're using the correct path from the user's config
|
|
109
|
+
this.routeScanner = new RouteScanner(routesDir);
|
|
110
110
|
|
|
111
111
|
if (!this.routeGenerator) {
|
|
112
112
|
this.routeGenerator = new RouteGenerator();
|