burger-api 0.9.7 → 1.0.0-beta.1
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/README.md +84 -241
- package/dist/src/adapter/bun/index.d.ts +14 -0
- package/dist/src/adapter/bun/index.js +73 -0
- package/dist/src/adapter/bun/types.d.ts +15 -0
- package/dist/src/adapter/bun/types.js +1 -0
- package/dist/src/adapter/index.d.ts +1 -0
- package/dist/src/adapter/index.js +1 -0
- package/dist/src/adapter/types.d.ts +49 -0
- package/dist/src/adapter/types.js +1 -0
- package/dist/src/adapter/web-standard/fetch-handler.d.ts +39 -0
- package/dist/src/adapter/web-standard/fetch-handler.js +54 -0
- package/dist/src/adapter/web-standard/index.d.ts +8 -0
- package/dist/src/adapter/web-standard/index.js +7 -0
- package/dist/src/analysis/route-access-analyzer.d.ts +10 -0
- package/dist/src/analysis/route-access-analyzer.js +287 -0
- package/dist/src/chain/chain.d.ts +16 -0
- package/dist/src/chain/chain.js +17 -0
- package/dist/src/chain/flattener.d.ts +3 -0
- package/dist/src/chain/flattener.js +78 -0
- package/dist/src/chain/node.d.ts +25 -0
- package/dist/src/chain/node.js +1 -0
- package/dist/src/compiler/conventions.d.ts +67 -0
- package/dist/src/compiler/conventions.js +129 -0
- package/dist/src/compiler/index.d.ts +13 -0
- package/dist/src/compiler/index.js +11 -0
- package/dist/src/compiler/module-loader.d.ts +75 -0
- package/dist/src/compiler/module-loader.js +276 -0
- package/dist/src/compiler/route-module.d.ts +97 -0
- package/dist/src/compiler/route-module.js +1 -0
- package/dist/src/compiler/route-tree.d.ts +19 -0
- package/dist/src/compiler/route-tree.js +28 -0
- package/dist/src/compiler/scanner.d.ts +42 -0
- package/dist/src/compiler/scanner.js +240 -0
- package/dist/src/context/context-set.d.ts +26 -0
- package/dist/src/context/context-set.js +45 -0
- package/dist/src/context/context.d.ts +357 -0
- package/dist/src/context/context.js +401 -0
- package/dist/src/context/query-parser.d.ts +23 -0
- package/dist/src/context/query-parser.js +132 -0
- package/dist/src/context/route-access.d.ts +7 -0
- package/dist/src/context/route-access.js +18 -0
- package/dist/src/context/types.d.ts +62 -0
- package/dist/src/context/types.js +5 -0
- package/dist/src/core/asset-mime.d.ts +9 -0
- package/dist/src/core/asset-mime.js +35 -0
- package/dist/src/core/assets.d.ts +30 -0
- package/dist/src/core/assets.js +67 -0
- package/dist/src/core/docs-providers.d.ts +13 -0
- package/dist/src/core/docs-providers.js +89 -0
- package/dist/src/core/embedded-assets.d.ts +18 -0
- package/dist/src/core/embedded-assets.js +13 -0
- package/dist/src/core/openapi.d.ts +9 -10
- package/dist/src/core/openapi.js +333 -127
- package/dist/src/core/page-router.d.ts +13 -17
- package/dist/src/core/page-router.js +86 -55
- package/dist/src/core/server.d.ts +20 -11
- package/dist/src/core/server.js +41 -45
- package/dist/src/errors/forbidden.d.ts +14 -0
- package/dist/src/errors/forbidden.js +16 -0
- package/dist/src/errors/http-error.d.ts +49 -0
- package/dist/src/errors/http-error.js +155 -0
- package/dist/src/errors/method-not-allowed.d.ts +13 -0
- package/dist/src/errors/method-not-allowed.js +15 -0
- package/dist/src/errors/not-found.d.ts +14 -0
- package/dist/src/errors/not-found.js +16 -0
- package/dist/src/errors/unauthorized.d.ts +14 -0
- package/dist/src/errors/unauthorized.js +16 -0
- package/dist/src/index.d.ts +275 -50
- package/dist/src/index.js +974 -333
- package/dist/src/lifecycle/executor.d.ts +64 -0
- package/dist/src/lifecycle/executor.js +201 -0
- package/dist/src/lifecycle/hook-runner.d.ts +11 -0
- package/dist/src/lifecycle/hook-runner.js +156 -0
- package/dist/src/lifecycle/jit.d.ts +50 -0
- package/dist/src/lifecycle/jit.js +258 -0
- package/dist/src/lifecycle/transform.d.ts +26 -0
- package/dist/src/lifecycle/transform.js +99 -0
- package/dist/src/lifecycle/types.d.ts +135 -0
- package/dist/src/lifecycle/types.js +1 -0
- package/dist/src/plugin/composer.d.ts +3 -0
- package/dist/src/plugin/composer.js +28 -0
- package/dist/src/plugin/registry.d.ts +25 -0
- package/dist/src/plugin/registry.js +107 -0
- package/dist/src/plugin/types.d.ts +20 -0
- package/dist/src/plugin/types.js +1 -0
- package/dist/src/router/allow-cache.d.ts +20 -0
- package/dist/src/router/allow-cache.js +26 -0
- package/dist/src/router/compiler.d.ts +39 -0
- package/dist/src/router/compiler.js +867 -0
- package/dist/src/router/define.d.ts +67 -0
- package/dist/src/router/define.js +34 -0
- package/dist/src/router/index.d.ts +6 -0
- package/dist/src/router/index.js +5 -0
- package/dist/src/router/param-extract.d.ts +33 -0
- package/dist/src/router/param-extract.js +87 -0
- package/dist/src/router/regex-matcher.d.ts +42 -0
- package/dist/src/router/regex-matcher.js +216 -0
- package/dist/src/router/router.d.ts +214 -0
- package/dist/src/router/router.js +670 -0
- package/dist/src/router/static-map.d.ts +39 -0
- package/dist/src/router/static-map.js +48 -0
- package/dist/src/router/trie.d.ts +69 -0
- package/dist/src/router/trie.js +572 -0
- package/dist/src/router/types.d.ts +104 -0
- package/dist/src/router/types.js +1 -0
- package/dist/src/runtime/capabilities.d.ts +29 -0
- package/dist/src/runtime/capabilities.js +48 -0
- package/dist/src/types/index.d.ts +260 -109
- package/dist/src/types/index.js +1 -1
- package/dist/src/types/inference.d.ts +78 -0
- package/dist/src/types/inference.js +20 -0
- package/dist/src/types/openapi-config.d.ts +164 -0
- package/dist/src/types/openapi-config.js +8 -0
- package/dist/src/utils/env.d.ts +13 -0
- package/dist/src/utils/env.js +24 -0
- package/dist/src/utils/fs.d.ts +29 -0
- package/dist/src/utils/fs.js +75 -0
- package/dist/src/utils/index.d.ts +1 -1
- package/dist/src/utils/index.js +2 -2
- package/dist/src/utils/pathConversion.js +13 -7
- package/dist/src/utils/response.d.ts +42 -6
- package/dist/src/utils/response.js +189 -7
- package/dist/src/utils/routing.d.ts +32 -13
- package/dist/src/utils/routing.js +41 -18
- package/dist/src/utils/thenable.d.ts +8 -0
- package/dist/src/utils/thenable.js +12 -0
- package/dist/src/utils/timing-safe.d.ts +9 -0
- package/dist/src/utils/timing-safe.js +20 -0
- package/dist/src/utils/wildcard.d.ts +6 -7
- package/dist/src/utils/wildcard.js +38 -55
- package/dist/src/validation/adapter.d.ts +54 -0
- package/dist/src/validation/adapter.js +75 -0
- package/dist/src/validation/adapters/standard.d.ts +11 -0
- package/dist/src/validation/adapters/standard.js +110 -0
- package/dist/src/validation/adapters/zod.d.ts +9 -0
- package/dist/src/validation/adapters/zod.js +128 -0
- package/dist/src/validation/cache.d.ts +26 -0
- package/dist/src/validation/cache.js +35 -0
- package/dist/src/validation/coerce.d.ts +28 -0
- package/dist/src/validation/coerce.js +176 -0
- package/dist/src/validation/compiler.d.ts +27 -0
- package/dist/src/validation/compiler.js +191 -0
- package/dist/src/validation/error.d.ts +69 -0
- package/dist/src/validation/error.js +137 -0
- package/dist/src/validation/index.d.ts +16 -0
- package/dist/src/validation/index.js +12 -0
- package/dist/src/validation/response.d.ts +25 -0
- package/dist/src/validation/response.js +85 -0
- package/dist/src/validation/types.d.ts +148 -0
- package/dist/src/validation/types.js +6 -0
- package/dist/src/validation/validator.d.ts +39 -0
- package/dist/src/validation/validator.js +441 -0
- package/dist/src/ws/adapter.d.ts +230 -0
- package/dist/src/ws/adapter.js +660 -0
- package/dist/src/ws/compiler.d.ts +37 -0
- package/dist/src/ws/compiler.js +178 -0
- package/dist/src/ws/index.d.ts +11 -0
- package/dist/src/ws/index.js +8 -0
- package/dist/src/ws/platform.d.ts +82 -0
- package/dist/src/ws/platform.js +122 -0
- package/dist/src/ws/router.d.ts +47 -0
- package/dist/src/ws/router.js +183 -0
- package/dist/src/ws/scanner.d.ts +97 -0
- package/dist/src/ws/scanner.js +253 -0
- package/dist/src/ws/types.d.ts +381 -0
- package/dist/src/ws/types.js +213 -0
- package/package.json +72 -60
- package/dist/src/core/api-router.d.ts +0 -65
- package/dist/src/core/api-router.js +0 -264
- package/dist/src/core/swagger-ui.d.ts +0 -1
- package/dist/src/core/swagger-ui.js +0 -33
- package/dist/src/middleware/validator.d.ts +0 -14
- package/dist/src/middleware/validator.js +0 -133
- package/dist/src/utils/error.d.ts +0 -17
- package/dist/src/utils/error.js +0 -63
package/package.json
CHANGED
|
@@ -1,14 +1,44 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "burger-api",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "1.0.0-beta.1",
|
|
4
|
+
"description": "Fast, file-based API framework for Bun with hooks, Standard Schema validation, OpenAPI and WebSockets. Runs on Bun, Node, Cloudflare Workers, Deno and Vercel.",
|
|
4
5
|
"author": "Isfhan Ahmed",
|
|
5
6
|
"type": "module",
|
|
7
|
+
"sideEffects": false,
|
|
6
8
|
"module": "dist/src/index.js",
|
|
7
9
|
"types": "dist/src/index.d.ts",
|
|
8
10
|
"exports": {
|
|
9
11
|
".": {
|
|
10
|
-
"
|
|
11
|
-
"
|
|
12
|
+
"types": "./dist/src/index.d.ts",
|
|
13
|
+
"import": "./dist/src/index.js"
|
|
14
|
+
},
|
|
15
|
+
"./validation": {
|
|
16
|
+
"types": "./dist/src/validation/index.d.ts",
|
|
17
|
+
"import": "./dist/src/validation/index.js"
|
|
18
|
+
},
|
|
19
|
+
"./compiler": {
|
|
20
|
+
"types": "./dist/src/compiler/index.d.ts",
|
|
21
|
+
"import": "./dist/src/compiler/index.js"
|
|
22
|
+
},
|
|
23
|
+
"./openapi": {
|
|
24
|
+
"types": "./dist/src/core/openapi.d.ts",
|
|
25
|
+
"import": "./dist/src/core/openapi.js"
|
|
26
|
+
},
|
|
27
|
+
"./ws": {
|
|
28
|
+
"types": "./dist/src/ws/index.d.ts",
|
|
29
|
+
"import": "./dist/src/ws/index.js"
|
|
30
|
+
},
|
|
31
|
+
"./adapter": {
|
|
32
|
+
"types": "./dist/src/adapter/index.d.ts",
|
|
33
|
+
"import": "./dist/src/adapter/index.js"
|
|
34
|
+
},
|
|
35
|
+
"./adapter/web-standard": {
|
|
36
|
+
"types": "./dist/src/adapter/web-standard/index.d.ts",
|
|
37
|
+
"import": "./dist/src/adapter/web-standard/index.js"
|
|
38
|
+
},
|
|
39
|
+
"./adapter/bun": {
|
|
40
|
+
"types": "./dist/src/adapter/bun/index.d.ts",
|
|
41
|
+
"import": "./dist/src/adapter/bun/index.js"
|
|
12
42
|
}
|
|
13
43
|
},
|
|
14
44
|
"files": [
|
|
@@ -16,85 +46,67 @@
|
|
|
16
46
|
],
|
|
17
47
|
"scripts": {
|
|
18
48
|
"typecheck": "tsc --noEmit",
|
|
19
|
-
"build": "tsc --project tsconfig.build.json",
|
|
49
|
+
"build": "rm -rf dist && tsc --project tsconfig.build.json",
|
|
20
50
|
"prepare": "bun run build",
|
|
21
|
-
"test": "bun run test:examples && bun run test:ecosystem",
|
|
22
|
-
"test:examples": "bun test --timeout 30000 --max-concurrency 1 examples
|
|
23
|
-
"test:ecosystem": "bun test --timeout 60000 --max-concurrency 1 test/ecosystem-
|
|
24
|
-
"
|
|
51
|
+
"test": "bun run test:examples && bun run test:ecosystem && bun run test:lifecycle && bun run test:context && bun run test:utils && bun run test:chain && bun run test:plugin && bun run test:router && bun run test:core && bun run test:errors && bun run test:validation && bun run test:compiler && bun run test:adapter && bun run test:provider && bun run test:smoke && bun run test:ws",
|
|
52
|
+
"test:examples": "bun test --timeout 30000 --max-concurrency 1 ./examples",
|
|
53
|
+
"test:ecosystem": "bun test --timeout 60000 --max-concurrency 1 test/ecosystem-smoke.test.ts test/ecosystem/u16-hardening.test.ts test/ecosystem/correctness.test.ts",
|
|
54
|
+
"test:lifecycle": "bun test --timeout 30000 ./test/lifecycle",
|
|
55
|
+
"test:context": "bun test --timeout 30000 ./test/context",
|
|
56
|
+
"test:utils": "bun test --timeout 30000 ./test/utils",
|
|
57
|
+
"test:chain": "bun test --timeout 30000 ./test/chain",
|
|
58
|
+
"test:plugin": "bun test --timeout 30000 ./test/plugin",
|
|
59
|
+
"test:router": "bun test --timeout 30000 ./test/router",
|
|
60
|
+
"test:core": "bun test --timeout 30000 ./test/core",
|
|
61
|
+
"test:errors": "bun test --timeout 30000 ./test/errors",
|
|
62
|
+
"test:smoke": "bun test --timeout 30000 test/plugin-smoke.test.ts",
|
|
63
|
+
"test:ws": "bun test --timeout 30000 ./test/ws",
|
|
64
|
+
"test:validation": "bun test --timeout 30000 ./test/validation",
|
|
65
|
+
"test:compiler": "bun test --timeout 30000 ./test/compiler",
|
|
66
|
+
"test:adapter": "bun test --timeout 30000 ./test/adapter",
|
|
67
|
+
"test:provider": "bun test --timeout 30000 ./test/provider",
|
|
68
|
+
"dev": "bun run examples/basic/src/index.ts"
|
|
25
69
|
},
|
|
26
70
|
"keywords": [
|
|
27
71
|
"burger-api",
|
|
28
|
-
"burger-api-framework",
|
|
29
72
|
"bun",
|
|
30
|
-
"bunjs",
|
|
31
73
|
"bun-framework",
|
|
32
|
-
"fast-backend",
|
|
33
|
-
"javascript-backend",
|
|
34
|
-
"high-performance",
|
|
35
|
-
"esm",
|
|
36
|
-
"typescript",
|
|
37
|
-
"openapi",
|
|
38
|
-
"swagger-ui",
|
|
39
|
-
"declarative-routing",
|
|
40
74
|
"api-framework",
|
|
41
|
-
"modern-backend",
|
|
42
|
-
"backend-framework",
|
|
43
|
-
"server",
|
|
44
|
-
"bun-native",
|
|
45
|
-
"js-backend",
|
|
46
|
-
"fast-api",
|
|
47
|
-
"scalable-backend",
|
|
48
|
-
"backend-development",
|
|
49
|
-
"modern-api",
|
|
50
|
-
"api-development",
|
|
51
|
-
"backend-engine",
|
|
52
|
-
"efficient",
|
|
53
|
-
"minimalist-backend",
|
|
54
|
-
"bun-powered",
|
|
55
|
-
"open-source",
|
|
56
|
-
"typescript-backend",
|
|
57
|
-
"performance",
|
|
58
|
-
"rapid-development",
|
|
59
75
|
"web-framework",
|
|
60
|
-
"
|
|
61
|
-
"
|
|
62
|
-
"
|
|
63
|
-
"
|
|
64
|
-
"
|
|
65
|
-
"
|
|
66
|
-
"
|
|
67
|
-
"
|
|
68
|
-
"
|
|
69
|
-
"
|
|
70
|
-
"bun-backend",
|
|
71
|
-
"bun-api-framework",
|
|
72
|
-
"pakistan-backend",
|
|
73
|
-
"pakistan-api-framework",
|
|
74
|
-
"pakistan-api-server",
|
|
75
|
-
"pakistan-backend-framework",
|
|
76
|
-
"pakistan-bunjs-framework",
|
|
77
|
-
"pakistan-javascript-framework"
|
|
76
|
+
"backend-framework",
|
|
77
|
+
"typescript",
|
|
78
|
+
"javascript",
|
|
79
|
+
"file-based-routing",
|
|
80
|
+
"openapi",
|
|
81
|
+
"zod",
|
|
82
|
+
"standard-schema",
|
|
83
|
+
"websocket",
|
|
84
|
+
"wintercg",
|
|
85
|
+
"cloudflare-workers"
|
|
78
86
|
],
|
|
79
87
|
"license": "MIT",
|
|
80
88
|
"repository": {
|
|
81
89
|
"type": "git",
|
|
82
|
-
"url": "git+https://github.com/
|
|
90
|
+
"url": "git+https://github.com/Isfhan/burger-api.git",
|
|
91
|
+
"directory": "packages/burger-api"
|
|
83
92
|
},
|
|
84
93
|
"bugs": {
|
|
85
94
|
"url": "https://github.com/isfhan/burger-api/issues"
|
|
86
95
|
},
|
|
87
96
|
"homepage": "https://burger-api.com",
|
|
88
97
|
"engines": {
|
|
89
|
-
"bun": ">=1.
|
|
98
|
+
"bun": ">=1.4.4",
|
|
99
|
+
"node": ">=24.22.1"
|
|
90
100
|
},
|
|
91
101
|
"dependencies": {
|
|
92
|
-
"zod": "^4.
|
|
102
|
+
"zod": "^4.6.7"
|
|
93
103
|
},
|
|
94
104
|
"devDependencies": {
|
|
95
|
-
"@types/bun": "latest"
|
|
105
|
+
"@types/bun": "latest",
|
|
106
|
+
"arktype": "^2.2.9",
|
|
107
|
+
"valibot": "^1.4.2"
|
|
96
108
|
},
|
|
97
109
|
"peerDependencies": {
|
|
98
|
-
"typescript": "
|
|
110
|
+
"typescript": ">=5"
|
|
99
111
|
}
|
|
100
|
-
}
|
|
112
|
+
}
|
|
@@ -1,65 +0,0 @@
|
|
|
1
|
-
import type { RouteDefinition, TrieNode } from '../types/index';
|
|
2
|
-
/**
|
|
3
|
-
* ApiRouter class for handling file-based routing.
|
|
4
|
-
* Loads routes from a directory structure and matches requests to the appropriate route handlers.
|
|
5
|
-
* Supports dynamic segments (e.g., [id] ,(group),[...]) and HTTP method handlers.
|
|
6
|
-
* Routes are sorted to prioritize static routes over dynamic and wildcard ones to prevent overlapping route issues.
|
|
7
|
-
*/
|
|
8
|
-
export declare class ApiRouter {
|
|
9
|
-
private routesDir;
|
|
10
|
-
private prefix;
|
|
11
|
-
/** The root of the trie where all routes will begin*/
|
|
12
|
-
private root;
|
|
13
|
-
/**
|
|
14
|
-
* Constructor for the ApiRouter class.
|
|
15
|
-
* @param routesDir The directory path where route modules are located.
|
|
16
|
-
* @param prefix Optional prefix to prepend to all routes (e.g., "api" becomes "/api/...").
|
|
17
|
-
* @throws {Error} If the routes directory path is not provided.
|
|
18
|
-
*/
|
|
19
|
-
constructor(routesDir: string, prefix?: string);
|
|
20
|
-
/**
|
|
21
|
-
* Getter for the routes trie.
|
|
22
|
-
* @returns The root of the trie.
|
|
23
|
-
*/
|
|
24
|
-
get routes(): TrieNode;
|
|
25
|
-
/**
|
|
26
|
-
* Loads all routes from the routes directory into the trie structure.
|
|
27
|
-
* @returns {Promise<void>} A promise that resolves when all routes are loaded.
|
|
28
|
-
* @throws {Error} If the routes directory is not found or if an error occurs during route loading.
|
|
29
|
-
*/
|
|
30
|
-
loadRoutes(): Promise<void>;
|
|
31
|
-
/**
|
|
32
|
-
* Inserts a route definition into the trie structure.
|
|
33
|
-
* @param routeDef The route definition to insert, containing path, handlers, middleware, schema, and OpenAPI metadata.
|
|
34
|
-
* @throws {Error} If the route definition is invalid or causes a conflict in the trie.
|
|
35
|
-
*/
|
|
36
|
-
private insertRoute;
|
|
37
|
-
/**
|
|
38
|
-
* Recursively scans a directory for route modules (route.ts files) and loads them into the trie.
|
|
39
|
-
* @param dir The current directory path to scan.
|
|
40
|
-
* @param basePath The base path used to construct route paths from the directory structure.
|
|
41
|
-
* @returns {Promise<void>} A promise that resolves when the directory scan is complete.
|
|
42
|
-
* @throws {Error} If multiple dynamic folders are found at the same level or if directory access fails.
|
|
43
|
-
*/
|
|
44
|
-
private scanDirectory;
|
|
45
|
-
/**
|
|
46
|
-
* Loads a route module from a file and inserts it into the trie.
|
|
47
|
-
* @param entryPath The full file system path to the route module (route.ts).
|
|
48
|
-
* @param relativePath The relative path used to construct the route path.
|
|
49
|
-
* @returns {Promise<void>} A promise that resolves when the module is loaded and inserted.
|
|
50
|
-
* @throws {Error} If the route module fails to load or is invalid.
|
|
51
|
-
*/
|
|
52
|
-
private loadRouteModule;
|
|
53
|
-
/**
|
|
54
|
-
* Resolves a request to a route definition and its parameters.
|
|
55
|
-
* @param pathname The normalized request pathname.
|
|
56
|
-
* @param method The uppercase HTTP method.
|
|
57
|
-
* @returns {{ route?: RouteDefinition; params: Record<string, string>; wildcardParams?: string[] }} An object containing the matched route (if any), extracted parameters, and wildcard segments (if applicable).
|
|
58
|
-
* @throws {Error} If the request URL is malformed.
|
|
59
|
-
*/
|
|
60
|
-
resolve(pathname: string, method: string): {
|
|
61
|
-
route?: RouteDefinition;
|
|
62
|
-
params: Record<string, string>;
|
|
63
|
-
wildcardParams?: string[];
|
|
64
|
-
};
|
|
65
|
-
}
|
|
@@ -1,264 +0,0 @@
|
|
|
1
|
-
// Import stuff from node
|
|
2
|
-
import { readdir } from 'fs/promises';
|
|
3
|
-
import * as path from 'path';
|
|
4
|
-
// Import utils
|
|
5
|
-
import { normalizePath, ROUTE_CONSTANTS, HTTP_METHODS } from '../utils/index';
|
|
6
|
-
import { filePathToApiRoutePath } from '../utils/pathConversion';
|
|
7
|
-
/**
|
|
8
|
-
* ApiRouter class for handling file-based routing.
|
|
9
|
-
* Loads routes from a directory structure and matches requests to the appropriate route handlers.
|
|
10
|
-
* Supports dynamic segments (e.g., [id] ,(group),[...]) and HTTP method handlers.
|
|
11
|
-
* Routes are sorted to prioritize static routes over dynamic and wildcard ones to prevent overlapping route issues.
|
|
12
|
-
*/
|
|
13
|
-
export class ApiRouter {
|
|
14
|
-
routesDir;
|
|
15
|
-
prefix;
|
|
16
|
-
/** The root of the trie where all routes will begin*/
|
|
17
|
-
root = { children: new Map() };
|
|
18
|
-
/**
|
|
19
|
-
* Constructor for the ApiRouter class.
|
|
20
|
-
* @param routesDir The directory path where route modules are located.
|
|
21
|
-
* @param prefix Optional prefix to prepend to all routes (e.g., "api" becomes "/api/...").
|
|
22
|
-
* @throws {Error} If the routes directory path is not provided.
|
|
23
|
-
*/
|
|
24
|
-
constructor(routesDir, prefix = '') {
|
|
25
|
-
this.routesDir = routesDir;
|
|
26
|
-
this.prefix = prefix;
|
|
27
|
-
if (!routesDir) {
|
|
28
|
-
throw new Error('Routes directory path is required');
|
|
29
|
-
}
|
|
30
|
-
}
|
|
31
|
-
/**
|
|
32
|
-
* Getter for the routes trie.
|
|
33
|
-
* @returns The root of the trie.
|
|
34
|
-
*/
|
|
35
|
-
get routes() {
|
|
36
|
-
return this.root;
|
|
37
|
-
}
|
|
38
|
-
/**
|
|
39
|
-
* Loads all routes from the routes directory into the trie structure.
|
|
40
|
-
* @returns {Promise<void>} A promise that resolves when all routes are loaded.
|
|
41
|
-
* @throws {Error} If the routes directory is not found or if an error occurs during route loading.
|
|
42
|
-
*/
|
|
43
|
-
async loadRoutes() {
|
|
44
|
-
try {
|
|
45
|
-
await this.scanDirectory(this.routesDir);
|
|
46
|
-
}
|
|
47
|
-
catch (error) {
|
|
48
|
-
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
49
|
-
throw new Error(`Failed to load routes: ${errorMessage}`);
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
/**
|
|
53
|
-
* Inserts a route definition into the trie structure.
|
|
54
|
-
* @param routeDef The route definition to insert, containing path, handlers, middleware, schema, and OpenAPI metadata.
|
|
55
|
-
* @throws {Error} If the route definition is invalid or causes a conflict in the trie.
|
|
56
|
-
*/
|
|
57
|
-
insertRoute(routeDef) {
|
|
58
|
-
let node = this.root;
|
|
59
|
-
const segments = routeDef.path.split('/').filter(Boolean);
|
|
60
|
-
for (const segment of segments) {
|
|
61
|
-
if (segment.startsWith(':')) {
|
|
62
|
-
// Handle dynamic segments (:param)
|
|
63
|
-
if (!node.paramChild) {
|
|
64
|
-
node.paramChild = { children: new Map() };
|
|
65
|
-
}
|
|
66
|
-
node = node.paramChild;
|
|
67
|
-
node.paramName = segment.slice(1);
|
|
68
|
-
}
|
|
69
|
-
else if (segment.startsWith('*')) {
|
|
70
|
-
// Handle wildcard segments (*param)
|
|
71
|
-
if (!node.wildcardChild) {
|
|
72
|
-
node.wildcardChild = { children: new Map() };
|
|
73
|
-
}
|
|
74
|
-
node = node.wildcardChild;
|
|
75
|
-
node.isWildcard = true; // Mark as wildcard route
|
|
76
|
-
}
|
|
77
|
-
else {
|
|
78
|
-
// Handle static segments
|
|
79
|
-
if (!node.children.has(segment)) {
|
|
80
|
-
node.children.set(segment, { children: new Map() });
|
|
81
|
-
}
|
|
82
|
-
node = node.children.get(segment);
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
node.route = routeDef;
|
|
86
|
-
}
|
|
87
|
-
/**
|
|
88
|
-
* Recursively scans a directory for route modules (route.ts files) and loads them into the trie.
|
|
89
|
-
* @param dir The current directory path to scan.
|
|
90
|
-
* @param basePath The base path used to construct route paths from the directory structure.
|
|
91
|
-
* @returns {Promise<void>} A promise that resolves when the directory scan is complete.
|
|
92
|
-
* @throws {Error} If multiple dynamic folders are found at the same level or if directory access fails.
|
|
93
|
-
*/
|
|
94
|
-
async scanDirectory(dir, basePath = '') {
|
|
95
|
-
// Track route types at this directory level to prevent conflicts
|
|
96
|
-
let dynamicFolderFound = false;
|
|
97
|
-
let wildcardFolderFound = false;
|
|
98
|
-
try {
|
|
99
|
-
const entries = await readdir(dir, { withFileTypes: true });
|
|
100
|
-
for (const entry of entries) {
|
|
101
|
-
const entryPath = path.join(dir, entry.name);
|
|
102
|
-
const relativePath = path.join(basePath, entry.name);
|
|
103
|
-
if (entry.isDirectory()) {
|
|
104
|
-
// Skip named wildcard folders
|
|
105
|
-
if (entry.name.startsWith(ROUTE_CONSTANTS.WILDCARD_START) &&
|
|
106
|
-
entry.name !== ROUTE_CONSTANTS.WILDCARD_SIMPLE) {
|
|
107
|
-
continue;
|
|
108
|
-
}
|
|
109
|
-
// Check if this is a dynamic or wildcard directory
|
|
110
|
-
const isDynamic = entry.name.startsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_START) &&
|
|
111
|
-
entry.name.endsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_END) &&
|
|
112
|
-
!entry.name.startsWith(ROUTE_CONSTANTS.WILDCARD_START);
|
|
113
|
-
const isWildcard = entry.name === ROUTE_CONSTANTS.WILDCARD_SIMPLE;
|
|
114
|
-
// Prevent conflicts between dynamic and wildcard routes
|
|
115
|
-
if (isDynamic && wildcardFolderFound) {
|
|
116
|
-
throw new Error(`Cannot mix dynamic and wildcard route folders in the same directory. ` +
|
|
117
|
-
`Found dynamic folder '${entry.name}' but wildcard folder already exists in '${dir}'.`);
|
|
118
|
-
}
|
|
119
|
-
if (isWildcard && dynamicFolderFound) {
|
|
120
|
-
throw new Error(`Cannot mix wildcard and dynamic route folders in the same directory. ` +
|
|
121
|
-
`Found wildcard folder '${entry.name}' but dynamic folder already exists in '${dir}'.`);
|
|
122
|
-
}
|
|
123
|
-
if (isDynamic && dynamicFolderFound) {
|
|
124
|
-
throw new Error(`Multiple dynamic route folders found in the same directory: ` +
|
|
125
|
-
`'${entry.name}' conflicts with another dynamic folder in '${dir}'.`);
|
|
126
|
-
}
|
|
127
|
-
if (isWildcard && wildcardFolderFound) {
|
|
128
|
-
throw new Error(`Multiple wildcard route folders found in the same directory: ` +
|
|
129
|
-
`'${entry.name}' conflicts with another wildcard folder in '${dir}'.`);
|
|
130
|
-
}
|
|
131
|
-
// Update flags
|
|
132
|
-
if (isDynamic)
|
|
133
|
-
dynamicFolderFound = true;
|
|
134
|
-
if (isWildcard)
|
|
135
|
-
wildcardFolderFound = true;
|
|
136
|
-
await this.scanDirectory(entryPath, relativePath);
|
|
137
|
-
}
|
|
138
|
-
else if (entry.isFile() && entry.name === 'route.ts') {
|
|
139
|
-
await this.loadRouteModule(entryPath, relativePath);
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
catch (error) {
|
|
144
|
-
if (error instanceof Error) {
|
|
145
|
-
throw error; // Re-throw specific errors we created
|
|
146
|
-
}
|
|
147
|
-
throw new Error(`Failed to scan directory '${dir}': ${String(error)}`);
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
/**
|
|
151
|
-
* Loads a route module from a file and inserts it into the trie.
|
|
152
|
-
* @param entryPath The full file system path to the route module (route.ts).
|
|
153
|
-
* @param relativePath The relative path used to construct the route path.
|
|
154
|
-
* @returns {Promise<void>} A promise that resolves when the module is loaded and inserted.
|
|
155
|
-
* @throws {Error} If the route module fails to load or is invalid.
|
|
156
|
-
*/
|
|
157
|
-
async loadRouteModule(entryPath, relativePath) {
|
|
158
|
-
try {
|
|
159
|
-
// Convert the file path to a route path
|
|
160
|
-
const routePath = filePathToApiRoutePath(relativePath, this.prefix);
|
|
161
|
-
console.info('Loading route:', routePath);
|
|
162
|
-
// Get the module path like "D:\\Projects\\src\\api\\users\\route.ts"
|
|
163
|
-
const modulePath = path.resolve(entryPath);
|
|
164
|
-
// Import the module
|
|
165
|
-
const routeModule = await import(modulePath);
|
|
166
|
-
// Variable to store the handlers for each method
|
|
167
|
-
const handlers = {};
|
|
168
|
-
// Loop through all the HTTP methods and add the handler to the handlers object
|
|
169
|
-
for (const method of HTTP_METHODS) {
|
|
170
|
-
if (typeof routeModule[method] === 'function') {
|
|
171
|
-
handlers[method] = routeModule[method];
|
|
172
|
-
}
|
|
173
|
-
}
|
|
174
|
-
// Auto-inject minimal OPTIONS handler for CORS preflight when needed
|
|
175
|
-
// Only if route defines any preflight-triggering methods and lacks an OPTIONS handler
|
|
176
|
-
const PREFLIGHT_METHODS = [
|
|
177
|
-
'POST',
|
|
178
|
-
'PUT',
|
|
179
|
-
'DELETE',
|
|
180
|
-
'PATCH',
|
|
181
|
-
];
|
|
182
|
-
let hasPreflightMethods = false;
|
|
183
|
-
// Manual loop is slightly faster than Array.prototype.some in tight paths
|
|
184
|
-
for (let i = 0; i < PREFLIGHT_METHODS.length; i++) {
|
|
185
|
-
if (handlers[PREFLIGHT_METHODS[i]]) {
|
|
186
|
-
hasPreflightMethods = true;
|
|
187
|
-
break;
|
|
188
|
-
}
|
|
189
|
-
}
|
|
190
|
-
// If the route defines any preflight-triggering methods and lacks an OPTIONS handler, auto-add an OPTIONS handler
|
|
191
|
-
if (hasPreflightMethods && typeof handlers.OPTIONS !== 'function') {
|
|
192
|
-
// if (process.env.NODE_ENV !== 'production') {
|
|
193
|
-
// console.debug('Auto-added OPTIONS handler for route:', routePath);
|
|
194
|
-
// }
|
|
195
|
-
handlers.OPTIONS = () => new Response(null, { status: 204 });
|
|
196
|
-
}
|
|
197
|
-
const routeDef = {
|
|
198
|
-
path: routePath,
|
|
199
|
-
handlers,
|
|
200
|
-
middleware: routeModule.middleware,
|
|
201
|
-
schema: routeModule.schema,
|
|
202
|
-
openapi: routeModule.openapi,
|
|
203
|
-
isWildcard: routePath.includes(ROUTE_CONSTANTS.WILDCARD_SEGMENT_PREFIX),
|
|
204
|
-
};
|
|
205
|
-
this.insertRoute(routeDef);
|
|
206
|
-
}
|
|
207
|
-
catch (error) {
|
|
208
|
-
throw new Error(`Failed to load route module '${entryPath}': ${String(error)}`);
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
|
-
/**
|
|
212
|
-
* Resolves a request to a route definition and its parameters.
|
|
213
|
-
* @param pathname The normalized request pathname.
|
|
214
|
-
* @param method The uppercase HTTP method.
|
|
215
|
-
* @returns {{ route?: RouteDefinition; params: Record<string, string>; wildcardParams?: string[] }} An object containing the matched route (if any), extracted parameters, and wildcard segments (if applicable).
|
|
216
|
-
* @throws {Error} If the request URL is malformed.
|
|
217
|
-
*/
|
|
218
|
-
resolve(pathname, method) {
|
|
219
|
-
try {
|
|
220
|
-
const segments = pathname.split('/').filter(Boolean);
|
|
221
|
-
let node = this.root;
|
|
222
|
-
const params = {};
|
|
223
|
-
let wildcardSegments = [];
|
|
224
|
-
// Traverse the trie with proper prioritization
|
|
225
|
-
for (let i = 0; i < segments.length; i++) {
|
|
226
|
-
const segment = segments[i];
|
|
227
|
-
// Priority 1: Exact static match (highest priority)
|
|
228
|
-
if (node.children.has(segment)) {
|
|
229
|
-
node = node.children.get(segment);
|
|
230
|
-
}
|
|
231
|
-
// Priority 2: Dynamic parameter match (medium priority)
|
|
232
|
-
else if (node.paramChild) {
|
|
233
|
-
node = node.paramChild;
|
|
234
|
-
params[node.paramName] = segment;
|
|
235
|
-
}
|
|
236
|
-
// Priority 3: Collect remaining segments for wildcard (lowest priority)
|
|
237
|
-
else {
|
|
238
|
-
wildcardSegments = segments.slice(i);
|
|
239
|
-
break;
|
|
240
|
-
}
|
|
241
|
-
}
|
|
242
|
-
// Check if we have a route at the current node
|
|
243
|
-
if (node.route?.handlers[method]) {
|
|
244
|
-
return { route: node.route, params };
|
|
245
|
-
}
|
|
246
|
-
// If no route found but we have wildcard segments, check for wildcard route
|
|
247
|
-
if (wildcardSegments.length > 0 &&
|
|
248
|
-
node.wildcardChild?.route?.handlers[method]) {
|
|
249
|
-
// Return wildcard segments so they can be added to req.wildcardParams
|
|
250
|
-
return {
|
|
251
|
-
route: node.wildcardChild.route,
|
|
252
|
-
params,
|
|
253
|
-
wildcardParams: wildcardSegments,
|
|
254
|
-
};
|
|
255
|
-
}
|
|
256
|
-
return { params: {} };
|
|
257
|
-
}
|
|
258
|
-
catch (error) {
|
|
259
|
-
// Log the error for better debugging
|
|
260
|
-
console.error(`Error resolving API route for path "${pathname}":`, error);
|
|
261
|
-
return { params: {} };
|
|
262
|
-
}
|
|
263
|
-
}
|
|
264
|
-
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export declare const swaggerHtml = "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\">\n <title>API Documentation</title>\n <link rel=\"stylesheet\" href=\"https://unpkg.com/swagger-ui-dist/swagger-ui.css\" />\n <style>\n body {\n margin: 0;\n padding: 0;\n }\n </style>\n </head>\n <body>\n <div id=\"swagger-ui\"></div>\n <script src=\"https://unpkg.com/swagger-ui-dist/swagger-ui-bundle.js\"></script>\n <script>\n window.onload = function() {\n SwaggerUIBundle({\n url: '/openapi.json',\n dom_id: '#swagger-ui',\n presets: [\n SwaggerUIBundle.presets.apis,\n SwaggerUIBundle.SwaggerUIStandalonePreset\n ],\n layout: \"BaseLayout\",\n docExpansion: \"none\",\n filter: true,\n });\n };\n </script>\n </body>\n</html>";
|
|
@@ -1,33 +0,0 @@
|
|
|
1
|
-
export const swaggerHtml = `<!DOCTYPE html>
|
|
2
|
-
<html lang="en">
|
|
3
|
-
<head>
|
|
4
|
-
<meta charset="UTF-8">
|
|
5
|
-
<title>API Documentation</title>
|
|
6
|
-
<link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist/swagger-ui.css" />
|
|
7
|
-
<style>
|
|
8
|
-
body {
|
|
9
|
-
margin: 0;
|
|
10
|
-
padding: 0;
|
|
11
|
-
}
|
|
12
|
-
</style>
|
|
13
|
-
</head>
|
|
14
|
-
<body>
|
|
15
|
-
<div id="swagger-ui"></div>
|
|
16
|
-
<script src="https://unpkg.com/swagger-ui-dist/swagger-ui-bundle.js"></script>
|
|
17
|
-
<script>
|
|
18
|
-
window.onload = function() {
|
|
19
|
-
SwaggerUIBundle({
|
|
20
|
-
url: '/openapi.json',
|
|
21
|
-
dom_id: '#swagger-ui',
|
|
22
|
-
presets: [
|
|
23
|
-
SwaggerUIBundle.presets.apis,
|
|
24
|
-
SwaggerUIBundle.SwaggerUIStandalonePreset
|
|
25
|
-
],
|
|
26
|
-
layout: "BaseLayout",
|
|
27
|
-
docExpansion: "none",
|
|
28
|
-
filter: true,
|
|
29
|
-
});
|
|
30
|
-
};
|
|
31
|
-
</script>
|
|
32
|
-
</body>
|
|
33
|
-
</html>`;
|
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
import type { RouteSchema, Middleware } from '../types/index';
|
|
2
|
-
/**
|
|
3
|
-
* createValidationMiddleware:
|
|
4
|
-
* - Precompute a smaller runtime descriptor per method to avoid
|
|
5
|
-
* repeatedly touching the full schema object on every request.
|
|
6
|
-
* - Uses safeParse (sync) for Zod schemas (no try/catch around safeParse).
|
|
7
|
-
* - Parses querystring manually (no URL constructor, no throw).
|
|
8
|
-
* - Lazily allocates the errors container only when needed.
|
|
9
|
-
* - Avoids unnecessary object allocations for successful paths.
|
|
10
|
-
*
|
|
11
|
-
* @param schema - The route schema to validate the request against.
|
|
12
|
-
* @returns The middleware function that validates the request.
|
|
13
|
-
*/
|
|
14
|
-
export declare function createValidationMiddleware(schema: RouteSchema): Middleware;
|