@morojs/moro 1.8.12 → 1.8.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -2
- package/dist/core/cluster/thread-cluster.d.ts +25 -0
- package/dist/core/cluster/thread-cluster.js +95 -3
- package/dist/core/cluster/thread-cluster.js.map +1 -1
- package/dist/core/config/config-validator.js +15 -0
- package/dist/core/config/config-validator.js.map +1 -1
- package/dist/core/config/index.js +19 -2
- package/dist/core/config/index.js.map +1 -1
- package/dist/core/framework.d.ts +26 -0
- package/dist/core/framework.js +195 -6
- package/dist/core/framework.js.map +1 -1
- package/dist/core/http/http-server.d.ts +17 -0
- package/dist/core/http/http-server.js +21 -1
- package/dist/core/http/http-server.js.map +1 -1
- package/dist/core/http/http2-server.d.ts +13 -0
- package/dist/core/http/http2-server.js +11 -0
- package/dist/core/http/http2-server.js.map +1 -1
- package/dist/core/http/moro-engine-server.d.ts +28 -0
- package/dist/core/http/moro-engine-server.js +115 -11
- package/dist/core/http/moro-engine-server.js.map +1 -1
- package/dist/core/http/utils/body-type.d.ts +12 -0
- package/dist/core/http/utils/body-type.js +70 -0
- package/dist/core/http/utils/body-type.js.map +1 -0
- package/dist/core/http/utils/ssl-config.d.ts +11 -0
- package/dist/core/http/utils/ssl-config.js +3 -0
- package/dist/core/http/utils/ssl-config.js.map +1 -1
- package/dist/core/http/utils/uws-worker-clustering.js +5 -4
- package/dist/core/http/utils/uws-worker-clustering.js.map +1 -1
- package/dist/core/http/uws-http-server.d.ts +3 -0
- package/dist/core/http/uws-http-server.js +22 -1
- package/dist/core/http/uws-http-server.js.map +1 -1
- package/dist/core/middleware/built-in/body-parsers/index.d.ts +18 -0
- package/dist/core/middleware/built-in/body-parsers/index.js +41 -0
- package/dist/core/middleware/built-in/body-parsers/index.js.map +1 -1
- package/dist/core/middleware/built-in/cache/adapters/cache/redis.d.ts +32 -8
- package/dist/core/middleware/built-in/cache/adapters/cache/redis.js +117 -25
- package/dist/core/middleware/built-in/cache/adapters/cache/redis.js.map +1 -1
- package/dist/core/middleware/built-in/compression/core.js +5 -0
- package/dist/core/middleware/built-in/compression/core.js.map +1 -1
- package/dist/core/middleware/built-in/session/core.d.ts +1 -0
- package/dist/core/middleware/built-in/session/core.js.map +1 -1
- package/dist/core/middleware/built-in/static/core.d.ts +18 -0
- package/dist/core/middleware/built-in/static/core.js +128 -7
- package/dist/core/middleware/built-in/static/core.js.map +1 -1
- package/dist/core/networking/adapters/engine-adapter.d.ts +2 -2
- package/dist/core/networking/adapters/engine-adapter.js +40 -1
- package/dist/core/networking/adapters/engine-adapter.js.map +1 -1
- package/dist/core/networking/adapters/socketio-adapter.d.ts +2 -2
- package/dist/core/networking/adapters/socketio-adapter.js +10 -1
- package/dist/core/networking/adapters/socketio-adapter.js.map +1 -1
- package/dist/core/networking/adapters/uws-adapter.d.ts +2 -2
- package/dist/core/networking/adapters/uws-adapter.js +54 -3
- package/dist/core/networking/adapters/uws-adapter.js.map +1 -1
- package/dist/core/networking/adapters/ws-adapter.d.ts +9 -2
- package/dist/core/networking/adapters/ws-adapter.js +97 -12
- package/dist/core/networking/adapters/ws-adapter.js.map +1 -1
- package/dist/core/networking/websocket-adapter.d.ts +19 -1
- package/dist/core/networking/websocket-adapter.js.map +1 -1
- package/dist/core/routing/index.d.ts +12 -8
- package/dist/core/routing/index.js +7 -2
- package/dist/core/routing/index.js.map +1 -1
- package/dist/core/routing/unified-router.d.ts +46 -8
- package/dist/core/routing/unified-router.js +108 -32
- package/dist/core/routing/unified-router.js.map +1 -1
- package/dist/core/utilities/package-utils.d.ts +7 -0
- package/dist/core/utilities/package-utils.js +2 -0
- package/dist/core/utilities/package-utils.js.map +1 -1
- package/dist/core/workers/worker-manager.js +2 -2
- package/dist/core/workers/worker-manager.js.map +1 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/moro.d.ts +12 -1
- package/dist/moro.js +63 -7
- package/dist/moro.js.map +1 -1
- package/dist/types/cache.d.ts +2 -0
- package/dist/types/cache.js.map +1 -1
- package/dist/types/config.d.ts +9 -0
- package/dist/types/config.js.map +1 -1
- package/dist/types/http.d.ts +6 -0
- package/dist/types/http.js.map +1 -1
- package/dist/types/session.d.ts +1 -0
- package/dist/types/session.js.map +1 -1
- package/package.json +1 -1
|
@@ -21,7 +21,7 @@ export interface RouteSchema {
|
|
|
21
21
|
method: HttpMethod;
|
|
22
22
|
path: string;
|
|
23
23
|
/** A function, or the response body itself (see StaticBody) */
|
|
24
|
-
handler: RouteHandler | StaticBody;
|
|
24
|
+
handler: RouteHandler | StaticBody | ParamEcho;
|
|
25
25
|
validation?: ValidationConfig;
|
|
26
26
|
auth?: AuthConfig;
|
|
27
27
|
rateLimit?: RateLimitConfig;
|
|
@@ -34,6 +34,18 @@ export interface RouteSchema {
|
|
|
34
34
|
* calling into JS; every other server runs `handler`, which sends the
|
|
35
35
|
* same bytes. */
|
|
36
36
|
static?: StaticResponse;
|
|
37
|
+
/** The engine shape of a param(name) handler on a bare route with exactly
|
|
38
|
+
* that one parameter: the path segment between prefix and suffix is the
|
|
39
|
+
* body. MoroEngineServer on @morojs/engine >= 1.1.9 (paramRoutes) answers
|
|
40
|
+
* it without calling into JS; every other server runs `handler`. */
|
|
41
|
+
paramEcho?: ParamRouteReply;
|
|
42
|
+
}
|
|
43
|
+
export interface ParamRouteReply {
|
|
44
|
+
name: string;
|
|
45
|
+
prefix: string;
|
|
46
|
+
suffix: string;
|
|
47
|
+
status: number;
|
|
48
|
+
headers: string[] | null;
|
|
37
49
|
}
|
|
38
50
|
/** The reply a literal handler sends, in the engine's shape. */
|
|
39
51
|
export interface StaticResponse {
|
|
@@ -44,14 +56,40 @@ export interface StaticResponse {
|
|
|
44
56
|
}
|
|
45
57
|
/** What .handler() accepts in place of a function: the response body itself. */
|
|
46
58
|
export type StaticBody = string | Buffer;
|
|
59
|
+
export declare const PARAM_ECHO: unique symbol;
|
|
60
|
+
/** The marker param(name) produces: "answer with this path parameter as the
|
|
61
|
+
* body". `.handler(param('id'))` on `/user/:id` answers `GET /user/42` with
|
|
62
|
+
* `42`, as `res.end(req.params.id)` would - and on Moro's native engine, on
|
|
63
|
+
* a route with nothing else configured, without entering JS at all. */
|
|
64
|
+
export interface ParamEcho {
|
|
65
|
+
readonly [PARAM_ECHO]: true;
|
|
66
|
+
readonly name: string;
|
|
67
|
+
}
|
|
68
|
+
export declare function param(name: string): ParamEcho;
|
|
69
|
+
export declare function isParamEcho(value: unknown): value is ParamEcho;
|
|
70
|
+
/**
|
|
71
|
+
* param(name) in place of a handler: the route answers with that path
|
|
72
|
+
* parameter as the body, as res.end(req.params[name]) would. When `:name` is
|
|
73
|
+
* a whole segment of the path, the only parameter in it, and nothing else is
|
|
74
|
+
* configured, the schema also carries `paramEcho` - prefix and suffix around
|
|
75
|
+
* the segment - so a server that can answer it natively does so without
|
|
76
|
+
* calling into JS. The engine echoes the segment as it is on the wire,
|
|
77
|
+
* undecoded (as uWS does); a parameter that needs decoding stays a function
|
|
78
|
+
* handler.
|
|
79
|
+
*/
|
|
80
|
+
export declare function compileParamRoute(schema: Partial<RouteSchema>, echo: ParamEcho): RouteSchema;
|
|
47
81
|
/**
|
|
48
82
|
* A literal body in place of a handler: the route answers with exactly that
|
|
49
|
-
* body
|
|
50
|
-
*
|
|
51
|
-
*
|
|
52
|
-
*
|
|
53
|
-
*
|
|
54
|
-
*
|
|
83
|
+
* body. A non-empty body goes out as res.send(body) would (status 200, the
|
|
84
|
+
* implied content-type). An empty body has nothing a content-type could
|
|
85
|
+
* describe, so it goes out as res.end() would: status and Content-Length: 0,
|
|
86
|
+
* no header block - 38 bytes less per response, and byte-identical to the
|
|
87
|
+
* engine's own static reply with no headers. When nothing else is configured
|
|
88
|
+
* on the route - no auth, validation, rate limit, cache or middleware, and a
|
|
89
|
+
* literal path - the schema also carries `static`, so a server that can
|
|
90
|
+
* answer it natively does so without calling into JS. Anything configured
|
|
91
|
+
* keeps the route on the normal pipeline, where the handler sends the same
|
|
92
|
+
* bytes after that configuration has run.
|
|
55
93
|
*/
|
|
56
94
|
export declare function compileStaticRoute(schema: Partial<RouteSchema>, body: StaticBody): RouteSchema;
|
|
57
95
|
export declare class RouteBuilder {
|
|
@@ -72,7 +110,7 @@ export declare class RouteBuilder {
|
|
|
72
110
|
use(...middleware: Middleware[]): this;
|
|
73
111
|
describe(description: string): this;
|
|
74
112
|
tag(...tags: string[]): this;
|
|
75
|
-
handler<T>(handler: RouteHandler<T> | StaticBody): void;
|
|
113
|
+
handler<T>(handler: RouteHandler<T> | StaticBody | ParamEcho): void;
|
|
76
114
|
}
|
|
77
115
|
export declare class UnifiedRouter {
|
|
78
116
|
private static instance;
|
|
@@ -13,6 +13,74 @@ const logger = createFrameworkLogger('UnifiedRouter');
|
|
|
13
13
|
const rateLimitCore = new RateLimitCore();
|
|
14
14
|
const cacheCore = new CacheCore();
|
|
15
15
|
const validationCore = new ValidationCore();
|
|
16
|
+
export const PARAM_ECHO = Symbol.for('moro.paramEcho');
|
|
17
|
+
export function param(name) {
|
|
18
|
+
if (typeof name !== 'string' || name.length === 0) {
|
|
19
|
+
throw new Error('param(name) needs the parameter name, e.g. param("id") for "/user/:id"');
|
|
20
|
+
}
|
|
21
|
+
return Object.freeze({ [PARAM_ECHO]: true, name });
|
|
22
|
+
}
|
|
23
|
+
export function isParamEcho(value) {
|
|
24
|
+
return (typeof value === 'object' &&
|
|
25
|
+
value !== null &&
|
|
26
|
+
value[PARAM_ECHO] === true);
|
|
27
|
+
}
|
|
28
|
+
// Nothing configured that a reply answered inside the engine would skip:
|
|
29
|
+
// no auth, validation, rate limit, cache or middleware. (Static replies also
|
|
30
|
+
// need a literal path; parameter echoes need exactly one parameter.)
|
|
31
|
+
function isBareRoute(schema) {
|
|
32
|
+
const mw = schema.middleware;
|
|
33
|
+
const hasMiddleware = Array.isArray(mw)
|
|
34
|
+
? mw.length > 0
|
|
35
|
+
: mw !== undefined &&
|
|
36
|
+
Object.keys(mw).some(phase => {
|
|
37
|
+
const list = mw[phase];
|
|
38
|
+
return Array.isArray(list) && list.length > 0;
|
|
39
|
+
});
|
|
40
|
+
return !schema.auth && !schema.validation && !schema.rateLimit && !schema.cache && !hasMiddleware;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* param(name) in place of a handler: the route answers with that path
|
|
44
|
+
* parameter as the body, as res.end(req.params[name]) would. When `:name` is
|
|
45
|
+
* a whole segment of the path, the only parameter in it, and nothing else is
|
|
46
|
+
* configured, the schema also carries `paramEcho` - prefix and suffix around
|
|
47
|
+
* the segment - so a server that can answer it natively does so without
|
|
48
|
+
* calling into JS. The engine echoes the segment as it is on the wire,
|
|
49
|
+
* undecoded (as uWS does); a parameter that needs decoding stays a function
|
|
50
|
+
* handler.
|
|
51
|
+
*/
|
|
52
|
+
export function compileParamRoute(schema, echo) {
|
|
53
|
+
const name = echo.name;
|
|
54
|
+
schema.handler = (req, res) => {
|
|
55
|
+
const value = req.params?.[name];
|
|
56
|
+
res.end(value === undefined ? undefined : String(value));
|
|
57
|
+
};
|
|
58
|
+
const path = schema.path ?? '';
|
|
59
|
+
const segments = path.split('/');
|
|
60
|
+
const marker = `:${name}`;
|
|
61
|
+
const at = segments.indexOf(marker);
|
|
62
|
+
if (at === -1) {
|
|
63
|
+
// The router names a parameter after its whole segment, so ":name.json"
|
|
64
|
+
// is a parameter called "name.json" and param('name') would never see it.
|
|
65
|
+
// (":names" is a different parameter, not a misuse; it gets no echo.)
|
|
66
|
+
const partial = segments.some(seg => seg.startsWith(marker) && /^[^A-Za-z0-9_$]/.test(seg.slice(marker.length)));
|
|
67
|
+
if (partial) {
|
|
68
|
+
throw new Error(`param('${name}') needs '${marker}' as a whole segment of the route path; ` +
|
|
69
|
+
`'${path}' has it inside a segment`);
|
|
70
|
+
}
|
|
71
|
+
return schema;
|
|
72
|
+
}
|
|
73
|
+
const rest = segments.slice(at + 1);
|
|
74
|
+
const plainShape = !segments.some((seg, i) => i !== at && seg.startsWith(':')) &&
|
|
75
|
+
!path.includes('*') &&
|
|
76
|
+
!rest.includes(''); // no trailing or doubled slash after the parameter
|
|
77
|
+
if (plainShape && isBareRoute(schema)) {
|
|
78
|
+
const prefix = segments.slice(0, at).join('/') + '/';
|
|
79
|
+
const suffix = rest.length > 0 ? '/' + rest.join('/') : '';
|
|
80
|
+
schema.paramEcho = { name, prefix, suffix, status: 200, headers: null };
|
|
81
|
+
}
|
|
82
|
+
return schema;
|
|
83
|
+
}
|
|
16
84
|
// The content-type res.send() implies for a body it was given no header for:
|
|
17
85
|
// the same three cases MoroEngineServer's send() picks a template by, spelled
|
|
18
86
|
// out here so an engine-answered reply carries the bytes send() would have.
|
|
@@ -26,35 +94,34 @@ function impliedContentType(body) {
|
|
|
26
94
|
}
|
|
27
95
|
/**
|
|
28
96
|
* A literal body in place of a handler: the route answers with exactly that
|
|
29
|
-
* body
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
-
*
|
|
97
|
+
* body. A non-empty body goes out as res.send(body) would (status 200, the
|
|
98
|
+
* implied content-type). An empty body has nothing a content-type could
|
|
99
|
+
* describe, so it goes out as res.end() would: status and Content-Length: 0,
|
|
100
|
+
* no header block - 38 bytes less per response, and byte-identical to the
|
|
101
|
+
* engine's own static reply with no headers. When nothing else is configured
|
|
102
|
+
* on the route - no auth, validation, rate limit, cache or middleware, and a
|
|
103
|
+
* literal path - the schema also carries `static`, so a server that can
|
|
104
|
+
* answer it natively does so without calling into JS. Anything configured
|
|
105
|
+
* keeps the route on the normal pipeline, where the handler sends the same
|
|
106
|
+
* bytes after that configuration has run.
|
|
35
107
|
*/
|
|
36
108
|
export function compileStaticRoute(schema, body) {
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
109
|
+
const empty = body.length === 0;
|
|
110
|
+
schema.handler = empty
|
|
111
|
+
? (_req, res) => {
|
|
112
|
+
res.end();
|
|
113
|
+
}
|
|
114
|
+
: (_req, res) => {
|
|
115
|
+
res.send(body);
|
|
116
|
+
};
|
|
40
117
|
const path = schema.path ?? '';
|
|
41
|
-
const
|
|
42
|
-
const hasMiddleware = Array.isArray(mw)
|
|
43
|
-
? mw.length > 0
|
|
44
|
-
: mw !== undefined &&
|
|
45
|
-
Object.keys(mw).some(phase => {
|
|
46
|
-
const list = mw[phase];
|
|
47
|
-
return Array.isArray(list) && list.length > 0;
|
|
48
|
-
});
|
|
49
|
-
const bare = !path.includes(':') &&
|
|
50
|
-
!path.includes('*') &&
|
|
51
|
-
!schema.auth &&
|
|
52
|
-
!schema.validation &&
|
|
53
|
-
!schema.rateLimit &&
|
|
54
|
-
!schema.cache &&
|
|
55
|
-
!hasMiddleware;
|
|
118
|
+
const bare = !path.includes(':') && !path.includes('*') && isBareRoute(schema);
|
|
56
119
|
if (bare) {
|
|
57
|
-
schema.static = {
|
|
120
|
+
schema.static = {
|
|
121
|
+
status: 200,
|
|
122
|
+
headers: empty ? null : ['content-type', impliedContentType(body)],
|
|
123
|
+
body,
|
|
124
|
+
};
|
|
58
125
|
}
|
|
59
126
|
return schema;
|
|
60
127
|
}
|
|
@@ -188,8 +255,8 @@ export class RouteBuilder {
|
|
|
188
255
|
}
|
|
189
256
|
return this;
|
|
190
257
|
}
|
|
191
|
-
// Terminal method: a function,
|
|
192
|
-
// compileStaticRoute
|
|
258
|
+
// Terminal method: a function, the response body itself (see
|
|
259
|
+
// compileStaticRoute), or param(name) (see compileParamRoute).
|
|
193
260
|
handler(handler) {
|
|
194
261
|
if (typeof handler === 'function') {
|
|
195
262
|
// Avoid spread operator - add handler directly
|
|
@@ -201,7 +268,11 @@ export class RouteBuilder {
|
|
|
201
268
|
this.router.registerRoute(compileStaticRoute(this.schema, handler));
|
|
202
269
|
return;
|
|
203
270
|
}
|
|
204
|
-
|
|
271
|
+
if (isParamEcho(handler)) {
|
|
272
|
+
this.router.registerRoute(compileParamRoute(this.schema, handler));
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
throw new Error('Handler is required: a function, the response body as a string or Buffer, or param(name)');
|
|
205
276
|
}
|
|
206
277
|
}
|
|
207
278
|
// ===== Unified Router =====
|
|
@@ -334,12 +405,17 @@ export class UnifiedRouter {
|
|
|
334
405
|
// - so this is where the body becomes a handler and, on a bare route, a
|
|
335
406
|
// reply the native engine can answer itself.
|
|
336
407
|
if (typeof schema.handler !== 'function') {
|
|
337
|
-
const
|
|
338
|
-
if (
|
|
408
|
+
const given = schema.handler;
|
|
409
|
+
if (isParamEcho(given)) {
|
|
410
|
+
compileParamRoute(schema, given);
|
|
411
|
+
}
|
|
412
|
+
else if (typeof given === 'string' || Buffer.isBuffer(given)) {
|
|
413
|
+
compileStaticRoute(schema, given);
|
|
414
|
+
}
|
|
415
|
+
else {
|
|
339
416
|
throw new Error(`Handler for ${schema.method} ${schema.path} must be a function, ` +
|
|
340
|
-
'
|
|
417
|
+
'the response body as a string or Buffer, or param(name)');
|
|
341
418
|
}
|
|
342
|
-
compileStaticRoute(schema, body);
|
|
343
419
|
}
|
|
344
420
|
// From here on the handler is a function, whichever form was registered.
|
|
345
421
|
const registered = schema;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"unified-router.js","sourceRoot":"","sources":["../../../src/core/routing/unified-router.ts"],"names":[],"mappings":"AAAA,mEAAmE;AACnE,sEAAsE;AAEtE,OAAO,EAAE,WAAW,EAAgB,MAAM,mBAAmB,CAAC;AAC9D,OAAO,EAAE,iBAAiB,EAAE,MAAM,mCAAmC,CAAC;AACtE,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAE3D,OAAO,EAAE,aAAa,EAAwB,MAAM,4CAA4C,CAAC;AACjG,OAAO,EAAE,SAAS,EAAoB,MAAM,uCAAuC,CAAC;AACpF,OAAO,EAAE,cAAc,EAAyB,MAAM,4CAA4C,CAAC;AACnG,OAAO,EAAE,WAAW,EAAE,MAAM,wCAAwC,CAAC;AAErE,OAAO,EAAE,iBAAiB,EA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AK,CAAC,SAAS;YAC/B,WAAW,EAAE,IAAI,CAAC,WAAW,CAAC,qBAAqB,EAAE;YACrD,WAAW,EAAE,WAAW,CAAC,QAAQ,EAAE;SACpC,CAAC;IACJ,CAAC;IAED,mBAAmB;QACjB,MAAM,KAAK,GAAG,IAAI,CAAC,QAAQ,EAAE,CAAC;QAC9B,MAAM,CAAC,IAAI,CAAC,2BAA2B,EAAE,OAAO,EAAE;YAChD,WAAW,EAAE,KAAK,CAAC,WAAW;YAC9B,YAAY,EAAE,KAAK,CAAC,YAAY;YAChC,aAAa,EAAE,KAAK,CAAC,aAAa;YAClC,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,QAAQ,EAAE,KAAK,CAAC,YAAY;YAC5B,WAAW,EAAE;gBACX,iBAAiB,EAAE,KAAK,CAAC,WAAW,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,GAAG;gBACvE,oBAAoB,EAAE,KAAK,CAAC,WAAW,CAAC,oBAAoB,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,GAAG;gBAC7E,oBAAoB,EAAE,KAAK,CAAC,WAAW,CAAC,oBAAoB,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,GAAG;gBAC7E,aAAa,EAAE,KAAK,CAAC,WAAW,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,KAAK;aAClE;SACF,CAAC,CAAC;IACL,CAAC","sourcesContent":["// Unified Router - Consolidates Intelligent Router and Core Router\n// Combines best features from both systems with zero breaking changes\n\nimport { PathMatcher, CompiledPath } from './path-matcher.js';\nimport { ObjectPoolManager } from '../pooling/object-pool-manager.js';\nimport { createFrameworkLogger } from '../logger/index.js';\nimport { HttpRequest, HttpResponse } from '../../types/http.js';\nimport { RateLimitCore, type RateLimitConfig } from '../middleware/built-in/rate-limit/index.js';\nimport { CacheCore, type CacheConfig } from '../middleware/built-in/cache/index.js';\nimport { ValidationCore, type ValidationConfig } from '../middleware/built-in/validation/index.js';\nimport { requireAuth } from '../middleware/built-in/auth/helpers.js';\nimport { ValidationSchema } from '../validation/schema-interface.js';\nimport { MethodRadixRouter } from './radix-tree.js';\n\nconst logger = createFrameworkLogger('UnifiedRouter');\n\n// Shared Core instances for route-based features\nconst rateLimitCore = new RateLimitCore();\nconst cacheCore = new CacheCore();\nconst validationCore = new ValidationCore();\n\n// ===== Types =====\n\nexport type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS';\nexport type RouteHandler<T = any> = (req: HttpRequest, res: HttpResponse) => T | Promise<T>;\nexport type Middleware = (\n req: HttpRequest,\n res: HttpResponse,\n next: () => void\n) => void | Promise<void>;\n\nexport interface AuthConfig {\n roles?: string[];\n permissions?: string[];\n optional?: boolean;\n}\n\n// Re-export config types from built-in middleware for convenience\nexport type { RateLimitConfig, CacheConfig, ValidationConfig };\n\nexport interface MiddlewarePhases {\n before?: Middleware[];\n after?: Middleware[];\n transform?: Middleware[];\n}\n\nexport interface RouteSchema {\n method: HttpMethod;\n path: string;\n /** A function, or the response body itself (see StaticBody) */\n handler: RouteHandler | StaticBody;\n validation?: ValidationConfig;\n auth?: AuthConfig;\n rateLimit?: RateLimitConfig;\n cache?: CacheConfig;\n middleware?: MiddlewarePhases | Middleware[];\n description?: string;\n tags?: string[];\n /** Fixed reply of a literal handler. A server that can answer it\n * natively (MoroEngineServer on @morojs/engine >= 1.1.6) does so without\n * calling into JS; every other server runs `handler`, which sends the\n * same bytes. */\n static?: StaticResponse;\n}\n\n/** The reply a literal handler sends, in the engine's shape. */\nexport interface StaticResponse {\n status: number;\n /** [name, value, name, value, ...], or null for no headers at all */\n headers: string[] | null;\n body: string | Buffer | null;\n}\n\n/** What .handler() accepts in place of a function: the response body itself. */\nexport type StaticBody = string | Buffer;\n\n// A RouteSchema after registerRoute(): a literal body has been compiled into\n// a function by compileStaticRoute, so dispatch can call the handler directly.\ntype RegisteredRouteSchema = RouteSchema & { handler: RouteHandler };\n\n// The content-type res.send() implies for a body it was given no header for:\n// the same three cases MoroEngineServer's send() picks a template by, spelled\n// out here so an engine-answered reply carries the bytes send() would have.\nconst STATIC_JSON_START = /^\\s*[{[]/;\nfunction impliedContentType(body: StaticBody): string {\n if (typeof body !== 'string') return 'application/octet-stream';\n return STATIC_JSON_START.test(body)\n ? 'application/json; charset=utf-8'\n : 'text/plain; charset=utf-8';\n}\n\n/**\n * A literal body in place of a handler: the route answers with exactly that\n * body, as res.send(body) would (status 200, the implied content-type). When\n * nothing else is configured on the route - no auth, validation, rate limit,\n * cache or middleware, and a literal path - the schema also carries `static`,\n * so a server that can answer it natively does so without calling into JS.\n * Anything configured keeps the route on the normal pipeline, where the\n * handler sends the same bytes after that configuration has run.\n */\nexport function compileStaticRoute(schema: Partial<RouteSchema>, body: StaticBody): RouteSchema {\n schema.handler = (_req: HttpRequest, res: HttpResponse) => {\n res.send(body);\n };\n\n const path = schema.path ?? '';\n const mw = schema.middleware;\n const hasMiddleware = Array.isArray(mw)\n ? mw.length > 0\n : mw !== undefined &&\n Object.keys(mw).some(phase => {\n const list = (mw as Record<string, unknown>)[phase];\n return Array.isArray(list) && list.length > 0;\n });\n const bare =\n !path.includes(':') &&\n !path.includes('*') &&\n !schema.auth &&\n !schema.validation &&\n !schema.rateLimit &&\n !schema.cache &&\n !hasMiddleware;\n if (bare) {\n schema.static = { status: 200, headers: ['content-type', impliedContentType(body)], body };\n }\n return schema as RouteSchema;\n}\n\n// Canonical uppercase methods - lets dispatch skip toUpperCase for the\n// interned method strings every adapter hands over\nconst UPPERCASE_METHODS = new Set(['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS']);\n\n// Internal route representation\ninterface InternalRoute {\n schema: RegisteredRouteSchema;\n compiledPath: CompiledPath;\n // Hoisted from schema at registration so the per-request dispatch is a\n // single monomorphic load instead of a two-level property chase\n handler: RouteHandler;\n isFastPath: boolean; // No middleware, auth, validation, rate limiting\n executionOrder: string[]; // Ordered list of execution phases\n // Route-specific configs (not middleware)\n rateLimitConfig?: RateLimitConfig;\n cacheConfig?: CacheConfig;\n authMiddleware?: Middleware; // Auth keeps middleware since it's using requireAuth helper\n validationConfig?: ValidationConfig;\n}\n\n// ===== Route Builder (Chainable API) =====\n\nexport class RouteBuilder {\n private schema: Partial<RouteSchema>;\n private router: UnifiedRouter;\n\n constructor(method: HttpMethod, path: string, router: UnifiedRouter) {\n this.schema = {\n method,\n path,\n middleware: {} as MiddlewarePhases,\n };\n this.router = router;\n }\n\n // Validation methods\n validate(config: ValidationConfig): this {\n // Avoid spread operator and Object.assign - manually merge properties\n if (!this.schema.validation) {\n this.schema.validation = config;\n } else {\n if (config.body !== undefined) this.schema.validation.body = config.body;\n if (config.query !== undefined) this.schema.validation.query = config.query;\n if (config.params !== undefined) this.schema.validation.params = config.params;\n if (config.headers !== undefined) this.schema.validation.headers = config.headers;\n // Without this, `.body(schema).validate({ onValidationError })` silently\n // dropped the handler and fell back to the default 400 response.\n if (config.onValidationError !== undefined) {\n this.schema.validation.onValidationError = config.onValidationError;\n }\n }\n return this;\n }\n\n body<T>(schema: ValidationSchema<T>): this {\n if (!this.schema.validation) this.schema.validation = {};\n this.schema.validation.body = schema;\n return this;\n }\n\n query<T>(schema: ValidationSchema<T>): this {\n if (!this.schema.validation) this.schema.validation = {};\n this.schema.validation.query = schema;\n return this;\n }\n\n params<T>(schema: ValidationSchema<T>): this {\n if (!this.schema.validation) this.schema.validation = {};\n this.schema.validation.params = schema;\n return this;\n }\n\n headers<T>(schema: ValidationSchema<T>): this {\n if (!this.schema.validation) this.schema.validation = {};\n this.schema.validation.headers = schema;\n return this;\n }\n\n // Security methods\n auth(config: AuthConfig): this {\n this.schema.auth = config;\n return this;\n }\n\n rateLimit(config: RateLimitConfig): this {\n this.schema.rateLimit = config;\n return this;\n }\n\n // Caching\n cache(config: CacheConfig): this {\n this.schema.cache = config;\n return this;\n }\n\n // Custom middleware\n before(...middleware: Middleware[]): this {\n if (!this.schema.middleware) this.schema.middleware = {};\n const phases = this.schema.middleware as MiddlewarePhases;\n // Avoid spread, use push for better performance\n if (!phases.before) phases.before = [];\n for (let i = 0; i < middleware.length; i++) {\n phases.before.push(middleware[i] as Middleware);\n }\n return this;\n }\n\n after(...middleware: Middleware[]): this {\n if (!this.schema.middleware) this.schema.middleware = {};\n const phases = this.schema.middleware as MiddlewarePhases;\n // Avoid spread, use push for better performance\n if (!phases.after) phases.after = [];\n for (let i = 0; i < middleware.length; i++) {\n phases.after.push(middleware[i] as Middleware);\n }\n return this;\n }\n\n transform(...middleware: Middleware[]): this {\n if (!this.schema.middleware) this.schema.middleware = {};\n const phases = this.schema.middleware as MiddlewarePhases;\n // Avoid spread, use push for better performance\n if (!phases.transform) phases.transform = [];\n for (let i = 0; i < middleware.length; i++) {\n phases.transform.push(middleware[i] as Middleware);\n }\n return this;\n }\n\n use(...middleware: Middleware[]): this {\n return this.after(...middleware);\n }\n\n // Metadata\n describe(description: string): this {\n this.schema.description = description;\n return this;\n }\n\n tag(...tags: string[]): this {\n // Avoid spread, use push for better performance\n if (!this.schema.tags) this.schema.tags = [];\n for (let i = 0; i < tags.length; i++) {\n this.schema.tags.push(tags[i] as string);\n }\n return this;\n }\n\n // Terminal method: a function, or the response body itself (see\n // compileStaticRoute for what a literal body means).\n handler<T>(handler: RouteHandler<T> | StaticBody): void {\n if (typeof handler === 'function') {\n // Avoid spread operator - add handler directly\n this.schema.handler = handler;\n this.router.registerRoute(this.schema as RouteSchema);\n return;\n }\n if (typeof handler === 'string' || Buffer.isBuffer(handler)) {\n this.router.registerRoute(compileStaticRoute(this.schema, handler));\n return;\n }\n throw new Error('Handler is required: a function, or the response body as a string or Buffer');\n }\n}\n\n// ===== Unified Router =====\n\nexport class UnifiedRouter {\n private static instance: UnifiedRouter | null = null;\n\n private readonly poolManager = ObjectPoolManager.getInstance();\n\n // Route storage optimized for different access patterns\n // OPTIMIZATION: Separate maps per method for faster lookup (no string concat needed)\n // Method -> path -> route. A Map (not a plain object) so the per-request\n // lookup keyed by a non-constant method string stays a monomorphic Map.get\n // instead of a megamorphic keyed object load.\n private staticRoutesByMethod = new Map<string, Map<string, InternalRoute>>([\n ['GET', new Map<string, InternalRoute>()],\n ['POST', new Map<string, InternalRoute>()],\n ['PUT', new Map<string, InternalRoute>()],\n ['DELETE', new Map<string, InternalRoute>()],\n ['PATCH', new Map<string, InternalRoute>()],\n ['HEAD', new Map<string, InternalRoute>()],\n ['OPTIONS', new Map<string, InternalRoute>()],\n ]);\n private dynamicRoutesBySegments = new Map<number, InternalRoute[]>(); // Grouped by segment count\n private fastPathRoutes = new Set<InternalRoute>(); // Routes with no middleware\n private allRoutes: InternalRoute[] = []; // For iteration/inspection\n\n // NEW: Radix tree for fast dynamic route matching\n private radixRouter = new MethodRadixRouter();\n\n // Statistics\n private stats = {\n totalRoutes: 0,\n staticRoutes: 0,\n dynamicRoutes: 0,\n fastPathRoutes: 0,\n requestCount: 0,\n fastPathHits: 0,\n staticHits: 0,\n dynamicHits: 0,\n cacheHits: 0,\n radixHits: 0,\n };\n\n constructor() {\n logger.debug('UnifiedRouter initialized', 'Initialization');\n }\n\n // User-registered global error handler (set via Moro.setErrorHandler)\n private errorHandler?: (err: any, req: HttpRequest, res: HttpResponse) => any | Promise<any>;\n\n // Lifecycle hook manager (set via Moro) so 'error' hooks observe handler\n // errors — the router swallows them here, so the server-level error\n // boundary never sees them.\n private hookManager?: any;\n\n setErrorHandler(fn: (err: any, req: HttpRequest, res: HttpResponse) => any | Promise<any>): void {\n this.errorHandler = fn;\n }\n\n setHookManager(hookManager: any): void {\n this.hookManager = hookManager;\n }\n\n // Invoke the registered error handler (if any). Returns true if it produced a response.\n private async invokeErrorHandler(\n err: any,\n req: HttpRequest,\n res: HttpResponse\n ): Promise<boolean> {\n // Error hooks are observational: fire-and-forget so a slow or throwing\n // observer can never delay or alter the error response.\n if (\n this.hookManager &&\n (this.hookManager.hasHooks === undefined || this.hookManager.hasHooks('error'))\n ) {\n void Promise.resolve(\n this.hookManager.execute('error', { request: req, response: res, error: err })\n ).catch((hookError: any) =>\n logger.error('Error hook error', 'Hooks', {\n error: hookError instanceof Error ? hookError.message : String(hookError),\n })\n );\n }\n\n if (!this.errorHandler || res.headersSent) return false;\n try {\n const result = this.errorHandler(err, req, res);\n if (result && typeof (result as any).then === 'function') {\n await result;\n }\n return res.headersSent;\n } catch (handlerErr) {\n logger.error('Error handler itself threw', 'Execution', {\n error: handlerErr instanceof Error ? handlerErr.message : String(handlerErr),\n });\n return false;\n }\n }\n\n /**\n * Get singleton instance (optional - can still create new instances)\n */\n static getInstance(): UnifiedRouter {\n if (!this.instance) {\n this.instance = new UnifiedRouter();\n logger.info(`UnifiedRouter initialized (PID: ${process.pid})`, 'Router');\n }\n return this.instance;\n }\n\n /**\n * Reset singleton (useful for testing)\n */\n static reset(): void {\n if (this.instance) {\n this.instance.clearAllRoutes();\n }\n this.instance = null;\n }\n\n /**\n * Clear all routes (useful for testing)\n */\n clearAllRoutes(): void {\n for (const methodMap of this.staticRoutesByMethod.values()) methodMap.clear();\n this.dynamicRoutesBySegments.clear();\n this.fastPathRoutes.clear();\n this.allRoutes = [];\n this.radixRouter.clear();\n this.stats = {\n totalRoutes: 0,\n staticRoutes: 0,\n dynamicRoutes: 0,\n fastPathRoutes: 0,\n requestCount: 0,\n fastPathHits: 0,\n staticHits: 0,\n dynamicHits: 0,\n cacheHits: 0,\n radixHits: 0,\n };\n logger.debug('UnifiedRouter routes cleared', 'Reset');\n }\n\n // ===== Route Registration =====\n\n /**\n * Register a route (internal method) - OPTIMIZED\n */\n registerRoute(schema: RouteSchema): void {\n // A literal body in place of a handler (see compileStaticRoute). Every\n // entry point lands here - the builder, app.get(path, body), route(schema)\n // - so this is where the body becomes a handler and, on a bare route, a\n // reply the native engine can answer itself.\n if (typeof schema.handler !== 'function') {\n const body: unknown = schema.handler;\n if (typeof body !== 'string' && !Buffer.isBuffer(body)) {\n throw new Error(\n `Handler for ${schema.method} ${schema.path} must be a function, ` +\n 'or the response body as a string or Buffer'\n );\n }\n compileStaticRoute(schema, body);\n }\n // From here on the handler is a function, whichever form was registered.\n const registered = schema as RegisteredRouteSchema;\n\n // OPTIMIZATION: Skip PathMatcher.compile for better performance\n // Determine if static route (optimized check)\n const pathLen = schema.path.length;\n let hasParams = false;\n for (let i = 0; i < pathLen; i++) {\n if (schema.path.charCodeAt(i) === 58) {\n // ':' character\n hasParams = true;\n break;\n }\n }\n\n const isStatic = !hasParams;\n const isFastPath = this.isFastPathRoute(schema);\n\n // OPTIMIZATION: Lazy execution order building (only when needed)\n const executionOrder = isFastPath ? [] : this.buildExecutionOrder(schema);\n\n // OPTIMIZATION: Lazy auth middleware creation (only create when needed, not during registration)\n // This speeds up route registration significantly\n const route: InternalRoute = {\n schema: registered,\n compiledPath: null as any, // Will be set lazily if needed\n handler: registered.handler,\n isFastPath,\n executionOrder,\n rateLimitConfig: schema.rateLimit,\n cacheConfig: schema.cache,\n authMiddleware: undefined, // Will be created lazily on first request\n validationConfig: schema.validation,\n } as any;\n\n // Store in appropriate structures\n if (isStatic) {\n const methodMap = this.staticRoutesByMethod.get(schema.method);\n if (methodMap) {\n methodMap.set(schema.path, route);\n }\n this.stats.staticRoutes++;\n\n // DON'T add static routes to radix tree - Map is faster\n } else {\n // Add ONLY dynamic routes to radix tree (primary lookup for dynamic routes)\n this.radixRouter.addRoute(schema.method, schema.path, route);\n\n // Keep segment-based grouping for backward compatibility\n const segments = this.countSegmentsFast(schema.path);\n let routes = this.dynamicRoutesBySegments.get(segments);\n if (!routes) {\n routes = [];\n this.dynamicRoutesBySegments.set(segments, routes);\n }\n routes.push(route);\n this.stats.dynamicRoutes++;\n }\n\n if (isFastPath) {\n this.fastPathRoutes.add(route);\n this.stats.fastPathRoutes++;\n }\n\n this.allRoutes.push(route);\n this.stats.totalRoutes++;\n\n // OPTIMIZATION: Skip logging in production for performance\n // Most routes are registered once at startup, so this isn't a hot path\n // But reducing allocations still helps\n }\n\n /**\n * Fast segment counting without allocations\n */\n private countSegmentsFast(path: string): number {\n let count = 0;\n let inSegment = false;\n const len = path.length;\n\n for (let i = 0; i < len; i++) {\n const char = path.charCodeAt(i);\n if (char === 47) {\n // '/' character\n inSegment = false;\n } else if (!inSegment) {\n inSegment = true;\n count++;\n }\n }\n\n return count;\n }\n\n /**\n * Compile specialized param extractor for common cases\n */\n private compileParamExtractor(\n compiledPath: CompiledPath\n ): (matches: RegExpMatchArray) => Record<string, string> {\n const paramNames = compiledPath.paramNames;\n const paramCount = paramNames.length;\n\n // Specialized extractors for common cases\n if (paramCount === 0) {\n return () => ({}); // No allocation needed\n } else if (paramCount === 1) {\n const name = paramNames[0] as string;\n return matches => ({ [name]: matches[1] as string });\n } else if (paramCount === 2) {\n const name1 = paramNames[0] as string;\n const name2 = paramNames[1] as string;\n return matches => ({ [name1]: matches[1] as string, [name2]: matches[2] as string });\n } else if (paramCount === 3) {\n const name1 = paramNames[0] as string;\n const name2 = paramNames[1] as string;\n const name3 = paramNames[2] as string;\n return matches => ({\n [name1]: matches[1] as string,\n [name2]: matches[2] as string,\n [name3]: matches[3] as string,\n });\n } else {\n // Generic path for 4+ params\n return matches => {\n const params: Record<string, string> = {};\n for (let i = 0; i < paramCount; i++) {\n params[paramNames[i] as string] = matches[i + 1] as string;\n }\n return params;\n };\n }\n }\n\n /**\n * Chainable API methods\n */\n get(path: string): RouteBuilder {\n return new RouteBuilder('GET', path, this);\n }\n\n post(path: string): RouteBuilder {\n return new RouteBuilder('POST', path, this);\n }\n\n put(path: string): RouteBuilder {\n return new RouteBuilder('PUT', path, this);\n }\n\n delete(path: string): RouteBuilder {\n return new RouteBuilder('DELETE', path, this);\n }\n\n patch(path: string): RouteBuilder {\n return new RouteBuilder('PATCH', path, this);\n }\n\n head(path: string): RouteBuilder {\n return new RouteBuilder('HEAD', path, this);\n }\n\n options(path: string): RouteBuilder {\n return new RouteBuilder('OPTIONS', path, this);\n }\n\n /**\n * Schema-first route registration\n */\n route(schema: RouteSchema): void {\n this.registerRoute(schema);\n }\n\n /**\n * Direct API (for backward compatibility)\n */\n addRoute(\n method: HttpMethod,\n path: string,\n handler: RouteHandler | StaticBody,\n middleware: Middleware[] = []\n ): void {\n this.registerRoute({\n method,\n path,\n handler,\n middleware,\n });\n }\n\n // ===== Route Matching =====\n\n /**\n * Find a matching route for the request - HYBRID OPTIMIZED\n * Returns boolean (sync) for fast-path routes, Promise<boolean> for others\n */\n handleRequest(req: HttpRequest, res: HttpResponse): Promise<boolean> | boolean {\n this.stats.requestCount++;\n\n // Adapters hand over interned uppercase method strings - the Set probe\n // skips a per-request toUpperCase call (and its scan) in the common case\n const rawMethod = req.method;\n const method = (\n rawMethod && UPPERCASE_METHODS.has(rawMethod) ? rawMethod : rawMethod?.toUpperCase()\n ) as HttpMethod;\n const path = req.path;\n\n // FAST PATH 1: Try static route Map lookup first (fastest possible - no string concat)\n const methodMap = this.staticRoutesByMethod.get(method);\n if (methodMap) {\n const staticRoute = methodMap.get(path);\n\n if (staticRoute) {\n // (params untouched here: every adapter req initializes params, and\n // the engine adapter materializes it lazily on first handler access)\n\n // Fast-path execution (no middleware)\n if (staticRoute.isFastPath) {\n try {\n const result = staticRoute.handler(req, res);\n\n if (result && typeof (result as any).then === 'function') {\n return (result as Promise<any>)\n .then(actualResult => {\n if (actualResult !== undefined && !res.headersSent) {\n res.json(actualResult);\n }\n return true;\n })\n .catch(async err => {\n const handled = await this.invokeErrorHandler(err, req, res);\n if (!handled && !res.headersSent) {\n res.status(500).json({ error: 'Internal server error' });\n }\n return true;\n });\n } else {\n if (result !== undefined && !res.headersSent) {\n res.json(result);\n }\n return true;\n }\n } catch (err) {\n return (async () => {\n const handled = await this.invokeErrorHandler(err, req, res);\n if (!handled && !res.headersSent) {\n res.status(500).json({ error: 'Internal server error' });\n }\n return true;\n })();\n }\n }\n\n // Non-fast-path static route\n return (async () => {\n await this.executeRoute(staticRoute, req, res, { params: {} });\n return true;\n })();\n }\n }\n\n // FAST PATH 2: Try radix tree for dynamic routes\n const radixResult = this.radixRouter.findRoute(method, path);\n if (radixResult) {\n const route = radixResult.handler as InternalRoute;\n req.params = radixResult.params;\n\n // Fast-path dynamic routes (no middleware)\n if (route.isFastPath) {\n try {\n const result = route.handler(req, res);\n\n if (result && typeof (result as any).then === 'function') {\n return (result as Promise<any>)\n .then(actualResult => {\n if (actualResult !== undefined && !res.headersSent) {\n res.json(actualResult);\n }\n return true;\n })\n .catch(async err => {\n const handled = await this.invokeErrorHandler(err, req, res);\n if (!handled && !res.headersSent) {\n res.status(500).json({ error: 'Internal server error' });\n }\n return true;\n });\n } else {\n if (result !== undefined && !res.headersSent) {\n res.json(result);\n }\n return true;\n }\n } catch (err) {\n return (async () => {\n const handled = await this.invokeErrorHandler(err, req, res);\n if (!handled && !res.headersSent) {\n res.status(500).json({ error: 'Internal server error' });\n }\n return true;\n })();\n }\n }\n\n // Non-fast-path dynamic routes (with middleware)\n return (async () => {\n await this.executeRoute(route, req, res, { params: radixResult.params });\n return true;\n })();\n }\n\n // No route found\n return false;\n }\n\n // ===== Route Execution =====\n\n private async executeRoute(\n route: InternalRoute,\n req: HttpRequest,\n res: HttpResponse,\n matchResult: { params: Record<string, string> }\n ): Promise<void> {\n // The matcher already built a fresh params object - use it directly.\n // (No pooling: handlers may retain req past the response, so recycling\n // the object would alias params across requests.)\n req.params = matchResult.params;\n\n try {\n // Performance: Skip empty executionOrder array iteration\n // Most routes have empty or very short executionOrder\n if (route.executionOrder.length > 0) {\n // Execute middleware phases in order\n for (const phase of route.executionOrder) {\n if (res.headersSent) break;\n await this.executePhase(phase, route, req, res);\n }\n }\n\n // Execute handler\n if (!res.headersSent) {\n const result = await route.schema.handler(req, res);\n if (result !== undefined && !res.headersSent) {\n await res.json(result);\n }\n } else {\n // Headers already sent by middleware (e.g., cache hit, validation error, rate limit, auth)\n // This is expected behavior, not an error\n logger.debug('Handler skipped - response already sent by middleware', 'Execution');\n }\n } catch (error) {\n logger.error('Route execution error', 'Execution', {\n error: error instanceof Error ? error.message : String(error),\n route: `${route.schema.method} ${route.schema.path}`,\n });\n\n const handled = await this.invokeErrorHandler(error, req, res);\n if (!handled && !res.headersSent) {\n res.status(500).json({\n success: false,\n error: 'Internal server error',\n requestId: req.requestId,\n });\n }\n }\n }\n\n private async executePhase(\n phase: string,\n route: InternalRoute,\n req: HttpRequest,\n res: HttpResponse\n ): Promise<void> {\n const schema = route.schema;\n const middleware = schema.middleware;\n\n switch (phase) {\n case 'before': {\n // Performance: Early exit if no middleware present (fast path)\n if (!middleware || !('before' in middleware)) break;\n const beforeMw = (middleware as MiddlewarePhases).before;\n if (!beforeMw || beforeMw.length === 0) break;\n\n const beforeLen = beforeMw.length;\n for (let i = 0; i < beforeLen; i++) {\n const r = this.executeMiddleware(beforeMw[i] as Middleware, req, res);\n if (r) await r;\n if (res.headersSent) return;\n }\n break;\n }\n\n case 'rateLimit':\n // Use Core directly for route-based rate limiting\n if (route.rateLimitConfig) {\n await rateLimitCore.checkLimit(req, res, route.rateLimitConfig);\n }\n break;\n\n case 'auth':\n // Auth uses middleware (from requireAuth helper) - created lazily\n if (schema.auth) {\n if (!route.authMiddleware) {\n route.authMiddleware = requireAuth({\n ...(schema.auth.roles !== undefined && { roles: schema.auth.roles }),\n ...(schema.auth.permissions !== undefined && {\n permissions: schema.auth.permissions,\n }),\n ...(schema.auth.optional !== undefined && {\n allowUnauthenticated: schema.auth.optional,\n }),\n });\n }\n const r = this.executeMiddleware(route.authMiddleware, req, res);\n if (r) await r;\n }\n break;\n\n case 'validation':\n // Use Core directly for route-based validation\n if (route.validationConfig) {\n const isValid = await validationCore.validate(req, res, route.validationConfig);\n if (!isValid) {\n return; // Validation failed, response already sent\n }\n }\n break;\n\n case 'transform': {\n // Performance: Early exit if no middleware present (fast path)\n if (!middleware || !('transform' in middleware)) break;\n const transformMw = (middleware as MiddlewarePhases).transform;\n if (!transformMw || transformMw.length === 0) break;\n\n const transformLen = transformMw.length;\n for (let i = 0; i < transformLen; i++) {\n const r = this.executeMiddleware(transformMw[i] as Middleware, req, res);\n if (r) await r;\n if (res.headersSent) return;\n }\n break;\n }\n\n case 'cache':\n // Use Core directly for route-based caching\n if (route.cacheConfig) {\n const cached = await cacheCore.tryGet(req, res, route.cacheConfig);\n if (cached) {\n return; // Cache hit, response already sent\n }\n }\n break;\n\n case 'after': {\n // Performance: Early exit if no middleware present (fast path)\n if (!middleware || !('after' in middleware)) break;\n const afterMw = (middleware as MiddlewarePhases).after;\n if (!afterMw || afterMw.length === 0) break;\n\n const afterLen = afterMw.length;\n for (let i = 0; i < afterLen; i++) {\n const r = this.executeMiddleware(afterMw[i] as Middleware, req, res);\n if (r) await r;\n if (res.headersSent) return;\n }\n break;\n }\n\n case 'middleware': {\n // Handle array-style middleware (backward compatibility)\n // Performance: Early exit if no middleware present (fast path)\n if (!middleware || !Array.isArray(middleware) || middleware.length === 0) break;\n\n const middlewareLen = middleware.length;\n for (let i = 0; i < middlewareLen; i++) {\n const r = this.executeMiddleware(middleware[i] as Middleware, req, res);\n if (r) await r;\n if (res.headersSent) return;\n }\n break;\n }\n }\n }\n\n // Sync-aware: a middleware that returns a non-thenable always settled before\n // the caller could await it (next() called, or the auto-advance below), so\n // the promise was pure overhead - one allocation plus an async suspension per\n // middleware per request. Returns undefined in that case; callers skip the\n // await. A promise is only built when the middleware is genuinely async.\n // Error/advance semantics are unchanged.\n private executeMiddleware(\n middleware: Middleware,\n req: HttpRequest,\n res: HttpResponse\n ): void | Promise<void> {\n let resolved = false;\n let settle: (() => void) | undefined;\n\n const next = () => {\n if (resolved) return;\n resolved = true;\n if (settle) settle();\n };\n\n let result: any;\n try {\n result = middleware(req, res, next);\n } catch (error) {\n // Matches the previous promise form: a throw after next() already\n // advanced the chain was swallowed; otherwise it rejects/throws.\n if (resolved) return;\n resolved = true;\n throw error;\n }\n\n // Duck typing faster than instanceof\n const isThenable = result && typeof result.then === 'function';\n\n if (!isThenable) {\n // Sync middleware: previously this either resolved via next() or was\n // auto-advanced - settled either way before any await could observe it.\n next();\n return;\n }\n\n if (resolved) {\n // next() ran synchronously, so the chain already advanced. Keep the\n // returned promise's rejection handled, exactly as the old .catch(reject)\n // did on an already-resolved promise, so it never surfaces as unhandled.\n (result as Promise<any>).then(undefined, () => {});\n return;\n }\n\n return new Promise<void>((resolve, reject) => {\n settle = resolve;\n (result as Promise<any>).then(() => next(), reject);\n });\n }\n\n // ===== Helper Methods =====\n\n private isFastPathRoute(schema: RouteSchema): boolean {\n const middleware = schema.middleware;\n const hasMiddleware =\n (middleware && Array.isArray(middleware) && middleware.length > 0) ||\n (middleware &&\n typeof middleware === 'object' &&\n ((middleware as MiddlewarePhases).before?.length ||\n (middleware as MiddlewarePhases).after?.length ||\n (middleware as MiddlewarePhases).transform?.length));\n\n return (\n !schema.auth && !schema.validation && !schema.rateLimit && !schema.cache && !hasMiddleware\n );\n }\n\n private buildExecutionOrder(schema: RouteSchema): string[] {\n const order: string[] = [];\n const middleware = schema.middleware;\n\n // Phase-based middleware\n if (middleware && 'before' in middleware && middleware.before?.length) {\n order.push('before');\n }\n\n if (schema.rateLimit) order.push('rateLimit');\n if (schema.auth) order.push('auth');\n if (schema.validation) order.push('validation');\n\n if (middleware && 'transform' in middleware && middleware.transform?.length) {\n order.push('transform');\n }\n\n if (schema.cache) order.push('cache');\n\n if (middleware && 'after' in middleware && middleware.after?.length) {\n order.push('after');\n }\n\n // Array-style middleware (backward compatibility)\n if (middleware && Array.isArray(middleware) && middleware.length > 0) {\n order.push('middleware');\n }\n\n return order;\n }\n\n // ===== Inspection Methods =====\n\n getAllRoutes(): RouteSchema[] {\n return this.allRoutes.map(r => r.schema);\n }\n\n /**\n * Fast-path routes (no middleware/auth/validation/rateLimit/cache) in a shape\n * suitable for registering directly on a native server router (e.g. uWS).\n */\n getNativeFastPathRoutes(): Array<{\n method: string;\n path: string;\n paramNames: string[] | null;\n handler: (req: HttpRequest, res: HttpResponse) => any;\n }> {\n const result: Array<{\n method: string;\n path: string;\n paramNames: string[] | null;\n handler: (req: HttpRequest, res: HttpResponse) => any;\n }> = [];\n for (const route of this.allRoutes) {\n if (!route.isFastPath) continue;\n const path = route.schema.path;\n let paramNames: string[] | null = null;\n if (path.indexOf(':') !== -1) {\n paramNames = [];\n for (const seg of path.split('/')) {\n if (seg.charCodeAt(0) === 58) paramNames.push(seg.slice(1));\n }\n }\n result.push({\n method: route.schema.method,\n path,\n paramNames,\n handler: route.schema.handler,\n });\n }\n return result;\n }\n\n /**\n * Public wrapper around the registered error handler so native fast paths\n * share the exact same error semantics as router-dispatched routes.\n * Returns true if the handler produced a response.\n */\n handleRouteError(err: any, req: HttpRequest, res: HttpResponse): Promise<boolean> {\n return this.invokeErrorHandler(err, req, res);\n }\n\n getRouteCount(): number {\n return this.stats.totalRoutes;\n }\n\n getStats() {\n // Manually build object instead of spread operator\n return {\n totalRoutes: this.stats.totalRoutes,\n staticRoutes: this.stats.staticRoutes,\n dynamicRoutes: this.stats.dynamicRoutes,\n fastPathRoutes: this.stats.fastPathRoutes,\n requestCount: this.stats.requestCount,\n fastPathHits: this.stats.fastPathHits,\n staticHits: this.stats.staticHits,\n dynamicHits: this.stats.dynamicHits,\n cacheHits: this.stats.cacheHits,\n radixHits: this.stats.radixHits,\n poolManager: this.poolManager.getPerformanceSummary(),\n pathMatcher: PathMatcher.getStats(),\n };\n }\n\n logPerformanceStats(): void {\n const stats = this.getStats();\n logger.info('UnifiedRouter Performance', 'Stats', {\n totalRoutes: stats.totalRoutes,\n staticRoutes: stats.staticRoutes,\n dynamicRoutes: stats.dynamicRoutes,\n fastPathRoutes: stats.fastPathRoutes,\n requests: stats.requestCount,\n poolManager: {\n routeCacheHitRate: stats.poolManager.routeCacheHitRate.toFixed(1) + '%',\n responseCacheHitRate: stats.poolManager.responseCacheHitRate.toFixed(1) + '%',\n paramPoolUtilization: stats.poolManager.paramPoolUtilization.toFixed(1) + '%',\n totalMemoryKB: stats.poolManager.totalMemoryKB.toFixed(1) + ' KB',\n },\n });\n }\n}\n"]}
|
|
1
|
+
{"version":3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/B,SAAS,EAAE,IAAI,CAAC,KAAK,CAAC,SAAS;YAC/B,WAAW,EAAE,IAAI,CAAC,WAAW,CAAC,qBAAqB,EAAE;YACrD,WAAW,EAAE,WAAW,CAAC,QAAQ,EAAE;SACpC,CAAC;IACJ,CAAC;IAED,mBAAmB;QACjB,MAAM,KAAK,GAAG,IAAI,CAAC,QAAQ,EAAE,CAAC;QAC9B,MAAM,CAAC,IAAI,CAAC,2BAA2B,EAAE,OAAO,EAAE;YAChD,WAAW,EAAE,KAAK,CAAC,WAAW;YAC9B,YAAY,EAAE,KAAK,CAAC,YAAY;YAChC,aAAa,EAAE,KAAK,CAAC,aAAa;YAClC,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,QAAQ,EAAE,KAAK,CAAC,YAAY;YAC5B,WAAW,EAAE;gBACX,iBAAiB,EAAE,KAAK,CAAC,WAAW,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,GAAG;gBACvE,oBAAoB,EAAE,KAAK,CAAC,WAAW,CAAC,oBAAoB,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,GAAG;gBAC7E,oBAAoB,EAAE,KAAK,CAAC,WAAW,CAAC,oBAAoB,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,GAAG;gBAC7E,aAAa,EAAE,KAAK,CAAC,WAAW,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,KAAK;aAClE;SACF,CAAC,CAAC;IACL,CAAC","sourcesContent":["// Unified Router - Consolidates Intelligent Router and Core Router\n// Combines best features from both systems with zero breaking changes\n\nimport { PathMatcher, CompiledPath } from './path-matcher.js';\nimport { ObjectPoolManager } from '../pooling/object-pool-manager.js';\nimport { createFrameworkLogger } from '../logger/index.js';\nimport { HttpRequest, HttpResponse } from '../../types/http.js';\nimport { RateLimitCore, type RateLimitConfig } from '../middleware/built-in/rate-limit/index.js';\nimport { CacheCore, type CacheConfig } from '../middleware/built-in/cache/index.js';\nimport { ValidationCore, type ValidationConfig } from '../middleware/built-in/validation/index.js';\nimport { requireAuth } from '../middleware/built-in/auth/helpers.js';\nimport { ValidationSchema } from '../validation/schema-interface.js';\nimport { MethodRadixRouter } from './radix-tree.js';\n\nconst logger = createFrameworkLogger('UnifiedRouter');\n\n// Shared Core instances for route-based features\nconst rateLimitCore = new RateLimitCore();\nconst cacheCore = new CacheCore();\nconst validationCore = new ValidationCore();\n\n// ===== Types =====\n\nexport type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS';\nexport type RouteHandler<T = any> = (req: HttpRequest, res: HttpResponse) => T | Promise<T>;\nexport type Middleware = (\n req: HttpRequest,\n res: HttpResponse,\n next: () => void\n) => void | Promise<void>;\n\nexport interface AuthConfig {\n roles?: string[];\n permissions?: string[];\n optional?: boolean;\n}\n\n// Re-export config types from built-in middleware for convenience\nexport type { RateLimitConfig, CacheConfig, ValidationConfig };\n\nexport interface MiddlewarePhases {\n before?: Middleware[];\n after?: Middleware[];\n transform?: Middleware[];\n}\n\nexport interface RouteSchema {\n method: HttpMethod;\n path: string;\n /** A function, or the response body itself (see StaticBody) */\n handler: RouteHandler | StaticBody | ParamEcho;\n validation?: ValidationConfig;\n auth?: AuthConfig;\n rateLimit?: RateLimitConfig;\n cache?: CacheConfig;\n middleware?: MiddlewarePhases | Middleware[];\n description?: string;\n tags?: string[];\n /** Fixed reply of a literal handler. A server that can answer it\n * natively (MoroEngineServer on @morojs/engine >= 1.1.6) does so without\n * calling into JS; every other server runs `handler`, which sends the\n * same bytes. */\n static?: StaticResponse;\n /** The engine shape of a param(name) handler on a bare route with exactly\n * that one parameter: the path segment between prefix and suffix is the\n * body. MoroEngineServer on @morojs/engine >= 1.1.9 (paramRoutes) answers\n * it without calling into JS; every other server runs `handler`. */\n paramEcho?: ParamRouteReply;\n}\n\nexport interface ParamRouteReply {\n name: string;\n prefix: string;\n suffix: string;\n status: number;\n headers: string[] | null;\n}\n\n/** The reply a literal handler sends, in the engine's shape. */\nexport interface StaticResponse {\n status: number;\n /** [name, value, name, value, ...], or null for no headers at all */\n headers: string[] | null;\n body: string | Buffer | null;\n}\n\n/** What .handler() accepts in place of a function: the response body itself. */\nexport type StaticBody = string | Buffer;\n\nexport const PARAM_ECHO: unique symbol = Symbol.for('moro.paramEcho');\n\n/** The marker param(name) produces: \"answer with this path parameter as the\n * body\". `.handler(param('id'))` on `/user/:id` answers `GET /user/42` with\n * `42`, as `res.end(req.params.id)` would - and on Moro's native engine, on\n * a route with nothing else configured, without entering JS at all. */\nexport interface ParamEcho {\n readonly [PARAM_ECHO]: true;\n readonly name: string;\n}\n\nexport function param(name: string): ParamEcho {\n if (typeof name !== 'string' || name.length === 0) {\n throw new Error('param(name) needs the parameter name, e.g. param(\"id\") for \"/user/:id\"');\n }\n return Object.freeze({ [PARAM_ECHO]: true as const, name });\n}\n\nexport function isParamEcho(value: unknown): value is ParamEcho {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { [PARAM_ECHO]?: unknown })[PARAM_ECHO] === true\n );\n}\n\n// Nothing configured that a reply answered inside the engine would skip:\n// no auth, validation, rate limit, cache or middleware. (Static replies also\n// need a literal path; parameter echoes need exactly one parameter.)\nfunction isBareRoute(schema: Partial<RouteSchema>): boolean {\n const mw = schema.middleware;\n const hasMiddleware = Array.isArray(mw)\n ? mw.length > 0\n : mw !== undefined &&\n Object.keys(mw).some(phase => {\n const list = (mw as Record<string, unknown>)[phase];\n return Array.isArray(list) && list.length > 0;\n });\n return !schema.auth && !schema.validation && !schema.rateLimit && !schema.cache && !hasMiddleware;\n}\n\n/**\n * param(name) in place of a handler: the route answers with that path\n * parameter as the body, as res.end(req.params[name]) would. When `:name` is\n * a whole segment of the path, the only parameter in it, and nothing else is\n * configured, the schema also carries `paramEcho` - prefix and suffix around\n * the segment - so a server that can answer it natively does so without\n * calling into JS. The engine echoes the segment as it is on the wire,\n * undecoded (as uWS does); a parameter that needs decoding stays a function\n * handler.\n */\nexport function compileParamRoute(schema: Partial<RouteSchema>, echo: ParamEcho): RouteSchema {\n const name = echo.name;\n schema.handler = (req: HttpRequest, res: HttpResponse) => {\n const value = (req as { params?: Record<string, unknown> }).params?.[name];\n res.end(value === undefined ? undefined : String(value));\n };\n\n const path = schema.path ?? '';\n const segments = path.split('/');\n const marker = `:${name}`;\n const at = segments.indexOf(marker);\n if (at === -1) {\n // The router names a parameter after its whole segment, so \":name.json\"\n // is a parameter called \"name.json\" and param('name') would never see it.\n // (\":names\" is a different parameter, not a misuse; it gets no echo.)\n const partial = segments.some(\n seg => seg.startsWith(marker) && /^[^A-Za-z0-9_$]/.test(seg.slice(marker.length))\n );\n if (partial) {\n throw new Error(\n `param('${name}') needs '${marker}' as a whole segment of the route path; ` +\n `'${path}' has it inside a segment`\n );\n }\n return schema as RouteSchema;\n }\n const rest = segments.slice(at + 1);\n const plainShape =\n !segments.some((seg, i) => i !== at && seg.startsWith(':')) &&\n !path.includes('*') &&\n !rest.includes(''); // no trailing or doubled slash after the parameter\n if (plainShape && isBareRoute(schema)) {\n const prefix = segments.slice(0, at).join('/') + '/';\n const suffix = rest.length > 0 ? '/' + rest.join('/') : '';\n schema.paramEcho = { name, prefix, suffix, status: 200, headers: null };\n }\n return schema as RouteSchema;\n}\n\n// A RouteSchema after registerRoute(): a literal body has been compiled into\n// a function by compileStaticRoute, so dispatch can call the handler directly.\ntype RegisteredRouteSchema = RouteSchema & { handler: RouteHandler };\n\n// The content-type res.send() implies for a body it was given no header for:\n// the same three cases MoroEngineServer's send() picks a template by, spelled\n// out here so an engine-answered reply carries the bytes send() would have.\nconst STATIC_JSON_START = /^\\s*[{[]/;\nfunction impliedContentType(body: StaticBody): string {\n if (typeof body !== 'string') return 'application/octet-stream';\n return STATIC_JSON_START.test(body)\n ? 'application/json; charset=utf-8'\n : 'text/plain; charset=utf-8';\n}\n\n/**\n * A literal body in place of a handler: the route answers with exactly that\n * body. A non-empty body goes out as res.send(body) would (status 200, the\n * implied content-type). An empty body has nothing a content-type could\n * describe, so it goes out as res.end() would: status and Content-Length: 0,\n * no header block - 38 bytes less per response, and byte-identical to the\n * engine's own static reply with no headers. When nothing else is configured\n * on the route - no auth, validation, rate limit, cache or middleware, and a\n * literal path - the schema also carries `static`, so a server that can\n * answer it natively does so without calling into JS. Anything configured\n * keeps the route on the normal pipeline, where the handler sends the same\n * bytes after that configuration has run.\n */\nexport function compileStaticRoute(schema: Partial<RouteSchema>, body: StaticBody): RouteSchema {\n const empty = body.length === 0;\n schema.handler = empty\n ? (_req: HttpRequest, res: HttpResponse) => {\n res.end();\n }\n : (_req: HttpRequest, res: HttpResponse) => {\n res.send(body);\n };\n\n const path = schema.path ?? '';\n const bare = !path.includes(':') && !path.includes('*') && isBareRoute(schema);\n if (bare) {\n schema.static = {\n status: 200,\n headers: empty ? null : ['content-type', impliedContentType(body)],\n body,\n };\n }\n return schema as RouteSchema;\n}\n\n// Canonical uppercase methods - lets dispatch skip toUpperCase for the\n// interned method strings every adapter hands over\nconst UPPERCASE_METHODS = new Set(['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS']);\n\n// Internal route representation\ninterface InternalRoute {\n schema: RegisteredRouteSchema;\n compiledPath: CompiledPath;\n // Hoisted from schema at registration so the per-request dispatch is a\n // single monomorphic load instead of a two-level property chase\n handler: RouteHandler;\n isFastPath: boolean; // No middleware, auth, validation, rate limiting\n executionOrder: string[]; // Ordered list of execution phases\n // Route-specific configs (not middleware)\n rateLimitConfig?: RateLimitConfig;\n cacheConfig?: CacheConfig;\n authMiddleware?: Middleware; // Auth keeps middleware since it's using requireAuth helper\n validationConfig?: ValidationConfig;\n}\n\n// ===== Route Builder (Chainable API) =====\n\nexport class RouteBuilder {\n private schema: Partial<RouteSchema>;\n private router: UnifiedRouter;\n\n constructor(method: HttpMethod, path: string, router: UnifiedRouter) {\n this.schema = {\n method,\n path,\n middleware: {} as MiddlewarePhases,\n };\n this.router = router;\n }\n\n // Validation methods\n validate(config: ValidationConfig): this {\n // Avoid spread operator and Object.assign - manually merge properties\n if (!this.schema.validation) {\n this.schema.validation = config;\n } else {\n if (config.body !== undefined) this.schema.validation.body = config.body;\n if (config.query !== undefined) this.schema.validation.query = config.query;\n if (config.params !== undefined) this.schema.validation.params = config.params;\n if (config.headers !== undefined) this.schema.validation.headers = config.headers;\n // Without this, `.body(schema).validate({ onValidationError })` silently\n // dropped the handler and fell back to the default 400 response.\n if (config.onValidationError !== undefined) {\n this.schema.validation.onValidationError = config.onValidationError;\n }\n }\n return this;\n }\n\n body<T>(schema: ValidationSchema<T>): this {\n if (!this.schema.validation) this.schema.validation = {};\n this.schema.validation.body = schema;\n return this;\n }\n\n query<T>(schema: ValidationSchema<T>): this {\n if (!this.schema.validation) this.schema.validation = {};\n this.schema.validation.query = schema;\n return this;\n }\n\n params<T>(schema: ValidationSchema<T>): this {\n if (!this.schema.validation) this.schema.validation = {};\n this.schema.validation.params = schema;\n return this;\n }\n\n headers<T>(schema: ValidationSchema<T>): this {\n if (!this.schema.validation) this.schema.validation = {};\n this.schema.validation.headers = schema;\n return this;\n }\n\n // Security methods\n auth(config: AuthConfig): this {\n this.schema.auth = config;\n return this;\n }\n\n rateLimit(config: RateLimitConfig): this {\n this.schema.rateLimit = config;\n return this;\n }\n\n // Caching\n cache(config: CacheConfig): this {\n this.schema.cache = config;\n return this;\n }\n\n // Custom middleware\n before(...middleware: Middleware[]): this {\n if (!this.schema.middleware) this.schema.middleware = {};\n const phases = this.schema.middleware as MiddlewarePhases;\n // Avoid spread, use push for better performance\n if (!phases.before) phases.before = [];\n for (let i = 0; i < middleware.length; i++) {\n phases.before.push(middleware[i] as Middleware);\n }\n return this;\n }\n\n after(...middleware: Middleware[]): this {\n if (!this.schema.middleware) this.schema.middleware = {};\n const phases = this.schema.middleware as MiddlewarePhases;\n // Avoid spread, use push for better performance\n if (!phases.after) phases.after = [];\n for (let i = 0; i < middleware.length; i++) {\n phases.after.push(middleware[i] as Middleware);\n }\n return this;\n }\n\n transform(...middleware: Middleware[]): this {\n if (!this.schema.middleware) this.schema.middleware = {};\n const phases = this.schema.middleware as MiddlewarePhases;\n // Avoid spread, use push for better performance\n if (!phases.transform) phases.transform = [];\n for (let i = 0; i < middleware.length; i++) {\n phases.transform.push(middleware[i] as Middleware);\n }\n return this;\n }\n\n use(...middleware: Middleware[]): this {\n return this.after(...middleware);\n }\n\n // Metadata\n describe(description: string): this {\n this.schema.description = description;\n return this;\n }\n\n tag(...tags: string[]): this {\n // Avoid spread, use push for better performance\n if (!this.schema.tags) this.schema.tags = [];\n for (let i = 0; i < tags.length; i++) {\n this.schema.tags.push(tags[i] as string);\n }\n return this;\n }\n\n // Terminal method: a function, the response body itself (see\n // compileStaticRoute), or param(name) (see compileParamRoute).\n handler<T>(handler: RouteHandler<T> | StaticBody | ParamEcho): void {\n if (typeof handler === 'function') {\n // Avoid spread operator - add handler directly\n this.schema.handler = handler;\n this.router.registerRoute(this.schema as RouteSchema);\n return;\n }\n if (typeof handler === 'string' || Buffer.isBuffer(handler)) {\n this.router.registerRoute(compileStaticRoute(this.schema, handler));\n return;\n }\n if (isParamEcho(handler)) {\n this.router.registerRoute(compileParamRoute(this.schema, handler));\n return;\n }\n throw new Error(\n 'Handler is required: a function, the response body as a string or Buffer, or param(name)'\n );\n }\n}\n\n// ===== Unified Router =====\n\nexport class UnifiedRouter {\n private static instance: UnifiedRouter | null = null;\n\n private readonly poolManager = ObjectPoolManager.getInstance();\n\n // Route storage optimized for different access patterns\n // OPTIMIZATION: Separate maps per method for faster lookup (no string concat needed)\n // Method -> path -> route. A Map (not a plain object) so the per-request\n // lookup keyed by a non-constant method string stays a monomorphic Map.get\n // instead of a megamorphic keyed object load.\n private staticRoutesByMethod = new Map<string, Map<string, InternalRoute>>([\n ['GET', new Map<string, InternalRoute>()],\n ['POST', new Map<string, InternalRoute>()],\n ['PUT', new Map<string, InternalRoute>()],\n ['DELETE', new Map<string, InternalRoute>()],\n ['PATCH', new Map<string, InternalRoute>()],\n ['HEAD', new Map<string, InternalRoute>()],\n ['OPTIONS', new Map<string, InternalRoute>()],\n ]);\n private dynamicRoutesBySegments = new Map<number, InternalRoute[]>(); // Grouped by segment count\n private fastPathRoutes = new Set<InternalRoute>(); // Routes with no middleware\n private allRoutes: InternalRoute[] = []; // For iteration/inspection\n\n // NEW: Radix tree for fast dynamic route matching\n private radixRouter = new MethodRadixRouter();\n\n // Statistics\n private stats = {\n totalRoutes: 0,\n staticRoutes: 0,\n dynamicRoutes: 0,\n fastPathRoutes: 0,\n requestCount: 0,\n fastPathHits: 0,\n staticHits: 0,\n dynamicHits: 0,\n cacheHits: 0,\n radixHits: 0,\n };\n\n constructor() {\n logger.debug('UnifiedRouter initialized', 'Initialization');\n }\n\n // User-registered global error handler (set via Moro.setErrorHandler)\n private errorHandler?: (err: any, req: HttpRequest, res: HttpResponse) => any | Promise<any>;\n\n // Lifecycle hook manager (set via Moro) so 'error' hooks observe handler\n // errors — the router swallows them here, so the server-level error\n // boundary never sees them.\n private hookManager?: any;\n\n setErrorHandler(fn: (err: any, req: HttpRequest, res: HttpResponse) => any | Promise<any>): void {\n this.errorHandler = fn;\n }\n\n setHookManager(hookManager: any): void {\n this.hookManager = hookManager;\n }\n\n // Invoke the registered error handler (if any). Returns true if it produced a response.\n private async invokeErrorHandler(\n err: any,\n req: HttpRequest,\n res: HttpResponse\n ): Promise<boolean> {\n // Error hooks are observational: fire-and-forget so a slow or throwing\n // observer can never delay or alter the error response.\n if (\n this.hookManager &&\n (this.hookManager.hasHooks === undefined || this.hookManager.hasHooks('error'))\n ) {\n void Promise.resolve(\n this.hookManager.execute('error', { request: req, response: res, error: err })\n ).catch((hookError: any) =>\n logger.error('Error hook error', 'Hooks', {\n error: hookError instanceof Error ? hookError.message : String(hookError),\n })\n );\n }\n\n if (!this.errorHandler || res.headersSent) return false;\n try {\n const result = this.errorHandler(err, req, res);\n if (result && typeof (result as any).then === 'function') {\n await result;\n }\n return res.headersSent;\n } catch (handlerErr) {\n logger.error('Error handler itself threw', 'Execution', {\n error: handlerErr instanceof Error ? handlerErr.message : String(handlerErr),\n });\n return false;\n }\n }\n\n /**\n * Get singleton instance (optional - can still create new instances)\n */\n static getInstance(): UnifiedRouter {\n if (!this.instance) {\n this.instance = new UnifiedRouter();\n logger.info(`UnifiedRouter initialized (PID: ${process.pid})`, 'Router');\n }\n return this.instance;\n }\n\n /**\n * Reset singleton (useful for testing)\n */\n static reset(): void {\n if (this.instance) {\n this.instance.clearAllRoutes();\n }\n this.instance = null;\n }\n\n /**\n * Clear all routes (useful for testing)\n */\n clearAllRoutes(): void {\n for (const methodMap of this.staticRoutesByMethod.values()) methodMap.clear();\n this.dynamicRoutesBySegments.clear();\n this.fastPathRoutes.clear();\n this.allRoutes = [];\n this.radixRouter.clear();\n this.stats = {\n totalRoutes: 0,\n staticRoutes: 0,\n dynamicRoutes: 0,\n fastPathRoutes: 0,\n requestCount: 0,\n fastPathHits: 0,\n staticHits: 0,\n dynamicHits: 0,\n cacheHits: 0,\n radixHits: 0,\n };\n logger.debug('UnifiedRouter routes cleared', 'Reset');\n }\n\n // ===== Route Registration =====\n\n /**\n * Register a route (internal method) - OPTIMIZED\n */\n registerRoute(schema: RouteSchema): void {\n // A literal body in place of a handler (see compileStaticRoute). Every\n // entry point lands here - the builder, app.get(path, body), route(schema)\n // - so this is where the body becomes a handler and, on a bare route, a\n // reply the native engine can answer itself.\n if (typeof schema.handler !== 'function') {\n const given: unknown = schema.handler;\n if (isParamEcho(given)) {\n compileParamRoute(schema, given);\n } else if (typeof given === 'string' || Buffer.isBuffer(given)) {\n compileStaticRoute(schema, given);\n } else {\n throw new Error(\n `Handler for ${schema.method} ${schema.path} must be a function, ` +\n 'the response body as a string or Buffer, or param(name)'\n );\n }\n }\n // From here on the handler is a function, whichever form was registered.\n const registered = schema as RegisteredRouteSchema;\n\n // OPTIMIZATION: Skip PathMatcher.compile for better performance\n // Determine if static route (optimized check)\n const pathLen = schema.path.length;\n let hasParams = false;\n for (let i = 0; i < pathLen; i++) {\n if (schema.path.charCodeAt(i) === 58) {\n // ':' character\n hasParams = true;\n break;\n }\n }\n\n const isStatic = !hasParams;\n const isFastPath = this.isFastPathRoute(schema);\n\n // OPTIMIZATION: Lazy execution order building (only when needed)\n const executionOrder = isFastPath ? [] : this.buildExecutionOrder(schema);\n\n // OPTIMIZATION: Lazy auth middleware creation (only create when needed, not during registration)\n // This speeds up route registration significantly\n const route: InternalRoute = {\n schema: registered,\n compiledPath: null as any, // Will be set lazily if needed\n handler: registered.handler,\n isFastPath,\n executionOrder,\n rateLimitConfig: schema.rateLimit,\n cacheConfig: schema.cache,\n authMiddleware: undefined, // Will be created lazily on first request\n validationConfig: schema.validation,\n } as any;\n\n // Store in appropriate structures\n if (isStatic) {\n const methodMap = this.staticRoutesByMethod.get(schema.method);\n if (methodMap) {\n methodMap.set(schema.path, route);\n }\n this.stats.staticRoutes++;\n\n // DON'T add static routes to radix tree - Map is faster\n } else {\n // Add ONLY dynamic routes to radix tree (primary lookup for dynamic routes)\n this.radixRouter.addRoute(schema.method, schema.path, route);\n\n // Keep segment-based grouping for backward compatibility\n const segments = this.countSegmentsFast(schema.path);\n let routes = this.dynamicRoutesBySegments.get(segments);\n if (!routes) {\n routes = [];\n this.dynamicRoutesBySegments.set(segments, routes);\n }\n routes.push(route);\n this.stats.dynamicRoutes++;\n }\n\n if (isFastPath) {\n this.fastPathRoutes.add(route);\n this.stats.fastPathRoutes++;\n }\n\n this.allRoutes.push(route);\n this.stats.totalRoutes++;\n\n // OPTIMIZATION: Skip logging in production for performance\n // Most routes are registered once at startup, so this isn't a hot path\n // But reducing allocations still helps\n }\n\n /**\n * Fast segment counting without allocations\n */\n private countSegmentsFast(path: string): number {\n let count = 0;\n let inSegment = false;\n const len = path.length;\n\n for (let i = 0; i < len; i++) {\n const char = path.charCodeAt(i);\n if (char === 47) {\n // '/' character\n inSegment = false;\n } else if (!inSegment) {\n inSegment = true;\n count++;\n }\n }\n\n return count;\n }\n\n /**\n * Compile specialized param extractor for common cases\n */\n private compileParamExtractor(\n compiledPath: CompiledPath\n ): (matches: RegExpMatchArray) => Record<string, string> {\n const paramNames = compiledPath.paramNames;\n const paramCount = paramNames.length;\n\n // Specialized extractors for common cases\n if (paramCount === 0) {\n return () => ({}); // No allocation needed\n } else if (paramCount === 1) {\n const name = paramNames[0] as string;\n return matches => ({ [name]: matches[1] as string });\n } else if (paramCount === 2) {\n const name1 = paramNames[0] as string;\n const name2 = paramNames[1] as string;\n return matches => ({ [name1]: matches[1] as string, [name2]: matches[2] as string });\n } else if (paramCount === 3) {\n const name1 = paramNames[0] as string;\n const name2 = paramNames[1] as string;\n const name3 = paramNames[2] as string;\n return matches => ({\n [name1]: matches[1] as string,\n [name2]: matches[2] as string,\n [name3]: matches[3] as string,\n });\n } else {\n // Generic path for 4+ params\n return matches => {\n const params: Record<string, string> = {};\n for (let i = 0; i < paramCount; i++) {\n params[paramNames[i] as string] = matches[i + 1] as string;\n }\n return params;\n };\n }\n }\n\n /**\n * Chainable API methods\n */\n get(path: string): RouteBuilder {\n return new RouteBuilder('GET', path, this);\n }\n\n post(path: string): RouteBuilder {\n return new RouteBuilder('POST', path, this);\n }\n\n put(path: string): RouteBuilder {\n return new RouteBuilder('PUT', path, this);\n }\n\n delete(path: string): RouteBuilder {\n return new RouteBuilder('DELETE', path, this);\n }\n\n patch(path: string): RouteBuilder {\n return new RouteBuilder('PATCH', path, this);\n }\n\n head(path: string): RouteBuilder {\n return new RouteBuilder('HEAD', path, this);\n }\n\n options(path: string): RouteBuilder {\n return new RouteBuilder('OPTIONS', path, this);\n }\n\n /**\n * Schema-first route registration\n */\n route(schema: RouteSchema): void {\n this.registerRoute(schema);\n }\n\n /**\n * Direct API (for backward compatibility)\n */\n addRoute(\n method: HttpMethod,\n path: string,\n handler: RouteHandler | StaticBody,\n middleware: Middleware[] = []\n ): void {\n this.registerRoute({\n method,\n path,\n handler,\n middleware,\n });\n }\n\n // ===== Route Matching =====\n\n /**\n * Find a matching route for the request - HYBRID OPTIMIZED\n * Returns boolean (sync) for fast-path routes, Promise<boolean> for others\n */\n handleRequest(req: HttpRequest, res: HttpResponse): Promise<boolean> | boolean {\n this.stats.requestCount++;\n\n // Adapters hand over interned uppercase method strings - the Set probe\n // skips a per-request toUpperCase call (and its scan) in the common case\n const rawMethod = req.method;\n const method = (\n rawMethod && UPPERCASE_METHODS.has(rawMethod) ? rawMethod : rawMethod?.toUpperCase()\n ) as HttpMethod;\n const path = req.path;\n\n // FAST PATH 1: Try static route Map lookup first (fastest possible - no string concat)\n const methodMap = this.staticRoutesByMethod.get(method);\n if (methodMap) {\n const staticRoute = methodMap.get(path);\n\n if (staticRoute) {\n // (params untouched here: every adapter req initializes params, and\n // the engine adapter materializes it lazily on first handler access)\n\n // Fast-path execution (no middleware)\n if (staticRoute.isFastPath) {\n try {\n const result = staticRoute.handler(req, res);\n\n if (result && typeof (result as any).then === 'function') {\n return (result as Promise<any>)\n .then(actualResult => {\n if (actualResult !== undefined && !res.headersSent) {\n res.json(actualResult);\n }\n return true;\n })\n .catch(async err => {\n const handled = await this.invokeErrorHandler(err, req, res);\n if (!handled && !res.headersSent) {\n res.status(500).json({ error: 'Internal server error' });\n }\n return true;\n });\n } else {\n if (result !== undefined && !res.headersSent) {\n res.json(result);\n }\n return true;\n }\n } catch (err) {\n return (async () => {\n const handled = await this.invokeErrorHandler(err, req, res);\n if (!handled && !res.headersSent) {\n res.status(500).json({ error: 'Internal server error' });\n }\n return true;\n })();\n }\n }\n\n // Non-fast-path static route\n return (async () => {\n await this.executeRoute(staticRoute, req, res, { params: {} });\n return true;\n })();\n }\n }\n\n // FAST PATH 2: Try radix tree for dynamic routes\n const radixResult = this.radixRouter.findRoute(method, path);\n if (radixResult) {\n const route = radixResult.handler as InternalRoute;\n req.params = radixResult.params;\n\n // Fast-path dynamic routes (no middleware)\n if (route.isFastPath) {\n try {\n const result = route.handler(req, res);\n\n if (result && typeof (result as any).then === 'function') {\n return (result as Promise<any>)\n .then(actualResult => {\n if (actualResult !== undefined && !res.headersSent) {\n res.json(actualResult);\n }\n return true;\n })\n .catch(async err => {\n const handled = await this.invokeErrorHandler(err, req, res);\n if (!handled && !res.headersSent) {\n res.status(500).json({ error: 'Internal server error' });\n }\n return true;\n });\n } else {\n if (result !== undefined && !res.headersSent) {\n res.json(result);\n }\n return true;\n }\n } catch (err) {\n return (async () => {\n const handled = await this.invokeErrorHandler(err, req, res);\n if (!handled && !res.headersSent) {\n res.status(500).json({ error: 'Internal server error' });\n }\n return true;\n })();\n }\n }\n\n // Non-fast-path dynamic routes (with middleware)\n return (async () => {\n await this.executeRoute(route, req, res, { params: radixResult.params });\n return true;\n })();\n }\n\n // No route found\n return false;\n }\n\n // ===== Route Execution =====\n\n private async executeRoute(\n route: InternalRoute,\n req: HttpRequest,\n res: HttpResponse,\n matchResult: { params: Record<string, string> }\n ): Promise<void> {\n // The matcher already built a fresh params object - use it directly.\n // (No pooling: handlers may retain req past the response, so recycling\n // the object would alias params across requests.)\n req.params = matchResult.params;\n\n try {\n // Performance: Skip empty executionOrder array iteration\n // Most routes have empty or very short executionOrder\n if (route.executionOrder.length > 0) {\n // Execute middleware phases in order\n for (const phase of route.executionOrder) {\n if (res.headersSent) break;\n await this.executePhase(phase, route, req, res);\n }\n }\n\n // Execute handler\n if (!res.headersSent) {\n const result = await route.schema.handler(req, res);\n if (result !== undefined && !res.headersSent) {\n await res.json(result);\n }\n } else {\n // Headers already sent by middleware (e.g., cache hit, validation error, rate limit, auth)\n // This is expected behavior, not an error\n logger.debug('Handler skipped - response already sent by middleware', 'Execution');\n }\n } catch (error) {\n logger.error('Route execution error', 'Execution', {\n error: error instanceof Error ? error.message : String(error),\n route: `${route.schema.method} ${route.schema.path}`,\n });\n\n const handled = await this.invokeErrorHandler(error, req, res);\n if (!handled && !res.headersSent) {\n res.status(500).json({\n success: false,\n error: 'Internal server error',\n requestId: req.requestId,\n });\n }\n }\n }\n\n private async executePhase(\n phase: string,\n route: InternalRoute,\n req: HttpRequest,\n res: HttpResponse\n ): Promise<void> {\n const schema = route.schema;\n const middleware = schema.middleware;\n\n switch (phase) {\n case 'before': {\n // Performance: Early exit if no middleware present (fast path)\n if (!middleware || !('before' in middleware)) break;\n const beforeMw = (middleware as MiddlewarePhases).before;\n if (!beforeMw || beforeMw.length === 0) break;\n\n const beforeLen = beforeMw.length;\n for (let i = 0; i < beforeLen; i++) {\n const r = this.executeMiddleware(beforeMw[i] as Middleware, req, res);\n if (r) await r;\n if (res.headersSent) return;\n }\n break;\n }\n\n case 'rateLimit':\n // Use Core directly for route-based rate limiting\n if (route.rateLimitConfig) {\n await rateLimitCore.checkLimit(req, res, route.rateLimitConfig);\n }\n break;\n\n case 'auth':\n // Auth uses middleware (from requireAuth helper) - created lazily\n if (schema.auth) {\n if (!route.authMiddleware) {\n route.authMiddleware = requireAuth({\n ...(schema.auth.roles !== undefined && { roles: schema.auth.roles }),\n ...(schema.auth.permissions !== undefined && {\n permissions: schema.auth.permissions,\n }),\n ...(schema.auth.optional !== undefined && {\n allowUnauthenticated: schema.auth.optional,\n }),\n });\n }\n const r = this.executeMiddleware(route.authMiddleware, req, res);\n if (r) await r;\n }\n break;\n\n case 'validation':\n // Use Core directly for route-based validation\n if (route.validationConfig) {\n const isValid = await validationCore.validate(req, res, route.validationConfig);\n if (!isValid) {\n return; // Validation failed, response already sent\n }\n }\n break;\n\n case 'transform': {\n // Performance: Early exit if no middleware present (fast path)\n if (!middleware || !('transform' in middleware)) break;\n const transformMw = (middleware as MiddlewarePhases).transform;\n if (!transformMw || transformMw.length === 0) break;\n\n const transformLen = transformMw.length;\n for (let i = 0; i < transformLen; i++) {\n const r = this.executeMiddleware(transformMw[i] as Middleware, req, res);\n if (r) await r;\n if (res.headersSent) return;\n }\n break;\n }\n\n case 'cache':\n // Use Core directly for route-based caching\n if (route.cacheConfig) {\n const cached = await cacheCore.tryGet(req, res, route.cacheConfig);\n if (cached) {\n return; // Cache hit, response already sent\n }\n }\n break;\n\n case 'after': {\n // Performance: Early exit if no middleware present (fast path)\n if (!middleware || !('after' in middleware)) break;\n const afterMw = (middleware as MiddlewarePhases).after;\n if (!afterMw || afterMw.length === 0) break;\n\n const afterLen = afterMw.length;\n for (let i = 0; i < afterLen; i++) {\n const r = this.executeMiddleware(afterMw[i] as Middleware, req, res);\n if (r) await r;\n if (res.headersSent) return;\n }\n break;\n }\n\n case 'middleware': {\n // Handle array-style middleware (backward compatibility)\n // Performance: Early exit if no middleware present (fast path)\n if (!middleware || !Array.isArray(middleware) || middleware.length === 0) break;\n\n const middlewareLen = middleware.length;\n for (let i = 0; i < middlewareLen; i++) {\n const r = this.executeMiddleware(middleware[i] as Middleware, req, res);\n if (r) await r;\n if (res.headersSent) return;\n }\n break;\n }\n }\n }\n\n // Sync-aware: a middleware that returns a non-thenable always settled before\n // the caller could await it (next() called, or the auto-advance below), so\n // the promise was pure overhead - one allocation plus an async suspension per\n // middleware per request. Returns undefined in that case; callers skip the\n // await. A promise is only built when the middleware is genuinely async.\n // Error/advance semantics are unchanged.\n private executeMiddleware(\n middleware: Middleware,\n req: HttpRequest,\n res: HttpResponse\n ): void | Promise<void> {\n let resolved = false;\n let settle: (() => void) | undefined;\n\n const next = () => {\n if (resolved) return;\n resolved = true;\n if (settle) settle();\n };\n\n let result: any;\n try {\n result = middleware(req, res, next);\n } catch (error) {\n // Matches the previous promise form: a throw after next() already\n // advanced the chain was swallowed; otherwise it rejects/throws.\n if (resolved) return;\n resolved = true;\n throw error;\n }\n\n // Duck typing faster than instanceof\n const isThenable = result && typeof result.then === 'function';\n\n if (!isThenable) {\n // Sync middleware: previously this either resolved via next() or was\n // auto-advanced - settled either way before any await could observe it.\n next();\n return;\n }\n\n if (resolved) {\n // next() ran synchronously, so the chain already advanced. Keep the\n // returned promise's rejection handled, exactly as the old .catch(reject)\n // did on an already-resolved promise, so it never surfaces as unhandled.\n (result as Promise<any>).then(undefined, () => {});\n return;\n }\n\n return new Promise<void>((resolve, reject) => {\n settle = resolve;\n (result as Promise<any>).then(() => next(), reject);\n });\n }\n\n // ===== Helper Methods =====\n\n private isFastPathRoute(schema: RouteSchema): boolean {\n const middleware = schema.middleware;\n const hasMiddleware =\n (middleware && Array.isArray(middleware) && middleware.length > 0) ||\n (middleware &&\n typeof middleware === 'object' &&\n ((middleware as MiddlewarePhases).before?.length ||\n (middleware as MiddlewarePhases).after?.length ||\n (middleware as MiddlewarePhases).transform?.length));\n\n return (\n !schema.auth && !schema.validation && !schema.rateLimit && !schema.cache && !hasMiddleware\n );\n }\n\n private buildExecutionOrder(schema: RouteSchema): string[] {\n const order: string[] = [];\n const middleware = schema.middleware;\n\n // Phase-based middleware\n if (middleware && 'before' in middleware && middleware.before?.length) {\n order.push('before');\n }\n\n if (schema.rateLimit) order.push('rateLimit');\n if (schema.auth) order.push('auth');\n if (schema.validation) order.push('validation');\n\n if (middleware && 'transform' in middleware && middleware.transform?.length) {\n order.push('transform');\n }\n\n if (schema.cache) order.push('cache');\n\n if (middleware && 'after' in middleware && middleware.after?.length) {\n order.push('after');\n }\n\n // Array-style middleware (backward compatibility)\n if (middleware && Array.isArray(middleware) && middleware.length > 0) {\n order.push('middleware');\n }\n\n return order;\n }\n\n // ===== Inspection Methods =====\n\n getAllRoutes(): RouteSchema[] {\n return this.allRoutes.map(r => r.schema);\n }\n\n /**\n * Fast-path routes (no middleware/auth/validation/rateLimit/cache) in a shape\n * suitable for registering directly on a native server router (e.g. uWS).\n */\n getNativeFastPathRoutes(): Array<{\n method: string;\n path: string;\n paramNames: string[] | null;\n handler: (req: HttpRequest, res: HttpResponse) => any;\n }> {\n const result: Array<{\n method: string;\n path: string;\n paramNames: string[] | null;\n handler: (req: HttpRequest, res: HttpResponse) => any;\n }> = [];\n for (const route of this.allRoutes) {\n if (!route.isFastPath) continue;\n const path = route.schema.path;\n let paramNames: string[] | null = null;\n if (path.indexOf(':') !== -1) {\n paramNames = [];\n for (const seg of path.split('/')) {\n if (seg.charCodeAt(0) === 58) paramNames.push(seg.slice(1));\n }\n }\n result.push({\n method: route.schema.method,\n path,\n paramNames,\n handler: route.schema.handler,\n });\n }\n return result;\n }\n\n /**\n * Public wrapper around the registered error handler so native fast paths\n * share the exact same error semantics as router-dispatched routes.\n * Returns true if the handler produced a response.\n */\n handleRouteError(err: any, req: HttpRequest, res: HttpResponse): Promise<boolean> {\n return this.invokeErrorHandler(err, req, res);\n }\n\n getRouteCount(): number {\n return this.stats.totalRoutes;\n }\n\n getStats() {\n // Manually build object instead of spread operator\n return {\n totalRoutes: this.stats.totalRoutes,\n staticRoutes: this.stats.staticRoutes,\n dynamicRoutes: this.stats.dynamicRoutes,\n fastPathRoutes: this.stats.fastPathRoutes,\n requestCount: this.stats.requestCount,\n fastPathHits: this.stats.fastPathHits,\n staticHits: this.stats.staticHits,\n dynamicHits: this.stats.dynamicHits,\n cacheHits: this.stats.cacheHits,\n radixHits: this.stats.radixHits,\n poolManager: this.poolManager.getPerformanceSummary(),\n pathMatcher: PathMatcher.getStats(),\n };\n }\n\n logPerformanceStats(): void {\n const stats = this.getStats();\n logger.info('UnifiedRouter Performance', 'Stats', {\n totalRoutes: stats.totalRoutes,\n staticRoutes: stats.staticRoutes,\n dynamicRoutes: stats.dynamicRoutes,\n fastPathRoutes: stats.fastPathRoutes,\n requests: stats.requestCount,\n poolManager: {\n routeCacheHitRate: stats.poolManager.routeCacheHitRate.toFixed(1) + '%',\n responseCacheHitRate: stats.poolManager.responseCacheHitRate.toFixed(1) + '%',\n paramPoolUtilization: stats.poolManager.paramPoolUtilization.toFixed(1) + '%',\n totalMemoryKB: stats.poolManager.totalMemoryKB.toFixed(1) + ' KB',\n },\n });\n }\n}\n"]}
|