@gravito/core 1.2.1 → 1.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1764 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/engine/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ AOTRouter: () => AOTRouter,
24
+ FastContextImpl: () => FastContext,
25
+ Gravito: () => Gravito,
26
+ MinimalContext: () => MinimalContext,
27
+ ObjectPool: () => ObjectPool,
28
+ extractPath: () => extractPath
29
+ });
30
+ module.exports = __toCommonJS(index_exports);
31
+
32
+ // src/adapters/bun/RadixNode.ts
33
+ var RadixNode = class _RadixNode {
34
+ // Path segment for this node (e.g., "users", ":id")
35
+ segment;
36
+ // Node type (Static, Param, Wildcard)
37
+ type;
38
+ // Children nodes (mapped by segment for fast lookup)
39
+ children = /* @__PURE__ */ new Map();
40
+ // Specialized child for parameter node (only one per level allowed usually to avoid ambiguity, though some routers support multiple)
41
+ paramChild = null;
42
+ // Specialized child for wildcard node
43
+ wildcardChild = null;
44
+ // Handlers registered at this node (keyed by HTTP method)
45
+ handlers = /* @__PURE__ */ new Map();
46
+ // Parameter name if this is a PARAM node (e.g., "id" for ":id")
47
+ paramName = null;
48
+ // Parameter constraints (regex) - only applicable if this is a PARAM node
49
+ // If we support per-route constraints, they might need to be stored differently,
50
+ // but for now assume constraints are defined at node level (uncommon) or checked at match time.
51
+ // Laravel allows global pattern constraints or per-route.
52
+ // Ideally, constraints should be stored with the handler or part of matching logic.
53
+ // For a Radix tree, if we have constraints, we might need to backtrack if constraint fails?
54
+ // Or simply store constraint with the param node.
55
+ regex = null;
56
+ constructor(segment = "", type = 0 /* STATIC */) {
57
+ this.segment = segment;
58
+ this.type = type;
59
+ }
60
+ toJSON() {
61
+ return {
62
+ segment: this.segment,
63
+ type: this.type,
64
+ children: Array.from(this.children.entries()).map(([k, v]) => [k, v.toJSON()]),
65
+ paramChild: this.paramChild?.toJSON() || null,
66
+ wildcardChild: this.wildcardChild?.toJSON() || null,
67
+ paramName: this.paramName,
68
+ regex: this.regex ? this.regex.source : null
69
+ };
70
+ }
71
+ static fromJSON(json) {
72
+ const node = new _RadixNode(json.segment, json.type);
73
+ node.paramName = json.paramName;
74
+ if (json.regex) {
75
+ node.regex = new RegExp(json.regex);
76
+ }
77
+ if (json.children) {
78
+ for (const [key, childJson] of json.children) {
79
+ node.children.set(key, _RadixNode.fromJSON(childJson));
80
+ }
81
+ }
82
+ if (json.paramChild) {
83
+ node.paramChild = _RadixNode.fromJSON(json.paramChild);
84
+ }
85
+ if (json.wildcardChild) {
86
+ node.wildcardChild = _RadixNode.fromJSON(json.wildcardChild);
87
+ }
88
+ return node;
89
+ }
90
+ };
91
+
92
+ // src/adapters/bun/RadixRouter.ts
93
+ var RadixRouter = class _RadixRouter {
94
+ root = new RadixNode();
95
+ // Global parameter constraints (e.g., id => /^\d+$/)
96
+ globalConstraints = /* @__PURE__ */ new Map();
97
+ /**
98
+ * Add a generic parameter constraint
99
+ */
100
+ where(param, regex) {
101
+ this.globalConstraints.set(param, regex);
102
+ }
103
+ /**
104
+ * Register a route
105
+ */
106
+ add(method, path, handlers) {
107
+ let node = this.root;
108
+ const segments = this.splitPath(path);
109
+ for (let i = 0; i < segments.length; i++) {
110
+ const segment = segments[i];
111
+ if (segment === "*") {
112
+ if (!node.wildcardChild) {
113
+ node.wildcardChild = new RadixNode("*", 2 /* WILDCARD */);
114
+ }
115
+ node = node.wildcardChild;
116
+ break;
117
+ } else if (segment.startsWith(":")) {
118
+ const paramName = segment.slice(1);
119
+ if (!node.paramChild) {
120
+ const child = new RadixNode(segment, 1 /* PARAM */);
121
+ child.paramName = paramName;
122
+ const constraint = this.globalConstraints.get(paramName);
123
+ if (constraint) {
124
+ child.regex = constraint;
125
+ }
126
+ node.paramChild = child;
127
+ }
128
+ node = node.paramChild;
129
+ } else {
130
+ if (!node.children.has(segment)) {
131
+ node.children.set(segment, new RadixNode(segment, 0 /* STATIC */));
132
+ }
133
+ node = node.children.get(segment);
134
+ }
135
+ }
136
+ node.handlers.set(method.toLowerCase(), handlers);
137
+ }
138
+ /**
139
+ * Match a request
140
+ */
141
+ match(method, path) {
142
+ const normalizedMethod = method.toLowerCase();
143
+ if (path === "/" || path === "") {
144
+ const handlers = this.root.handlers.get(normalizedMethod);
145
+ if (handlers) {
146
+ return { handlers, params: {} };
147
+ }
148
+ return null;
149
+ }
150
+ const searchPath = path.startsWith("/") ? path.slice(1) : path;
151
+ const segments = searchPath.split("/");
152
+ return this.matchRecursive(this.root, segments, 0, {}, normalizedMethod);
153
+ }
154
+ matchRecursive(node, segments, depth, params, method) {
155
+ if (depth >= segments.length) {
156
+ let handlers = node.handlers.get(method);
157
+ if (!handlers) {
158
+ handlers = node.handlers.get("all");
159
+ }
160
+ if (handlers) {
161
+ return { handlers, params };
162
+ }
163
+ return null;
164
+ }
165
+ const segment = segments[depth];
166
+ const staticChild = node.children.get(segment);
167
+ if (staticChild) {
168
+ const match = this.matchRecursive(staticChild, segments, depth + 1, params, method);
169
+ if (match) {
170
+ return match;
171
+ }
172
+ }
173
+ const paramChild = node.paramChild;
174
+ if (paramChild) {
175
+ if (paramChild.regex && !paramChild.regex.test(segment)) {
176
+ } else {
177
+ if (paramChild.paramName) {
178
+ params[paramChild.paramName] = decodeURIComponent(segment);
179
+ const match = this.matchRecursive(paramChild, segments, depth + 1, params, method);
180
+ if (match) {
181
+ return match;
182
+ }
183
+ delete params[paramChild.paramName];
184
+ }
185
+ }
186
+ }
187
+ if (node.wildcardChild) {
188
+ let handlers = node.wildcardChild.handlers.get(method);
189
+ if (!handlers) {
190
+ handlers = node.wildcardChild.handlers.get("all");
191
+ }
192
+ if (handlers) {
193
+ return { handlers, params };
194
+ }
195
+ }
196
+ return null;
197
+ }
198
+ splitPath(path) {
199
+ if (path === "/" || path === "") {
200
+ return [];
201
+ }
202
+ let p = path;
203
+ if (p.startsWith("/")) {
204
+ p = p.slice(1);
205
+ }
206
+ if (p.endsWith("/")) {
207
+ p = p.slice(0, -1);
208
+ }
209
+ return p.split("/");
210
+ }
211
+ /**
212
+ * Serialize the router to a JSON string
213
+ */
214
+ serialize() {
215
+ return JSON.stringify({
216
+ root: this.root.toJSON(),
217
+ globalConstraints: Array.from(this.globalConstraints.entries()).map(([k, v]) => [
218
+ k,
219
+ v.source
220
+ ])
221
+ });
222
+ }
223
+ /**
224
+ * Restore a router from a serialized JSON string
225
+ */
226
+ static fromSerialized(json) {
227
+ const data = JSON.parse(json);
228
+ const router = new _RadixRouter();
229
+ router.root = RadixNode.fromJSON(data.root);
230
+ if (data.globalConstraints) {
231
+ for (const [key, source] of data.globalConstraints) {
232
+ router.globalConstraints.set(key, new RegExp(source));
233
+ }
234
+ }
235
+ return router;
236
+ }
237
+ };
238
+
239
+ // src/engine/AOTRouter.ts
240
+ var AOTRouter = class {
241
+ // Static route cache: "METHOD:PATH" -> RouteMetadata
242
+ /** @internal */
243
+ staticRoutes = /* @__PURE__ */ new Map();
244
+ // Dynamic route handler (Radix Tree)
245
+ dynamicRouter = new RadixRouter();
246
+ // Store all route definitions to support mounting/merging
247
+ /** @internal */
248
+ routeDefinitions = [];
249
+ // Global middleware (applies to all routes)
250
+ /** @internal */
251
+ globalMiddleware = [];
252
+ // Path-based middleware: pattern -> middleware[]
253
+ /** @internal */
254
+ pathMiddleware = /* @__PURE__ */ new Map();
255
+ // Dynamic route patterns: handler function -> route pattern
256
+ // 用於追蹤動態路由的模式,防止高基數問題
257
+ dynamicRoutePatterns = /* @__PURE__ */ new Map();
258
+ middlewareCache = /* @__PURE__ */ new Map();
259
+ cacheMaxSize = 1e3;
260
+ _version = 0;
261
+ /**
262
+ * Get the current version for cache invalidation
263
+ * Incremented whenever middleware or routes are modified
264
+ */
265
+ get version() {
266
+ return this._version;
267
+ }
268
+ /**
269
+ * Register a route
270
+ *
271
+ * Automatically determines if route is static or dynamic.
272
+ * Static routes are stored in a Map for O(1) lookup.
273
+ * Dynamic routes use the Radix Tree.
274
+ *
275
+ * @param method - HTTP method
276
+ * @param path - Route path
277
+ * @param handler - Route handler
278
+ * @param middleware - Route-specific middleware
279
+ */
280
+ add(method, path, handler, middleware = []) {
281
+ this.routeDefinitions.push({ method, path, handler, middleware });
282
+ const normalizedMethod = method.toLowerCase();
283
+ if (this.isStaticPath(path)) {
284
+ const key = `${normalizedMethod}:${path}`;
285
+ this.staticRoutes.set(key, { handler, middleware });
286
+ } else {
287
+ const wrappedHandler = handler;
288
+ this.dynamicRouter.add(normalizedMethod, path, [wrappedHandler]);
289
+ this.dynamicRoutePatterns.set(wrappedHandler, path);
290
+ if (middleware.length > 0) {
291
+ this.pathMiddleware.set(`${normalizedMethod}:${path}`, middleware);
292
+ }
293
+ }
294
+ }
295
+ /**
296
+ * Mount another router at a prefix
297
+ */
298
+ mount(prefix, other) {
299
+ if (other.globalMiddleware.length > 0) {
300
+ this.usePattern(prefix, ...other.globalMiddleware);
301
+ const wildcard = prefix === "/" ? "/*" : `${prefix}/*`;
302
+ this.usePattern(wildcard, ...other.globalMiddleware);
303
+ }
304
+ for (const [pattern, mws] of other.pathMiddleware) {
305
+ if (pattern.includes(":")) {
306
+ continue;
307
+ }
308
+ let newPattern;
309
+ if (pattern === "*") {
310
+ newPattern = prefix === "/" ? "/*" : `${prefix}/*`;
311
+ } else if (pattern.startsWith("/")) {
312
+ newPattern = prefix === "/" ? pattern : `${prefix}${pattern}`;
313
+ } else {
314
+ newPattern = prefix === "/" ? `/${pattern}` : `${prefix}/${pattern}`;
315
+ }
316
+ this.usePattern(newPattern, ...mws);
317
+ }
318
+ for (const def of other.routeDefinitions) {
319
+ let newPath;
320
+ if (prefix === "/") {
321
+ newPath = def.path;
322
+ } else if (def.path === "/") {
323
+ newPath = prefix;
324
+ } else {
325
+ newPath = `${prefix}${def.path}`;
326
+ }
327
+ this.add(def.method, newPath, def.handler, def.middleware);
328
+ }
329
+ }
330
+ /**
331
+ * Add global middleware
332
+ *
333
+ * These run for every request, before route-specific middleware.
334
+ *
335
+ * @param middleware - Middleware functions
336
+ */
337
+ use(...middleware) {
338
+ this.globalMiddleware.push(...middleware);
339
+ this._version++;
340
+ }
341
+ /**
342
+ * Add path-based middleware
343
+ *
344
+ * Supports wildcard patterns like '/api/*'
345
+ *
346
+ * @param pattern - Path pattern
347
+ * @param middleware - Middleware functions
348
+ */
349
+ usePattern(pattern, ...middleware) {
350
+ if (pattern === "*") {
351
+ this.globalMiddleware.push(...middleware);
352
+ } else {
353
+ const existing = this.pathMiddleware.get(pattern) ?? [];
354
+ this.pathMiddleware.set(pattern, [...existing, ...middleware]);
355
+ }
356
+ this._version++;
357
+ }
358
+ /**
359
+ * Match a request to a route
360
+ *
361
+ * Returns the handler, params, and all applicable middleware.
362
+ *
363
+ * @param method - HTTP method
364
+ * @param path - Request path
365
+ * @returns Route match or null if not found
366
+ */
367
+ match(method, path) {
368
+ const normalizedMethod = method.toLowerCase();
369
+ const staticKey = `${normalizedMethod}:${path}`;
370
+ const staticRoute = this.staticRoutes.get(staticKey);
371
+ if (staticRoute) {
372
+ return {
373
+ handler: staticRoute.handler,
374
+ params: {},
375
+ middleware: this.collectMiddleware(path, staticRoute.middleware),
376
+ routePattern: path
377
+ };
378
+ }
379
+ const match = this.dynamicRouter.match(normalizedMethod, path);
380
+ if (match && match.handlers.length > 0) {
381
+ const handler = match.handlers[0];
382
+ const wrappedHandler = match.handlers[0];
383
+ const routePattern = this.dynamicRoutePatterns.get(wrappedHandler);
384
+ const routeKey = routePattern ? `${normalizedMethod}:${routePattern}` : null;
385
+ const routeMiddleware = routeKey ? this.pathMiddleware.get(routeKey) ?? [] : [];
386
+ return {
387
+ handler,
388
+ params: match.params,
389
+ middleware: this.collectMiddleware(path, routeMiddleware),
390
+ routePattern
391
+ };
392
+ }
393
+ return {
394
+ handler: null,
395
+ params: {},
396
+ middleware: []
397
+ };
398
+ }
399
+ /**
400
+ * Public wrapper for collectMiddleware (used by Gravito for optimization)
401
+ */
402
+ collectMiddlewarePublic(path, routeMiddleware) {
403
+ return this.collectMiddleware(path, routeMiddleware);
404
+ }
405
+ /**
406
+ * Collect all applicable middleware for a path
407
+ *
408
+ * Order: global -> pattern-based -> route-specific
409
+ *
410
+ * @param path - Request path
411
+ * @param routeMiddleware - Route-specific middleware
412
+ * @returns Combined middleware array
413
+ */
414
+ collectMiddleware(path, routeMiddleware) {
415
+ if (this.globalMiddleware.length === 0 && this.pathMiddleware.size === 0 && routeMiddleware.length === 0) {
416
+ return [];
417
+ }
418
+ const cacheKey = path;
419
+ const cached = this.middlewareCache.get(cacheKey);
420
+ if (cached !== void 0 && cached.version === this._version) {
421
+ return cached.data;
422
+ }
423
+ const middleware = [];
424
+ if (this.globalMiddleware.length > 0) {
425
+ middleware.push(...this.globalMiddleware);
426
+ }
427
+ if (this.pathMiddleware.size > 0) {
428
+ for (const [pattern, mw] of this.pathMiddleware) {
429
+ if (pattern.includes(":")) {
430
+ continue;
431
+ }
432
+ if (this.matchPattern(pattern, path)) {
433
+ middleware.push(...mw);
434
+ }
435
+ }
436
+ }
437
+ if (routeMiddleware.length > 0) {
438
+ middleware.push(...routeMiddleware);
439
+ }
440
+ if (this.middlewareCache.size < this.cacheMaxSize) {
441
+ this.middlewareCache.set(cacheKey, { data: middleware, version: this._version });
442
+ } else if (this.middlewareCache.has(cacheKey)) {
443
+ this.middlewareCache.set(cacheKey, { data: middleware, version: this._version });
444
+ }
445
+ return middleware;
446
+ }
447
+ /**
448
+ * Check if a path is static (no parameters or wildcards)
449
+ */
450
+ isStaticPath(path) {
451
+ return !path.includes(":") && !path.includes("*");
452
+ }
453
+ /**
454
+ * Match a pattern against a path
455
+ *
456
+ * Supports:
457
+ * - Exact match: '/api/users'
458
+ * - Wildcard suffix: '/api/*'
459
+ *
460
+ * @param pattern - Pattern to match
461
+ * @param path - Path to test
462
+ * @returns True if pattern matches
463
+ */
464
+ matchPattern(pattern, path) {
465
+ if (pattern === "*") {
466
+ return true;
467
+ }
468
+ if (pattern === path) {
469
+ return true;
470
+ }
471
+ if (pattern.endsWith("/*")) {
472
+ const prefix = pattern.slice(0, -2);
473
+ return path.startsWith(prefix);
474
+ }
475
+ return false;
476
+ }
477
+ /**
478
+ * Get all registered routes (for debugging)
479
+ */
480
+ getRoutes() {
481
+ const routes = [];
482
+ for (const key of this.staticRoutes.keys()) {
483
+ const [method, path] = key.split(":");
484
+ routes.push({ method, path, type: "static" });
485
+ }
486
+ return routes;
487
+ }
488
+ };
489
+
490
+ // src/engine/analyzer.ts
491
+ function analyzeHandler(handler) {
492
+ const source = handler.toString();
493
+ return {
494
+ usesHeaders: source.includes(".header(") || source.includes(".header)") || source.includes(".headers(") || source.includes(".headers)"),
495
+ usesQuery: source.includes(".query(") || source.includes(".query)") || source.includes(".queries(") || source.includes(".queries)"),
496
+ usesBody: source.includes(".json()") || source.includes(".text()") || source.includes(".formData()") || source.includes(".body"),
497
+ usesParams: source.includes(".param(") || source.includes(".param)") || source.includes(".params(") || source.includes(".params)"),
498
+ isAsync: source.includes("async") || source.includes("await")
499
+ };
500
+ }
501
+ function getOptimalContextType(analysis) {
502
+ if (analysis.usesHeaders) {
503
+ return "fast";
504
+ }
505
+ if (!analysis.usesQuery && !analysis.usesBody && !analysis.usesParams) {
506
+ return "minimal";
507
+ }
508
+ if (!analysis.usesQuery && !analysis.usesBody && analysis.usesParams) {
509
+ return "minimal";
510
+ }
511
+ if (analysis.usesBody) {
512
+ return "full";
513
+ }
514
+ return "fast";
515
+ }
516
+
517
+ // src/engine/constants.ts
518
+ var encoder = new TextEncoder();
519
+ var CACHED_RESPONSES = {
520
+ NOT_FOUND: encoder.encode('{"error":"Not Found"}'),
521
+ INTERNAL_ERROR: encoder.encode('{"error":"Internal Server Error"}'),
522
+ OK: encoder.encode('{"ok":true}'),
523
+ EMPTY: new Uint8Array(0)
524
+ };
525
+ var HEADERS = {
526
+ JSON: { "Content-Type": "application/json; charset=utf-8" },
527
+ TEXT: { "Content-Type": "text/plain; charset=utf-8" },
528
+ HTML: { "Content-Type": "text/html; charset=utf-8" }
529
+ };
530
+
531
+ // src/Container/RequestScopeMetrics.ts
532
+ var RequestScopeMetrics = class {
533
+ cleanupStartTime = null;
534
+ cleanupDuration = null;
535
+ scopeSize = 0;
536
+ servicesCleaned = 0;
537
+ errorsOccurred = 0;
538
+ /**
539
+ * Record start of cleanup operation
540
+ */
541
+ recordCleanupStart() {
542
+ this.cleanupStartTime = performance.now();
543
+ }
544
+ /**
545
+ * Record end of cleanup operation
546
+ *
547
+ * @param scopeSize - Number of services in the scope
548
+ * @param servicesCleaned - Number of services that had cleanup called
549
+ * @param errorsOccurred - Number of cleanup errors
550
+ */
551
+ recordCleanupEnd(scopeSize, servicesCleaned, errorsOccurred = 0) {
552
+ if (this.cleanupStartTime !== null) {
553
+ this.cleanupDuration = performance.now() - this.cleanupStartTime;
554
+ this.cleanupStartTime = null;
555
+ }
556
+ this.scopeSize = scopeSize;
557
+ this.servicesCleaned = servicesCleaned;
558
+ this.errorsOccurred = errorsOccurred;
559
+ }
560
+ /**
561
+ * Get cleanup duration in milliseconds
562
+ *
563
+ * @returns Duration in ms, or null if cleanup not completed
564
+ */
565
+ getCleanupDuration() {
566
+ return this.cleanupDuration;
567
+ }
568
+ /**
569
+ * Check if cleanup took longer than threshold (default 2ms)
570
+ * Useful for detecting slow cleanups
571
+ *
572
+ * @param thresholdMs - Threshold in milliseconds
573
+ * @returns True if cleanup exceeded threshold
574
+ */
575
+ isSlowCleanup(thresholdMs = 2) {
576
+ if (this.cleanupDuration === null) return false;
577
+ return this.cleanupDuration > thresholdMs;
578
+ }
579
+ /**
580
+ * Export metrics as JSON for logging/monitoring
581
+ */
582
+ toJSON() {
583
+ return {
584
+ cleanupDuration: this.cleanupDuration,
585
+ scopeSize: this.scopeSize,
586
+ servicesCleaned: this.servicesCleaned,
587
+ errorsOccurred: this.errorsOccurred,
588
+ hasErrors: this.errorsOccurred > 0,
589
+ isSlowCleanup: this.isSlowCleanup()
590
+ };
591
+ }
592
+ /**
593
+ * Export metrics as compact string for logging
594
+ */
595
+ toString() {
596
+ const duration = this.cleanupDuration ?? "pending";
597
+ return `cleanup: ${duration}ms, scope: ${this.scopeSize}, cleaned: ${this.servicesCleaned}, errors: ${this.errorsOccurred}`;
598
+ }
599
+ };
600
+
601
+ // src/Container/RequestScopeManager.ts
602
+ var RequestScopeManager = class {
603
+ scoped = /* @__PURE__ */ new Map();
604
+ metadata = /* @__PURE__ */ new Map();
605
+ metrics = new RequestScopeMetrics();
606
+ observer = null;
607
+ constructor(observer) {
608
+ this.observer = observer || null;
609
+ }
610
+ /**
611
+ * Set observer for monitoring scope lifecycle
612
+ */
613
+ setObserver(observer) {
614
+ this.observer = observer;
615
+ }
616
+ /**
617
+ * Get metrics for this scope
618
+ */
619
+ getMetrics() {
620
+ return this.metrics;
621
+ }
622
+ /**
623
+ * Resolve or retrieve a request-scoped service instance.
624
+ *
625
+ * If the service already exists in this scope, returns the cached instance.
626
+ * Otherwise, calls the factory function to create a new instance and caches it.
627
+ *
628
+ * Automatically detects and records services with cleanup methods.
629
+ *
630
+ * @template T - The type of the service.
631
+ * @param key - The service key (for caching).
632
+ * @param factory - Factory function to create the instance if not cached.
633
+ * @returns The cached or newly created instance.
634
+ */
635
+ resolve(key, factory) {
636
+ const keyStr = String(key);
637
+ const isFromCache = this.scoped.has(keyStr);
638
+ if (!isFromCache) {
639
+ const instance = factory();
640
+ this.scoped.set(keyStr, instance);
641
+ if (instance && typeof instance === "object" && "cleanup" in instance) {
642
+ this.metadata.set(keyStr, { hasCleanup: true });
643
+ }
644
+ }
645
+ this.observer?.onServiceResolved?.(key, isFromCache);
646
+ return this.scoped.get(keyStr);
647
+ }
648
+ /**
649
+ * Clean up all request-scoped instances.
650
+ *
651
+ * Calls the cleanup() method on each service that has one.
652
+ * Silently ignores cleanup errors to prevent cascading failures.
653
+ * Called automatically by the Gravito engine in the request finally block.
654
+ *
655
+ * @returns Promise that resolves when all cleanup is complete.
656
+ */
657
+ async cleanup() {
658
+ this.metrics.recordCleanupStart();
659
+ this.observer?.onCleanupStart?.();
660
+ const errors = [];
661
+ let servicesCleaned = 0;
662
+ for (const [, instance] of this.scoped) {
663
+ if (instance && typeof instance === "object" && "cleanup" in instance) {
664
+ const fn = instance.cleanup;
665
+ if (typeof fn === "function") {
666
+ try {
667
+ await fn.call(instance);
668
+ servicesCleaned++;
669
+ } catch (error) {
670
+ errors.push(error);
671
+ this.observer?.onCleanupError?.(
672
+ error instanceof Error ? error : new Error(String(error))
673
+ );
674
+ }
675
+ }
676
+ }
677
+ }
678
+ const scopeSize = this.scoped.size;
679
+ this.scoped.clear();
680
+ this.metadata.clear();
681
+ this.metrics.recordCleanupEnd(scopeSize, servicesCleaned, errors.length);
682
+ this.observer?.onCleanupEnd?.(this.metrics);
683
+ if (errors.length > 0) {
684
+ console.error("RequestScope cleanup errors:", errors);
685
+ }
686
+ }
687
+ /**
688
+ * Get the number of services in this scope (for monitoring).
689
+ *
690
+ * @returns The count of cached services.
691
+ */
692
+ size() {
693
+ return this.scoped.size;
694
+ }
695
+ };
696
+
697
+ // src/engine/FastContext.ts
698
+ var FastRequestImpl = class {
699
+ _request;
700
+ _params;
701
+ _path;
702
+ _routePattern;
703
+ _url = null;
704
+ _query = null;
705
+ _headers = null;
706
+ _cachedJson = void 0;
707
+ _jsonParsed = false;
708
+ _cachedText = void 0;
709
+ _textParsed = false;
710
+ _cachedFormData = void 0;
711
+ _formDataParsed = false;
712
+ _cachedQueries = null;
713
+ // Back-reference for release check optimization
714
+ _ctx;
715
+ constructor(ctx) {
716
+ this._ctx = ctx;
717
+ }
718
+ /**
719
+ * Initialize for new request
720
+ */
721
+ init(request, params = {}, path = "", routePattern) {
722
+ this._request = request;
723
+ this._params = params;
724
+ this._path = path;
725
+ this._routePattern = routePattern;
726
+ this._url = null;
727
+ this._query = null;
728
+ this._headers = null;
729
+ this._cachedJson = void 0;
730
+ this._jsonParsed = false;
731
+ this._cachedText = void 0;
732
+ this._textParsed = false;
733
+ this._cachedFormData = void 0;
734
+ this._formDataParsed = false;
735
+ this._cachedQueries = null;
736
+ return this;
737
+ }
738
+ /**
739
+ * Reset for pooling
740
+ */
741
+ reset() {
742
+ this._request = void 0;
743
+ this._params = void 0;
744
+ this._url = null;
745
+ this._query = null;
746
+ this._headers = null;
747
+ this._cachedJson = void 0;
748
+ this._jsonParsed = false;
749
+ this._cachedText = void 0;
750
+ this._textParsed = false;
751
+ this._cachedFormData = void 0;
752
+ this._formDataParsed = false;
753
+ this._cachedQueries = null;
754
+ }
755
+ checkReleased() {
756
+ if (this._ctx._isReleased) {
757
+ throw new Error(
758
+ "FastContext usage after release detected! (Object Pool Strict Lifecycle Guard)"
759
+ );
760
+ }
761
+ }
762
+ get url() {
763
+ this.checkReleased();
764
+ return this._request.url;
765
+ }
766
+ get method() {
767
+ this.checkReleased();
768
+ return this._request.method;
769
+ }
770
+ get path() {
771
+ this.checkReleased();
772
+ return this._path;
773
+ }
774
+ get routePattern() {
775
+ this.checkReleased();
776
+ return this._routePattern;
777
+ }
778
+ param(name) {
779
+ this.checkReleased();
780
+ return this._params[name];
781
+ }
782
+ params() {
783
+ this.checkReleased();
784
+ return { ...this._params };
785
+ }
786
+ getUrl() {
787
+ if (!this._url) {
788
+ this._url = new URL(this._request.url);
789
+ }
790
+ return this._url;
791
+ }
792
+ query(name) {
793
+ this.checkReleased();
794
+ if (!this._query) {
795
+ this._query = this.getUrl().searchParams;
796
+ }
797
+ return this._query.get(name) ?? void 0;
798
+ }
799
+ queries() {
800
+ this.checkReleased();
801
+ if (this._cachedQueries !== null) {
802
+ return this._cachedQueries;
803
+ }
804
+ if (!this._query) {
805
+ this._query = this.getUrl().searchParams;
806
+ }
807
+ const result = {};
808
+ for (const [key, value] of this._query.entries()) {
809
+ const existing = result[key];
810
+ if (existing === void 0) {
811
+ result[key] = value;
812
+ } else if (Array.isArray(existing)) {
813
+ existing.push(value);
814
+ } else {
815
+ result[key] = [existing, value];
816
+ }
817
+ }
818
+ this._cachedQueries = result;
819
+ return result;
820
+ }
821
+ header(name) {
822
+ this.checkReleased();
823
+ return this._request.headers.get(name) ?? void 0;
824
+ }
825
+ headers() {
826
+ this.checkReleased();
827
+ if (!this._headers) {
828
+ this._headers = {};
829
+ for (const [key, value] of this._request.headers.entries()) {
830
+ this._headers[key] = value;
831
+ }
832
+ }
833
+ return { ...this._headers };
834
+ }
835
+ async json() {
836
+ this.checkReleased();
837
+ if (!this._jsonParsed) {
838
+ this._cachedJson = await this._request.json();
839
+ this._jsonParsed = true;
840
+ }
841
+ return this._cachedJson;
842
+ }
843
+ async text() {
844
+ this.checkReleased();
845
+ if (!this._textParsed) {
846
+ this._cachedText = await this._request.text();
847
+ this._textParsed = true;
848
+ }
849
+ return this._cachedText;
850
+ }
851
+ async formData() {
852
+ this.checkReleased();
853
+ if (!this._formDataParsed) {
854
+ this._cachedFormData = await this._request.formData();
855
+ this._formDataParsed = true;
856
+ }
857
+ return this._cachedFormData;
858
+ }
859
+ get raw() {
860
+ this.checkReleased();
861
+ return this._request;
862
+ }
863
+ };
864
+ var FastContext = class {
865
+ req = new FastRequestImpl(this);
866
+ // private _statusCode = 200
867
+ _headers = new Headers();
868
+ // Reuse this object
869
+ _isReleased = false;
870
+ // Made public for internal check access
871
+ _requestScope = null;
872
+ // Request-scoped services
873
+ /**
874
+ * Initialize context for a new request
875
+ *
876
+ * This is called when acquiring from the pool.
877
+ */
878
+ init(request, params = {}, path = "", routePattern) {
879
+ this._isReleased = false;
880
+ this.req.init(request, params, path, routePattern);
881
+ this._headers = new Headers();
882
+ this._requestScope = new RequestScopeManager();
883
+ return this;
884
+ }
885
+ /**
886
+ * Reset context for pooling (Cleanup)
887
+ *
888
+ * This is called when releasing back to the pool.
889
+ * Implements "Deep-Reset Protocol" and "Release Guard".
890
+ */
891
+ reset() {
892
+ this._isReleased = true;
893
+ this.req.reset();
894
+ this._store.clear();
895
+ }
896
+ /**
897
+ * Check if context is released
898
+ */
899
+ checkReleased() {
900
+ if (this._isReleased) {
901
+ throw new Error(
902
+ "FastContext usage after release detected! (Object Pool Strict Lifecycle Guard)"
903
+ );
904
+ }
905
+ }
906
+ // ─────────────────────────────────────────────────────────────────────────
907
+ // Response Helpers
908
+ // ─────────────────────────────────────────────────────────────────────────
909
+ json(data, status = 200) {
910
+ this.checkReleased();
911
+ this._headers.set("Content-Type", "application/json; charset=utf-8");
912
+ return new Response(JSON.stringify(data), {
913
+ status,
914
+ headers: this._headers
915
+ });
916
+ }
917
+ text(text, status = 200) {
918
+ this.checkReleased();
919
+ this._headers.set("Content-Type", "text/plain; charset=utf-8");
920
+ return new Response(text, {
921
+ status,
922
+ headers: this._headers
923
+ });
924
+ }
925
+ html(html, status = 200) {
926
+ this.checkReleased();
927
+ this._headers.set("Content-Type", "text/html; charset=utf-8");
928
+ return new Response(html, {
929
+ status,
930
+ headers: this._headers
931
+ });
932
+ }
933
+ redirect(url, status = 302) {
934
+ this.checkReleased();
935
+ this._headers.set("Location", url);
936
+ return new Response(null, {
937
+ status,
938
+ headers: this._headers
939
+ });
940
+ }
941
+ body(data, status = 200) {
942
+ this.checkReleased();
943
+ return new Response(data, {
944
+ status,
945
+ headers: this._headers
946
+ });
947
+ }
948
+ stream(stream, status = 200) {
949
+ this.checkReleased();
950
+ this._headers.set("Content-Type", "application/octet-stream");
951
+ return new Response(stream, {
952
+ status,
953
+ headers: this._headers
954
+ });
955
+ }
956
+ notFound(message = "Not Found") {
957
+ return this.text(message, 404);
958
+ }
959
+ forbidden(message = "Forbidden") {
960
+ return this.text(message, 403);
961
+ }
962
+ unauthorized(message = "Unauthorized") {
963
+ return this.text(message, 401);
964
+ }
965
+ badRequest(message = "Bad Request") {
966
+ return this.text(message, 400);
967
+ }
968
+ async forward(target, _options = {}) {
969
+ this.checkReleased();
970
+ const url = new URL(this.req.url);
971
+ const targetUrl = new URL(
972
+ target.startsWith("http") ? target : `${url.protocol}//${target}${this.req.path}`
973
+ );
974
+ const searchParams = new URLSearchParams(url.search);
975
+ searchParams.forEach((v, k) => {
976
+ targetUrl.searchParams.set(k, v);
977
+ });
978
+ return fetch(targetUrl.toString(), {
979
+ method: this.req.method,
980
+ headers: this.req.raw.headers,
981
+ body: this.req.method !== "GET" && this.req.method !== "HEAD" ? this.req.raw.body : null,
982
+ // @ts-expect-error - Bun/Fetch specific
983
+ duplex: "half"
984
+ });
985
+ }
986
+ header(name, value) {
987
+ this.checkReleased();
988
+ if (value !== void 0) {
989
+ this._headers.set(name, value);
990
+ return;
991
+ }
992
+ return this.req.header(name);
993
+ }
994
+ status(_code) {
995
+ this.checkReleased();
996
+ }
997
+ // ─────────────────────────────────────────────────────────────────────────
998
+ // Context Variables
999
+ // ─────────────────────────────────────────────────────────────────────────
1000
+ _store = /* @__PURE__ */ new Map();
1001
+ get(key) {
1002
+ return this._store.get(key);
1003
+ }
1004
+ set(key, value) {
1005
+ this._store.set(key, value);
1006
+ }
1007
+ // ─────────────────────────────────────────────────────────────────────────
1008
+ // Request Scope Management
1009
+ // ─────────────────────────────────────────────────────────────────────────
1010
+ /**
1011
+ * Get the request-scoped service manager for this request.
1012
+ *
1013
+ * @returns The RequestScopeManager for this request.
1014
+ * @throws Error if called before init() or after reset().
1015
+ */
1016
+ requestScope() {
1017
+ if (!this._requestScope) {
1018
+ throw new Error("RequestScope not initialized. Call init() first.");
1019
+ }
1020
+ return this._requestScope;
1021
+ }
1022
+ /**
1023
+ * Resolve a request-scoped service (convenience method).
1024
+ *
1025
+ * @template T - The service type.
1026
+ * @param key - The service key for caching.
1027
+ * @param factory - Factory function to create the service.
1028
+ * @returns The cached or newly created service instance.
1029
+ */
1030
+ scoped(key, factory) {
1031
+ return this.requestScope().resolve(key, factory);
1032
+ }
1033
+ // ─────────────────────────────────────────────────────────────────────────
1034
+ // Lifecycle helpers
1035
+ // ─────────────────────────────────────────────────────────────────────────
1036
+ route = () => "";
1037
+ get native() {
1038
+ return this;
1039
+ }
1040
+ };
1041
+
1042
+ // src/engine/MinimalContext.ts
1043
+ var MinimalRequest = class {
1044
+ constructor(_request, _params, _path, _routePattern) {
1045
+ this._request = _request;
1046
+ this._params = _params;
1047
+ this._path = _path;
1048
+ this._routePattern = _routePattern;
1049
+ }
1050
+ _searchParams = null;
1051
+ _cachedQueries = null;
1052
+ _cachedJsonPromise = null;
1053
+ _cachedTextPromise = null;
1054
+ _cachedFormDataPromise = null;
1055
+ get url() {
1056
+ return this._request.url;
1057
+ }
1058
+ get method() {
1059
+ return this._request.method;
1060
+ }
1061
+ get path() {
1062
+ return this._path;
1063
+ }
1064
+ get routePattern() {
1065
+ return this._routePattern;
1066
+ }
1067
+ param(name) {
1068
+ return this._params[name];
1069
+ }
1070
+ params() {
1071
+ return { ...this._params };
1072
+ }
1073
+ /**
1074
+ * Lazy-initialize searchParams, only parse once
1075
+ */
1076
+ getSearchParams() {
1077
+ if (this._searchParams === null) {
1078
+ const url = this._request.url;
1079
+ const queryStart = url.indexOf("?");
1080
+ if (queryStart === -1) {
1081
+ this._searchParams = new URLSearchParams();
1082
+ } else {
1083
+ const hashStart = url.indexOf("#", queryStart);
1084
+ const queryString = hashStart === -1 ? url.slice(queryStart + 1) : url.slice(queryStart + 1, hashStart);
1085
+ this._searchParams = new URLSearchParams(queryString);
1086
+ }
1087
+ }
1088
+ return this._searchParams;
1089
+ }
1090
+ query(name) {
1091
+ return this.getSearchParams().get(name) ?? void 0;
1092
+ }
1093
+ queries() {
1094
+ if (this._cachedQueries !== null) {
1095
+ return this._cachedQueries;
1096
+ }
1097
+ const params = this.getSearchParams();
1098
+ const result = {};
1099
+ for (const [key, value] of params.entries()) {
1100
+ const existing = result[key];
1101
+ if (existing === void 0) {
1102
+ result[key] = value;
1103
+ } else if (Array.isArray(existing)) {
1104
+ existing.push(value);
1105
+ } else {
1106
+ result[key] = [existing, value];
1107
+ }
1108
+ }
1109
+ this._cachedQueries = result;
1110
+ return result;
1111
+ }
1112
+ header(name) {
1113
+ return this._request.headers.get(name) ?? void 0;
1114
+ }
1115
+ headers() {
1116
+ const result = {};
1117
+ for (const [key, value] of this._request.headers.entries()) {
1118
+ result[key] = value;
1119
+ }
1120
+ return result;
1121
+ }
1122
+ async json() {
1123
+ if (this._cachedJsonPromise === null) {
1124
+ this._cachedJsonPromise = this._request.json();
1125
+ }
1126
+ return this._cachedJsonPromise;
1127
+ }
1128
+ async text() {
1129
+ if (this._cachedTextPromise === null) {
1130
+ this._cachedTextPromise = this._request.text();
1131
+ }
1132
+ return this._cachedTextPromise;
1133
+ }
1134
+ async formData() {
1135
+ if (this._cachedFormDataPromise === null) {
1136
+ this._cachedFormDataPromise = this._request.formData();
1137
+ }
1138
+ return this._cachedFormDataPromise;
1139
+ }
1140
+ get raw() {
1141
+ return this._request;
1142
+ }
1143
+ };
1144
+ var MinimalContext = class {
1145
+ req;
1146
+ _resHeaders = {};
1147
+ _requestScope;
1148
+ constructor(request, params, path, routePattern) {
1149
+ this.req = new MinimalRequest(request, params, path, routePattern);
1150
+ this._requestScope = new RequestScopeManager();
1151
+ }
1152
+ // get req(): FastRequest {
1153
+ // return this._req
1154
+ // }
1155
+ // Response helpers - merge custom headers with defaults
1156
+ // Optimized: use Object.assign instead of spread to avoid shallow copy overhead
1157
+ getHeaders(contentType) {
1158
+ const headers = Object.assign({ "Content-Type": contentType }, this._resHeaders);
1159
+ return headers;
1160
+ }
1161
+ json(data, status = 200) {
1162
+ return new Response(JSON.stringify(data), {
1163
+ status,
1164
+ headers: this.getHeaders("application/json; charset=utf-8")
1165
+ });
1166
+ }
1167
+ text(text, status = 200) {
1168
+ return new Response(text, {
1169
+ status,
1170
+ headers: this.getHeaders("text/plain; charset=utf-8")
1171
+ });
1172
+ }
1173
+ html(html, status = 200) {
1174
+ return new Response(html, {
1175
+ status,
1176
+ headers: this.getHeaders("text/html; charset=utf-8")
1177
+ });
1178
+ }
1179
+ redirect(url, status = 302) {
1180
+ return new Response(null, {
1181
+ status,
1182
+ headers: { ...this._resHeaders, Location: url }
1183
+ });
1184
+ }
1185
+ body(data, status = 200) {
1186
+ return new Response(data, {
1187
+ status,
1188
+ headers: this._resHeaders
1189
+ });
1190
+ }
1191
+ header(name, value) {
1192
+ if (value !== void 0) {
1193
+ this._resHeaders[name] = value;
1194
+ return;
1195
+ }
1196
+ return this.req.header(name);
1197
+ }
1198
+ status(_code) {
1199
+ }
1200
+ stream(stream, status = 200) {
1201
+ return new Response(stream, {
1202
+ status,
1203
+ headers: this.getHeaders("application/octet-stream")
1204
+ });
1205
+ }
1206
+ notFound(message = "Not Found") {
1207
+ return this.text(message, 404);
1208
+ }
1209
+ forbidden(message = "Forbidden") {
1210
+ return this.text(message, 403);
1211
+ }
1212
+ unauthorized(message = "Unauthorized") {
1213
+ return this.text(message, 401);
1214
+ }
1215
+ badRequest(message = "Bad Request") {
1216
+ return this.text(message, 400);
1217
+ }
1218
+ async forward(target, _options = {}) {
1219
+ const url = new URL(this.req.url);
1220
+ const targetUrl = new URL(
1221
+ target.startsWith("http") ? target : `${url.protocol}//${target}${this.req.path}`
1222
+ );
1223
+ return fetch(targetUrl.toString(), {
1224
+ method: this.req.method,
1225
+ headers: this.req.raw.headers
1226
+ });
1227
+ }
1228
+ get(_key) {
1229
+ return void 0;
1230
+ }
1231
+ set(_key, _value) {
1232
+ }
1233
+ /**
1234
+ * Get the request-scoped service manager for this request.
1235
+ *
1236
+ * @returns The RequestScopeManager for this request.
1237
+ */
1238
+ requestScope() {
1239
+ return this._requestScope;
1240
+ }
1241
+ /**
1242
+ * Resolve a request-scoped service (convenience method).
1243
+ *
1244
+ * @template T - The service type.
1245
+ * @param key - The service key for caching.
1246
+ * @param factory - Factory function to create the service.
1247
+ * @returns The cached or newly created service instance.
1248
+ */
1249
+ scoped(key, factory) {
1250
+ return this._requestScope.resolve(key, factory);
1251
+ }
1252
+ route = () => "";
1253
+ get native() {
1254
+ return this;
1255
+ }
1256
+ // Required for interface compatibility
1257
+ init(_request, _params, _path) {
1258
+ throw new Error("MinimalContext does not support init. Create a new instance instead.");
1259
+ }
1260
+ // Required for interface compatibility
1261
+ reset() {
1262
+ }
1263
+ };
1264
+
1265
+ // src/engine/path.ts
1266
+ function extractPath(url) {
1267
+ const protocolEnd = url.indexOf("://");
1268
+ const searchStart = protocolEnd === -1 ? 0 : protocolEnd + 3;
1269
+ const pathStart = url.indexOf("/", searchStart);
1270
+ if (pathStart === -1) {
1271
+ return "/";
1272
+ }
1273
+ const queryStart = url.indexOf("?", pathStart);
1274
+ if (queryStart === -1) {
1275
+ return url.slice(pathStart);
1276
+ }
1277
+ return url.slice(pathStart, queryStart);
1278
+ }
1279
+
1280
+ // src/engine/pool.ts
1281
+ var ObjectPool = class {
1282
+ pool = [];
1283
+ factory;
1284
+ reset;
1285
+ maxSize;
1286
+ /**
1287
+ * Create a new object pool
1288
+ *
1289
+ * @param factory - Function to create new objects
1290
+ * @param reset - Function to reset objects before reuse
1291
+ * @param maxSize - Maximum pool size (default: 256)
1292
+ */
1293
+ constructor(factory, reset, maxSize = 256) {
1294
+ this.factory = factory;
1295
+ this.reset = reset;
1296
+ this.maxSize = maxSize;
1297
+ }
1298
+ /**
1299
+ * Acquire an object from the pool
1300
+ *
1301
+ * If the pool is empty, creates a new object (overflow strategy).
1302
+ * This ensures the pool never blocks under high load.
1303
+ *
1304
+ * @returns Object from pool or newly created
1305
+ */
1306
+ acquire() {
1307
+ const obj = this.pool.pop();
1308
+ if (obj !== void 0) {
1309
+ return obj;
1310
+ }
1311
+ return this.factory();
1312
+ }
1313
+ /**
1314
+ * Release an object back to the pool
1315
+ *
1316
+ * If the pool is full, the object is discarded (will be GC'd).
1317
+ * This prevents unbounded memory growth.
1318
+ *
1319
+ * @param obj - Object to release
1320
+ */
1321
+ release(obj) {
1322
+ if (this.pool.length < this.maxSize) {
1323
+ this.reset(obj);
1324
+ this.pool.push(obj);
1325
+ }
1326
+ }
1327
+ /**
1328
+ * Clear all objects from the pool
1329
+ *
1330
+ * Useful for testing or when you need to force a clean slate.
1331
+ */
1332
+ clear() {
1333
+ this.pool = [];
1334
+ }
1335
+ /**
1336
+ * Get current pool size
1337
+ */
1338
+ get size() {
1339
+ return this.pool.length;
1340
+ }
1341
+ /**
1342
+ * Get maximum pool size
1343
+ */
1344
+ get capacity() {
1345
+ return this.maxSize;
1346
+ }
1347
+ /**
1348
+ * Pre-warm the pool by creating objects in advance
1349
+ *
1350
+ * This can reduce latency for the first N requests.
1351
+ *
1352
+ * @param count - Number of objects to pre-create
1353
+ */
1354
+ prewarm(count) {
1355
+ const targetSize = Math.min(count, this.maxSize);
1356
+ while (this.pool.length < targetSize) {
1357
+ const obj = this.factory();
1358
+ this.reset(obj);
1359
+ this.pool.push(obj);
1360
+ }
1361
+ }
1362
+ };
1363
+
1364
+ // src/engine/Gravito.ts
1365
+ function compileMiddlewareChain(middleware, handler) {
1366
+ if (middleware.length === 0) {
1367
+ return handler;
1368
+ }
1369
+ if (middleware.length === 1) {
1370
+ const mw = middleware[0];
1371
+ return async (ctx) => {
1372
+ let nextCalled = false;
1373
+ const result = await mw(ctx, async () => {
1374
+ nextCalled = true;
1375
+ return void 0;
1376
+ });
1377
+ if (result instanceof Response) {
1378
+ return result;
1379
+ }
1380
+ if (nextCalled) {
1381
+ return await handler(ctx);
1382
+ }
1383
+ return ctx.json({ error: "Middleware did not call next or return response" }, 500);
1384
+ };
1385
+ }
1386
+ let compiled = handler;
1387
+ for (let i = middleware.length - 1; i >= 0; i--) {
1388
+ const mw = middleware[i];
1389
+ const nextHandler = compiled;
1390
+ compiled = async (ctx) => {
1391
+ let nextCalled = false;
1392
+ const result = await mw(ctx, async () => {
1393
+ nextCalled = true;
1394
+ return void 0;
1395
+ });
1396
+ if (result instanceof Response) {
1397
+ return result;
1398
+ }
1399
+ if (nextCalled) {
1400
+ return await nextHandler(ctx);
1401
+ }
1402
+ return ctx.json({ error: "Middleware did not call next or return response" }, 500);
1403
+ };
1404
+ }
1405
+ return compiled;
1406
+ }
1407
+ var Gravito = class {
1408
+ router = new AOTRouter();
1409
+ contextPool;
1410
+ errorHandler;
1411
+ notFoundHandler;
1412
+ // Direct reference to static routes Map (O(1) access)
1413
+ /** @internal */
1414
+ staticRoutes;
1415
+ // Flag: pure static app (no middleware at all) allows ultra-fast path
1416
+ isPureStaticApp = true;
1417
+ // Cache for precompiled dynamic routes
1418
+ compiledDynamicRoutes = /* @__PURE__ */ new Map();
1419
+ /**
1420
+ * Create a new Gravito instance
1421
+ *
1422
+ * @param options - Engine configuration options
1423
+ */
1424
+ constructor(options = {}) {
1425
+ const poolSize = options.poolSize ?? 256;
1426
+ this.contextPool = new ObjectPool(
1427
+ () => new FastContext(),
1428
+ (ctx) => ctx.reset(),
1429
+ poolSize
1430
+ );
1431
+ this.contextPool.prewarm(Math.min(32, poolSize));
1432
+ if (options.onError) {
1433
+ this.errorHandler = options.onError;
1434
+ }
1435
+ if (options.onNotFound) {
1436
+ this.notFoundHandler = options.onNotFound;
1437
+ }
1438
+ this.compileRoutes();
1439
+ }
1440
+ // ─────────────────────────────────────────────────────────────────────────
1441
+ // HTTP Method Registration
1442
+ // ─────────────────────────────────────────────────────────────────────────
1443
+ /**
1444
+ * Register a GET route
1445
+ *
1446
+ * @param path - Route path (e.g., '/users/:id')
1447
+ * @param handlers - Handler and optional middleware
1448
+ * @returns This instance for chaining
1449
+ */
1450
+ get(path, ...handlers) {
1451
+ return this.addRoute("get", path, handlers);
1452
+ }
1453
+ /**
1454
+ * Register a POST route
1455
+ */
1456
+ post(path, ...handlers) {
1457
+ return this.addRoute("post", path, handlers);
1458
+ }
1459
+ /**
1460
+ * Register a PUT route
1461
+ */
1462
+ put(path, ...handlers) {
1463
+ return this.addRoute("put", path, handlers);
1464
+ }
1465
+ /**
1466
+ * Register a DELETE route
1467
+ */
1468
+ delete(path, ...handlers) {
1469
+ return this.addRoute("delete", path, handlers);
1470
+ }
1471
+ /**
1472
+ * Register a PDF route
1473
+ */
1474
+ patch(path, ...handlers) {
1475
+ return this.addRoute("patch", path, handlers);
1476
+ }
1477
+ /**
1478
+ * Register an OPTIONS route
1479
+ */
1480
+ options(path, ...handlers) {
1481
+ return this.addRoute("options", path, handlers);
1482
+ }
1483
+ /**
1484
+ * Register a HEAD route
1485
+ */
1486
+ head(path, ...handlers) {
1487
+ return this.addRoute("head", path, handlers);
1488
+ }
1489
+ /**
1490
+ * Register a route for all HTTP methods
1491
+ */
1492
+ all(path, ...handlers) {
1493
+ const methods = ["get", "post", "put", "delete", "patch", "options", "head"];
1494
+ for (const method of methods) {
1495
+ this.addRoute(method, path, handlers);
1496
+ }
1497
+ return this;
1498
+ }
1499
+ use(pathOrMiddleware, ...middleware) {
1500
+ this.isPureStaticApp = false;
1501
+ if (typeof pathOrMiddleware === "string") {
1502
+ this.router.usePattern(pathOrMiddleware, ...middleware);
1503
+ } else {
1504
+ this.router.use(pathOrMiddleware, ...middleware);
1505
+ }
1506
+ this.compileRoutes();
1507
+ return this;
1508
+ }
1509
+ // ─────────────────────────────────────────────────────────────────────────
1510
+ // Route Grouping
1511
+ // ─────────────────────────────────────────────────────────────────────────
1512
+ /**
1513
+ * Mount a sub-application at a path prefix
1514
+ */
1515
+ route(path, app) {
1516
+ this.router.mount(path, app.router);
1517
+ this.compileRoutes();
1518
+ return this;
1519
+ }
1520
+ // ─────────────────────────────────────────────────────────────────────────
1521
+ // Error Handling
1522
+ // ─────────────────────────────────────────────────────────────────────────
1523
+ /**
1524
+ * Set custom error handler
1525
+ */
1526
+ onError(handler) {
1527
+ this.errorHandler = handler;
1528
+ return this;
1529
+ }
1530
+ /**
1531
+ * Set custom 404 handler
1532
+ */
1533
+ notFound(handler) {
1534
+ this.notFoundHandler = handler;
1535
+ return this;
1536
+ }
1537
+ // ─────────────────────────────────────────────────────────────────────────
1538
+ // Request Handling (Bun.serve integration)
1539
+ // ─────────────────────────────────────────────────────────────────────────
1540
+ /**
1541
+ * Predictive Route Warming (JIT Optimization)
1542
+ *
1543
+ * Simulates requests to specified routes to trigger JIT compilation (FTL)
1544
+ * before real traffic arrives.
1545
+ *
1546
+ * @param paths List of paths to warm up (e.g. ['/api/users', '/health'])
1547
+ */
1548
+ async warmup(paths) {
1549
+ const dummyReqOpts = { headers: { "User-Agent": "Gravito-Warmup/1.0" } };
1550
+ for (const path of paths) {
1551
+ const req = new Request(`http://localhost${path}`, dummyReqOpts);
1552
+ await this.fetch(req);
1553
+ }
1554
+ }
1555
+ /**
1556
+ * Handle an incoming request
1557
+ */
1558
+ fetch = async (request) => {
1559
+ const path = extractPath(request.url);
1560
+ const method = request.method.toLowerCase();
1561
+ const staticKey = `${method}:${path}`;
1562
+ const staticRoute = this.staticRoutes.get(staticKey);
1563
+ if (staticRoute) {
1564
+ if (staticRoute.useMinimal) {
1565
+ const ctx = new MinimalContext(request, {}, path, path);
1566
+ try {
1567
+ const result = staticRoute.handler(ctx);
1568
+ if (result instanceof Response) {
1569
+ return result;
1570
+ }
1571
+ return await result;
1572
+ } catch (error) {
1573
+ return this.handleErrorSync(error, request, path);
1574
+ }
1575
+ }
1576
+ return await this.handleWithMiddleware(request, path, staticRoute);
1577
+ }
1578
+ return await this.handleDynamicRoute(request, method, path);
1579
+ };
1580
+ /**
1581
+ * Handle routes with middleware (async path)
1582
+ */
1583
+ async handleWithMiddleware(request, path, route) {
1584
+ const ctx = this.contextPool.acquire();
1585
+ try {
1586
+ ctx.init(request, {}, path, path);
1587
+ if (route.compiled) {
1588
+ return await route.compiled(ctx);
1589
+ }
1590
+ const middleware = this.collectMiddlewareForPath(path, route.middleware);
1591
+ if (middleware.length === 0) {
1592
+ return await route.handler(ctx);
1593
+ }
1594
+ return await this.executeMiddleware(ctx, middleware, route.handler);
1595
+ } catch (error) {
1596
+ return await this.handleError(error, ctx);
1597
+ } finally {
1598
+ try {
1599
+ await ctx.requestScope().cleanup();
1600
+ } catch (cleanupError) {
1601
+ console.error("RequestScope cleanup failed:", cleanupError);
1602
+ }
1603
+ this.contextPool.release(ctx);
1604
+ }
1605
+ }
1606
+ /**
1607
+ * Handle dynamic routes (Radix Tree lookup)
1608
+ */
1609
+ handleDynamicRoute(request, method, path) {
1610
+ const match = this.router.match(method.toUpperCase(), path);
1611
+ if (!match.handler) {
1612
+ return this.handleNotFoundSync(request, path);
1613
+ }
1614
+ const cacheKey = `${method}:${match.routePattern ?? path}`;
1615
+ let entry = this.compiledDynamicRoutes.get(cacheKey);
1616
+ if (!entry || entry.version !== this.router.version) {
1617
+ const compiled = compileMiddlewareChain(match.middleware, match.handler);
1618
+ if (this.compiledDynamicRoutes.size > 1e3) {
1619
+ this.compiledDynamicRoutes.clear();
1620
+ }
1621
+ entry = { compiled, version: this.router.version };
1622
+ this.compiledDynamicRoutes.set(cacheKey, entry);
1623
+ }
1624
+ const ctx = this.contextPool.acquire();
1625
+ const execute = async () => {
1626
+ try {
1627
+ ctx.init(request, match.params, path, match.routePattern);
1628
+ return await entry?.compiled(ctx);
1629
+ } catch (error) {
1630
+ return await this.handleError(error, ctx);
1631
+ } finally {
1632
+ try {
1633
+ await ctx.requestScope().cleanup();
1634
+ } catch (cleanupError) {
1635
+ console.error("RequestScope cleanup failed:", cleanupError);
1636
+ }
1637
+ this.contextPool.release(ctx);
1638
+ }
1639
+ };
1640
+ return execute();
1641
+ }
1642
+ /**
1643
+ * Sync error handler (for ultra-fast path)
1644
+ */
1645
+ handleErrorSync(error, request, path) {
1646
+ if (this.errorHandler) {
1647
+ const ctx = new MinimalContext(request, {}, path);
1648
+ const result = this.errorHandler(error, ctx);
1649
+ if (result instanceof Response) {
1650
+ return result;
1651
+ }
1652
+ return result;
1653
+ }
1654
+ console.error("Unhandled error:", error);
1655
+ return new Response(CACHED_RESPONSES.INTERNAL_ERROR, {
1656
+ status: 500,
1657
+ headers: HEADERS.JSON
1658
+ });
1659
+ }
1660
+ /**
1661
+ * Sync 404 handler (for ultra-fast path)
1662
+ */
1663
+ handleNotFoundSync(request, path) {
1664
+ if (this.notFoundHandler) {
1665
+ const ctx = new MinimalContext(request, {}, path);
1666
+ const result = this.notFoundHandler(ctx);
1667
+ if (result instanceof Response) {
1668
+ return result;
1669
+ }
1670
+ return result;
1671
+ }
1672
+ return new Response(CACHED_RESPONSES.NOT_FOUND, {
1673
+ status: 404,
1674
+ headers: HEADERS.JSON
1675
+ });
1676
+ }
1677
+ /**
1678
+ * Collect middleware for a specific path
1679
+ */
1680
+ collectMiddlewareForPath(path, routeMiddleware) {
1681
+ if (this.router.globalMiddleware.length === 0 && this.router.pathMiddleware.size === 0) {
1682
+ return routeMiddleware;
1683
+ }
1684
+ return this.router.collectMiddlewarePublic(path, routeMiddleware);
1685
+ }
1686
+ /**
1687
+ * Compile routes for optimization
1688
+ */
1689
+ compileRoutes() {
1690
+ this.staticRoutes = this.router.staticRoutes;
1691
+ const hasGlobalMiddleware = this.router.globalMiddleware.length > 0;
1692
+ const hasPathMiddleware = this.router.pathMiddleware.size > 0;
1693
+ this.isPureStaticApp = !hasGlobalMiddleware && !hasPathMiddleware;
1694
+ for (const [key, route] of this.staticRoutes) {
1695
+ if (route.compiledVersion === this.router.version) {
1696
+ continue;
1697
+ }
1698
+ const analysis = analyzeHandler(route.handler);
1699
+ const optimalType = getOptimalContextType(analysis);
1700
+ route.useMinimal = this.isPureStaticApp && route.middleware.length === 0 && optimalType === "minimal";
1701
+ if (!route.useMinimal) {
1702
+ const allMiddleware = this.collectMiddlewareForPath(key.split(":")[1], route.middleware);
1703
+ route.compiled = compileMiddlewareChain(allMiddleware, route.handler);
1704
+ }
1705
+ route.compiledVersion = this.router.version;
1706
+ }
1707
+ }
1708
+ /**
1709
+ * Add a route to the router
1710
+ */
1711
+ addRoute(method, path, handlers) {
1712
+ if (handlers.length === 0) {
1713
+ throw new Error(`No handler provided for ${method.toUpperCase()} ${path}`);
1714
+ }
1715
+ const handler = handlers[handlers.length - 1];
1716
+ const middleware = handlers.slice(0, -1);
1717
+ this.router.add(method, path, handler, middleware);
1718
+ this.compileRoutes();
1719
+ return this;
1720
+ }
1721
+ /**
1722
+ * Execute middleware chain followed by handler
1723
+ */
1724
+ async executeMiddleware(ctx, middleware, handler) {
1725
+ let index = 0;
1726
+ const next = async () => {
1727
+ if (index < middleware.length) {
1728
+ const mw = middleware[index++];
1729
+ return await mw(ctx, next);
1730
+ }
1731
+ return void 0;
1732
+ };
1733
+ const result = await next();
1734
+ if (result instanceof Response) {
1735
+ return result;
1736
+ }
1737
+ return await handler(ctx);
1738
+ }
1739
+ /**
1740
+ * Handle errors (Async version for dynamic/middleware paths)
1741
+ */
1742
+ async handleError(error, ctx) {
1743
+ if (this.errorHandler) {
1744
+ return await this.errorHandler(error, ctx);
1745
+ }
1746
+ console.error("Unhandled error:", error);
1747
+ return ctx.json(
1748
+ {
1749
+ error: "Internal Server Error",
1750
+ message: error.message
1751
+ },
1752
+ 500
1753
+ );
1754
+ }
1755
+ };
1756
+ // Annotate the CommonJS export names for ESM import in node:
1757
+ 0 && (module.exports = {
1758
+ AOTRouter,
1759
+ FastContextImpl,
1760
+ Gravito,
1761
+ MinimalContext,
1762
+ ObjectPool,
1763
+ extractPath
1764
+ });