burger-api 0.5.1 → 0.5.2
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 +1 -2
- package/dist/src/core/api-router.d.ts +53 -0
- package/dist/src/core/api-router.js +93 -3
- package/dist/src/core/openapi.js +58 -1
- package/dist/src/core/page-router.d.ts +43 -0
- package/dist/src/core/page-router.js +72 -1
- package/dist/src/core/server.d.ts +10 -0
- package/dist/src/core/server.js +16 -0
- package/dist/src/index.d.ts +57 -0
- package/dist/src/index.js +154 -3
- package/dist/src/middleware/validator.d.ts +12 -0
- package/dist/src/middleware/validator.js +59 -9
- package/dist/src/types/index.d.ts +143 -0
- package/dist/src/utils/error.d.ts +16 -0
- package/dist/src/utils/error.js +24 -0
- package/dist/src/utils/index.d.ts +17 -0
- package/dist/src/utils/index.js +22 -0
- package/dist/src/utils/response.d.ts +9 -0
- package/dist/src/utils/response.js +9 -0
- package/dist/src/utils/routing.d.ts +28 -0
- package/dist/src/utils/routing.js +41 -3
- package/dist/src/utils/wildcard.d.ts +11 -0
- package/dist/src/utils/wildcard.js +42 -6
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -66,11 +66,10 @@ burger-api is built to offer a robust developer experience through:
|
|
|
66
66
|
|
|
67
67
|
## 📣 Changelog
|
|
68
68
|
|
|
69
|
-
### Latest Version: 0.5.
|
|
69
|
+
### Latest Version: 0.5.2 (November 9, 2025)
|
|
70
70
|
|
|
71
71
|
- 🔧 **Internal Improvements:**
|
|
72
72
|
- Refactored wildcard parameter extraction logic into reusable utility functions
|
|
73
|
-
- Enabled `removeComments` in build configuration to reduce bundle size
|
|
74
73
|
- Added test suites and README files for all example projects
|
|
75
74
|
|
|
76
75
|
### Previous Version: 0.5.0 (November 1, 2025)
|
|
@@ -1,15 +1,68 @@
|
|
|
1
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
|
+
*/
|
|
2
8
|
export declare class ApiRouter {
|
|
3
9
|
private routesDir;
|
|
4
10
|
private prefix;
|
|
11
|
+
/** The root of the trie where all routes will begin*/
|
|
5
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
|
+
*/
|
|
6
19
|
constructor(routesDir: string, prefix?: string);
|
|
20
|
+
/**
|
|
21
|
+
* Getter for the routes trie.
|
|
22
|
+
* @returns The root of the trie.
|
|
23
|
+
*/
|
|
7
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
|
+
*/
|
|
8
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
|
+
*/
|
|
9
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
|
+
*/
|
|
10
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
|
+
*/
|
|
11
52
|
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
|
+
*/
|
|
12
58
|
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
|
+
*/
|
|
13
66
|
resolve(pathname: string, method: string): {
|
|
14
67
|
route?: RouteDefinition;
|
|
15
68
|
params: Record<string, string>;
|
|
@@ -1,10 +1,25 @@
|
|
|
1
|
+
// Import stuff from node
|
|
1
2
|
import { readdir } from 'fs/promises';
|
|
2
3
|
import * as path from 'path';
|
|
4
|
+
// Import utils
|
|
3
5
|
import { cleanPrefix, normalizePath, ROUTE_CONSTANTS, HTTP_METHODS, } from '../utils/index';
|
|
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
|
+
*/
|
|
4
12
|
export class ApiRouter {
|
|
5
13
|
routesDir;
|
|
6
14
|
prefix;
|
|
15
|
+
/** The root of the trie where all routes will begin*/
|
|
7
16
|
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
|
+
*/
|
|
8
23
|
constructor(routesDir, prefix = '') {
|
|
9
24
|
this.routesDir = routesDir;
|
|
10
25
|
this.prefix = prefix;
|
|
@@ -12,9 +27,18 @@ export class ApiRouter {
|
|
|
12
27
|
throw new Error('Routes directory path is required');
|
|
13
28
|
}
|
|
14
29
|
}
|
|
30
|
+
/**
|
|
31
|
+
* Getter for the routes trie.
|
|
32
|
+
* @returns The root of the trie.
|
|
33
|
+
*/
|
|
15
34
|
get routes() {
|
|
16
35
|
return this.root;
|
|
17
36
|
}
|
|
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
|
+
*/
|
|
18
42
|
async loadRoutes() {
|
|
19
43
|
try {
|
|
20
44
|
await this.scanDirectory(this.routesDir);
|
|
@@ -24,11 +48,17 @@ export class ApiRouter {
|
|
|
24
48
|
throw new Error(`Failed to load routes: ${errorMessage}`);
|
|
25
49
|
}
|
|
26
50
|
}
|
|
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
|
+
*/
|
|
27
56
|
insertRoute(routeDef) {
|
|
28
57
|
let node = this.root;
|
|
29
58
|
const segments = routeDef.path.split('/').filter(Boolean);
|
|
30
59
|
for (const segment of segments) {
|
|
31
60
|
if (segment.startsWith(':')) {
|
|
61
|
+
// Handle dynamic segments (:param)
|
|
32
62
|
if (!node.paramChild) {
|
|
33
63
|
node.paramChild = { children: new Map() };
|
|
34
64
|
}
|
|
@@ -36,13 +66,15 @@ export class ApiRouter {
|
|
|
36
66
|
node.paramName = segment.slice(1);
|
|
37
67
|
}
|
|
38
68
|
else if (segment.startsWith('*')) {
|
|
69
|
+
// Handle wildcard segments (*param)
|
|
39
70
|
if (!node.wildcardChild) {
|
|
40
71
|
node.wildcardChild = { children: new Map() };
|
|
41
72
|
}
|
|
42
73
|
node = node.wildcardChild;
|
|
43
|
-
node.isWildcard = true;
|
|
74
|
+
node.isWildcard = true; // Mark as wildcard route
|
|
44
75
|
}
|
|
45
76
|
else {
|
|
77
|
+
// Handle static segments
|
|
46
78
|
if (!node.children.has(segment)) {
|
|
47
79
|
node.children.set(segment, { children: new Map() });
|
|
48
80
|
}
|
|
@@ -51,7 +83,15 @@ export class ApiRouter {
|
|
|
51
83
|
}
|
|
52
84
|
node.route = routeDef;
|
|
53
85
|
}
|
|
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
|
+
*/
|
|
54
93
|
async scanDirectory(dir, basePath = '') {
|
|
94
|
+
// Track route types at this directory level to prevent conflicts
|
|
55
95
|
let dynamicFolderFound = false;
|
|
56
96
|
let wildcardFolderFound = false;
|
|
57
97
|
try {
|
|
@@ -60,10 +100,12 @@ export class ApiRouter {
|
|
|
60
100
|
const entryPath = path.join(dir, entry.name);
|
|
61
101
|
const relativePath = path.join(basePath, entry.name);
|
|
62
102
|
if (entry.isDirectory()) {
|
|
103
|
+
// Check if this is a dynamic or wildcard directory
|
|
63
104
|
const isDynamic = entry.name.startsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_START) &&
|
|
64
105
|
entry.name.endsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_END) &&
|
|
65
106
|
entry.name !== ROUTE_CONSTANTS.WILDCARD_SIMPLE;
|
|
66
107
|
const isWildcard = entry.name === ROUTE_CONSTANTS.WILDCARD_SIMPLE;
|
|
108
|
+
// Prevent conflicts between dynamic and wildcard routes
|
|
67
109
|
if (isDynamic && wildcardFolderFound) {
|
|
68
110
|
throw new Error(`Cannot mix dynamic and wildcard route folders in the same directory. ` +
|
|
69
111
|
`Found dynamic folder '${entry.name}' but wildcard folder already exists in '${dir}'.`);
|
|
@@ -80,6 +122,7 @@ export class ApiRouter {
|
|
|
80
122
|
throw new Error(`Multiple wildcard route folders found in the same directory: ` +
|
|
81
123
|
`'${entry.name}' conflicts with another wildcard folder in '${dir}'.`);
|
|
82
124
|
}
|
|
125
|
+
// Update flags
|
|
83
126
|
if (isDynamic)
|
|
84
127
|
dynamicFolderFound = true;
|
|
85
128
|
if (isWildcard)
|
|
@@ -93,32 +136,51 @@ export class ApiRouter {
|
|
|
93
136
|
}
|
|
94
137
|
catch (error) {
|
|
95
138
|
if (error instanceof Error) {
|
|
96
|
-
throw error;
|
|
139
|
+
throw error; // Re-throw specific errors we created
|
|
97
140
|
}
|
|
98
141
|
throw new Error(`Failed to scan directory '${dir}': ${String(error)}`);
|
|
99
142
|
}
|
|
100
143
|
}
|
|
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
|
+
*/
|
|
101
151
|
async loadRouteModule(entryPath, relativePath) {
|
|
102
152
|
try {
|
|
153
|
+
// Convert the file path to a route path
|
|
103
154
|
const routePath = this.convertFilePathToRoute(relativePath);
|
|
104
155
|
console.info('Loading route:', routePath);
|
|
156
|
+
// Get the module path like "D:\\Projects\\src\\api\\users\\route.ts"
|
|
105
157
|
const modulePath = path.resolve(entryPath);
|
|
158
|
+
// Import the module
|
|
106
159
|
const routeModule = await import(modulePath);
|
|
160
|
+
// Variable to store the handlers for each method
|
|
107
161
|
const handlers = {};
|
|
162
|
+
// Loop through all the HTTP methods and add the handler to the handlers object
|
|
108
163
|
for (const method of HTTP_METHODS) {
|
|
109
164
|
if (typeof routeModule[method] === 'function') {
|
|
110
165
|
handlers[method] = routeModule[method];
|
|
111
166
|
}
|
|
112
167
|
}
|
|
168
|
+
// Auto-inject minimal OPTIONS handler for CORS preflight when needed
|
|
169
|
+
// Only if route defines any preflight-triggering methods and lacks an OPTIONS handler
|
|
113
170
|
const PREFLIGHT_METHODS = ['POST', 'PUT', 'DELETE', 'PATCH'];
|
|
114
171
|
let hasPreflightMethods = false;
|
|
172
|
+
// Manual loop is slightly faster than Array.prototype.some in tight paths
|
|
115
173
|
for (let i = 0; i < PREFLIGHT_METHODS.length; i++) {
|
|
116
174
|
if (handlers[PREFLIGHT_METHODS[i]]) {
|
|
117
175
|
hasPreflightMethods = true;
|
|
118
176
|
break;
|
|
119
177
|
}
|
|
120
178
|
}
|
|
179
|
+
// If the route defines any preflight-triggering methods and lacks an OPTIONS handler, auto-add an OPTIONS handler
|
|
121
180
|
if (hasPreflightMethods && typeof handlers.OPTIONS !== 'function') {
|
|
181
|
+
// if (process.env.NODE_ENV !== 'production') {
|
|
182
|
+
// console.debug('Auto-added OPTIONS handler for route:', routePath);
|
|
183
|
+
// }
|
|
122
184
|
handlers.OPTIONS = () => new Response(null, { status: 204 });
|
|
123
185
|
}
|
|
124
186
|
const routeDef = {
|
|
@@ -135,25 +197,35 @@ export class ApiRouter {
|
|
|
135
197
|
throw new Error(`Failed to load route module '${entryPath}': ${String(error)}`);
|
|
136
198
|
}
|
|
137
199
|
}
|
|
200
|
+
/**
|
|
201
|
+
* Converts a file path to a route path by processing dynamic segments and wildcard segments applying the prefix.
|
|
202
|
+
* @param filePath The file path to convert (e.g., "users/[id]/route.ts" , "users/[...slug]/route.ts").
|
|
203
|
+
* @returns {string} The converted route path (e.g., "/users/:id" , "/users/*slug").
|
|
204
|
+
*/
|
|
138
205
|
convertFilePathToRoute(filePath) {
|
|
206
|
+
// Remove the "route.ts" suffix
|
|
139
207
|
if (filePath.endsWith('route.ts')) {
|
|
140
208
|
filePath = filePath.slice(0, -'route.ts'.length);
|
|
141
209
|
}
|
|
210
|
+
// Split path into segments
|
|
142
211
|
const segments = filePath.split(path.sep);
|
|
143
212
|
const resultSegments = [];
|
|
144
213
|
for (let segment of segments) {
|
|
145
214
|
if (!segment)
|
|
146
|
-
continue;
|
|
215
|
+
continue; // Skip empty segments
|
|
216
|
+
// Skip grouping segments (e.g., (group))
|
|
147
217
|
if (segment.startsWith(ROUTE_CONSTANTS.GROUPING_FOLDER_START) &&
|
|
148
218
|
segment.endsWith(ROUTE_CONSTANTS.GROUPING_FOLDER_END)) {
|
|
149
219
|
continue;
|
|
150
220
|
}
|
|
221
|
+
// Convert dynamic segments from [param] to :param
|
|
151
222
|
if (segment.startsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_START) &&
|
|
152
223
|
segment.endsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_END) &&
|
|
153
224
|
!segment.startsWith(ROUTE_CONSTANTS.WILDCARD_START)) {
|
|
154
225
|
const param = segment.slice(1, -1);
|
|
155
226
|
resultSegments.push(ROUTE_CONSTANTS.DYNAMIC_SEGMENT_PREFIX + param);
|
|
156
227
|
}
|
|
228
|
+
// Convert wildcard segments from [...] to *
|
|
157
229
|
else if (segment === ROUTE_CONSTANTS.WILDCARD_SIMPLE) {
|
|
158
230
|
resultSegments.push(ROUTE_CONSTANTS.WILDCARD_SEGMENT_PREFIX);
|
|
159
231
|
}
|
|
@@ -161,41 +233,58 @@ export class ApiRouter {
|
|
|
161
233
|
resultSegments.push(segment);
|
|
162
234
|
}
|
|
163
235
|
}
|
|
236
|
+
// Construct the route with leading slash
|
|
164
237
|
let route = '/' + resultSegments.join('/');
|
|
238
|
+
// Apply prefix if provided
|
|
165
239
|
if (this.prefix) {
|
|
166
240
|
const cleanPrefixStr = cleanPrefix(this.prefix);
|
|
167
241
|
route = '/' + cleanPrefixStr + route;
|
|
168
242
|
}
|
|
243
|
+
// Remove trailing slash unless it's the root
|
|
169
244
|
if (route !== '/' && route.endsWith('/')) {
|
|
170
245
|
route = route.slice(0, -1);
|
|
171
246
|
}
|
|
172
247
|
return route;
|
|
173
248
|
}
|
|
249
|
+
/**
|
|
250
|
+
* Resolves a request to a route definition and its parameters.
|
|
251
|
+
* @param pathname The normalized request pathname.
|
|
252
|
+
* @param method The uppercase HTTP method.
|
|
253
|
+
* @returns {{ route?: RouteDefinition; params: Record<string, string>; wildcardParams?: string[] }} An object containing the matched route (if any), extracted parameters, and wildcard segments (if applicable).
|
|
254
|
+
* @throws {Error} If the request URL is malformed.
|
|
255
|
+
*/
|
|
174
256
|
resolve(pathname, method) {
|
|
175
257
|
try {
|
|
176
258
|
const segments = pathname.split('/').filter(Boolean);
|
|
177
259
|
let node = this.root;
|
|
178
260
|
const params = {};
|
|
179
261
|
let wildcardSegments = [];
|
|
262
|
+
// Traverse the trie with proper prioritization
|
|
180
263
|
for (let i = 0; i < segments.length; i++) {
|
|
181
264
|
const segment = segments[i];
|
|
265
|
+
// Priority 1: Exact static match (highest priority)
|
|
182
266
|
if (node.children.has(segment)) {
|
|
183
267
|
node = node.children.get(segment);
|
|
184
268
|
}
|
|
269
|
+
// Priority 2: Dynamic parameter match (medium priority)
|
|
185
270
|
else if (node.paramChild) {
|
|
186
271
|
node = node.paramChild;
|
|
187
272
|
params[node.paramName] = segment;
|
|
188
273
|
}
|
|
274
|
+
// Priority 3: Collect remaining segments for wildcard (lowest priority)
|
|
189
275
|
else {
|
|
190
276
|
wildcardSegments = segments.slice(i);
|
|
191
277
|
break;
|
|
192
278
|
}
|
|
193
279
|
}
|
|
280
|
+
// Check if we have a route at the current node
|
|
194
281
|
if (node.route?.handlers[method]) {
|
|
195
282
|
return { route: node.route, params };
|
|
196
283
|
}
|
|
284
|
+
// If no route found but we have wildcard segments, check for wildcard route
|
|
197
285
|
if (wildcardSegments.length > 0 &&
|
|
198
286
|
node.wildcardChild?.route?.handlers[method]) {
|
|
287
|
+
// Return wildcard segments so they can be added to req.wildcardParams
|
|
199
288
|
return {
|
|
200
289
|
route: node.wildcardChild.route,
|
|
201
290
|
params,
|
|
@@ -205,6 +294,7 @@ export class ApiRouter {
|
|
|
205
294
|
return { params: {} };
|
|
206
295
|
}
|
|
207
296
|
catch (error) {
|
|
297
|
+
// Log the error for better debugging
|
|
208
298
|
console.error(`Error resolving API route for path "${pathname}":`, error);
|
|
209
299
|
return { params: {} };
|
|
210
300
|
}
|
package/dist/src/core/openapi.js
CHANGED
|
@@ -1,4 +1,10 @@
|
|
|
1
|
+
// Import stuff from Zod 4.x
|
|
1
2
|
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
|
+
*/
|
|
2
8
|
function mapZodTypeToOpenAPIType(zodType) {
|
|
3
9
|
if (zodType instanceof ZodOptional) {
|
|
4
10
|
return mapZodTypeToOpenAPIType(zodType.unwrap());
|
|
@@ -13,31 +19,59 @@ function mapZodTypeToOpenAPIType(zodType) {
|
|
|
13
19
|
return 'array';
|
|
14
20
|
if (zodType instanceof ZodObject)
|
|
15
21
|
return 'object';
|
|
16
|
-
return 'string';
|
|
22
|
+
return 'string'; // fallback
|
|
17
23
|
}
|
|
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
|
+
*/
|
|
18
33
|
function buildParameters(zodSchema, location) {
|
|
19
34
|
const parameters = [];
|
|
20
35
|
if (zodSchema && typeof zodSchema.shape === 'object') {
|
|
36
|
+
// Get the shape of the Zod schema
|
|
21
37
|
const shape = zodSchema.shape;
|
|
22
38
|
for (const key in shape) {
|
|
39
|
+
// Get the definition of the field
|
|
23
40
|
const fieldDef = shape[key];
|
|
41
|
+
// Determine if the field is optional
|
|
24
42
|
const isOptional = fieldDef instanceof ZodOptional;
|
|
43
|
+
// Map the Zod type to an OpenAPI schema type
|
|
25
44
|
const type = mapZodTypeToOpenAPIType(fieldDef);
|
|
26
45
|
parameters.push({
|
|
46
|
+
// Set the name of the parameter
|
|
27
47
|
name: key,
|
|
48
|
+
// Type of the parameter path or query
|
|
28
49
|
in: location,
|
|
50
|
+
// Set the required flag
|
|
29
51
|
required: !isOptional,
|
|
52
|
+
// Set the schema type
|
|
30
53
|
schema: { type },
|
|
54
|
+
// Description of the parameter
|
|
31
55
|
description: `${location} parameter ${key}`,
|
|
32
56
|
});
|
|
33
57
|
}
|
|
34
58
|
}
|
|
35
59
|
return parameters;
|
|
36
60
|
}
|
|
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
|
+
*/
|
|
37
68
|
function buildRequestBody(zodSchema) {
|
|
69
|
+
// If no schema is provided, return undefined
|
|
38
70
|
if (!zodSchema)
|
|
39
71
|
return undefined;
|
|
72
|
+
// Convert the Zod schema to a JSON schema
|
|
40
73
|
const jsonSchema = toJSONSchema(zodSchema);
|
|
74
|
+
// Return the OpenAPI requestBody object
|
|
41
75
|
return {
|
|
42
76
|
content: {
|
|
43
77
|
'application/json': {
|
|
@@ -48,11 +82,25 @@ function buildRequestBody(zodSchema) {
|
|
|
48
82
|
required: true,
|
|
49
83
|
};
|
|
50
84
|
}
|
|
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
|
+
*/
|
|
51
92
|
function convertPathForOpenAPI(routePath) {
|
|
93
|
+
// Fast path: if no special chars, return as-is
|
|
52
94
|
if (routePath.indexOf(':') === -1 && routePath.indexOf('*') === -1) {
|
|
53
95
|
return routePath;
|
|
54
96
|
}
|
|
97
|
+
// Replace occurrences of :param with {param}
|
|
55
98
|
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*}');
|
|
56
104
|
return converted;
|
|
57
105
|
}
|
|
58
106
|
export function generateOpenAPIDocument(apiRoutes, options) {
|
|
@@ -65,14 +113,22 @@ export function generateOpenAPIDocument(apiRoutes, options) {
|
|
|
65
113
|
},
|
|
66
114
|
paths: {},
|
|
67
115
|
};
|
|
116
|
+
// Iterate over each route
|
|
68
117
|
for (const route of apiRoutes) {
|
|
118
|
+
// Convert colon-based dynamic segments to OpenAPI's {param} syntax
|
|
69
119
|
const openApiPath = convertPathForOpenAPI(route.path);
|
|
120
|
+
// Initialize path object if necessary
|
|
70
121
|
openapiDoc.paths[openApiPath] = openapiDoc.paths[openApiPath] || {};
|
|
122
|
+
// For each HTTP method in the route, add an OpenAPI operation.
|
|
71
123
|
for (const method in route.handlers) {
|
|
124
|
+
// Convert HTTP method to lowercase
|
|
72
125
|
const lowerMethod = method.toLowerCase();
|
|
126
|
+
// Use provided openapi metadata if available; else, fallback to auto-generated values.
|
|
73
127
|
const methodMeta = route.openapi?.[lowerMethod] || {};
|
|
128
|
+
// Generate an operationId: e.g., "get_api_product"
|
|
74
129
|
const operationId = methodMeta.operationId ||
|
|
75
130
|
`${lowerMethod}_${route.path.replace(/[\/:]/g, '_')}`;
|
|
131
|
+
// Build parameters for both path and query from the schema.
|
|
76
132
|
let parameters = [];
|
|
77
133
|
if (route.schema && route.schema[lowerMethod]) {
|
|
78
134
|
const schemaDef = route.schema[lowerMethod];
|
|
@@ -81,6 +137,7 @@ export function generateOpenAPIDocument(apiRoutes, options) {
|
|
|
81
137
|
...buildParameters(schemaDef.query, 'query'),
|
|
82
138
|
];
|
|
83
139
|
}
|
|
140
|
+
// Build requestBody if a body schema exists.
|
|
84
141
|
let requestBody = undefined;
|
|
85
142
|
if (route.schema && route.schema[lowerMethod]?.body) {
|
|
86
143
|
requestBody = buildRequestBody(route.schema[lowerMethod].body);
|
|
@@ -1,16 +1,59 @@
|
|
|
1
1
|
import type { PageDefinition } from '../types/index';
|
|
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
|
+
*/
|
|
2
7
|
export declare class PageRouter {
|
|
3
8
|
private pagesDir;
|
|
4
9
|
private prefix;
|
|
10
|
+
/** Array of loaded page definitions */
|
|
5
11
|
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
|
+
*/
|
|
6
17
|
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
|
+
*/
|
|
7
23
|
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
|
+
*/
|
|
8
29
|
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
|
+
*/
|
|
9
36
|
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
|
+
*/
|
|
10
42
|
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
|
+
*/
|
|
11
48
|
resolve(request: Request): {
|
|
12
49
|
page?: PageDefinition;
|
|
13
50
|
params: Record<string, string>;
|
|
14
51
|
};
|
|
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
|
+
*/
|
|
15
58
|
private matchRoute;
|
|
16
59
|
}
|