burger-api 0.4.1 → 0.5.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 +47 -7
- package/dist/src/core/api-router.d.ts +1 -54
- package/dist/src/core/api-router.js +15 -87
- package/dist/src/core/openapi.d.ts +1 -1
- package/dist/src/core/openapi.js +1 -58
- package/dist/src/core/page-router.d.ts +1 -44
- package/dist/src/core/page-router.js +2 -73
- package/dist/src/core/server.d.ts +1 -11
- package/dist/src/core/server.js +1 -17
- package/dist/src/index.d.ts +3 -60
- package/dist/src/index.js +27 -286
- package/dist/src/middleware/validator.d.ts +1 -13
- package/dist/src/middleware/validator.js +9 -59
- package/dist/src/types/index.d.ts +73 -0
- package/dist/src/types/index.js +1 -0
- package/dist/src/utils/error.d.ts +0 -16
- package/dist/src/utils/error.js +1 -25
- package/dist/src/utils/index.d.ts +1 -18
- package/dist/src/utils/index.js +1 -23
- package/dist/src/utils/response.d.ts +0 -9
- package/dist/src/utils/response.js +0 -9
- package/dist/src/utils/routing.d.ts +1 -29
- package/dist/src/utils/routing.js +3 -41
- package/dist/src/utils/wildcard.d.ts +3 -0
- package/dist/src/utils/wildcard.js +30 -0
- package/package.json +3 -4
- package/dist/src/utils/zod-to-json.d.ts +0 -11
- package/dist/src/utils/zod-to-json.js +0 -117
package/README.md
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
[](https://github.com/isfhan/burger-api)
|
|
6
6
|
[](LICENSE)
|
|
7
7
|
[](https://bun.sh)
|
|
8
|
-
[](https://github.com/isfhan/burger-api/releases)
|
|
9
9
|
|
|
10
10
|
**burger-api** is a modern, open source API framework built on
|
|
11
11
|
[Bun.js](https://bun.sh). It combines the simplicity of file-based routing with
|
|
@@ -44,6 +44,13 @@ burger-api is built to offer a robust developer experience through:
|
|
|
44
44
|
- 🔄 **Middleware Architecture:**
|
|
45
45
|
Supports both global and route-specific middleware.
|
|
46
46
|
|
|
47
|
+
- After middlewares (functions returned by a middleware) run after the
|
|
48
|
+
route handler.
|
|
49
|
+
- They now run even if an earlier middleware returned a Response, so
|
|
50
|
+
post-processing is reliable.
|
|
51
|
+
- They run in reverse order and are useful for adding CORS headers,
|
|
52
|
+
logging, or tweaking the final Response.
|
|
53
|
+
|
|
47
54
|
- ✅ **Type-Safe Validation:**
|
|
48
55
|
Utilizes Zod for request validation, ensuring full type safety and automatic
|
|
49
56
|
error reporting.
|
|
@@ -59,19 +66,52 @@ burger-api is built to offer a robust developer experience through:
|
|
|
59
66
|
|
|
60
67
|
## 📣 Changelog
|
|
61
68
|
|
|
62
|
-
### Latest Version: 0.
|
|
69
|
+
### Latest Version: 0.5.1 (December 2025)
|
|
70
|
+
|
|
71
|
+
- 🔧 **Internal Improvements:**
|
|
72
|
+
- Refactored wildcard parameter extraction logic into reusable utility functions
|
|
73
|
+
- Enabled `removeComments` in build configuration to reduce bundle size
|
|
74
|
+
- Added test suites and README files for all example projects
|
|
75
|
+
|
|
76
|
+
### Previous Version: 0.5.0 (November 1, 2025)
|
|
77
|
+
|
|
78
|
+
- 🌟 **Feature:** Auto-injected OPTIONS handler for CORS preflight:
|
|
79
|
+
|
|
80
|
+
- Automatically injects an OPTIONS handler for CORS preflight when needed
|
|
81
|
+
- Only injects if the route defines any preflight-triggering methods and
|
|
82
|
+
lacks an OPTIONS handler
|
|
83
|
+
- Injects a minimal OPTIONS handler that returns a 204 No Content response
|
|
84
|
+
- Works for all HTTP methods that trigger CORS preflight (POST, PUT,
|
|
85
|
+
DELETE, PATCH)
|
|
86
|
+
- Does not inject if the route already has an OPTIONS handler
|
|
87
|
+
|
|
88
|
+
- 🌟 **Feature:** Improved response handling in middleware (after
|
|
89
|
+
middlewares):
|
|
90
|
+
|
|
91
|
+
- After middlewares now run even if the current middleware already
|
|
92
|
+
returned a response
|
|
93
|
+
- After middlewares run in reverse order to make changing the response
|
|
94
|
+
easier and to help with CORS
|
|
95
|
+
|
|
96
|
+
- 🐛 **Bug Fix:** Fixed TypeScript type resolution for package consumers:
|
|
97
|
+
- Users now get full IntelliSense, autocomplete, and type safety out of
|
|
98
|
+
the box
|
|
99
|
+
|
|
100
|
+
### Previous Version: 0.4.0 (October 21, 2025)
|
|
63
101
|
|
|
64
|
-
-
|
|
65
|
-
- Added wildcard routes using `[...]` folder name - matches any path after
|
|
102
|
+
- 🌟 **Feature:** Wildcard Routes:
|
|
103
|
+
- Added wildcard routes using `[...]` folder name - matches any path after
|
|
104
|
+
it
|
|
66
105
|
- Create routes that handle multiple path segments automatically
|
|
67
106
|
- Access all matched path parts through `wildcardParams` in your request
|
|
68
|
-
- Routes are matched in order: exact paths first, then dynamic routes
|
|
107
|
+
- Routes are matched in order: exact paths first, then dynamic routes
|
|
108
|
+
(like `[id]`), then wildcards last
|
|
69
109
|
- Works inside dynamic routes too (example: `/api/users/[userId]/[...]`)
|
|
70
110
|
- View wildcard routes in OpenAPI docs and Swagger UI
|
|
71
111
|
|
|
72
|
-
### Version 0.3.0 (August 15, 2025)
|
|
112
|
+
### Previous Version: 0.3.0 (August 15, 2025)
|
|
73
113
|
|
|
74
|
-
-
|
|
114
|
+
- 🌟 **Feature:** Updated Zod to version 4:
|
|
75
115
|
- Updated Zod version from 3.x to 4.x
|
|
76
116
|
- Updated built-in request validation middleware to use Zod 4
|
|
77
117
|
- Updated and better request validation middleware error handling
|
|
@@ -1,68 +1,15 @@
|
|
|
1
|
-
import type { RouteDefinition, TrieNode } from '
|
|
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
|
-
*/
|
|
1
|
+
import type { RouteDefinition, TrieNode } from '../types/index';
|
|
8
2
|
export declare class ApiRouter {
|
|
9
3
|
private routesDir;
|
|
10
4
|
private prefix;
|
|
11
|
-
/** The root of the trie where all routes will begin*/
|
|
12
5
|
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
6
|
constructor(routesDir: string, prefix?: string);
|
|
20
|
-
/**
|
|
21
|
-
* Getter for the routes trie.
|
|
22
|
-
* @returns The root of the trie.
|
|
23
|
-
*/
|
|
24
7
|
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
8
|
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
9
|
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
10
|
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
11
|
private loadRouteModule;
|
|
53
|
-
/**
|
|
54
|
-
* Converts a file path to a route path by processing dynamic segments and wildcard segments applying the prefix.
|
|
55
|
-
* @param filePath The file path to convert (e.g., "users/[id]/route.ts" , "users/[...slug]/route.ts").
|
|
56
|
-
* @returns {string} The converted route path (e.g., "/users/:id" , "/users/*slug").
|
|
57
|
-
*/
|
|
58
12
|
private convertFilePathToRoute;
|
|
59
|
-
/**
|
|
60
|
-
* Resolves a request to a route definition and its parameters.
|
|
61
|
-
* @param pathname The normalized request pathname.
|
|
62
|
-
* @param method The uppercase HTTP method.
|
|
63
|
-
* @returns {{ route?: RouteDefinition; params: Record<string, string>; wildcardParams?: string[] }} An object containing the matched route (if any), extracted parameters, and wildcard segments (if applicable).
|
|
64
|
-
* @throws {Error} If the request URL is malformed.
|
|
65
|
-
*/
|
|
66
13
|
resolve(pathname: string, method: string): {
|
|
67
14
|
route?: RouteDefinition;
|
|
68
15
|
params: Record<string, string>;
|
|
@@ -1,25 +1,10 @@
|
|
|
1
|
-
// Import stuff from node
|
|
2
1
|
import { readdir } from 'fs/promises';
|
|
3
2
|
import * as path from 'path';
|
|
4
|
-
|
|
5
|
-
import { cleanPrefix, normalizePath, ROUTE_CONSTANTS, HTTP_METHODS, } from '../utils/index.js';
|
|
6
|
-
/**
|
|
7
|
-
* ApiRouter class for handling file-based routing.
|
|
8
|
-
* Loads routes from a directory structure and matches requests to the appropriate route handlers.
|
|
9
|
-
* Supports dynamic segments (e.g., [id] ,(group),[...]) and HTTP method handlers.
|
|
10
|
-
* Routes are sorted to prioritize static routes over dynamic and wildcard ones to prevent overlapping route issues.
|
|
11
|
-
*/
|
|
3
|
+
import { cleanPrefix, normalizePath, ROUTE_CONSTANTS, HTTP_METHODS, } from '../utils/index';
|
|
12
4
|
export class ApiRouter {
|
|
13
5
|
routesDir;
|
|
14
6
|
prefix;
|
|
15
|
-
/** The root of the trie where all routes will begin*/
|
|
16
7
|
root = { children: new Map() };
|
|
17
|
-
/**
|
|
18
|
-
* Constructor for the ApiRouter class.
|
|
19
|
-
* @param routesDir The directory path where route modules are located.
|
|
20
|
-
* @param prefix Optional prefix to prepend to all routes (e.g., "api" becomes "/api/...").
|
|
21
|
-
* @throws {Error} If the routes directory path is not provided.
|
|
22
|
-
*/
|
|
23
8
|
constructor(routesDir, prefix = '') {
|
|
24
9
|
this.routesDir = routesDir;
|
|
25
10
|
this.prefix = prefix;
|
|
@@ -27,18 +12,9 @@ export class ApiRouter {
|
|
|
27
12
|
throw new Error('Routes directory path is required');
|
|
28
13
|
}
|
|
29
14
|
}
|
|
30
|
-
/**
|
|
31
|
-
* Getter for the routes trie.
|
|
32
|
-
* @returns The root of the trie.
|
|
33
|
-
*/
|
|
34
15
|
get routes() {
|
|
35
16
|
return this.root;
|
|
36
17
|
}
|
|
37
|
-
/**
|
|
38
|
-
* Loads all routes from the routes directory into the trie structure.
|
|
39
|
-
* @returns {Promise<void>} A promise that resolves when all routes are loaded.
|
|
40
|
-
* @throws {Error} If the routes directory is not found or if an error occurs during route loading.
|
|
41
|
-
*/
|
|
42
18
|
async loadRoutes() {
|
|
43
19
|
try {
|
|
44
20
|
await this.scanDirectory(this.routesDir);
|
|
@@ -48,17 +24,11 @@ export class ApiRouter {
|
|
|
48
24
|
throw new Error(`Failed to load routes: ${errorMessage}`);
|
|
49
25
|
}
|
|
50
26
|
}
|
|
51
|
-
/**
|
|
52
|
-
* Inserts a route definition into the trie structure.
|
|
53
|
-
* @param routeDef The route definition to insert, containing path, handlers, middleware, schema, and OpenAPI metadata.
|
|
54
|
-
* @throws {Error} If the route definition is invalid or causes a conflict in the trie.
|
|
55
|
-
*/
|
|
56
27
|
insertRoute(routeDef) {
|
|
57
28
|
let node = this.root;
|
|
58
29
|
const segments = routeDef.path.split('/').filter(Boolean);
|
|
59
30
|
for (const segment of segments) {
|
|
60
31
|
if (segment.startsWith(':')) {
|
|
61
|
-
// Handle dynamic segments (:param)
|
|
62
32
|
if (!node.paramChild) {
|
|
63
33
|
node.paramChild = { children: new Map() };
|
|
64
34
|
}
|
|
@@ -66,15 +36,13 @@ export class ApiRouter {
|
|
|
66
36
|
node.paramName = segment.slice(1);
|
|
67
37
|
}
|
|
68
38
|
else if (segment.startsWith('*')) {
|
|
69
|
-
// Handle wildcard segments (*param)
|
|
70
39
|
if (!node.wildcardChild) {
|
|
71
40
|
node.wildcardChild = { children: new Map() };
|
|
72
41
|
}
|
|
73
42
|
node = node.wildcardChild;
|
|
74
|
-
node.isWildcard = true;
|
|
43
|
+
node.isWildcard = true;
|
|
75
44
|
}
|
|
76
45
|
else {
|
|
77
|
-
// Handle static segments
|
|
78
46
|
if (!node.children.has(segment)) {
|
|
79
47
|
node.children.set(segment, { children: new Map() });
|
|
80
48
|
}
|
|
@@ -83,15 +51,7 @@ export class ApiRouter {
|
|
|
83
51
|
}
|
|
84
52
|
node.route = routeDef;
|
|
85
53
|
}
|
|
86
|
-
/**
|
|
87
|
-
* Recursively scans a directory for route modules (route.ts files) and loads them into the trie.
|
|
88
|
-
* @param dir The current directory path to scan.
|
|
89
|
-
* @param basePath The base path used to construct route paths from the directory structure.
|
|
90
|
-
* @returns {Promise<void>} A promise that resolves when the directory scan is complete.
|
|
91
|
-
* @throws {Error} If multiple dynamic folders are found at the same level or if directory access fails.
|
|
92
|
-
*/
|
|
93
54
|
async scanDirectory(dir, basePath = '') {
|
|
94
|
-
// Track route types at this directory level to prevent conflicts
|
|
95
55
|
let dynamicFolderFound = false;
|
|
96
56
|
let wildcardFolderFound = false;
|
|
97
57
|
try {
|
|
@@ -100,12 +60,10 @@ export class ApiRouter {
|
|
|
100
60
|
const entryPath = path.join(dir, entry.name);
|
|
101
61
|
const relativePath = path.join(basePath, entry.name);
|
|
102
62
|
if (entry.isDirectory()) {
|
|
103
|
-
// Check if this is a dynamic or wildcard directory
|
|
104
63
|
const isDynamic = entry.name.startsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_START) &&
|
|
105
64
|
entry.name.endsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_END) &&
|
|
106
65
|
entry.name !== ROUTE_CONSTANTS.WILDCARD_SIMPLE;
|
|
107
66
|
const isWildcard = entry.name === ROUTE_CONSTANTS.WILDCARD_SIMPLE;
|
|
108
|
-
// Prevent conflicts between dynamic and wildcard routes
|
|
109
67
|
if (isDynamic && wildcardFolderFound) {
|
|
110
68
|
throw new Error(`Cannot mix dynamic and wildcard route folders in the same directory. ` +
|
|
111
69
|
`Found dynamic folder '${entry.name}' but wildcard folder already exists in '${dir}'.`);
|
|
@@ -122,7 +80,6 @@ export class ApiRouter {
|
|
|
122
80
|
throw new Error(`Multiple wildcard route folders found in the same directory: ` +
|
|
123
81
|
`'${entry.name}' conflicts with another wildcard folder in '${dir}'.`);
|
|
124
82
|
}
|
|
125
|
-
// Update flags
|
|
126
83
|
if (isDynamic)
|
|
127
84
|
dynamicFolderFound = true;
|
|
128
85
|
if (isWildcard)
|
|
@@ -136,35 +93,34 @@ export class ApiRouter {
|
|
|
136
93
|
}
|
|
137
94
|
catch (error) {
|
|
138
95
|
if (error instanceof Error) {
|
|
139
|
-
throw error;
|
|
96
|
+
throw error;
|
|
140
97
|
}
|
|
141
98
|
throw new Error(`Failed to scan directory '${dir}': ${String(error)}`);
|
|
142
99
|
}
|
|
143
100
|
}
|
|
144
|
-
/**
|
|
145
|
-
* Loads a route module from a file and inserts it into the trie.
|
|
146
|
-
* @param entryPath The full file system path to the route module (route.ts).
|
|
147
|
-
* @param relativePath The relative path used to construct the route path.
|
|
148
|
-
* @returns {Promise<void>} A promise that resolves when the module is loaded and inserted.
|
|
149
|
-
* @throws {Error} If the route module fails to load or is invalid.
|
|
150
|
-
*/
|
|
151
101
|
async loadRouteModule(entryPath, relativePath) {
|
|
152
102
|
try {
|
|
153
|
-
// Convert the file path to a route path
|
|
154
103
|
const routePath = this.convertFilePathToRoute(relativePath);
|
|
155
104
|
console.info('Loading route:', routePath);
|
|
156
|
-
// Get the module path like "D:\\Projects\\src\\api\\users\\route.ts"
|
|
157
105
|
const modulePath = path.resolve(entryPath);
|
|
158
|
-
// Import the module
|
|
159
106
|
const routeModule = await import(modulePath);
|
|
160
|
-
// Variable to store the handlers for each method
|
|
161
107
|
const handlers = {};
|
|
162
|
-
// Loop through all the HTTP methods and add the handler to the handlers object
|
|
163
108
|
for (const method of HTTP_METHODS) {
|
|
164
109
|
if (typeof routeModule[method] === 'function') {
|
|
165
110
|
handlers[method] = routeModule[method];
|
|
166
111
|
}
|
|
167
112
|
}
|
|
113
|
+
const PREFLIGHT_METHODS = ['POST', 'PUT', 'DELETE', 'PATCH'];
|
|
114
|
+
let hasPreflightMethods = false;
|
|
115
|
+
for (let i = 0; i < PREFLIGHT_METHODS.length; i++) {
|
|
116
|
+
if (handlers[PREFLIGHT_METHODS[i]]) {
|
|
117
|
+
hasPreflightMethods = true;
|
|
118
|
+
break;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
if (hasPreflightMethods && typeof handlers.OPTIONS !== 'function') {
|
|
122
|
+
handlers.OPTIONS = () => new Response(null, { status: 204 });
|
|
123
|
+
}
|
|
168
124
|
const routeDef = {
|
|
169
125
|
path: routePath,
|
|
170
126
|
handlers,
|
|
@@ -179,35 +135,25 @@ export class ApiRouter {
|
|
|
179
135
|
throw new Error(`Failed to load route module '${entryPath}': ${String(error)}`);
|
|
180
136
|
}
|
|
181
137
|
}
|
|
182
|
-
/**
|
|
183
|
-
* Converts a file path to a route path by processing dynamic segments and wildcard segments applying the prefix.
|
|
184
|
-
* @param filePath The file path to convert (e.g., "users/[id]/route.ts" , "users/[...slug]/route.ts").
|
|
185
|
-
* @returns {string} The converted route path (e.g., "/users/:id" , "/users/*slug").
|
|
186
|
-
*/
|
|
187
138
|
convertFilePathToRoute(filePath) {
|
|
188
|
-
// Remove the "route.ts" suffix
|
|
189
139
|
if (filePath.endsWith('route.ts')) {
|
|
190
140
|
filePath = filePath.slice(0, -'route.ts'.length);
|
|
191
141
|
}
|
|
192
|
-
// Split path into segments
|
|
193
142
|
const segments = filePath.split(path.sep);
|
|
194
143
|
const resultSegments = [];
|
|
195
144
|
for (let segment of segments) {
|
|
196
145
|
if (!segment)
|
|
197
|
-
continue;
|
|
198
|
-
// Skip grouping segments (e.g., (group))
|
|
146
|
+
continue;
|
|
199
147
|
if (segment.startsWith(ROUTE_CONSTANTS.GROUPING_FOLDER_START) &&
|
|
200
148
|
segment.endsWith(ROUTE_CONSTANTS.GROUPING_FOLDER_END)) {
|
|
201
149
|
continue;
|
|
202
150
|
}
|
|
203
|
-
// Convert dynamic segments from [param] to :param
|
|
204
151
|
if (segment.startsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_START) &&
|
|
205
152
|
segment.endsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_END) &&
|
|
206
153
|
!segment.startsWith(ROUTE_CONSTANTS.WILDCARD_START)) {
|
|
207
154
|
const param = segment.slice(1, -1);
|
|
208
155
|
resultSegments.push(ROUTE_CONSTANTS.DYNAMIC_SEGMENT_PREFIX + param);
|
|
209
156
|
}
|
|
210
|
-
// Convert wildcard segments from [...] to *
|
|
211
157
|
else if (segment === ROUTE_CONSTANTS.WILDCARD_SIMPLE) {
|
|
212
158
|
resultSegments.push(ROUTE_CONSTANTS.WILDCARD_SEGMENT_PREFIX);
|
|
213
159
|
}
|
|
@@ -215,58 +161,41 @@ export class ApiRouter {
|
|
|
215
161
|
resultSegments.push(segment);
|
|
216
162
|
}
|
|
217
163
|
}
|
|
218
|
-
// Construct the route with leading slash
|
|
219
164
|
let route = '/' + resultSegments.join('/');
|
|
220
|
-
// Apply prefix if provided
|
|
221
165
|
if (this.prefix) {
|
|
222
166
|
const cleanPrefixStr = cleanPrefix(this.prefix);
|
|
223
167
|
route = '/' + cleanPrefixStr + route;
|
|
224
168
|
}
|
|
225
|
-
// Remove trailing slash unless it's the root
|
|
226
169
|
if (route !== '/' && route.endsWith('/')) {
|
|
227
170
|
route = route.slice(0, -1);
|
|
228
171
|
}
|
|
229
172
|
return route;
|
|
230
173
|
}
|
|
231
|
-
/**
|
|
232
|
-
* Resolves a request to a route definition and its parameters.
|
|
233
|
-
* @param pathname The normalized request pathname.
|
|
234
|
-
* @param method The uppercase HTTP method.
|
|
235
|
-
* @returns {{ route?: RouteDefinition; params: Record<string, string>; wildcardParams?: string[] }} An object containing the matched route (if any), extracted parameters, and wildcard segments (if applicable).
|
|
236
|
-
* @throws {Error} If the request URL is malformed.
|
|
237
|
-
*/
|
|
238
174
|
resolve(pathname, method) {
|
|
239
175
|
try {
|
|
240
176
|
const segments = pathname.split('/').filter(Boolean);
|
|
241
177
|
let node = this.root;
|
|
242
178
|
const params = {};
|
|
243
179
|
let wildcardSegments = [];
|
|
244
|
-
// Traverse the trie with proper prioritization
|
|
245
180
|
for (let i = 0; i < segments.length; i++) {
|
|
246
181
|
const segment = segments[i];
|
|
247
|
-
// Priority 1: Exact static match (highest priority)
|
|
248
182
|
if (node.children.has(segment)) {
|
|
249
183
|
node = node.children.get(segment);
|
|
250
184
|
}
|
|
251
|
-
// Priority 2: Dynamic parameter match (medium priority)
|
|
252
185
|
else if (node.paramChild) {
|
|
253
186
|
node = node.paramChild;
|
|
254
187
|
params[node.paramName] = segment;
|
|
255
188
|
}
|
|
256
|
-
// Priority 3: Collect remaining segments for wildcard (lowest priority)
|
|
257
189
|
else {
|
|
258
190
|
wildcardSegments = segments.slice(i);
|
|
259
191
|
break;
|
|
260
192
|
}
|
|
261
193
|
}
|
|
262
|
-
// Check if we have a route at the current node
|
|
263
194
|
if (node.route?.handlers[method]) {
|
|
264
195
|
return { route: node.route, params };
|
|
265
196
|
}
|
|
266
|
-
// If no route found but we have wildcard segments, check for wildcard route
|
|
267
197
|
if (wildcardSegments.length > 0 &&
|
|
268
198
|
node.wildcardChild?.route?.handlers[method]) {
|
|
269
|
-
// Return wildcard segments so they can be added to req.wildcardParams
|
|
270
199
|
return {
|
|
271
200
|
route: node.wildcardChild.route,
|
|
272
201
|
params,
|
|
@@ -276,7 +205,6 @@ export class ApiRouter {
|
|
|
276
205
|
return { params: {} };
|
|
277
206
|
}
|
|
278
207
|
catch (error) {
|
|
279
|
-
// Log the error for better debugging
|
|
280
208
|
console.error(`Error resolving API route for path "${pathname}":`, error);
|
|
281
209
|
return { params: {} };
|
|
282
210
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { ServerOptions, RouteDefinition } from '
|
|
1
|
+
import type { ServerOptions, RouteDefinition } from '../types/index';
|
|
2
2
|
export declare function generateOpenAPIDocument(apiRoutes: RouteDefinition[], options: ServerOptions): {
|
|
3
3
|
openapi: string;
|
|
4
4
|
info: {
|
package/dist/src/core/openapi.js
CHANGED
|
@@ -1,10 +1,4 @@
|
|
|
1
|
-
// Import stuff from Zod 4.x
|
|
2
1
|
import { toJSONSchema, ZodArray, ZodBoolean, ZodNumber, ZodObject, ZodOptional, ZodString, ZodType, } from 'zod';
|
|
3
|
-
/**
|
|
4
|
-
* Maps a Zod type to an OpenAPI schema type.
|
|
5
|
-
* @param zodType - The Zod type to map.
|
|
6
|
-
* @returns The OpenAPI schema type.
|
|
7
|
-
*/
|
|
8
2
|
function mapZodTypeToOpenAPIType(zodType) {
|
|
9
3
|
if (zodType instanceof ZodOptional) {
|
|
10
4
|
return mapZodTypeToOpenAPIType(zodType.unwrap());
|
|
@@ -19,59 +13,31 @@ function mapZodTypeToOpenAPIType(zodType) {
|
|
|
19
13
|
return 'array';
|
|
20
14
|
if (zodType instanceof ZodObject)
|
|
21
15
|
return 'object';
|
|
22
|
-
return 'string';
|
|
16
|
+
return 'string';
|
|
23
17
|
}
|
|
24
|
-
/**
|
|
25
|
-
* Builds an array of OpenAPI 3.0 parameters based on the Zod schema.
|
|
26
|
-
* For each property in the Zod schema, an OpenAPI parameter is constructed
|
|
27
|
-
* with the same name and required flag. The schema of the parameter is set
|
|
28
|
-
* to a string type.
|
|
29
|
-
* @param zodSchema - The Zod schema to construct parameters from. Can be undefined.
|
|
30
|
-
* @param location - The location of the parameter. Must be either "path" or "query".
|
|
31
|
-
* @returns An array of OpenAPI 3.0 parameter objects or an empty array if the Zod schema is undefined.
|
|
32
|
-
*/
|
|
33
18
|
function buildParameters(zodSchema, location) {
|
|
34
19
|
const parameters = [];
|
|
35
20
|
if (zodSchema && typeof zodSchema.shape === 'object') {
|
|
36
|
-
// Get the shape of the Zod schema
|
|
37
21
|
const shape = zodSchema.shape;
|
|
38
22
|
for (const key in shape) {
|
|
39
|
-
// Get the definition of the field
|
|
40
23
|
const fieldDef = shape[key];
|
|
41
|
-
// Determine if the field is optional
|
|
42
24
|
const isOptional = fieldDef instanceof ZodOptional;
|
|
43
|
-
// Map the Zod type to an OpenAPI schema type
|
|
44
25
|
const type = mapZodTypeToOpenAPIType(fieldDef);
|
|
45
26
|
parameters.push({
|
|
46
|
-
// Set the name of the parameter
|
|
47
27
|
name: key,
|
|
48
|
-
// Type of the parameter path or query
|
|
49
28
|
in: location,
|
|
50
|
-
// Set the required flag
|
|
51
29
|
required: !isOptional,
|
|
52
|
-
// Set the schema type
|
|
53
30
|
schema: { type },
|
|
54
|
-
// Description of the parameter
|
|
55
31
|
description: `${location} parameter ${key}`,
|
|
56
32
|
});
|
|
57
33
|
}
|
|
58
34
|
}
|
|
59
35
|
return parameters;
|
|
60
36
|
}
|
|
61
|
-
/**
|
|
62
|
-
* Builds a request body object for OpenAPI based on a Zod schema.
|
|
63
|
-
* Converts the Zod schema into JSON schema and constructs an OpenAPI
|
|
64
|
-
* requestBody object with content type "application/json".
|
|
65
|
-
* @param zodSchema - The Zod schema to convert into JSON schema.
|
|
66
|
-
* @returns An OpenAPI requestBody object, or undefined if no schema is provided.
|
|
67
|
-
*/
|
|
68
37
|
function buildRequestBody(zodSchema) {
|
|
69
|
-
// If no schema is provided, return undefined
|
|
70
38
|
if (!zodSchema)
|
|
71
39
|
return undefined;
|
|
72
|
-
// Convert the Zod schema to a JSON schema
|
|
73
40
|
const jsonSchema = toJSONSchema(zodSchema);
|
|
74
|
-
// Return the OpenAPI requestBody object
|
|
75
41
|
return {
|
|
76
42
|
content: {
|
|
77
43
|
'application/json': {
|
|
@@ -82,25 +48,11 @@ function buildRequestBody(zodSchema) {
|
|
|
82
48
|
required: true,
|
|
83
49
|
};
|
|
84
50
|
}
|
|
85
|
-
/**
|
|
86
|
-
* Converts a route path from colon-based dynamic segments to OpenAPI's curly brace syntax.
|
|
87
|
-
* Also handles wildcard routes.
|
|
88
|
-
*
|
|
89
|
-
* @param routePath The original route path with colon-based dynamic segments (e.g., "/user/:id") or wildcards (e.g., "/files/*").
|
|
90
|
-
* @returns The converted route path with curly brace syntax (e.g., "/user/{id}") or wildcard format (e.g., "/files/*").
|
|
91
|
-
*/
|
|
92
51
|
function convertPathForOpenAPI(routePath) {
|
|
93
|
-
// Fast path: if no special chars, return as-is
|
|
94
52
|
if (routePath.indexOf(':') === -1 && routePath.indexOf('*') === -1) {
|
|
95
53
|
return routePath;
|
|
96
54
|
}
|
|
97
|
-
// Replace occurrences of :param with {param}
|
|
98
55
|
let converted = routePath.replace(/:([a-zA-Z0-9_]+)/g, '{$1}');
|
|
99
|
-
// Handle wildcard routes
|
|
100
|
-
// OpenAPI 3.0 doesn't have official wildcard syntax, so we keep /* as-is
|
|
101
|
-
// This will display in Swagger as /api/files/* which is intuitive and common
|
|
102
|
-
// Alternative: convert to {path*} format if preferred
|
|
103
|
-
// converted = converted.replace(/\/\*$/g, '/{path*}');
|
|
104
56
|
return converted;
|
|
105
57
|
}
|
|
106
58
|
export function generateOpenAPIDocument(apiRoutes, options) {
|
|
@@ -113,22 +65,14 @@ export function generateOpenAPIDocument(apiRoutes, options) {
|
|
|
113
65
|
},
|
|
114
66
|
paths: {},
|
|
115
67
|
};
|
|
116
|
-
// Iterate over each route
|
|
117
68
|
for (const route of apiRoutes) {
|
|
118
|
-
// Convert colon-based dynamic segments to OpenAPI's {param} syntax
|
|
119
69
|
const openApiPath = convertPathForOpenAPI(route.path);
|
|
120
|
-
// Initialize path object if necessary
|
|
121
70
|
openapiDoc.paths[openApiPath] = openapiDoc.paths[openApiPath] || {};
|
|
122
|
-
// For each HTTP method in the route, add an OpenAPI operation.
|
|
123
71
|
for (const method in route.handlers) {
|
|
124
|
-
// Convert HTTP method to lowercase
|
|
125
72
|
const lowerMethod = method.toLowerCase();
|
|
126
|
-
// Use provided openapi metadata if available; else, fallback to auto-generated values.
|
|
127
73
|
const methodMeta = route.openapi?.[lowerMethod] || {};
|
|
128
|
-
// Generate an operationId: e.g., "get_api_product"
|
|
129
74
|
const operationId = methodMeta.operationId ||
|
|
130
75
|
`${lowerMethod}_${route.path.replace(/[\/:]/g, '_')}`;
|
|
131
|
-
// Build parameters for both path and query from the schema.
|
|
132
76
|
let parameters = [];
|
|
133
77
|
if (route.schema && route.schema[lowerMethod]) {
|
|
134
78
|
const schemaDef = route.schema[lowerMethod];
|
|
@@ -137,7 +81,6 @@ export function generateOpenAPIDocument(apiRoutes, options) {
|
|
|
137
81
|
...buildParameters(schemaDef.query, 'query'),
|
|
138
82
|
];
|
|
139
83
|
}
|
|
140
|
-
// Build requestBody if a body schema exists.
|
|
141
84
|
let requestBody = undefined;
|
|
142
85
|
if (route.schema && route.schema[lowerMethod]?.body) {
|
|
143
86
|
requestBody = buildRequestBody(route.schema[lowerMethod].body);
|
|
@@ -1,59 +1,16 @@
|
|
|
1
|
-
import type { PageDefinition } from '
|
|
2
|
-
/**
|
|
3
|
-
* PageRouter class for handling file-based page routing.
|
|
4
|
-
* Loads pages from a directory structure and matches requests to the appropriate page handlers.
|
|
5
|
-
* Supports dynamic segments (e.g., [id]) and uses default exports as page handlers.
|
|
6
|
-
*/
|
|
1
|
+
import type { PageDefinition } from '../types/index';
|
|
7
2
|
export declare class PageRouter {
|
|
8
3
|
private pagesDir;
|
|
9
4
|
private prefix;
|
|
10
|
-
/** Array of loaded page definitions */
|
|
11
5
|
pages: PageDefinition[];
|
|
12
|
-
/**
|
|
13
|
-
* Constructor for the PageRouter class.
|
|
14
|
-
* @param pagesDir The directory path where page modules are located.
|
|
15
|
-
* @param prefix Optional prefix to prepend to all routes (e.g., "pages" becomes "/pages/...").
|
|
16
|
-
*/
|
|
17
6
|
constructor(pagesDir: string, prefix?: string);
|
|
18
|
-
/**
|
|
19
|
-
* Loads page modules from the specified directory and adds them to the pages array.
|
|
20
|
-
* After loading, sorts the pages to prioritize static routes over dynamic ones based on specificity.
|
|
21
|
-
* @returns A promise that resolves when all page modules have been loaded and sorted.
|
|
22
|
-
*/
|
|
23
7
|
loadPages(): Promise<void>;
|
|
24
|
-
/**
|
|
25
|
-
* Recursively scans the directory for page modules and adds them to the pages array.
|
|
26
|
-
* @param dir The current directory to scan.
|
|
27
|
-
* @param basePath The base path for constructing the route path.
|
|
28
|
-
*/
|
|
29
8
|
private scanDirectory;
|
|
30
|
-
/**
|
|
31
|
-
* Converts a file path to a route path by processing dynamic segments,
|
|
32
|
-
* removing certain directory indicators, and applying a prefix if specified.
|
|
33
|
-
* @param filePath The file path to convert into a route path.
|
|
34
|
-
* @returns The converted route path string (before extension cleaning).
|
|
35
|
-
*/
|
|
36
9
|
private convertFilePathToRoute;
|
|
37
|
-
/**
|
|
38
|
-
* Cleans a route path by handling index files and removing extensions.
|
|
39
|
-
* @param routePath The route path to clean
|
|
40
|
-
* @returns The cleaned route path
|
|
41
|
-
*/
|
|
42
10
|
private cleanRoutePath;
|
|
43
|
-
/**
|
|
44
|
-
* Resolves the given request by finding a matching page and extracting dynamic parameters.
|
|
45
|
-
* @param request The request to resolve.
|
|
46
|
-
* @returns An object containing the matched page and parameters, or an empty params object if no match.
|
|
47
|
-
*/
|
|
48
11
|
resolve(request: Request): {
|
|
49
12
|
page?: PageDefinition;
|
|
50
13
|
params: Record<string, string>;
|
|
51
14
|
};
|
|
52
|
-
/**
|
|
53
|
-
* Checks if the request path matches the page path, extracting dynamic parameters if matched.
|
|
54
|
-
* @param requestPath The request path to check.
|
|
55
|
-
* @param pagePath The page path to match against.
|
|
56
|
-
* @returns A record of dynamic parameters if matched, otherwise null.
|
|
57
|
-
*/
|
|
58
15
|
private matchRoute;
|
|
59
16
|
}
|