@gravito/core 1.0.0-beta.6 → 1.1.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 +2 -0
- package/dist/compat.d.cts +1 -0
- package/dist/compat.d.ts +1 -0
- package/dist/engine/index.cjs +1173 -0
- package/dist/engine/index.d.cts +612 -0
- package/dist/engine/index.d.ts +612 -0
- package/dist/engine/index.js +1141 -0
- package/dist/index.cjs +953 -8
- package/dist/index.d.cts +632 -1
- package/dist/index.d.ts +632 -1
- package/dist/index.js +957 -8
- package/package.json +6 -1
|
@@ -0,0 +1,1141 @@
|
|
|
1
|
+
// src/adapters/bun/RadixNode.ts
|
|
2
|
+
var RadixNode = class _RadixNode {
|
|
3
|
+
// Path segment for this node (e.g., "users", ":id")
|
|
4
|
+
segment;
|
|
5
|
+
// Node type (Static, Param, Wildcard)
|
|
6
|
+
type;
|
|
7
|
+
// Children nodes (mapped by segment for fast lookup)
|
|
8
|
+
children = /* @__PURE__ */ new Map();
|
|
9
|
+
// Specialized child for parameter node (only one per level allowed usually to avoid ambiguity, though some routers support multiple)
|
|
10
|
+
paramChild = null;
|
|
11
|
+
// Specialized child for wildcard node
|
|
12
|
+
wildcardChild = null;
|
|
13
|
+
// Handlers registered at this node (keyed by HTTP method)
|
|
14
|
+
handlers = /* @__PURE__ */ new Map();
|
|
15
|
+
// Parameter name if this is a PARAM node (e.g., "id" for ":id")
|
|
16
|
+
paramName = null;
|
|
17
|
+
// Parameter constraints (regex) - only applicable if this is a PARAM node
|
|
18
|
+
// If we support per-route constraints, they might need to be stored differently,
|
|
19
|
+
// but for now assume constraints are defined at node level (uncommon) or checked at match time.
|
|
20
|
+
// Laravel allows global pattern constraints or per-route.
|
|
21
|
+
// Ideally, constraints should be stored with the handler or part of matching logic.
|
|
22
|
+
// For a Radix tree, if we have constraints, we might need to backtrack if constraint fails?
|
|
23
|
+
// Or simply store constraint with the param node.
|
|
24
|
+
regex = null;
|
|
25
|
+
constructor(segment = "", type = 0 /* STATIC */) {
|
|
26
|
+
this.segment = segment;
|
|
27
|
+
this.type = type;
|
|
28
|
+
}
|
|
29
|
+
toJSON() {
|
|
30
|
+
return {
|
|
31
|
+
segment: this.segment,
|
|
32
|
+
type: this.type,
|
|
33
|
+
children: Array.from(this.children.entries()).map(([k, v]) => [k, v.toJSON()]),
|
|
34
|
+
paramChild: this.paramChild?.toJSON() || null,
|
|
35
|
+
wildcardChild: this.wildcardChild?.toJSON() || null,
|
|
36
|
+
paramName: this.paramName,
|
|
37
|
+
regex: this.regex ? this.regex.source : null
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
static fromJSON(json) {
|
|
41
|
+
const node = new _RadixNode(json.segment, json.type);
|
|
42
|
+
node.paramName = json.paramName;
|
|
43
|
+
if (json.regex) {
|
|
44
|
+
node.regex = new RegExp(json.regex);
|
|
45
|
+
}
|
|
46
|
+
if (json.children) {
|
|
47
|
+
for (const [key, childJson] of json.children) {
|
|
48
|
+
node.children.set(key, _RadixNode.fromJSON(childJson));
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
if (json.paramChild) {
|
|
52
|
+
node.paramChild = _RadixNode.fromJSON(json.paramChild);
|
|
53
|
+
}
|
|
54
|
+
if (json.wildcardChild) {
|
|
55
|
+
node.wildcardChild = _RadixNode.fromJSON(json.wildcardChild);
|
|
56
|
+
}
|
|
57
|
+
return node;
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
// src/adapters/bun/RadixRouter.ts
|
|
62
|
+
var RadixRouter = class _RadixRouter {
|
|
63
|
+
root = new RadixNode();
|
|
64
|
+
// Global parameter constraints (e.g., id => /^\d+$/)
|
|
65
|
+
globalConstraints = /* @__PURE__ */ new Map();
|
|
66
|
+
/**
|
|
67
|
+
* Add a generic parameter constraint
|
|
68
|
+
*/
|
|
69
|
+
where(param, regex) {
|
|
70
|
+
this.globalConstraints.set(param, regex);
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Register a route
|
|
74
|
+
*/
|
|
75
|
+
add(method, path, handlers) {
|
|
76
|
+
let node = this.root;
|
|
77
|
+
const segments = this.splitPath(path);
|
|
78
|
+
for (let i = 0; i < segments.length; i++) {
|
|
79
|
+
const segment = segments[i];
|
|
80
|
+
if (segment === "*") {
|
|
81
|
+
if (!node.wildcardChild) {
|
|
82
|
+
node.wildcardChild = new RadixNode("*", 2 /* WILDCARD */);
|
|
83
|
+
}
|
|
84
|
+
node = node.wildcardChild;
|
|
85
|
+
break;
|
|
86
|
+
} else if (segment.startsWith(":")) {
|
|
87
|
+
const paramName = segment.slice(1);
|
|
88
|
+
if (!node.paramChild) {
|
|
89
|
+
const child = new RadixNode(segment, 1 /* PARAM */);
|
|
90
|
+
child.paramName = paramName;
|
|
91
|
+
const constraint = this.globalConstraints.get(paramName);
|
|
92
|
+
if (constraint) {
|
|
93
|
+
child.regex = constraint;
|
|
94
|
+
}
|
|
95
|
+
node.paramChild = child;
|
|
96
|
+
}
|
|
97
|
+
node = node.paramChild;
|
|
98
|
+
} else {
|
|
99
|
+
if (!node.children.has(segment)) {
|
|
100
|
+
node.children.set(segment, new RadixNode(segment, 0 /* STATIC */));
|
|
101
|
+
}
|
|
102
|
+
node = node.children.get(segment);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
node.handlers.set(method.toLowerCase(), handlers);
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Match a request
|
|
109
|
+
*/
|
|
110
|
+
match(method, path) {
|
|
111
|
+
const normalizedMethod = method.toLowerCase();
|
|
112
|
+
if (path === "/" || path === "") {
|
|
113
|
+
const handlers = this.root.handlers.get(normalizedMethod);
|
|
114
|
+
if (handlers) {
|
|
115
|
+
return { handlers, params: {} };
|
|
116
|
+
}
|
|
117
|
+
return null;
|
|
118
|
+
}
|
|
119
|
+
const searchPath = path.startsWith("/") ? path.slice(1) : path;
|
|
120
|
+
const segments = searchPath.split("/");
|
|
121
|
+
return this.matchRecursive(this.root, segments, 0, {}, normalizedMethod);
|
|
122
|
+
}
|
|
123
|
+
matchRecursive(node, segments, depth, params, method) {
|
|
124
|
+
if (depth >= segments.length) {
|
|
125
|
+
let handlers = node.handlers.get(method);
|
|
126
|
+
if (!handlers) {
|
|
127
|
+
handlers = node.handlers.get("all");
|
|
128
|
+
}
|
|
129
|
+
if (handlers) {
|
|
130
|
+
return { handlers, params };
|
|
131
|
+
}
|
|
132
|
+
return null;
|
|
133
|
+
}
|
|
134
|
+
const segment = segments[depth];
|
|
135
|
+
const staticChild = node.children.get(segment);
|
|
136
|
+
if (staticChild) {
|
|
137
|
+
const match = this.matchRecursive(staticChild, segments, depth + 1, params, method);
|
|
138
|
+
if (match) {
|
|
139
|
+
return match;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
const paramChild = node.paramChild;
|
|
143
|
+
if (paramChild) {
|
|
144
|
+
if (paramChild.regex && !paramChild.regex.test(segment)) {
|
|
145
|
+
} else {
|
|
146
|
+
if (paramChild.paramName) {
|
|
147
|
+
params[paramChild.paramName] = decodeURIComponent(segment);
|
|
148
|
+
const match = this.matchRecursive(paramChild, segments, depth + 1, params, method);
|
|
149
|
+
if (match) {
|
|
150
|
+
return match;
|
|
151
|
+
}
|
|
152
|
+
delete params[paramChild.paramName];
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
if (node.wildcardChild) {
|
|
157
|
+
let handlers = node.wildcardChild.handlers.get(method);
|
|
158
|
+
if (!handlers) {
|
|
159
|
+
handlers = node.wildcardChild.handlers.get("all");
|
|
160
|
+
}
|
|
161
|
+
if (handlers) {
|
|
162
|
+
return { handlers, params };
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
return null;
|
|
166
|
+
}
|
|
167
|
+
splitPath(path) {
|
|
168
|
+
if (path === "/" || path === "") {
|
|
169
|
+
return [];
|
|
170
|
+
}
|
|
171
|
+
let p = path;
|
|
172
|
+
if (p.startsWith("/")) {
|
|
173
|
+
p = p.slice(1);
|
|
174
|
+
}
|
|
175
|
+
if (p.endsWith("/")) {
|
|
176
|
+
p = p.slice(0, -1);
|
|
177
|
+
}
|
|
178
|
+
return p.split("/");
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Serialize the router to a JSON string
|
|
182
|
+
*/
|
|
183
|
+
serialize() {
|
|
184
|
+
return JSON.stringify({
|
|
185
|
+
root: this.root.toJSON(),
|
|
186
|
+
globalConstraints: Array.from(this.globalConstraints.entries()).map(([k, v]) => [
|
|
187
|
+
k,
|
|
188
|
+
v.source
|
|
189
|
+
])
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Restore a router from a serialized JSON string
|
|
194
|
+
*/
|
|
195
|
+
static fromSerialized(json) {
|
|
196
|
+
const data = JSON.parse(json);
|
|
197
|
+
const router = new _RadixRouter();
|
|
198
|
+
router.root = RadixNode.fromJSON(data.root);
|
|
199
|
+
if (data.globalConstraints) {
|
|
200
|
+
for (const [key, source] of data.globalConstraints) {
|
|
201
|
+
router.globalConstraints.set(key, new RegExp(source));
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
return router;
|
|
205
|
+
}
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
// src/engine/AOTRouter.ts
|
|
209
|
+
var AOTRouter = class {
|
|
210
|
+
// Static route cache: "METHOD:PATH" -> RouteMetadata
|
|
211
|
+
staticRoutes = /* @__PURE__ */ new Map();
|
|
212
|
+
// Dynamic route handler (Radix Tree)
|
|
213
|
+
dynamicRouter = new RadixRouter();
|
|
214
|
+
// Global middleware (applies to all routes)
|
|
215
|
+
globalMiddleware = [];
|
|
216
|
+
// Path-based middleware: pattern -> middleware[]
|
|
217
|
+
pathMiddleware = /* @__PURE__ */ new Map();
|
|
218
|
+
/**
|
|
219
|
+
* Register a route
|
|
220
|
+
*
|
|
221
|
+
* Automatically determines if route is static or dynamic.
|
|
222
|
+
* Static routes are stored in a Map for O(1) lookup.
|
|
223
|
+
* Dynamic routes use the Radix Tree.
|
|
224
|
+
*
|
|
225
|
+
* @param method - HTTP method
|
|
226
|
+
* @param path - Route path
|
|
227
|
+
* @param handler - Route handler
|
|
228
|
+
* @param middleware - Route-specific middleware
|
|
229
|
+
*/
|
|
230
|
+
add(method, path, handler, middleware = []) {
|
|
231
|
+
const normalizedMethod = method.toLowerCase();
|
|
232
|
+
if (this.isStaticPath(path)) {
|
|
233
|
+
const key = `${normalizedMethod}:${path}`;
|
|
234
|
+
this.staticRoutes.set(key, { handler, middleware });
|
|
235
|
+
} else {
|
|
236
|
+
const wrappedHandler = handler;
|
|
237
|
+
this.dynamicRouter.add(normalizedMethod, path, [wrappedHandler]);
|
|
238
|
+
if (middleware.length > 0) {
|
|
239
|
+
this.pathMiddleware.set(`${normalizedMethod}:${path}`, middleware);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* Add global middleware
|
|
245
|
+
*
|
|
246
|
+
* These run for every request, before route-specific middleware.
|
|
247
|
+
*
|
|
248
|
+
* @param middleware - Middleware functions
|
|
249
|
+
*/
|
|
250
|
+
use(...middleware) {
|
|
251
|
+
this.globalMiddleware.push(...middleware);
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* Add path-based middleware
|
|
255
|
+
*
|
|
256
|
+
* Supports wildcard patterns like '/api/*'
|
|
257
|
+
*
|
|
258
|
+
* @param pattern - Path pattern
|
|
259
|
+
* @param middleware - Middleware functions
|
|
260
|
+
*/
|
|
261
|
+
usePattern(pattern, ...middleware) {
|
|
262
|
+
const existing = this.pathMiddleware.get(pattern) ?? [];
|
|
263
|
+
this.pathMiddleware.set(pattern, [...existing, ...middleware]);
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* Match a request to a route
|
|
267
|
+
*
|
|
268
|
+
* Returns the handler, params, and all applicable middleware.
|
|
269
|
+
*
|
|
270
|
+
* @param method - HTTP method
|
|
271
|
+
* @param path - Request path
|
|
272
|
+
* @returns Route match or null if not found
|
|
273
|
+
*/
|
|
274
|
+
match(method, path) {
|
|
275
|
+
const normalizedMethod = method.toLowerCase();
|
|
276
|
+
const staticKey = `${normalizedMethod}:${path}`;
|
|
277
|
+
const staticRoute = this.staticRoutes.get(staticKey);
|
|
278
|
+
if (staticRoute) {
|
|
279
|
+
return {
|
|
280
|
+
handler: staticRoute.handler,
|
|
281
|
+
params: {},
|
|
282
|
+
middleware: this.collectMiddleware(path, staticRoute.middleware)
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
const match = this.dynamicRouter.match(normalizedMethod, path);
|
|
286
|
+
if (match && match.handlers.length > 0) {
|
|
287
|
+
const handler = match.handlers[0];
|
|
288
|
+
const routeKey = this.findDynamicRouteKey(normalizedMethod, path);
|
|
289
|
+
const routeMiddleware = routeKey ? this.pathMiddleware.get(routeKey) ?? [] : [];
|
|
290
|
+
return {
|
|
291
|
+
handler,
|
|
292
|
+
params: match.params,
|
|
293
|
+
middleware: this.collectMiddleware(path, routeMiddleware)
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
return {
|
|
297
|
+
handler: null,
|
|
298
|
+
params: {},
|
|
299
|
+
middleware: []
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
/**
|
|
303
|
+
* Public wrapper for collectMiddleware (used by Gravito for optimization)
|
|
304
|
+
*/
|
|
305
|
+
collectMiddlewarePublic(path, routeMiddleware) {
|
|
306
|
+
return this.collectMiddleware(path, routeMiddleware);
|
|
307
|
+
}
|
|
308
|
+
/**
|
|
309
|
+
* Collect all applicable middleware for a path
|
|
310
|
+
*
|
|
311
|
+
* Order: global -> pattern-based -> route-specific
|
|
312
|
+
*
|
|
313
|
+
* @param path - Request path
|
|
314
|
+
* @param routeMiddleware - Route-specific middleware
|
|
315
|
+
* @returns Combined middleware array
|
|
316
|
+
*/
|
|
317
|
+
collectMiddleware(path, routeMiddleware) {
|
|
318
|
+
if (this.globalMiddleware.length === 0 && this.pathMiddleware.size === 0 && routeMiddleware.length === 0) {
|
|
319
|
+
return [];
|
|
320
|
+
}
|
|
321
|
+
const middleware = [];
|
|
322
|
+
if (this.globalMiddleware.length > 0) {
|
|
323
|
+
middleware.push(...this.globalMiddleware);
|
|
324
|
+
}
|
|
325
|
+
if (this.pathMiddleware.size > 0) {
|
|
326
|
+
for (const [pattern, mw] of this.pathMiddleware) {
|
|
327
|
+
if (pattern.includes(":")) continue;
|
|
328
|
+
if (this.matchPattern(pattern, path)) {
|
|
329
|
+
middleware.push(...mw);
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
if (routeMiddleware.length > 0) {
|
|
334
|
+
middleware.push(...routeMiddleware);
|
|
335
|
+
}
|
|
336
|
+
return middleware;
|
|
337
|
+
}
|
|
338
|
+
/**
|
|
339
|
+
* Check if a path is static (no parameters or wildcards)
|
|
340
|
+
*/
|
|
341
|
+
isStaticPath(path) {
|
|
342
|
+
return !path.includes(":") && !path.includes("*");
|
|
343
|
+
}
|
|
344
|
+
/**
|
|
345
|
+
* Match a pattern against a path
|
|
346
|
+
*
|
|
347
|
+
* Supports:
|
|
348
|
+
* - Exact match: '/api/users'
|
|
349
|
+
* - Wildcard suffix: '/api/*'
|
|
350
|
+
*
|
|
351
|
+
* @param pattern - Pattern to match
|
|
352
|
+
* @param path - Path to test
|
|
353
|
+
* @returns True if pattern matches
|
|
354
|
+
*/
|
|
355
|
+
matchPattern(pattern, path) {
|
|
356
|
+
if (pattern === "*") return true;
|
|
357
|
+
if (pattern === path) return true;
|
|
358
|
+
if (pattern.endsWith("/*")) {
|
|
359
|
+
const prefix = pattern.slice(0, -2);
|
|
360
|
+
return path.startsWith(prefix);
|
|
361
|
+
}
|
|
362
|
+
return false;
|
|
363
|
+
}
|
|
364
|
+
/**
|
|
365
|
+
* Find the original route key for a matched dynamic route
|
|
366
|
+
*
|
|
367
|
+
* This is needed to look up route-specific middleware.
|
|
368
|
+
* It's a bit of a hack, but avoids storing duplicate data.
|
|
369
|
+
*
|
|
370
|
+
* @param method - HTTP method
|
|
371
|
+
* @param path - Matched path
|
|
372
|
+
* @returns Route key or null
|
|
373
|
+
*/
|
|
374
|
+
findDynamicRouteKey(method, path) {
|
|
375
|
+
for (const key of this.pathMiddleware.keys()) {
|
|
376
|
+
if (key.startsWith(`${method}:`)) {
|
|
377
|
+
return key;
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
return null;
|
|
381
|
+
}
|
|
382
|
+
/**
|
|
383
|
+
* Get all registered routes (for debugging)
|
|
384
|
+
*/
|
|
385
|
+
getRoutes() {
|
|
386
|
+
const routes = [];
|
|
387
|
+
for (const key of this.staticRoutes.keys()) {
|
|
388
|
+
const [method, path] = key.split(":");
|
|
389
|
+
routes.push({ method, path, type: "static" });
|
|
390
|
+
}
|
|
391
|
+
return routes;
|
|
392
|
+
}
|
|
393
|
+
};
|
|
394
|
+
|
|
395
|
+
// src/engine/analyzer.ts
|
|
396
|
+
function analyzeHandler(handler) {
|
|
397
|
+
const source = handler.toString();
|
|
398
|
+
return {
|
|
399
|
+
usesHeaders: source.includes(".header(") || source.includes(".header)") || source.includes(".headers(") || source.includes(".headers)"),
|
|
400
|
+
usesQuery: source.includes(".query(") || source.includes(".query)") || source.includes(".queries(") || source.includes(".queries)"),
|
|
401
|
+
usesBody: source.includes(".json()") || source.includes(".text()") || source.includes(".formData()") || source.includes(".body"),
|
|
402
|
+
usesParams: source.includes(".param(") || source.includes(".param)") || source.includes(".params(") || source.includes(".params)"),
|
|
403
|
+
isAsync: source.includes("async") || source.includes("await")
|
|
404
|
+
};
|
|
405
|
+
}
|
|
406
|
+
function getOptimalContextType(analysis) {
|
|
407
|
+
if (analysis.usesHeaders) {
|
|
408
|
+
return "fast";
|
|
409
|
+
}
|
|
410
|
+
if (!analysis.usesQuery && !analysis.usesBody && !analysis.usesParams) {
|
|
411
|
+
return "minimal";
|
|
412
|
+
}
|
|
413
|
+
if (!analysis.usesQuery && !analysis.usesBody && analysis.usesParams) {
|
|
414
|
+
return "minimal";
|
|
415
|
+
}
|
|
416
|
+
if (analysis.usesBody) {
|
|
417
|
+
return "full";
|
|
418
|
+
}
|
|
419
|
+
return "fast";
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
// src/engine/FastContext.ts
|
|
423
|
+
var FastRequestImpl = class {
|
|
424
|
+
_request;
|
|
425
|
+
_params;
|
|
426
|
+
_url = new URL("http://localhost");
|
|
427
|
+
// Reuse this object
|
|
428
|
+
_query = null;
|
|
429
|
+
_headers = null;
|
|
430
|
+
/**
|
|
431
|
+
* Reset for pooling
|
|
432
|
+
*/
|
|
433
|
+
reset(request, params = {}) {
|
|
434
|
+
this._request = request;
|
|
435
|
+
this._params = params;
|
|
436
|
+
this._url.href = request.url;
|
|
437
|
+
this._query = null;
|
|
438
|
+
this._headers = null;
|
|
439
|
+
}
|
|
440
|
+
get url() {
|
|
441
|
+
return this._request.url;
|
|
442
|
+
}
|
|
443
|
+
get method() {
|
|
444
|
+
return this._request.method;
|
|
445
|
+
}
|
|
446
|
+
get path() {
|
|
447
|
+
return this._url.pathname;
|
|
448
|
+
}
|
|
449
|
+
param(name) {
|
|
450
|
+
return this._params[name];
|
|
451
|
+
}
|
|
452
|
+
params() {
|
|
453
|
+
return { ...this._params };
|
|
454
|
+
}
|
|
455
|
+
query(name) {
|
|
456
|
+
if (!this._query) {
|
|
457
|
+
this._query = this._url.searchParams;
|
|
458
|
+
}
|
|
459
|
+
return this._query.get(name) ?? void 0;
|
|
460
|
+
}
|
|
461
|
+
queries() {
|
|
462
|
+
if (!this._query) {
|
|
463
|
+
this._query = this._url.searchParams;
|
|
464
|
+
}
|
|
465
|
+
const result = {};
|
|
466
|
+
for (const [key, value] of this._query.entries()) {
|
|
467
|
+
const existing = result[key];
|
|
468
|
+
if (existing === void 0) {
|
|
469
|
+
result[key] = value;
|
|
470
|
+
} else if (Array.isArray(existing)) {
|
|
471
|
+
existing.push(value);
|
|
472
|
+
} else {
|
|
473
|
+
result[key] = [existing, value];
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
return result;
|
|
477
|
+
}
|
|
478
|
+
header(name) {
|
|
479
|
+
return this._request.headers.get(name) ?? void 0;
|
|
480
|
+
}
|
|
481
|
+
headers() {
|
|
482
|
+
if (!this._headers) {
|
|
483
|
+
this._headers = {};
|
|
484
|
+
for (const [key, value] of this._request.headers.entries()) {
|
|
485
|
+
this._headers[key] = value;
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
return { ...this._headers };
|
|
489
|
+
}
|
|
490
|
+
async json() {
|
|
491
|
+
return this._request.json();
|
|
492
|
+
}
|
|
493
|
+
async text() {
|
|
494
|
+
return this._request.text();
|
|
495
|
+
}
|
|
496
|
+
async formData() {
|
|
497
|
+
return this._request.formData();
|
|
498
|
+
}
|
|
499
|
+
get raw() {
|
|
500
|
+
return this._request;
|
|
501
|
+
}
|
|
502
|
+
};
|
|
503
|
+
var FastContext = class {
|
|
504
|
+
_req = new FastRequestImpl();
|
|
505
|
+
_statusCode = 200;
|
|
506
|
+
_headers = new Headers();
|
|
507
|
+
// Reuse this object
|
|
508
|
+
/**
|
|
509
|
+
* Reset context for pooling
|
|
510
|
+
*
|
|
511
|
+
* This is called when acquiring from the pool.
|
|
512
|
+
* Must clear all state from previous request.
|
|
513
|
+
*/
|
|
514
|
+
reset(request, params = {}) {
|
|
515
|
+
this._req.reset(request, params);
|
|
516
|
+
this._statusCode = 200;
|
|
517
|
+
this._headers = new Headers();
|
|
518
|
+
return this;
|
|
519
|
+
}
|
|
520
|
+
get req() {
|
|
521
|
+
return this._req;
|
|
522
|
+
}
|
|
523
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
524
|
+
// Response Helpers
|
|
525
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
526
|
+
json(data, status = 200) {
|
|
527
|
+
this._headers.set("Content-Type", "application/json; charset=utf-8");
|
|
528
|
+
return new Response(JSON.stringify(data), {
|
|
529
|
+
status,
|
|
530
|
+
headers: this._headers
|
|
531
|
+
});
|
|
532
|
+
}
|
|
533
|
+
text(text, status = 200) {
|
|
534
|
+
this._headers.set("Content-Type", "text/plain; charset=utf-8");
|
|
535
|
+
return new Response(text, {
|
|
536
|
+
status,
|
|
537
|
+
headers: this._headers
|
|
538
|
+
});
|
|
539
|
+
}
|
|
540
|
+
html(html, status = 200) {
|
|
541
|
+
this._headers.set("Content-Type", "text/html; charset=utf-8");
|
|
542
|
+
return new Response(html, {
|
|
543
|
+
status,
|
|
544
|
+
headers: this._headers
|
|
545
|
+
});
|
|
546
|
+
}
|
|
547
|
+
redirect(url, status = 302) {
|
|
548
|
+
this._headers.set("Location", url);
|
|
549
|
+
return new Response(null, {
|
|
550
|
+
status,
|
|
551
|
+
headers: this._headers
|
|
552
|
+
});
|
|
553
|
+
}
|
|
554
|
+
body(data, status = 200) {
|
|
555
|
+
return new Response(data, {
|
|
556
|
+
status,
|
|
557
|
+
headers: this._headers
|
|
558
|
+
});
|
|
559
|
+
}
|
|
560
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
561
|
+
// Header Management
|
|
562
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
563
|
+
header(name, value) {
|
|
564
|
+
this._headers.set(name, value);
|
|
565
|
+
}
|
|
566
|
+
status(code) {
|
|
567
|
+
this._statusCode = code;
|
|
568
|
+
}
|
|
569
|
+
};
|
|
570
|
+
|
|
571
|
+
// src/engine/MinimalContext.ts
|
|
572
|
+
var MinimalRequest = class {
|
|
573
|
+
constructor(_request, _params, _path) {
|
|
574
|
+
this._request = _request;
|
|
575
|
+
this._params = _params;
|
|
576
|
+
this._path = _path;
|
|
577
|
+
}
|
|
578
|
+
get url() {
|
|
579
|
+
return this._request.url;
|
|
580
|
+
}
|
|
581
|
+
get method() {
|
|
582
|
+
return this._request.method;
|
|
583
|
+
}
|
|
584
|
+
get path() {
|
|
585
|
+
return this._path;
|
|
586
|
+
}
|
|
587
|
+
param(name) {
|
|
588
|
+
return this._params[name];
|
|
589
|
+
}
|
|
590
|
+
params() {
|
|
591
|
+
return { ...this._params };
|
|
592
|
+
}
|
|
593
|
+
query(name) {
|
|
594
|
+
const url = new URL(this._request.url);
|
|
595
|
+
return url.searchParams.get(name) ?? void 0;
|
|
596
|
+
}
|
|
597
|
+
queries() {
|
|
598
|
+
const url = new URL(this._request.url);
|
|
599
|
+
const result = {};
|
|
600
|
+
for (const [key, value] of url.searchParams.entries()) {
|
|
601
|
+
const existing = result[key];
|
|
602
|
+
if (existing === void 0) {
|
|
603
|
+
result[key] = value;
|
|
604
|
+
} else if (Array.isArray(existing)) {
|
|
605
|
+
existing.push(value);
|
|
606
|
+
} else {
|
|
607
|
+
result[key] = [existing, value];
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
return result;
|
|
611
|
+
}
|
|
612
|
+
header(name) {
|
|
613
|
+
return this._request.headers.get(name) ?? void 0;
|
|
614
|
+
}
|
|
615
|
+
headers() {
|
|
616
|
+
const result = {};
|
|
617
|
+
for (const [key, value] of this._request.headers.entries()) {
|
|
618
|
+
result[key] = value;
|
|
619
|
+
}
|
|
620
|
+
return result;
|
|
621
|
+
}
|
|
622
|
+
async json() {
|
|
623
|
+
return this._request.json();
|
|
624
|
+
}
|
|
625
|
+
async text() {
|
|
626
|
+
return this._request.text();
|
|
627
|
+
}
|
|
628
|
+
async formData() {
|
|
629
|
+
return this._request.formData();
|
|
630
|
+
}
|
|
631
|
+
get raw() {
|
|
632
|
+
return this._request;
|
|
633
|
+
}
|
|
634
|
+
};
|
|
635
|
+
var MinimalContext = class {
|
|
636
|
+
_req;
|
|
637
|
+
constructor(request, params, path) {
|
|
638
|
+
this._req = new MinimalRequest(request, params, path);
|
|
639
|
+
}
|
|
640
|
+
get req() {
|
|
641
|
+
return this._req;
|
|
642
|
+
}
|
|
643
|
+
// Response helpers - create headers inline (no reuse overhead)
|
|
644
|
+
json(data, status = 200) {
|
|
645
|
+
return new Response(JSON.stringify(data), {
|
|
646
|
+
status,
|
|
647
|
+
headers: { "Content-Type": "application/json; charset=utf-8" }
|
|
648
|
+
});
|
|
649
|
+
}
|
|
650
|
+
text(text, status = 200) {
|
|
651
|
+
return new Response(text, {
|
|
652
|
+
status,
|
|
653
|
+
headers: { "Content-Type": "text/plain; charset=utf-8" }
|
|
654
|
+
});
|
|
655
|
+
}
|
|
656
|
+
html(html, status = 200) {
|
|
657
|
+
return new Response(html, {
|
|
658
|
+
status,
|
|
659
|
+
headers: { "Content-Type": "text/html; charset=utf-8" }
|
|
660
|
+
});
|
|
661
|
+
}
|
|
662
|
+
redirect(url, status = 302) {
|
|
663
|
+
return new Response(null, {
|
|
664
|
+
status,
|
|
665
|
+
headers: { Location: url }
|
|
666
|
+
});
|
|
667
|
+
}
|
|
668
|
+
body(data, status = 200) {
|
|
669
|
+
return new Response(data, { status });
|
|
670
|
+
}
|
|
671
|
+
header(_name, _value) {
|
|
672
|
+
console.warn("MinimalContext.header() is a no-op. Use FastContext for custom headers.");
|
|
673
|
+
}
|
|
674
|
+
status(_code) {
|
|
675
|
+
}
|
|
676
|
+
// Required for interface compatibility
|
|
677
|
+
reset(_request, _params) {
|
|
678
|
+
throw new Error("MinimalContext does not support reset. Create a new instance instead.");
|
|
679
|
+
}
|
|
680
|
+
};
|
|
681
|
+
|
|
682
|
+
// src/engine/path.ts
|
|
683
|
+
function extractPath(url) {
|
|
684
|
+
const protocolEnd = url.indexOf("://");
|
|
685
|
+
const searchStart = protocolEnd === -1 ? 0 : protocolEnd + 3;
|
|
686
|
+
const pathStart = url.indexOf("/", searchStart);
|
|
687
|
+
if (pathStart === -1) {
|
|
688
|
+
return "/";
|
|
689
|
+
}
|
|
690
|
+
const queryStart = url.indexOf("?", pathStart);
|
|
691
|
+
if (queryStart === -1) {
|
|
692
|
+
return url.slice(pathStart);
|
|
693
|
+
}
|
|
694
|
+
return url.slice(pathStart, queryStart);
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
// src/engine/pool.ts
|
|
698
|
+
var ObjectPool = class {
|
|
699
|
+
pool = [];
|
|
700
|
+
factory;
|
|
701
|
+
reset;
|
|
702
|
+
maxSize;
|
|
703
|
+
/**
|
|
704
|
+
* Create a new object pool
|
|
705
|
+
*
|
|
706
|
+
* @param factory - Function to create new objects
|
|
707
|
+
* @param reset - Function to reset objects before reuse
|
|
708
|
+
* @param maxSize - Maximum pool size (default: 256)
|
|
709
|
+
*/
|
|
710
|
+
constructor(factory, reset, maxSize = 256) {
|
|
711
|
+
this.factory = factory;
|
|
712
|
+
this.reset = reset;
|
|
713
|
+
this.maxSize = maxSize;
|
|
714
|
+
}
|
|
715
|
+
/**
|
|
716
|
+
* Acquire an object from the pool
|
|
717
|
+
*
|
|
718
|
+
* If the pool is empty, creates a new object (overflow strategy).
|
|
719
|
+
* This ensures the pool never blocks under high load.
|
|
720
|
+
*
|
|
721
|
+
* @returns Object from pool or newly created
|
|
722
|
+
*/
|
|
723
|
+
acquire() {
|
|
724
|
+
const obj = this.pool.pop();
|
|
725
|
+
if (obj !== void 0) {
|
|
726
|
+
return obj;
|
|
727
|
+
}
|
|
728
|
+
return this.factory();
|
|
729
|
+
}
|
|
730
|
+
/**
|
|
731
|
+
* Release an object back to the pool
|
|
732
|
+
*
|
|
733
|
+
* If the pool is full, the object is discarded (will be GC'd).
|
|
734
|
+
* This prevents unbounded memory growth.
|
|
735
|
+
*
|
|
736
|
+
* @param obj - Object to release
|
|
737
|
+
*/
|
|
738
|
+
release(obj) {
|
|
739
|
+
if (this.pool.length < this.maxSize) {
|
|
740
|
+
this.reset(obj);
|
|
741
|
+
this.pool.push(obj);
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
/**
|
|
745
|
+
* Clear all objects from the pool
|
|
746
|
+
*
|
|
747
|
+
* Useful for testing or when you need to force a clean slate.
|
|
748
|
+
*/
|
|
749
|
+
clear() {
|
|
750
|
+
this.pool = [];
|
|
751
|
+
}
|
|
752
|
+
/**
|
|
753
|
+
* Get current pool size
|
|
754
|
+
*/
|
|
755
|
+
get size() {
|
|
756
|
+
return this.pool.length;
|
|
757
|
+
}
|
|
758
|
+
/**
|
|
759
|
+
* Get maximum pool size
|
|
760
|
+
*/
|
|
761
|
+
get capacity() {
|
|
762
|
+
return this.maxSize;
|
|
763
|
+
}
|
|
764
|
+
/**
|
|
765
|
+
* Pre-warm the pool by creating objects in advance
|
|
766
|
+
*
|
|
767
|
+
* This can reduce latency for the first N requests.
|
|
768
|
+
*
|
|
769
|
+
* @param count - Number of objects to pre-create
|
|
770
|
+
*/
|
|
771
|
+
prewarm(count) {
|
|
772
|
+
const targetSize = Math.min(count, this.maxSize);
|
|
773
|
+
while (this.pool.length < targetSize) {
|
|
774
|
+
const obj = this.factory();
|
|
775
|
+
this.reset(obj);
|
|
776
|
+
this.pool.push(obj);
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
};
|
|
780
|
+
|
|
781
|
+
// src/engine/Gravito.ts
|
|
782
|
+
var Gravito = class {
|
|
783
|
+
router = new AOTRouter();
|
|
784
|
+
contextPool;
|
|
785
|
+
errorHandler;
|
|
786
|
+
notFoundHandler;
|
|
787
|
+
// Direct reference to static routes Map (O(1) access)
|
|
788
|
+
// Optimization: Bypass getter/setter overhead
|
|
789
|
+
staticRoutes;
|
|
790
|
+
// Flag: pure static app (no middleware at all) allows ultra-fast path
|
|
791
|
+
isPureStaticApp = true;
|
|
792
|
+
/**
|
|
793
|
+
* Create a new Gravito instance
|
|
794
|
+
*
|
|
795
|
+
* @param options - Engine configuration options
|
|
796
|
+
*/
|
|
797
|
+
constructor(options = {}) {
|
|
798
|
+
const poolSize = options.poolSize ?? 256;
|
|
799
|
+
this.contextPool = new ObjectPool(
|
|
800
|
+
() => new FastContext(),
|
|
801
|
+
(ctx) => ctx.reset(new Request("http://localhost")),
|
|
802
|
+
poolSize
|
|
803
|
+
);
|
|
804
|
+
this.contextPool.prewarm(Math.min(32, poolSize));
|
|
805
|
+
if (options.onError) {
|
|
806
|
+
this.errorHandler = options.onError;
|
|
807
|
+
}
|
|
808
|
+
if (options.onNotFound) {
|
|
809
|
+
this.notFoundHandler = options.onNotFound;
|
|
810
|
+
}
|
|
811
|
+
this.compileRoutes();
|
|
812
|
+
}
|
|
813
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
814
|
+
// HTTP Method Registration
|
|
815
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
816
|
+
/**
|
|
817
|
+
* Register a GET route
|
|
818
|
+
*
|
|
819
|
+
* @param path - Route path (e.g., '/users/:id')
|
|
820
|
+
* @param handlers - Handler and optional middleware
|
|
821
|
+
* @returns This instance for chaining
|
|
822
|
+
*/
|
|
823
|
+
get(path, ...handlers) {
|
|
824
|
+
return this.addRoute("get", path, handlers);
|
|
825
|
+
}
|
|
826
|
+
/**
|
|
827
|
+
* Register a POST route
|
|
828
|
+
*/
|
|
829
|
+
post(path, ...handlers) {
|
|
830
|
+
return this.addRoute("post", path, handlers);
|
|
831
|
+
}
|
|
832
|
+
/**
|
|
833
|
+
* Register a PUT route
|
|
834
|
+
*/
|
|
835
|
+
put(path, ...handlers) {
|
|
836
|
+
return this.addRoute("put", path, handlers);
|
|
837
|
+
}
|
|
838
|
+
/**
|
|
839
|
+
* Register a DELETE route
|
|
840
|
+
*/
|
|
841
|
+
delete(path, ...handlers) {
|
|
842
|
+
return this.addRoute("delete", path, handlers);
|
|
843
|
+
}
|
|
844
|
+
/**
|
|
845
|
+
* Register a PATCH route
|
|
846
|
+
*/
|
|
847
|
+
patch(path, ...handlers) {
|
|
848
|
+
return this.addRoute("patch", path, handlers);
|
|
849
|
+
}
|
|
850
|
+
/**
|
|
851
|
+
* Register an OPTIONS route
|
|
852
|
+
*/
|
|
853
|
+
options(path, ...handlers) {
|
|
854
|
+
return this.addRoute("options", path, handlers);
|
|
855
|
+
}
|
|
856
|
+
/**
|
|
857
|
+
* Register a HEAD route
|
|
858
|
+
*/
|
|
859
|
+
head(path, ...handlers) {
|
|
860
|
+
return this.addRoute("head", path, handlers);
|
|
861
|
+
}
|
|
862
|
+
/**
|
|
863
|
+
* Register a route for all HTTP methods
|
|
864
|
+
*/
|
|
865
|
+
all(path, ...handlers) {
|
|
866
|
+
const methods = ["get", "post", "put", "delete", "patch", "options", "head"];
|
|
867
|
+
for (const method of methods) {
|
|
868
|
+
this.addRoute(method, path, handlers);
|
|
869
|
+
}
|
|
870
|
+
return this;
|
|
871
|
+
}
|
|
872
|
+
use(pathOrMiddleware, ...middleware) {
|
|
873
|
+
this.isPureStaticApp = false;
|
|
874
|
+
if (typeof pathOrMiddleware === "string") {
|
|
875
|
+
this.router.usePattern(pathOrMiddleware, ...middleware);
|
|
876
|
+
} else {
|
|
877
|
+
this.router.use(pathOrMiddleware, ...middleware);
|
|
878
|
+
}
|
|
879
|
+
return this;
|
|
880
|
+
}
|
|
881
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
882
|
+
// Route Grouping
|
|
883
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
884
|
+
/**
|
|
885
|
+
* Mount a sub-application at a path prefix
|
|
886
|
+
*
|
|
887
|
+
* @example
|
|
888
|
+
* ```typescript
|
|
889
|
+
* const api = new Gravito()
|
|
890
|
+
* api.get('/users', (c) => c.json({ users: [] }))
|
|
891
|
+
*
|
|
892
|
+
* const app = new Gravito()
|
|
893
|
+
* app.route('/api', api)
|
|
894
|
+
* // Now accessible at /api/users
|
|
895
|
+
* ```
|
|
896
|
+
*/
|
|
897
|
+
route(path, app) {
|
|
898
|
+
console.warn("route() method is not yet fully implemented");
|
|
899
|
+
return this;
|
|
900
|
+
}
|
|
901
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
902
|
+
// Error Handling
|
|
903
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
904
|
+
/**
|
|
905
|
+
* Set custom error handler
|
|
906
|
+
*
|
|
907
|
+
* @example
|
|
908
|
+
* ```typescript
|
|
909
|
+
* app.onError((err, c) => {
|
|
910
|
+
* console.error(err)
|
|
911
|
+
* return c.json({ error: err.message }, 500)
|
|
912
|
+
* })
|
|
913
|
+
* ```
|
|
914
|
+
*/
|
|
915
|
+
onError(handler) {
|
|
916
|
+
this.errorHandler = handler;
|
|
917
|
+
return this;
|
|
918
|
+
}
|
|
919
|
+
/**
|
|
920
|
+
* Set custom 404 handler
|
|
921
|
+
*
|
|
922
|
+
* @example
|
|
923
|
+
* ```typescript
|
|
924
|
+
* app.notFound((c) => {
|
|
925
|
+
* return c.json({ error: 'Not Found' }, 404)
|
|
926
|
+
* })
|
|
927
|
+
* ```
|
|
928
|
+
*/
|
|
929
|
+
notFound(handler) {
|
|
930
|
+
this.notFoundHandler = handler;
|
|
931
|
+
return this;
|
|
932
|
+
}
|
|
933
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
934
|
+
// Request Handling (Bun.serve integration)
|
|
935
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
936
|
+
/**
|
|
937
|
+
* Handle an incoming request
|
|
938
|
+
*
|
|
939
|
+
* Optimized for minimal allocations and maximum throughput.
|
|
940
|
+
* Uses sync/async dual-path strategy inspired by Hono.
|
|
941
|
+
*
|
|
942
|
+
* @param request - Incoming Request object
|
|
943
|
+
* @returns Response object (sync or async)
|
|
944
|
+
*/
|
|
945
|
+
fetch = (request) => {
|
|
946
|
+
const path = extractPath(request.url);
|
|
947
|
+
const method = request.method.toLowerCase();
|
|
948
|
+
const staticKey = `${method}:${path}`;
|
|
949
|
+
const staticRoute = this.staticRoutes.get(staticKey);
|
|
950
|
+
if (staticRoute) {
|
|
951
|
+
if (staticRoute.useMinimal) {
|
|
952
|
+
const ctx = new MinimalContext(request, {}, path);
|
|
953
|
+
try {
|
|
954
|
+
const result = staticRoute.handler(ctx);
|
|
955
|
+
if (result instanceof Response) {
|
|
956
|
+
return result;
|
|
957
|
+
}
|
|
958
|
+
return result;
|
|
959
|
+
} catch (error) {
|
|
960
|
+
return this.handleErrorSync(error, request, path);
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
return this.handleWithMiddleware(request, path, staticRoute);
|
|
964
|
+
}
|
|
965
|
+
return this.handleDynamicRoute(request, method, path);
|
|
966
|
+
};
|
|
967
|
+
/**
|
|
968
|
+
* Handle routes with middleware (async path)
|
|
969
|
+
*/
|
|
970
|
+
async handleWithMiddleware(request, path, route) {
|
|
971
|
+
const ctx = this.contextPool.acquire();
|
|
972
|
+
try {
|
|
973
|
+
ctx.reset(request, {});
|
|
974
|
+
const middleware = this.collectMiddlewareForPath(path, route.middleware);
|
|
975
|
+
if (middleware.length === 0) {
|
|
976
|
+
return await route.handler(ctx);
|
|
977
|
+
}
|
|
978
|
+
return await this.executeMiddleware(ctx, middleware, route.handler);
|
|
979
|
+
} catch (error) {
|
|
980
|
+
return await this.handleError(error, ctx);
|
|
981
|
+
} finally {
|
|
982
|
+
this.contextPool.release(ctx);
|
|
983
|
+
}
|
|
984
|
+
}
|
|
985
|
+
/**
|
|
986
|
+
* Handle dynamic routes (Radix Tree lookup)
|
|
987
|
+
*/
|
|
988
|
+
handleDynamicRoute(request, method, path) {
|
|
989
|
+
const match = this.router.match(method.toUpperCase(), path);
|
|
990
|
+
if (!match.handler) {
|
|
991
|
+
return this.handleNotFoundSync(request, path);
|
|
992
|
+
}
|
|
993
|
+
const ctx = this.contextPool.acquire();
|
|
994
|
+
const execute = async () => {
|
|
995
|
+
try {
|
|
996
|
+
ctx.reset(request, match.params);
|
|
997
|
+
if (match.middleware.length === 0) {
|
|
998
|
+
return await match.handler(ctx);
|
|
999
|
+
}
|
|
1000
|
+
return await this.executeMiddleware(ctx, match.middleware, match.handler);
|
|
1001
|
+
} catch (error) {
|
|
1002
|
+
return await this.handleError(error, ctx);
|
|
1003
|
+
} finally {
|
|
1004
|
+
this.contextPool.release(ctx);
|
|
1005
|
+
}
|
|
1006
|
+
};
|
|
1007
|
+
return execute();
|
|
1008
|
+
}
|
|
1009
|
+
/**
|
|
1010
|
+
* Sync error handler (for ultra-fast path)
|
|
1011
|
+
*/
|
|
1012
|
+
handleErrorSync(error, request, path) {
|
|
1013
|
+
if (this.errorHandler) {
|
|
1014
|
+
const ctx = new MinimalContext(request, {}, path);
|
|
1015
|
+
const result = this.errorHandler(error, ctx);
|
|
1016
|
+
if (result instanceof Response) {
|
|
1017
|
+
return result;
|
|
1018
|
+
}
|
|
1019
|
+
return result;
|
|
1020
|
+
}
|
|
1021
|
+
console.error("Unhandled error:", error);
|
|
1022
|
+
return new Response(
|
|
1023
|
+
JSON.stringify({
|
|
1024
|
+
error: "Internal Server Error",
|
|
1025
|
+
message: error.message
|
|
1026
|
+
}),
|
|
1027
|
+
{
|
|
1028
|
+
status: 500,
|
|
1029
|
+
headers: { "Content-Type": "application/json" }
|
|
1030
|
+
}
|
|
1031
|
+
);
|
|
1032
|
+
}
|
|
1033
|
+
/**
|
|
1034
|
+
* Sync 404 handler (for ultra-fast path)
|
|
1035
|
+
*/
|
|
1036
|
+
handleNotFoundSync(request, path) {
|
|
1037
|
+
if (this.notFoundHandler) {
|
|
1038
|
+
const ctx = new MinimalContext(request, {}, path);
|
|
1039
|
+
const result = this.notFoundHandler(ctx);
|
|
1040
|
+
if (result instanceof Response) {
|
|
1041
|
+
return result;
|
|
1042
|
+
}
|
|
1043
|
+
return result;
|
|
1044
|
+
}
|
|
1045
|
+
return new Response(JSON.stringify({ error: "Not Found" }), {
|
|
1046
|
+
status: 404,
|
|
1047
|
+
headers: { "Content-Type": "application/json" }
|
|
1048
|
+
});
|
|
1049
|
+
}
|
|
1050
|
+
/**
|
|
1051
|
+
* Collect middleware for a specific path
|
|
1052
|
+
* (Simplified version - assumes we've already checked for pure static)
|
|
1053
|
+
*/
|
|
1054
|
+
collectMiddlewareForPath(path, routeMiddleware) {
|
|
1055
|
+
if (this.router.globalMiddleware.length === 0 && this.router.pathMiddleware.size === 0) {
|
|
1056
|
+
return routeMiddleware;
|
|
1057
|
+
}
|
|
1058
|
+
return this.router.collectMiddlewarePublic(path, routeMiddleware);
|
|
1059
|
+
}
|
|
1060
|
+
/**
|
|
1061
|
+
* Compile routes for optimization
|
|
1062
|
+
* Called once during initialization and when routes change
|
|
1063
|
+
*/
|
|
1064
|
+
compileRoutes() {
|
|
1065
|
+
this.staticRoutes = this.router.staticRoutes;
|
|
1066
|
+
const hasGlobalMiddleware = this.router.globalMiddleware.length > 0;
|
|
1067
|
+
const hasPathMiddleware = this.router.pathMiddleware.size > 0;
|
|
1068
|
+
this.isPureStaticApp = !hasGlobalMiddleware && !hasPathMiddleware;
|
|
1069
|
+
for (const [_key, route] of this.staticRoutes) {
|
|
1070
|
+
const analysis = analyzeHandler(route.handler);
|
|
1071
|
+
const optimalType = getOptimalContextType(analysis);
|
|
1072
|
+
route.useMinimal = this.isPureStaticApp && route.middleware.length === 0 && optimalType === "minimal";
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
1076
|
+
// Internal Methods
|
|
1077
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
1078
|
+
/**
|
|
1079
|
+
* Add a route to the router
|
|
1080
|
+
*/
|
|
1081
|
+
addRoute(method, path, handlers) {
|
|
1082
|
+
if (handlers.length === 0) {
|
|
1083
|
+
throw new Error(`No handler provided for ${method.toUpperCase()} ${path}`);
|
|
1084
|
+
}
|
|
1085
|
+
const handler = handlers[handlers.length - 1];
|
|
1086
|
+
const middleware = handlers.slice(0, -1);
|
|
1087
|
+
this.router.add(method, path, handler, middleware);
|
|
1088
|
+
this.compileRoutes();
|
|
1089
|
+
return this;
|
|
1090
|
+
}
|
|
1091
|
+
/**
|
|
1092
|
+
* Execute middleware chain followed by handler
|
|
1093
|
+
*
|
|
1094
|
+
* Implements the standard middleware pattern:
|
|
1095
|
+
* Each middleware can call next() to continue the chain.
|
|
1096
|
+
*/
|
|
1097
|
+
async executeMiddleware(ctx, middleware, handler) {
|
|
1098
|
+
let index = 0;
|
|
1099
|
+
const next = async () => {
|
|
1100
|
+
if (index < middleware.length) {
|
|
1101
|
+
const mw = middleware[index++];
|
|
1102
|
+
await mw(ctx, next);
|
|
1103
|
+
}
|
|
1104
|
+
};
|
|
1105
|
+
await next();
|
|
1106
|
+
return await handler(ctx);
|
|
1107
|
+
}
|
|
1108
|
+
/**
|
|
1109
|
+
* Handle 404 Not Found (Async version for dynamic/middleware paths)
|
|
1110
|
+
*/
|
|
1111
|
+
async handleNotFound(ctx) {
|
|
1112
|
+
if (this.notFoundHandler) {
|
|
1113
|
+
return await this.notFoundHandler(ctx);
|
|
1114
|
+
}
|
|
1115
|
+
return ctx.json({ error: "Not Found" }, 404);
|
|
1116
|
+
}
|
|
1117
|
+
/**
|
|
1118
|
+
* Handle errors (Async version for dynamic/middleware paths)
|
|
1119
|
+
*/
|
|
1120
|
+
async handleError(error, ctx) {
|
|
1121
|
+
if (this.errorHandler) {
|
|
1122
|
+
return await this.errorHandler(error, ctx);
|
|
1123
|
+
}
|
|
1124
|
+
console.error("Unhandled error:", error);
|
|
1125
|
+
return ctx.json(
|
|
1126
|
+
{
|
|
1127
|
+
error: "Internal Server Error",
|
|
1128
|
+
message: error.message
|
|
1129
|
+
},
|
|
1130
|
+
500
|
|
1131
|
+
);
|
|
1132
|
+
}
|
|
1133
|
+
};
|
|
1134
|
+
export {
|
|
1135
|
+
AOTRouter,
|
|
1136
|
+
FastContext as FastContextImpl,
|
|
1137
|
+
Gravito,
|
|
1138
|
+
MinimalContext,
|
|
1139
|
+
ObjectPool,
|
|
1140
|
+
extractPath
|
|
1141
|
+
};
|