@cosmneo/onion-lasagna 0.2.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-GGSAAZPM.js → chunk-AUMHMWDD.js} +19 -20
- package/dist/chunk-AUMHMWDD.js.map +1 -0
- package/dist/chunk-H5TNDC5U.js +138 -0
- package/dist/chunk-H5TNDC5U.js.map +1 -0
- package/dist/chunk-MF2JDREK.js +168 -0
- package/dist/chunk-MF2JDREK.js.map +1 -0
- package/dist/{chunk-PUVAB3JX.js → chunk-XIRJ73IO.js} +38 -36
- package/dist/chunk-XIRJ73IO.js.map +1 -0
- package/dist/{chunk-DS7TE6KZ.js → chunk-XP6PLTV2.js} +11 -3
- package/dist/chunk-XP6PLTV2.js.map +1 -0
- package/dist/global.js +3 -3
- package/dist/http/index.cjs +563 -93
- package/dist/http/index.cjs.map +1 -1
- package/dist/http/index.d.cts +4 -3
- package/dist/http/index.d.ts +4 -3
- package/dist/http/index.js +30 -12
- package/dist/http/openapi/index.cjs +43 -35
- package/dist/http/openapi/index.cjs.map +1 -1
- package/dist/http/openapi/index.d.cts +8 -34
- package/dist/http/openapi/index.d.ts +8 -34
- package/dist/http/openapi/index.js +2 -2
- package/dist/http/route/index.cjs +106 -9
- package/dist/http/route/index.cjs.map +1 -1
- package/dist/http/route/index.d.cts +133 -227
- package/dist/http/route/index.d.ts +133 -227
- package/dist/http/route/index.js +5 -2
- package/dist/http/server/index.cjs +24 -19
- package/dist/http/server/index.cjs.map +1 -1
- package/dist/http/server/index.d.cts +1 -1
- package/dist/http/server/index.d.ts +1 -1
- package/dist/http/server/index.js +2 -2
- package/dist/http/shared/index.cjs.map +1 -1
- package/dist/http/shared/index.d.cts +10 -14
- package/dist/http/shared/index.d.ts +10 -14
- package/dist/http/shared/index.js +11 -127
- package/dist/http/shared/index.js.map +1 -1
- package/dist/index.js +6 -6
- package/dist/{router-definition.type-ynBhT16T.d.cts → router-definition.type-BElX-Pl4.d.cts} +169 -256
- package/dist/{router-definition.type-DORVlLNk.d.ts → router-definition.type-DxG8ncJZ.d.ts} +169 -256
- package/package.json +1 -1
- package/dist/chunk-BZULBF4N.js +0 -82
- package/dist/chunk-BZULBF4N.js.map +0 -1
- package/dist/chunk-DS7TE6KZ.js.map +0 -1
- package/dist/chunk-GGSAAZPM.js.map +0 -1
- package/dist/chunk-PUVAB3JX.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/presentation/http/server/index.ts","../../../src/presentation/http/route/types/path-params.type.ts","../../../src/presentation/http/route/types/router-definition.type.ts","../../../src/presentation/http/server/types.ts","../../../src/global/exceptions/coded-error.error.ts","../../../src/global/exceptions/error-codes.const.ts","../../../src/presentation/exceptions/invalid-request.error.ts","../../../src/presentation/exceptions/controller.error.ts","../../../src/app/exceptions/use-case.error.ts","../../../src/app/exceptions/unauthorized.error.ts","../../../src/global/utils/wrap-error.util.ts","../../../src/presentation/http/server/create-server-routes.ts","../../../src/presentation/http/server/server-routes-builder.ts"],"sourcesContent":["/**\n * @fileoverview Server module exports.\n *\n * This module provides server-side route registration with automatic validation.\n * It follows the BaseController pattern: requestMapper → useCase → responseMapper\n *\n * @module unified/server\n *\n * @example Create server routes with builder pattern\n * ```typescript\n * import { serverRoutes } from '@cosmneo/onion-lasagna/http/server';\n * import { projectRouter } from './routes';\n *\n * const routes = serverRoutes(projectRouter)\n * .handle('projects.create', {\n * requestMapper: (req, ctx) => ({\n * name: req.body.name, // Fully typed!\n * createdBy: ctx.userId, // Fully typed!\n * }),\n * useCase: createProjectUseCase,\n * responseMapper: (output) => ({\n * status: 201 as const,\n * body: { projectId: output.projectId },\n * }),\n * })\n * .handle('projects.list', { ... })\n * .build();\n * ```\n */\n\n// Builder pattern for server routes\nexport { serverRoutes } from './server-routes-builder';\nexport type {\n ServerRoutesBuilder,\n MissingHandlersError,\n BuilderHandlerConfig,\n} from './server-routes-builder';\n\nexport type {\n UseCasePort,\n ValidatedRequest,\n TypedContext,\n HandlerContext,\n HandlerResponse,\n RouteHandlerConfig,\n MiddlewareFunction,\n ServerRoutesConfig,\n CreateServerRoutesOptions,\n UnifiedRouteInput,\n RawHttpRequest,\n} from './types';\n","/**\n * @fileoverview Path parameter extraction types.\n *\n * These types enable TypeScript to extract path parameter names from\n * URL path templates at compile time, providing full type safety for\n * path parameters in routes.\n *\n * @module unified/route/types/path-params\n */\n\n/**\n * Extracts parameter names from a path template string.\n *\n * Supports both `:param` and `{param}` syntaxes for maximum compatibility\n * with different routing conventions.\n *\n * @example Colon syntax (Express-style)\n * ```typescript\n * type Params = ExtractPathParamNames<'/users/:userId/posts/:postId'>;\n * // 'userId' | 'postId'\n * ```\n *\n * @example Brace syntax (OpenAPI-style)\n * ```typescript\n * type Params = ExtractPathParamNames<'/users/{userId}/posts/{postId}'>;\n * // 'userId' | 'postId'\n * ```\n *\n * @example No parameters\n * ```typescript\n * type Params = ExtractPathParamNames<'/users'>;\n * // never\n * ```\n */\nexport type ExtractPathParamNames<T extends string> =\n // Match :param followed by more path\n T extends `${string}:${infer Param}/${infer Rest}`\n ? Param | ExtractPathParamNames<`/${Rest}`>\n : // Match :param at end\n T extends `${string}:${infer Param}`\n ? Param\n : // Match {param} followed by more path\n T extends `${string}{${infer Param}}/${infer Rest}`\n ? Param | ExtractPathParamNames<`/${Rest}`>\n : // Match {param} at end\n T extends `${string}{${infer Param}}`\n ? Param\n : never;\n\n/**\n * Creates an object type with all path parameters as string properties.\n *\n * @example\n * ```typescript\n * type Params = PathParams<'/projects/:projectId/tasks/:taskId'>;\n * // { projectId: string; taskId: string }\n *\n * type NoParams = PathParams<'/projects'>;\n * // Record<string, never> (empty object type)\n * ```\n */\nexport type PathParams<T extends string> =\n ExtractPathParamNames<T> extends never\n ? Record<string, never>\n : Record<ExtractPathParamNames<T>, string>;\n\n/**\n * Checks if a path has any parameters.\n *\n * @example\n * ```typescript\n * type HasParams = HasPathParams<'/users/:id'>; // true\n * type NoParams = HasPathParams<'/users'>; // false\n * ```\n */\nexport type HasPathParams<T extends string> = ExtractPathParamNames<T> extends never ? false : true;\n\n/**\n * Converts a path template with parameters to a regex pattern.\n * This is used internally for route matching.\n *\n * @example\n * ```typescript\n * pathToRegex('/users/:id/posts/:postId')\n * // /^\\/users\\/([^\\/]+)\\/posts\\/([^\\/]+)\\/?$/\n * ```\n */\nexport function pathToRegex(path: string): RegExp {\n const pattern = path\n // Escape special regex characters except : and {}\n .replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n // Replace :param with capture group\n .replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g, '([^/]+)')\n // Replace {param} with capture group\n .replace(/\\\\\\{([a-zA-Z_][a-zA-Z0-9_]*)\\\\\\}/g, '([^/]+)');\n\n return new RegExp(`^${pattern}/?$`);\n}\n\n/**\n * Extracts parameter names from a path string at runtime.\n *\n * @example\n * ```typescript\n * getPathParamNames('/users/:userId/posts/:postId')\n * // ['userId', 'postId']\n * ```\n */\nexport function getPathParamNames(path: string): string[] {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- regex capture group always exists\n const colonParams = [...path.matchAll(/:([a-zA-Z_][a-zA-Z0-9_]*)/g)].map((m) => m[1]!);\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- regex capture group always exists\n const braceParams = [...path.matchAll(/\\{([a-zA-Z_][a-zA-Z0-9_]*)\\}/g)].map((m) => m[1]!);\n return [...colonParams, ...braceParams];\n}\n\n/**\n * Checks if a path has any parameters at runtime.\n */\nexport function hasPathParams(path: string): boolean {\n return /:([a-zA-Z_][a-zA-Z0-9_]*)/.test(path) || /\\{([a-zA-Z_][a-zA-Z0-9_]*)\\}/.test(path);\n}\n\n/**\n * Replaces path parameters with actual values.\n *\n * @example\n * ```typescript\n * buildPath('/users/:userId/posts/:postId', { userId: '123', postId: '456' })\n * // '/users/123/posts/456'\n *\n * buildPath('/users/{userId}', { userId: '123' })\n * // '/users/123'\n * ```\n */\nexport function buildPath(template: string, params: Record<string, string>): string {\n let result = template;\n\n // Replace :param syntax\n for (const [key, value] of Object.entries(params)) {\n result = result.replace(`:${key}`, encodeURIComponent(value));\n result = result.replace(`{${key}}`, encodeURIComponent(value));\n }\n\n return result;\n}\n\n/**\n * Normalizes a path template to use consistent :param syntax.\n *\n * @example\n * ```typescript\n * normalizePath('/users/{userId}')\n * // '/users/:userId'\n * ```\n */\nexport function normalizePath(path: string): string {\n return path.replace(/\\{([a-zA-Z_][a-zA-Z0-9_]*)\\}/g, ':$1');\n}\n","/**\n * @fileoverview Router definition types for grouping routes.\n *\n * A router is a hierarchical grouping of routes that enables:\n * - Organized API structure\n * - Nested client method generation\n * - Grouped OpenAPI tags\n *\n * @module unified/route/types/router-definition\n */\n\nimport type { RouteDefinition, ResponsesConfig } from './route-definition.type';\nimport type { HttpMethod } from './http.type';\n\n// ============================================================================\n// Router Types\n// ============================================================================\n\n/**\n * A router entry can be either a route definition or a nested router.\n * Uses permissive types to allow any valid route definition.\n */\nexport type RouterEntry =\n | RouteDefinition<\n HttpMethod,\n string,\n unknown,\n unknown,\n unknown,\n unknown,\n unknown,\n ResponsesConfig\n >\n | RouterConfig;\n\n/**\n * Configuration for a router (group of routes).\n */\nexport interface RouterConfig {\n readonly [key: string]: RouterEntry;\n}\n\n/**\n * A fully defined router.\n */\nexport interface RouterDefinition<T extends RouterConfig = RouterConfig> {\n /**\n * The routes and nested routers in this router.\n */\n readonly routes: T;\n\n /**\n * Base path prefix for all routes in this router.\n */\n readonly basePath?: string;\n\n /**\n * Default tags for all routes in this router.\n */\n readonly tags?: readonly string[];\n\n /**\n * Marker to identify this as a router.\n * @internal\n */\n readonly _isRouter: true;\n}\n\n// ============================================================================\n// Type Guards\n// ============================================================================\n\n/**\n * Checks if a value is a RouteDefinition.\n */\nexport function isRouteDefinition(value: unknown): value is RouteDefinition {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'method' in value &&\n 'path' in value &&\n 'responses' in value &&\n '_types' in value\n );\n}\n\n/**\n * Checks if a value is a RouterDefinition.\n */\nexport function isRouterDefinition(value: unknown): value is RouterDefinition {\n return (\n typeof value === 'object' &&\n value !== null &&\n '_isRouter' in value &&\n (value as RouterDefinition)._isRouter === true\n );\n}\n\n// ============================================================================\n// Utility Types\n// ============================================================================\n\n/**\n * Flattens a router into a map of path keys to route definitions.\n *\n * @example\n * ```typescript\n * const router = defineRouter({\n * users: {\n * list: listUsersRoute,\n * get: getUserRoute,\n * },\n * posts: {\n * create: createPostRoute,\n * },\n * });\n *\n * type Flat = FlattenRouter<typeof router>;\n * // {\n * // 'users.list': typeof listUsersRoute,\n * // 'users.get': typeof getUserRoute,\n * // 'posts.create': typeof createPostRoute,\n * // }\n * ```\n */\nexport type FlattenRouter<\n T extends RouterConfig,\n Prefix extends string = '',\n> = T extends RouterConfig\n ? {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [K in keyof T]: T[K] extends RouteDefinition<any, any, any, any, any, any, any, any>\n ? { [P in `${Prefix}${K & string}`]: T[K] }\n : T[K] extends RouterConfig\n ? FlattenRouter<T[K], `${Prefix}${K & string}.`>\n : never;\n }[keyof T] extends infer U\n ? // eslint-disable-next-line @typescript-eslint/no-explicit-any\n U extends Record<string, RouteDefinition<any, any, any, any, any, any, any, any>>\n ? U\n : never\n : never\n : never;\n\n/**\n * Gets all route keys from a router.\n *\n * @example\n * ```typescript\n * type Keys = RouterKeys<typeof router>;\n * // 'users.list' | 'users.get' | 'posts.create'\n * ```\n */\nexport type RouterKeys<T extends RouterConfig, Prefix extends string = ''> = T extends RouterConfig\n ? {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [K in keyof T]: T[K] extends RouteDefinition<any, any, any, any, any, any, any, any>\n ? `${Prefix}${K & string}`\n : T[K] extends RouterConfig\n ? RouterKeys<T[K], `${Prefix}${K & string}.`>\n : never;\n }[keyof T]\n : never;\n\n/**\n * Gets a route by its dotted key path.\n *\n * @example\n * ```typescript\n * type UserGet = GetRoute<typeof router, 'users.get'>;\n * // typeof getUserRoute\n * ```\n */\nexport type GetRoute<\n T extends RouterConfig,\n K extends string,\n> = K extends `${infer Head}.${infer Tail}`\n ? Head extends keyof T\n ? T[Head] extends RouterConfig\n ? GetRoute<T[Head], Tail>\n : never\n : never\n : K extends keyof T\n ? // eslint-disable-next-line @typescript-eslint/no-explicit-any\n T[K] extends RouteDefinition<any, any, any, any, any, any, any, any>\n ? T[K]\n : never\n : never;\n\n// ============================================================================\n// Deep Merge Types\n// ============================================================================\n\n/**\n * Deep-merges two router configs at the type level.\n *\n * - If both sides are sub-routers (extend RouterConfig), recurse.\n * - Otherwise last-one-wins (B overrides A).\n * - RouteDefinition does NOT extend RouterConfig (it has `method`, `path`, etc.)\n * so the conditional correctly distinguishes leaves from sub-routers.\n */\nexport type DeepMergeTwo<A extends RouterConfig, B extends RouterConfig> = {\n readonly [K in keyof A | keyof B]: K extends keyof A\n ? K extends keyof B\n ? A[K] extends RouterConfig\n ? B[K] extends RouterConfig\n ? DeepMergeTwo<A[K], B[K]>\n : B[K]\n : B[K]\n : A[K]\n : K extends keyof B\n ? B[K]\n : never;\n};\n\n/**\n * Recursively deep-merges N router configs left-to-right.\n */\nexport type DeepMergeAll<T extends readonly RouterConfig[]> = T extends readonly [\n infer Only extends RouterConfig,\n]\n ? Only\n : T extends readonly [\n infer First extends RouterConfig,\n infer Second extends RouterConfig,\n ...infer Rest extends readonly RouterConfig[],\n ]\n ? DeepMergeAll<[DeepMergeTwo<First, Second>, ...Rest]>\n : RouterConfig;\n\n/**\n * Recursively flattens complex types for clean IDE hover display.\n * Applied at return sites (not inside recursion) so DTS emit stays fast —\n * TypeScript only resolves when concrete types are provided.\n *\n * Works with any recursive object type: router configs, client types,\n * React Query hooks, etc. Functions and primitives pass through unchanged.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type PrettifyDeep<T> = T extends (...args: any[]) => any\n ? T\n : T extends object\n ? { readonly [K in keyof T]: PrettifyDeep<T[K]> }\n : T;\n\n/**\n * Collects all routes from a router into an array.\n */\nexport function collectRoutes(\n config: RouterConfig,\n basePath = '',\n): { key: string; route: RouteDefinition }[] {\n const routes: { key: string; route: RouteDefinition }[] = [];\n\n for (const [key, value] of Object.entries(config)) {\n const fullKey = basePath ? `${basePath}.${key}` : key;\n\n if (isRouteDefinition(value)) {\n routes.push({ key: fullKey, route: value });\n } else if (isRouterDefinition(value)) {\n routes.push(...collectRoutes(value.routes, fullKey));\n } else if (typeof value === 'object' && value !== null) {\n routes.push(...collectRoutes(value as RouterConfig, fullKey));\n }\n }\n\n return routes;\n}\n","/**\n * @fileoverview Server types for the unified route system.\n *\n * @module unified/server/types\n */\n\nimport type {\n HttpMethod,\n RouteDefinition,\n RouterConfig,\n RouterKeys,\n GetRoute,\n} from '../route/types';\n\n// ============================================================================\n// Validated Request\n// ============================================================================\n\n/**\n * A validated request with typed data.\n * This is what handlers receive after validation passes.\n */\nexport interface ValidatedRequest<TRoute extends RouteDefinition> {\n /**\n * Validated request body.\n */\n readonly body: TRoute['_types']['body'];\n\n /**\n * Validated query parameters.\n */\n readonly query: TRoute['_types']['query'];\n\n /**\n * Validated path parameters.\n */\n readonly pathParams: TRoute['_types']['pathParams'];\n\n /**\n * Validated headers.\n */\n readonly headers: TRoute['_types']['headers'];\n\n /**\n * Raw request object for advanced use cases.\n */\n readonly raw: {\n readonly method: string;\n readonly url: string;\n readonly headers: Record<string, string>;\n };\n}\n\n/**\n * Typed context based on route definition.\n * If the route defines a context schema, this will be the validated type.\n * Otherwise, it falls back to the generic HandlerContext.\n */\nexport type TypedContext<TRoute extends RouteDefinition> =\n TRoute['_types']['context'] extends undefined ? HandlerContext : TRoute['_types']['context'];\n\n// ============================================================================\n// Handler Types\n// ============================================================================\n\n/**\n * Context passed to handlers.\n * Can be extended with custom context via serverRoutes options.\n */\nexport interface HandlerContext {\n /**\n * Request ID for tracing.\n */\n readonly requestId?: string;\n\n /**\n * Additional context data.\n */\n readonly [key: string]: unknown;\n}\n\n/**\n * Response from a handler.\n */\nexport interface HandlerResponse<TData = unknown> {\n /**\n * HTTP status code.\n */\n readonly status: number;\n\n /**\n * Response body.\n */\n readonly body?: TData;\n\n /**\n * Response headers.\n */\n readonly headers?: Record<string, string>;\n}\n\n// ============================================================================\n// Use Case Port\n// ============================================================================\n\n/**\n * Use case port interface for unified routes.\n *\n * This is a simplified version that accepts any input/output types (plain objects).\n * It's structurally compatible with `BaseInboundPort`, so existing use case\n * implementations work without changes.\n *\n * @typeParam TInput - Input type (plain object or void for no input)\n * @typeParam TOutput - Output type (plain object or void for no output)\n *\n * @example\n * ```typescript\n * // Define plain types for use case contracts\n * type CreateProjectInput = {\n * name: string;\n * description?: string;\n * };\n *\n * type CreateProjectOutput = {\n * projectId: string;\n * };\n *\n * // Use case implements this interface\n * class CreateProjectUseCase implements UseCasePort<CreateProjectInput, CreateProjectOutput> {\n * async execute(input: CreateProjectInput): Promise<CreateProjectOutput> {\n * // ... implementation\n * return { projectId: '...' };\n * }\n * }\n * ```\n */\n\nexport interface UseCasePort<TInput = void, TOutput = void> {\n execute(input?: TInput): Promise<TOutput>;\n}\n\n// ============================================================================\n// Server Configuration\n// ============================================================================\n\n/**\n * Handler configuration for a single route.\n *\n * Mirrors the BaseController pattern with three components:\n * - `requestMapper`: Maps validated HTTP request to use case input\n * - `useCase`: The use case to execute\n * - `responseMapper`: Maps use case output to HTTP response\n *\n * @typeParam TRoute - The route definition type\n * @typeParam TInput - Use case input type (plain object)\n * @typeParam TOutput - Use case output type (plain object)\n *\n * @example\n * ```typescript\n * const config: RouteHandlerConfig<typeof createProjectRoute, CreateProjectInput, CreateProjectOutput> = {\n * requestMapper: (req) => ({\n * name: req.body.name,\n * description: req.body.description,\n * }),\n * useCase: createProjectUseCase,\n * responseMapper: (out) => ({\n * status: 201,\n * body: { projectId: out.projectId },\n * }),\n * };\n * ```\n */\n\nexport interface RouteHandlerConfig<TRoute extends RouteDefinition, TInput = void, TOutput = void> {\n /**\n * Maps the validated HTTP request to use case input.\n * The request has already been validated by the route's schemas.\n * Context is typed based on the route's context schema (if defined).\n */\n readonly requestMapper: (req: ValidatedRequest<TRoute>, ctx: TypedContext<TRoute>) => TInput;\n\n /**\n * The use case to execute.\n * Can be any object with an `execute` method matching `UseCasePort`.\n */\n readonly useCase: UseCasePort<TInput, TOutput>;\n\n /**\n * Maps the use case output to an HTTP response.\n * Determines the status code and response body.\n */\n readonly responseMapper: (output: TOutput) => HandlerResponse;\n\n /**\n * Middleware to run before the handler.\n */\n readonly middleware?: readonly MiddlewareFunction[];\n}\n\n/**\n * Middleware function type.\n */\nexport type MiddlewareFunction = (\n request: unknown,\n context: HandlerContext,\n next: () => Promise<HandlerResponse>,\n) => Promise<HandlerResponse>;\n\n// ============================================================================\n// Simple Handler Types\n// ============================================================================\n\n/**\n * Simple handler function that directly returns a response.\n * Use this for simple routes that don't need the use case pattern.\n */\nexport type SimpleHandlerFn<TRoute extends RouteDefinition> = (\n req: ValidatedRequest<TRoute>,\n ctx: TypedContext<TRoute>,\n) => Promise<HandlerResponse> | HandlerResponse;\n\n/**\n * Configuration for a simple handler (no use case).\n */\nexport interface SimpleHandlerConfig<TRoute extends RouteDefinition> {\n readonly handler: SimpleHandlerFn<TRoute>;\n readonly middleware?: readonly MiddlewareFunction[];\n}\n\n/**\n * Union of all handler config types.\n * Used internally to store handlers in the builder.\n */\nexport type AnyHandlerConfig<TRoute extends RouteDefinition, TInput = unknown, TOutput = unknown> =\n | RouteHandlerConfig<TRoute, TInput, TOutput>\n | SimpleHandlerConfig<TRoute>;\n\n/**\n * Type guard to check if config is a simple handler.\n */\nexport function isSimpleHandlerConfig(\n config: AnyHandlerConfig<RouteDefinition, unknown, unknown>,\n): config is SimpleHandlerConfig<RouteDefinition> {\n return 'handler' in config && typeof config.handler === 'function';\n}\n\n/**\n * Configuration mapping route keys to handlers.\n *\n * Each route key maps to a `RouteHandlerConfig` with:\n * - The route definition for that key (provides request/response types)\n * - User-defined input/output types for the use case\n *\n * The `TInput` and `TOutput` types are inferred from the `useCase` property,\n * so you don't need to specify them explicitly.\n */\n// TInput/TOutput are user-defined per route - any is required for heterogeneous route configs\nexport type ServerRoutesConfig<T extends RouterConfig> = {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [K in RouterKeys<T>]: RouteHandlerConfig<GetRoute<T, K>, any, any>;\n};\n\n/**\n * Options for creating server routes.\n */\nexport interface CreateServerRoutesOptions {\n /**\n * Global middleware to run before all handlers.\n */\n readonly middleware?: readonly MiddlewareFunction[];\n\n /**\n * Whether to validate incoming requests against route schemas.\n * When enabled, invalid requests throw InvalidRequestError.\n * @default true\n */\n readonly validateRequest?: boolean;\n\n /**\n * Whether to validate outgoing responses against route schemas.\n * When enabled, invalid responses throw ControllerError.\n * Useful for catching bugs and ensuring API contract compliance.\n * @default true\n */\n readonly validateResponse?: boolean;\n\n /**\n * Context factory to create handler context.\n */\n readonly createContext?: (rawRequest: unknown) => HandlerContext;\n\n /**\n * Allow partial handler configuration (not all routes need handlers).\n * When true, missing handlers are silently skipped.\n * When false (default), missing handlers throw an error.\n * @default false\n * @internal Used by builder pattern's buildPartial()\n */\n readonly allowPartial?: boolean;\n}\n\n// ============================================================================\n// Route Input (for framework adapters)\n// ============================================================================\n\n/**\n * Route input compatible with framework adapters.\n * This is the output of serverRoutes().build().\n */\nexport interface UnifiedRouteInput {\n /**\n * HTTP method.\n */\n readonly method: HttpMethod;\n\n /**\n * URL path pattern.\n */\n readonly path: string;\n\n /**\n * Handler function.\n */\n readonly handler: (\n rawRequest: RawHttpRequest,\n context?: HandlerContext,\n ) => Promise<HandlerResponse>;\n\n /**\n * Route metadata for documentation.\n */\n readonly metadata: {\n readonly operationId?: string;\n readonly summary?: string;\n readonly description?: string;\n readonly tags?: readonly string[];\n readonly deprecated?: boolean;\n };\n}\n\n/**\n * Raw HTTP request from the framework.\n */\nexport interface RawHttpRequest {\n readonly method: string;\n readonly url: string;\n readonly headers: Record<string, string | string[] | undefined>;\n readonly body?: unknown;\n readonly query?: Record<string, string | string[] | undefined>;\n readonly params?: Record<string, string>;\n}\n","import type { ErrorCode } from './error-codes.const';\n\n/**\n * Base error class for all application errors with a machine-readable code.\n *\n * Abstract class that extends the native `Error` with:\n * - A `code` property for programmatic error handling\n * - Optional `cause` for error chaining (ES2022 compatible)\n * - A `fromError` static factory pattern for error transformation\n *\n * **Why abstract:** Prevents non-declarative error usage. All errors must\n * be explicitly defined as subclasses to ensure consistent error taxonomy.\n *\n * @example Subclass implementation\n * ```typescript\n * class DbError extends InfraError {\n * static override fromError(cause: unknown): DbError {\n * return new DbError({\n * message: cause instanceof Error ? cause.message : 'Database error',\n * cause,\n * });\n * }\n * }\n * ```\n *\n * @example Usage with wrapErrorAsync\n * ```typescript\n * await wrapErrorAsync(\n * () => this.db.query(...),\n * DbError.fromError,\n * );\n * ```\n */\nexport abstract class CodedError extends Error {\n /** Machine-readable error code for programmatic handling. */\n public readonly code: ErrorCode | string;\n\n /**\n * Creates a new CodedError instance.\n *\n * @param options - Error configuration\n * @param options.message - Human-readable error message\n * @param options.code - Machine-readable error code from ErrorCodes registry or custom string\n * @param options.cause - Optional underlying error that caused this error\n */\n constructor({\n message,\n code,\n cause,\n }: {\n message: string;\n code: ErrorCode | string;\n cause?: unknown;\n }) {\n super(message);\n this.name = this.constructor.name;\n this.code = code;\n if (cause !== undefined) {\n Object.defineProperty(this, 'cause', {\n value: cause,\n writable: false,\n enumerable: false,\n configurable: true,\n });\n }\n }\n\n /**\n * Factory method to create a typed error from a caught error.\n *\n * Subclasses should override this to provide proper error transformation.\n * Designed for use with {@link wrapErrorAsync} and {@link wrapError}.\n *\n * @param _cause - The original caught error\n * @returns A new CodedError instance\n * @throws {Error} If not overridden by subclass\n *\n * @example\n * ```typescript\n * class NotFoundError extends UseCaseError {\n * static override fromError(cause: unknown): NotFoundError {\n * return new NotFoundError({\n * message: 'Resource not found',\n * cause,\n * });\n * }\n * }\n * ```\n */\n static fromError(_cause: unknown): CodedError {\n throw new Error(`${this.name}.fromError() must be implemented by subclass`);\n }\n}\n","/**\n * Centralized registry of all error codes used across the application.\n *\n * Error codes are grouped by architectural layer to maintain clear boundaries\n * and make it easy to identify where an error originated.\n *\n * @example Using error codes in custom errors\n * ```typescript\n * import { ErrorCodes } from '@cosmneo/onion-lasagna/global';\n *\n * throw new NotFoundError({\n * message: 'User not found',\n * code: ErrorCodes.App.NOT_FOUND,\n * });\n * ```\n *\n * @example Checking error codes programmatically\n * ```typescript\n * if (error.code === ErrorCodes.App.NOT_FOUND) {\n * // Handle not found case\n * }\n * ```\n */\nexport const ErrorCodes = {\n /**\n * Domain layer error codes.\n * Used for business rule violations and invariant failures.\n */\n Domain: {\n /** Generic domain error */\n DOMAIN_ERROR: 'DOMAIN_ERROR',\n /** Business invariant was violated */\n INVARIANT_VIOLATION: 'INVARIANT_VIOLATION',\n /** Aggregate was partially loaded (missing required relations) */\n PARTIAL_LOAD: 'PARTIAL_LOAD',\n },\n\n /**\n * Application layer (use case) error codes.\n * Used for orchestration failures and business operation errors.\n */\n App: {\n /** Generic use case error */\n USE_CASE_ERROR: 'USE_CASE_ERROR',\n /** Requested resource was not found */\n NOT_FOUND: 'NOT_FOUND',\n /** Resource state conflict (e.g., duplicate, already exists) */\n CONFLICT: 'CONFLICT',\n /** Request is valid but cannot be processed due to business rules */\n UNPROCESSABLE: 'UNPROCESSABLE',\n /** Authorization denied - user lacks permission for this operation */\n FORBIDDEN: 'FORBIDDEN',\n /** Authentication required or invalid - user is not authenticated */\n UNAUTHORIZED: 'UNAUTHORIZED',\n },\n\n /**\n * Infrastructure layer error codes.\n * Used for data access, external services, and I/O failures.\n */\n Infra: {\n /** Generic infrastructure error */\n INFRA_ERROR: 'INFRA_ERROR',\n /** Database operation failed */\n DB_ERROR: 'DB_ERROR',\n /** Network connectivity or communication error */\n NETWORK_ERROR: 'NETWORK_ERROR',\n /** Operation timed out */\n TIMEOUT_ERROR: 'TIMEOUT_ERROR',\n /** External/third-party service error */\n EXTERNAL_SERVICE_ERROR: 'EXTERNAL_SERVICE_ERROR',\n },\n\n /**\n * Presentation layer error codes.\n * Used for controller, request handling, and authorization errors.\n */\n Presentation: {\n /** Generic controller error */\n CONTROLLER_ERROR: 'CONTROLLER_ERROR',\n /** Request denied due to authorization failure */\n ACCESS_DENIED: 'ACCESS_DENIED',\n /** Request validation failed (malformed input) */\n INVALID_REQUEST: 'INVALID_REQUEST',\n },\n\n /**\n * Global/cross-cutting error codes.\n * Used for validation and other cross-layer concerns.\n */\n Global: {\n /** Object/schema validation failed */\n OBJECT_VALIDATION_ERROR: 'OBJECT_VALIDATION_ERROR',\n },\n} as const;\n\n/**\n * Type representing all possible domain error codes.\n */\nexport type DomainErrorCode = (typeof ErrorCodes.Domain)[keyof typeof ErrorCodes.Domain];\n\n/**\n * Type representing all possible application error codes.\n */\nexport type AppErrorCode = (typeof ErrorCodes.App)[keyof typeof ErrorCodes.App];\n\n/**\n * Type representing all possible infrastructure error codes.\n */\nexport type InfraErrorCode = (typeof ErrorCodes.Infra)[keyof typeof ErrorCodes.Infra];\n\n/**\n * Type representing all possible presentation error codes.\n */\nexport type PresentationErrorCode =\n (typeof ErrorCodes.Presentation)[keyof typeof ErrorCodes.Presentation];\n\n/**\n * Type representing all possible global error codes.\n */\nexport type GlobalErrorCode = (typeof ErrorCodes.Global)[keyof typeof ErrorCodes.Global];\n\n/**\n * Union type of all error codes across all layers.\n *\n * Use this when you need to accept any valid error code.\n *\n * @example\n * ```typescript\n * function logError(code: ErrorCode, message: string) {\n * console.error(`[${code}] ${message}`);\n * }\n * ```\n */\nexport type ErrorCode =\n | DomainErrorCode\n | AppErrorCode\n | InfraErrorCode\n | PresentationErrorCode\n | GlobalErrorCode;\n","import { CodedError } from '../../global/exceptions/coded-error.error';\nimport { ErrorCodes, type PresentationErrorCode } from '../../global/exceptions/error-codes.const';\nimport type { ValidationError } from '../../global/interfaces/types/validation-error.type';\n\n/**\n * Error thrown when request validation fails at the controller level.\n *\n * Contains structured validation errors with field paths and messages,\n * converted from {@link ObjectValidationError} by {@link BaseController}.\n * Provides detailed feedback about which fields failed validation.\n *\n * **When thrown:**\n * - Request DTO validation fails\n * - Malformed request data\n * - Missing required fields\n *\n * @example\n * ```typescript\n * // Automatically thrown by BaseController when DTO validation fails\n * // The validationErrors array contains field-level details:\n * // [\n * // { field: 'email', message: 'Invalid email format' },\n * // { field: 'age', message: 'Must be a positive number' }\n * // ]\n * ```\n *\n * @example Manual usage\n * ```typescript\n * throw new InvalidRequestError({\n * message: 'Request validation failed',\n * validationErrors: [\n * { field: 'username', message: 'Username is required' },\n * ],\n * });\n * ```\n *\n * @extends CodedError\n */\nexport class InvalidRequestError extends CodedError {\n /**\n * Array of field-level validation errors.\n *\n * Each entry contains:\n * - `field`: Dot-notation path to the invalid field\n * - `message`: Human-readable validation failure message\n */\n readonly validationErrors: ValidationError[];\n\n /**\n * Creates a new InvalidRequestError instance.\n *\n * @param options - Error configuration\n * @param options.message - Summary of the validation failure\n * @param options.code - Machine-readable error code (default: 'INVALID_REQUEST')\n * @param options.cause - Optional underlying error\n * @param options.validationErrors - Array of field-level validation errors\n */\n constructor({\n message,\n code = ErrorCodes.Presentation.INVALID_REQUEST,\n cause,\n validationErrors,\n }: {\n message: string;\n code?: PresentationErrorCode | string;\n cause?: unknown;\n validationErrors: ValidationError[];\n }) {\n super({ message, code, cause });\n this.validationErrors = validationErrors;\n }\n\n /**\n * Creates an InvalidRequestError from a caught error.\n *\n * @param cause - The original caught error\n * @returns A new InvalidRequestError instance with the cause attached\n */\n static override fromError(cause: unknown): InvalidRequestError {\n return new InvalidRequestError({\n message: cause instanceof Error ? cause.message : 'Invalid request',\n cause,\n validationErrors: [],\n });\n }\n}\n","import { CodedError } from '../../global/exceptions/coded-error.error';\nimport { ErrorCodes, type PresentationErrorCode } from '../../global/exceptions/error-codes.const';\n\n/**\n * Base error class for presentation layer (controller) failures.\n *\n * Controller errors represent failures in request handling,\n * such as access control violations or malformed requests.\n * They are the outermost error layer and typically map to HTTP responses.\n *\n * **When to throw:**\n * - Access control failures (unauthorized/forbidden)\n * - Request validation failures\n * - Unexpected controller execution errors\n *\n * **Child classes:**\n * - {@link AccessDeniedError} - Authorization failures (HTTP 403)\n * - {@link InvalidRequestError} - Request validation failures (HTTP 400)\n *\n * @example\n * ```typescript\n * // Thrown automatically by BaseController for unexpected errors\n * throw new ControllerError({\n * message: 'Controller execution failed',\n * cause: originalError,\n * });\n * ```\n */\nexport class ControllerError extends CodedError {\n /**\n * Creates a new ControllerError instance.\n *\n * @param options - Error configuration\n * @param options.message - Human-readable error description\n * @param options.code - Machine-readable error code (default: 'CONTROLLER_ERROR')\n * @param options.cause - Optional underlying error\n */\n constructor({\n message,\n code = ErrorCodes.Presentation.CONTROLLER_ERROR,\n cause,\n }: {\n message: string;\n code?: PresentationErrorCode | string;\n cause?: unknown;\n }) {\n super({ message, code, cause });\n }\n\n /**\n * Creates a ControllerError from a caught error.\n *\n * @param cause - The original caught error\n * @returns A new ControllerError instance with the cause attached\n */\n static override fromError(cause: unknown): ControllerError {\n return new ControllerError({\n message: cause instanceof Error ? cause.message : 'Controller error',\n cause,\n });\n }\n}\n","import { CodedError } from '../../global/exceptions/coded-error.error';\nimport { ErrorCodes, type AppErrorCode } from '../../global/exceptions/error-codes.const';\n\n/**\n * Base error class for application layer (use case) failures.\n *\n * Use case errors represent failures in the application's business logic\n * orchestration, such as resource conflicts, missing entities, or\n * unprocessable requests. They bridge domain errors to the presentation layer.\n *\n * **When to throw:**\n * - Resource not found (e.g., \"User with ID X not found\")\n * - Conflict states (e.g., \"Email already registered\")\n * - Unprocessable business operations\n *\n * **Child classes:**\n * - {@link ConflictError} - Resource state conflicts (HTTP 409)\n * - {@link NotFoundError} - Resource not found (HTTP 404)\n * - {@link UnprocessableError} - Valid but unprocessable request (HTTP 422)\n *\n * @example\n * ```typescript\n * const user = await this.userRepo.findById(id);\n * if (!user) {\n * throw new NotFoundError({\n * message: `User with ID ${id} not found`,\n * code: 'USER_NOT_FOUND',\n * });\n * }\n * ```\n */\nexport class UseCaseError extends CodedError {\n /**\n * Creates a new UseCaseError instance.\n *\n * @param options - Error configuration\n * @param options.message - Human-readable error description\n * @param options.code - Machine-readable error code (default: 'USE_CASE_ERROR')\n * @param options.cause - Optional underlying error\n */\n constructor({\n message,\n code = ErrorCodes.App.USE_CASE_ERROR,\n cause,\n }: {\n message: string;\n code?: AppErrorCode | string;\n cause?: unknown;\n }) {\n super({ message, code, cause });\n }\n\n /**\n * Creates a UseCaseError from a caught error.\n *\n * @param cause - The original caught error\n * @returns A new UseCaseError instance with the cause attached\n */\n static override fromError(cause: unknown): UseCaseError {\n return new UseCaseError({\n message: cause instanceof Error ? cause.message : 'Use case error',\n cause,\n });\n }\n}\n","import { ErrorCodes, type AppErrorCode } from '../../global/exceptions/error-codes.const';\nimport { UseCaseError } from './use-case.error';\n\n/**\n * Error thrown when authentication is required or invalid.\n *\n * Indicates that the user is not authenticated or their authentication\n * credentials are invalid/expired. This is different from `ForbiddenError`\n * which is for authenticated users who lack permission.\n *\n * **When to throw:**\n * - User is not logged in but authentication is required\n * - Authentication token is missing, invalid, or expired\n * - Session has been invalidated\n * - API key is invalid or revoked\n *\n * **Difference from ForbiddenError:**\n * - `UnauthorizedError` (401) = Not authenticated (who are you?)\n * - `ForbiddenError` (403) = Authenticated but not authorized (you can't do this)\n *\n * @example Missing authentication\n * ```typescript\n * protected async authorize(input: Input): Promise<AuthContext> {\n * if (!input.userId) {\n * throw new UnauthorizedError({ message: 'Authentication required' });\n * }\n *\n * const user = await this.userRepo.findById(input.userId);\n * if (!user) {\n * throw new UnauthorizedError({ message: 'Invalid user credentials' });\n * }\n *\n * return { user };\n * }\n * ```\n *\n * @example Token validation\n * ```typescript\n * if (!token || isTokenExpired(token)) {\n * throw new UnauthorizedError({\n * message: 'Session expired, please log in again',\n * code: 'SESSION_EXPIRED',\n * });\n * }\n * ```\n *\n * @extends UseCaseError\n */\nexport class UnauthorizedError extends UseCaseError {\n /**\n * Creates a new UnauthorizedError instance.\n *\n * @param options - Error configuration\n * @param options.message - Description of why authentication failed\n * @param options.code - Machine-readable error code (default: 'UNAUTHORIZED')\n * @param options.cause - Optional underlying error\n */\n constructor({\n message,\n code = ErrorCodes.App.UNAUTHORIZED,\n cause,\n }: {\n message: string;\n code?: AppErrorCode | string;\n cause?: unknown;\n }) {\n super({ message, code, cause });\n }\n\n /**\n * Creates an UnauthorizedError from a caught error.\n *\n * @param cause - The original caught error\n * @returns A new UnauthorizedError instance with the cause attached\n */\n static override fromError(cause: unknown): UnauthorizedError {\n return new UnauthorizedError({\n message: cause instanceof Error ? cause.message : 'Authentication required',\n cause,\n });\n }\n}\n","/**\n * Error wrapping utilities for boundary error handling.\n *\n * Provides functions to wrap code execution with error transformation,\n * converting caught errors into typed Error instances.\n * Useful at layer boundaries (infra, use case, controller) to normalize errors.\n *\n * @example Wrapping async database calls\n * ```typescript\n * const user = await wrapErrorAsync(\n * () => this.db.query('SELECT * FROM users WHERE id = ?', [id]),\n * (cause) => new DbError({ message: 'Failed to fetch user', cause }),\n * );\n * ```\n *\n * @example Wrapping sync operations\n * ```typescript\n * const parsed = wrapError(\n * () => JSON.parse(data),\n * (cause) => new InvariantViolationError({\n * message: 'Invalid JSON format',\n * cause,\n * }),\n * );\n * ```\n *\n * @module\n */\n\n/**\n * Factory function that creates an Error from a caught error.\n *\n * @typeParam E - The specific Error subclass to create\n * @param cause - The original caught error\n * @returns A new Error instance\n */\nexport type ErrorFactory<E extends Error> = (cause: unknown) => E;\n\n/**\n * Wraps a synchronous function with error transformation.\n *\n * Executes the provided function and catches any thrown errors,\n * transforming them using the error factory.\n *\n * @typeParam T - The return type of the wrapped function\n * @typeParam E - The Error subclass to throw on error\n * @param fn - The function to execute\n * @param errorFactory - Factory to create the typed error from the caught error\n * @returns The result of the function if successful\n * @throws {E} The transformed error if the function throws\n *\n * @example\n * ```typescript\n * const config = wrapError(\n * () => JSON.parse(configString),\n * (cause) => new InvariantViolationError({\n * message: 'Invalid configuration format',\n * code: 'CONFIG_PARSE_ERROR',\n * cause,\n * }),\n * );\n * ```\n */\nexport function wrapError<T, E extends Error>(fn: () => T, errorFactory: ErrorFactory<E>): T {\n try {\n return fn();\n } catch (error) {\n throw errorFactory(error);\n }\n}\n\n/**\n * Wraps an asynchronous function with error transformation.\n *\n * Executes the provided async function and catches any thrown errors,\n * transforming them using the error factory.\n *\n * @typeParam T - The return type of the wrapped function\n * @typeParam E - The Error subclass to throw on error\n * @param fn - The async function to execute\n * @param errorFactory - Factory to create the typed error from the caught error\n * @returns A promise resolving to the result if successful\n * @throws {E} The transformed error if the function throws\n *\n * @example Repository usage\n * ```typescript\n * async findById(id: string): Promise<User | null> {\n * return wrapErrorAsync(\n * () => this.db.users.findUnique({ where: { id } }),\n * (cause) => new DbError({\n * message: `Failed to find user by ID: ${id}`,\n * cause,\n * }),\n * );\n * }\n * ```\n *\n * @example External service usage\n * ```typescript\n * async sendEmail(to: string, body: string): Promise<void> {\n * await wrapErrorAsync(\n * () => this.emailClient.send({ to, body }),\n * (cause) => new ExternalServiceError({\n * message: 'Email delivery failed',\n * code: 'EMAIL_SEND_FAILED',\n * cause,\n * }),\n * );\n * }\n * ```\n */\nexport async function wrapErrorAsync<T, E extends Error>(\n fn: () => Promise<T>,\n errorFactory: ErrorFactory<E>,\n): Promise<T> {\n try {\n return await fn();\n } catch (error) {\n throw errorFactory(error);\n }\n}\n\n/**\n * Constructor type for error classes (including abstract classes).\n *\n * Used to specify error types that should pass through without transformation.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type ErrorConstructor = abstract new (...args: any[]) => Error;\n\n/**\n * Wraps a synchronous function with conditional error transformation.\n *\n * Executes the provided function and catches any thrown errors.\n * Errors matching any of the passthrough types are re-thrown as-is.\n * All other errors are transformed using the error factory.\n *\n * @typeParam T - The return type of the wrapped function\n * @typeParam E - The Error subclass to throw for unknown errors\n * @param fn - The function to execute\n * @param errorFactory - Factory to create the typed error from unknown errors\n * @param passthroughTypes - Array of error classes to re-throw without transformation\n * @returns The result of the function if successful\n * @throws The original error if it matches a passthrough type\n * @throws {E} The transformed error for unknown error types\n *\n * @example Controller boundary\n * ```typescript\n * const result = wrapErrorUnless(\n * () => this.requestMapper(input),\n * (cause) => new ControllerError({ message: 'Mapping failed', cause }),\n * [CodedError],\n * );\n * ```\n */\nexport function wrapErrorUnless<T, E extends Error>(\n fn: () => T,\n errorFactory: ErrorFactory<E>,\n passthroughTypes: ErrorConstructor[],\n): T {\n try {\n return fn();\n } catch (error) {\n if (passthroughTypes.some((Type) => error instanceof Type)) {\n throw error;\n }\n throw errorFactory(error);\n }\n}\n\n/**\n * Wraps an asynchronous function with conditional error transformation.\n *\n * Executes the provided async function and catches any thrown errors.\n * Errors matching any of the passthrough types are re-thrown as-is.\n * All other errors are transformed using the error factory.\n *\n * @typeParam T - The return type of the wrapped function\n * @typeParam E - The Error subclass to throw for unknown errors\n * @param fn - The async function to execute\n * @param errorFactory - Factory to create the typed error from unknown errors\n * @param passthroughTypes - Array of error classes to re-throw without transformation\n * @returns A promise resolving to the result if successful\n * @throws The original error if it matches a passthrough type\n * @throws {E} The transformed error for unknown error types\n *\n * @example Use case boundary\n * ```typescript\n * return wrapErrorUnlessAsync(\n * () => this.handle(input),\n * (cause) => new UseCaseError({ message: 'Unexpected error', cause }),\n * [ObjectValidationError, UseCaseError, DomainError, InfraError],\n * );\n * ```\n *\n * @example Controller boundary\n * ```typescript\n * return wrapErrorUnlessAsync(\n * async () => {\n * const result = await this.useCase.execute(input);\n * return this.responseMapper(result);\n * },\n * (cause) => new ControllerError({ message: 'Controller failed', cause }),\n * [CodedError],\n * );\n * ```\n */\nexport async function wrapErrorUnlessAsync<T, E extends Error>(\n fn: () => Promise<T>,\n errorFactory: ErrorFactory<E>,\n passthroughTypes: ErrorConstructor[],\n): Promise<T> {\n try {\n return await fn();\n } catch (error) {\n if (passthroughTypes.some((Type) => error instanceof Type)) {\n throw error;\n }\n throw errorFactory(error);\n }\n}\n","/**\n * @fileoverview Internal implementation for creating server routes with auto-validation.\n *\n * Generates server-side route handlers from a router definition.\n * Each handler automatically validates incoming requests and outgoing\n * responses against the route's schemas.\n *\n * @module unified/server/create-server-routes\n * @internal\n */\n\nimport type { SchemaAdapter, ValidationIssue } from '../schema/types';\nimport type { RouterConfig, RouterDefinition, RouteDefinition } from '../route/types';\nimport { isRouterDefinition, collectRoutes, normalizePath } from '../route/types';\nimport type {\n AnyHandlerConfig,\n CreateServerRoutesOptions,\n HandlerContext,\n HandlerResponse,\n RawHttpRequest,\n UnifiedRouteInput,\n ValidatedRequest,\n} from './types';\nimport { isSimpleHandlerConfig } from './types';\nimport { InvalidRequestError } from '../../exceptions/invalid-request.error';\nimport { ControllerError } from '../../exceptions/controller.error';\nimport { UnauthorizedError } from '../../../app/exceptions/unauthorized.error';\nimport { wrapError } from '../../../global/utils/wrap-error.util';\n\n/**\n * Internal implementation for creating server routes.\n * Used by the builder pattern (serverRoutes).\n *\n * @internal\n */\nexport function createServerRoutesInternal<T extends RouterConfig>(\n router: T | RouterDefinition<T>,\n handlers: Record<string, AnyHandlerConfig<RouteDefinition, unknown, unknown>>,\n options?: CreateServerRoutesOptions,\n): UnifiedRouteInput[] {\n const routes = isRouterDefinition(router) ? router.routes : router;\n const collectedRoutes = collectRoutes(routes);\n\n // Sort routes by specificity: static segments before parameterized\n // This ensures /api/users/me is registered before /api/users/:userId\n const sortedRoutes = sortRoutesBySpecificity(collectedRoutes);\n\n const result: UnifiedRouteInput[] = [];\n\n // Default validation options to true, allowPartial to false\n const resolvedOptions: CreateServerRoutesOptions = {\n ...options,\n validateRequest: options?.validateRequest ?? true,\n validateResponse: options?.validateResponse ?? true,\n allowPartial: options?.allowPartial ?? false,\n };\n\n for (const { key, route } of sortedRoutes) {\n const handlerConfig = handlers[key] as AnyHandlerConfig<RouteDefinition, any, any> | undefined;\n\n if (!handlerConfig) {\n if (resolvedOptions.allowPartial) {\n // Skip routes without handlers when allowPartial is true\n continue;\n }\n throw new Error(\n `Missing handler for route \"${key}\". All routes must have a handler configuration.`,\n );\n }\n\n result.push(createRouteHandler(route, handlerConfig, resolvedOptions));\n }\n\n return result;\n}\n\n/**\n * Sorts routes by path specificity to ensure correct route matching.\n *\n * Static path segments are sorted before parameterized segments at each position.\n * This ensures that `/api/users/me` is registered before `/api/users/:userId`,\n * preventing the parameterized route from incorrectly matching the static path.\n *\n * @example\n * Given routes:\n * - /api/users/:userId (parameterized)\n * - /api/users/me (static)\n *\n * After sorting:\n * - /api/users/me (registered first - matches exactly)\n * - /api/users/:userId (registered second - catches remaining)\n */\nfunction sortRoutesBySpecificity<T extends { route: { path: string } }>(routes: T[]): T[] {\n return [...routes].sort((a, b) => {\n const aSegments = a.route.path.split('/').filter(Boolean);\n const bSegments = b.route.path.split('/').filter(Boolean);\n\n const maxLen = Math.max(aSegments.length, bSegments.length);\n\n for (let i = 0; i < maxLen; i++) {\n const aSeg = aSegments[i];\n const bSeg = bSegments[i];\n\n // Missing segment (shorter path) - shorter paths first for same prefix\n if (aSeg === undefined && bSeg !== undefined) return -1;\n if (aSeg !== undefined && bSeg === undefined) return 1;\n if (aSeg === undefined || bSeg === undefined) return 0;\n\n // Check if segment is parameterized (supports both :param and {param} formats)\n const aIsParam = aSeg.startsWith(':') || (aSeg.startsWith('{') && aSeg.endsWith('}'));\n const bIsParam = bSeg.startsWith(':') || (bSeg.startsWith('{') && bSeg.endsWith('}'));\n\n // Static segments come before parameterized segments\n if (!aIsParam && bIsParam) return -1;\n if (aIsParam && !bIsParam) return 1;\n\n // Both static or both parameterized - compare alphabetically for stable sorting\n const cmp = aSeg.localeCompare(bSeg);\n if (cmp !== 0) return cmp;\n }\n\n return 0;\n });\n}\n\n/**\n * Creates a single route handler with validation.\n *\n * Supports two handler patterns:\n * - Simple handler: handler(req, ctx) → response\n * - Use case pattern: requestMapper → useCase.execute → responseMapper\n */\nfunction createRouteHandler(\n route: RouteDefinition,\n // TInput/TOutput are user-defined and erased at this level - any is required for type compatibility\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n config: AnyHandlerConfig<RouteDefinition, any, any>,\n options: CreateServerRoutesOptions,\n): UnifiedRouteInput {\n const middleware = config.middleware ?? [];\n const globalMiddleware = options?.middleware ?? [];\n const allMiddleware = [...globalMiddleware, ...middleware];\n\n const shouldValidateRequest = options.validateRequest ?? true;\n const shouldValidateResponse = options.validateResponse ?? true;\n\n return {\n method: route.method,\n path: normalizePath(route.path),\n metadata: {\n operationId: route.docs.operationId,\n summary: route.docs.summary,\n description: route.docs.description,\n tags: route.docs.tags as string[],\n deprecated: route.docs.deprecated,\n },\n handler: async (rawRequest: RawHttpRequest, ctx?: HandlerContext): Promise<HandlerResponse> => {\n // Create context\n const rawContext: HandlerContext = options?.createContext\n ? options.createContext(rawRequest)\n : (ctx ?? { requestId: generateRequestId() });\n\n // Validate context (if schema defined)\n // Context validation failures are treated as authentication errors (401)\n // because context typically carries auth data (user, session, token).\n // A missing or invalid context means the caller is not properly authenticated.\n const validatedContext: unknown = route.request.context?.schema\n ? wrapError(\n () => {\n const result = validateContextData(route, rawContext);\n if (!result.success) {\n const errors = result.errors ?? [];\n throw new InvalidRequestError({\n message: 'Context validation failed',\n validationErrors: errors.map((e) => ({\n field: e.path.join('.'),\n message: e.message,\n })),\n });\n }\n return result.data;\n },\n () => new UnauthorizedError({ message: 'Authentication required' }),\n )\n : rawContext;\n\n // Validate request (if enabled)\n // Use internal type since specific route types are erased in this function\n let validatedRequest: ValidatedRequestInternal;\n\n if (shouldValidateRequest) {\n const validationResult = validateRequestData(route, rawRequest);\n\n if (!validationResult.success) {\n const errors = validationResult.errors ?? [];\n throw new InvalidRequestError({\n message: 'Request validation failed',\n validationErrors: errors.map((e) => ({\n field: e.path.join('.'),\n message: e.message,\n })),\n });\n }\n\n const data = validationResult.data ?? {};\n\n validatedRequest = {\n body: data.body,\n query: data.query,\n pathParams: data.pathParams,\n headers: data.headers,\n raw: {\n method: rawRequest.method,\n url: rawRequest.url,\n headers: normalizeHeaders(rawRequest.headers),\n },\n };\n } else {\n // Skip validation - pass through normalized data\n\n validatedRequest = {\n body: rawRequest.body,\n query: normalizeQuery(rawRequest.query),\n pathParams: normalizePathParams(rawRequest.params),\n headers: normalizeHeaders(rawRequest.headers),\n raw: {\n method: rawRequest.method,\n url: rawRequest.url,\n headers: normalizeHeaders(rawRequest.headers),\n },\n };\n }\n\n // Execute the pipeline based on handler type\n // Errors from the use case/handler propagate to the framework's error handler\n const executePipeline = async (): Promise<HandlerResponse> => {\n if (isSimpleHandlerConfig(config)) {\n // Simple handler: direct call\n return config.handler(\n validatedRequest as unknown as ValidatedRequest<RouteDefinition>,\n validatedContext as HandlerContext,\n );\n } else {\n // Use case handler: requestMapper → useCase → responseMapper\n const { requestMapper, useCase, responseMapper } = config;\n\n // Map request to use case input\n // Cast is safe: ValidatedRequestInternal has same shape as ValidatedRequest<TRoute>\n // Type erasure in this function requires the cast for TypeScript\n // validatedContext is typed correctly based on route's context schema\n const input = requestMapper(\n validatedRequest as unknown as ValidatedRequest<RouteDefinition>,\n validatedContext as HandlerContext,\n );\n\n // Execute use case\n const output = await useCase.execute(input);\n\n // Map output to HTTP response\n return responseMapper(output);\n }\n };\n\n let response: HandlerResponse;\n\n if (allMiddleware.length === 0) {\n response = await executePipeline();\n } else {\n // Build middleware chain\n // Note: Middleware receives the raw context before validation\n let index = 0;\n const next = async (): Promise<HandlerResponse> => {\n if (index >= allMiddleware.length) {\n return executePipeline();\n }\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- index bounds checked above\n const mw = allMiddleware[index++]!;\n return mw(rawRequest, rawContext, next);\n };\n\n response = await next();\n }\n\n // Always validate status code (must be 100-599)\n validateStatusCode(response.status);\n\n // Validate response schema (if enabled)\n if (shouldValidateResponse) {\n const responseValidationResult = validateResponseData(route, response);\n\n if (!responseValidationResult.success) {\n const errors = responseValidationResult.errors ?? [];\n throw new ControllerError({\n message: 'Response validation failed',\n code: 'RESPONSE_VALIDATION_ERROR',\n cause: new Error(errors.map((e) => `${e.path.join('.')}: ${e.message}`).join('; ')),\n });\n }\n }\n\n return response;\n },\n };\n}\n\n/**\n * Validates request data against route schemas.\n */\nfunction validateRequestData(\n route: RouteDefinition,\n rawRequest: RawHttpRequest,\n): ValidationResultInternal {\n const errors: ValidationIssue[] = [];\n const data: {\n body?: unknown;\n query?: unknown;\n pathParams?: unknown;\n headers?: unknown;\n } = {};\n\n // Validate body\n if (route.request.body?.schema) {\n const result = (route.request.body.schema as SchemaAdapter).validate(rawRequest.body);\n if (result.success) {\n data.body = result.data;\n } else {\n errors.push(\n ...result.issues.map((issue) => ({\n ...issue,\n path: ['body', ...issue.path],\n })),\n );\n }\n }\n\n // Validate query\n if (route.request.query?.schema) {\n const queryObj = normalizeQuery(rawRequest.query);\n const result = (route.request.query.schema as SchemaAdapter).validate(queryObj);\n if (result.success) {\n data.query = result.data;\n } else {\n errors.push(\n ...result.issues.map((issue) => ({\n ...issue,\n path: ['query', ...issue.path],\n })),\n );\n }\n }\n\n // Validate path params\n if (route.request.params?.schema) {\n const result = (route.request.params.schema as SchemaAdapter).validate(rawRequest.params ?? {});\n if (result.success) {\n data.pathParams = result.data;\n } else {\n errors.push(\n ...result.issues.map((issue) => ({\n ...issue,\n path: ['pathParams', ...issue.path],\n })),\n );\n }\n } else {\n // Normalize raw params if no schema (ensure all values are strings)\n data.pathParams = normalizePathParams(rawRequest.params);\n }\n\n // Validate headers\n if (route.request.headers?.schema) {\n const headersObj = normalizeHeaders(rawRequest.headers);\n const result = (route.request.headers.schema as SchemaAdapter).validate(headersObj);\n if (result.success) {\n data.headers = result.data;\n } else {\n errors.push(\n ...result.issues.map((issue) => ({\n ...issue,\n path: ['headers', ...issue.path],\n })),\n );\n }\n }\n\n if (errors.length > 0) {\n return { success: false, errors };\n }\n\n return { success: true, data };\n}\n\n/**\n * Validates response data against route response schemas.\n */\nfunction validateResponseData(\n route: RouteDefinition,\n response: HandlerResponse,\n): ValidationResultInternal {\n const statusCode = String(response.status);\n const responses = route.responses as Record<string, { schema?: SchemaAdapter } | undefined>;\n const responseConfig = responses[statusCode];\n\n // No schema defined for this status code - skip validation\n if (!responseConfig) {\n return { success: true };\n }\n\n const schema = responseConfig.schema;\n\n // No schema in the response config - skip validation\n if (!schema) {\n return { success: true };\n }\n\n // Validate response body against schema\n const result = schema.validate(response.body);\n\n if (result.success) {\n return { success: true };\n }\n\n // Prefix errors with 'response.' for clarity\n const errors = result.issues.map((issue) => ({\n ...issue,\n path: ['response', ...issue.path],\n }));\n\n return { success: false, errors };\n}\n\n/**\n * Validates context data against route context schema.\n */\nfunction validateContextData(\n route: RouteDefinition,\n context: HandlerContext,\n): ContextValidationResultInternal {\n const contextSchema = route.request.context?.schema as SchemaAdapter | undefined;\n\n // No context schema defined - skip validation\n if (!contextSchema) {\n return { success: true, data: context };\n }\n\n // Validate context against schema\n const result = contextSchema.validate(context);\n\n if (result.success) {\n return { success: true, data: result.data };\n }\n\n // Prefix errors with 'context.' for clarity\n const errors = result.issues.map((issue) => ({\n ...issue,\n path: ['context', ...issue.path],\n }));\n\n return { success: false, errors };\n}\n\ninterface ValidationResultInternal {\n success: boolean;\n errors?: ValidationIssue[];\n data?: {\n body?: unknown;\n query?: unknown;\n pathParams?: unknown;\n headers?: unknown;\n };\n}\n\ninterface ContextValidationResultInternal {\n success: boolean;\n errors?: ValidationIssue[];\n data?: unknown;\n}\n\n/**\n * Internal validated request type with unknown fields.\n * Used inside createRouteHandler where specific types are erased.\n * The requestMapper receives the properly typed ValidatedRequest<TRoute>.\n */\ninterface ValidatedRequestInternal {\n readonly body: unknown;\n readonly query: unknown;\n readonly pathParams: unknown;\n readonly headers: unknown;\n readonly raw: {\n readonly method: string;\n readonly url: string;\n readonly headers: Record<string, string>;\n };\n}\n\n/**\n * Validates that an HTTP status code is in the valid range (100-599).\n *\n * @throws {ControllerError} If the status code is invalid\n */\nfunction validateStatusCode(status: number): void {\n if (!Number.isInteger(status) || status < 100 || status > 599) {\n throw new ControllerError({\n message: `Invalid HTTP status code: ${status}. Status must be an integer between 100 and 599.`,\n code: 'INVALID_STATUS_CODE',\n });\n }\n}\n\n/**\n * Normalizes query parameters, preserving arrays for duplicate keys.\n *\n * When a query parameter appears multiple times (e.g., `?tag=a&tag=b`),\n * the framework provides an array. This function preserves that array\n * so schema validation can properly validate array vs single-value params.\n *\n * Empty strings are allowed (e.g., `?flag=` results in `{ flag: '' }`).\n * Undefined values are filtered out from arrays.\n */\nfunction normalizeQuery(\n query?: Record<string, string | string[] | undefined>,\n): Record<string, string | string[]> {\n if (!query) return {};\n\n const result: Record<string, string | string[]> = {};\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined) continue;\n\n if (Array.isArray(value)) {\n // Filter out undefined values but preserve the array structure\n const definedValues = value.filter((v): v is string => v !== undefined);\n if (definedValues.length === 1 && definedValues[0] !== undefined) {\n // Single value in array - unwrap for convenience\n result[key] = definedValues[0];\n } else if (definedValues.length > 1) {\n // Multiple values - preserve as array for schema validation\n result[key] = definedValues;\n }\n // Empty array (all undefined) - skip this key\n } else {\n result[key] = value;\n }\n }\n return result;\n}\n\n/**\n * Normalizes path parameters to ensure all values are non-empty strings.\n *\n * @throws {InvalidRequestError} If any path parameter is empty\n */\nfunction normalizePathParams(params?: Record<string, string>): Record<string, string> {\n if (!params) return {};\n\n const result: Record<string, string> = {};\n const emptyParams: string[] = [];\n\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined) {\n const stringValue = String(value);\n if (stringValue === '') {\n emptyParams.push(key);\n } else {\n result[key] = stringValue;\n }\n }\n }\n\n // Throw error for empty path params instead of silently filtering\n if (emptyParams.length > 0) {\n throw new InvalidRequestError({\n message: 'Path parameters cannot be empty',\n validationErrors: emptyParams.map((param) => ({\n field: `pathParams.${param}`,\n message: 'Path parameter cannot be empty',\n })),\n });\n }\n\n return result;\n}\n\n/**\n * Normalizes headers to a flat object.\n *\n * Per RFC 7230, multiple header values are joined with \", \" (comma + space).\n * Headers are lowercased for consistency.\n */\nfunction normalizeHeaders(\n headers: Record<string, string | string[] | undefined>,\n): Record<string, string> {\n const result: Record<string, string> = {};\n for (const [key, value] of Object.entries(headers)) {\n if (value === undefined) continue;\n\n if (Array.isArray(value)) {\n // Filter undefined values and join per RFC 7230\n const definedValues = value.filter((v): v is string => v !== undefined);\n if (definedValues.length > 0) {\n result[key.toLowerCase()] = definedValues.join(', ');\n }\n } else {\n result[key.toLowerCase()] = value;\n }\n }\n return result;\n}\n\n/**\n * Generates a unique request ID using crypto-secure UUID.\n */\nfunction generateRequestId(): string {\n return `req_${crypto.randomUUID()}`;\n}\n","/**\n * @fileoverview Builder pattern for creating type-safe server routes.\n *\n * The `serverRoutes` function returns a builder that provides 100% type inference\n * for all handler parameters - no manual type annotations required.\n *\n * @module unified/server/server-routes-builder\n */\n\nimport type { RouterConfig, RouterDefinition, GetRoute, RouterKeys } from '../route/types';\nimport type {\n AnyHandlerConfig,\n CreateServerRoutesOptions,\n HandlerResponse,\n MiddlewareFunction,\n RouteHandlerConfig,\n SimpleHandlerConfig,\n SimpleHandlerFn,\n TypedContext,\n UnifiedRouteInput,\n UseCasePort,\n ValidatedRequest,\n} from './types';\nimport { createServerRoutesInternal } from './create-server-routes';\nimport type { RouteDefinition } from '../route/types';\n\n// ============================================================================\n// Builder Types\n// ============================================================================\n\n/**\n * Error type displayed when attempting to build() with missing handlers.\n * The `___missingRoutes` property shows which routes are missing.\n */\nexport interface MissingHandlersError<TMissing extends string> {\n /**\n * This error indicates that not all routes have handlers.\n * Use buildPartial() to build with only the defined handlers,\n * or add handlers for the missing routes.\n */\n (options?: never): never;\n /** Routes that are missing handlers */\n readonly ___missingRoutes: TMissing;\n}\n\n/**\n * Handler configuration for the builder pattern.\n * Identical to RouteHandlerConfig but with proper TypedContext.\n */\nexport interface BuilderHandlerConfig<TRoute extends RouteDefinition, TInput, TOutput> {\n /**\n * Maps the validated HTTP request to use case input.\n * Both `req` and `ctx` are fully typed based on route schemas.\n */\n readonly requestMapper: (req: ValidatedRequest<TRoute>, ctx: TypedContext<TRoute>) => TInput;\n\n /**\n * The use case to execute.\n */\n readonly useCase: UseCasePort<TInput, TOutput>;\n\n /**\n * Maps the use case output to an HTTP response.\n */\n readonly responseMapper: (output: TOutput) => HandlerResponse;\n\n /**\n * Middleware to run before the handler.\n */\n readonly middleware?: readonly MiddlewareFunction[];\n}\n\n/**\n * Builder interface for creating type-safe server routes.\n *\n * Each `.handle()` call captures the specific route type and provides\n * full type inference for requestMapper, useCase, and responseMapper.\n *\n * @typeParam T - The router configuration type\n * @typeParam THandled - Union of route keys that have handlers (accumulates)\n *\n * @example\n * ```typescript\n * const routes = serverRoutes(projectRouter)\n * .handle('projects.create', {\n * requestMapper: (req, ctx) => ({\n * name: req.body.name, // Fully typed!\n * createdBy: ctx.userId, // Fully typed!\n * }),\n * useCase: createProjectUseCase,\n * responseMapper: (output) => ({\n * status: 201 as const,\n * body: { projectId: output.projectId },\n * }),\n * })\n * .handle('projects.list', { ... })\n * .build();\n * ```\n */\nexport interface ServerRoutesBuilder<T extends RouterConfig, THandled extends string = never> {\n /**\n * Register a simple handler for a route.\n * The handler receives validated request and context, returns response directly.\n *\n * @param key - The route key (e.g., 'projects.get')\n * @param handlerOrConfig - Simple handler function or configuration with handler and optional middleware\n * @returns A new builder with the route key added to handled routes\n */\n handle<K extends Exclude<RouterKeys<T>, THandled>>(\n key: K,\n handlerOrConfig: SimpleHandlerFn<GetRoute<T, K>> | SimpleHandlerConfig<GetRoute<T, K>>,\n ): ServerRoutesBuilder<T, THandled | K>;\n\n /**\n * Register a handler using the use case pattern.\n * Follows: requestMapper → useCase.execute() → responseMapper\n *\n * @param key - The route key (e.g., 'projects.create')\n * @param config - Handler configuration with requestMapper, useCase, responseMapper\n * @returns A new builder with the route key added to handled routes\n */\n handleWithUseCase<K extends Exclude<RouterKeys<T>, THandled>, TInput, TOutput>(\n key: K,\n config: BuilderHandlerConfig<GetRoute<T, K>, TInput, TOutput>,\n ): ServerRoutesBuilder<T, THandled | K>;\n\n /**\n * Build the routes array for framework registration.\n *\n * This method is only available when ALL routes have handlers.\n * If some routes are missing handlers, use `buildPartial()` instead.\n *\n * @param options - Optional configuration (validation, middleware)\n * @returns Array of route inputs for framework registration\n *\n * @throws {Error} At compile time if routes are missing (type error)\n */\n build: [Exclude<RouterKeys<T>, THandled>] extends [never]\n ? (options?: CreateServerRoutesOptions) => UnifiedRouteInput[]\n : MissingHandlersError<Exclude<RouterKeys<T>, THandled>>;\n\n /**\n * Build routes for only the defined handlers.\n *\n * Use this when you only want to register handlers for some routes,\n * not all routes in the router. No compile-time enforcement.\n *\n * @param options - Optional configuration (validation, middleware)\n * @returns Array of route inputs for framework registration\n */\n buildPartial(options?: CreateServerRoutesOptions): UnifiedRouteInput[];\n}\n\n// ============================================================================\n// Builder Implementation\n// ============================================================================\n\n/**\n * Internal builder implementation.\n *\n * Uses an immutable pattern where each handle() call returns a new\n * builder instance with the updated handlers map.\n */\nclass ServerRoutesBuilderImpl<T extends RouterConfig, THandled extends string = never> {\n private readonly router: T | RouterDefinition<T>;\n private readonly handlers: Map<string, AnyHandlerConfig<RouteDefinition, unknown, unknown>>;\n\n constructor(\n router: T | RouterDefinition<T>,\n handlers?: Map<string, AnyHandlerConfig<RouteDefinition, unknown, unknown>>,\n ) {\n this.router = router;\n this.handlers = handlers ?? new Map();\n }\n\n handle<K extends Exclude<RouterKeys<T>, THandled>>(\n key: K,\n handlerOrConfig: SimpleHandlerFn<GetRoute<T, K>> | SimpleHandlerConfig<GetRoute<T, K>>,\n ): ServerRoutesBuilder<T, THandled | K> {\n // Normalize function to config object\n const config: SimpleHandlerConfig<RouteDefinition> =\n typeof handlerOrConfig === 'function'\n ? { handler: handlerOrConfig as SimpleHandlerFn<RouteDefinition> }\n : (handlerOrConfig as SimpleHandlerConfig<RouteDefinition>);\n\n const newHandlers = new Map(this.handlers);\n newHandlers.set(key as string, config);\n\n return new ServerRoutesBuilderImpl<T, THandled | K>(\n this.router,\n newHandlers,\n ) as unknown as ServerRoutesBuilder<T, THandled | K>;\n }\n\n handleWithUseCase<K extends Exclude<RouterKeys<T>, THandled>, TInput, TOutput>(\n key: K,\n config: BuilderHandlerConfig<GetRoute<T, K>, TInput, TOutput>,\n ): ServerRoutesBuilder<T, THandled | K> {\n // Create new handlers map (immutable pattern)\n const newHandlers = new Map(this.handlers);\n newHandlers.set(key as string, config as RouteHandlerConfig<RouteDefinition, unknown, unknown>);\n\n // Return new builder with updated type\n // Cast through unknown is safe: the type system tracks THandled | K through the interface\n // The conditional type on `build` cannot be proven at compile time, hence the cast\n return new ServerRoutesBuilderImpl<T, THandled | K>(\n this.router,\n newHandlers,\n ) as unknown as ServerRoutesBuilder<T, THandled | K>;\n }\n\n // The build method's type is determined by the interface conditional type\n // At runtime, it always works the same way - the conditional type only affects compile-time\n build(options?: CreateServerRoutesOptions): UnifiedRouteInput[] {\n return createServerRoutesInternal(this.router, Object.fromEntries(this.handlers), options);\n }\n\n buildPartial(options?: CreateServerRoutesOptions): UnifiedRouteInput[] {\n return createServerRoutesInternal(this.router, Object.fromEntries(this.handlers), {\n ...options,\n allowPartial: true,\n });\n }\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * Creates a type-safe server routes builder for a router.\n *\n * The builder pattern provides 100% type inference for all handler parameters:\n * - `req.body`, `req.query`, `req.pathParams`, `req.headers` are typed from route schemas\n * - `ctx` is typed from the route's context schema\n * - `output` in responseMapper is typed from the use case\n *\n * @param router - Router definition or router config\n * @returns Builder for registering handlers\n *\n * @example Basic usage\n * ```typescript\n * import { serverRoutes } from '@cosmneo/onion-lasagna/http/server';\n * import { projectRouter } from './router';\n *\n * const routes = serverRoutes(projectRouter)\n * .handle('projects.create', {\n * requestMapper: (req, ctx) => ({\n * name: req.body.name,\n * createdBy: ctx.userId,\n * }),\n * useCase: createProjectUseCase,\n * responseMapper: (output) => ({\n * status: 201 as const,\n * body: { projectId: output.projectId },\n * }),\n * })\n * .handle('projects.list', {\n * requestMapper: (req) => ({\n * page: req.query.page ?? 1,\n * limit: req.query.limit ?? 20,\n * }),\n * useCase: listProjectsUseCase,\n * responseMapper: (output) => ({\n * status: 200 as const,\n * body: output.projects,\n * }),\n * })\n * .build();\n *\n * // Register with framework\n * registerHonoRoutes(app, routes);\n * ```\n *\n * @example Partial build (only some routes)\n * ```typescript\n * const routes = serverRoutes(projectRouter)\n * .handle('projects.create', { ... })\n * // Skip other routes\n * .buildPartial(); // No type error even with missing routes\n * ```\n *\n * @example With options\n * ```typescript\n * const routes = serverRoutes(projectRouter)\n * .handle('projects.create', { ... })\n * .handle('projects.list', { ... })\n * .build({\n * validateRequest: true,\n * validateResponse: process.env.NODE_ENV !== 'production',\n * middleware: [loggingMiddleware],\n * });\n * ```\n */\nexport function serverRoutes<T extends RouterConfig>(\n router: T | RouterDefinition<T>,\n): ServerRoutesBuilder<T, never> {\n // Cast through unknown is safe: initial builder has no handlers (THandled = never)\n return new ServerRoutesBuilderImpl(router) as unknown as ServerRoutesBuilder<T, never>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC4JO,SAAS,cAAc,MAAsB;AAClD,SAAO,KAAK,QAAQ,iCAAiC,KAAK;AAC5D;;;ACnFO,SAAS,kBAAkB,OAA0C;AAC1E,SACE,OAAO,UAAU,YACjB,UAAU,QACV,YAAY,SACZ,UAAU,SACV,eAAe,SACf,YAAY;AAEhB;AAKO,SAAS,mBAAmB,OAA2C;AAC5E,SACE,OAAO,UAAU,YACjB,UAAU,QACV,eAAe,SACd,MAA2B,cAAc;AAE9C;AAwJO,SAAS,cACd,QACA,WAAW,IACgC;AAC3C,QAAM,SAAoD,CAAC;AAE3D,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,MAAM,GAAG;AACjD,UAAM,UAAU,WAAW,GAAG,QAAQ,IAAI,GAAG,KAAK;AAElD,QAAI,kBAAkB,KAAK,GAAG;AAC5B,aAAO,KAAK,EAAE,KAAK,SAAS,OAAO,MAAM,CAAC;AAAA,IAC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A,MACH,cAAc;AAAA,IAChB,CAAC;AAAA,EACH;AACF;AAuEO,SAAS,aACd,QAC+B;AAE/B,SAAO,IAAI,wBAAwB,MAAM;AAC3C;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../src/presentation/http/server/index.ts","../../../src/presentation/http/route/types/path-params.type.ts","../../../src/presentation/http/route/types/router-definition.type.ts","../../../src/presentation/http/server/types.ts","../../../src/global/exceptions/coded-error.error.ts","../../../src/global/exceptions/error-codes.const.ts","../../../src/presentation/exceptions/invalid-request.error.ts","../../../src/presentation/exceptions/controller.error.ts","../../../src/app/exceptions/use-case.error.ts","../../../src/app/exceptions/unauthorized.error.ts","../../../src/global/utils/wrap-error.util.ts","../../../src/presentation/http/route/utils.ts","../../../src/presentation/http/server/create-server-routes.ts","../../../src/presentation/http/server/server-routes-builder.ts"],"sourcesContent":["/**\n * @fileoverview Server module exports.\n *\n * This module provides server-side route registration with automatic validation.\n * It follows the BaseController pattern: requestMapper → useCase → responseMapper\n *\n * @module unified/server\n *\n * @example Create server routes with builder pattern\n * ```typescript\n * import { serverRoutes } from '@cosmneo/onion-lasagna/http/server';\n * import { projectRouter } from './routes';\n *\n * const routes = serverRoutes(projectRouter)\n * .handle('projects.create', {\n * requestMapper: (req, ctx) => ({\n * name: req.body.name, // Fully typed!\n * createdBy: ctx.userId, // Fully typed!\n * }),\n * useCase: createProjectUseCase,\n * responseMapper: (output) => ({\n * status: 201 as const,\n * body: { projectId: output.projectId },\n * }),\n * })\n * .handle('projects.list', { ... })\n * .build();\n * ```\n */\n\n// Builder pattern for server routes\nexport { serverRoutes } from './server-routes-builder';\nexport type {\n ServerRoutesBuilder,\n MissingHandlersError,\n BuilderHandlerConfig,\n} from './server-routes-builder';\n\nexport type {\n UseCasePort,\n ValidatedRequest,\n TypedContext,\n HandlerContext,\n HandlerResponse,\n RouteHandlerConfig,\n MiddlewareFunction,\n ServerRoutesConfig,\n CreateServerRoutesOptions,\n UnifiedRouteInput,\n RawHttpRequest,\n} from './types';\n","/**\n * @fileoverview Path parameter extraction types.\n *\n * These types enable TypeScript to extract path parameter names from\n * URL path templates at compile time, providing full type safety for\n * path parameters in routes.\n *\n * @module unified/route/types/path-params\n */\n\n/**\n * Extracts parameter names from a path template string.\n *\n * Supports both `:param` and `{param}` syntaxes for maximum compatibility\n * with different routing conventions.\n *\n * @example Colon syntax (Express-style)\n * ```typescript\n * type Params = ExtractPathParamNames<'/users/:userId/posts/:postId'>;\n * // 'userId' | 'postId'\n * ```\n *\n * @example Brace syntax (OpenAPI-style)\n * ```typescript\n * type Params = ExtractPathParamNames<'/users/{userId}/posts/{postId}'>;\n * // 'userId' | 'postId'\n * ```\n *\n * @example No parameters\n * ```typescript\n * type Params = ExtractPathParamNames<'/users'>;\n * // never\n * ```\n */\nexport type ExtractPathParamNames<T extends string> =\n // Match :param followed by more path\n T extends `${string}:${infer Param}/${infer Rest}`\n ? Param | ExtractPathParamNames<`/${Rest}`>\n : // Match :param at end\n T extends `${string}:${infer Param}`\n ? Param\n : // Match {param} followed by more path\n T extends `${string}{${infer Param}}/${infer Rest}`\n ? Param | ExtractPathParamNames<`/${Rest}`>\n : // Match {param} at end\n T extends `${string}{${infer Param}}`\n ? Param\n : never;\n\n/**\n * Creates an object type with all path parameters as string properties.\n *\n * @example\n * ```typescript\n * type Params = PathParams<'/projects/:projectId/tasks/:taskId'>;\n * // { projectId: string; taskId: string }\n *\n * type NoParams = PathParams<'/projects'>;\n * // Record<string, never> (empty object type)\n * ```\n */\nexport type PathParams<T extends string> =\n ExtractPathParamNames<T> extends never\n ? Record<string, never>\n : Record<ExtractPathParamNames<T>, string>;\n\n/**\n * Checks if a path has any parameters.\n *\n * @example\n * ```typescript\n * type HasParams = HasPathParams<'/users/:id'>; // true\n * type NoParams = HasPathParams<'/users'>; // false\n * ```\n */\nexport type HasPathParams<T extends string> = ExtractPathParamNames<T> extends never ? false : true;\n\n/**\n * Converts a path template with parameters to a regex pattern.\n * This is used internally for route matching.\n *\n * @example\n * ```typescript\n * pathToRegex('/users/:id/posts/:postId')\n * // /^\\/users\\/([^\\/]+)\\/posts\\/([^\\/]+)\\/?$/\n * ```\n */\nexport function pathToRegex(path: string): RegExp {\n const pattern = path\n // Escape special regex characters except : and {}\n .replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n // Replace :param with capture group\n .replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g, '([^/]+)')\n // Replace {param} with capture group\n .replace(/\\\\\\{([a-zA-Z_][a-zA-Z0-9_]*)\\\\\\}/g, '([^/]+)');\n\n return new RegExp(`^${pattern}/?$`);\n}\n\n/**\n * Extracts parameter names from a path string at runtime.\n *\n * @example\n * ```typescript\n * getPathParamNames('/users/:userId/posts/:postId')\n * // ['userId', 'postId']\n * ```\n */\nexport function getPathParamNames(path: string): string[] {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- regex capture group always exists\n const colonParams = [...path.matchAll(/:([a-zA-Z_][a-zA-Z0-9_]*)/g)].map((m) => m[1]!);\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- regex capture group always exists\n const braceParams = [...path.matchAll(/\\{([a-zA-Z_][a-zA-Z0-9_]*)\\}/g)].map((m) => m[1]!);\n return [...colonParams, ...braceParams];\n}\n\n/**\n * Checks if a path has any parameters at runtime.\n */\nexport function hasPathParams(path: string): boolean {\n return /:([a-zA-Z_][a-zA-Z0-9_]*)/.test(path) || /\\{([a-zA-Z_][a-zA-Z0-9_]*)\\}/.test(path);\n}\n\n/**\n * Replaces path parameters with actual values.\n *\n * @example\n * ```typescript\n * buildPath('/users/:userId/posts/:postId', { userId: '123', postId: '456' })\n * // '/users/123/posts/456'\n *\n * buildPath('/users/{userId}', { userId: '123' })\n * // '/users/123'\n * ```\n */\nexport function buildPath(template: string, params: Record<string, string>): string {\n let result = template;\n\n // Replace :param syntax\n for (const [key, value] of Object.entries(params)) {\n result = result.replace(`:${key}`, encodeURIComponent(value));\n result = result.replace(`{${key}}`, encodeURIComponent(value));\n }\n\n return result;\n}\n\n/**\n * Normalizes a path template to use consistent :param syntax.\n *\n * @example\n * ```typescript\n * normalizePath('/users/{userId}')\n * // '/users/:userId'\n * ```\n */\nexport function normalizePath(path: string): string {\n return path.replace(/\\{([a-zA-Z_][a-zA-Z0-9_]*)\\}/g, ':$1');\n}\n","/**\n * @fileoverview Router definition types for grouping routes.\n *\n * A router is a hierarchical grouping of routes that enables:\n * - Organized API structure\n * - Nested client method generation\n * - Grouped OpenAPI tags\n *\n * @module unified/route/types/router-definition\n */\n\nimport type { RouteDefinition } from './route-definition.type';\nimport type { HttpMethod } from './http.type';\nimport type { SchemaAdapter } from '../../schema/types';\n\n// ============================================================================\n// Router Types\n// ============================================================================\n\n/**\n * A router entry can be a route definition, a nested router config, or a router definition.\n */\nexport type RouterEntry =\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | RouteDefinition<HttpMethod, string, unknown, unknown, unknown, unknown, unknown, any>\n | RouterConfig\n | RouterDefinition;\n\n/**\n * Configuration for a router (group of routes).\n */\nexport interface RouterConfig {\n readonly [key: string]: RouterEntry;\n}\n\n/**\n * Router-level defaults applied to all child routes.\n */\nexport interface RouterDefaults {\n /**\n * Default tags for all routes in this router.\n * Merged with route-specific tags.\n */\n readonly tags?: readonly string[];\n\n /**\n * Default context schema for all routes in this router.\n * Applied to routes that don't define their own context.\n */\n readonly context?: SchemaAdapter;\n}\n\n/**\n * A fully defined router.\n */\nexport interface RouterDefinition<T extends RouterConfig = RouterConfig> {\n /**\n * The routes and nested routers in this router.\n */\n readonly routes: T;\n\n /**\n * Base path prefix for all routes in this router.\n */\n readonly basePath?: string;\n\n /**\n * Default values applied to all child routes.\n */\n readonly defaults?: RouterDefaults;\n\n /**\n * Marker to identify this as a router.\n * @internal\n */\n readonly _isRouter: true;\n}\n\n// ============================================================================\n// Type Guards\n// ============================================================================\n\n/**\n * Checks if a value is a RouteDefinition.\n */\nexport function isRouteDefinition(value: unknown): value is RouteDefinition {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'method' in value &&\n 'path' in value &&\n '_types' in value\n );\n}\n\n/**\n * Checks if a value is a RouterDefinition.\n */\nexport function isRouterDefinition(value: unknown): value is RouterDefinition {\n return (\n typeof value === 'object' &&\n value !== null &&\n '_isRouter' in value &&\n (value as RouterDefinition)._isRouter === true\n );\n}\n\n// ============================================================================\n// Utility Types\n// ============================================================================\n\n/**\n * Flattens a router into a map of path keys to route definitions.\n */\nexport type FlattenRouter<\n T extends RouterConfig,\n Prefix extends string = '',\n> = T extends RouterConfig\n ? {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [K in keyof T]: T[K] extends RouteDefinition<any, any, any, any, any, any, any, any>\n ? { [P in `${Prefix}${K & string}`]: T[K] }\n : T[K] extends RouterConfig\n ? FlattenRouter<T[K], `${Prefix}${K & string}.`>\n : never;\n }[keyof T] extends infer U\n ? // eslint-disable-next-line @typescript-eslint/no-explicit-any\n U extends Record<string, RouteDefinition<any, any, any, any, any, any, any, any>>\n ? U\n : never\n : never\n : never;\n\n/**\n * Gets all route keys from a router.\n */\nexport type RouterKeys<T extends RouterConfig, Prefix extends string = ''> = T extends RouterConfig\n ? {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [K in keyof T]: T[K] extends RouteDefinition<any, any, any, any, any, any, any, any>\n ? `${Prefix}${K & string}`\n : T[K] extends RouterConfig\n ? RouterKeys<T[K], `${Prefix}${K & string}.`>\n : never;\n }[keyof T]\n : never;\n\n/**\n * Gets a route by its dotted key path.\n */\nexport type GetRoute<\n T extends RouterConfig,\n K extends string,\n> = K extends `${infer Head}.${infer Tail}`\n ? Head extends keyof T\n ? T[Head] extends RouterConfig\n ? GetRoute<T[Head], Tail>\n : never\n : never\n : K extends keyof T\n ? // eslint-disable-next-line @typescript-eslint/no-explicit-any\n T[K] extends RouteDefinition<any, any, any, any, any, any, any, any>\n ? T[K]\n : never\n : never;\n\n// ============================================================================\n// Deep Merge Types\n// ============================================================================\n\n/**\n * Deep-merges two router configs at the type level.\n */\nexport type DeepMergeTwo<A extends RouterConfig, B extends RouterConfig> = {\n readonly [K in keyof A | keyof B]: K extends keyof A\n ? K extends keyof B\n ? A[K] extends RouterConfig\n ? B[K] extends RouterConfig\n ? DeepMergeTwo<A[K], B[K]>\n : B[K]\n : B[K]\n : A[K]\n : K extends keyof B\n ? B[K]\n : never;\n};\n\n/**\n * Recursively deep-merges N router configs left-to-right.\n */\nexport type DeepMergeAll<T extends readonly RouterConfig[]> = T extends readonly [\n infer Only extends RouterConfig,\n]\n ? Only\n : T extends readonly [\n infer First extends RouterConfig,\n infer Second extends RouterConfig,\n ...infer Rest extends readonly RouterConfig[],\n ]\n ? DeepMergeAll<[DeepMergeTwo<First, Second>, ...Rest]>\n : RouterConfig;\n\n/**\n * Recursively flattens complex types for clean IDE hover display.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type PrettifyDeep<T> = T extends (...args: any[]) => any\n ? T\n : T extends object\n ? { readonly [K in keyof T]: PrettifyDeep<T[K]> }\n : T;\n\n/**\n * Collects all routes from a router into an array.\n */\nexport function collectRoutes(\n config: RouterConfig,\n basePath = '',\n): { key: string; route: RouteDefinition }[] {\n const routes: { key: string; route: RouteDefinition }[] = [];\n\n for (const [key, value] of Object.entries(config)) {\n const fullKey = basePath ? `${basePath}.${key}` : key;\n\n if (isRouteDefinition(value)) {\n routes.push({ key: fullKey, route: value });\n } else if (isRouterDefinition(value)) {\n routes.push(...collectRoutes(value.routes, fullKey));\n } else if (typeof value === 'object' && value !== null) {\n routes.push(...collectRoutes(value as RouterConfig, fullKey));\n }\n }\n\n return routes;\n}\n","/**\n * @fileoverview Server types for the unified route system.\n *\n * @module unified/server/types\n */\n\nimport type {\n HttpMethod,\n RouteDefinition,\n RouterConfig,\n RouterKeys,\n GetRoute,\n} from '../route/types';\n\n// ============================================================================\n// Validated Request\n// ============================================================================\n\n/**\n * A validated request with typed data.\n * This is what handlers receive after validation passes.\n */\nexport interface ValidatedRequest<TRoute extends RouteDefinition> {\n /**\n * Validated request body.\n */\n readonly body: TRoute['_types']['body'];\n\n /**\n * Validated query parameters.\n */\n readonly query: TRoute['_types']['query'];\n\n /**\n * Validated path parameters.\n */\n readonly pathParams: TRoute['_types']['pathParams'];\n\n /**\n * Validated headers.\n */\n readonly headers: TRoute['_types']['headers'];\n\n /**\n * Raw request object for advanced use cases.\n */\n readonly raw: {\n readonly method: string;\n readonly url: string;\n readonly headers: Record<string, string>;\n };\n}\n\n/**\n * Typed context based on route definition.\n * If the route defines a context schema, this will be the validated type.\n * Otherwise, it falls back to the generic HandlerContext.\n */\nexport type TypedContext<TRoute extends RouteDefinition> =\n TRoute['_types']['context'] extends undefined ? HandlerContext : TRoute['_types']['context'];\n\n// ============================================================================\n// Handler Types\n// ============================================================================\n\n/**\n * Context passed to handlers.\n * Can be extended with custom context via serverRoutes options.\n */\nexport interface HandlerContext {\n /**\n * Request ID for tracing.\n */\n readonly requestId?: string;\n\n /**\n * Additional context data.\n */\n readonly [key: string]: unknown;\n}\n\n/**\n * Response from a handler.\n */\nexport interface HandlerResponse<TData = unknown> {\n /**\n * HTTP status code.\n */\n readonly status: number;\n\n /**\n * Response body.\n */\n readonly body?: TData;\n\n /**\n * Response headers.\n */\n readonly headers?: Record<string, string>;\n}\n\n// ============================================================================\n// Use Case Port\n// ============================================================================\n\n/**\n * Use case port interface for unified routes.\n *\n * This is a simplified version that accepts any input/output types (plain objects).\n * It's structurally compatible with `BaseInboundPort`, so existing use case\n * implementations work without changes.\n *\n * @typeParam TInput - Input type (plain object or void for no input)\n * @typeParam TOutput - Output type (plain object or void for no output)\n *\n * @example\n * ```typescript\n * // Define plain types for use case contracts\n * type CreateProjectInput = {\n * name: string;\n * description?: string;\n * };\n *\n * type CreateProjectOutput = {\n * projectId: string;\n * };\n *\n * // Use case implements this interface\n * class CreateProjectUseCase implements UseCasePort<CreateProjectInput, CreateProjectOutput> {\n * async execute(input: CreateProjectInput): Promise<CreateProjectOutput> {\n * // ... implementation\n * return { projectId: '...' };\n * }\n * }\n * ```\n */\n\nexport interface UseCasePort<TInput = void, TOutput = void> {\n execute(input?: TInput): Promise<TOutput>;\n}\n\n// ============================================================================\n// Server Configuration\n// ============================================================================\n\n/**\n * Handler configuration for a single route.\n *\n * Mirrors the BaseController pattern with three components:\n * - `requestMapper`: Maps validated HTTP request to use case input\n * - `useCase`: The use case to execute\n * - `responseMapper`: Maps use case output to HTTP response\n *\n * @typeParam TRoute - The route definition type\n * @typeParam TInput - Use case input type (plain object)\n * @typeParam TOutput - Use case output type (plain object)\n *\n * @example\n * ```typescript\n * const config: RouteHandlerConfig<typeof createProjectRoute, CreateProjectInput, CreateProjectOutput> = {\n * requestMapper: (req) => ({\n * name: req.body.name,\n * description: req.body.description,\n * }),\n * useCase: createProjectUseCase,\n * responseMapper: (out) => ({\n * status: 201,\n * body: { projectId: out.projectId },\n * }),\n * };\n * ```\n */\n\nexport interface RouteHandlerConfig<TRoute extends RouteDefinition, TInput = void, TOutput = void> {\n /**\n * Maps the validated HTTP request to use case input.\n * The request has already been validated by the route's schemas.\n * Context is typed based on the route's context schema (if defined).\n */\n readonly requestMapper: (req: ValidatedRequest<TRoute>, ctx: TypedContext<TRoute>) => TInput;\n\n /**\n * The use case to execute.\n * Can be any object with an `execute` method matching `UseCasePort`.\n */\n readonly useCase: UseCasePort<TInput, TOutput>;\n\n /**\n * Maps the use case output to an HTTP response.\n * Determines the status code and response body.\n */\n readonly responseMapper: (output: TOutput) => HandlerResponse;\n\n /**\n * Middleware to run before the handler.\n */\n readonly middleware?: readonly MiddlewareFunction[];\n}\n\n/**\n * Middleware function type.\n */\nexport type MiddlewareFunction = (\n request: unknown,\n context: HandlerContext,\n next: () => Promise<HandlerResponse>,\n) => Promise<HandlerResponse>;\n\n// ============================================================================\n// Simple Handler Types\n// ============================================================================\n\n/**\n * Simple handler function that directly returns a response.\n * Use this for simple routes that don't need the use case pattern.\n */\nexport type SimpleHandlerFn<TRoute extends RouteDefinition> = (\n req: ValidatedRequest<TRoute>,\n ctx: TypedContext<TRoute>,\n) => Promise<HandlerResponse> | HandlerResponse;\n\n/**\n * Configuration for a simple handler (no use case).\n */\nexport interface SimpleHandlerConfig<TRoute extends RouteDefinition> {\n readonly handler: SimpleHandlerFn<TRoute>;\n readonly middleware?: readonly MiddlewareFunction[];\n}\n\n/**\n * Union of all handler config types.\n * Used internally to store handlers in the builder.\n */\nexport type AnyHandlerConfig<TRoute extends RouteDefinition, TInput = unknown, TOutput = unknown> =\n | RouteHandlerConfig<TRoute, TInput, TOutput>\n | SimpleHandlerConfig<TRoute>;\n\n/**\n * Type guard to check if config is a simple handler.\n */\nexport function isSimpleHandlerConfig(\n config: AnyHandlerConfig<RouteDefinition, unknown, unknown>,\n): config is SimpleHandlerConfig<RouteDefinition> {\n return 'handler' in config && typeof config.handler === 'function';\n}\n\n/**\n * Configuration mapping route keys to handlers.\n *\n * Each route key maps to a `RouteHandlerConfig` with:\n * - The route definition for that key (provides request/response types)\n * - User-defined input/output types for the use case\n *\n * The `TInput` and `TOutput` types are inferred from the `useCase` property,\n * so you don't need to specify them explicitly.\n */\n// TInput/TOutput are user-defined per route - any is required for heterogeneous route configs\nexport type ServerRoutesConfig<T extends RouterConfig> = {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [K in RouterKeys<T>]: RouteHandlerConfig<GetRoute<T, K>, any, any>;\n};\n\n/**\n * Options for creating server routes.\n */\nexport interface CreateServerRoutesOptions {\n /**\n * Global middleware to run before all handlers.\n */\n readonly middleware?: readonly MiddlewareFunction[];\n\n /**\n * Whether to validate incoming requests against route schemas.\n * When enabled, invalid requests throw InvalidRequestError.\n * @default true\n */\n readonly validateRequest?: boolean;\n\n /**\n * Whether to validate outgoing responses against route schemas.\n * When enabled, invalid responses throw ControllerError.\n * Useful for catching bugs and ensuring API contract compliance.\n * @default true\n */\n readonly validateResponse?: boolean;\n\n /**\n * Context factory to create handler context.\n */\n readonly createContext?: (rawRequest: unknown) => HandlerContext;\n\n /**\n * Allow partial handler configuration (not all routes need handlers).\n * When true, missing handlers are silently skipped.\n * When false (default), missing handlers throw an error.\n * @default false\n * @internal Used by builder pattern's buildPartial()\n */\n readonly allowPartial?: boolean;\n}\n\n// ============================================================================\n// Route Input (for framework adapters)\n// ============================================================================\n\n/**\n * Route input compatible with framework adapters.\n * This is the output of serverRoutes().build().\n */\nexport interface UnifiedRouteInput {\n /**\n * HTTP method.\n */\n readonly method: HttpMethod;\n\n /**\n * URL path pattern.\n */\n readonly path: string;\n\n /**\n * Handler function.\n */\n readonly handler: (\n rawRequest: RawHttpRequest,\n context?: HandlerContext,\n ) => Promise<HandlerResponse>;\n\n /**\n * Route metadata for documentation.\n */\n readonly metadata: {\n readonly operationId?: string;\n readonly summary?: string;\n readonly description?: string;\n readonly tags?: readonly string[];\n readonly deprecated?: boolean;\n };\n}\n\n/**\n * Raw HTTP request from the framework.\n */\nexport interface RawHttpRequest {\n readonly method: string;\n readonly url: string;\n readonly headers: Record<string, string | string[] | undefined>;\n readonly body?: unknown;\n readonly query?: Record<string, string | string[] | undefined>;\n readonly params?: Record<string, string>;\n}\n","import type { ErrorCode } from './error-codes.const';\n\n/**\n * Base error class for all application errors with a machine-readable code.\n *\n * Abstract class that extends the native `Error` with:\n * - A `code` property for programmatic error handling\n * - Optional `cause` for error chaining (ES2022 compatible)\n * - A `fromError` static factory pattern for error transformation\n *\n * **Why abstract:** Prevents non-declarative error usage. All errors must\n * be explicitly defined as subclasses to ensure consistent error taxonomy.\n *\n * @example Subclass implementation\n * ```typescript\n * class DbError extends InfraError {\n * static override fromError(cause: unknown): DbError {\n * return new DbError({\n * message: cause instanceof Error ? cause.message : 'Database error',\n * cause,\n * });\n * }\n * }\n * ```\n *\n * @example Usage with wrapErrorAsync\n * ```typescript\n * await wrapErrorAsync(\n * () => this.db.query(...),\n * DbError.fromError,\n * );\n * ```\n */\nexport abstract class CodedError extends Error {\n /** Machine-readable error code for programmatic handling. */\n public readonly code: ErrorCode | string;\n\n /**\n * Creates a new CodedError instance.\n *\n * @param options - Error configuration\n * @param options.message - Human-readable error message\n * @param options.code - Machine-readable error code from ErrorCodes registry or custom string\n * @param options.cause - Optional underlying error that caused this error\n */\n constructor({\n message,\n code,\n cause,\n }: {\n message: string;\n code: ErrorCode | string;\n cause?: unknown;\n }) {\n super(message);\n this.name = this.constructor.name;\n this.code = code;\n if (cause !== undefined) {\n Object.defineProperty(this, 'cause', {\n value: cause,\n writable: false,\n enumerable: false,\n configurable: true,\n });\n }\n }\n\n /**\n * Factory method to create a typed error from a caught error.\n *\n * Subclasses should override this to provide proper error transformation.\n * Designed for use with {@link wrapErrorAsync} and {@link wrapError}.\n *\n * @param _cause - The original caught error\n * @returns A new CodedError instance\n * @throws {Error} If not overridden by subclass\n *\n * @example\n * ```typescript\n * class NotFoundError extends UseCaseError {\n * static override fromError(cause: unknown): NotFoundError {\n * return new NotFoundError({\n * message: 'Resource not found',\n * cause,\n * });\n * }\n * }\n * ```\n */\n static fromError(_cause: unknown): CodedError {\n throw new Error(`${this.name}.fromError() must be implemented by subclass`);\n }\n}\n","/**\n * Centralized registry of all error codes used across the application.\n *\n * Error codes are grouped by architectural layer to maintain clear boundaries\n * and make it easy to identify where an error originated.\n *\n * @example Using error codes in custom errors\n * ```typescript\n * import { ErrorCodes } from '@cosmneo/onion-lasagna/global';\n *\n * throw new NotFoundError({\n * message: 'User not found',\n * code: ErrorCodes.App.NOT_FOUND,\n * });\n * ```\n *\n * @example Checking error codes programmatically\n * ```typescript\n * if (error.code === ErrorCodes.App.NOT_FOUND) {\n * // Handle not found case\n * }\n * ```\n */\nexport const ErrorCodes = {\n /**\n * Domain layer error codes.\n * Used for business rule violations and invariant failures.\n */\n Domain: {\n /** Generic domain error */\n DOMAIN_ERROR: 'DOMAIN_ERROR',\n /** Business invariant was violated */\n INVARIANT_VIOLATION: 'INVARIANT_VIOLATION',\n /** Aggregate was partially loaded (missing required relations) */\n PARTIAL_LOAD: 'PARTIAL_LOAD',\n },\n\n /**\n * Application layer (use case) error codes.\n * Used for orchestration failures and business operation errors.\n */\n App: {\n /** Generic use case error */\n USE_CASE_ERROR: 'USE_CASE_ERROR',\n /** Requested resource was not found */\n NOT_FOUND: 'NOT_FOUND',\n /** Resource state conflict (e.g., duplicate, already exists) */\n CONFLICT: 'CONFLICT',\n /** Request is valid but cannot be processed due to business rules */\n UNPROCESSABLE: 'UNPROCESSABLE',\n /** Authorization denied - user lacks permission for this operation */\n FORBIDDEN: 'FORBIDDEN',\n /** Authentication required or invalid - user is not authenticated */\n UNAUTHORIZED: 'UNAUTHORIZED',\n },\n\n /**\n * Infrastructure layer error codes.\n * Used for data access, external services, and I/O failures.\n */\n Infra: {\n /** Generic infrastructure error */\n INFRA_ERROR: 'INFRA_ERROR',\n /** Database operation failed */\n DB_ERROR: 'DB_ERROR',\n /** Network connectivity or communication error */\n NETWORK_ERROR: 'NETWORK_ERROR',\n /** Operation timed out */\n TIMEOUT_ERROR: 'TIMEOUT_ERROR',\n /** External/third-party service error */\n EXTERNAL_SERVICE_ERROR: 'EXTERNAL_SERVICE_ERROR',\n },\n\n /**\n * Presentation layer error codes.\n * Used for controller, request handling, and authorization errors.\n */\n Presentation: {\n /** Generic controller error */\n CONTROLLER_ERROR: 'CONTROLLER_ERROR',\n /** Request denied due to authorization failure */\n ACCESS_DENIED: 'ACCESS_DENIED',\n /** Request validation failed (malformed input) */\n INVALID_REQUEST: 'INVALID_REQUEST',\n },\n\n /**\n * Global/cross-cutting error codes.\n * Used for validation and other cross-layer concerns.\n */\n Global: {\n /** Object/schema validation failed */\n OBJECT_VALIDATION_ERROR: 'OBJECT_VALIDATION_ERROR',\n },\n} as const;\n\n/**\n * Type representing all possible domain error codes.\n */\nexport type DomainErrorCode = (typeof ErrorCodes.Domain)[keyof typeof ErrorCodes.Domain];\n\n/**\n * Type representing all possible application error codes.\n */\nexport type AppErrorCode = (typeof ErrorCodes.App)[keyof typeof ErrorCodes.App];\n\n/**\n * Type representing all possible infrastructure error codes.\n */\nexport type InfraErrorCode = (typeof ErrorCodes.Infra)[keyof typeof ErrorCodes.Infra];\n\n/**\n * Type representing all possible presentation error codes.\n */\nexport type PresentationErrorCode =\n (typeof ErrorCodes.Presentation)[keyof typeof ErrorCodes.Presentation];\n\n/**\n * Type representing all possible global error codes.\n */\nexport type GlobalErrorCode = (typeof ErrorCodes.Global)[keyof typeof ErrorCodes.Global];\n\n/**\n * Union type of all error codes across all layers.\n *\n * Use this when you need to accept any valid error code.\n *\n * @example\n * ```typescript\n * function logError(code: ErrorCode, message: string) {\n * console.error(`[${code}] ${message}`);\n * }\n * ```\n */\nexport type ErrorCode =\n | DomainErrorCode\n | AppErrorCode\n | InfraErrorCode\n | PresentationErrorCode\n | GlobalErrorCode;\n","import { CodedError } from '../../global/exceptions/coded-error.error';\nimport { ErrorCodes, type PresentationErrorCode } from '../../global/exceptions/error-codes.const';\nimport type { ValidationError } from '../../global/interfaces/types/validation-error.type';\n\n/**\n * Error thrown when request validation fails at the controller level.\n *\n * Contains structured validation errors with field paths and messages,\n * converted from {@link ObjectValidationError} by {@link BaseController}.\n * Provides detailed feedback about which fields failed validation.\n *\n * **When thrown:**\n * - Request DTO validation fails\n * - Malformed request data\n * - Missing required fields\n *\n * @example\n * ```typescript\n * // Automatically thrown by BaseController when DTO validation fails\n * // The validationErrors array contains field-level details:\n * // [\n * // { field: 'email', message: 'Invalid email format' },\n * // { field: 'age', message: 'Must be a positive number' }\n * // ]\n * ```\n *\n * @example Manual usage\n * ```typescript\n * throw new InvalidRequestError({\n * message: 'Request validation failed',\n * validationErrors: [\n * { field: 'username', message: 'Username is required' },\n * ],\n * });\n * ```\n *\n * @extends CodedError\n */\nexport class InvalidRequestError extends CodedError {\n /**\n * Array of field-level validation errors.\n *\n * Each entry contains:\n * - `field`: Dot-notation path to the invalid field\n * - `message`: Human-readable validation failure message\n */\n readonly validationErrors: ValidationError[];\n\n /**\n * Creates a new InvalidRequestError instance.\n *\n * @param options - Error configuration\n * @param options.message - Summary of the validation failure\n * @param options.code - Machine-readable error code (default: 'INVALID_REQUEST')\n * @param options.cause - Optional underlying error\n * @param options.validationErrors - Array of field-level validation errors\n */\n constructor({\n message,\n code = ErrorCodes.Presentation.INVALID_REQUEST,\n cause,\n validationErrors,\n }: {\n message: string;\n code?: PresentationErrorCode | string;\n cause?: unknown;\n validationErrors: ValidationError[];\n }) {\n super({ message, code, cause });\n this.validationErrors = validationErrors;\n }\n\n /**\n * Creates an InvalidRequestError from a caught error.\n *\n * @param cause - The original caught error\n * @returns A new InvalidRequestError instance with the cause attached\n */\n static override fromError(cause: unknown): InvalidRequestError {\n return new InvalidRequestError({\n message: cause instanceof Error ? cause.message : 'Invalid request',\n cause,\n validationErrors: [],\n });\n }\n}\n","import { CodedError } from '../../global/exceptions/coded-error.error';\nimport { ErrorCodes, type PresentationErrorCode } from '../../global/exceptions/error-codes.const';\n\n/**\n * Base error class for presentation layer (controller) failures.\n *\n * Controller errors represent failures in request handling,\n * such as access control violations or malformed requests.\n * They are the outermost error layer and typically map to HTTP responses.\n *\n * **When to throw:**\n * - Access control failures (unauthorized/forbidden)\n * - Request validation failures\n * - Unexpected controller execution errors\n *\n * **Child classes:**\n * - {@link AccessDeniedError} - Authorization failures (HTTP 403)\n * - {@link InvalidRequestError} - Request validation failures (HTTP 400)\n *\n * @example\n * ```typescript\n * // Thrown automatically by BaseController for unexpected errors\n * throw new ControllerError({\n * message: 'Controller execution failed',\n * cause: originalError,\n * });\n * ```\n */\nexport class ControllerError extends CodedError {\n /**\n * Creates a new ControllerError instance.\n *\n * @param options - Error configuration\n * @param options.message - Human-readable error description\n * @param options.code - Machine-readable error code (default: 'CONTROLLER_ERROR')\n * @param options.cause - Optional underlying error\n */\n constructor({\n message,\n code = ErrorCodes.Presentation.CONTROLLER_ERROR,\n cause,\n }: {\n message: string;\n code?: PresentationErrorCode | string;\n cause?: unknown;\n }) {\n super({ message, code, cause });\n }\n\n /**\n * Creates a ControllerError from a caught error.\n *\n * @param cause - The original caught error\n * @returns A new ControllerError instance with the cause attached\n */\n static override fromError(cause: unknown): ControllerError {\n return new ControllerError({\n message: cause instanceof Error ? cause.message : 'Controller error',\n cause,\n });\n }\n}\n","import { CodedError } from '../../global/exceptions/coded-error.error';\nimport { ErrorCodes, type AppErrorCode } from '../../global/exceptions/error-codes.const';\n\n/**\n * Base error class for application layer (use case) failures.\n *\n * Use case errors represent failures in the application's business logic\n * orchestration, such as resource conflicts, missing entities, or\n * unprocessable requests. They bridge domain errors to the presentation layer.\n *\n * **When to throw:**\n * - Resource not found (e.g., \"User with ID X not found\")\n * - Conflict states (e.g., \"Email already registered\")\n * - Unprocessable business operations\n *\n * **Child classes:**\n * - {@link ConflictError} - Resource state conflicts (HTTP 409)\n * - {@link NotFoundError} - Resource not found (HTTP 404)\n * - {@link UnprocessableError} - Valid but unprocessable request (HTTP 422)\n *\n * @example\n * ```typescript\n * const user = await this.userRepo.findById(id);\n * if (!user) {\n * throw new NotFoundError({\n * message: `User with ID ${id} not found`,\n * code: 'USER_NOT_FOUND',\n * });\n * }\n * ```\n */\nexport class UseCaseError extends CodedError {\n /**\n * Creates a new UseCaseError instance.\n *\n * @param options - Error configuration\n * @param options.message - Human-readable error description\n * @param options.code - Machine-readable error code (default: 'USE_CASE_ERROR')\n * @param options.cause - Optional underlying error\n */\n constructor({\n message,\n code = ErrorCodes.App.USE_CASE_ERROR,\n cause,\n }: {\n message: string;\n code?: AppErrorCode | string;\n cause?: unknown;\n }) {\n super({ message, code, cause });\n }\n\n /**\n * Creates a UseCaseError from a caught error.\n *\n * @param cause - The original caught error\n * @returns A new UseCaseError instance with the cause attached\n */\n static override fromError(cause: unknown): UseCaseError {\n return new UseCaseError({\n message: cause instanceof Error ? cause.message : 'Use case error',\n cause,\n });\n }\n}\n","import { ErrorCodes, type AppErrorCode } from '../../global/exceptions/error-codes.const';\nimport { UseCaseError } from './use-case.error';\n\n/**\n * Error thrown when authentication is required or invalid.\n *\n * Indicates that the user is not authenticated or their authentication\n * credentials are invalid/expired. This is different from `ForbiddenError`\n * which is for authenticated users who lack permission.\n *\n * **When to throw:**\n * - User is not logged in but authentication is required\n * - Authentication token is missing, invalid, or expired\n * - Session has been invalidated\n * - API key is invalid or revoked\n *\n * **Difference from ForbiddenError:**\n * - `UnauthorizedError` (401) = Not authenticated (who are you?)\n * - `ForbiddenError` (403) = Authenticated but not authorized (you can't do this)\n *\n * @example Missing authentication\n * ```typescript\n * protected async authorize(input: Input): Promise<AuthContext> {\n * if (!input.userId) {\n * throw new UnauthorizedError({ message: 'Authentication required' });\n * }\n *\n * const user = await this.userRepo.findById(input.userId);\n * if (!user) {\n * throw new UnauthorizedError({ message: 'Invalid user credentials' });\n * }\n *\n * return { user };\n * }\n * ```\n *\n * @example Token validation\n * ```typescript\n * if (!token || isTokenExpired(token)) {\n * throw new UnauthorizedError({\n * message: 'Session expired, please log in again',\n * code: 'SESSION_EXPIRED',\n * });\n * }\n * ```\n *\n * @extends UseCaseError\n */\nexport class UnauthorizedError extends UseCaseError {\n /**\n * Creates a new UnauthorizedError instance.\n *\n * @param options - Error configuration\n * @param options.message - Description of why authentication failed\n * @param options.code - Machine-readable error code (default: 'UNAUTHORIZED')\n * @param options.cause - Optional underlying error\n */\n constructor({\n message,\n code = ErrorCodes.App.UNAUTHORIZED,\n cause,\n }: {\n message: string;\n code?: AppErrorCode | string;\n cause?: unknown;\n }) {\n super({ message, code, cause });\n }\n\n /**\n * Creates an UnauthorizedError from a caught error.\n *\n * @param cause - The original caught error\n * @returns A new UnauthorizedError instance with the cause attached\n */\n static override fromError(cause: unknown): UnauthorizedError {\n return new UnauthorizedError({\n message: cause instanceof Error ? cause.message : 'Authentication required',\n cause,\n });\n }\n}\n","/**\n * Error wrapping utilities for boundary error handling.\n *\n * Provides functions to wrap code execution with error transformation,\n * converting caught errors into typed Error instances.\n * Useful at layer boundaries (infra, use case, controller) to normalize errors.\n *\n * @example Wrapping async database calls\n * ```typescript\n * const user = await wrapErrorAsync(\n * () => this.db.query('SELECT * FROM users WHERE id = ?', [id]),\n * (cause) => new DbError({ message: 'Failed to fetch user', cause }),\n * );\n * ```\n *\n * @example Wrapping sync operations\n * ```typescript\n * const parsed = wrapError(\n * () => JSON.parse(data),\n * (cause) => new InvariantViolationError({\n * message: 'Invalid JSON format',\n * cause,\n * }),\n * );\n * ```\n *\n * @module\n */\n\n/**\n * Factory function that creates an Error from a caught error.\n *\n * @typeParam E - The specific Error subclass to create\n * @param cause - The original caught error\n * @returns A new Error instance\n */\nexport type ErrorFactory<E extends Error> = (cause: unknown) => E;\n\n/**\n * Wraps a synchronous function with error transformation.\n *\n * Executes the provided function and catches any thrown errors,\n * transforming them using the error factory.\n *\n * @typeParam T - The return type of the wrapped function\n * @typeParam E - The Error subclass to throw on error\n * @param fn - The function to execute\n * @param errorFactory - Factory to create the typed error from the caught error\n * @returns The result of the function if successful\n * @throws {E} The transformed error if the function throws\n *\n * @example\n * ```typescript\n * const config = wrapError(\n * () => JSON.parse(configString),\n * (cause) => new InvariantViolationError({\n * message: 'Invalid configuration format',\n * code: 'CONFIG_PARSE_ERROR',\n * cause,\n * }),\n * );\n * ```\n */\nexport function wrapError<T, E extends Error>(fn: () => T, errorFactory: ErrorFactory<E>): T {\n try {\n return fn();\n } catch (error) {\n throw errorFactory(error);\n }\n}\n\n/**\n * Wraps an asynchronous function with error transformation.\n *\n * Executes the provided async function and catches any thrown errors,\n * transforming them using the error factory.\n *\n * @typeParam T - The return type of the wrapped function\n * @typeParam E - The Error subclass to throw on error\n * @param fn - The async function to execute\n * @param errorFactory - Factory to create the typed error from the caught error\n * @returns A promise resolving to the result if successful\n * @throws {E} The transformed error if the function throws\n *\n * @example Repository usage\n * ```typescript\n * async findById(id: string): Promise<User | null> {\n * return wrapErrorAsync(\n * () => this.db.users.findUnique({ where: { id } }),\n * (cause) => new DbError({\n * message: `Failed to find user by ID: ${id}`,\n * cause,\n * }),\n * );\n * }\n * ```\n *\n * @example External service usage\n * ```typescript\n * async sendEmail(to: string, body: string): Promise<void> {\n * await wrapErrorAsync(\n * () => this.emailClient.send({ to, body }),\n * (cause) => new ExternalServiceError({\n * message: 'Email delivery failed',\n * code: 'EMAIL_SEND_FAILED',\n * cause,\n * }),\n * );\n * }\n * ```\n */\nexport async function wrapErrorAsync<T, E extends Error>(\n fn: () => Promise<T>,\n errorFactory: ErrorFactory<E>,\n): Promise<T> {\n try {\n return await fn();\n } catch (error) {\n throw errorFactory(error);\n }\n}\n\n/**\n * Constructor type for error classes (including abstract classes).\n *\n * Used to specify error types that should pass through without transformation.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type ErrorConstructor = abstract new (...args: any[]) => Error;\n\n/**\n * Wraps a synchronous function with conditional error transformation.\n *\n * Executes the provided function and catches any thrown errors.\n * Errors matching any of the passthrough types are re-thrown as-is.\n * All other errors are transformed using the error factory.\n *\n * @typeParam T - The return type of the wrapped function\n * @typeParam E - The Error subclass to throw for unknown errors\n * @param fn - The function to execute\n * @param errorFactory - Factory to create the typed error from unknown errors\n * @param passthroughTypes - Array of error classes to re-throw without transformation\n * @returns The result of the function if successful\n * @throws The original error if it matches a passthrough type\n * @throws {E} The transformed error for unknown error types\n *\n * @example Controller boundary\n * ```typescript\n * const result = wrapErrorUnless(\n * () => this.requestMapper(input),\n * (cause) => new ControllerError({ message: 'Mapping failed', cause }),\n * [CodedError],\n * );\n * ```\n */\nexport function wrapErrorUnless<T, E extends Error>(\n fn: () => T,\n errorFactory: ErrorFactory<E>,\n passthroughTypes: ErrorConstructor[],\n): T {\n try {\n return fn();\n } catch (error) {\n if (passthroughTypes.some((Type) => error instanceof Type)) {\n throw error;\n }\n throw errorFactory(error);\n }\n}\n\n/**\n * Wraps an asynchronous function with conditional error transformation.\n *\n * Executes the provided async function and catches any thrown errors.\n * Errors matching any of the passthrough types are re-thrown as-is.\n * All other errors are transformed using the error factory.\n *\n * @typeParam T - The return type of the wrapped function\n * @typeParam E - The Error subclass to throw for unknown errors\n * @param fn - The async function to execute\n * @param errorFactory - Factory to create the typed error from unknown errors\n * @param passthroughTypes - Array of error classes to re-throw without transformation\n * @returns A promise resolving to the result if successful\n * @throws The original error if it matches a passthrough type\n * @throws {E} The transformed error for unknown error types\n *\n * @example Use case boundary\n * ```typescript\n * return wrapErrorUnlessAsync(\n * () => this.handle(input),\n * (cause) => new UseCaseError({ message: 'Unexpected error', cause }),\n * [ObjectValidationError, UseCaseError, DomainError, InfraError],\n * );\n * ```\n *\n * @example Controller boundary\n * ```typescript\n * return wrapErrorUnlessAsync(\n * async () => {\n * const result = await this.useCase.execute(input);\n * return this.responseMapper(result);\n * },\n * (cause) => new ControllerError({ message: 'Controller failed', cause }),\n * [CodedError],\n * );\n * ```\n */\nexport async function wrapErrorUnlessAsync<T, E extends Error>(\n fn: () => Promise<T>,\n errorFactory: ErrorFactory<E>,\n passthroughTypes: ErrorConstructor[],\n): Promise<T> {\n try {\n return await fn();\n } catch (error) {\n if (passthroughTypes.some((Type) => error instanceof Type)) {\n throw error;\n }\n throw errorFactory(error);\n }\n}\n","/**\n * @fileoverview Route utility functions.\n *\n * @module unified/route/utils\n */\n\n/**\n * Generates an operationId from a router key path.\n *\n * Converts dotted key paths to camelCase:\n * - `\"users.list\"` → `\"usersList\"`\n * - `\"organizations.members.get\"` → `\"organizationsMembersGet\"`\n *\n * @param key - The dotted router key path\n * @returns A camelCase operationId string\n */\nexport function generateOperationId(key: string): string {\n return key\n .split('.')\n .map((segment, index) =>\n index === 0 ? segment : segment.charAt(0).toUpperCase() + segment.slice(1),\n )\n .join('');\n}\n","/**\n * @fileoverview Internal implementation for creating server routes with auto-validation.\n *\n * Generates server-side route handlers from a router definition.\n * Each handler automatically validates incoming requests and outgoing\n * responses against the route's schemas.\n *\n * @module unified/server/create-server-routes\n * @internal\n */\n\nimport type { SchemaAdapter, ValidationIssue } from '../schema/types';\nimport type { RouterConfig, RouterDefinition, RouteDefinition } from '../route/types';\nimport { isRouterDefinition, collectRoutes, normalizePath } from '../route/types';\nimport type {\n AnyHandlerConfig,\n CreateServerRoutesOptions,\n HandlerContext,\n HandlerResponse,\n RawHttpRequest,\n UnifiedRouteInput,\n ValidatedRequest,\n} from './types';\nimport { isSimpleHandlerConfig } from './types';\nimport { InvalidRequestError } from '../../exceptions/invalid-request.error';\nimport { ControllerError } from '../../exceptions/controller.error';\nimport { UnauthorizedError } from '../../../app/exceptions/unauthorized.error';\nimport { wrapError } from '../../../global/utils/wrap-error.util';\nimport { generateOperationId } from '../route/utils';\n\n/**\n * Internal implementation for creating server routes.\n * Used by the builder pattern (serverRoutes).\n *\n * @internal\n */\nexport function createServerRoutesInternal<T extends RouterConfig>(\n router: T | RouterDefinition<T>,\n handlers: Record<string, AnyHandlerConfig<RouteDefinition, unknown, unknown>>,\n options?: CreateServerRoutesOptions,\n): UnifiedRouteInput[] {\n const routes = isRouterDefinition(router) ? router.routes : router;\n const collectedRoutes = collectRoutes(routes);\n\n // Sort routes by specificity: static segments before parameterized\n // This ensures /api/users/me is registered before /api/users/:userId\n const sortedRoutes = sortRoutesBySpecificity(collectedRoutes);\n\n const result: UnifiedRouteInput[] = [];\n\n // Default validation options to true, allowPartial to false\n const resolvedOptions: CreateServerRoutesOptions = {\n ...options,\n validateRequest: options?.validateRequest ?? true,\n validateResponse: options?.validateResponse ?? true,\n allowPartial: options?.allowPartial ?? false,\n };\n\n for (const { key, route } of sortedRoutes) {\n const handlerConfig = handlers[key] as AnyHandlerConfig<RouteDefinition, any, any> | undefined;\n\n if (!handlerConfig) {\n if (resolvedOptions.allowPartial) {\n // Skip routes without handlers when allowPartial is true\n continue;\n }\n throw new Error(\n `Missing handler for route \"${key}\". All routes must have a handler configuration.`,\n );\n }\n\n result.push(createRouteHandler(key, route, handlerConfig, resolvedOptions));\n }\n\n return result;\n}\n\n/**\n * Sorts routes by path specificity to ensure correct route matching.\n *\n * Static path segments are sorted before parameterized segments at each position.\n * This ensures that `/api/users/me` is registered before `/api/users/:userId`,\n * preventing the parameterized route from incorrectly matching the static path.\n *\n * @example\n * Given routes:\n * - /api/users/:userId (parameterized)\n * - /api/users/me (static)\n *\n * After sorting:\n * - /api/users/me (registered first - matches exactly)\n * - /api/users/:userId (registered second - catches remaining)\n */\nfunction sortRoutesBySpecificity<T extends { route: { path: string } }>(routes: T[]): T[] {\n return [...routes].sort((a, b) => {\n const aSegments = a.route.path.split('/').filter(Boolean);\n const bSegments = b.route.path.split('/').filter(Boolean);\n\n const maxLen = Math.max(aSegments.length, bSegments.length);\n\n for (let i = 0; i < maxLen; i++) {\n const aSeg = aSegments[i];\n const bSeg = bSegments[i];\n\n // Missing segment (shorter path) - shorter paths first for same prefix\n if (aSeg === undefined && bSeg !== undefined) return -1;\n if (aSeg !== undefined && bSeg === undefined) return 1;\n if (aSeg === undefined || bSeg === undefined) return 0;\n\n // Check if segment is parameterized (supports both :param and {param} formats)\n const aIsParam = aSeg.startsWith(':') || (aSeg.startsWith('{') && aSeg.endsWith('}'));\n const bIsParam = bSeg.startsWith(':') || (bSeg.startsWith('{') && bSeg.endsWith('}'));\n\n // Static segments come before parameterized segments\n if (!aIsParam && bIsParam) return -1;\n if (aIsParam && !bIsParam) return 1;\n\n // Both static or both parameterized - compare alphabetically for stable sorting\n const cmp = aSeg.localeCompare(bSeg);\n if (cmp !== 0) return cmp;\n }\n\n return 0;\n });\n}\n\n/**\n * Creates a single route handler with validation.\n *\n * Supports two handler patterns:\n * - Simple handler: handler(req, ctx) → response\n * - Use case pattern: requestMapper → useCase.execute → responseMapper\n */\nfunction createRouteHandler(\n key: string,\n route: RouteDefinition,\n // TInput/TOutput are user-defined and erased at this level - any is required for type compatibility\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n config: AnyHandlerConfig<RouteDefinition, any, any>,\n options: CreateServerRoutesOptions,\n): UnifiedRouteInput {\n const middleware = config.middleware ?? [];\n const globalMiddleware = options?.middleware ?? [];\n const allMiddleware = [...globalMiddleware, ...middleware];\n\n const shouldValidateRequest = options.validateRequest ?? true;\n const shouldValidateResponse = options.validateResponse ?? true;\n\n return {\n method: route.method,\n path: normalizePath(route.path),\n metadata: {\n operationId: route.docs.operationId ?? generateOperationId(key),\n summary: route.docs.summary,\n description: route.docs.description,\n tags: route.docs.tags as string[],\n deprecated: route.docs.deprecated,\n },\n handler: async (rawRequest: RawHttpRequest, ctx?: HandlerContext): Promise<HandlerResponse> => {\n // Create context\n const rawContext: HandlerContext = options?.createContext\n ? options.createContext(rawRequest)\n : (ctx ?? { requestId: generateRequestId() });\n\n // Validate context (if schema defined)\n // Context validation failures are treated as authentication errors (401)\n // because context typically carries auth data (user, session, token).\n // A missing or invalid context means the caller is not properly authenticated.\n const validatedContext: unknown = route.request.context\n ? wrapError(\n () => {\n const result = validateContextData(route, rawContext);\n if (!result.success) {\n const errors = result.errors ?? [];\n throw new InvalidRequestError({\n message: 'Context validation failed',\n validationErrors: errors.map((e) => ({\n field: e.path.join('.'),\n message: e.message,\n })),\n });\n }\n return result.data;\n },\n () => new UnauthorizedError({ message: 'Authentication required' }),\n )\n : rawContext;\n\n // Validate request (if enabled)\n // Use internal type since specific route types are erased in this function\n let validatedRequest: ValidatedRequestInternal;\n\n if (shouldValidateRequest) {\n const validationResult = validateRequestData(route, rawRequest);\n\n if (!validationResult.success) {\n const errors = validationResult.errors ?? [];\n throw new InvalidRequestError({\n message: 'Request validation failed',\n validationErrors: errors.map((e) => ({\n field: e.path.join('.'),\n message: e.message,\n })),\n });\n }\n\n const data = validationResult.data ?? {};\n\n validatedRequest = {\n body: data.body,\n query: data.query,\n pathParams: data.pathParams,\n headers: data.headers,\n raw: {\n method: rawRequest.method,\n url: rawRequest.url,\n headers: normalizeHeaders(rawRequest.headers),\n },\n };\n } else {\n // Skip validation - pass through normalized data\n\n validatedRequest = {\n body: rawRequest.body,\n query: normalizeQuery(rawRequest.query),\n pathParams: normalizePathParams(rawRequest.params),\n headers: normalizeHeaders(rawRequest.headers),\n raw: {\n method: rawRequest.method,\n url: rawRequest.url,\n headers: normalizeHeaders(rawRequest.headers),\n },\n };\n }\n\n // Execute the pipeline based on handler type\n // Errors from the use case/handler propagate to the framework's error handler\n const executePipeline = async (): Promise<HandlerResponse> => {\n if (isSimpleHandlerConfig(config)) {\n // Simple handler: direct call\n return config.handler(\n validatedRequest as unknown as ValidatedRequest<RouteDefinition>,\n validatedContext as HandlerContext,\n );\n } else {\n // Use case handler: requestMapper → useCase → responseMapper\n const { requestMapper, useCase, responseMapper } = config;\n\n // Map request to use case input\n // Cast is safe: ValidatedRequestInternal has same shape as ValidatedRequest<TRoute>\n // Type erasure in this function requires the cast for TypeScript\n // validatedContext is typed correctly based on route's context schema\n const input = requestMapper(\n validatedRequest as unknown as ValidatedRequest<RouteDefinition>,\n validatedContext as HandlerContext,\n );\n\n // Execute use case\n const output = await useCase.execute(input);\n\n // Map output to HTTP response\n return responseMapper(output);\n }\n };\n\n let response: HandlerResponse;\n\n if (allMiddleware.length === 0) {\n response = await executePipeline();\n } else {\n // Build middleware chain\n // Note: Middleware receives the raw context before validation\n let index = 0;\n const next = async (): Promise<HandlerResponse> => {\n if (index >= allMiddleware.length) {\n return executePipeline();\n }\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- index bounds checked above\n const mw = allMiddleware[index++]!;\n return mw(rawRequest, rawContext, next);\n };\n\n response = await next();\n }\n\n // Always validate status code (must be 100-599)\n validateStatusCode(response.status);\n\n // Validate response schema (if enabled)\n if (shouldValidateResponse) {\n const responseValidationResult = validateResponseData(route, response);\n\n if (!responseValidationResult.success) {\n const errors = responseValidationResult.errors ?? [];\n throw new ControllerError({\n message: 'Response validation failed',\n code: 'RESPONSE_VALIDATION_ERROR',\n cause: new Error(errors.map((e) => `${e.path.join('.')}: ${e.message}`).join('; ')),\n });\n }\n }\n\n return response;\n },\n };\n}\n\n/**\n * Validates request data against route request schemas.\n */\nfunction validateRequestData(\n route: RouteDefinition,\n rawRequest: RawHttpRequest,\n): ValidationResultInternal {\n const errors: ValidationIssue[] = [];\n const data: {\n body?: unknown;\n query?: unknown;\n pathParams?: unknown;\n headers?: unknown;\n } = {};\n\n // Validate body\n if (route.request.body) {\n const result = (route.request.body as SchemaAdapter).validate(rawRequest.body);\n if (result.success) {\n data.body = result.data;\n } else {\n errors.push(\n ...result.issues.map((issue) => ({\n ...issue,\n path: ['body', ...issue.path],\n })),\n );\n }\n }\n\n // Validate query\n if (route.request.query) {\n const queryObj = normalizeQuery(rawRequest.query);\n const result = (route.request.query as SchemaAdapter).validate(queryObj);\n if (result.success) {\n data.query = result.data;\n } else {\n errors.push(\n ...result.issues.map((issue) => ({\n ...issue,\n path: ['query', ...issue.path],\n })),\n );\n }\n }\n\n // Validate path params\n if (route.request.params) {\n const result = (route.request.params as SchemaAdapter).validate(rawRequest.params ?? {});\n if (result.success) {\n data.pathParams = result.data;\n } else {\n errors.push(\n ...result.issues.map((issue) => ({\n ...issue,\n path: ['pathParams', ...issue.path],\n })),\n );\n }\n } else {\n // Normalize raw params if no schema (ensure all values are strings)\n data.pathParams = normalizePathParams(rawRequest.params);\n }\n\n // Validate headers\n if (route.request.headers) {\n const headersObj = normalizeHeaders(rawRequest.headers);\n const result = (route.request.headers as SchemaAdapter).validate(headersObj);\n if (result.success) {\n data.headers = result.data;\n } else {\n errors.push(\n ...result.issues.map((issue) => ({\n ...issue,\n path: ['headers', ...issue.path],\n })),\n );\n }\n }\n\n if (errors.length > 0) {\n return { success: false, errors };\n }\n\n return { success: true, data };\n}\n\n/**\n * Validates response data against the route's response schema.\n *\n * Looks up the matching status code in `route.responses` and validates\n * the response body against its schema, if one is defined.\n */\nfunction validateResponseData(\n route: RouteDefinition,\n response: HandlerResponse,\n): ValidationResultInternal {\n if (!route.responses) {\n return { success: true };\n }\n\n const entry = route.responses[String(response.status)];\n const schema = entry?.schema as SchemaAdapter | undefined;\n\n if (!schema) {\n return { success: true };\n }\n\n const result = schema.validate(response.body);\n\n if (result.success) {\n return { success: true };\n }\n\n const errors = result.issues.map((issue) => ({\n ...issue,\n path: ['response', ...issue.path],\n }));\n\n return { success: false, errors };\n}\n\n/**\n * Validates context data against route context schema.\n */\nfunction validateContextData(\n route: RouteDefinition,\n context: HandlerContext,\n): ContextValidationResultInternal {\n const contextSchema = route.request.context as SchemaAdapter | undefined;\n\n // No context schema defined - skip validation\n if (!contextSchema) {\n return { success: true, data: context };\n }\n\n // Validate context against schema\n const result = contextSchema.validate(context);\n\n if (result.success) {\n return { success: true, data: result.data };\n }\n\n // Prefix errors with 'context.' for clarity\n const errors = result.issues.map((issue) => ({\n ...issue,\n path: ['context', ...issue.path],\n }));\n\n return { success: false, errors };\n}\n\ninterface ValidationResultInternal {\n success: boolean;\n errors?: ValidationIssue[];\n data?: {\n body?: unknown;\n query?: unknown;\n pathParams?: unknown;\n headers?: unknown;\n };\n}\n\ninterface ContextValidationResultInternal {\n success: boolean;\n errors?: ValidationIssue[];\n data?: unknown;\n}\n\n/**\n * Internal validated request type with unknown fields.\n * Used inside createRouteHandler where specific types are erased.\n * The requestMapper receives the properly typed ValidatedRequest<TRoute>.\n */\ninterface ValidatedRequestInternal {\n readonly body: unknown;\n readonly query: unknown;\n readonly pathParams: unknown;\n readonly headers: unknown;\n readonly raw: {\n readonly method: string;\n readonly url: string;\n readonly headers: Record<string, string>;\n };\n}\n\n/**\n * Validates that an HTTP status code is in the valid range (100-599).\n *\n * @throws {ControllerError} If the status code is invalid\n */\nfunction validateStatusCode(status: number): void {\n if (!Number.isInteger(status) || status < 100 || status > 599) {\n throw new ControllerError({\n message: `Invalid HTTP status code: ${status}. Status must be an integer between 100 and 599.`,\n code: 'INVALID_STATUS_CODE',\n });\n }\n}\n\n/**\n * Normalizes query parameters, preserving arrays for duplicate keys.\n *\n * When a query parameter appears multiple times (e.g., `?tag=a&tag=b`),\n * the framework provides an array. This function preserves that array\n * so schema validation can properly validate array vs single-value params.\n *\n * Empty strings are allowed (e.g., `?flag=` results in `{ flag: '' }`).\n * Undefined values are filtered out from arrays.\n */\nfunction normalizeQuery(\n query?: Record<string, string | string[] | undefined>,\n): Record<string, string | string[]> {\n if (!query) return {};\n\n const result: Record<string, string | string[]> = {};\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined) continue;\n\n if (Array.isArray(value)) {\n // Filter out undefined values but preserve the array structure\n const definedValues = value.filter((v): v is string => v !== undefined);\n if (definedValues.length === 1 && definedValues[0] !== undefined) {\n // Single value in array - unwrap for convenience\n result[key] = definedValues[0];\n } else if (definedValues.length > 1) {\n // Multiple values - preserve as array for schema validation\n result[key] = definedValues;\n }\n // Empty array (all undefined) - skip this key\n } else {\n result[key] = value;\n }\n }\n return result;\n}\n\n/**\n * Normalizes path parameters to ensure all values are non-empty strings.\n *\n * @throws {InvalidRequestError} If any path parameter is empty\n */\nfunction normalizePathParams(params?: Record<string, string>): Record<string, string> {\n if (!params) return {};\n\n const result: Record<string, string> = {};\n const emptyParams: string[] = [];\n\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined) {\n const stringValue = String(value);\n if (stringValue === '') {\n emptyParams.push(key);\n } else {\n result[key] = stringValue;\n }\n }\n }\n\n // Throw error for empty path params instead of silently filtering\n if (emptyParams.length > 0) {\n throw new InvalidRequestError({\n message: 'Path parameters cannot be empty',\n validationErrors: emptyParams.map((param) => ({\n field: `pathParams.${param}`,\n message: 'Path parameter cannot be empty',\n })),\n });\n }\n\n return result;\n}\n\n/**\n * Normalizes headers to a flat object.\n *\n * Per RFC 7230, multiple header values are joined with \", \" (comma + space).\n * Headers are lowercased for consistency.\n */\nfunction normalizeHeaders(\n headers: Record<string, string | string[] | undefined>,\n): Record<string, string> {\n const result: Record<string, string> = {};\n for (const [key, value] of Object.entries(headers)) {\n if (value === undefined) continue;\n\n if (Array.isArray(value)) {\n // Filter undefined values and join per RFC 7230\n const definedValues = value.filter((v): v is string => v !== undefined);\n if (definedValues.length > 0) {\n result[key.toLowerCase()] = definedValues.join(', ');\n }\n } else {\n result[key.toLowerCase()] = value;\n }\n }\n return result;\n}\n\n/**\n * Generates a unique request ID using crypto-secure UUID.\n */\nfunction generateRequestId(): string {\n return `req_${crypto.randomUUID()}`;\n}\n","/**\n * @fileoverview Builder pattern for creating type-safe server routes.\n *\n * The `serverRoutes` function returns a builder that provides 100% type inference\n * for all handler parameters - no manual type annotations required.\n *\n * @module unified/server/server-routes-builder\n */\n\nimport type { RouterConfig, RouterDefinition, GetRoute, RouterKeys } from '../route/types';\nimport type {\n AnyHandlerConfig,\n CreateServerRoutesOptions,\n HandlerResponse,\n MiddlewareFunction,\n RouteHandlerConfig,\n SimpleHandlerConfig,\n SimpleHandlerFn,\n TypedContext,\n UnifiedRouteInput,\n UseCasePort,\n ValidatedRequest,\n} from './types';\nimport { createServerRoutesInternal } from './create-server-routes';\nimport type { RouteDefinition } from '../route/types';\n\n// ============================================================================\n// Builder Types\n// ============================================================================\n\n/**\n * Error type displayed when attempting to build() with missing handlers.\n * The `___missingRoutes` property shows which routes are missing.\n */\nexport interface MissingHandlersError<TMissing extends string> {\n /**\n * This error indicates that not all routes have handlers.\n * Use buildPartial() to build with only the defined handlers,\n * or add handlers for the missing routes.\n */\n (options?: never): never;\n /** Routes that are missing handlers */\n readonly ___missingRoutes: TMissing;\n}\n\n/**\n * Handler configuration for the builder pattern.\n * Identical to RouteHandlerConfig but with proper TypedContext.\n */\nexport interface BuilderHandlerConfig<TRoute extends RouteDefinition, TInput, TOutput> {\n /**\n * Maps the validated HTTP request to use case input.\n * Both `req` and `ctx` are fully typed based on route schemas.\n */\n readonly requestMapper: (req: ValidatedRequest<TRoute>, ctx: TypedContext<TRoute>) => TInput;\n\n /**\n * The use case to execute.\n */\n readonly useCase: UseCasePort<TInput, TOutput>;\n\n /**\n * Maps the use case output to an HTTP response.\n */\n readonly responseMapper: (output: TOutput) => HandlerResponse;\n\n /**\n * Middleware to run before the handler.\n */\n readonly middleware?: readonly MiddlewareFunction[];\n}\n\n/**\n * Builder interface for creating type-safe server routes.\n *\n * Each `.handle()` call captures the specific route type and provides\n * full type inference for requestMapper, useCase, and responseMapper.\n *\n * @typeParam T - The router configuration type\n * @typeParam THandled - Union of route keys that have handlers (accumulates)\n *\n * @example\n * ```typescript\n * const routes = serverRoutes(projectRouter)\n * .handle('projects.create', {\n * requestMapper: (req, ctx) => ({\n * name: req.body.name, // Fully typed!\n * createdBy: ctx.userId, // Fully typed!\n * }),\n * useCase: createProjectUseCase,\n * responseMapper: (output) => ({\n * status: 201 as const,\n * body: { projectId: output.projectId },\n * }),\n * })\n * .handle('projects.list', { ... })\n * .build();\n * ```\n */\nexport interface ServerRoutesBuilder<T extends RouterConfig, THandled extends string = never> {\n /**\n * Register a simple handler for a route.\n * The handler receives validated request and context, returns response directly.\n *\n * @param key - The route key (e.g., 'projects.get')\n * @param handlerOrConfig - Simple handler function or configuration with handler and optional middleware\n * @returns A new builder with the route key added to handled routes\n */\n handle<K extends Exclude<RouterKeys<T>, THandled>>(\n key: K,\n handlerOrConfig: SimpleHandlerFn<GetRoute<T, K>> | SimpleHandlerConfig<GetRoute<T, K>>,\n ): ServerRoutesBuilder<T, THandled | K>;\n\n /**\n * Register a handler using the use case pattern.\n * Follows: requestMapper → useCase.execute() → responseMapper\n *\n * @param key - The route key (e.g., 'projects.create')\n * @param config - Handler configuration with requestMapper, useCase, responseMapper\n * @returns A new builder with the route key added to handled routes\n */\n handleWithUseCase<K extends Exclude<RouterKeys<T>, THandled>, TInput, TOutput>(\n key: K,\n config: BuilderHandlerConfig<GetRoute<T, K>, TInput, TOutput>,\n ): ServerRoutesBuilder<T, THandled | K>;\n\n /**\n * Build the routes array for framework registration.\n *\n * This method is only available when ALL routes have handlers.\n * If some routes are missing handlers, use `buildPartial()` instead.\n *\n * @param options - Optional configuration (validation, middleware)\n * @returns Array of route inputs for framework registration\n *\n * @throws {Error} At compile time if routes are missing (type error)\n */\n build: [Exclude<RouterKeys<T>, THandled>] extends [never]\n ? (options?: CreateServerRoutesOptions) => UnifiedRouteInput[]\n : MissingHandlersError<Exclude<RouterKeys<T>, THandled>>;\n\n /**\n * Build routes for only the defined handlers.\n *\n * Use this when you only want to register handlers for some routes,\n * not all routes in the router. No compile-time enforcement.\n *\n * @param options - Optional configuration (validation, middleware)\n * @returns Array of route inputs for framework registration\n */\n buildPartial(options?: CreateServerRoutesOptions): UnifiedRouteInput[];\n}\n\n// ============================================================================\n// Builder Implementation\n// ============================================================================\n\n/**\n * Internal builder implementation.\n *\n * Uses an immutable pattern where each handle() call returns a new\n * builder instance with the updated handlers map.\n */\nclass ServerRoutesBuilderImpl<T extends RouterConfig, THandled extends string = never> {\n private readonly router: T | RouterDefinition<T>;\n private readonly handlers: Map<string, AnyHandlerConfig<RouteDefinition, unknown, unknown>>;\n\n constructor(\n router: T | RouterDefinition<T>,\n handlers?: Map<string, AnyHandlerConfig<RouteDefinition, unknown, unknown>>,\n ) {\n this.router = router;\n this.handlers = handlers ?? new Map();\n }\n\n handle<K extends Exclude<RouterKeys<T>, THandled>>(\n key: K,\n handlerOrConfig: SimpleHandlerFn<GetRoute<T, K>> | SimpleHandlerConfig<GetRoute<T, K>>,\n ): ServerRoutesBuilder<T, THandled | K> {\n // Normalize function to config object\n const config: SimpleHandlerConfig<RouteDefinition> =\n typeof handlerOrConfig === 'function'\n ? { handler: handlerOrConfig as SimpleHandlerFn<RouteDefinition> }\n : (handlerOrConfig as SimpleHandlerConfig<RouteDefinition>);\n\n const newHandlers = new Map(this.handlers);\n newHandlers.set(key as string, config);\n\n return new ServerRoutesBuilderImpl<T, THandled | K>(\n this.router,\n newHandlers,\n ) as unknown as ServerRoutesBuilder<T, THandled | K>;\n }\n\n handleWithUseCase<K extends Exclude<RouterKeys<T>, THandled>, TInput, TOutput>(\n key: K,\n config: BuilderHandlerConfig<GetRoute<T, K>, TInput, TOutput>,\n ): ServerRoutesBuilder<T, THandled | K> {\n // Create new handlers map (immutable pattern)\n const newHandlers = new Map(this.handlers);\n newHandlers.set(key as string, config as RouteHandlerConfig<RouteDefinition, unknown, unknown>);\n\n // Return new builder with updated type\n // Cast through unknown is safe: the type system tracks THandled | K through the interface\n // The conditional type on `build` cannot be proven at compile time, hence the cast\n return new ServerRoutesBuilderImpl<T, THandled | K>(\n this.router,\n newHandlers,\n ) as unknown as ServerRoutesBuilder<T, THandled | K>;\n }\n\n // The build method's type is determined by the interface conditional type\n // At runtime, it always works the same way - the conditional type only affects compile-time\n build(options?: CreateServerRoutesOptions): UnifiedRouteInput[] {\n return createServerRoutesInternal(this.router, Object.fromEntries(this.handlers), options);\n }\n\n buildPartial(options?: CreateServerRoutesOptions): UnifiedRouteInput[] {\n return createServerRoutesInternal(this.router, Object.fromEntries(this.handlers), {\n ...options,\n allowPartial: true,\n });\n }\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * Creates a type-safe server routes builder for a router.\n *\n * The builder pattern provides 100% type inference for all handler parameters:\n * - `req.body`, `req.query`, `req.pathParams`, `req.headers` are typed from route schemas\n * - `ctx` is typed from the route's context schema\n * - `output` in responseMapper is typed from the use case\n *\n * @param router - Router definition or router config\n * @returns Builder for registering handlers\n *\n * @example Basic usage\n * ```typescript\n * import { serverRoutes } from '@cosmneo/onion-lasagna/http/server';\n * import { projectRouter } from './router';\n *\n * const routes = serverRoutes(projectRouter)\n * .handle('projects.create', {\n * requestMapper: (req, ctx) => ({\n * name: req.body.name,\n * createdBy: ctx.userId,\n * }),\n * useCase: createProjectUseCase,\n * responseMapper: (output) => ({\n * status: 201 as const,\n * body: { projectId: output.projectId },\n * }),\n * })\n * .handle('projects.list', {\n * requestMapper: (req) => ({\n * page: req.query.page ?? 1,\n * limit: req.query.limit ?? 20,\n * }),\n * useCase: listProjectsUseCase,\n * responseMapper: (output) => ({\n * status: 200 as const,\n * body: output.projects,\n * }),\n * })\n * .build();\n *\n * // Register with framework\n * registerHonoRoutes(app, routes);\n * ```\n *\n * @example Partial build (only some routes)\n * ```typescript\n * const routes = serverRoutes(projectRouter)\n * .handle('projects.create', { ... })\n * // Skip other routes\n * .buildPartial(); // No type error even with missing routes\n * ```\n *\n * @example With options\n * ```typescript\n * const routes = serverRoutes(projectRouter)\n * .handle('projects.create', { ... })\n * .handle('projects.list', { ... })\n * .build({\n * validateRequest: true,\n * validateResponse: process.env.NODE_ENV !== 'production',\n * middleware: [loggingMiddleware],\n * });\n * ```\n */\nexport function serverRoutes<T extends RouterConfig>(\n router: T | RouterDefinition<T>,\n): ServerRoutesBuilder<T, never> {\n // Cast through unknown is safe: initial builder has no handlers (THandled = never)\n return new ServerRoutesBuilderImpl(router) as unknown as ServerRoutesBuilder<T, never>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC4JO,SAAS,cAAc,MAAsB;AAClD,SAAO,KAAK,QAAQ,iCAAiC,KAAK;AAC5D;;;ACzEO,SAAS,kBAAkB,OAA0C;AAC1E,SACE,OAAO,UAAU,YACjB,UAAU,QACV,YAAY,SACZ,UAAU,SACV,YAAY;AAEhB;AAKO,SAAS,mBAAmB,OAA2C;AAC5E,SACE,OAAO,UAAU,YACjB,UAAU,QACV,eAAe,SACd,MAA2B,cAAc;AAE9C;AA8GO,SAAS,cACd,QACA,WAAW,IACgC;AAC3C,QAAM,SAAoD,CAAC;AAE3D,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,MAAM,GAAG;AACjD,UAAM,UAAU,WAAW,GAAG,QAAQ,IAAI,GAAG,KAAK;AAElD,QAAI,kBAAkB,KAAK,GAAG;AAC5B,aAAO,KAAK,EAAE,KAAK,SAAS,OAAO,MAAM,CAAC;AAAA,IAC5C,WAAW,mBAAmB,KAAK,GAAG;AACpC,aAAO,KAAK,GAAG,cAAc,MAAM,QAAQ,OAAO,CAAC;AAAA,IACrD,WAAW,OAAO,UAAU,YAAY,UAAU,MAAM;AACtD,aAAO,KAAK,GAAG,cAAc,OAAuB,OAAO,CAAC;AAAA,IAC9D;AAAA,EACF;AAEA,SAAO;AACT;;;ACMO,SAAS,sBACd,QACgD;AAChD,SAAO,aAAa,UAAU,OAAO,OAAO,YAAY;AAC1D;;;ACnNO,IAAe,aAAf,cAAkC,MAAM;AAAA;AAAA,EAE7B;AAAA;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d as RouterConfig, g as RouterKeys, G as GetRoute, e as RouterDefinition } from '../../router-definition.type-BElX-Pl4.cjs';
|
|
2
2
|
import '../schema/types.cjs';
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { R as RouteDefinition, H as HttpMethod,
|
|
1
|
+
import { R as RouteDefinition, H as HttpMethod, d as RouterConfig, g as RouterKeys, G as GetRoute, e as RouterDefinition } from '../../router-definition.type-DxG8ncJZ.js';
|
|
2
2
|
import '../schema/types.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import {
|
|
2
2
|
serverRoutes
|
|
3
|
-
} from "../../chunk-
|
|
3
|
+
} from "../../chunk-AUMHMWDD.js";
|
|
4
4
|
import "../../chunk-T7S574XQ.js";
|
|
5
5
|
import "../../chunk-ZG26OQFN.js";
|
|
6
6
|
import "../../chunk-A4JUAZK4.js";
|
|
7
|
-
import "../../chunk-
|
|
7
|
+
import "../../chunk-XP6PLTV2.js";
|
|
8
8
|
export {
|
|
9
9
|
serverRoutes
|
|
10
10
|
};
|