@morojs/moro 1.8.4 → 1.8.6

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":"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,CAAC;AAC1C,MAAM,SAAS,GAAG,IAAI,SAAS,EAAE,CAAC;AAClC,MAAM,cAAc,GAAG,IAAI,cAAc,EAAE,CAAC;AAqD5C,4CAA4C;AAE5C,MAAM,OAAO,YAAY;IACf,MAAM,CAAuB;IAC7B,MAAM,CAAgB;IAE9B,YAAY,MAAkB,EAAE,IAAY,EAAE,MAAqB;QACjE,IAAI,CAAC,MAAM,GAAG;YACZ,MAAM;YACN,IAAI;YACJ,UAAU,EAAE,EAAsB;SACnC,CAAC;QACF,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;IAED,qBAAqB;IACrB,QAAQ,CAAC,MAAwB;QAC/B,sEAAsE;QACtE,IAAI,CAAC,IAAI,CAAC,MAAM,CAA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AC,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// 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 setErrorHandler(fn: (err: any, req: HttpRequest, res: HttpResponse) => any | Promise<any>): void {\n this.errorHandler = fn;\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 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 });\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,MAAM,4CAA4C,CAAC;AACjG,OAAO,EAAE,SAAS,EAAoB,MAAM,uCA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,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// 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 // 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 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 });\n }\n}\n"]}
@@ -1,10 +1,11 @@
1
1
  import { EventEmitter } from 'events';
2
2
  import { HookFunction, HookContext } from '../../types/hooks.js';
3
3
  export declare const HOOK_EVENTS: {
4
- readonly BEFORE_REQUEST: "before:request";
5
- readonly AFTER_REQUEST: "after:request";
6
- readonly BEFORE_RESPONSE: "before:response";
7
- readonly AFTER_RESPONSE: "after:response";
4
+ /** Pre-routing, after body parse: hooks.before/after('request', ...) */
5
+ readonly REQUEST: "request";
6
+ /** After the response is flushed: hooks.before/after('response', ...) */
7
+ readonly RESPONSE: "response";
8
+ /** When a request fails at the server error boundary: hooks.before/after('error', ...) */
8
9
  readonly ERROR: "error";
9
10
  };
10
11
  export declare class HookManager extends EventEmitter {
@@ -1,11 +1,16 @@
1
1
  // Hook System for Moro
2
2
  import { EventEmitter } from 'events';
3
3
  import { createFrameworkLogger } from '../logger/index.js';
4
+ // The lifecycle events the servers actually execute. These are the exact
5
+ // strings passed to before()/after() — the before/after phase is expressed by
6
+ // which method you call, not by the event name. (Earlier versions exported
7
+ // 'before:request'-style values here that were never valid registration keys.)
4
8
  export const HOOK_EVENTS = {
5
- BEFORE_REQUEST: 'before:request',
6
- AFTER_REQUEST: 'after:request',
7
- BEFORE_RESPONSE: 'before:response',
8
- AFTER_RESPONSE: 'after:response',
9
+ /** Pre-routing, after body parse: hooks.before/after('request', ...) */
10
+ REQUEST: 'request',
11
+ /** After the response is flushed: hooks.before/after('response', ...) */
12
+ RESPONSE: 'response',
13
+ /** When a request fails at the server error boundary: hooks.before/after('error', ...) */
9
14
  ERROR: 'error',
10
15
  };
11
16
  export class HookManager extends EventEmitter {
@@ -1 +1 @@
1
- {"version":3,"file":"hooks.js","sourceRoot":"","sources":["../../../src/core/utilities/hooks.ts"],"names":[],"mappings":"AAAA,uBAAuB;AACvB,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAEtC,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAE3D,MAAM,CAAC,MAAM,WAAW,GAAG;IACzB,cAAc,EAAE,gBAAgB;IAChC,aAAa,EAAE,eAAe;IAC9B,eAAe,EAAE,iBAAiB;IAClC,cAAc,EAAE,gBAAgB;IAChC,KAAK,EAAE,OAAO;CACN,CAAC;AAEX,MAAM,OAAO,WAAY,SAAQ,YAAY;IACnC,KAAK,GAAG,IAAI,GAAG,EAA0B,CAAC;IAC1C,WAAW,GAAG,IAAI,GAAG,EAA0B,CAAC;IAChD,UAAU,GAAG,IAAI,GAAG,EAA0B,CAAC;IAC/C,MAAM,GAAG,qBAAqB,CAAC,OAAO,CAAC,CAAC;IAEhD,2BAA2B;IAC3B,4DAA4D;IACpD,YAAY,GAAG,IAAI,GAAG,EAA0D,CAAC;IAEzF,2DAA2D;IACnD,cAAc,GAAG,IAAI,GAAG,EAAmB,CAAC;IAEpD,8EAA8E;IAC9E,gFAAgF;IACxE,YAAY,GAAG,IAAI,GAAG,EAAU,CAAC;IAEzC;QACE,KAAK,EAAE,CAAC;QACR,yBAAyB;QACzB,MAAM,eAAe,GAA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wB,EAAE,CAAC;QACzC,MAAM,SAAS,GAAG,IAAI,GAAG,CAAC;YACxB,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE;YACpB,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,EAAE;YAC1B,GAAG,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE;SAC1B,CAAC,CAAC;QAEH,SAAS,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;YACxB,QAAQ,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;QACzC,CAAC,CAAC,CAAC;QAEH,OAAO,QAAQ,CAAC;IAClB,CAAC;CACF","sourcesContent":["// Hook System for Moro\nimport { EventEmitter } from 'events';\nimport { HookFunction, HookContext } from '../../types/hooks.js';\nimport { createFrameworkLogger } from '../logger/index.js';\n\nexport const HOOK_EVENTS = {\n BEFORE_REQUEST: 'before:request',\n AFTER_REQUEST: 'after:request',\n BEFORE_RESPONSE: 'before:response',\n AFTER_RESPONSE: 'after:response',\n ERROR: 'error',\n} as const;\n\nexport class HookManager extends EventEmitter {\n private hooks = new Map<string, HookFunction[]>();\n private beforeHooks = new Map<string, HookFunction[]>();\n private afterHooks = new Map<string, HookFunction[]>();\n private logger = createFrameworkLogger('Hooks');\n\n // Cached execute functions\n // When no hooks are registered, replace execute() with noop\n private executeCache = new Map<string, (context: HookContext) => Promise<HookContext>>();\n\n // Track if hooks are synchronous to avoid Promise overhead\n private hookSyncStatus = new Map<string, boolean>();\n\n // Events that currently have at least one hook registered - lets callers skip\n // execute() entirely (no context object, no promise) when nothing is registered\n private activeEvents = new Set<string>();\n\n constructor() {\n super();\n // Initialize hook arrays\n const hookEventValues = Object.values(HOOK_EVENTS);\n const hookEventLen = hookEventValues.length;\n for (let i = 0; i < hookEventLen; i++) {\n const event = hookEventValues[i];\n if (event === undefined) continue;\n this.hooks.set(event, []);\n this.beforeHooks.set(event, []);\n this.afterHooks.set(event, []);\n // Initialize with noop functions\n this.updateExecuteCache(event);\n }\n }\n\n // Update cached execute function for an event\n private updateExecuteCache(event: string): void {\n const beforeHooks = this.beforeHooks.get(event) || [];\n const hooks = this.hooks.get(event) || [];\n const afterHooks = this.afterHooks.get(event) || [];\n\n // If no hooks registered, use noop for zero overhead\n if (beforeHooks.length === 0 && hooks.length === 0 && afterHooks.length === 0) {\n this.executeCache.set(event, async (context: HookContext) => context);\n this.hookSyncStatus.set(event, true); // Mark as sync (noop)\n this.activeEvents.delete(event);\n return;\n }\n\n this.activeEvents.add(event);\n\n // Detect if all hooks are synchronous\n const allSync = this.areHooksSynchronous(beforeHooks, hooks, afterHooks);\n this.hookSyncStatus.set(event, allSync);\n\n if (allSync) {\n // FAST PATH: Create synchronous version (no Promise overhead)\n // Cast to Promise return type to satisfy interface\n this.executeCache.set(event, ((context: HookContext) => {\n // Execute before hooks synchronously\n const beforeLen = beforeHooks.length;\n for (let i = 0; i < beforeLen; i++) {\n try {\n const hook = beforeHooks[i];\n if (hook !== undefined) {\n hook(context);\n }\n } catch (error) {\n // Check if this is a known/expected error that should not halt execution\n const errorMessage = error instanceof Error ? error.message : String(error);\n const isHeadersError =\n errorMessage.includes('headersSent') && errorMessage.includes('getter');\n\n if (isHeadersError) {\n // This is an expected error when trying to set read-only headersSent property\n // Log as debug instead of error, and don't re-throw\n this.logger.debug(\n 'Hook attempted to set read-only headersSent property',\n 'HookExecution',\n {\n error: errorMessage,\n context: context.request?.method || 'unknown',\n }\n );\n continue;\n }\n\n this.logger.error('Hook execution error', 'HookExecution', {\n error: errorMessage,\n });\n throw error;\n }\n }\n\n // Execute main hooks synchronously\n const hooksLen = hooks.length;\n for (let i = 0; i < hooksLen; i++) {\n try {\n const hook = hooks[i];\n if (hook !== undefined) {\n hook(context);\n }\n } catch (error) {\n // Check if this is a known/expected error that should not halt execution\n const errorMessage = error instanceof Error ? error.message : String(error);\n const isHeadersError =\n errorMessage.includes('headersSent') && errorMessage.includes('getter');\n\n if (isHeadersError) {\n // This is an expected error when trying to set read-only headersSent property\n // Log as debug instead of error, and don't re-throw\n this.logger.debug(\n 'Hook attempted to set read-only headersSent property',\n 'HookExecution',\n {\n error: errorMessage,\n context: context.request?.method || 'unknown',\n }\n );\n continue;\n }\n\n this.logger.error('Hook execution error', 'HookExecution', {\n error: errorMessage,\n });\n throw error;\n }\n }\n\n // Execute after hooks synchronously\n const afterLen = afterHooks.length;\n for (let i = 0; i < afterLen; i++) {\n try {\n const hook = afterHooks[i];\n if (hook !== undefined) {\n hook(context);\n }\n } catch (error) {\n // Check if this is a known/expected error that should not halt execution\n const errorMessage = error instanceof Error ? error.message : String(error);\n const isHeadersError =\n errorMessage.includes('headersSent') && errorMessage.includes('getter');\n\n if (isHeadersError) {\n // This is an expected error when trying to set read-only headersSent property\n // Log as debug instead of error, and don't re-throw\n this.logger.debug(\n 'Hook attempted to set read-only headersSent property',\n 'HookExecution',\n {\n error: errorMessage,\n context: context.request?.method || 'unknown',\n }\n );\n continue;\n }\n\n this.logger.error('Hook execution error', 'HookExecution', {\n error: errorMessage,\n });\n throw error;\n }\n }\n\n // Emit event for listeners\n this.emit(event, context);\n\n return context as any; // Cast to satisfy Promise return\n }) as any);\n } else {\n // SLOW PATH: Use async version only when needed\n this.executeCache.set(event, async (context: HookContext) => {\n // Execute before hooks\n const beforeLen = beforeHooks.length;\n for (let i = 0; i < beforeLen; i++) {\n const hook = beforeHooks[i];\n if (hook !== undefined) {\n await this.executeHook(hook, context);\n }\n }\n\n // Execute main hooks\n const hooksLen = hooks.length;\n for (let i = 0; i < hooksLen; i++) {\n const hook = hooks[i];\n if (hook !== undefined) {\n await this.executeHook(hook, context);\n }\n }\n\n // Execute after hooks\n const afterLen = afterHooks.length;\n for (let i = 0; i < afterLen; i++) {\n const hook = afterHooks[i];\n if (hook !== undefined) {\n await this.executeHook(hook, context);\n }\n }\n\n // Emit event for listeners\n this.emit(event, context);\n\n return context;\n });\n }\n }\n\n // Detect if hooks are synchronous by checking function signatures\n private areHooksSynchronous(...hookArrays: HookFunction[][]): boolean {\n for (const hooks of hookArrays) {\n for (const hook of hooks) {\n // Check if function is async or returns a Promise\n if (hook.constructor.name === 'AsyncFunction') {\n return false;\n }\n // Additional heuristic: check if function name suggests async\n if (hook.name && (hook.name.includes('async') || hook.name.includes('Async'))) {\n return false;\n }\n }\n }\n return true; // Assume synchronous by default\n }\n\n // Register a hook for a specific event\n hook(event: string, fn: HookFunction): this {\n if (!this.hooks.has(event)) {\n this.hooks.set(event, []);\n }\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n this.hooks.get(event)!.push(fn);\n this.updateExecuteCache(event); // Update cache\n return this;\n }\n\n // Register a before hook\n before(event: string, fn: HookFunction): this {\n if (!this.beforeHooks.has(event)) {\n this.beforeHooks.set(event, []);\n }\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n this.beforeHooks.get(event)!.push(fn);\n this.updateExecuteCache(event); // Update cache\n return this;\n }\n\n // Register an after hook\n after(event: string, fn: HookFunction): this {\n if (!this.afterHooks.has(event)) {\n this.afterHooks.set(event, []);\n }\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n this.afterHooks.get(event)!.push(fn);\n this.updateExecuteCache(event); // Update cache\n return this;\n }\n\n // O(1) check that lets hot paths skip execute() (and its context/promise\n // allocation) entirely when no hooks are registered for an event.\n // Note: EventEmitter listeners attached via .on(event) also count, since the\n // cached executors emit the event after running hooks.\n hasHooks(event: string): boolean {\n return this.activeEvents.has(event) || this.listenerCount(event) > 0;\n }\n\n // Execute hooks for an event - optimized with cached functions\n async execute(event: string, context: HookContext = {}): Promise<HookContext> {\n const executeFn = this.executeCache.get(event);\n if (executeFn) {\n return executeFn(context);\n }\n\n // Fallback for events not in cache (shouldn't happen in normal operation)\n this.updateExecuteCache(event);\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return this.executeCache.get(event)!(context);\n }\n\n // Execute a single hook with error handling\n private async executeHook(hook: HookFunction, context: HookContext): Promise<void> {\n try {\n await hook(context);\n } catch (error) {\n // Check if this is a known/expected error that should not halt execution\n const errorMessage = error instanceof Error ? error.message : String(error);\n const isHeadersError =\n errorMessage.includes('headersSent') && errorMessage.includes('getter');\n\n if (isHeadersError) {\n // This is an expected error when trying to set read-only headersSent property\n // Log as debug instead of error, and don't re-throw\n this.logger.debug('Hook attempted to set read-only headersSent property', 'HookExecution', {\n error: errorMessage,\n context: context.request?.method || 'unknown',\n });\n return;\n }\n\n // For other errors, log and re-throw as before\n this.logger.error('Hook execution error', 'HookExecution', {\n error: errorMessage,\n context: context.request?.method || 'unknown',\n });\n throw error;\n }\n }\n\n // Remove hooks\n removeHook(event: string, fn?: HookFunction): this {\n if (!fn) {\n this.hooks.delete(event);\n this.beforeHooks.delete(event);\n this.afterHooks.delete(event);\n } else {\n const maps = [this.hooks, this.beforeHooks, this.afterHooks];\n const mapsLen = maps.length;\n for (let i = 0; i < mapsLen; i++) {\n const map = maps[i];\n if (map === undefined) continue;\n const hooks = map.get(event);\n if (hooks) {\n const index = hooks.indexOf(fn);\n if (index !== -1) {\n hooks.splice(index, 1);\n }\n }\n }\n }\n this.updateExecuteCache(event); // Update cache\n return this;\n }\n\n // Get all registered hooks for debugging\n getHooks(event?: string): Record<string, any> {\n if (event) {\n return {\n before: this.beforeHooks.get(event) || [],\n main: this.hooks.get(event) || [],\n after: this.afterHooks.get(event) || [],\n };\n }\n\n const allHooks: Record<string, any> = {};\n const allEvents = new Set([\n ...this.hooks.keys(),\n ...this.beforeHooks.keys(),\n ...this.afterHooks.keys(),\n ]);\n\n allEvents.forEach(event => {\n allHooks[event] = this.getHooks(event);\n });\n\n return allHooks;\n }\n}\n"]}
1
+ {"version":3,"file":"hooks.js","sourceRoot":"","sources":["../../../src/core/utilities/hooks.ts"],"names":[],"mappings":"AAAA,uBAAuB;AACvB,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAEtC,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAE3D,yEAAyE;AACz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AAK,EAAE,CAAC;oBACV,MAAM,KAAK,GAAG,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;oBAChC,IAAI,KAAK,KAAK,CAAC,CAAC,EAAE,CAAC;wBACjB,KAAK,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;oBACzB,CAAC;gBACH,CAAC;YACH,CAAC;QACH,CAAC;QACD,IAAI,CAAC,kBAAkB,CAAC,KAAK,CAAC,CAAC,CAAC,eAAe;QAC/C,OAAO,IAAI,CAAC;IACd,CAAC;IAED,yCAAyC;IACzC,QAAQ,CAAC,KAAc;QACrB,IAAI,KAAK,EAAE,CAAC;YACV,OAAO;gBACL,MAAM,EAAE,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE;gBACzC,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE;gBACjC,KAAK,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE;aACxC,CAAC;QACJ,CAAC;QAED,MAAM,QAAQ,GAAwB,EAAE,CAAC;QACzC,MAAM,SAAS,GAAG,IAAI,GAAG,CAAC;YACxB,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE;YACpB,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,EAAE;YAC1B,GAAG,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE;SAC1B,CAAC,CAAC;QAEH,SAAS,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;YACxB,QAAQ,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;QACzC,CAAC,CAAC,CAAC;QAEH,OAAO,QAAQ,CAAC;IAClB,CAAC;CACF","sourcesContent":["// Hook System for Moro\nimport { EventEmitter } from 'events';\nimport { HookFunction, HookContext } from '../../types/hooks.js';\nimport { createFrameworkLogger } from '../logger/index.js';\n\n// The lifecycle events the servers actually execute. These are the exact\n// strings passed to before()/after() — the before/after phase is expressed by\n// which method you call, not by the event name. (Earlier versions exported\n// 'before:request'-style values here that were never valid registration keys.)\nexport const HOOK_EVENTS = {\n /** Pre-routing, after body parse: hooks.before/after('request', ...) */\n REQUEST: 'request',\n /** After the response is flushed: hooks.before/after('response', ...) */\n RESPONSE: 'response',\n /** When a request fails at the server error boundary: hooks.before/after('error', ...) */\n ERROR: 'error',\n} as const;\n\nexport class HookManager extends EventEmitter {\n private hooks = new Map<string, HookFunction[]>();\n private beforeHooks = new Map<string, HookFunction[]>();\n private afterHooks = new Map<string, HookFunction[]>();\n private logger = createFrameworkLogger('Hooks');\n\n // Cached execute functions\n // When no hooks are registered, replace execute() with noop\n private executeCache = new Map<string, (context: HookContext) => Promise<HookContext>>();\n\n // Track if hooks are synchronous to avoid Promise overhead\n private hookSyncStatus = new Map<string, boolean>();\n\n // Events that currently have at least one hook registered - lets callers skip\n // execute() entirely (no context object, no promise) when nothing is registered\n private activeEvents = new Set<string>();\n\n constructor() {\n super();\n // Initialize hook arrays\n const hookEventValues = Object.values(HOOK_EVENTS);\n const hookEventLen = hookEventValues.length;\n for (let i = 0; i < hookEventLen; i++) {\n const event = hookEventValues[i];\n if (event === undefined) continue;\n this.hooks.set(event, []);\n this.beforeHooks.set(event, []);\n this.afterHooks.set(event, []);\n // Initialize with noop functions\n this.updateExecuteCache(event);\n }\n }\n\n // Update cached execute function for an event\n private updateExecuteCache(event: string): void {\n const beforeHooks = this.beforeHooks.get(event) || [];\n const hooks = this.hooks.get(event) || [];\n const afterHooks = this.afterHooks.get(event) || [];\n\n // If no hooks registered, use noop for zero overhead\n if (beforeHooks.length === 0 && hooks.length === 0 && afterHooks.length === 0) {\n this.executeCache.set(event, async (context: HookContext) => context);\n this.hookSyncStatus.set(event, true); // Mark as sync (noop)\n this.activeEvents.delete(event);\n return;\n }\n\n this.activeEvents.add(event);\n\n // Detect if all hooks are synchronous\n const allSync = this.areHooksSynchronous(beforeHooks, hooks, afterHooks);\n this.hookSyncStatus.set(event, allSync);\n\n if (allSync) {\n // FAST PATH: Create synchronous version (no Promise overhead)\n // Cast to Promise return type to satisfy interface\n this.executeCache.set(event, ((context: HookContext) => {\n // Execute before hooks synchronously\n const beforeLen = beforeHooks.length;\n for (let i = 0; i < beforeLen; i++) {\n try {\n const hook = beforeHooks[i];\n if (hook !== undefined) {\n hook(context);\n }\n } catch (error) {\n // Check if this is a known/expected error that should not halt execution\n const errorMessage = error instanceof Error ? error.message : String(error);\n const isHeadersError =\n errorMessage.includes('headersSent') && errorMessage.includes('getter');\n\n if (isHeadersError) {\n // This is an expected error when trying to set read-only headersSent property\n // Log as debug instead of error, and don't re-throw\n this.logger.debug(\n 'Hook attempted to set read-only headersSent property',\n 'HookExecution',\n {\n error: errorMessage,\n context: context.request?.method || 'unknown',\n }\n );\n continue;\n }\n\n this.logger.error('Hook execution error', 'HookExecution', {\n error: errorMessage,\n });\n throw error;\n }\n }\n\n // Execute main hooks synchronously\n const hooksLen = hooks.length;\n for (let i = 0; i < hooksLen; i++) {\n try {\n const hook = hooks[i];\n if (hook !== undefined) {\n hook(context);\n }\n } catch (error) {\n // Check if this is a known/expected error that should not halt execution\n const errorMessage = error instanceof Error ? error.message : String(error);\n const isHeadersError =\n errorMessage.includes('headersSent') && errorMessage.includes('getter');\n\n if (isHeadersError) {\n // This is an expected error when trying to set read-only headersSent property\n // Log as debug instead of error, and don't re-throw\n this.logger.debug(\n 'Hook attempted to set read-only headersSent property',\n 'HookExecution',\n {\n error: errorMessage,\n context: context.request?.method || 'unknown',\n }\n );\n continue;\n }\n\n this.logger.error('Hook execution error', 'HookExecution', {\n error: errorMessage,\n });\n throw error;\n }\n }\n\n // Execute after hooks synchronously\n const afterLen = afterHooks.length;\n for (let i = 0; i < afterLen; i++) {\n try {\n const hook = afterHooks[i];\n if (hook !== undefined) {\n hook(context);\n }\n } catch (error) {\n // Check if this is a known/expected error that should not halt execution\n const errorMessage = error instanceof Error ? error.message : String(error);\n const isHeadersError =\n errorMessage.includes('headersSent') && errorMessage.includes('getter');\n\n if (isHeadersError) {\n // This is an expected error when trying to set read-only headersSent property\n // Log as debug instead of error, and don't re-throw\n this.logger.debug(\n 'Hook attempted to set read-only headersSent property',\n 'HookExecution',\n {\n error: errorMessage,\n context: context.request?.method || 'unknown',\n }\n );\n continue;\n }\n\n this.logger.error('Hook execution error', 'HookExecution', {\n error: errorMessage,\n });\n throw error;\n }\n }\n\n // Emit event for listeners\n this.emit(event, context);\n\n return context as any; // Cast to satisfy Promise return\n }) as any);\n } else {\n // SLOW PATH: Use async version only when needed\n this.executeCache.set(event, async (context: HookContext) => {\n // Execute before hooks\n const beforeLen = beforeHooks.length;\n for (let i = 0; i < beforeLen; i++) {\n const hook = beforeHooks[i];\n if (hook !== undefined) {\n await this.executeHook(hook, context);\n }\n }\n\n // Execute main hooks\n const hooksLen = hooks.length;\n for (let i = 0; i < hooksLen; i++) {\n const hook = hooks[i];\n if (hook !== undefined) {\n await this.executeHook(hook, context);\n }\n }\n\n // Execute after hooks\n const afterLen = afterHooks.length;\n for (let i = 0; i < afterLen; i++) {\n const hook = afterHooks[i];\n if (hook !== undefined) {\n await this.executeHook(hook, context);\n }\n }\n\n // Emit event for listeners\n this.emit(event, context);\n\n return context;\n });\n }\n }\n\n // Detect if hooks are synchronous by checking function signatures\n private areHooksSynchronous(...hookArrays: HookFunction[][]): boolean {\n for (const hooks of hookArrays) {\n for (const hook of hooks) {\n // Check if function is async or returns a Promise\n if (hook.constructor.name === 'AsyncFunction') {\n return false;\n }\n // Additional heuristic: check if function name suggests async\n if (hook.name && (hook.name.includes('async') || hook.name.includes('Async'))) {\n return false;\n }\n }\n }\n return true; // Assume synchronous by default\n }\n\n // Register a hook for a specific event\n hook(event: string, fn: HookFunction): this {\n if (!this.hooks.has(event)) {\n this.hooks.set(event, []);\n }\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n this.hooks.get(event)!.push(fn);\n this.updateExecuteCache(event); // Update cache\n return this;\n }\n\n // Register a before hook\n before(event: string, fn: HookFunction): this {\n if (!this.beforeHooks.has(event)) {\n this.beforeHooks.set(event, []);\n }\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n this.beforeHooks.get(event)!.push(fn);\n this.updateExecuteCache(event); // Update cache\n return this;\n }\n\n // Register an after hook\n after(event: string, fn: HookFunction): this {\n if (!this.afterHooks.has(event)) {\n this.afterHooks.set(event, []);\n }\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n this.afterHooks.get(event)!.push(fn);\n this.updateExecuteCache(event); // Update cache\n return this;\n }\n\n // O(1) check that lets hot paths skip execute() (and its context/promise\n // allocation) entirely when no hooks are registered for an event.\n // Note: EventEmitter listeners attached via .on(event) also count, since the\n // cached executors emit the event after running hooks.\n hasHooks(event: string): boolean {\n return this.activeEvents.has(event) || this.listenerCount(event) > 0;\n }\n\n // Execute hooks for an event - optimized with cached functions\n async execute(event: string, context: HookContext = {}): Promise<HookContext> {\n const executeFn = this.executeCache.get(event);\n if (executeFn) {\n return executeFn(context);\n }\n\n // Fallback for events not in cache (shouldn't happen in normal operation)\n this.updateExecuteCache(event);\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return this.executeCache.get(event)!(context);\n }\n\n // Execute a single hook with error handling\n private async executeHook(hook: HookFunction, context: HookContext): Promise<void> {\n try {\n await hook(context);\n } catch (error) {\n // Check if this is a known/expected error that should not halt execution\n const errorMessage = error instanceof Error ? error.message : String(error);\n const isHeadersError =\n errorMessage.includes('headersSent') && errorMessage.includes('getter');\n\n if (isHeadersError) {\n // This is an expected error when trying to set read-only headersSent property\n // Log as debug instead of error, and don't re-throw\n this.logger.debug('Hook attempted to set read-only headersSent property', 'HookExecution', {\n error: errorMessage,\n context: context.request?.method || 'unknown',\n });\n return;\n }\n\n // For other errors, log and re-throw as before\n this.logger.error('Hook execution error', 'HookExecution', {\n error: errorMessage,\n context: context.request?.method || 'unknown',\n });\n throw error;\n }\n }\n\n // Remove hooks\n removeHook(event: string, fn?: HookFunction): this {\n if (!fn) {\n this.hooks.delete(event);\n this.beforeHooks.delete(event);\n this.afterHooks.delete(event);\n } else {\n const maps = [this.hooks, this.beforeHooks, this.afterHooks];\n const mapsLen = maps.length;\n for (let i = 0; i < mapsLen; i++) {\n const map = maps[i];\n if (map === undefined) continue;\n const hooks = map.get(event);\n if (hooks) {\n const index = hooks.indexOf(fn);\n if (index !== -1) {\n hooks.splice(index, 1);\n }\n }\n }\n }\n this.updateExecuteCache(event); // Update cache\n return this;\n }\n\n // Get all registered hooks for debugging\n getHooks(event?: string): Record<string, any> {\n if (event) {\n return {\n before: this.beforeHooks.get(event) || [],\n main: this.hooks.get(event) || [],\n after: this.afterHooks.get(event) || [],\n };\n }\n\n const allHooks: Record<string, any> = {};\n const allEvents = new Set([\n ...this.hooks.keys(),\n ...this.beforeHooks.keys(),\n ...this.afterHooks.keys(),\n ]);\n\n allEvents.forEach(event => {\n allHooks[event] = this.getHooks(event);\n });\n\n return allHooks;\n }\n}\n"]}
package/dist/moro.d.ts CHANGED
@@ -213,6 +213,7 @@ export declare class Moro extends EventEmitter {
213
213
  private findMatchingRoute;
214
214
  private pathToRegex;
215
215
  get events(): MoroEventBus;
216
+ get hooks(): import("./index.js").HookManager;
216
217
  get core(): MoroCore;
217
218
  get engine(): ReturnType<MoroCore['getServerKind']>;
218
219
  getServerKind(): ReturnType<MoroCore['getServerKind']>;
package/dist/moro.js CHANGED
@@ -230,6 +230,9 @@ export class Moro extends EventEmitter {
230
230
  const httpServer = this.coreFramework.httpServer;
231
231
  if (httpServer && httpServer.setHookManager) {
232
232
  httpServer.setHookManager(this.middlewareManager.hooks);
233
+ // The router swallows handler errors (it produces the 500), so it needs
234
+ // the hook manager too for 'error' hooks to observe them.
235
+ this.unifiedRouter.setHookManager(this.middlewareManager.hooks);
233
236
  }
234
237
  // Configure HTTP server performance based on config
235
238
  if (httpServer && httpServer.configurePerformance) {
@@ -1011,25 +1014,58 @@ export class Moro extends EventEmitter {
1011
1014
  error: error instanceof Error ? error.message : String(error),
1012
1015
  });
1013
1016
  });
1014
- // Create a unified request handler that works with the runtime adapter
1017
+ // Create a unified request handler that works with the runtime adapter.
1018
+ // Lifecycle hooks run here so serverless runtimes (Lambda, Edge, Workers)
1019
+ // have parity with the long-running servers. Unlike those servers,
1020
+ // 'response' hooks are awaited before returning — post-return work would
1021
+ // be frozen or dropped by the platform.
1022
+ const hookManager = this.middlewareManager.getHookManager();
1015
1023
  const handler = async (req, res) => {
1016
- // Add documentation middleware first (if enabled)
1017
1024
  try {
1018
- const docsMiddleware = this.documentation.getDocsMiddleware();
1019
- await docsMiddleware(req, res, () => { });
1020
- if (res.headersSent)
1025
+ if (hookManager.hasHooks('request')) {
1026
+ await hookManager.execute('request', { request: req, response: res });
1027
+ if (res.headersSent)
1028
+ return;
1029
+ }
1030
+ // Add documentation middleware first (if enabled)
1031
+ try {
1032
+ const docsMiddleware = this.documentation.getDocsMiddleware();
1033
+ await docsMiddleware(req, res, () => { });
1034
+ if (res.headersSent)
1035
+ return;
1036
+ }
1037
+ catch {
1038
+ // Documentation not enabled, that's fine
1039
+ }
1040
+ // Try unified router first (handles all routes)
1041
+ const handled = await this.unifiedRouter.handleRequest(req, res);
1042
+ if (handled)
1021
1043
  return;
1044
+ // Handle legacy direct routes (backward compatibility)
1045
+ if (this.routes.length > 0) {
1046
+ await this.handleDirectRoutes(req, res);
1047
+ }
1022
1048
  }
1023
- catch {
1024
- // Documentation not enabled, that's fine
1049
+ catch (error) {
1050
+ if (hookManager.hasHooks('error')) {
1051
+ try {
1052
+ await hookManager.execute('error', { request: req, response: res, error });
1053
+ }
1054
+ catch (hookError) {
1055
+ this.logger.error(`Error hook error: ${hookError?.message || hookError}`, 'Hooks');
1056
+ }
1057
+ }
1058
+ throw error;
1025
1059
  }
1026
- // Try unified router first (handles all routes)
1027
- const handled = await this.unifiedRouter.handleRequest(req, res);
1028
- if (handled)
1029
- return;
1030
- // Handle legacy direct routes (backward compatibility)
1031
- if (this.routes.length > 0) {
1032
- await this.handleDirectRoutes(req, res);
1060
+ finally {
1061
+ if (hookManager.hasHooks('response')) {
1062
+ try {
1063
+ await hookManager.execute('response', { request: req, response: res });
1064
+ }
1065
+ catch (hookError) {
1066
+ this.logger.error(`Response hook error: ${hookError?.message || hookError}`, 'Hooks');
1067
+ }
1068
+ }
1033
1069
  }
1034
1070
  };
1035
1071
  // Use the runtime adapter to create the appropriate handler
@@ -1162,6 +1198,13 @@ export class Moro extends EventEmitter {
1162
1198
  get events() {
1163
1199
  return this.eventBus;
1164
1200
  }
1201
+ // The application's live hook manager — the same instance
1202
+ // MiddlewareInterface.install() receives. Register request-lifecycle hooks
1203
+ // directly: app.hooks.before('request', ctx => {...}),
1204
+ // app.hooks.after('response', ctx => {...}).
1205
+ get hooks() {
1206
+ return this.middlewareManager.getHookManager();
1207
+ }
1165
1208
  // Access to core framework for advanced usage
1166
1209
  get core() {
1167
1210
  return this.coreFramework;