@morojs/moro 1.8.5 → 1.8.7

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 +1 @@
1
- {"version":3,"file":"radix-tree.js","sourceRoot":"","sources":["../../../src/core/routing/radix-tree.ts"],"names":[],"mappings":"AAAA,yDAAyD;AAqBzD,yDAAyD;AACzD,SAAS,QAAQ,CAAC,GAAW;IAC3B,IAAI,IAAI,GAAG,UAAU,CAAC,CAAC,mBAAmB;IAC1C,MAAM,GAAG,GAAG,GAAG,CAAC,MAAM,CAAC;IAEvB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,EAAE,EAAE,CAAC;QAC7B,IAAI,IAAI,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;QAC1B,IAAI,GAAG,CAAC,IAAI,GAAG,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,qBAAqB;IACzD,CAAC;IAED,OAAO,IAAI,CAAC;AACd,CAAC;AAED,wEAAwE;AACxE,SAAS,aAAa,CAAC,IAAY,EAAE,KAAa,EAAE,GAAW;IAC7D,IAAI,IAAI,GAAG,UAAU,CAAC;IACtB,KAAK,IAAI,CAAC,GAAG,KAAK,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,EAAE,EAAE,CAAC;QACjC,IAAI,IAAI,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;QAC3B,IAAI,GAAG,CAAC,IAAI,GAAG,UAAU,CAAC,KAAK,CAAC,CAAC;IACnC,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED,mEAAmE;AACnE,SAAS,kBAAkB,CAAC,OAAe,EAAE,IAAY,EAAE,KAAa,EAAE,GAAW;IACnF,IAAI,OAAO,CAAC,MAAM,KAAK,GAAG,GAAG,KAAK;QAAE,OAAO,KAAK,CAAC;IACjD,KAAK,IAAI,CAAC,GAAG,KAAK,EAAE,CAAC,GAAG,GAA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AAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QACpC,OAAO,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;IACzC,CAAC;IAED;;OAEG;IACH,KAAK;QACH,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC;IACrB,CAAC;CACF","sourcesContent":["// High-performance Radix Tree for dynamic route matching\n\nexport interface RadixNode {\n // Store hash for faster lookups\n segmentHash: number;\n segment: string;\n staticChildren: Map<number, RadixNode> | null; // Hash-based lookup\n paramChild: RadixNode | null;\n paramName: string | null;\n handler: any;\n // Store parameter names for this specific handler/route\n paramPath: string[] | null;\n // Sibling chain for FNV hash collisions (segments with equal hash, different text)\n collisionNext: RadixNode | null;\n}\n\nexport interface MatchResult {\n handler: any;\n params: Record<string, string>;\n}\n\n// Fast hash function for path segments (FNV-1a inspired)\nfunction fastHash(str: string): number {\n let hash = 0x811c9dc5; // FNV offset basis\n const len = str.length;\n\n for (let i = 0; i < len; i++) {\n hash ^= str.charCodeAt(i);\n hash = (hash * 0x01000193) >>> 0; // FNV prime (32-bit)\n }\n\n return hash;\n}\n\n// Same hash computed over a path slice without allocating the substring\nfunction fastHashRange(path: string, start: number, end: number): number {\n let hash = 0x811c9dc5;\n for (let i = start; i < end; i++) {\n hash ^= path.charCodeAt(i);\n hash = (hash * 0x01000193) >>> 0;\n }\n return hash;\n}\n\n// Compare a stored segment against a path slice without allocating\nfunction segmentEqualsRange(segment: string, path: string, start: number, end: number): boolean {\n if (segment.length !== end - start) return false;\n for (let i = start; i < end; i++) {\n if (segment.charCodeAt(i - start) !== path.charCodeAt(i)) return false;\n }\n return true;\n}\n\nexport class RadixTree {\n private root: RadixNode;\n\n constructor() {\n this.root = {\n segmentHash: 0,\n segment: '',\n staticChildren: null,\n paramChild: null,\n paramName: null,\n handler: null,\n paramPath: null,\n collisionNext: null,\n };\n }\n\n /**\n * Insert a route into the radix tree - HASH-BASED\n */\n insert(path: string, handler: any): void {\n let node = this.root;\n let i = 0;\n const len = path.length;\n const paramNames: string[] = [];\n\n // Skip leading slash\n if (len > 0 && path.charCodeAt(0) === 47) {\n i = 1;\n }\n\n while (i < len) {\n const charCode = path.charCodeAt(i);\n\n // Skip any additional slashes\n if (charCode === 47) {\n i++;\n continue;\n }\n\n // Check for parameter (58 = ':')\n if (charCode === 58) {\n // Find end of parameter name (47 = '/')\n let end = i + 1;\n while (end < len && path.charCodeAt(end) !== 47) {\n end++;\n }\n\n const paramName = path.slice(i + 1, end);\n paramNames.push(paramName);\n\n // Create param child if needed\n if (!node.paramChild) {\n node.paramChild = {\n segmentHash: 0,\n segment: '',\n staticChildren: null,\n paramChild: null,\n paramName: paramName,\n handler: null,\n paramPath: null,\n collisionNext: null,\n };\n }\n\n node = node.paramChild;\n i = end;\n continue;\n }\n\n // Find end of static segment (up to next '/' or ':')\n let segEnd = i + 1;\n while (segEnd < len) {\n const code = path.charCodeAt(segEnd);\n if (code === 47 || code === 58) break; // '/' or ':'\n segEnd++;\n }\n const segment = path.slice(i, segEnd);\n const segmentHash = fastHash(segment);\n\n // Lazy initialization of staticChildren (hash-based)\n if (!node.staticChildren) {\n node.staticChildren = new Map();\n const child: RadixNode = {\n segmentHash,\n segment,\n staticChildren: null,\n paramChild: null,\n paramName: null,\n handler: null,\n paramPath: null,\n collisionNext: null,\n };\n node.staticChildren.set(segmentHash, child);\n node = child;\n } else {\n let child = node.staticChildren.get(segmentHash);\n if (!child) {\n child = {\n segmentHash,\n segment,\n staticChildren: null,\n paramChild: null,\n paramName: null,\n handler: null,\n paramPath: null,\n collisionNext: null,\n };\n node.staticChildren.set(segmentHash, child);\n } else {\n // FNV hash collision: walk the sibling chain for a true segment match,\n // appending a new node if this exact segment isn't chained yet\n while (child.segment !== segment) {\n if (!child.collisionNext) {\n child.collisionNext = {\n segmentHash,\n segment,\n staticChildren: null,\n paramChild: null,\n paramName: null,\n handler: null,\n paramPath: null,\n collisionNext: null,\n };\n }\n child = child.collisionNext;\n }\n }\n node = child;\n }\n\n i = segEnd;\n }\n\n // Store handler and parameter names for this specific route\n node.handler = handler;\n node.paramPath = paramNames.length > 0 ? paramNames : null;\n }\n\n /**\n * Search for a route in the radix tree - HASH-BASED\n */\n search(path: string): MatchResult | null {\n const paramValues: string[] = [];\n const result = this.searchNode(this.root, path, 0, paramValues);\n\n if (result) {\n // Build params object using stored parameter names from the matched route\n const params: Record<string, string> = {};\n if (result.paramPath) {\n for (let i = 0; i < result.paramPath.length; i++) {\n params[result.paramPath[i] as string] = paramValues[i] as string;\n }\n }\n return { handler: result.handler, params };\n }\n\n return null;\n }\n\n private searchNode(\n node: RadixNode,\n path: string,\n idx: number,\n paramValues: string[]\n ): RadixNode | null {\n const len = path.length;\n\n // Skip slashes\n while (idx < len && path.charCodeAt(idx) === 47) {\n idx++;\n }\n\n // End of path - return node if it has a handler\n if (idx === len) {\n return node.handler ? node : null;\n }\n\n // Try static children first (fastest) - hash-based lookup\n if (node.staticChildren) {\n // Extract current segment and compute hash (until next '/' or end)\n let segEnd = idx;\n const slashCode = 47; // '/'\n while (segEnd < len && path.charCodeAt(segEnd) !== slashCode) {\n segEnd++;\n }\n // Hash and compare in place - no substring allocation per segment\n const segmentHash = fastHashRange(path, idx, segEnd);\n\n // Direct hash lookup (O(1)), walking the collision chain if needed\n let child: RadixNode | null | undefined = node.staticChildren.get(segmentHash);\n while (child && !segmentEqualsRange(child.segment, path, idx, segEnd)) {\n child = child.collisionNext;\n }\n if (child) {\n const result = this.searchNode(child, path, segEnd, paramValues);\n if (result) {\n return result;\n }\n }\n }\n\n // Try parameter child\n if (node.paramChild) {\n // Find end of param value (next '/' or end of path)\n let end = idx;\n const slashCode = 47; // '/'\n while (end < len && path.charCodeAt(end) !== slashCode) {\n end++;\n }\n\n if (end > idx) {\n const paramValue = path.slice(idx, end);\n paramValues.push(paramValue);\n\n const result = this.searchNode(node.paramChild, path, end, paramValues);\n if (result) {\n return result;\n }\n\n // Backtrack if no match\n paramValues.pop();\n }\n }\n\n return null;\n }\n\n /**\n * Clear the tree\n */\n clear(): void {\n this.root = {\n segmentHash: 0,\n segment: '',\n staticChildren: null,\n paramChild: null,\n paramName: null,\n handler: null,\n paramPath: null,\n collisionNext: null,\n };\n }\n}\n\n/**\n * Method-specific radix tree router\n */\nexport class MethodRadixRouter {\n private trees: Map<string, RadixTree>;\n\n constructor() {\n this.trees = new Map();\n }\n\n /**\n * Add a route - OPTIMIZED\n */\n addRoute(method: string, path: string, handler: any): void {\n let tree = this.trees.get(method);\n if (!tree) {\n tree = new RadixTree();\n this.trees.set(method, tree);\n }\n tree.insert(path, handler);\n }\n\n /**\n * Find a route - OPTIMIZED\n */\n findRoute(method: string, path: string): MatchResult | null {\n const tree = this.trees.get(method);\n return tree ? tree.search(path) : null;\n }\n\n /**\n * Clear all routes\n */\n clear(): void {\n this.trees.clear();\n }\n}\n"]}
1
+ {"version":3,"file":"radix-tree.js","sourceRoot":"","sources":["../../../src/core/routing/radix-tree.ts"],"names":[],"mappings":"AAAA,yDAAyD;AAqBzD,yDAAyD;AACzD,SAAS,QAAQ,CAAC,GAAW;IAC3B,IAAI,IAAI,GAAG,UAAU,CAAC,CAAC,mBAAmB;IAC1C,MAAM,GAAG,GAAG,GAAG,CAAC,MAAM,CAAC;IAEvB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,EAAE,EAAE,CAAC;QAC7B,IAAI,IAAI,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;QAC1B,IAAI,GAAG,CAAC,IAAI,GAAG,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,qBAAqB;IACzD,CAAC;IAED,OAAO,IAAI,CAAC;AACd,CAAC;AAED,wEAAwE;AACxE,SAAS,aAAa,CAAC,IAAY,EAAE,KAAa,EAAE,GAAW;IAC7D,IAAI,IAAI,GAAG,UAAU,CAAC;IACtB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ACf,aAAa,EAAE,IAAI;SACpB,CAAC;IACJ,CAAC;CACF;AAED;;GAEG;AACH,MAAM,OAAO,iBAAiB;IACpB,KAAK,CAAyB;IAEtC;QACE,IAAI,CAAC,KAAK,GAAG,IAAI,GAAG,EAAE,CAAC;IACzB,CAAC;IAED;;OAEG;IACH,QAAQ,CAAC,MAAc,EAAE,IAAY,EAAE,OAAY;QACjD,IAAI,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QAClC,IAAI,CAAC,IAAI,EAAE,CAAC;YACV,IAAI,GAAG,IAAI,SAAS,EAAE,CAAC;YACvB,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;QAC/B,CAAC;QACD,IAAI,CAAC,MAAM,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;IAC7B,CAAC;IAED;;OAEG;IACH,SAAS,CAAC,MAAc,EAAE,IAAY;QACpC,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QACpC,OAAO,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;IACzC,CAAC;IAED;;OAEG;IACH,KAAK;QACH,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC;IACrB,CAAC;CACF","sourcesContent":["// High-performance Radix Tree for dynamic route matching\n\nexport interface RadixNode {\n // Store hash for faster lookups\n segmentHash: number;\n segment: string;\n staticChildren: Map<number, RadixNode> | null; // Hash-based lookup\n paramChild: RadixNode | null;\n paramName: string | null;\n handler: any;\n // Store parameter names for this specific handler/route\n paramPath: string[] | null;\n // Sibling chain for FNV hash collisions (segments with equal hash, different text)\n collisionNext: RadixNode | null;\n}\n\nexport interface MatchResult {\n handler: any;\n params: Record<string, string>;\n}\n\n// Fast hash function for path segments (FNV-1a inspired)\nfunction fastHash(str: string): number {\n let hash = 0x811c9dc5; // FNV offset basis\n const len = str.length;\n\n for (let i = 0; i < len; i++) {\n hash ^= str.charCodeAt(i);\n hash = (hash * 0x01000193) >>> 0; // FNV prime (32-bit)\n }\n\n return hash;\n}\n\n// Same hash computed over a path slice without allocating the substring\nfunction fastHashRange(path: string, start: number, end: number): number {\n let hash = 0x811c9dc5;\n for (let i = start; i < end; i++) {\n hash ^= path.charCodeAt(i);\n hash = (hash * 0x01000193) >>> 0;\n }\n return hash;\n}\n\n// Compare a stored segment against a path slice without allocating\nfunction segmentEqualsRange(segment: string, path: string, start: number, end: number): boolean {\n if (segment.length !== end - start) return false;\n for (let i = start; i < end; i++) {\n if (segment.charCodeAt(i - start) !== path.charCodeAt(i)) return false;\n }\n return true;\n}\n\nexport class RadixTree {\n private root: RadixNode;\n // Scratch buffer for search() - see the comment there before touching\n private readonly paramScratch: string[] = [];\n\n constructor() {\n this.root = {\n segmentHash: 0,\n segment: '',\n staticChildren: null,\n paramChild: null,\n paramName: null,\n handler: null,\n paramPath: null,\n collisionNext: null,\n };\n }\n\n /**\n * Insert a route into the radix tree - HASH-BASED\n */\n insert(path: string, handler: any): void {\n let node = this.root;\n let i = 0;\n const len = path.length;\n const paramNames: string[] = [];\n\n // Skip leading slash\n if (len > 0 && path.charCodeAt(0) === 47) {\n i = 1;\n }\n\n while (i < len) {\n const charCode = path.charCodeAt(i);\n\n // Skip any additional slashes\n if (charCode === 47) {\n i++;\n continue;\n }\n\n // Check for parameter (58 = ':')\n if (charCode === 58) {\n // Find end of parameter name (47 = '/')\n let end = i + 1;\n while (end < len && path.charCodeAt(end) !== 47) {\n end++;\n }\n\n const paramName = path.slice(i + 1, end);\n paramNames.push(paramName);\n\n // Create param child if needed\n if (!node.paramChild) {\n node.paramChild = {\n segmentHash: 0,\n segment: '',\n staticChildren: null,\n paramChild: null,\n paramName: paramName,\n handler: null,\n paramPath: null,\n collisionNext: null,\n };\n }\n\n node = node.paramChild;\n i = end;\n continue;\n }\n\n // Find end of static segment (up to next '/' or ':')\n let segEnd = i + 1;\n while (segEnd < len) {\n const code = path.charCodeAt(segEnd);\n if (code === 47 || code === 58) break; // '/' or ':'\n segEnd++;\n }\n const segment = path.slice(i, segEnd);\n const segmentHash = fastHash(segment);\n\n // Lazy initialization of staticChildren (hash-based)\n if (!node.staticChildren) {\n node.staticChildren = new Map();\n const child: RadixNode = {\n segmentHash,\n segment,\n staticChildren: null,\n paramChild: null,\n paramName: null,\n handler: null,\n paramPath: null,\n collisionNext: null,\n };\n node.staticChildren.set(segmentHash, child);\n node = child;\n } else {\n let child = node.staticChildren.get(segmentHash);\n if (!child) {\n child = {\n segmentHash,\n segment,\n staticChildren: null,\n paramChild: null,\n paramName: null,\n handler: null,\n paramPath: null,\n collisionNext: null,\n };\n node.staticChildren.set(segmentHash, child);\n } else {\n // FNV hash collision: walk the sibling chain for a true segment match,\n // appending a new node if this exact segment isn't chained yet\n while (child.segment !== segment) {\n if (!child.collisionNext) {\n child.collisionNext = {\n segmentHash,\n segment,\n staticChildren: null,\n paramChild: null,\n paramName: null,\n handler: null,\n paramPath: null,\n collisionNext: null,\n };\n }\n child = child.collisionNext;\n }\n }\n node = child;\n }\n\n i = segEnd;\n }\n\n // Store handler and parameter names for this specific route\n node.handler = handler;\n node.paramPath = paramNames.length > 0 ? paramNames : null;\n }\n\n /**\n * Search for a route in the radix tree - HASH-BASED\n */\n search(path: string): MatchResult | null {\n // Reused across calls: search is synchronous and the values are copied\n // into the fresh params object below before returning, so nothing escapes\n const paramValues = this.paramScratch;\n paramValues.length = 0;\n const result = this.searchNode(this.root, path, 0, paramValues);\n\n if (result) {\n // Build params object using stored parameter names from the matched route\n const params: Record<string, string> = {};\n if (result.paramPath) {\n for (let i = 0; i < result.paramPath.length; i++) {\n params[result.paramPath[i] as string] = paramValues[i] as string;\n }\n }\n return { handler: result.handler, params };\n }\n\n return null;\n }\n\n private searchNode(\n node: RadixNode,\n path: string,\n idx: number,\n paramValues: string[]\n ): RadixNode | null {\n const len = path.length;\n\n // Skip slashes\n while (idx < len && path.charCodeAt(idx) === 47) {\n idx++;\n }\n\n // End of path - return node if it has a handler\n if (idx === len) {\n return node.handler ? node : null;\n }\n\n // Try static children first (fastest) - hash-based lookup\n if (node.staticChildren) {\n // Extract current segment and compute hash (until next '/' or end)\n let segEnd = idx;\n const slashCode = 47; // '/'\n while (segEnd < len && path.charCodeAt(segEnd) !== slashCode) {\n segEnd++;\n }\n // Hash and compare in place - no substring allocation per segment\n const segmentHash = fastHashRange(path, idx, segEnd);\n\n // Direct hash lookup (O(1)), walking the collision chain if needed\n let child: RadixNode | null | undefined = node.staticChildren.get(segmentHash);\n while (child && !segmentEqualsRange(child.segment, path, idx, segEnd)) {\n child = child.collisionNext;\n }\n if (child) {\n const result = this.searchNode(child, path, segEnd, paramValues);\n if (result) {\n return result;\n }\n }\n }\n\n // Try parameter child\n if (node.paramChild) {\n // Find end of param value (next '/' or end of path)\n let end = idx;\n const slashCode = 47; // '/'\n while (end < len && path.charCodeAt(end) !== slashCode) {\n end++;\n }\n\n if (end > idx) {\n const paramValue = path.slice(idx, end);\n paramValues.push(paramValue);\n\n const result = this.searchNode(node.paramChild, path, end, paramValues);\n if (result) {\n return result;\n }\n\n // Backtrack if no match\n paramValues.pop();\n }\n }\n\n return null;\n }\n\n /**\n * Clear the tree\n */\n clear(): void {\n this.root = {\n segmentHash: 0,\n segment: '',\n staticChildren: null,\n paramChild: null,\n paramName: null,\n handler: null,\n paramPath: null,\n collisionNext: null,\n };\n }\n}\n\n/**\n * Method-specific radix tree router\n */\nexport class MethodRadixRouter {\n private trees: Map<string, RadixTree>;\n\n constructor() {\n this.trees = new Map();\n }\n\n /**\n * Add a route - OPTIMIZED\n */\n addRoute(method: string, path: string, handler: any): void {\n let tree = this.trees.get(method);\n if (!tree) {\n tree = new RadixTree();\n this.trees.set(method, tree);\n }\n tree.insert(path, handler);\n }\n\n /**\n * Find a route - OPTIMIZED\n */\n findRoute(method: string, path: string): MatchResult | null {\n const tree = this.trees.get(method);\n return tree ? tree.search(path) : null;\n }\n\n /**\n * Clear all routes\n */\n clear(): void {\n this.trees.clear();\n }\n}\n"]}
@@ -13,6 +13,9 @@ const logger = createFrameworkLogger('UnifiedRouter');
13
13
  const rateLimitCore = new RateLimitCore();
14
14
  const cacheCore = new CacheCore();
15
15
  const validationCore = new ValidationCore();
16
+ // Canonical uppercase methods - lets dispatch skip toUpperCase for the
17
+ // interned method strings every adapter hands over
18
+ const UPPERCASE_METHODS = new Set(['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS']);
16
19
  // ===== Route Builder (Chainable API) =====
17
20
  export class RouteBuilder {
18
21
  schema;
@@ -40,6 +43,11 @@ export class RouteBuilder {
40
43
  this.schema.validation.params = config.params;
41
44
  if (config.headers !== undefined)
42
45
  this.schema.validation.headers = config.headers;
46
+ // Without this, `.body(schema).validate({ onValidationError })` silently
47
+ // dropped the handler and fell back to the default 400 response.
48
+ if (config.onValidationError !== undefined) {
49
+ this.schema.validation.onValidationError = config.onValidationError;
50
+ }
43
51
  }
44
52
  return this;
45
53
  }
@@ -151,15 +159,18 @@ export class UnifiedRouter {
151
159
  poolManager = ObjectPoolManager.getInstance();
152
160
  // Route storage optimized for different access patterns
153
161
  // OPTIMIZATION: Separate maps per method for faster lookup (no string concat needed)
154
- staticRoutesByMethod = {
155
- GET: new Map(),
156
- POST: new Map(),
157
- PUT: new Map(),
158
- DELETE: new Map(),
159
- PATCH: new Map(),
160
- HEAD: new Map(),
161
- OPTIONS: new Map(),
162
- };
162
+ // Method -> path -> route. A Map (not a plain object) so the per-request
163
+ // lookup keyed by a non-constant method string stays a monomorphic Map.get
164
+ // instead of a megamorphic keyed object load.
165
+ staticRoutesByMethod = new Map([
166
+ ['GET', new Map()],
167
+ ['POST', new Map()],
168
+ ['PUT', new Map()],
169
+ ['DELETE', new Map()],
170
+ ['PATCH', new Map()],
171
+ ['HEAD', new Map()],
172
+ ['OPTIONS', new Map()],
173
+ ]);
163
174
  dynamicRoutesBySegments = new Map(); // Grouped by segment count
164
175
  fastPathRoutes = new Set(); // Routes with no middleware
165
176
  allRoutes = []; // For iteration/inspection
@@ -242,13 +253,8 @@ export class UnifiedRouter {
242
253
  * Clear all routes (useful for testing)
243
254
  */
244
255
  clearAllRoutes() {
245
- this.staticRoutesByMethod.GET.clear();
246
- this.staticRoutesByMethod.POST.clear();
247
- this.staticRoutesByMethod.PUT.clear();
248
- this.staticRoutesByMethod.DELETE.clear();
249
- this.staticRoutesByMethod.PATCH.clear();
250
- this.staticRoutesByMethod.HEAD.clear();
251
- this.staticRoutesByMethod.OPTIONS.clear();
256
+ for (const methodMap of this.staticRoutesByMethod.values())
257
+ methodMap.clear();
252
258
  this.dynamicRoutesBySegments.clear();
253
259
  this.fastPathRoutes.clear();
254
260
  this.allRoutes = [];
@@ -292,6 +298,7 @@ export class UnifiedRouter {
292
298
  const route = {
293
299
  schema,
294
300
  compiledPath: null, // Will be set lazily if needed
301
+ handler: schema.handler,
295
302
  isFastPath,
296
303
  executionOrder,
297
304
  rateLimitConfig: schema.rateLimit,
@@ -301,7 +308,7 @@ export class UnifiedRouter {
301
308
  };
302
309
  // Store in appropriate structures
303
310
  if (isStatic) {
304
- const methodMap = this.staticRoutesByMethod[schema.method];
311
+ const methodMap = this.staticRoutesByMethod.get(schema.method);
305
312
  if (methodMap) {
306
313
  methodMap.set(schema.path, route);
307
314
  }
@@ -439,21 +446,22 @@ export class UnifiedRouter {
439
446
  */
440
447
  handleRequest(req, res) {
441
448
  this.stats.requestCount++;
442
- const method = req.method?.toUpperCase();
449
+ // Adapters hand over interned uppercase method strings - the Set probe
450
+ // skips a per-request toUpperCase call (and its scan) in the common case
451
+ const rawMethod = req.method;
452
+ const method = (rawMethod && UPPERCASE_METHODS.has(rawMethod) ? rawMethod : rawMethod?.toUpperCase());
443
453
  const path = req.path;
444
454
  // FAST PATH 1: Try static route Map lookup first (fastest possible - no string concat)
445
- const methodMap = this.staticRoutesByMethod[method];
455
+ const methodMap = this.staticRoutesByMethod.get(method);
446
456
  if (methodMap) {
447
457
  const staticRoute = methodMap.get(path);
448
458
  if (staticRoute) {
449
- // OPTIMIZATION: Reuse empty params object to avoid allocation
450
- if (!req.params) {
451
- req.params = {};
452
- }
459
+ // (params untouched here: every adapter req initializes params, and
460
+ // the engine adapter materializes it lazily on first handler access)
453
461
  // Fast-path execution (no middleware)
454
462
  if (staticRoute.isFastPath) {
455
463
  try {
456
- const result = staticRoute.schema.handler(req, res);
464
+ const result = staticRoute.handler(req, res);
457
465
  if (result && typeof result.then === 'function') {
458
466
  return result
459
467
  .then(actualResult => {
@@ -502,7 +510,7 @@ export class UnifiedRouter {
502
510
  // Fast-path dynamic routes (no middleware)
503
511
  if (route.isFastPath) {
504
512
  try {
505
- const result = route.schema.handler(req, res);
513
+ const result = route.handler(req, res);
506
514
  if (result && typeof result.then === 'function') {
507
515
  return result
508
516
  .then(actualResult => {
@@ -1 +1 @@
1
- {"version":3,"file":"unified-router.js","sourceRoot":"","sources":["../../../src/core/routing/unified-router.ts"],"names":[],"mappings":"AAAA,mEAAmE;AACnE,sEAAsE;AAEtE,OAAO,EAAE,WAAW,EAAgB,MAAM,mBAAmB,CAAC;AAC9D,OAAO,EAAE,iBAAiB,EAAE,MAAM,mCAAmC,CAAC;AACtE,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAE3D,OAAO,EAAE,aAAa,EAAwB,MAAM,4CAA4C,CAAC;AACjG,OAAO,EAAE,SAAS,EAAoB,MAAM,uCAAuC,CAAC;AACpF,OAAO,EAAE,cAAc,EAAyB,MAAM,4CAA4C,CAAC;AACnG,OAAO,EAAE,WAAW,EAAE,MAAM,wCAAwC,CAAC;AAErE,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAEpD,MAAM,MAAM,GAAG,qBAAqB,CAAC,eAAe,CAAC,CAAC;AAEtD,iDAAiD;AACjD,MAAM,aAAa,GAAG,IAAI,aAAa,EAAE,CA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AK;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}\n\n// Internal route representation\ninterface InternalRoute {\n schema: RouteSchema;\n compiledPath: CompiledPath;\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 }\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 private staticRoutesByMethod = {\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 this.staticRoutesByMethod.GET.clear();\n this.staticRoutesByMethod.POST.clear();\n this.staticRoutesByMethod.PUT.clear();\n this.staticRoutesByMethod.DELETE.clear();\n this.staticRoutesByMethod.PATCH.clear();\n this.staticRoutesByMethod.HEAD.clear();\n this.staticRoutesByMethod.OPTIONS.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 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[schema.method as HttpMethod];\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 const method = req.method?.toUpperCase() 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[method];\n if (methodMap) {\n const staticRoute = methodMap.get(path);\n\n if (staticRoute) {\n // OPTIMIZATION: Reuse empty params object to avoid allocation\n if (!req.params) {\n req.params = {};\n }\n\n // Fast-path execution (no middleware)\n if (staticRoute.isFastPath) {\n try {\n const result = staticRoute.schema.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.schema.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 await this.executeMiddleware(beforeMw[i] as Middleware, req, res);\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 await this.executeMiddleware(route.authMiddleware, req, res);\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 await this.executeMiddleware(transformMw[i] as Middleware, req, res);\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 await this.executeMiddleware(afterMw[i] as Middleware, req, res);\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 await this.executeMiddleware(middleware[i] as Middleware, req, res);\n if (res.headersSent) return;\n }\n break;\n }\n }\n }\n\n private async executeMiddleware(\n middleware: Middleware,\n req: HttpRequest,\n res: HttpResponse\n ): Promise<void> {\n return new Promise((resolve, reject) => {\n let resolved = false;\n\n const next = () => {\n if (!resolved) {\n resolved = true;\n resolve();\n }\n };\n\n try {\n const result = middleware(req, res, next);\n // Duck typing faster than instanceof\n if (result && typeof result.then === 'function') {\n result.then(() => !resolved && next()).catch(reject);\n } else if (!resolved) {\n next();\n }\n } catch (error) {\n if (!resolved) {\n resolved = true;\n reject(error);\n }\n }\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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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}\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 await this.executeMiddleware(beforeMw[i] as Middleware, req, res);\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 await this.executeMiddleware(route.authMiddleware, req, res);\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 await this.executeMiddleware(transformMw[i] as Middleware, req, res);\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 await this.executeMiddleware(afterMw[i] as Middleware, req, res);\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 await this.executeMiddleware(middleware[i] as Middleware, req, res);\n if (res.headersSent) return;\n }\n break;\n }\n }\n }\n\n private async executeMiddleware(\n middleware: Middleware,\n req: HttpRequest,\n res: HttpResponse\n ): Promise<void> {\n return new Promise((resolve, reject) => {\n let resolved = false;\n\n const next = () => {\n if (!resolved) {\n resolved = true;\n resolve();\n }\n };\n\n try {\n const result = middleware(req, res, next);\n // Duck typing faster than instanceof\n if (result && typeof result.then === 'function') {\n result.then(() => !resolved && next()).catch(reject);\n } else if (!resolved) {\n next();\n }\n } catch (error) {\n if (!resolved) {\n resolved = true;\n reject(error);\n }\n }\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"]}
@@ -16,6 +16,7 @@ export declare class HookManager extends EventEmitter {
16
16
  private executeCache;
17
17
  private hookSyncStatus;
18
18
  private activeEvents;
19
+ private hotEvents;
19
20
  constructor();
20
21
  private updateExecuteCache;
21
22
  private areHooksSynchronous;
@@ -23,6 +24,7 @@ export declare class HookManager extends EventEmitter {
23
24
  before(event: string, fn: HookFunction): this;
24
25
  after(event: string, fn: HookFunction): this;
25
26
  hasHooks(event: string): boolean;
27
+ private refreshHotEvent;
26
28
  execute(event: string, context?: HookContext): Promise<HookContext>;
27
29
  private executeHook;
28
30
  removeHook(event: string, fn?: HookFunction): this;
@@ -26,6 +26,10 @@ export class HookManager extends EventEmitter {
26
26
  // Events that currently have at least one hook registered - lets callers skip
27
27
  // execute() entirely (no context object, no promise) when nothing is registered
28
28
  activeEvents = new Set();
29
+ // Exact union of activeEvents and events with raw EventEmitter listeners,
30
+ // maintained on every registration change so the per-request hasHooks()
31
+ // check is a single Set probe instead of Set + listenerCount lookups
32
+ hotEvents = new Set();
29
33
  constructor() {
30
34
  super();
31
35
  // Initialize hook arrays
@@ -41,6 +45,17 @@ export class HookManager extends EventEmitter {
41
45
  // Initialize with noop functions
42
46
  this.updateExecuteCache(event);
43
47
  }
48
+ // Raw EventEmitter listeners count toward hasHooks(); track additions and
49
+ // removals so hotEvents stays the exact union ('newListener' fires just
50
+ // before the listener lands, 'removeListener' just after removal)
51
+ this.on('newListener', (event) => {
52
+ if (typeof event === 'string')
53
+ this.hotEvents.add(event);
54
+ });
55
+ this.on('removeListener', (event) => {
56
+ if (typeof event === 'string')
57
+ this.refreshHotEvent(event);
58
+ });
44
59
  }
45
60
  // Update cached execute function for an event
46
61
  updateExecuteCache(event) {
@@ -52,9 +67,11 @@ export class HookManager extends EventEmitter {
52
67
  this.executeCache.set(event, async (context) => context);
53
68
  this.hookSyncStatus.set(event, true); // Mark as sync (noop)
54
69
  this.activeEvents.delete(event);
70
+ this.refreshHotEvent(event);
55
71
  return;
56
72
  }
57
73
  this.activeEvents.add(event);
74
+ this.hotEvents.add(event);
58
75
  // Detect if all hooks are synchronous
59
76
  const allSync = this.areHooksSynchronous(beforeHooks, hooks, afterHooks);
60
77
  this.hookSyncStatus.set(event, allSync);
@@ -233,9 +250,18 @@ export class HookManager extends EventEmitter {
233
250
  // O(1) check that lets hot paths skip execute() (and its context/promise
234
251
  // allocation) entirely when no hooks are registered for an event.
235
252
  // Note: EventEmitter listeners attached via .on(event) also count, since the
236
- // cached executors emit the event after running hooks.
253
+ // cached executors emit the event after running hooks. hotEvents is kept as
254
+ // the exact union of both sources, so this is one Set probe.
237
255
  hasHooks(event) {
238
- return this.activeEvents.has(event) || this.listenerCount(event) > 0;
256
+ return this.hotEvents.has(event);
257
+ }
258
+ refreshHotEvent(event) {
259
+ if (this.activeEvents.has(event) || this.listenerCount(event) > 0) {
260
+ this.hotEvents.add(event);
261
+ }
262
+ else {
263
+ this.hotEvents.delete(event);
264
+ }
239
265
  }
240
266
  // Execute hooks for an event - optimized with cached functions
241
267
  async execute(event, context = {}) {