burger-api 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -2
- package/dist/src/core/api-router.d.ts +7 -6
- package/dist/src/core/api-router.js +75 -20
- package/dist/src/core/openapi.js +49 -14
- package/dist/src/core/page-router.js +1 -1
- package/dist/src/core/server.js +1 -1
- package/dist/src/index.d.ts +1 -1
- package/dist/src/index.js +168 -10
- package/dist/src/middleware/validator.d.ts +12 -0
- package/dist/src/middleware/validator.js +83 -60
- package/dist/src/utils/error.js +1 -1
- package/dist/src/utils/index.d.ts +1 -1
- package/dist/src/utils/index.js +1 -1
- package/dist/src/utils/routing.d.ts +6 -1
- package/dist/src/utils/routing.js +22 -3
- package/package.json +88 -88
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
|
|
@@ -59,7 +59,17 @@ burger-api is built to offer a robust developer experience through:
|
|
|
59
59
|
|
|
60
60
|
## 📣 Changelog
|
|
61
61
|
|
|
62
|
-
### Latest Version: 0.
|
|
62
|
+
### Latest Version: 0.4.0 (October 21, 2025)
|
|
63
|
+
|
|
64
|
+
- 🎯 **Wildcard Routes:**
|
|
65
|
+
- Added wildcard routes using `[...]` folder name - matches any path after it
|
|
66
|
+
- Create routes that handle multiple path segments automatically
|
|
67
|
+
- Access all matched path parts through `wildcardParams` in your request
|
|
68
|
+
- Routes are matched in order: exact paths first, then dynamic routes (like `[id]`), then wildcards last
|
|
69
|
+
- Works inside dynamic routes too (example: `/api/users/[userId]/[...]`)
|
|
70
|
+
- View wildcard routes in OpenAPI docs and Swagger UI
|
|
71
|
+
|
|
72
|
+
### Version 0.3.0 (August 15, 2025)
|
|
63
73
|
|
|
64
74
|
- 🔧 **Updated Zod to version 4:**
|
|
65
75
|
- Updated Zod version from 3.x to 4.x
|
|
@@ -2,8 +2,8 @@ import type { RouteDefinition, TrieNode } from '@burgerTypes';
|
|
|
2
2
|
/**
|
|
3
3
|
* ApiRouter class for handling file-based routing.
|
|
4
4
|
* Loads routes from a directory structure and matches requests to the appropriate route handlers.
|
|
5
|
-
* Supports dynamic segments (e.g., [id]) and HTTP method handlers.
|
|
6
|
-
* Routes are sorted to prioritize static routes over dynamic ones to prevent overlapping route issues.
|
|
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
7
|
*/
|
|
8
8
|
export declare class ApiRouter {
|
|
9
9
|
private routesDir;
|
|
@@ -51,20 +51,21 @@ export declare class ApiRouter {
|
|
|
51
51
|
*/
|
|
52
52
|
private loadRouteModule;
|
|
53
53
|
/**
|
|
54
|
-
* Converts a file path to a route path by processing dynamic segments and applying the prefix.
|
|
55
|
-
* @param filePath The file path to convert (e.g., "users/[id]/route.ts").
|
|
56
|
-
* @returns {string} The converted route path (e.g., "/users/:id").
|
|
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
57
|
*/
|
|
58
58
|
private convertFilePathToRoute;
|
|
59
59
|
/**
|
|
60
60
|
* Resolves a request to a route definition and its parameters.
|
|
61
61
|
* @param pathname The normalized request pathname.
|
|
62
62
|
* @param method The uppercase HTTP method.
|
|
63
|
-
* @returns {{ route?: RouteDefinition; params: Record<string, string
|
|
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
64
|
* @throws {Error} If the request URL is malformed.
|
|
65
65
|
*/
|
|
66
66
|
resolve(pathname: string, method: string): {
|
|
67
67
|
route?: RouteDefinition;
|
|
68
68
|
params: Record<string, string>;
|
|
69
|
+
wildcardParams?: string[];
|
|
69
70
|
};
|
|
70
71
|
}
|
|
@@ -2,12 +2,12 @@
|
|
|
2
2
|
import { readdir } from 'fs/promises';
|
|
3
3
|
import * as path from 'path';
|
|
4
4
|
// Import utils
|
|
5
|
-
import { cleanPrefix, normalizePath, ROUTE_CONSTANTS, HTTP_METHODS, } from '
|
|
5
|
+
import { cleanPrefix, normalizePath, ROUTE_CONSTANTS, HTTP_METHODS, } from '../utils/index.js';
|
|
6
6
|
/**
|
|
7
7
|
* ApiRouter class for handling file-based routing.
|
|
8
8
|
* Loads routes from a directory structure and matches requests to the appropriate route handlers.
|
|
9
|
-
* Supports dynamic segments (e.g., [id]) and HTTP method handlers.
|
|
10
|
-
* Routes are sorted to prioritize static routes over dynamic ones to prevent overlapping route issues.
|
|
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
11
|
*/
|
|
12
12
|
export class ApiRouter {
|
|
13
13
|
routesDir;
|
|
@@ -58,13 +58,23 @@ export class ApiRouter {
|
|
|
58
58
|
const segments = routeDef.path.split('/').filter(Boolean);
|
|
59
59
|
for (const segment of segments) {
|
|
60
60
|
if (segment.startsWith(':')) {
|
|
61
|
+
// Handle dynamic segments (:param)
|
|
61
62
|
if (!node.paramChild) {
|
|
62
63
|
node.paramChild = { children: new Map() };
|
|
63
64
|
}
|
|
64
65
|
node = node.paramChild;
|
|
65
66
|
node.paramName = segment.slice(1);
|
|
66
67
|
}
|
|
68
|
+
else if (segment.startsWith('*')) {
|
|
69
|
+
// Handle wildcard segments (*param)
|
|
70
|
+
if (!node.wildcardChild) {
|
|
71
|
+
node.wildcardChild = { children: new Map() };
|
|
72
|
+
}
|
|
73
|
+
node = node.wildcardChild;
|
|
74
|
+
node.isWildcard = true; // Mark as wildcard route
|
|
75
|
+
}
|
|
67
76
|
else {
|
|
77
|
+
// Handle static segments
|
|
68
78
|
if (!node.children.has(segment)) {
|
|
69
79
|
node.children.set(segment, { children: new Map() });
|
|
70
80
|
}
|
|
@@ -81,22 +91,42 @@ export class ApiRouter {
|
|
|
81
91
|
* @throws {Error} If multiple dynamic folders are found at the same level or if directory access fails.
|
|
82
92
|
*/
|
|
83
93
|
async scanDirectory(dir, basePath = '') {
|
|
84
|
-
// Track
|
|
94
|
+
// Track route types at this directory level to prevent conflicts
|
|
85
95
|
let dynamicFolderFound = false;
|
|
96
|
+
let wildcardFolderFound = false;
|
|
86
97
|
try {
|
|
87
98
|
const entries = await readdir(dir, { withFileTypes: true });
|
|
88
99
|
for (const entry of entries) {
|
|
89
100
|
const entryPath = path.join(dir, entry.name);
|
|
90
101
|
const relativePath = path.join(basePath, entry.name);
|
|
91
102
|
if (entry.isDirectory()) {
|
|
92
|
-
//
|
|
93
|
-
|
|
94
|
-
entry.name.endsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_END)
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
103
|
+
// Check if this is a dynamic or wildcard directory
|
|
104
|
+
const isDynamic = entry.name.startsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_START) &&
|
|
105
|
+
entry.name.endsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_END) &&
|
|
106
|
+
entry.name !== ROUTE_CONSTANTS.WILDCARD_SIMPLE;
|
|
107
|
+
const isWildcard = entry.name === ROUTE_CONSTANTS.WILDCARD_SIMPLE;
|
|
108
|
+
// Prevent conflicts between dynamic and wildcard routes
|
|
109
|
+
if (isDynamic && wildcardFolderFound) {
|
|
110
|
+
throw new Error(`Cannot mix dynamic and wildcard route folders in the same directory. ` +
|
|
111
|
+
`Found dynamic folder '${entry.name}' but wildcard folder already exists in '${dir}'.`);
|
|
112
|
+
}
|
|
113
|
+
if (isWildcard && dynamicFolderFound) {
|
|
114
|
+
throw new Error(`Cannot mix wildcard and dynamic route folders in the same directory. ` +
|
|
115
|
+
`Found wildcard folder '${entry.name}' but dynamic folder already exists in '${dir}'.`);
|
|
116
|
+
}
|
|
117
|
+
if (isDynamic && dynamicFolderFound) {
|
|
118
|
+
throw new Error(`Multiple dynamic route folders found in the same directory: ` +
|
|
119
|
+
`'${entry.name}' conflicts with another dynamic folder in '${dir}'.`);
|
|
99
120
|
}
|
|
121
|
+
if (isWildcard && wildcardFolderFound) {
|
|
122
|
+
throw new Error(`Multiple wildcard route folders found in the same directory: ` +
|
|
123
|
+
`'${entry.name}' conflicts with another wildcard folder in '${dir}'.`);
|
|
124
|
+
}
|
|
125
|
+
// Update flags
|
|
126
|
+
if (isDynamic)
|
|
127
|
+
dynamicFolderFound = true;
|
|
128
|
+
if (isWildcard)
|
|
129
|
+
wildcardFolderFound = true;
|
|
100
130
|
await this.scanDirectory(entryPath, relativePath);
|
|
101
131
|
}
|
|
102
132
|
else if (entry.isFile() && entry.name === 'route.ts') {
|
|
@@ -141,6 +171,7 @@ export class ApiRouter {
|
|
|
141
171
|
middleware: routeModule.middleware,
|
|
142
172
|
schema: routeModule.schema,
|
|
143
173
|
openapi: routeModule.openapi,
|
|
174
|
+
isWildcard: routePath.includes(ROUTE_CONSTANTS.WILDCARD_SEGMENT_PREFIX),
|
|
144
175
|
};
|
|
145
176
|
this.insertRoute(routeDef);
|
|
146
177
|
}
|
|
@@ -149,9 +180,9 @@ export class ApiRouter {
|
|
|
149
180
|
}
|
|
150
181
|
}
|
|
151
182
|
/**
|
|
152
|
-
* Converts a file path to a route path by processing dynamic segments and applying the prefix.
|
|
153
|
-
* @param filePath The file path to convert (e.g., "users/[id]/route.ts").
|
|
154
|
-
* @returns {string} The converted route path (e.g., "/users/:id").
|
|
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").
|
|
155
186
|
*/
|
|
156
187
|
convertFilePathToRoute(filePath) {
|
|
157
188
|
// Remove the "route.ts" suffix
|
|
@@ -166,14 +197,20 @@ export class ApiRouter {
|
|
|
166
197
|
continue; // Skip empty segments
|
|
167
198
|
// Skip grouping segments (e.g., (group))
|
|
168
199
|
if (segment.startsWith(ROUTE_CONSTANTS.GROUPING_FOLDER_START) &&
|
|
169
|
-
segment.endsWith(ROUTE_CONSTANTS.GROUPING_FOLDER_END))
|
|
200
|
+
segment.endsWith(ROUTE_CONSTANTS.GROUPING_FOLDER_END)) {
|
|
170
201
|
continue;
|
|
202
|
+
}
|
|
171
203
|
// Convert dynamic segments from [param] to :param
|
|
172
204
|
if (segment.startsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_START) &&
|
|
173
|
-
segment.endsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_END)
|
|
205
|
+
segment.endsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_END) &&
|
|
206
|
+
!segment.startsWith(ROUTE_CONSTANTS.WILDCARD_START)) {
|
|
174
207
|
const param = segment.slice(1, -1);
|
|
175
208
|
resultSegments.push(ROUTE_CONSTANTS.DYNAMIC_SEGMENT_PREFIX + param);
|
|
176
209
|
}
|
|
210
|
+
// Convert wildcard segments from [...] to *
|
|
211
|
+
else if (segment === ROUTE_CONSTANTS.WILDCARD_SIMPLE) {
|
|
212
|
+
resultSegments.push(ROUTE_CONSTANTS.WILDCARD_SEGMENT_PREFIX);
|
|
213
|
+
}
|
|
177
214
|
else {
|
|
178
215
|
resultSegments.push(segment);
|
|
179
216
|
}
|
|
@@ -195,7 +232,7 @@ export class ApiRouter {
|
|
|
195
232
|
* Resolves a request to a route definition and its parameters.
|
|
196
233
|
* @param pathname The normalized request pathname.
|
|
197
234
|
* @param method The uppercase HTTP method.
|
|
198
|
-
* @returns {{ route?: RouteDefinition; params: Record<string, string
|
|
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).
|
|
199
236
|
* @throws {Error} If the request URL is malformed.
|
|
200
237
|
*/
|
|
201
238
|
resolve(pathname, method) {
|
|
@@ -203,21 +240,39 @@ export class ApiRouter {
|
|
|
203
240
|
const segments = pathname.split('/').filter(Boolean);
|
|
204
241
|
let node = this.root;
|
|
205
242
|
const params = {};
|
|
206
|
-
|
|
243
|
+
let wildcardSegments = [];
|
|
244
|
+
// Traverse the trie with proper prioritization
|
|
245
|
+
for (let i = 0; i < segments.length; i++) {
|
|
246
|
+
const segment = segments[i];
|
|
247
|
+
// Priority 1: Exact static match (highest priority)
|
|
207
248
|
if (node.children.has(segment)) {
|
|
208
249
|
node = node.children.get(segment);
|
|
209
250
|
}
|
|
251
|
+
// Priority 2: Dynamic parameter match (medium priority)
|
|
210
252
|
else if (node.paramChild) {
|
|
211
253
|
node = node.paramChild;
|
|
212
254
|
params[node.paramName] = segment;
|
|
213
255
|
}
|
|
256
|
+
// Priority 3: Collect remaining segments for wildcard (lowest priority)
|
|
214
257
|
else {
|
|
215
|
-
|
|
258
|
+
wildcardSegments = segments.slice(i);
|
|
259
|
+
break;
|
|
216
260
|
}
|
|
217
261
|
}
|
|
218
|
-
if
|
|
262
|
+
// Check if we have a route at the current node
|
|
263
|
+
if (node.route?.handlers[method]) {
|
|
219
264
|
return { route: node.route, params };
|
|
220
265
|
}
|
|
266
|
+
// If no route found but we have wildcard segments, check for wildcard route
|
|
267
|
+
if (wildcardSegments.length > 0 &&
|
|
268
|
+
node.wildcardChild?.route?.handlers[method]) {
|
|
269
|
+
// Return wildcard segments so they can be added to req.wildcardParams
|
|
270
|
+
return {
|
|
271
|
+
route: node.wildcardChild.route,
|
|
272
|
+
params,
|
|
273
|
+
wildcardParams: wildcardSegments,
|
|
274
|
+
};
|
|
275
|
+
}
|
|
221
276
|
return { params: {} };
|
|
222
277
|
}
|
|
223
278
|
catch (error) {
|
package/dist/src/core/openapi.js
CHANGED
|
@@ -1,25 +1,47 @@
|
|
|
1
|
-
|
|
1
|
+
// Import stuff from Zod 4.x
|
|
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
|
+
*/
|
|
8
|
+
function mapZodTypeToOpenAPIType(zodType) {
|
|
9
|
+
if (zodType instanceof ZodOptional) {
|
|
10
|
+
return mapZodTypeToOpenAPIType(zodType.unwrap());
|
|
11
|
+
}
|
|
12
|
+
if (zodType instanceof ZodString)
|
|
13
|
+
return 'string';
|
|
14
|
+
if (zodType instanceof ZodNumber)
|
|
15
|
+
return 'number';
|
|
16
|
+
if (zodType instanceof ZodBoolean)
|
|
17
|
+
return 'boolean';
|
|
18
|
+
if (zodType instanceof ZodArray)
|
|
19
|
+
return 'array';
|
|
20
|
+
if (zodType instanceof ZodObject)
|
|
21
|
+
return 'object';
|
|
22
|
+
return 'string'; // fallback
|
|
23
|
+
}
|
|
2
24
|
/**
|
|
3
25
|
* Builds an array of OpenAPI 3.0 parameters based on the Zod schema.
|
|
4
26
|
* For each property in the Zod schema, an OpenAPI parameter is constructed
|
|
5
27
|
* with the same name and required flag. The schema of the parameter is set
|
|
6
28
|
* to a string type.
|
|
7
|
-
* @param zodSchema - The Zod schema to construct parameters from.
|
|
29
|
+
* @param zodSchema - The Zod schema to construct parameters from. Can be undefined.
|
|
8
30
|
* @param location - The location of the parameter. Must be either "path" or "query".
|
|
9
|
-
* @returns An array of OpenAPI 3.0 parameter objects.
|
|
31
|
+
* @returns An array of OpenAPI 3.0 parameter objects or an empty array if the Zod schema is undefined.
|
|
10
32
|
*/
|
|
11
33
|
function buildParameters(zodSchema, location) {
|
|
12
34
|
const parameters = [];
|
|
13
|
-
if (zodSchema &&
|
|
14
|
-
zodSchema._def &&
|
|
15
|
-
typeof zodSchema._def.shape === 'function') {
|
|
35
|
+
if (zodSchema && typeof zodSchema.shape === 'object') {
|
|
16
36
|
// Get the shape of the Zod schema
|
|
17
|
-
const shape = zodSchema.
|
|
37
|
+
const shape = zodSchema.shape;
|
|
18
38
|
for (const key in shape) {
|
|
19
39
|
// Get the definition of the field
|
|
20
40
|
const fieldDef = shape[key];
|
|
21
41
|
// Determine if the field is optional
|
|
22
|
-
const isOptional = fieldDef
|
|
42
|
+
const isOptional = fieldDef instanceof ZodOptional;
|
|
43
|
+
// Map the Zod type to an OpenAPI schema type
|
|
44
|
+
const type = mapZodTypeToOpenAPIType(fieldDef);
|
|
23
45
|
parameters.push({
|
|
24
46
|
// Set the name of the parameter
|
|
25
47
|
name: key,
|
|
@@ -28,7 +50,7 @@ function buildParameters(zodSchema, location) {
|
|
|
28
50
|
// Set the required flag
|
|
29
51
|
required: !isOptional,
|
|
30
52
|
// Set the schema type
|
|
31
|
-
schema: { type
|
|
53
|
+
schema: { type },
|
|
32
54
|
// Description of the parameter
|
|
33
55
|
description: `${location} parameter ${key}`,
|
|
34
56
|
});
|
|
@@ -44,10 +66,12 @@ function buildParameters(zodSchema, location) {
|
|
|
44
66
|
* @returns An OpenAPI requestBody object, or undefined if no schema is provided.
|
|
45
67
|
*/
|
|
46
68
|
function buildRequestBody(zodSchema) {
|
|
69
|
+
// If no schema is provided, return undefined
|
|
47
70
|
if (!zodSchema)
|
|
48
71
|
return undefined;
|
|
49
|
-
//
|
|
50
|
-
const jsonSchema =
|
|
72
|
+
// Convert the Zod schema to a JSON schema
|
|
73
|
+
const jsonSchema = toJSONSchema(zodSchema);
|
|
74
|
+
// Return the OpenAPI requestBody object
|
|
51
75
|
return {
|
|
52
76
|
content: {
|
|
53
77
|
'application/json': {
|
|
@@ -60,13 +84,24 @@ function buildRequestBody(zodSchema) {
|
|
|
60
84
|
}
|
|
61
85
|
/**
|
|
62
86
|
* Converts a route path from colon-based dynamic segments to OpenAPI's curly brace syntax.
|
|
87
|
+
* Also handles wildcard routes.
|
|
63
88
|
*
|
|
64
|
-
* @param routePath The original route path with colon-based dynamic segments (e.g., "/user/:id").
|
|
65
|
-
* @returns The converted route path with curly brace syntax (e.g., "/user/{id}").
|
|
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/*").
|
|
66
91
|
*/
|
|
67
92
|
function convertPathForOpenAPI(routePath) {
|
|
93
|
+
// Fast path: if no special chars, return as-is
|
|
94
|
+
if (routePath.indexOf(':') === -1 && routePath.indexOf('*') === -1) {
|
|
95
|
+
return routePath;
|
|
96
|
+
}
|
|
68
97
|
// Replace occurrences of :param with {param}
|
|
69
|
-
|
|
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*}');
|
|
104
|
+
return converted;
|
|
70
105
|
}
|
|
71
106
|
export function generateOpenAPIDocument(apiRoutes, options) {
|
|
72
107
|
const openapiDoc = {
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { readdirSync } from 'fs';
|
|
3
3
|
import * as path from 'path';
|
|
4
4
|
// Import utils
|
|
5
|
-
import { cleanPrefix, normalizePath, compareRoutes, ROUTE_CONSTANTS, } from '
|
|
5
|
+
import { cleanPrefix, normalizePath, compareRoutes, ROUTE_CONSTANTS, } from '../utils/index.js';
|
|
6
6
|
/**
|
|
7
7
|
* PageRouter class for handling file-based page routing.
|
|
8
8
|
* Loads pages from a directory structure and matches requests to the appropriate page handlers.
|
package/dist/src/core/server.js
CHANGED
package/dist/src/index.d.ts
CHANGED
|
@@ -73,5 +73,5 @@ export declare class Burger {
|
|
|
73
73
|
*/
|
|
74
74
|
serve(port?: number, cb?: () => void): Promise<void>;
|
|
75
75
|
}
|
|
76
|
-
export { setDir } from '
|
|
76
|
+
export { setDir } from './utils/index.js';
|
|
77
77
|
export type { ServerOptions, RequestHandler, BurgerRequest, BurgerNext, Middleware, openapi, } from '@burgerTypes';
|
package/dist/src/index.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
// Import stuff from core
|
|
2
|
-
import { Server } from '
|
|
3
|
-
import { ApiRouter } from '
|
|
4
|
-
import { PageRouter } from '
|
|
5
|
-
import { generateOpenAPIDocument } from '
|
|
6
|
-
import { swaggerHtml } from '
|
|
2
|
+
import { Server } from './core/server.js';
|
|
3
|
+
import { ApiRouter } from './core/api-router.js';
|
|
4
|
+
import { PageRouter } from './core/page-router.js';
|
|
5
|
+
import { generateOpenAPIDocument } from './core/openapi.js';
|
|
6
|
+
import { swaggerHtml } from './core/swagger-ui.js';
|
|
7
7
|
// Import utils
|
|
8
|
-
import { collectRoutes } from '
|
|
9
|
-
import { METHOD_NOT_ALLOWED, NOT_FOUND, OPENAPI_ERROR } from '
|
|
8
|
+
import { collectRoutes } from './utils/index.js';
|
|
9
|
+
import { METHOD_NOT_ALLOWED, NOT_FOUND, OPENAPI_ERROR } from './utils/response';
|
|
10
10
|
// Import middleware
|
|
11
|
-
import { createValidationMiddleware } from '
|
|
11
|
+
import { createValidationMiddleware } from './middleware/validator.js';
|
|
12
12
|
export class Burger {
|
|
13
13
|
options;
|
|
14
14
|
/**
|
|
@@ -147,7 +147,80 @@ export class Burger {
|
|
|
147
147
|
// Create optimized route handler
|
|
148
148
|
if (totalMiddlewareCount === 0) {
|
|
149
149
|
// Ultra-fast path: no middleware
|
|
150
|
+
// Pre-compute wildcard segment count for faster extraction
|
|
151
|
+
const isWildcard = route.isWildcard;
|
|
152
|
+
// Calculate how many segments come before the wildcard
|
|
153
|
+
// E.g., "/api/users/:userId/*" has 3 segments before wildcard (api, users, :userId)
|
|
154
|
+
const baseSegmentCount = isWildcard
|
|
155
|
+
? path.split('/').filter(Boolean).length - 1 // Subtract 1 for the * itself
|
|
156
|
+
: 0;
|
|
150
157
|
routes[path] = (request) => {
|
|
158
|
+
// Extract wildcard params if this is a wildcard route
|
|
159
|
+
if (isWildcard) {
|
|
160
|
+
// Step 1: Get the pathname from the URL
|
|
161
|
+
// Example: "http://localhost:4000/api/users/123/profile?id=1" → "/api/users/123/profile"
|
|
162
|
+
const url = request.url;
|
|
163
|
+
// Find where the path starts (after protocol and domain)
|
|
164
|
+
// Example: "http://localhost:4000/api/..." → protocolEnd = 4 (after "http")
|
|
165
|
+
const protocolEnd = url.indexOf('://');
|
|
166
|
+
// Find first "/" after the domain
|
|
167
|
+
// Example: "http://localhost:4000/api/..." → pathStart = 21 (the "/" before "api")
|
|
168
|
+
const pathStart = url.indexOf('/', protocolEnd + 3);
|
|
169
|
+
// Find where query parameters start (if any)
|
|
170
|
+
// Example: "/api/users/123?id=1" → pathEnd = 15 (at the "?")
|
|
171
|
+
const pathEnd = url.indexOf('?', pathStart);
|
|
172
|
+
// Extract just the pathname without query parameters
|
|
173
|
+
// Example: "/api/users/123/profile"
|
|
174
|
+
const pathname = pathEnd === -1
|
|
175
|
+
? url.substring(pathStart) // No query params
|
|
176
|
+
: url.substring(pathStart, pathEnd); // Has query params, stop at "?"
|
|
177
|
+
// Step 2: Extract wildcard segments efficiently
|
|
178
|
+
// Example route: "/api/users/:userId/*" has baseSegmentCount = 3
|
|
179
|
+
// - Segment 0: "api"
|
|
180
|
+
// - Segment 1: "users"
|
|
181
|
+
// - Segment 2: ":userId" (or "123" in actual URL)
|
|
182
|
+
// - Segment 3+: wildcard segments we want!
|
|
183
|
+
if (baseSegmentCount === 0) {
|
|
184
|
+
// Fast path: The entire path is wildcard
|
|
185
|
+
// Example: "/api/docs/*" where all segments after domain are wildcards
|
|
186
|
+
// Just split everything and we're done!
|
|
187
|
+
request.wildcardParams = pathname
|
|
188
|
+
.split('/')
|
|
189
|
+
.filter(Boolean);
|
|
190
|
+
}
|
|
191
|
+
else {
|
|
192
|
+
// Optimized path: Skip base segments and only collect wildcard segments
|
|
193
|
+
// Example: "/api/users/123/settings/privacy"
|
|
194
|
+
// - We need to skip 3 segments (api, users, 123)
|
|
195
|
+
// - Only collect: ["settings", "privacy"]
|
|
196
|
+
const wildcardParams = [];
|
|
197
|
+
let segmentCount = 0; // Counts how many segments we've seen
|
|
198
|
+
let start = pathname[0] === '/' ? 1 : 0; // Start after leading "/" if present
|
|
199
|
+
// Loop through each character in the pathname
|
|
200
|
+
// When we hit "/" or end of string, we know we found a segment
|
|
201
|
+
for (let i = start; i <= pathname.length; i++) {
|
|
202
|
+
// Found end of a segment (either "/" or end of string)
|
|
203
|
+
if (i === pathname.length ||
|
|
204
|
+
pathname[i] === '/') {
|
|
205
|
+
// Make sure it's not an empty segment (from double slashes)
|
|
206
|
+
if (i > start) {
|
|
207
|
+
// Only save segments AFTER we've skipped the base segments
|
|
208
|
+
// Example: If baseSegmentCount=3, save segment 3, 4, 5, etc.
|
|
209
|
+
if (segmentCount >= baseSegmentCount) {
|
|
210
|
+
// Extract this segment from the pathname
|
|
211
|
+
// Example: pathname.substring(5, 13) might give "settings"
|
|
212
|
+
wildcardParams.push(pathname.substring(start, i));
|
|
213
|
+
}
|
|
214
|
+
segmentCount++; // Increment count for next segment
|
|
215
|
+
}
|
|
216
|
+
start = i + 1; // Move start position to character after "/"
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
// Done! wildcardParams now contains only the wildcard segments
|
|
220
|
+
// Example: ["settings", "privacy"] instead of ["api", "users", "123", "settings", "privacy"]
|
|
221
|
+
request.wildcardParams = wildcardParams;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
151
224
|
const handler = handlers[request.method];
|
|
152
225
|
return handler ? handler(request) : this.METHOD_NOT_ALLOWED;
|
|
153
226
|
};
|
|
@@ -176,14 +249,99 @@ export class Burger {
|
|
|
176
249
|
* Pre-compute the required functionality end
|
|
177
250
|
* ================================================
|
|
178
251
|
*/
|
|
252
|
+
// Pre-compute wildcard segment count for faster extraction
|
|
253
|
+
const isWildcard = route.isWildcard;
|
|
254
|
+
// Calculate how many segments come before the wildcard
|
|
255
|
+
// E.g., "/api/users/:userId/*" has 3 segments before wildcard (api, users, :userId)
|
|
256
|
+
const baseSegmentCount = isWildcard
|
|
257
|
+
? path.split('/').filter(Boolean).length - 1 // Subtract 1 for the * itself
|
|
258
|
+
: 0;
|
|
179
259
|
// Create handler with middleware
|
|
180
260
|
routes[path] = (request) => {
|
|
261
|
+
// Extract wildcard params if this is a wildcard route
|
|
262
|
+
if (isWildcard) {
|
|
263
|
+
// Step 1: Get the pathname from the URL
|
|
264
|
+
// Example: "http://localhost:4000/api/users/123/profile?id=1" → "/api/users/123/profile"
|
|
265
|
+
const url = request.url;
|
|
266
|
+
// Find where the path starts (after protocol and domain)
|
|
267
|
+
// Example: "http://localhost:4000/api/..." → protocolEnd = 4 (after "http")
|
|
268
|
+
const protocolEnd = url.indexOf('://');
|
|
269
|
+
// Find first "/" after the domain
|
|
270
|
+
// Example: "http://localhost:4000/api/..." → pathStart = 21 (the "/" before "api")
|
|
271
|
+
const pathStart = url.indexOf('/', protocolEnd + 3);
|
|
272
|
+
// Find where query parameters start (if any)
|
|
273
|
+
// Example: "/api/users/123?id=1" → pathEnd = 15 (at the "?")
|
|
274
|
+
const pathEnd = url.indexOf('?', pathStart);
|
|
275
|
+
// Extract just the pathname without query parameters
|
|
276
|
+
// Example: "/api/users/123/profile"
|
|
277
|
+
const pathname = pathEnd === -1
|
|
278
|
+
? url.substring(pathStart) // No query params
|
|
279
|
+
: url.substring(pathStart, pathEnd); // Has query params, stop at "?"
|
|
280
|
+
// Step 2: Extract wildcard segments efficiently
|
|
281
|
+
// Example route: "/api/users/:userId/*" has baseSegmentCount = 3
|
|
282
|
+
// - Segment 0: "api"
|
|
283
|
+
// - Segment 1: "users"
|
|
284
|
+
// - Segment 2: ":userId" (or "123" in actual URL)
|
|
285
|
+
// - Segment 3+: wildcard segments we want!
|
|
286
|
+
if (baseSegmentCount === 0) {
|
|
287
|
+
// Fast path: The entire path is wildcard
|
|
288
|
+
// Example: "/api/docs/*" where all segments after domain are wildcards
|
|
289
|
+
// Just split everything and we're done!
|
|
290
|
+
request.wildcardParams = pathname
|
|
291
|
+
.split('/')
|
|
292
|
+
.filter(Boolean);
|
|
293
|
+
}
|
|
294
|
+
else {
|
|
295
|
+
// Optimized path: Skip base segments and only collect wildcard segments
|
|
296
|
+
// Example: "/api/users/123/settings/privacy"
|
|
297
|
+
// - We need to skip 3 segments (api, users, 123)
|
|
298
|
+
// - Only collect: ["settings", "privacy"]
|
|
299
|
+
const wildcardParams = [];
|
|
300
|
+
let segmentCount = 0; // Counts how many segments we've seen
|
|
301
|
+
let start = pathname[0] === '/' ? 1 : 0; // Start after leading "/" if present
|
|
302
|
+
// Loop through each character in the pathname
|
|
303
|
+
// When we hit "/" or end of string, we know we found a segment
|
|
304
|
+
for (let i = start; i <= pathname.length; i++) {
|
|
305
|
+
// Found end of a segment (either "/" or end of string)
|
|
306
|
+
if (i === pathname.length ||
|
|
307
|
+
pathname[i] === '/') {
|
|
308
|
+
// Make sure it's not an empty segment (from double slashes)
|
|
309
|
+
if (i > start) {
|
|
310
|
+
// Only save segments AFTER we've skipped the base segments
|
|
311
|
+
// Example: If baseSegmentCount=3, save segment 3, 4, 5, etc.
|
|
312
|
+
if (segmentCount >= baseSegmentCount) {
|
|
313
|
+
// Extract this segment from the pathname
|
|
314
|
+
// Example: pathname.substring(5, 13) might give "settings"
|
|
315
|
+
wildcardParams.push(pathname.substring(start, i));
|
|
316
|
+
}
|
|
317
|
+
segmentCount++; // Increment count for next segment
|
|
318
|
+
}
|
|
319
|
+
start = i + 1; // Move start position to character after "/"
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
// Done! wildcardParams now contains only the wildcard segments
|
|
323
|
+
// Example: ["settings", "privacy"] instead of ["api", "users", "123", "settings", "privacy"]
|
|
324
|
+
request.wildcardParams = wildcardParams;
|
|
325
|
+
}
|
|
326
|
+
}
|
|
181
327
|
const handler = handlers[request.method];
|
|
182
328
|
if (!handler)
|
|
183
329
|
return this.METHOD_NOT_ALLOWED;
|
|
184
330
|
return this.processMiddleware(request, middlewares, handler);
|
|
185
331
|
};
|
|
186
332
|
}
|
|
333
|
+
// For wildcard routes, also register the base path
|
|
334
|
+
// Bun's /* wildcard may not match the base path itself, so we register both
|
|
335
|
+
if (route.isWildcard && path.endsWith('/*')) {
|
|
336
|
+
const basePath = path.slice(0, -2); // Remove "/*" to get base path
|
|
337
|
+
// Only register base path if no static route exists (preserve priority)
|
|
338
|
+
// Static routes have highest priority: Static > Dynamic > Wildcard
|
|
339
|
+
if (!routes[basePath]) {
|
|
340
|
+
// No static route found, register wildcard for base path
|
|
341
|
+
routes[basePath] = routes[path];
|
|
342
|
+
}
|
|
343
|
+
// If static route exists, it takes priority (correct behavior)
|
|
344
|
+
}
|
|
187
345
|
}
|
|
188
346
|
// Add special routes for OpenAPI
|
|
189
347
|
routes['/openapi.json'] = () => this.openApiDoc
|
|
@@ -253,7 +411,7 @@ export class Burger {
|
|
|
253
411
|
for (let i = afterCount - 1; i >= 0; i--) {
|
|
254
412
|
response = await afterStack[i](response);
|
|
255
413
|
}
|
|
256
|
-
// Return the
|
|
414
|
+
// Return the response
|
|
257
415
|
return response;
|
|
258
416
|
}
|
|
259
417
|
/**
|
|
@@ -284,4 +442,4 @@ export class Burger {
|
|
|
284
442
|
}
|
|
285
443
|
}
|
|
286
444
|
// Export utils
|
|
287
|
-
export { setDir } from '
|
|
445
|
+
export { setDir } from './utils/index.js';
|
|
@@ -1,2 +1,14 @@
|
|
|
1
1
|
import type { RouteSchema, Middleware } from '@burgerTypes';
|
|
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
|
+
*/
|
|
2
14
|
export declare function createValidationMiddleware(schema: RouteSchema): Middleware;
|
|
@@ -1,79 +1,100 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* createValidationMiddleware:
|
|
3
|
+
* - Precompute a smaller runtime descriptor per method to avoid
|
|
4
|
+
* repeatedly touching the full schema object on every request.
|
|
5
|
+
* - Uses safeParse (sync) for Zod schemas (no try/catch around safeParse).
|
|
6
|
+
* - Parses querystring manually (no URL constructor, no throw).
|
|
7
|
+
* - Lazily allocates the errors container only when needed.
|
|
8
|
+
* - Avoids unnecessary object allocations for successful paths.
|
|
9
|
+
*
|
|
10
|
+
* @param schema - The route schema to validate the request against.
|
|
11
|
+
* @returns The middleware function that validates the request.
|
|
12
|
+
*/
|
|
1
13
|
export function createValidationMiddleware(schema) {
|
|
14
|
+
// Precompute a minimal descriptor per HTTP method (lowercased)
|
|
15
|
+
// This work runs once at middleware creation time (fast startup cost, zero cost on each request for those computations).
|
|
16
|
+
const methodMap = {};
|
|
17
|
+
// Loop through the schema and create a method map
|
|
18
|
+
for (const rawMethod of Object.keys(schema)) {
|
|
19
|
+
// Convert the method to lowercase
|
|
20
|
+
const key = rawMethod.toLowerCase();
|
|
21
|
+
// Get the method schema
|
|
22
|
+
const m = schema[rawMethod] || {};
|
|
23
|
+
// Create a method map
|
|
24
|
+
methodMap[key] = {
|
|
25
|
+
paramsSchema: m.params, // URL parameters schema
|
|
26
|
+
querySchema: m.query, // Query parameters schema
|
|
27
|
+
bodySchema: m.body, // Request body schema
|
|
28
|
+
hasParams: !!m.params, // Whether the method has URL parameters
|
|
29
|
+
hasQuery: !!m.query, // Whether the method has query parameters
|
|
30
|
+
hasBody: !!m.body, // Whether the method has a request body
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* The middleware function that validates the request.
|
|
35
|
+
*
|
|
36
|
+
* @param req - The request object.
|
|
37
|
+
* @returns The next middleware or handler.
|
|
38
|
+
*/
|
|
2
39
|
return async (req) => {
|
|
3
40
|
// If the request has been validated, continue.
|
|
4
41
|
if (req.validated) {
|
|
5
42
|
return undefined; // Proceed to the next middleware or handler
|
|
6
43
|
}
|
|
7
44
|
// Determine the HTTP method (in lowercase) to match the schema.
|
|
8
|
-
const method = req.method.toLowerCase();
|
|
45
|
+
const method = (req.method || 'get').toLowerCase();
|
|
9
46
|
// Get the schema for the current method.
|
|
10
|
-
const methodSchema =
|
|
47
|
+
const methodSchema = methodMap[method];
|
|
11
48
|
// If there's no schema for this method, continue.
|
|
12
49
|
if (!methodSchema) {
|
|
13
50
|
return undefined; // Proceed to the next middleware or handler
|
|
14
51
|
}
|
|
15
52
|
// Get the schemas for the current method.
|
|
16
|
-
const paramsSchema = methodSchema
|
|
17
|
-
const querySchema = methodSchema.query;
|
|
18
|
-
const bodySchema = methodSchema.body;
|
|
19
|
-
/**
|
|
20
|
-
* Array to collect validation errors.
|
|
21
|
-
* Each error contains a `field` indicating the part of the request that failed validation,
|
|
22
|
-
* and an `error` providing details about the validation failure.
|
|
23
|
-
*/
|
|
24
|
-
const errors = new Array(3); // Pre-allocate for params, query, body
|
|
25
|
-
let errorCount = 0;
|
|
53
|
+
const { paramsSchema, querySchema, bodySchema, hasParams, hasQuery, hasBody, } = methodSchema;
|
|
26
54
|
/**
|
|
27
55
|
* Object to store validated request data. This will be attached to the
|
|
28
56
|
* request object if validation is successful. The object will contain
|
|
29
57
|
* validated data for the following fields:
|
|
30
58
|
*
|
|
31
|
-
* - `params`: Validated URL parameters.
|
|
32
|
-
* - `query`: Validated query parameters.
|
|
33
|
-
* - `body`: Validated request body (if JSON).
|
|
59
|
+
* - `params`: Validated URL parameters (if available and schema provided).
|
|
60
|
+
* - `query`: Validated query parameters (if available and schema provided).
|
|
61
|
+
* - `body`: Validated request body (if JSON and schema provided).
|
|
34
62
|
*/
|
|
35
63
|
const validated = {};
|
|
64
|
+
// Lazy errors — create only if/when an error occurs
|
|
65
|
+
let errors = null;
|
|
36
66
|
// Validate URL parameters (if available and schema provided).
|
|
37
|
-
if (
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
validated.params = result.data;
|
|
42
|
-
}
|
|
43
|
-
else {
|
|
44
|
-
errors[errorCount++] = {
|
|
45
|
-
field: 'params',
|
|
46
|
-
error: result.error,
|
|
47
|
-
};
|
|
48
|
-
}
|
|
67
|
+
if (hasParams && req.params) {
|
|
68
|
+
const result = paramsSchema.safeParse(req.params);
|
|
69
|
+
if (result.success) {
|
|
70
|
+
validated.params = result.data;
|
|
49
71
|
}
|
|
50
|
-
|
|
51
|
-
|
|
72
|
+
else {
|
|
73
|
+
if (!errors)
|
|
74
|
+
errors = {};
|
|
75
|
+
errors.params = result.error.issues;
|
|
52
76
|
}
|
|
53
77
|
}
|
|
54
|
-
// Validate query parameters.
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
validated.query = result.data;
|
|
62
|
-
}
|
|
63
|
-
else {
|
|
64
|
-
errors[errorCount++] = {
|
|
65
|
-
field: 'query',
|
|
66
|
-
error: result.error,
|
|
67
|
-
};
|
|
68
|
-
}
|
|
78
|
+
// Validate query parameters if available and schema provided.
|
|
79
|
+
if (hasQuery) {
|
|
80
|
+
const url = new URL(req.url);
|
|
81
|
+
const queryParams = Object.fromEntries(url.searchParams.entries());
|
|
82
|
+
const result = querySchema.safeParse(queryParams);
|
|
83
|
+
if (result.success) {
|
|
84
|
+
validated.query = result.data;
|
|
69
85
|
}
|
|
70
|
-
|
|
71
|
-
|
|
86
|
+
else {
|
|
87
|
+
if (!errors)
|
|
88
|
+
errors = {};
|
|
89
|
+
errors.query = result.error.issues;
|
|
72
90
|
}
|
|
73
91
|
}
|
|
74
|
-
//
|
|
75
|
-
|
|
76
|
-
req.headers.get('Content-Type')
|
|
92
|
+
// Get the content type header
|
|
93
|
+
const contentType = req.headers.get('content-type') ??
|
|
94
|
+
req.headers.get('Content-Type') ??
|
|
95
|
+
'';
|
|
96
|
+
// Validate request body if it's JSON
|
|
97
|
+
if (hasBody && contentType?.includes('application/json')) {
|
|
77
98
|
try {
|
|
78
99
|
// Attempt to parse the JSON body.
|
|
79
100
|
const bodyData = await req.json();
|
|
@@ -82,23 +103,25 @@ export function createValidationMiddleware(schema) {
|
|
|
82
103
|
// Set the validated body.
|
|
83
104
|
validated.body = result.data;
|
|
84
105
|
// Set the json method to return the validated body.
|
|
85
|
-
req.json = () => result.data;
|
|
106
|
+
req.json = async () => result.data;
|
|
86
107
|
}
|
|
87
108
|
else {
|
|
88
|
-
errors
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
};
|
|
109
|
+
if (!errors)
|
|
110
|
+
errors = {};
|
|
111
|
+
errors.body = result.error.issues;
|
|
92
112
|
}
|
|
93
113
|
}
|
|
94
|
-
catch (
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
error
|
|
98
|
-
|
|
114
|
+
catch (error) {
|
|
115
|
+
// Create a message from the error.
|
|
116
|
+
const msg = error && typeof error.message === 'string'
|
|
117
|
+
? error.message
|
|
118
|
+
: String(error);
|
|
119
|
+
if (!errors)
|
|
120
|
+
errors = {};
|
|
121
|
+
errors.body = [{ message: msg }];
|
|
99
122
|
}
|
|
100
123
|
}
|
|
101
|
-
if (
|
|
124
|
+
if (errors) {
|
|
102
125
|
// If validation fails, return a 400 response with error details.
|
|
103
126
|
return Response.json({ errors }, { status: 400 });
|
|
104
127
|
}
|
package/dist/src/utils/error.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { ROUTE_CONSTANTS, HTTP_METHODS, compareRoutes, getRouteSpecificity, collectRoutes, } from '
|
|
1
|
+
export { ROUTE_CONSTANTS, HTTP_METHODS, compareRoutes, getRouteSpecificity, collectRoutes, } from './routing.js';
|
|
2
2
|
/**
|
|
3
3
|
* Resolves the given path to the specified directory.
|
|
4
4
|
* @param directory the directory to resolve to
|
package/dist/src/utils/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { resolve } from 'path';
|
|
2
2
|
// Export constants
|
|
3
|
-
export { ROUTE_CONSTANTS, HTTP_METHODS, compareRoutes, getRouteSpecificity, collectRoutes, } from '
|
|
3
|
+
export { ROUTE_CONSTANTS, HTTP_METHODS, compareRoutes, getRouteSpecificity, collectRoutes, } from './routing.js';
|
|
4
4
|
/**
|
|
5
5
|
* Resolves the given path to the specified directory.
|
|
6
6
|
* @param directory the directory to resolve to
|
|
@@ -10,6 +10,9 @@ export declare const ROUTE_CONSTANTS: {
|
|
|
10
10
|
DYNAMIC_FOLDER_END: string;
|
|
11
11
|
GROUPING_FOLDER_START: string;
|
|
12
12
|
GROUPING_FOLDER_END: string;
|
|
13
|
+
WILDCARD_SEGMENT_PREFIX: string;
|
|
14
|
+
WILDCARD_SIMPLE: string;
|
|
15
|
+
WILDCARD_START: string;
|
|
13
16
|
};
|
|
14
17
|
/**
|
|
15
18
|
* Supported HTTP methods
|
|
@@ -18,12 +21,14 @@ export declare const HTTP_METHODS: string[];
|
|
|
18
21
|
/**
|
|
19
22
|
* Calculates the specificity of a route path based on the number of static segments.
|
|
20
23
|
* Static segments increase the score, while dynamic segments (:param) do not.
|
|
24
|
+
* Wildcard segments (*) have the lowest specificity (highest penalty).
|
|
21
25
|
* @param path The route path to evaluate.
|
|
22
|
-
* @returns The specificity score (higher means more static segments).
|
|
26
|
+
* @returns The specificity score (higher means more static segments, lower priority for wildcard).
|
|
23
27
|
*/
|
|
24
28
|
export declare const getRouteSpecificity: (path: string) => number;
|
|
25
29
|
/**
|
|
26
30
|
* Compares two routes for sorting, prioritizing those with higher specificity (more static segments).
|
|
31
|
+
* Route prioritization: Static > Dynamic > Wildcard.
|
|
27
32
|
* If specificity is equal, sorts alphabetically by path.
|
|
28
33
|
* @param a The first route to compare.
|
|
29
34
|
* @param b The second route to compare.
|
|
@@ -2,13 +2,21 @@
|
|
|
2
2
|
* Constants for route handling.
|
|
3
3
|
*/
|
|
4
4
|
export const ROUTE_CONSTANTS = {
|
|
5
|
+
// Supported page extensions
|
|
5
6
|
SUPPORTED_PAGE_EXTENSIONS: ['.tsx', '.html'],
|
|
7
|
+
// Page index files
|
|
6
8
|
PAGE_INDEX_FILES: ['index.tsx', 'index.html'],
|
|
9
|
+
// Dynamic route constants
|
|
7
10
|
DYNAMIC_SEGMENT_PREFIX: ':',
|
|
8
11
|
DYNAMIC_FOLDER_START: '[',
|
|
9
12
|
DYNAMIC_FOLDER_END: ']',
|
|
13
|
+
// Grouping folder constants
|
|
10
14
|
GROUPING_FOLDER_START: '(',
|
|
11
15
|
GROUPING_FOLDER_END: ')',
|
|
16
|
+
// Wildcard route constants
|
|
17
|
+
WILDCARD_SEGMENT_PREFIX: '*',
|
|
18
|
+
WILDCARD_SIMPLE: '[...]',
|
|
19
|
+
WILDCARD_START: '[...',
|
|
12
20
|
};
|
|
13
21
|
/**
|
|
14
22
|
* Supported HTTP methods
|
|
@@ -25,19 +33,24 @@ export const HTTP_METHODS = [
|
|
|
25
33
|
/**
|
|
26
34
|
* Calculates the specificity of a route path based on the number of static segments.
|
|
27
35
|
* Static segments increase the score, while dynamic segments (:param) do not.
|
|
36
|
+
* Wildcard segments (*) have the lowest specificity (highest penalty).
|
|
28
37
|
* @param path The route path to evaluate.
|
|
29
|
-
* @returns The specificity score (higher means more static segments).
|
|
38
|
+
* @returns The specificity score (higher means more static segments, lower priority for wildcard).
|
|
30
39
|
*/
|
|
31
40
|
export const getRouteSpecificity = (path) => {
|
|
32
41
|
const segments = path.split('/').filter(Boolean);
|
|
33
42
|
return segments.reduce((score, segment) => {
|
|
43
|
+
if (segment.startsWith(ROUTE_CONSTANTS.WILDCARD_SEGMENT_PREFIX)) {
|
|
44
|
+
return score + 1000; // Wildcard routes get highest penalty (lowest priority)
|
|
45
|
+
}
|
|
34
46
|
return segment.startsWith(ROUTE_CONSTANTS.DYNAMIC_SEGMENT_PREFIX)
|
|
35
|
-
? score
|
|
36
|
-
: score + 1;
|
|
47
|
+
? score + 100 // Dynamic routes get medium penalty
|
|
48
|
+
: score + 1; // Static routes get minimal penalty
|
|
37
49
|
}, 0);
|
|
38
50
|
};
|
|
39
51
|
/**
|
|
40
52
|
* Compares two routes for sorting, prioritizing those with higher specificity (more static segments).
|
|
53
|
+
* Route prioritization: Static > Dynamic > Wildcard.
|
|
41
54
|
* If specificity is equal, sorts alphabetically by path.
|
|
42
55
|
* @param a The first route to compare.
|
|
43
56
|
* @param b The second route to compare.
|
|
@@ -76,5 +89,11 @@ export function collectRoutes(node, currentPath = '', routes = []) {
|
|
|
76
89
|
const paramPath = `${currentPath}/:${node.paramChild.paramName}`;
|
|
77
90
|
collectRoutes(node.paramChild, paramPath, routes);
|
|
78
91
|
}
|
|
92
|
+
// Traverse wildcard child if exists (lowest priority)
|
|
93
|
+
if (node.wildcardChild) {
|
|
94
|
+
// const wildcardPath = `${currentPath}/${node.wildcardChild.wildcardParamName}`;
|
|
95
|
+
const wildcardPath = `${currentPath}/${ROUTE_CONSTANTS.WILDCARD_SEGMENT_PREFIX}`;
|
|
96
|
+
collectRoutes(node.wildcardChild, wildcardPath, routes);
|
|
97
|
+
}
|
|
79
98
|
return routes;
|
|
80
99
|
}
|
package/package.json
CHANGED
|
@@ -1,89 +1,89 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "burger-api",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"author": "Isfhan Ahmed",
|
|
5
|
-
"type": "module",
|
|
6
|
-
"module": "dist/src/index.js",
|
|
7
|
-
"types": "dist/src/index.d.ts",
|
|
8
|
-
"files": [
|
|
9
|
-
"dist"
|
|
10
|
-
],
|
|
11
|
-
"scripts": {
|
|
12
|
-
"typecheck": "tsc --noEmit",
|
|
13
|
-
"build": "tsc --project tsconfig.build.json && tsc-alias -p tsconfig.build.json",
|
|
14
|
-
"test": "bun test",
|
|
15
|
-
"dev": "bun run examples/file-base-static-page-routing-app/index.ts"
|
|
16
|
-
},
|
|
17
|
-
"keywords": [
|
|
18
|
-
"burger-api",
|
|
19
|
-
"burger-api-framework",
|
|
20
|
-
"bun",
|
|
21
|
-
"bunjs",
|
|
22
|
-
"bun-framework",
|
|
23
|
-
"fast-backend",
|
|
24
|
-
"javascript-backend",
|
|
25
|
-
"high-performance",
|
|
26
|
-
"esm",
|
|
27
|
-
"typescript",
|
|
28
|
-
"openapi",
|
|
29
|
-
"swagger-ui",
|
|
30
|
-
"declarative-routing",
|
|
31
|
-
"api-framework",
|
|
32
|
-
"modern-backend",
|
|
33
|
-
"backend-framework",
|
|
34
|
-
"server",
|
|
35
|
-
"bun-native",
|
|
36
|
-
"js-backend",
|
|
37
|
-
"fast-api",
|
|
38
|
-
"scalable-backend",
|
|
39
|
-
"backend-development",
|
|
40
|
-
"modern-api",
|
|
41
|
-
"api-development",
|
|
42
|
-
"backend-engine",
|
|
43
|
-
"efficient",
|
|
44
|
-
"minimalist-backend",
|
|
45
|
-
"bun-powered",
|
|
46
|
-
"open-source",
|
|
47
|
-
"typescript-backend",
|
|
48
|
-
"performance",
|
|
49
|
-
"rapid-development",
|
|
50
|
-
"web-framework",
|
|
51
|
-
"api-server",
|
|
52
|
-
"dynamic-routing",
|
|
53
|
-
"backend-routing",
|
|
54
|
-
"extensible",
|
|
55
|
-
"modular",
|
|
56
|
-
"declarative-api",
|
|
57
|
-
"lightweight",
|
|
58
|
-
"contemporary-backend",
|
|
59
|
-
"fast-javascript",
|
|
60
|
-
"bun-js-framework",
|
|
61
|
-
"bun-backend",
|
|
62
|
-
"bun-api-framework",
|
|
63
|
-
"pakistan-backend",
|
|
64
|
-
"pakistan-api-framework",
|
|
65
|
-
"pakistan-api-server",
|
|
66
|
-
"pakistan-backend-framework",
|
|
67
|
-
"pakistan-bunjs-framework",
|
|
68
|
-
"pakistan-javascript-framework"
|
|
69
|
-
],
|
|
70
|
-
"license": "MIT",
|
|
71
|
-
"repository": {
|
|
72
|
-
"type": "git",
|
|
73
|
-
"url": "git+https://github.com/isfhan/burger-api.git"
|
|
74
|
-
},
|
|
75
|
-
"bugs": {
|
|
76
|
-
"url": "https://github.com/isfhan/burger-api/issues"
|
|
77
|
-
},
|
|
78
|
-
"homepage": "https://burger-api.com",
|
|
79
|
-
"dependencies": {
|
|
80
|
-
"zod": "^4.0.17"
|
|
81
|
-
},
|
|
82
|
-
"devDependencies": {
|
|
83
|
-
"@types/bun": "latest",
|
|
84
|
-
"tsc-alias": "^1.8.16"
|
|
85
|
-
},
|
|
86
|
-
"peerDependencies": {
|
|
87
|
-
"typescript": "^5.7.3"
|
|
88
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"name": "burger-api",
|
|
3
|
+
"version": "0.4.0",
|
|
4
|
+
"author": "Isfhan Ahmed",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"module": "dist/src/index.js",
|
|
7
|
+
"types": "dist/src/index.d.ts",
|
|
8
|
+
"files": [
|
|
9
|
+
"dist"
|
|
10
|
+
],
|
|
11
|
+
"scripts": {
|
|
12
|
+
"typecheck": "tsc --noEmit",
|
|
13
|
+
"build": "tsc --project tsconfig.build.json && tsc-alias -p tsconfig.build.json",
|
|
14
|
+
"test": "bun test",
|
|
15
|
+
"dev": "bun run examples/file-base-static-page-routing-app/index.ts"
|
|
16
|
+
},
|
|
17
|
+
"keywords": [
|
|
18
|
+
"burger-api",
|
|
19
|
+
"burger-api-framework",
|
|
20
|
+
"bun",
|
|
21
|
+
"bunjs",
|
|
22
|
+
"bun-framework",
|
|
23
|
+
"fast-backend",
|
|
24
|
+
"javascript-backend",
|
|
25
|
+
"high-performance",
|
|
26
|
+
"esm",
|
|
27
|
+
"typescript",
|
|
28
|
+
"openapi",
|
|
29
|
+
"swagger-ui",
|
|
30
|
+
"declarative-routing",
|
|
31
|
+
"api-framework",
|
|
32
|
+
"modern-backend",
|
|
33
|
+
"backend-framework",
|
|
34
|
+
"server",
|
|
35
|
+
"bun-native",
|
|
36
|
+
"js-backend",
|
|
37
|
+
"fast-api",
|
|
38
|
+
"scalable-backend",
|
|
39
|
+
"backend-development",
|
|
40
|
+
"modern-api",
|
|
41
|
+
"api-development",
|
|
42
|
+
"backend-engine",
|
|
43
|
+
"efficient",
|
|
44
|
+
"minimalist-backend",
|
|
45
|
+
"bun-powered",
|
|
46
|
+
"open-source",
|
|
47
|
+
"typescript-backend",
|
|
48
|
+
"performance",
|
|
49
|
+
"rapid-development",
|
|
50
|
+
"web-framework",
|
|
51
|
+
"api-server",
|
|
52
|
+
"dynamic-routing",
|
|
53
|
+
"backend-routing",
|
|
54
|
+
"extensible",
|
|
55
|
+
"modular",
|
|
56
|
+
"declarative-api",
|
|
57
|
+
"lightweight",
|
|
58
|
+
"contemporary-backend",
|
|
59
|
+
"fast-javascript",
|
|
60
|
+
"bun-js-framework",
|
|
61
|
+
"bun-backend",
|
|
62
|
+
"bun-api-framework",
|
|
63
|
+
"pakistan-backend",
|
|
64
|
+
"pakistan-api-framework",
|
|
65
|
+
"pakistan-api-server",
|
|
66
|
+
"pakistan-backend-framework",
|
|
67
|
+
"pakistan-bunjs-framework",
|
|
68
|
+
"pakistan-javascript-framework"
|
|
69
|
+
],
|
|
70
|
+
"license": "MIT",
|
|
71
|
+
"repository": {
|
|
72
|
+
"type": "git",
|
|
73
|
+
"url": "git+https://github.com/isfhan/burger-api.git"
|
|
74
|
+
},
|
|
75
|
+
"bugs": {
|
|
76
|
+
"url": "https://github.com/isfhan/burger-api/issues"
|
|
77
|
+
},
|
|
78
|
+
"homepage": "https://burger-api.com",
|
|
79
|
+
"dependencies": {
|
|
80
|
+
"zod": "^4.0.17"
|
|
81
|
+
},
|
|
82
|
+
"devDependencies": {
|
|
83
|
+
"@types/bun": "latest",
|
|
84
|
+
"tsc-alias": "^1.8.16"
|
|
85
|
+
},
|
|
86
|
+
"peerDependencies": {
|
|
87
|
+
"typescript": "^5.7.3"
|
|
88
|
+
}
|
|
89
89
|
}
|