@morojs/moro 1.8.10 → 1.8.11

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.
@@ -1,5 +1,7 @@
1
1
  import { ValidationSchema } from '../validation/schema-interface.js';
2
2
  import { HttpRequest, HttpResponse } from '../http/index.js';
3
+ import { type StaticBody, type StaticResponse } from './unified-router.js';
4
+ export type { StaticBody, StaticResponse };
3
5
  export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS';
4
6
  export type RouteHandler<T = any> = (req: HttpRequest, res: HttpResponse) => T | Promise<T>;
5
7
  export type Middleware = (req: HttpRequest, res: HttpResponse, next: () => void) => void | Promise<void>;
@@ -41,6 +43,8 @@ export interface RouteSchema {
41
43
  middleware?: MiddlewarePhases;
42
44
  description?: string;
43
45
  tags?: string[];
46
+ /** Fixed reply of a literal handler; see StaticResponse */
47
+ static?: StaticResponse;
44
48
  }
45
49
  export declare const EXECUTION_PHASES: readonly ["security", "parsing", "rateLimit", "before", "auth", "validation", "transform", "cache", "after", "handler"];
46
50
  export type ExecutionPhase = (typeof EXECUTION_PHASES)[number];
@@ -66,7 +70,10 @@ export interface RouteBuilder {
66
70
  use(...middleware: Middleware[]): RouteBuilder;
67
71
  describe(description: string): RouteBuilder;
68
72
  tag(...tags: string[]): RouteBuilder;
69
- handler<T>(handler: RouteHandler<T>): void;
73
+ /** Terminal. A function handles the request; a string or Buffer IS the
74
+ * response body (as res.send would send it), and on a route with nothing
75
+ * else configured Moro's native engine answers it without calling JS. */
76
+ handler<T>(handler: RouteHandler<T> | StaticBody): void;
70
77
  }
71
78
  export interface CompiledRoute {
72
79
  schema: RouteSchema;
@@ -94,7 +101,7 @@ export declare class IntelligentRouteBuilder implements RouteBuilder {
94
101
  use(...middleware: Middleware[]): RouteBuilder;
95
102
  describe(description: string): RouteBuilder;
96
103
  tag(...tags: string[]): RouteBuilder;
97
- handler<T>(handler: RouteHandler<T>): void;
104
+ handler<T>(handler: RouteHandler<T> | StaticBody): void;
98
105
  }
99
106
  /**
100
107
  * Thin facade implementing CompiledRoute interface
@@ -3,7 +3,7 @@
3
3
  //
4
4
  // NOTE: This file exports types and thin facades to UnifiedRouter
5
5
  // All routing logic has been consolidated in unified-router.ts
6
- import { UnifiedRouter } from './unified-router.js';
6
+ import { UnifiedRouter, compileStaticRoute, } from './unified-router.js';
7
7
  export const EXECUTION_PHASES = [
8
8
  'security',
9
9
  'parsing',
@@ -137,13 +137,18 @@ export class IntelligentRouteBuilder {
137
137
  return this;
138
138
  }
139
139
  handler(handler) {
140
- if (!handler) {
141
- throw new Error('Handler is required');
140
+ if (typeof handler === 'function') {
141
+ // Avoid spread operator - add handler directly
142
+ this.schema.handler = handler;
143
+ // Delegate to UnifiedRouter
144
+ this.router.registerRoute(this.schema);
145
+ return;
142
146
  }
143
- // Avoid spread operator - add handler directly
144
- this.schema.handler = handler;
145
- // Delegate to UnifiedRouter
146
- this.router.registerRoute(this.schema);
147
+ if (typeof handler === 'string' || Buffer.isBuffer(handler)) {
148
+ this.router.registerRoute(compileStaticRoute(this.schema, handler));
149
+ return;
150
+ }
151
+ throw new Error('Handler is required: a function, or the response body as a string or Buffer');
147
152
  }
148
153
  }
149
154
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/core/routing/index.ts"],"names":[],"mappings":"AAAA,gDAAgD;AAChD,oEAAoE;AACpE,EAAE;AACF,kEAAkE;AAClE,+DAA+D;AAI/D,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAyDpD,MAAM,CAAC,MAAM,gBAAgB,GAAG;IAC9B,UAAU;IACV,SAAS;IACT,WAAW;IACX,QAAQ;IACR,MAAM;IACN,YAAY;IACZ,WAAW;IACX,OAAO;IACP,OAAO;IACP,SAAS;CACD,CAAC;AAuCX,iEAAiE;AAEjE;;;GAGG;AACH,MAAM,OAAO,uBAAuB;IAC1B,MAAM,CA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,CAAC;CACF;AAED,yDAAyD;AAEzD,MAAM,UAAU,WAAW,CAAC,MAAkB,EAAE,IAAY;IAC1D,OAAO,IAAI,uBAAuB,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;AACnD,CAAC;AAED,MAAM,UAAU,WAAW,CAAC,MAAmB;IAC7C,OAAO,IAAI,eAAe,CAAC,MAAM,CAAC,CAAC;AACrC,CAAC;AAED,6CAA6C;AAE7C,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,YAAY,IAAI,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAC1E,OAAO,EAAE,WAAW,EAAuC,MAAM,mBAAmB,CAAC;AACrF,OAAO,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,mCAAmC,CAAC","sourcesContent":["// Intelligent Routing System for Moro Framework\n// Schema-first with automatic middleware ordering and chainable API\n//\n// NOTE: This file exports types and thin facades to UnifiedRouter\n// All routing logic has been consolidated in unified-router.ts\n\nimport { ValidationSchema } from '../validation/schema-interface.js';\nimport { HttpRequest, HttpResponse } from '../http/index.js';\nimport { UnifiedRouter } from './unified-router.js';\n\n// ===== TYPE EXPORTS (Keep all - used by app code) =====\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 ValidationConfig {\n body?: ValidationSchema;\n query?: ValidationSchema;\n params?: ValidationSchema;\n headers?: ValidationSchema;\n}\n\nexport interface AuthConfig {\n roles?: string[];\n permissions?: string[];\n optional?: boolean;\n}\n\nexport interface RateLimitConfig {\n requests: number;\n window: number;\n skipSuccessfulRequests?: boolean;\n skipFailedRequests?: boolean;\n}\n\nexport interface CacheConfig {\n ttl: number;\n key?: string;\n tags?: string[];\n}\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 handler: RouteHandler;\n validation?: ValidationConfig;\n auth?: AuthConfig;\n rateLimit?: RateLimitConfig;\n cache?: CacheConfig;\n middleware?: MiddlewarePhases;\n description?: string;\n tags?: string[];\n}\n\nexport const EXECUTION_PHASES = [\n 'security',\n 'parsing',\n 'rateLimit',\n 'before',\n 'auth',\n 'validation',\n 'transform',\n 'cache',\n 'after',\n 'handler',\n] as const;\n\nexport type ExecutionPhase = (typeof EXECUTION_PHASES)[number];\n\nexport interface ValidatedRequest<T = any> extends HttpRequest {\n validatedBody?: T;\n validatedQuery?: any;\n validatedParams?: any;\n validatedHeaders?: any;\n user?: any;\n}\n\n// ===== ROUTE BUILDER INTERFACE (Public API) =====\n\nexport interface RouteBuilder {\n validate(config: ValidationConfig): RouteBuilder;\n body<T>(schema: ValidationSchema<T>): RouteBuilder;\n query<T>(schema: ValidationSchema<T>): RouteBuilder;\n params<T>(schema: ValidationSchema<T>): RouteBuilder;\n headers<T>(schema: ValidationSchema<T>): RouteBuilder;\n auth(config: AuthConfig): RouteBuilder;\n rateLimit(config: RateLimitConfig): RouteBuilder;\n cache(config: CacheConfig): RouteBuilder;\n before(...middleware: Middleware[]): RouteBuilder;\n after(...middleware: Middleware[]): RouteBuilder;\n transform(...middleware: Middleware[]): RouteBuilder;\n use(...middleware: Middleware[]): RouteBuilder;\n describe(description: string): RouteBuilder;\n tag(...tags: string[]): RouteBuilder;\n handler<T>(handler: RouteHandler<T>): void;\n}\n\n// ===== COMPILED ROUTE INTERFACE (Public API) =====\n\nexport interface CompiledRoute {\n schema: RouteSchema;\n execute(req: HttpRequest, res: HttpResponse): Promise<void>;\n}\n\n// ===== FACADE IMPLEMENTATIONS (Delegate to UnifiedRouter) =====\n\n/**\n * Thin facade to UnifiedRouter.RouteBuilder\n * Maintains backward compatibility while using optimized implementation\n */\nexport class IntelligentRouteBuilder implements RouteBuilder {\n private schema: Partial<RouteSchema>;\n private router = UnifiedRouter.getInstance();\n\n constructor(method: HttpMethod, path: string) {\n this.schema = {\n method,\n path,\n middleware: {} as MiddlewarePhases,\n };\n }\n\n validate(config: ValidationConfig): RouteBuilder {\n // Avoid spread operator - 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 }\n return this;\n }\n\n body<T>(schema: ValidationSchema<T>): RouteBuilder {\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>): RouteBuilder {\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>): RouteBuilder {\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>): RouteBuilder {\n if (!this.schema.validation) this.schema.validation = {};\n this.schema.validation.headers = schema;\n return this;\n }\n\n auth(config: AuthConfig): RouteBuilder {\n this.schema.auth = config;\n return this;\n }\n\n rateLimit(config: RateLimitConfig): RouteBuilder {\n this.schema.rateLimit = config;\n return this;\n }\n\n cache(config: CacheConfig): RouteBuilder {\n this.schema.cache = config;\n return this;\n }\n\n before(...middleware: Middleware[]): RouteBuilder {\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[]): RouteBuilder {\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[]): RouteBuilder {\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[]): RouteBuilder {\n return this.after(...middleware);\n }\n\n describe(description: string): RouteBuilder {\n this.schema.description = description;\n return this;\n }\n\n tag(...tags: string[]): RouteBuilder {\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 handler<T>(handler: RouteHandler<T>): void {\n if (!handler) {\n throw new Error('Handler is required');\n }\n\n // Avoid spread operator - add handler directly\n this.schema.handler = handler;\n\n // Delegate to UnifiedRouter\n this.router.registerRoute(this.schema as RouteSchema);\n }\n}\n\n/**\n * Thin facade implementing CompiledRoute interface\n * Just stores schema for documentation purposes\n */\nexport class ExecutableRoute implements CompiledRoute {\n constructor(public readonly schema: RouteSchema) {\n // Register with UnifiedRouter\n UnifiedRouter.getInstance().registerRoute(schema);\n }\n\n async execute(_req: HttpRequest, _res: HttpResponse): Promise<void> {\n // This is never called - UnifiedRouter handles execution\n // But we implement it for interface compatibility\n throw new Error(\n 'ExecutableRoute.execute() should not be called directly - routing handled by UnifiedRouter'\n );\n }\n}\n\n// ===== FACTORY FUNCTIONS (Backward Compatibility) =====\n\nexport function createRoute(method: HttpMethod, path: string): RouteBuilder {\n return new IntelligentRouteBuilder(method, path);\n}\n\nexport function defineRoute(schema: RouteSchema): CompiledRoute {\n return new ExecutableRoute(schema);\n}\n\n// ===== RE-EXPORTS FROM UNIFIED ROUTER =====\n\nexport { UnifiedRouter } from './unified-router.js';\nexport { RouteBuilder as UnifiedRouteBuilder } from './unified-router.js';\nexport { PathMatcher, type CompiledPath, type MatchResult } from './path-matcher.js';\nexport { ObjectPoolManager, getPoolManager } from '../pooling/object-pool-manager.js';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/core/routing/index.ts"],"names":[],"mappings":"AAAA,gDAAgD;AAChD,oEAAoE;AACpE,EAAE;AACF,kEAAkE;AAClE,+DAA+D;AAI/D,OAAO,EACL,aAAa,EACb,kBAAkB,GAInB,MAAM,qBAAqB,CAAC;AA6D7B,MAAM,CAAC,MAAM,gBAAgB,GAAG;IAC9B,UAAU;IACV,SAAS;IACT,WAAW;IACX,QAAQ;IACR,MAAM;IACN,YAAY;IACZ,WAAW;IACX,OAAO;IACP,OAAO;IACP,SAAS;CACD,CAAC;AA0CX,iEAAiE;AAEjE;;;GAGG;AACH,MAAM,OAAO,uBAAuB;IAC1B,MAAM,CAAuB;IAC7B,MAAM,GAAG,aAAa,CAAC,WAAW,EAAE,CAAC;IAE7C,YAAY,MAAkB,EAAE,IAAY;QAC1C,IAAI,CAAC,MAAM,GAAG;YACZ,MAAM;YACN,IAAI;YACJ,UAAU,EAAE,EAAsB;SACnC,CAAC;IACJ,CAAC;IAED,QAAQ,CAAC,MAAwB;QAC/B,oDAAoD;QACpD,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,UAAU,EAAE,CAAC;YAC5B,IAAI,CAAC,MAAM,CAAC,UAAU,GAAG,MAAM,CAAC;QAClC,CAAC;aAAM,CAAC;YACN,IAAI,MAAM,CAAC,IAAI,KAAK,SAAS;gBAAE,IAAI,CAAC,MAAM,CAAC,UAAU,CAAC,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC;YACzE,IAAI,MAAM,CAAC,KAAK,KAAK,SAAS;gBAAE,IAAI,CAAC,MAAM,CAAC,UAAU,CAAC,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC;YAC5E,IAAI,MAAM,CAAC,MAAM,KAAK,SAAS;gBAAE,IAAI,C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B,CAAC;AACrF,OAAO,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,mCAAmC,CAAC","sourcesContent":["// Intelligent Routing System for Moro Framework\n// Schema-first with automatic middleware ordering and chainable API\n//\n// NOTE: This file exports types and thin facades to UnifiedRouter\n// All routing logic has been consolidated in unified-router.ts\n\nimport { ValidationSchema } from '../validation/schema-interface.js';\nimport { HttpRequest, HttpResponse } from '../http/index.js';\nimport {\n UnifiedRouter,\n compileStaticRoute,\n type RouteSchema as UnifiedRouteSchema,\n type StaticBody,\n type StaticResponse,\n} from './unified-router.js';\n\nexport type { StaticBody, StaticResponse };\n\n// ===== TYPE EXPORTS (Keep all - used by app code) =====\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 ValidationConfig {\n body?: ValidationSchema;\n query?: ValidationSchema;\n params?: ValidationSchema;\n headers?: ValidationSchema;\n}\n\nexport interface AuthConfig {\n roles?: string[];\n permissions?: string[];\n optional?: boolean;\n}\n\nexport interface RateLimitConfig {\n requests: number;\n window: number;\n skipSuccessfulRequests?: boolean;\n skipFailedRequests?: boolean;\n}\n\nexport interface CacheConfig {\n ttl: number;\n key?: string;\n tags?: string[];\n}\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 handler: RouteHandler;\n validation?: ValidationConfig;\n auth?: AuthConfig;\n rateLimit?: RateLimitConfig;\n cache?: CacheConfig;\n middleware?: MiddlewarePhases;\n description?: string;\n tags?: string[];\n /** Fixed reply of a literal handler; see StaticResponse */\n static?: StaticResponse;\n}\n\nexport const EXECUTION_PHASES = [\n 'security',\n 'parsing',\n 'rateLimit',\n 'before',\n 'auth',\n 'validation',\n 'transform',\n 'cache',\n 'after',\n 'handler',\n] as const;\n\nexport type ExecutionPhase = (typeof EXECUTION_PHASES)[number];\n\nexport interface ValidatedRequest<T = any> extends HttpRequest {\n validatedBody?: T;\n validatedQuery?: any;\n validatedParams?: any;\n validatedHeaders?: any;\n user?: any;\n}\n\n// ===== ROUTE BUILDER INTERFACE (Public API) =====\n\nexport interface RouteBuilder {\n validate(config: ValidationConfig): RouteBuilder;\n body<T>(schema: ValidationSchema<T>): RouteBuilder;\n query<T>(schema: ValidationSchema<T>): RouteBuilder;\n params<T>(schema: ValidationSchema<T>): RouteBuilder;\n headers<T>(schema: ValidationSchema<T>): RouteBuilder;\n auth(config: AuthConfig): RouteBuilder;\n rateLimit(config: RateLimitConfig): RouteBuilder;\n cache(config: CacheConfig): RouteBuilder;\n before(...middleware: Middleware[]): RouteBuilder;\n after(...middleware: Middleware[]): RouteBuilder;\n transform(...middleware: Middleware[]): RouteBuilder;\n use(...middleware: Middleware[]): RouteBuilder;\n describe(description: string): RouteBuilder;\n tag(...tags: string[]): RouteBuilder;\n /** Terminal. A function handles the request; a string or Buffer IS the\n * response body (as res.send would send it), and on a route with nothing\n * else configured Moro's native engine answers it without calling JS. */\n handler<T>(handler: RouteHandler<T> | StaticBody): void;\n}\n\n// ===== COMPILED ROUTE INTERFACE (Public API) =====\n\nexport interface CompiledRoute {\n schema: RouteSchema;\n execute(req: HttpRequest, res: HttpResponse): Promise<void>;\n}\n\n// ===== FACADE IMPLEMENTATIONS (Delegate to UnifiedRouter) =====\n\n/**\n * Thin facade to UnifiedRouter.RouteBuilder\n * Maintains backward compatibility while using optimized implementation\n */\nexport class IntelligentRouteBuilder implements RouteBuilder {\n private schema: Partial<RouteSchema>;\n private router = UnifiedRouter.getInstance();\n\n constructor(method: HttpMethod, path: string) {\n this.schema = {\n method,\n path,\n middleware: {} as MiddlewarePhases,\n };\n }\n\n validate(config: ValidationConfig): RouteBuilder {\n // Avoid spread operator - 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 }\n return this;\n }\n\n body<T>(schema: ValidationSchema<T>): RouteBuilder {\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>): RouteBuilder {\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>): RouteBuilder {\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>): RouteBuilder {\n if (!this.schema.validation) this.schema.validation = {};\n this.schema.validation.headers = schema;\n return this;\n }\n\n auth(config: AuthConfig): RouteBuilder {\n this.schema.auth = config;\n return this;\n }\n\n rateLimit(config: RateLimitConfig): RouteBuilder {\n this.schema.rateLimit = config;\n return this;\n }\n\n cache(config: CacheConfig): RouteBuilder {\n this.schema.cache = config;\n return this;\n }\n\n before(...middleware: Middleware[]): RouteBuilder {\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[]): RouteBuilder {\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[]): RouteBuilder {\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[]): RouteBuilder {\n return this.after(...middleware);\n }\n\n describe(description: string): RouteBuilder {\n this.schema.description = description;\n return this;\n }\n\n tag(...tags: string[]): RouteBuilder {\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 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\n // Delegate to UnifiedRouter\n this.router.registerRoute(this.schema as RouteSchema);\n return;\n }\n if (typeof handler === 'string' || Buffer.isBuffer(handler)) {\n this.router.registerRoute(\n compileStaticRoute(this.schema as Partial<UnifiedRouteSchema>, handler)\n );\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/**\n * Thin facade implementing CompiledRoute interface\n * Just stores schema for documentation purposes\n */\nexport class ExecutableRoute implements CompiledRoute {\n constructor(public readonly schema: RouteSchema) {\n // Register with UnifiedRouter\n UnifiedRouter.getInstance().registerRoute(schema);\n }\n\n async execute(_req: HttpRequest, _res: HttpResponse): Promise<void> {\n // This is never called - UnifiedRouter handles execution\n // But we implement it for interface compatibility\n throw new Error(\n 'ExecutableRoute.execute() should not be called directly - routing handled by UnifiedRouter'\n );\n }\n}\n\n// ===== FACTORY FUNCTIONS (Backward Compatibility) =====\n\nexport function createRoute(method: HttpMethod, path: string): RouteBuilder {\n return new IntelligentRouteBuilder(method, path);\n}\n\nexport function defineRoute(schema: RouteSchema): CompiledRoute {\n return new ExecutableRoute(schema);\n}\n\n// ===== RE-EXPORTS FROM UNIFIED ROUTER =====\n\nexport { UnifiedRouter } from './unified-router.js';\nexport { RouteBuilder as UnifiedRouteBuilder } from './unified-router.js';\nexport { PathMatcher, type CompiledPath, type MatchResult } from './path-matcher.js';\nexport { ObjectPoolManager, getPoolManager } from '../pooling/object-pool-manager.js';\n"]}
@@ -28,7 +28,31 @@ export interface RouteSchema {
28
28
  middleware?: MiddlewarePhases | Middleware[];
29
29
  description?: string;
30
30
  tags?: string[];
31
+ /** Fixed reply of a literal handler. A server that can answer it
32
+ * natively (MoroEngineServer on @morojs/engine >= 1.1.6) does so without
33
+ * calling into JS; every other server runs `handler`, which sends the
34
+ * same bytes. */
35
+ static?: StaticResponse;
31
36
  }
37
+ /** The reply a literal handler sends, in the engine's shape. */
38
+ export interface StaticResponse {
39
+ status: number;
40
+ /** [name, value, name, value, ...], or null for no headers at all */
41
+ headers: string[] | null;
42
+ body: string | Buffer | null;
43
+ }
44
+ /** What .handler() accepts in place of a function: the response body itself. */
45
+ export type StaticBody = string | Buffer;
46
+ /**
47
+ * A literal body in place of a handler: the route answers with exactly that
48
+ * body, as res.send(body) would (status 200, the implied content-type). When
49
+ * nothing else is configured on the route - no auth, validation, rate limit,
50
+ * cache or middleware, and a literal path - the schema also carries `static`,
51
+ * so a server that can answer it natively does so without calling into JS.
52
+ * Anything configured keeps the route on the normal pipeline, where the
53
+ * handler sends the same bytes after that configuration has run.
54
+ */
55
+ export declare function compileStaticRoute(schema: Partial<RouteSchema>, body: StaticBody): RouteSchema;
32
56
  export declare class RouteBuilder {
33
57
  private schema;
34
58
  private router;
@@ -47,7 +71,7 @@ export declare class RouteBuilder {
47
71
  use(...middleware: Middleware[]): this;
48
72
  describe(description: string): this;
49
73
  tag(...tags: string[]): this;
50
- handler<T>(handler: RouteHandler<T>): void;
74
+ handler<T>(handler: RouteHandler<T> | StaticBody): void;
51
75
  }
52
76
  export declare class UnifiedRouter {
53
77
  private static instance;
@@ -13,6 +13,51 @@ const logger = createFrameworkLogger('UnifiedRouter');
13
13
  const rateLimitCore = new RateLimitCore();
14
14
  const cacheCore = new CacheCore();
15
15
  const validationCore = new ValidationCore();
16
+ // The content-type res.send() implies for a body it was given no header for:
17
+ // the same three cases MoroEngineServer's send() picks a template by, spelled
18
+ // out here so an engine-answered reply carries the bytes send() would have.
19
+ const STATIC_JSON_START = /^\s*[{[]/;
20
+ function impliedContentType(body) {
21
+ if (typeof body !== 'string')
22
+ return 'application/octet-stream';
23
+ return STATIC_JSON_START.test(body)
24
+ ? 'application/json; charset=utf-8'
25
+ : 'text/plain; charset=utf-8';
26
+ }
27
+ /**
28
+ * A literal body in place of a handler: the route answers with exactly that
29
+ * body, as res.send(body) would (status 200, the implied content-type). When
30
+ * nothing else is configured on the route - no auth, validation, rate limit,
31
+ * cache or middleware, and a literal path - the schema also carries `static`,
32
+ * so a server that can answer it natively does so without calling into JS.
33
+ * Anything configured keeps the route on the normal pipeline, where the
34
+ * handler sends the same bytes after that configuration has run.
35
+ */
36
+ export function compileStaticRoute(schema, body) {
37
+ schema.handler = (_req, res) => {
38
+ res.send(body);
39
+ };
40
+ const path = schema.path ?? '';
41
+ const mw = schema.middleware;
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;
56
+ if (bare) {
57
+ schema.static = { status: 200, headers: ['content-type', impliedContentType(body)], body };
58
+ }
59
+ return schema;
60
+ }
16
61
  // Canonical uppercase methods - lets dispatch skip toUpperCase for the
17
62
  // interned method strings every adapter hands over
18
63
  const UPPERCASE_METHODS = new Set(['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS']);
@@ -143,14 +188,20 @@ export class RouteBuilder {
143
188
  }
144
189
  return this;
145
190
  }
146
- // Terminal method
191
+ // Terminal method: a function, or the response body itself (see
192
+ // compileStaticRoute for what a literal body means).
147
193
  handler(handler) {
148
- if (!handler) {
149
- throw new Error('Handler is required');
194
+ if (typeof handler === 'function') {
195
+ // Avoid spread operator - add handler directly
196
+ this.schema.handler = handler;
197
+ this.router.registerRoute(this.schema);
198
+ return;
150
199
  }
151
- // Avoid spread operator - add handler directly
152
- this.schema.handler = handler;
153
- this.router.registerRoute(this.schema);
200
+ if (typeof handler === 'string' || Buffer.isBuffer(handler)) {
201
+ this.router.registerRoute(compileStaticRoute(this.schema, handler));
202
+ return;
203
+ }
204
+ throw new Error('Handler is required: a function, or the response body as a string or Buffer');
154
205
  }
155
206
  }
156
207
  // ===== Unified Router =====
@@ -278,6 +329,18 @@ export class UnifiedRouter {
278
329
  * Register a route (internal method) - OPTIMIZED
279
330
  */
280
331
  registerRoute(schema) {
332
+ // A literal body in place of a handler (see compileStaticRoute). Every
333
+ // entry point lands here - the builder, app.get(path, body), route(schema)
334
+ // - so this is where the body becomes a handler and, on a bare route, a
335
+ // reply the native engine can answer itself.
336
+ if (typeof schema.handler !== 'function') {
337
+ const body = schema.handler;
338
+ if (typeof body !== 'string' && !Buffer.isBuffer(body)) {
339
+ throw new Error(`Handler for ${schema.method} ${schema.path} must be a function, ` +
340
+ 'or the response body as a string or Buffer');
341
+ }
342
+ compileStaticRoute(schema, body);
343
+ }
281
344
  // OPTIMIZATION: Skip PathMatcher.compile for better performance
282
345
  // Determine if static route (optimized check)
283
346
  const pathLen = schema.path.length;
@@ -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,MA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- 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 handler: RouteHandler;\n validation?: ValidationConfig;\n auth?: AuthConfig;\n rateLimit?: RateLimitConfig;\n cache?: CacheConfig;\n middleware?: MiddlewarePhases | Middleware[];\n description?: string;\n tags?: string[];\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: RouteSchema;\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: RouteSchema['handler'];\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\n handler<T>(handler: RouteHandler<T>): void {\n if (!handler) {\n throw new Error('Handler is required');\n }\n\n // Avoid spread operator - add handler directly\n this.schema.handler = handler;\n this.router.registerRoute(this.schema as RouteSchema);\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 // 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,\n compiledPath: null as any, // Will be set lazily if needed\n handler: schema.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,\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,"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,MA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AU;YACjC,WAAW,EAAE,IAAI,CAAC,KAAK,CAAC,WAAW;YACnC,SAAS,EAAE,IAAI,CAAC,KAAK,CAAC,SAAS;YAC/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 handler: RouteHandler;\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// 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: RouteSchema;\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: RouteSchema['handler'];\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\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,\n compiledPath: null as any, // Will be set lazily if needed\n handler: schema.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,\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"]}
@@ -58,9 +58,10 @@ export interface EngineCapabilities {
58
58
  responseLimits: boolean;
59
59
  /** ssl.ciphers / ssl.ciphersuites / ssl.ecdhCurve are parsed. */
60
60
  tlsPolicy: boolean;
61
- /** setStaticRoute()/clearStaticRoutes() exist (not used by the framework:
62
- * a static route bypasses middleware and hooks, so exposing it is an API
63
- * decision, not an adapter one). */
61
+ /** setStaticRoute()/clearStaticRoutes() exist. Used for a literal body
62
+ * given to the route builder's .handler() when the route has nothing
63
+ * else configured, because a static route bypasses middleware, hooks,
64
+ * auth and validation by design. */
64
65
  staticRoutes: boolean;
65
66
  /** prepareResponse()/respondPrepared()/respondPreparedEmpty()/endWith()
66
67
  * exist (engine >= 1.1.6): the adapter replays prepared header blocks for