@gravito/core 1.0.0-beta.6 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1173 @@
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
+ staticRoutes = /* @__PURE__ */ new Map();
243
+ // Dynamic route handler (Radix Tree)
244
+ dynamicRouter = new RadixRouter();
245
+ // Global middleware (applies to all routes)
246
+ globalMiddleware = [];
247
+ // Path-based middleware: pattern -> middleware[]
248
+ pathMiddleware = /* @__PURE__ */ new Map();
249
+ /**
250
+ * Register a route
251
+ *
252
+ * Automatically determines if route is static or dynamic.
253
+ * Static routes are stored in a Map for O(1) lookup.
254
+ * Dynamic routes use the Radix Tree.
255
+ *
256
+ * @param method - HTTP method
257
+ * @param path - Route path
258
+ * @param handler - Route handler
259
+ * @param middleware - Route-specific middleware
260
+ */
261
+ add(method, path, handler, middleware = []) {
262
+ const normalizedMethod = method.toLowerCase();
263
+ if (this.isStaticPath(path)) {
264
+ const key = `${normalizedMethod}:${path}`;
265
+ this.staticRoutes.set(key, { handler, middleware });
266
+ } else {
267
+ const wrappedHandler = handler;
268
+ this.dynamicRouter.add(normalizedMethod, path, [wrappedHandler]);
269
+ if (middleware.length > 0) {
270
+ this.pathMiddleware.set(`${normalizedMethod}:${path}`, middleware);
271
+ }
272
+ }
273
+ }
274
+ /**
275
+ * Add global middleware
276
+ *
277
+ * These run for every request, before route-specific middleware.
278
+ *
279
+ * @param middleware - Middleware functions
280
+ */
281
+ use(...middleware) {
282
+ this.globalMiddleware.push(...middleware);
283
+ }
284
+ /**
285
+ * Add path-based middleware
286
+ *
287
+ * Supports wildcard patterns like '/api/*'
288
+ *
289
+ * @param pattern - Path pattern
290
+ * @param middleware - Middleware functions
291
+ */
292
+ usePattern(pattern, ...middleware) {
293
+ const existing = this.pathMiddleware.get(pattern) ?? [];
294
+ this.pathMiddleware.set(pattern, [...existing, ...middleware]);
295
+ }
296
+ /**
297
+ * Match a request to a route
298
+ *
299
+ * Returns the handler, params, and all applicable middleware.
300
+ *
301
+ * @param method - HTTP method
302
+ * @param path - Request path
303
+ * @returns Route match or null if not found
304
+ */
305
+ match(method, path) {
306
+ const normalizedMethod = method.toLowerCase();
307
+ const staticKey = `${normalizedMethod}:${path}`;
308
+ const staticRoute = this.staticRoutes.get(staticKey);
309
+ if (staticRoute) {
310
+ return {
311
+ handler: staticRoute.handler,
312
+ params: {},
313
+ middleware: this.collectMiddleware(path, staticRoute.middleware)
314
+ };
315
+ }
316
+ const match = this.dynamicRouter.match(normalizedMethod, path);
317
+ if (match && match.handlers.length > 0) {
318
+ const handler = match.handlers[0];
319
+ const routeKey = this.findDynamicRouteKey(normalizedMethod, path);
320
+ const routeMiddleware = routeKey ? this.pathMiddleware.get(routeKey) ?? [] : [];
321
+ return {
322
+ handler,
323
+ params: match.params,
324
+ middleware: this.collectMiddleware(path, routeMiddleware)
325
+ };
326
+ }
327
+ return {
328
+ handler: null,
329
+ params: {},
330
+ middleware: []
331
+ };
332
+ }
333
+ /**
334
+ * Public wrapper for collectMiddleware (used by Gravito for optimization)
335
+ */
336
+ collectMiddlewarePublic(path, routeMiddleware) {
337
+ return this.collectMiddleware(path, routeMiddleware);
338
+ }
339
+ /**
340
+ * Collect all applicable middleware for a path
341
+ *
342
+ * Order: global -> pattern-based -> route-specific
343
+ *
344
+ * @param path - Request path
345
+ * @param routeMiddleware - Route-specific middleware
346
+ * @returns Combined middleware array
347
+ */
348
+ collectMiddleware(path, routeMiddleware) {
349
+ if (this.globalMiddleware.length === 0 && this.pathMiddleware.size === 0 && routeMiddleware.length === 0) {
350
+ return [];
351
+ }
352
+ const middleware = [];
353
+ if (this.globalMiddleware.length > 0) {
354
+ middleware.push(...this.globalMiddleware);
355
+ }
356
+ if (this.pathMiddleware.size > 0) {
357
+ for (const [pattern, mw] of this.pathMiddleware) {
358
+ if (pattern.includes(":")) continue;
359
+ if (this.matchPattern(pattern, path)) {
360
+ middleware.push(...mw);
361
+ }
362
+ }
363
+ }
364
+ if (routeMiddleware.length > 0) {
365
+ middleware.push(...routeMiddleware);
366
+ }
367
+ return middleware;
368
+ }
369
+ /**
370
+ * Check if a path is static (no parameters or wildcards)
371
+ */
372
+ isStaticPath(path) {
373
+ return !path.includes(":") && !path.includes("*");
374
+ }
375
+ /**
376
+ * Match a pattern against a path
377
+ *
378
+ * Supports:
379
+ * - Exact match: '/api/users'
380
+ * - Wildcard suffix: '/api/*'
381
+ *
382
+ * @param pattern - Pattern to match
383
+ * @param path - Path to test
384
+ * @returns True if pattern matches
385
+ */
386
+ matchPattern(pattern, path) {
387
+ if (pattern === "*") return true;
388
+ if (pattern === path) return true;
389
+ if (pattern.endsWith("/*")) {
390
+ const prefix = pattern.slice(0, -2);
391
+ return path.startsWith(prefix);
392
+ }
393
+ return false;
394
+ }
395
+ /**
396
+ * Find the original route key for a matched dynamic route
397
+ *
398
+ * This is needed to look up route-specific middleware.
399
+ * It's a bit of a hack, but avoids storing duplicate data.
400
+ *
401
+ * @param method - HTTP method
402
+ * @param path - Matched path
403
+ * @returns Route key or null
404
+ */
405
+ findDynamicRouteKey(method, path) {
406
+ for (const key of this.pathMiddleware.keys()) {
407
+ if (key.startsWith(`${method}:`)) {
408
+ return key;
409
+ }
410
+ }
411
+ return null;
412
+ }
413
+ /**
414
+ * Get all registered routes (for debugging)
415
+ */
416
+ getRoutes() {
417
+ const routes = [];
418
+ for (const key of this.staticRoutes.keys()) {
419
+ const [method, path] = key.split(":");
420
+ routes.push({ method, path, type: "static" });
421
+ }
422
+ return routes;
423
+ }
424
+ };
425
+
426
+ // src/engine/analyzer.ts
427
+ function analyzeHandler(handler) {
428
+ const source = handler.toString();
429
+ return {
430
+ usesHeaders: source.includes(".header(") || source.includes(".header)") || source.includes(".headers(") || source.includes(".headers)"),
431
+ usesQuery: source.includes(".query(") || source.includes(".query)") || source.includes(".queries(") || source.includes(".queries)"),
432
+ usesBody: source.includes(".json()") || source.includes(".text()") || source.includes(".formData()") || source.includes(".body"),
433
+ usesParams: source.includes(".param(") || source.includes(".param)") || source.includes(".params(") || source.includes(".params)"),
434
+ isAsync: source.includes("async") || source.includes("await")
435
+ };
436
+ }
437
+ function getOptimalContextType(analysis) {
438
+ if (analysis.usesHeaders) {
439
+ return "fast";
440
+ }
441
+ if (!analysis.usesQuery && !analysis.usesBody && !analysis.usesParams) {
442
+ return "minimal";
443
+ }
444
+ if (!analysis.usesQuery && !analysis.usesBody && analysis.usesParams) {
445
+ return "minimal";
446
+ }
447
+ if (analysis.usesBody) {
448
+ return "full";
449
+ }
450
+ return "fast";
451
+ }
452
+
453
+ // src/engine/FastContext.ts
454
+ var FastRequestImpl = class {
455
+ _request;
456
+ _params;
457
+ _url = new URL("http://localhost");
458
+ // Reuse this object
459
+ _query = null;
460
+ _headers = null;
461
+ /**
462
+ * Reset for pooling
463
+ */
464
+ reset(request, params = {}) {
465
+ this._request = request;
466
+ this._params = params;
467
+ this._url.href = request.url;
468
+ this._query = null;
469
+ this._headers = null;
470
+ }
471
+ get url() {
472
+ return this._request.url;
473
+ }
474
+ get method() {
475
+ return this._request.method;
476
+ }
477
+ get path() {
478
+ return this._url.pathname;
479
+ }
480
+ param(name) {
481
+ return this._params[name];
482
+ }
483
+ params() {
484
+ return { ...this._params };
485
+ }
486
+ query(name) {
487
+ if (!this._query) {
488
+ this._query = this._url.searchParams;
489
+ }
490
+ return this._query.get(name) ?? void 0;
491
+ }
492
+ queries() {
493
+ if (!this._query) {
494
+ this._query = this._url.searchParams;
495
+ }
496
+ const result = {};
497
+ for (const [key, value] of this._query.entries()) {
498
+ const existing = result[key];
499
+ if (existing === void 0) {
500
+ result[key] = value;
501
+ } else if (Array.isArray(existing)) {
502
+ existing.push(value);
503
+ } else {
504
+ result[key] = [existing, value];
505
+ }
506
+ }
507
+ return result;
508
+ }
509
+ header(name) {
510
+ return this._request.headers.get(name) ?? void 0;
511
+ }
512
+ headers() {
513
+ if (!this._headers) {
514
+ this._headers = {};
515
+ for (const [key, value] of this._request.headers.entries()) {
516
+ this._headers[key] = value;
517
+ }
518
+ }
519
+ return { ...this._headers };
520
+ }
521
+ async json() {
522
+ return this._request.json();
523
+ }
524
+ async text() {
525
+ return this._request.text();
526
+ }
527
+ async formData() {
528
+ return this._request.formData();
529
+ }
530
+ get raw() {
531
+ return this._request;
532
+ }
533
+ };
534
+ var FastContext = class {
535
+ _req = new FastRequestImpl();
536
+ _statusCode = 200;
537
+ _headers = new Headers();
538
+ // Reuse this object
539
+ /**
540
+ * Reset context for pooling
541
+ *
542
+ * This is called when acquiring from the pool.
543
+ * Must clear all state from previous request.
544
+ */
545
+ reset(request, params = {}) {
546
+ this._req.reset(request, params);
547
+ this._statusCode = 200;
548
+ this._headers = new Headers();
549
+ return this;
550
+ }
551
+ get req() {
552
+ return this._req;
553
+ }
554
+ // ─────────────────────────────────────────────────────────────────────────
555
+ // Response Helpers
556
+ // ─────────────────────────────────────────────────────────────────────────
557
+ json(data, status = 200) {
558
+ this._headers.set("Content-Type", "application/json; charset=utf-8");
559
+ return new Response(JSON.stringify(data), {
560
+ status,
561
+ headers: this._headers
562
+ });
563
+ }
564
+ text(text, status = 200) {
565
+ this._headers.set("Content-Type", "text/plain; charset=utf-8");
566
+ return new Response(text, {
567
+ status,
568
+ headers: this._headers
569
+ });
570
+ }
571
+ html(html, status = 200) {
572
+ this._headers.set("Content-Type", "text/html; charset=utf-8");
573
+ return new Response(html, {
574
+ status,
575
+ headers: this._headers
576
+ });
577
+ }
578
+ redirect(url, status = 302) {
579
+ this._headers.set("Location", url);
580
+ return new Response(null, {
581
+ status,
582
+ headers: this._headers
583
+ });
584
+ }
585
+ body(data, status = 200) {
586
+ return new Response(data, {
587
+ status,
588
+ headers: this._headers
589
+ });
590
+ }
591
+ // ─────────────────────────────────────────────────────────────────────────
592
+ // Header Management
593
+ // ─────────────────────────────────────────────────────────────────────────
594
+ header(name, value) {
595
+ this._headers.set(name, value);
596
+ }
597
+ status(code) {
598
+ this._statusCode = code;
599
+ }
600
+ };
601
+
602
+ // src/engine/MinimalContext.ts
603
+ var MinimalRequest = class {
604
+ constructor(_request, _params, _path) {
605
+ this._request = _request;
606
+ this._params = _params;
607
+ this._path = _path;
608
+ }
609
+ get url() {
610
+ return this._request.url;
611
+ }
612
+ get method() {
613
+ return this._request.method;
614
+ }
615
+ get path() {
616
+ return this._path;
617
+ }
618
+ param(name) {
619
+ return this._params[name];
620
+ }
621
+ params() {
622
+ return { ...this._params };
623
+ }
624
+ query(name) {
625
+ const url = new URL(this._request.url);
626
+ return url.searchParams.get(name) ?? void 0;
627
+ }
628
+ queries() {
629
+ const url = new URL(this._request.url);
630
+ const result = {};
631
+ for (const [key, value] of url.searchParams.entries()) {
632
+ const existing = result[key];
633
+ if (existing === void 0) {
634
+ result[key] = value;
635
+ } else if (Array.isArray(existing)) {
636
+ existing.push(value);
637
+ } else {
638
+ result[key] = [existing, value];
639
+ }
640
+ }
641
+ return result;
642
+ }
643
+ header(name) {
644
+ return this._request.headers.get(name) ?? void 0;
645
+ }
646
+ headers() {
647
+ const result = {};
648
+ for (const [key, value] of this._request.headers.entries()) {
649
+ result[key] = value;
650
+ }
651
+ return result;
652
+ }
653
+ async json() {
654
+ return this._request.json();
655
+ }
656
+ async text() {
657
+ return this._request.text();
658
+ }
659
+ async formData() {
660
+ return this._request.formData();
661
+ }
662
+ get raw() {
663
+ return this._request;
664
+ }
665
+ };
666
+ var MinimalContext = class {
667
+ _req;
668
+ constructor(request, params, path) {
669
+ this._req = new MinimalRequest(request, params, path);
670
+ }
671
+ get req() {
672
+ return this._req;
673
+ }
674
+ // Response helpers - create headers inline (no reuse overhead)
675
+ json(data, status = 200) {
676
+ return new Response(JSON.stringify(data), {
677
+ status,
678
+ headers: { "Content-Type": "application/json; charset=utf-8" }
679
+ });
680
+ }
681
+ text(text, status = 200) {
682
+ return new Response(text, {
683
+ status,
684
+ headers: { "Content-Type": "text/plain; charset=utf-8" }
685
+ });
686
+ }
687
+ html(html, status = 200) {
688
+ return new Response(html, {
689
+ status,
690
+ headers: { "Content-Type": "text/html; charset=utf-8" }
691
+ });
692
+ }
693
+ redirect(url, status = 302) {
694
+ return new Response(null, {
695
+ status,
696
+ headers: { Location: url }
697
+ });
698
+ }
699
+ body(data, status = 200) {
700
+ return new Response(data, { status });
701
+ }
702
+ header(_name, _value) {
703
+ console.warn("MinimalContext.header() is a no-op. Use FastContext for custom headers.");
704
+ }
705
+ status(_code) {
706
+ }
707
+ // Required for interface compatibility
708
+ reset(_request, _params) {
709
+ throw new Error("MinimalContext does not support reset. Create a new instance instead.");
710
+ }
711
+ };
712
+
713
+ // src/engine/path.ts
714
+ function extractPath(url) {
715
+ const protocolEnd = url.indexOf("://");
716
+ const searchStart = protocolEnd === -1 ? 0 : protocolEnd + 3;
717
+ const pathStart = url.indexOf("/", searchStart);
718
+ if (pathStart === -1) {
719
+ return "/";
720
+ }
721
+ const queryStart = url.indexOf("?", pathStart);
722
+ if (queryStart === -1) {
723
+ return url.slice(pathStart);
724
+ }
725
+ return url.slice(pathStart, queryStart);
726
+ }
727
+
728
+ // src/engine/pool.ts
729
+ var ObjectPool = class {
730
+ pool = [];
731
+ factory;
732
+ reset;
733
+ maxSize;
734
+ /**
735
+ * Create a new object pool
736
+ *
737
+ * @param factory - Function to create new objects
738
+ * @param reset - Function to reset objects before reuse
739
+ * @param maxSize - Maximum pool size (default: 256)
740
+ */
741
+ constructor(factory, reset, maxSize = 256) {
742
+ this.factory = factory;
743
+ this.reset = reset;
744
+ this.maxSize = maxSize;
745
+ }
746
+ /**
747
+ * Acquire an object from the pool
748
+ *
749
+ * If the pool is empty, creates a new object (overflow strategy).
750
+ * This ensures the pool never blocks under high load.
751
+ *
752
+ * @returns Object from pool or newly created
753
+ */
754
+ acquire() {
755
+ const obj = this.pool.pop();
756
+ if (obj !== void 0) {
757
+ return obj;
758
+ }
759
+ return this.factory();
760
+ }
761
+ /**
762
+ * Release an object back to the pool
763
+ *
764
+ * If the pool is full, the object is discarded (will be GC'd).
765
+ * This prevents unbounded memory growth.
766
+ *
767
+ * @param obj - Object to release
768
+ */
769
+ release(obj) {
770
+ if (this.pool.length < this.maxSize) {
771
+ this.reset(obj);
772
+ this.pool.push(obj);
773
+ }
774
+ }
775
+ /**
776
+ * Clear all objects from the pool
777
+ *
778
+ * Useful for testing or when you need to force a clean slate.
779
+ */
780
+ clear() {
781
+ this.pool = [];
782
+ }
783
+ /**
784
+ * Get current pool size
785
+ */
786
+ get size() {
787
+ return this.pool.length;
788
+ }
789
+ /**
790
+ * Get maximum pool size
791
+ */
792
+ get capacity() {
793
+ return this.maxSize;
794
+ }
795
+ /**
796
+ * Pre-warm the pool by creating objects in advance
797
+ *
798
+ * This can reduce latency for the first N requests.
799
+ *
800
+ * @param count - Number of objects to pre-create
801
+ */
802
+ prewarm(count) {
803
+ const targetSize = Math.min(count, this.maxSize);
804
+ while (this.pool.length < targetSize) {
805
+ const obj = this.factory();
806
+ this.reset(obj);
807
+ this.pool.push(obj);
808
+ }
809
+ }
810
+ };
811
+
812
+ // src/engine/Gravito.ts
813
+ var Gravito = class {
814
+ router = new AOTRouter();
815
+ contextPool;
816
+ errorHandler;
817
+ notFoundHandler;
818
+ // Direct reference to static routes Map (O(1) access)
819
+ // Optimization: Bypass getter/setter overhead
820
+ staticRoutes;
821
+ // Flag: pure static app (no middleware at all) allows ultra-fast path
822
+ isPureStaticApp = true;
823
+ /**
824
+ * Create a new Gravito instance
825
+ *
826
+ * @param options - Engine configuration options
827
+ */
828
+ constructor(options = {}) {
829
+ const poolSize = options.poolSize ?? 256;
830
+ this.contextPool = new ObjectPool(
831
+ () => new FastContext(),
832
+ (ctx) => ctx.reset(new Request("http://localhost")),
833
+ poolSize
834
+ );
835
+ this.contextPool.prewarm(Math.min(32, poolSize));
836
+ if (options.onError) {
837
+ this.errorHandler = options.onError;
838
+ }
839
+ if (options.onNotFound) {
840
+ this.notFoundHandler = options.onNotFound;
841
+ }
842
+ this.compileRoutes();
843
+ }
844
+ // ─────────────────────────────────────────────────────────────────────────
845
+ // HTTP Method Registration
846
+ // ─────────────────────────────────────────────────────────────────────────
847
+ /**
848
+ * Register a GET route
849
+ *
850
+ * @param path - Route path (e.g., '/users/:id')
851
+ * @param handlers - Handler and optional middleware
852
+ * @returns This instance for chaining
853
+ */
854
+ get(path, ...handlers) {
855
+ return this.addRoute("get", path, handlers);
856
+ }
857
+ /**
858
+ * Register a POST route
859
+ */
860
+ post(path, ...handlers) {
861
+ return this.addRoute("post", path, handlers);
862
+ }
863
+ /**
864
+ * Register a PUT route
865
+ */
866
+ put(path, ...handlers) {
867
+ return this.addRoute("put", path, handlers);
868
+ }
869
+ /**
870
+ * Register a DELETE route
871
+ */
872
+ delete(path, ...handlers) {
873
+ return this.addRoute("delete", path, handlers);
874
+ }
875
+ /**
876
+ * Register a PATCH route
877
+ */
878
+ patch(path, ...handlers) {
879
+ return this.addRoute("patch", path, handlers);
880
+ }
881
+ /**
882
+ * Register an OPTIONS route
883
+ */
884
+ options(path, ...handlers) {
885
+ return this.addRoute("options", path, handlers);
886
+ }
887
+ /**
888
+ * Register a HEAD route
889
+ */
890
+ head(path, ...handlers) {
891
+ return this.addRoute("head", path, handlers);
892
+ }
893
+ /**
894
+ * Register a route for all HTTP methods
895
+ */
896
+ all(path, ...handlers) {
897
+ const methods = ["get", "post", "put", "delete", "patch", "options", "head"];
898
+ for (const method of methods) {
899
+ this.addRoute(method, path, handlers);
900
+ }
901
+ return this;
902
+ }
903
+ use(pathOrMiddleware, ...middleware) {
904
+ this.isPureStaticApp = false;
905
+ if (typeof pathOrMiddleware === "string") {
906
+ this.router.usePattern(pathOrMiddleware, ...middleware);
907
+ } else {
908
+ this.router.use(pathOrMiddleware, ...middleware);
909
+ }
910
+ return this;
911
+ }
912
+ // ─────────────────────────────────────────────────────────────────────────
913
+ // Route Grouping
914
+ // ─────────────────────────────────────────────────────────────────────────
915
+ /**
916
+ * Mount a sub-application at a path prefix
917
+ *
918
+ * @example
919
+ * ```typescript
920
+ * const api = new Gravito()
921
+ * api.get('/users', (c) => c.json({ users: [] }))
922
+ *
923
+ * const app = new Gravito()
924
+ * app.route('/api', api)
925
+ * // Now accessible at /api/users
926
+ * ```
927
+ */
928
+ route(path, app) {
929
+ console.warn("route() method is not yet fully implemented");
930
+ return this;
931
+ }
932
+ // ─────────────────────────────────────────────────────────────────────────
933
+ // Error Handling
934
+ // ─────────────────────────────────────────────────────────────────────────
935
+ /**
936
+ * Set custom error handler
937
+ *
938
+ * @example
939
+ * ```typescript
940
+ * app.onError((err, c) => {
941
+ * console.error(err)
942
+ * return c.json({ error: err.message }, 500)
943
+ * })
944
+ * ```
945
+ */
946
+ onError(handler) {
947
+ this.errorHandler = handler;
948
+ return this;
949
+ }
950
+ /**
951
+ * Set custom 404 handler
952
+ *
953
+ * @example
954
+ * ```typescript
955
+ * app.notFound((c) => {
956
+ * return c.json({ error: 'Not Found' }, 404)
957
+ * })
958
+ * ```
959
+ */
960
+ notFound(handler) {
961
+ this.notFoundHandler = handler;
962
+ return this;
963
+ }
964
+ // ─────────────────────────────────────────────────────────────────────────
965
+ // Request Handling (Bun.serve integration)
966
+ // ─────────────────────────────────────────────────────────────────────────
967
+ /**
968
+ * Handle an incoming request
969
+ *
970
+ * Optimized for minimal allocations and maximum throughput.
971
+ * Uses sync/async dual-path strategy inspired by Hono.
972
+ *
973
+ * @param request - Incoming Request object
974
+ * @returns Response object (sync or async)
975
+ */
976
+ fetch = (request) => {
977
+ const path = extractPath(request.url);
978
+ const method = request.method.toLowerCase();
979
+ const staticKey = `${method}:${path}`;
980
+ const staticRoute = this.staticRoutes.get(staticKey);
981
+ if (staticRoute) {
982
+ if (staticRoute.useMinimal) {
983
+ const ctx = new MinimalContext(request, {}, path);
984
+ try {
985
+ const result = staticRoute.handler(ctx);
986
+ if (result instanceof Response) {
987
+ return result;
988
+ }
989
+ return result;
990
+ } catch (error) {
991
+ return this.handleErrorSync(error, request, path);
992
+ }
993
+ }
994
+ return this.handleWithMiddleware(request, path, staticRoute);
995
+ }
996
+ return this.handleDynamicRoute(request, method, path);
997
+ };
998
+ /**
999
+ * Handle routes with middleware (async path)
1000
+ */
1001
+ async handleWithMiddleware(request, path, route) {
1002
+ const ctx = this.contextPool.acquire();
1003
+ try {
1004
+ ctx.reset(request, {});
1005
+ const middleware = this.collectMiddlewareForPath(path, route.middleware);
1006
+ if (middleware.length === 0) {
1007
+ return await route.handler(ctx);
1008
+ }
1009
+ return await this.executeMiddleware(ctx, middleware, route.handler);
1010
+ } catch (error) {
1011
+ return await this.handleError(error, ctx);
1012
+ } finally {
1013
+ this.contextPool.release(ctx);
1014
+ }
1015
+ }
1016
+ /**
1017
+ * Handle dynamic routes (Radix Tree lookup)
1018
+ */
1019
+ handleDynamicRoute(request, method, path) {
1020
+ const match = this.router.match(method.toUpperCase(), path);
1021
+ if (!match.handler) {
1022
+ return this.handleNotFoundSync(request, path);
1023
+ }
1024
+ const ctx = this.contextPool.acquire();
1025
+ const execute = async () => {
1026
+ try {
1027
+ ctx.reset(request, match.params);
1028
+ if (match.middleware.length === 0) {
1029
+ return await match.handler(ctx);
1030
+ }
1031
+ return await this.executeMiddleware(ctx, match.middleware, match.handler);
1032
+ } catch (error) {
1033
+ return await this.handleError(error, ctx);
1034
+ } finally {
1035
+ this.contextPool.release(ctx);
1036
+ }
1037
+ };
1038
+ return execute();
1039
+ }
1040
+ /**
1041
+ * Sync error handler (for ultra-fast path)
1042
+ */
1043
+ handleErrorSync(error, request, path) {
1044
+ if (this.errorHandler) {
1045
+ const ctx = new MinimalContext(request, {}, path);
1046
+ const result = this.errorHandler(error, ctx);
1047
+ if (result instanceof Response) {
1048
+ return result;
1049
+ }
1050
+ return result;
1051
+ }
1052
+ console.error("Unhandled error:", error);
1053
+ return new Response(
1054
+ JSON.stringify({
1055
+ error: "Internal Server Error",
1056
+ message: error.message
1057
+ }),
1058
+ {
1059
+ status: 500,
1060
+ headers: { "Content-Type": "application/json" }
1061
+ }
1062
+ );
1063
+ }
1064
+ /**
1065
+ * Sync 404 handler (for ultra-fast path)
1066
+ */
1067
+ handleNotFoundSync(request, path) {
1068
+ if (this.notFoundHandler) {
1069
+ const ctx = new MinimalContext(request, {}, path);
1070
+ const result = this.notFoundHandler(ctx);
1071
+ if (result instanceof Response) {
1072
+ return result;
1073
+ }
1074
+ return result;
1075
+ }
1076
+ return new Response(JSON.stringify({ error: "Not Found" }), {
1077
+ status: 404,
1078
+ headers: { "Content-Type": "application/json" }
1079
+ });
1080
+ }
1081
+ /**
1082
+ * Collect middleware for a specific path
1083
+ * (Simplified version - assumes we've already checked for pure static)
1084
+ */
1085
+ collectMiddlewareForPath(path, routeMiddleware) {
1086
+ if (this.router.globalMiddleware.length === 0 && this.router.pathMiddleware.size === 0) {
1087
+ return routeMiddleware;
1088
+ }
1089
+ return this.router.collectMiddlewarePublic(path, routeMiddleware);
1090
+ }
1091
+ /**
1092
+ * Compile routes for optimization
1093
+ * Called once during initialization and when routes change
1094
+ */
1095
+ compileRoutes() {
1096
+ this.staticRoutes = this.router.staticRoutes;
1097
+ const hasGlobalMiddleware = this.router.globalMiddleware.length > 0;
1098
+ const hasPathMiddleware = this.router.pathMiddleware.size > 0;
1099
+ this.isPureStaticApp = !hasGlobalMiddleware && !hasPathMiddleware;
1100
+ for (const [_key, route] of this.staticRoutes) {
1101
+ const analysis = analyzeHandler(route.handler);
1102
+ const optimalType = getOptimalContextType(analysis);
1103
+ route.useMinimal = this.isPureStaticApp && route.middleware.length === 0 && optimalType === "minimal";
1104
+ }
1105
+ }
1106
+ // ─────────────────────────────────────────────────────────────────────────
1107
+ // Internal Methods
1108
+ // ─────────────────────────────────────────────────────────────────────────
1109
+ /**
1110
+ * Add a route to the router
1111
+ */
1112
+ addRoute(method, path, handlers) {
1113
+ if (handlers.length === 0) {
1114
+ throw new Error(`No handler provided for ${method.toUpperCase()} ${path}`);
1115
+ }
1116
+ const handler = handlers[handlers.length - 1];
1117
+ const middleware = handlers.slice(0, -1);
1118
+ this.router.add(method, path, handler, middleware);
1119
+ this.compileRoutes();
1120
+ return this;
1121
+ }
1122
+ /**
1123
+ * Execute middleware chain followed by handler
1124
+ *
1125
+ * Implements the standard middleware pattern:
1126
+ * Each middleware can call next() to continue the chain.
1127
+ */
1128
+ async executeMiddleware(ctx, middleware, handler) {
1129
+ let index = 0;
1130
+ const next = async () => {
1131
+ if (index < middleware.length) {
1132
+ const mw = middleware[index++];
1133
+ await mw(ctx, next);
1134
+ }
1135
+ };
1136
+ await next();
1137
+ return await handler(ctx);
1138
+ }
1139
+ /**
1140
+ * Handle 404 Not Found (Async version for dynamic/middleware paths)
1141
+ */
1142
+ async handleNotFound(ctx) {
1143
+ if (this.notFoundHandler) {
1144
+ return await this.notFoundHandler(ctx);
1145
+ }
1146
+ return ctx.json({ error: "Not Found" }, 404);
1147
+ }
1148
+ /**
1149
+ * Handle errors (Async version for dynamic/middleware paths)
1150
+ */
1151
+ async handleError(error, ctx) {
1152
+ if (this.errorHandler) {
1153
+ return await this.errorHandler(error, ctx);
1154
+ }
1155
+ console.error("Unhandled error:", error);
1156
+ return ctx.json(
1157
+ {
1158
+ error: "Internal Server Error",
1159
+ message: error.message
1160
+ },
1161
+ 500
1162
+ );
1163
+ }
1164
+ };
1165
+ // Annotate the CommonJS export names for ESM import in node:
1166
+ 0 && (module.exports = {
1167
+ AOTRouter,
1168
+ FastContextImpl,
1169
+ Gravito,
1170
+ MinimalContext,
1171
+ ObjectPool,
1172
+ extractPath
1173
+ });