@gravito/core 1.2.1 → 1.6.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.
@@ -0,0 +1,1435 @@
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
+ /** @internal */
212
+ staticRoutes = /* @__PURE__ */ new Map();
213
+ // Dynamic route handler (Radix Tree)
214
+ dynamicRouter = new RadixRouter();
215
+ // Store all route definitions to support mounting/merging
216
+ /** @internal */
217
+ routeDefinitions = [];
218
+ // Global middleware (applies to all routes)
219
+ /** @internal */
220
+ globalMiddleware = [];
221
+ // Path-based middleware: pattern -> middleware[]
222
+ /** @internal */
223
+ pathMiddleware = /* @__PURE__ */ new Map();
224
+ // Dynamic route patterns: handler function -> route pattern
225
+ // 用於追蹤動態路由的模式,防止高基數問題
226
+ dynamicRoutePatterns = /* @__PURE__ */ new Map();
227
+ middlewareCache = /* @__PURE__ */ new Map();
228
+ cacheMaxSize = 1e3;
229
+ version = 0;
230
+ /**
231
+ * Register a route
232
+ *
233
+ * Automatically determines if route is static or dynamic.
234
+ * Static routes are stored in a Map for O(1) lookup.
235
+ * Dynamic routes use the Radix Tree.
236
+ *
237
+ * @param method - HTTP method
238
+ * @param path - Route path
239
+ * @param handler - Route handler
240
+ * @param middleware - Route-specific middleware
241
+ */
242
+ add(method, path, handler, middleware = []) {
243
+ this.routeDefinitions.push({ method, path, handler, middleware });
244
+ const normalizedMethod = method.toLowerCase();
245
+ if (this.isStaticPath(path)) {
246
+ const key = `${normalizedMethod}:${path}`;
247
+ this.staticRoutes.set(key, { handler, middleware });
248
+ } else {
249
+ const wrappedHandler = handler;
250
+ this.dynamicRouter.add(normalizedMethod, path, [wrappedHandler]);
251
+ this.dynamicRoutePatterns.set(wrappedHandler, path);
252
+ if (middleware.length > 0) {
253
+ this.pathMiddleware.set(`${normalizedMethod}:${path}`, middleware);
254
+ }
255
+ }
256
+ }
257
+ /**
258
+ * Mount another router at a prefix
259
+ */
260
+ mount(prefix, other) {
261
+ if (other.globalMiddleware.length > 0) {
262
+ this.usePattern(prefix, ...other.globalMiddleware);
263
+ const wildcard = prefix === "/" ? "/*" : `${prefix}/*`;
264
+ this.usePattern(wildcard, ...other.globalMiddleware);
265
+ }
266
+ for (const [pattern, mws] of other.pathMiddleware) {
267
+ if (pattern.includes(":")) {
268
+ continue;
269
+ }
270
+ let newPattern;
271
+ if (pattern === "*") {
272
+ newPattern = prefix === "/" ? "/*" : `${prefix}/*`;
273
+ } else if (pattern.startsWith("/")) {
274
+ newPattern = prefix === "/" ? pattern : `${prefix}${pattern}`;
275
+ } else {
276
+ newPattern = prefix === "/" ? `/${pattern}` : `${prefix}/${pattern}`;
277
+ }
278
+ this.usePattern(newPattern, ...mws);
279
+ }
280
+ for (const def of other.routeDefinitions) {
281
+ let newPath;
282
+ if (prefix === "/") {
283
+ newPath = def.path;
284
+ } else if (def.path === "/") {
285
+ newPath = prefix;
286
+ } else {
287
+ newPath = `${prefix}${def.path}`;
288
+ }
289
+ this.add(def.method, newPath, def.handler, def.middleware);
290
+ }
291
+ }
292
+ /**
293
+ * Add global middleware
294
+ *
295
+ * These run for every request, before route-specific middleware.
296
+ *
297
+ * @param middleware - Middleware functions
298
+ */
299
+ use(...middleware) {
300
+ this.globalMiddleware.push(...middleware);
301
+ this.version++;
302
+ }
303
+ /**
304
+ * Add path-based middleware
305
+ *
306
+ * Supports wildcard patterns like '/api/*'
307
+ *
308
+ * @param pattern - Path pattern
309
+ * @param middleware - Middleware functions
310
+ */
311
+ usePattern(pattern, ...middleware) {
312
+ if (pattern === "*") {
313
+ this.globalMiddleware.push(...middleware);
314
+ } else {
315
+ const existing = this.pathMiddleware.get(pattern) ?? [];
316
+ this.pathMiddleware.set(pattern, [...existing, ...middleware]);
317
+ }
318
+ this.version++;
319
+ }
320
+ /**
321
+ * Match a request to a route
322
+ *
323
+ * Returns the handler, params, and all applicable middleware.
324
+ *
325
+ * @param method - HTTP method
326
+ * @param path - Request path
327
+ * @returns Route match or null if not found
328
+ */
329
+ match(method, path) {
330
+ const normalizedMethod = method.toLowerCase();
331
+ const staticKey = `${normalizedMethod}:${path}`;
332
+ const staticRoute = this.staticRoutes.get(staticKey);
333
+ if (staticRoute) {
334
+ return {
335
+ handler: staticRoute.handler,
336
+ params: {},
337
+ middleware: this.collectMiddleware(path, staticRoute.middleware),
338
+ routePattern: path
339
+ };
340
+ }
341
+ const match = this.dynamicRouter.match(normalizedMethod, path);
342
+ if (match && match.handlers.length > 0) {
343
+ const handler = match.handlers[0];
344
+ const wrappedHandler = match.handlers[0];
345
+ const routePattern = this.dynamicRoutePatterns.get(wrappedHandler);
346
+ const routeKey = routePattern ? `${normalizedMethod}:${routePattern}` : null;
347
+ const routeMiddleware = routeKey ? this.pathMiddleware.get(routeKey) ?? [] : [];
348
+ return {
349
+ handler,
350
+ params: match.params,
351
+ middleware: this.collectMiddleware(path, routeMiddleware),
352
+ routePattern
353
+ };
354
+ }
355
+ return {
356
+ handler: null,
357
+ params: {},
358
+ middleware: []
359
+ };
360
+ }
361
+ /**
362
+ * Public wrapper for collectMiddleware (used by Gravito for optimization)
363
+ */
364
+ collectMiddlewarePublic(path, routeMiddleware) {
365
+ return this.collectMiddleware(path, routeMiddleware);
366
+ }
367
+ /**
368
+ * Collect all applicable middleware for a path
369
+ *
370
+ * Order: global -> pattern-based -> route-specific
371
+ *
372
+ * @param path - Request path
373
+ * @param routeMiddleware - Route-specific middleware
374
+ * @returns Combined middleware array
375
+ */
376
+ collectMiddleware(path, routeMiddleware) {
377
+ if (this.globalMiddleware.length === 0 && this.pathMiddleware.size === 0 && routeMiddleware.length === 0) {
378
+ return [];
379
+ }
380
+ const cacheKey = `${path}:${routeMiddleware.length}`;
381
+ const cached = this.middlewareCache.get(cacheKey);
382
+ if (cached !== void 0 && cached.version === this.version) {
383
+ return cached.data;
384
+ }
385
+ const middleware = [];
386
+ if (this.globalMiddleware.length > 0) {
387
+ middleware.push(...this.globalMiddleware);
388
+ }
389
+ if (this.pathMiddleware.size > 0) {
390
+ for (const [pattern, mw] of this.pathMiddleware) {
391
+ if (pattern.includes(":")) {
392
+ continue;
393
+ }
394
+ if (this.matchPattern(pattern, path)) {
395
+ middleware.push(...mw);
396
+ }
397
+ }
398
+ }
399
+ if (routeMiddleware.length > 0) {
400
+ middleware.push(...routeMiddleware);
401
+ }
402
+ if (this.middlewareCache.size < this.cacheMaxSize) {
403
+ this.middlewareCache.set(cacheKey, { data: middleware, version: this.version });
404
+ }
405
+ return middleware;
406
+ }
407
+ /**
408
+ * Check if a path is static (no parameters or wildcards)
409
+ */
410
+ isStaticPath(path) {
411
+ return !path.includes(":") && !path.includes("*");
412
+ }
413
+ /**
414
+ * Match a pattern against a path
415
+ *
416
+ * Supports:
417
+ * - Exact match: '/api/users'
418
+ * - Wildcard suffix: '/api/*'
419
+ *
420
+ * @param pattern - Pattern to match
421
+ * @param path - Path to test
422
+ * @returns True if pattern matches
423
+ */
424
+ matchPattern(pattern, path) {
425
+ if (pattern === "*") {
426
+ return true;
427
+ }
428
+ if (pattern === path) {
429
+ return true;
430
+ }
431
+ if (pattern.endsWith("/*")) {
432
+ const prefix = pattern.slice(0, -2);
433
+ return path.startsWith(prefix);
434
+ }
435
+ return false;
436
+ }
437
+ /**
438
+ * Get all registered routes (for debugging)
439
+ */
440
+ getRoutes() {
441
+ const routes = [];
442
+ for (const key of this.staticRoutes.keys()) {
443
+ const [method, path] = key.split(":");
444
+ routes.push({ method, path, type: "static" });
445
+ }
446
+ return routes;
447
+ }
448
+ };
449
+
450
+ // src/engine/analyzer.ts
451
+ function analyzeHandler(handler) {
452
+ const source = handler.toString();
453
+ return {
454
+ usesHeaders: source.includes(".header(") || source.includes(".header)") || source.includes(".headers(") || source.includes(".headers)"),
455
+ usesQuery: source.includes(".query(") || source.includes(".query)") || source.includes(".queries(") || source.includes(".queries)"),
456
+ usesBody: source.includes(".json()") || source.includes(".text()") || source.includes(".formData()") || source.includes(".body"),
457
+ usesParams: source.includes(".param(") || source.includes(".param)") || source.includes(".params(") || source.includes(".params)"),
458
+ isAsync: source.includes("async") || source.includes("await")
459
+ };
460
+ }
461
+ function getOptimalContextType(analysis) {
462
+ if (analysis.usesHeaders) {
463
+ return "fast";
464
+ }
465
+ if (!analysis.usesQuery && !analysis.usesBody && !analysis.usesParams) {
466
+ return "minimal";
467
+ }
468
+ if (!analysis.usesQuery && !analysis.usesBody && analysis.usesParams) {
469
+ return "minimal";
470
+ }
471
+ if (analysis.usesBody) {
472
+ return "full";
473
+ }
474
+ return "fast";
475
+ }
476
+
477
+ // src/engine/constants.ts
478
+ var encoder = new TextEncoder();
479
+ var CACHED_RESPONSES = {
480
+ NOT_FOUND: encoder.encode('{"error":"Not Found"}'),
481
+ INTERNAL_ERROR: encoder.encode('{"error":"Internal Server Error"}'),
482
+ OK: encoder.encode('{"ok":true}'),
483
+ EMPTY: new Uint8Array(0)
484
+ };
485
+ var HEADERS = {
486
+ JSON: { "Content-Type": "application/json; charset=utf-8" },
487
+ TEXT: { "Content-Type": "text/plain; charset=utf-8" },
488
+ HTML: { "Content-Type": "text/html; charset=utf-8" }
489
+ };
490
+
491
+ // src/engine/FastContext.ts
492
+ var FastRequestImpl = class {
493
+ _request;
494
+ _params;
495
+ _path;
496
+ _routePattern;
497
+ _url = null;
498
+ _query = null;
499
+ _headers = null;
500
+ _cachedJson = void 0;
501
+ _jsonParsed = false;
502
+ // Back-reference for release check optimization
503
+ _ctx;
504
+ constructor(ctx) {
505
+ this._ctx = ctx;
506
+ }
507
+ /**
508
+ * Initialize for new request
509
+ */
510
+ init(request, params = {}, path = "", routePattern) {
511
+ this._request = request;
512
+ this._params = params;
513
+ this._path = path;
514
+ this._routePattern = routePattern;
515
+ this._url = null;
516
+ this._query = null;
517
+ this._headers = null;
518
+ this._cachedJson = void 0;
519
+ this._jsonParsed = false;
520
+ return this;
521
+ }
522
+ /**
523
+ * Reset for pooling
524
+ */
525
+ reset() {
526
+ this._request = void 0;
527
+ this._params = void 0;
528
+ this._url = null;
529
+ this._query = null;
530
+ this._headers = null;
531
+ this._cachedJson = void 0;
532
+ this._jsonParsed = false;
533
+ }
534
+ checkReleased() {
535
+ if (this._ctx._isReleased) {
536
+ throw new Error(
537
+ "FastContext usage after release detected! (Object Pool Strict Lifecycle Guard)"
538
+ );
539
+ }
540
+ }
541
+ get url() {
542
+ this.checkReleased();
543
+ return this._request.url;
544
+ }
545
+ get method() {
546
+ this.checkReleased();
547
+ return this._request.method;
548
+ }
549
+ get path() {
550
+ this.checkReleased();
551
+ return this._path;
552
+ }
553
+ get routePattern() {
554
+ this.checkReleased();
555
+ return this._routePattern;
556
+ }
557
+ param(name) {
558
+ this.checkReleased();
559
+ return this._params[name];
560
+ }
561
+ params() {
562
+ this.checkReleased();
563
+ return { ...this._params };
564
+ }
565
+ getUrl() {
566
+ if (!this._url) {
567
+ this._url = new URL(this._request.url);
568
+ }
569
+ return this._url;
570
+ }
571
+ query(name) {
572
+ this.checkReleased();
573
+ if (!this._query) {
574
+ this._query = this.getUrl().searchParams;
575
+ }
576
+ return this._query.get(name) ?? void 0;
577
+ }
578
+ queries() {
579
+ this.checkReleased();
580
+ if (!this._query) {
581
+ this._query = this.getUrl().searchParams;
582
+ }
583
+ const result = {};
584
+ for (const [key, value] of this._query.entries()) {
585
+ const existing = result[key];
586
+ if (existing === void 0) {
587
+ result[key] = value;
588
+ } else if (Array.isArray(existing)) {
589
+ existing.push(value);
590
+ } else {
591
+ result[key] = [existing, value];
592
+ }
593
+ }
594
+ return result;
595
+ }
596
+ header(name) {
597
+ this.checkReleased();
598
+ return this._request.headers.get(name) ?? void 0;
599
+ }
600
+ headers() {
601
+ this.checkReleased();
602
+ if (!this._headers) {
603
+ this._headers = {};
604
+ for (const [key, value] of this._request.headers.entries()) {
605
+ this._headers[key] = value;
606
+ }
607
+ }
608
+ return { ...this._headers };
609
+ }
610
+ async json() {
611
+ this.checkReleased();
612
+ if (!this._jsonParsed) {
613
+ this._cachedJson = await this._request.json();
614
+ this._jsonParsed = true;
615
+ }
616
+ return this._cachedJson;
617
+ }
618
+ async text() {
619
+ this.checkReleased();
620
+ return this._request.text();
621
+ }
622
+ async formData() {
623
+ this.checkReleased();
624
+ return this._request.formData();
625
+ }
626
+ get raw() {
627
+ this.checkReleased();
628
+ return this._request;
629
+ }
630
+ };
631
+ var FastContext = class {
632
+ req = new FastRequestImpl(this);
633
+ // private _statusCode = 200
634
+ _headers = new Headers();
635
+ // Reuse this object
636
+ _isReleased = false;
637
+ // Made public for internal check access
638
+ /**
639
+ * Initialize context for a new request
640
+ *
641
+ * This is called when acquiring from the pool.
642
+ */
643
+ init(request, params = {}, path = "", routePattern) {
644
+ this._isReleased = false;
645
+ this.req.init(request, params, path, routePattern);
646
+ this._headers = new Headers();
647
+ return this;
648
+ }
649
+ /**
650
+ * Reset context for pooling (Cleanup)
651
+ *
652
+ * This is called when releasing back to the pool.
653
+ * Implements "Deep-Reset Protocol" and "Release Guard".
654
+ */
655
+ reset() {
656
+ this._isReleased = true;
657
+ this.req.reset();
658
+ this._store.clear();
659
+ }
660
+ /**
661
+ * Check if context is released
662
+ */
663
+ checkReleased() {
664
+ if (this._isReleased) {
665
+ throw new Error(
666
+ "FastContext usage after release detected! (Object Pool Strict Lifecycle Guard)"
667
+ );
668
+ }
669
+ }
670
+ // ─────────────────────────────────────────────────────────────────────────
671
+ // Response Helpers
672
+ // ─────────────────────────────────────────────────────────────────────────
673
+ json(data, status = 200) {
674
+ this.checkReleased();
675
+ this._headers.set("Content-Type", "application/json; charset=utf-8");
676
+ return new Response(JSON.stringify(data), {
677
+ status,
678
+ headers: this._headers
679
+ });
680
+ }
681
+ text(text, status = 200) {
682
+ this.checkReleased();
683
+ this._headers.set("Content-Type", "text/plain; charset=utf-8");
684
+ return new Response(text, {
685
+ status,
686
+ headers: this._headers
687
+ });
688
+ }
689
+ html(html, status = 200) {
690
+ this.checkReleased();
691
+ this._headers.set("Content-Type", "text/html; charset=utf-8");
692
+ return new Response(html, {
693
+ status,
694
+ headers: this._headers
695
+ });
696
+ }
697
+ redirect(url, status = 302) {
698
+ this.checkReleased();
699
+ this._headers.set("Location", url);
700
+ return new Response(null, {
701
+ status,
702
+ headers: this._headers
703
+ });
704
+ }
705
+ body(data, status = 200) {
706
+ this.checkReleased();
707
+ return new Response(data, {
708
+ status,
709
+ headers: this._headers
710
+ });
711
+ }
712
+ stream(stream, status = 200) {
713
+ this.checkReleased();
714
+ this._headers.set("Content-Type", "application/octet-stream");
715
+ return new Response(stream, {
716
+ status,
717
+ headers: this._headers
718
+ });
719
+ }
720
+ notFound(message = "Not Found") {
721
+ return this.text(message, 404);
722
+ }
723
+ forbidden(message = "Forbidden") {
724
+ return this.text(message, 403);
725
+ }
726
+ unauthorized(message = "Unauthorized") {
727
+ return this.text(message, 401);
728
+ }
729
+ badRequest(message = "Bad Request") {
730
+ return this.text(message, 400);
731
+ }
732
+ async forward(target, _options = {}) {
733
+ this.checkReleased();
734
+ const url = new URL(this.req.url);
735
+ const targetUrl = new URL(
736
+ target.startsWith("http") ? target : `${url.protocol}//${target}${this.req.path}`
737
+ );
738
+ const searchParams = new URLSearchParams(url.search);
739
+ searchParams.forEach((v, k) => {
740
+ targetUrl.searchParams.set(k, v);
741
+ });
742
+ return fetch(targetUrl.toString(), {
743
+ method: this.req.method,
744
+ headers: this.req.raw.headers,
745
+ body: this.req.method !== "GET" && this.req.method !== "HEAD" ? this.req.raw.body : null,
746
+ // @ts-expect-error - Bun/Fetch specific
747
+ duplex: "half"
748
+ });
749
+ }
750
+ header(name, value) {
751
+ this.checkReleased();
752
+ if (value !== void 0) {
753
+ this._headers.set(name, value);
754
+ return;
755
+ }
756
+ return this.req.header(name);
757
+ }
758
+ status(_code) {
759
+ this.checkReleased();
760
+ }
761
+ // ─────────────────────────────────────────────────────────────────────────
762
+ // Context Variables
763
+ // ─────────────────────────────────────────────────────────────────────────
764
+ _store = /* @__PURE__ */ new Map();
765
+ get(key) {
766
+ return this._store.get(key);
767
+ }
768
+ set(key, value) {
769
+ this._store.set(key, value);
770
+ }
771
+ // ─────────────────────────────────────────────────────────────────────────
772
+ // Lifecycle helpers
773
+ // ─────────────────────────────────────────────────────────────────────────
774
+ route = () => "";
775
+ get native() {
776
+ return this;
777
+ }
778
+ };
779
+
780
+ // src/engine/MinimalContext.ts
781
+ var MinimalRequest = class {
782
+ constructor(_request, _params, _path, _routePattern) {
783
+ this._request = _request;
784
+ this._params = _params;
785
+ this._path = _path;
786
+ this._routePattern = _routePattern;
787
+ }
788
+ _searchParams = null;
789
+ get url() {
790
+ return this._request.url;
791
+ }
792
+ get method() {
793
+ return this._request.method;
794
+ }
795
+ get path() {
796
+ return this._path;
797
+ }
798
+ get routePattern() {
799
+ return this._routePattern;
800
+ }
801
+ param(name) {
802
+ return this._params[name];
803
+ }
804
+ params() {
805
+ return { ...this._params };
806
+ }
807
+ /**
808
+ * Lazy-initialize searchParams, only parse once
809
+ */
810
+ getSearchParams() {
811
+ if (this._searchParams === null) {
812
+ const url = this._request.url;
813
+ const queryStart = url.indexOf("?");
814
+ if (queryStart === -1) {
815
+ this._searchParams = new URLSearchParams();
816
+ } else {
817
+ const hashStart = url.indexOf("#", queryStart);
818
+ const queryString = hashStart === -1 ? url.slice(queryStart + 1) : url.slice(queryStart + 1, hashStart);
819
+ this._searchParams = new URLSearchParams(queryString);
820
+ }
821
+ }
822
+ return this._searchParams;
823
+ }
824
+ query(name) {
825
+ return this.getSearchParams().get(name) ?? void 0;
826
+ }
827
+ queries() {
828
+ const params = this.getSearchParams();
829
+ const result = {};
830
+ for (const [key, value] of params.entries()) {
831
+ const existing = result[key];
832
+ if (existing === void 0) {
833
+ result[key] = value;
834
+ } else if (Array.isArray(existing)) {
835
+ existing.push(value);
836
+ } else {
837
+ result[key] = [existing, value];
838
+ }
839
+ }
840
+ return result;
841
+ }
842
+ header(name) {
843
+ return this._request.headers.get(name) ?? void 0;
844
+ }
845
+ headers() {
846
+ const result = {};
847
+ for (const [key, value] of this._request.headers.entries()) {
848
+ result[key] = value;
849
+ }
850
+ return result;
851
+ }
852
+ async json() {
853
+ return this._request.json();
854
+ }
855
+ async text() {
856
+ return this._request.text();
857
+ }
858
+ async formData() {
859
+ return this._request.formData();
860
+ }
861
+ get raw() {
862
+ return this._request;
863
+ }
864
+ };
865
+ var MinimalContext = class {
866
+ req;
867
+ _resHeaders = {};
868
+ constructor(request, params, path, routePattern) {
869
+ this.req = new MinimalRequest(request, params, path, routePattern);
870
+ }
871
+ // get req(): FastRequest {
872
+ // return this._req
873
+ // }
874
+ // Response helpers - merge custom headers with defaults
875
+ getHeaders(contentType) {
876
+ return {
877
+ ...this._resHeaders,
878
+ "Content-Type": contentType
879
+ };
880
+ }
881
+ json(data, status = 200) {
882
+ return new Response(JSON.stringify(data), {
883
+ status,
884
+ headers: this.getHeaders("application/json; charset=utf-8")
885
+ });
886
+ }
887
+ text(text, status = 200) {
888
+ return new Response(text, {
889
+ status,
890
+ headers: this.getHeaders("text/plain; charset=utf-8")
891
+ });
892
+ }
893
+ html(html, status = 200) {
894
+ return new Response(html, {
895
+ status,
896
+ headers: this.getHeaders("text/html; charset=utf-8")
897
+ });
898
+ }
899
+ redirect(url, status = 302) {
900
+ return new Response(null, {
901
+ status,
902
+ headers: { ...this._resHeaders, Location: url }
903
+ });
904
+ }
905
+ body(data, status = 200) {
906
+ return new Response(data, {
907
+ status,
908
+ headers: this._resHeaders
909
+ });
910
+ }
911
+ header(name, value) {
912
+ if (value !== void 0) {
913
+ this._resHeaders[name] = value;
914
+ return;
915
+ }
916
+ return this.req.header(name);
917
+ }
918
+ status(_code) {
919
+ }
920
+ stream(stream, status = 200) {
921
+ return new Response(stream, {
922
+ status,
923
+ headers: this.getHeaders("application/octet-stream")
924
+ });
925
+ }
926
+ notFound(message = "Not Found") {
927
+ return this.text(message, 404);
928
+ }
929
+ forbidden(message = "Forbidden") {
930
+ return this.text(message, 403);
931
+ }
932
+ unauthorized(message = "Unauthorized") {
933
+ return this.text(message, 401);
934
+ }
935
+ badRequest(message = "Bad Request") {
936
+ return this.text(message, 400);
937
+ }
938
+ async forward(target, _options = {}) {
939
+ const url = new URL(this.req.url);
940
+ const targetUrl = new URL(
941
+ target.startsWith("http") ? target : `${url.protocol}//${target}${this.req.path}`
942
+ );
943
+ return fetch(targetUrl.toString(), {
944
+ method: this.req.method,
945
+ headers: this.req.raw.headers
946
+ });
947
+ }
948
+ get(_key) {
949
+ return void 0;
950
+ }
951
+ set(_key, _value) {
952
+ }
953
+ route = () => "";
954
+ get native() {
955
+ return this;
956
+ }
957
+ // Required for interface compatibility
958
+ init(_request, _params, _path) {
959
+ throw new Error("MinimalContext does not support init. Create a new instance instead.");
960
+ }
961
+ // Required for interface compatibility
962
+ reset() {
963
+ }
964
+ };
965
+
966
+ // src/engine/path.ts
967
+ function extractPath(url) {
968
+ const protocolEnd = url.indexOf("://");
969
+ const searchStart = protocolEnd === -1 ? 0 : protocolEnd + 3;
970
+ const pathStart = url.indexOf("/", searchStart);
971
+ if (pathStart === -1) {
972
+ return "/";
973
+ }
974
+ const queryStart = url.indexOf("?", pathStart);
975
+ if (queryStart === -1) {
976
+ return url.slice(pathStart);
977
+ }
978
+ return url.slice(pathStart, queryStart);
979
+ }
980
+
981
+ // src/engine/pool.ts
982
+ var ObjectPool = class {
983
+ pool = [];
984
+ factory;
985
+ reset;
986
+ maxSize;
987
+ /**
988
+ * Create a new object pool
989
+ *
990
+ * @param factory - Function to create new objects
991
+ * @param reset - Function to reset objects before reuse
992
+ * @param maxSize - Maximum pool size (default: 256)
993
+ */
994
+ constructor(factory, reset, maxSize = 256) {
995
+ this.factory = factory;
996
+ this.reset = reset;
997
+ this.maxSize = maxSize;
998
+ }
999
+ /**
1000
+ * Acquire an object from the pool
1001
+ *
1002
+ * If the pool is empty, creates a new object (overflow strategy).
1003
+ * This ensures the pool never blocks under high load.
1004
+ *
1005
+ * @returns Object from pool or newly created
1006
+ */
1007
+ acquire() {
1008
+ const obj = this.pool.pop();
1009
+ if (obj !== void 0) {
1010
+ return obj;
1011
+ }
1012
+ return this.factory();
1013
+ }
1014
+ /**
1015
+ * Release an object back to the pool
1016
+ *
1017
+ * If the pool is full, the object is discarded (will be GC'd).
1018
+ * This prevents unbounded memory growth.
1019
+ *
1020
+ * @param obj - Object to release
1021
+ */
1022
+ release(obj) {
1023
+ if (this.pool.length < this.maxSize) {
1024
+ this.reset(obj);
1025
+ this.pool.push(obj);
1026
+ }
1027
+ }
1028
+ /**
1029
+ * Clear all objects from the pool
1030
+ *
1031
+ * Useful for testing or when you need to force a clean slate.
1032
+ */
1033
+ clear() {
1034
+ this.pool = [];
1035
+ }
1036
+ /**
1037
+ * Get current pool size
1038
+ */
1039
+ get size() {
1040
+ return this.pool.length;
1041
+ }
1042
+ /**
1043
+ * Get maximum pool size
1044
+ */
1045
+ get capacity() {
1046
+ return this.maxSize;
1047
+ }
1048
+ /**
1049
+ * Pre-warm the pool by creating objects in advance
1050
+ *
1051
+ * This can reduce latency for the first N requests.
1052
+ *
1053
+ * @param count - Number of objects to pre-create
1054
+ */
1055
+ prewarm(count) {
1056
+ const targetSize = Math.min(count, this.maxSize);
1057
+ while (this.pool.length < targetSize) {
1058
+ const obj = this.factory();
1059
+ this.reset(obj);
1060
+ this.pool.push(obj);
1061
+ }
1062
+ }
1063
+ };
1064
+
1065
+ // src/engine/Gravito.ts
1066
+ function compileMiddlewareChain(middleware, handler) {
1067
+ if (middleware.length === 0) {
1068
+ return handler;
1069
+ }
1070
+ let compiled = handler;
1071
+ for (let i = middleware.length - 1; i >= 0; i--) {
1072
+ const mw = middleware[i];
1073
+ const nextHandler = compiled;
1074
+ compiled = async (ctx) => {
1075
+ let nextResult;
1076
+ const next = async () => {
1077
+ nextResult = await nextHandler(ctx);
1078
+ return nextResult;
1079
+ };
1080
+ const result = await mw(ctx, next);
1081
+ return result ?? nextResult;
1082
+ };
1083
+ }
1084
+ return compiled;
1085
+ }
1086
+ var Gravito = class {
1087
+ router = new AOTRouter();
1088
+ contextPool;
1089
+ errorHandler;
1090
+ notFoundHandler;
1091
+ // Direct reference to static routes Map (O(1) access)
1092
+ /** @internal */
1093
+ staticRoutes;
1094
+ // Flag: pure static app (no middleware at all) allows ultra-fast path
1095
+ isPureStaticApp = true;
1096
+ // Cache for precompiled dynamic routes
1097
+ compiledDynamicRoutes = /* @__PURE__ */ new Map();
1098
+ // Version tracking for cache invalidation
1099
+ middlewareVersion = 0;
1100
+ /**
1101
+ * Create a new Gravito instance
1102
+ *
1103
+ * @param options - Engine configuration options
1104
+ */
1105
+ constructor(options = {}) {
1106
+ const poolSize = options.poolSize ?? 256;
1107
+ this.contextPool = new ObjectPool(
1108
+ () => new FastContext(),
1109
+ (ctx) => ctx.reset(),
1110
+ poolSize
1111
+ );
1112
+ this.contextPool.prewarm(Math.min(32, poolSize));
1113
+ if (options.onError) {
1114
+ this.errorHandler = options.onError;
1115
+ }
1116
+ if (options.onNotFound) {
1117
+ this.notFoundHandler = options.onNotFound;
1118
+ }
1119
+ this.compileRoutes();
1120
+ }
1121
+ // ─────────────────────────────────────────────────────────────────────────
1122
+ // HTTP Method Registration
1123
+ // ─────────────────────────────────────────────────────────────────────────
1124
+ /**
1125
+ * Register a GET route
1126
+ *
1127
+ * @param path - Route path (e.g., '/users/:id')
1128
+ * @param handlers - Handler and optional middleware
1129
+ * @returns This instance for chaining
1130
+ */
1131
+ get(path, ...handlers) {
1132
+ return this.addRoute("get", path, handlers);
1133
+ }
1134
+ /**
1135
+ * Register a POST route
1136
+ */
1137
+ post(path, ...handlers) {
1138
+ return this.addRoute("post", path, handlers);
1139
+ }
1140
+ /**
1141
+ * Register a PUT route
1142
+ */
1143
+ put(path, ...handlers) {
1144
+ return this.addRoute("put", path, handlers);
1145
+ }
1146
+ /**
1147
+ * Register a DELETE route
1148
+ */
1149
+ delete(path, ...handlers) {
1150
+ return this.addRoute("delete", path, handlers);
1151
+ }
1152
+ /**
1153
+ * Register a PDF route
1154
+ */
1155
+ patch(path, ...handlers) {
1156
+ return this.addRoute("patch", path, handlers);
1157
+ }
1158
+ /**
1159
+ * Register an OPTIONS route
1160
+ */
1161
+ options(path, ...handlers) {
1162
+ return this.addRoute("options", path, handlers);
1163
+ }
1164
+ /**
1165
+ * Register a HEAD route
1166
+ */
1167
+ head(path, ...handlers) {
1168
+ return this.addRoute("head", path, handlers);
1169
+ }
1170
+ /**
1171
+ * Register a route for all HTTP methods
1172
+ */
1173
+ all(path, ...handlers) {
1174
+ const methods = ["get", "post", "put", "delete", "patch", "options", "head"];
1175
+ for (const method of methods) {
1176
+ this.addRoute(method, path, handlers);
1177
+ }
1178
+ return this;
1179
+ }
1180
+ use(pathOrMiddleware, ...middleware) {
1181
+ this.isPureStaticApp = false;
1182
+ if (typeof pathOrMiddleware === "string") {
1183
+ this.router.usePattern(pathOrMiddleware, ...middleware);
1184
+ } else {
1185
+ this.router.use(pathOrMiddleware, ...middleware);
1186
+ }
1187
+ this.middlewareVersion++;
1188
+ this.compileRoutes();
1189
+ return this;
1190
+ }
1191
+ // ─────────────────────────────────────────────────────────────────────────
1192
+ // Route Grouping
1193
+ // ─────────────────────────────────────────────────────────────────────────
1194
+ /**
1195
+ * Mount a sub-application at a path prefix
1196
+ */
1197
+ route(path, app) {
1198
+ this.router.mount(path, app.router);
1199
+ this.compileRoutes();
1200
+ return this;
1201
+ }
1202
+ // ─────────────────────────────────────────────────────────────────────────
1203
+ // Error Handling
1204
+ // ─────────────────────────────────────────────────────────────────────────
1205
+ /**
1206
+ * Set custom error handler
1207
+ */
1208
+ onError(handler) {
1209
+ this.errorHandler = handler;
1210
+ return this;
1211
+ }
1212
+ /**
1213
+ * Set custom 404 handler
1214
+ */
1215
+ notFound(handler) {
1216
+ this.notFoundHandler = handler;
1217
+ return this;
1218
+ }
1219
+ // ─────────────────────────────────────────────────────────────────────────
1220
+ // Request Handling (Bun.serve integration)
1221
+ // ─────────────────────────────────────────────────────────────────────────
1222
+ /**
1223
+ * Predictive Route Warming (JIT Optimization)
1224
+ *
1225
+ * Simulates requests to specified routes to trigger JIT compilation (FTL)
1226
+ * before real traffic arrives.
1227
+ *
1228
+ * @param paths List of paths to warm up (e.g. ['/api/users', '/health'])
1229
+ */
1230
+ async warmup(paths) {
1231
+ const dummyReqOpts = { headers: { "User-Agent": "Gravito-Warmup/1.0" } };
1232
+ for (const path of paths) {
1233
+ const req = new Request(`http://localhost${path}`, dummyReqOpts);
1234
+ await this.fetch(req);
1235
+ }
1236
+ }
1237
+ /**
1238
+ * Handle an incoming request
1239
+ */
1240
+ fetch = async (request) => {
1241
+ const path = extractPath(request.url);
1242
+ const method = request.method.toLowerCase();
1243
+ const staticKey = `${method}:${path}`;
1244
+ const staticRoute = this.staticRoutes.get(staticKey);
1245
+ if (staticRoute) {
1246
+ if (staticRoute.useMinimal) {
1247
+ const ctx = new MinimalContext(request, {}, path, path);
1248
+ try {
1249
+ const result = staticRoute.handler(ctx);
1250
+ if (result instanceof Response) {
1251
+ return result;
1252
+ }
1253
+ return await result;
1254
+ } catch (error) {
1255
+ return this.handleErrorSync(error, request, path);
1256
+ }
1257
+ }
1258
+ return await this.handleWithMiddleware(request, path, staticRoute);
1259
+ }
1260
+ return await this.handleDynamicRoute(request, method, path);
1261
+ };
1262
+ /**
1263
+ * Handle routes with middleware (async path)
1264
+ */
1265
+ async handleWithMiddleware(request, path, route) {
1266
+ const ctx = this.contextPool.acquire();
1267
+ try {
1268
+ ctx.init(request, {}, path, path);
1269
+ if (route.compiled) {
1270
+ return await route.compiled(ctx);
1271
+ }
1272
+ const middleware = this.collectMiddlewareForPath(path, route.middleware);
1273
+ if (middleware.length === 0) {
1274
+ return await route.handler(ctx);
1275
+ }
1276
+ return await this.executeMiddleware(ctx, middleware, route.handler);
1277
+ } catch (error) {
1278
+ return await this.handleError(error, ctx);
1279
+ } finally {
1280
+ this.contextPool.release(ctx);
1281
+ }
1282
+ }
1283
+ /**
1284
+ * Handle dynamic routes (Radix Tree lookup)
1285
+ */
1286
+ handleDynamicRoute(request, method, path) {
1287
+ const match = this.router.match(method.toUpperCase(), path);
1288
+ if (!match.handler) {
1289
+ return this.handleNotFoundSync(request, path);
1290
+ }
1291
+ const cacheKey = `${method}:${match.routePattern ?? path}`;
1292
+ let entry = this.compiledDynamicRoutes.get(cacheKey);
1293
+ if (!entry || entry.version !== this.middlewareVersion) {
1294
+ const compiled = compileMiddlewareChain(match.middleware, match.handler);
1295
+ if (this.compiledDynamicRoutes.size > 1e3) {
1296
+ this.compiledDynamicRoutes.clear();
1297
+ }
1298
+ entry = { compiled, version: this.middlewareVersion };
1299
+ this.compiledDynamicRoutes.set(cacheKey, entry);
1300
+ }
1301
+ const ctx = this.contextPool.acquire();
1302
+ const execute = async () => {
1303
+ try {
1304
+ ctx.init(request, match.params, path, match.routePattern);
1305
+ return await entry?.compiled(ctx);
1306
+ } catch (error) {
1307
+ return await this.handleError(error, ctx);
1308
+ } finally {
1309
+ this.contextPool.release(ctx);
1310
+ }
1311
+ };
1312
+ return execute();
1313
+ }
1314
+ /**
1315
+ * Sync error handler (for ultra-fast path)
1316
+ */
1317
+ handleErrorSync(error, request, path) {
1318
+ if (this.errorHandler) {
1319
+ const ctx = new MinimalContext(request, {}, path);
1320
+ const result = this.errorHandler(error, ctx);
1321
+ if (result instanceof Response) {
1322
+ return result;
1323
+ }
1324
+ return result;
1325
+ }
1326
+ console.error("Unhandled error:", error);
1327
+ return new Response(CACHED_RESPONSES.INTERNAL_ERROR, {
1328
+ status: 500,
1329
+ headers: HEADERS.JSON
1330
+ });
1331
+ }
1332
+ /**
1333
+ * Sync 404 handler (for ultra-fast path)
1334
+ */
1335
+ handleNotFoundSync(request, path) {
1336
+ if (this.notFoundHandler) {
1337
+ const ctx = new MinimalContext(request, {}, path);
1338
+ const result = this.notFoundHandler(ctx);
1339
+ if (result instanceof Response) {
1340
+ return result;
1341
+ }
1342
+ return result;
1343
+ }
1344
+ return new Response(CACHED_RESPONSES.NOT_FOUND, {
1345
+ status: 404,
1346
+ headers: HEADERS.JSON
1347
+ });
1348
+ }
1349
+ /**
1350
+ * Collect middleware for a specific path
1351
+ */
1352
+ collectMiddlewareForPath(path, routeMiddleware) {
1353
+ if (this.router.globalMiddleware.length === 0 && this.router.pathMiddleware.size === 0) {
1354
+ return routeMiddleware;
1355
+ }
1356
+ return this.router.collectMiddlewarePublic(path, routeMiddleware);
1357
+ }
1358
+ /**
1359
+ * Compile routes for optimization
1360
+ */
1361
+ compileRoutes() {
1362
+ this.staticRoutes = this.router.staticRoutes;
1363
+ const hasGlobalMiddleware = this.router.globalMiddleware.length > 0;
1364
+ const hasPathMiddleware = this.router.pathMiddleware.size > 0;
1365
+ this.isPureStaticApp = !hasGlobalMiddleware && !hasPathMiddleware;
1366
+ for (const [key, route] of this.staticRoutes) {
1367
+ if (route.compiledVersion === this.middlewareVersion) {
1368
+ continue;
1369
+ }
1370
+ const analysis = analyzeHandler(route.handler);
1371
+ const optimalType = getOptimalContextType(analysis);
1372
+ route.useMinimal = this.isPureStaticApp && route.middleware.length === 0 && optimalType === "minimal";
1373
+ if (!route.useMinimal) {
1374
+ const allMiddleware = this.collectMiddlewareForPath(key.split(":")[1], route.middleware);
1375
+ route.compiled = compileMiddlewareChain(allMiddleware, route.handler);
1376
+ }
1377
+ route.compiledVersion = this.middlewareVersion;
1378
+ }
1379
+ }
1380
+ /**
1381
+ * Add a route to the router
1382
+ */
1383
+ addRoute(method, path, handlers) {
1384
+ if (handlers.length === 0) {
1385
+ throw new Error(`No handler provided for ${method.toUpperCase()} ${path}`);
1386
+ }
1387
+ const handler = handlers[handlers.length - 1];
1388
+ const middleware = handlers.slice(0, -1);
1389
+ this.router.add(method, path, handler, middleware);
1390
+ this.compileRoutes();
1391
+ return this;
1392
+ }
1393
+ /**
1394
+ * Execute middleware chain followed by handler
1395
+ */
1396
+ async executeMiddleware(ctx, middleware, handler) {
1397
+ let index = 0;
1398
+ const next = async () => {
1399
+ if (index < middleware.length) {
1400
+ const mw = middleware[index++];
1401
+ return await mw(ctx, next);
1402
+ }
1403
+ return void 0;
1404
+ };
1405
+ const result = await next();
1406
+ if (result instanceof Response) {
1407
+ return result;
1408
+ }
1409
+ return await handler(ctx);
1410
+ }
1411
+ /**
1412
+ * Handle errors (Async version for dynamic/middleware paths)
1413
+ */
1414
+ async handleError(error, ctx) {
1415
+ if (this.errorHandler) {
1416
+ return await this.errorHandler(error, ctx);
1417
+ }
1418
+ console.error("Unhandled error:", error);
1419
+ return ctx.json(
1420
+ {
1421
+ error: "Internal Server Error",
1422
+ message: error.message
1423
+ },
1424
+ 500
1425
+ );
1426
+ }
1427
+ };
1428
+ export {
1429
+ AOTRouter,
1430
+ FastContext as FastContextImpl,
1431
+ Gravito,
1432
+ MinimalContext,
1433
+ ObjectPool,
1434
+ extractPath
1435
+ };