@fresho/router 0.3.2 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +65 -4
- package/dist/index.d.mts +102 -22
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +77 -15
- package/dist/index.mjs.map +1 -1
- package/dist/middleware/index.d.mts +50 -1
- package/dist/middleware/index.d.mts.map +1 -1
- package/dist/middleware/index.mjs +82 -1
- package/dist/middleware/index.mjs.map +1 -1
- package/dist/middleware-Bxq0LHLS.d.mts.map +1 -1
- package/docs/middleware.md +43 -0
- package/package.json +1 -1
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["errors: Record<string, string[]>","resultArray: unknown[]","success","coerced","errorMsg","result: Record<string, unknown>","allErrors: Record<string, string[]>","paramNames: string[]","propertyToSegment","compiled: CompiledRoute[]","path: Record<string, string>","context: MiddlewareContext","query: unknown","body: unknown","collectedRoutes: CollectedRoute[]","paths: Record<string, Record<string, object>>","operation: Record<string, unknown>","route","sharedConfig: SharedConfig","parts: string[]","init: RequestInit","current: Router<RouterRoutes> | undefined","entry: unknown","entry","params: Record<string, string>","sharedConfig: SharedConfig","query: unknown","result","body: unknown","requestInit: RequestInit","lines: string[]","keepAliveTimer: ReturnType<typeof setInterval> | undefined"],"sources":["../src/schema.ts","../src/types.ts","../src/handler.ts","../src/core.ts","../src/docs.ts","../src/client-proxy.ts","../src/http-client.ts","../src/local-client.ts","../src/streaming.ts"],"sourcesContent":["/**\n * @fileoverview Schema types and validation utilities.\n *\n * Provides shorthand schema definitions for validating query parameters and request bodies.\n * No external dependencies - uses simple string-based type definitions.\n *\n * Supported types:\n * - Primitives: `'string'`, `'number'`, `'boolean'`\n * - Optional: `'string?'`, `'number?'`, `'boolean?'`\n * - Arrays: `'string[]'`, `'number[]'`, `'boolean[]'`\n * - Optional arrays: `'string[]?'`, `'number[]?'`, `'boolean[]?'`\n * - Nested objects: `{ field: { nested: 'string' } }`\n *\n * @example\n * ```typescript\n * // In route definitions\n * const api = router({\n * users: router({\n * post: route({\n * query: { page: 'number?', limit: 'number?' },\n * body: {\n * name: 'string',\n * age: 'number',\n * tags: 'string[]?',\n * address: { city: 'string', zip: 'string?' },\n * },\n * handler: async (c) => {\n * c.query.page; // number | undefined\n * c.body.name; // string\n * c.body.address.city // string\n * },\n * }),\n * }),\n * });\n * ```\n */\n\n/** Primitive type strings. */\nexport type PrimitiveType = 'string' | 'number' | 'boolean' | 'unknown';\n\n/** Optional primitive type strings. */\nexport type OptionalPrimitiveType = 'string?' | 'number?' | 'boolean?' | 'unknown?';\n\n/** Array type strings. */\nexport type ArrayType = 'string[]' | 'number[]' | 'boolean[]' | 'unknown[]';\n\n/** Optional array type strings. */\nexport type OptionalArrayType = 'string[]?' | 'number[]?' | 'boolean[]?' | 'unknown[]?';\n\n/** All supported type strings. */\nexport type SchemaType = PrimitiveType | OptionalPrimitiveType | ArrayType | OptionalArrayType;\n\n/** Schema definition using shorthand syntax. Supports nested objects. */\nexport interface SchemaDefinition {\n [key: string]: SchemaType | SchemaDefinition;\n}\n\n/** Maps primitive type strings to TypeScript types. */\nexport type SchemaTypeMap = {\n string: string;\n 'string?': string | undefined;\n number: number;\n 'number?': number | undefined;\n boolean: boolean;\n 'boolean?': boolean | undefined;\n unknown: unknown;\n 'unknown?': unknown | undefined;\n 'string[]': string[];\n 'string[]?': string[] | undefined;\n 'number[]': number[];\n 'number[]?': number[] | undefined;\n 'boolean[]': boolean[];\n 'boolean[]?': boolean[] | undefined;\n 'unknown[]': unknown[];\n 'unknown[]?': unknown[] | undefined;\n};\n\n/** Checks if a schema field type is optional (ends with ?). */\ntype IsOptionalField<T> = T extends `${string}?` ? true : false;\n\n/** Infers TypeScript type from a schema field (type string or nested object). */\nexport type InferSchemaField<T> = T extends SchemaType\n ? SchemaTypeMap[T]\n : T extends SchemaDefinition\n ? InferSchema<T>\n : never;\n\n/** Gets keys of required fields (non-optional types). */\ntype RequiredKeys<T extends SchemaDefinition> = {\n [K in keyof T]: IsOptionalField<T[K]> extends true ? never : K;\n}[keyof T];\n\n/** Gets keys of optional fields (types ending with ?). */\ntype OptionalKeys<T extends SchemaDefinition> = {\n [K in keyof T]: IsOptionalField<T[K]> extends true ? K : never;\n}[keyof T];\n\n/**\n * Infers TypeScript type from schema definition.\n *\n * Required fields become required properties, optional fields (ending with ?)\n * become optional properties with `| undefined`.\n */\nexport type InferSchema<T extends SchemaDefinition> = {\n [K in RequiredKeys<T>]: InferSchemaField<T[K]>;\n} & {\n [K in OptionalKeys<T>]?: InferSchemaField<T[K]>;\n};\n\n/** Error object returned when validation fails. */\nexport interface ValidationError {\n flatten: () => { fieldErrors: Record<string, string[]> };\n}\n\n/** Validation result matching Zod's safeParse API for compatibility. */\nexport type ValidationResult<T> =\n | { success: true; data: T; error?: undefined }\n | { success: false; data?: undefined; error: ValidationError };\n\n/** Compiled schema with validate method. */\nexport interface CompiledSchema<T> {\n safeParse: (data: object) => ValidationResult<T>;\n}\n\n/** Valid base types for primitives and arrays. */\nconst PRIMITIVE_TYPES = ['string', 'number', 'boolean', 'unknown'];\n\n/** Checks if a schema field is a nested object (not a type string). */\nfunction isNestedSchema(field: SchemaType | SchemaDefinition): field is SchemaDefinition {\n return typeof field === 'object' && field !== null;\n}\n\n/**\n * Validates and coerces a single primitive value.\n * Returns [success, result, errorMessage].\n */\nfunction validatePrimitive(value: unknown, baseType: string): [boolean, unknown, string | null] {\n switch (baseType) {\n case 'string':\n return [true, String(value), null];\n\n case 'number': {\n const num = Number(value);\n if (Number.isNaN(num)) {\n return [false, undefined, 'Expected number'];\n }\n return [true, num, null];\n }\n\n case 'boolean': {\n if (value === 'true' || value === '1' || value === true) {\n return [true, true, null];\n } else if (value === 'false' || value === '0' || value === false) {\n return [true, false, null];\n }\n return [false, undefined, 'Expected boolean (true/false)'];\n }\n\n case 'unknown':\n // Pass through any value without validation.\n return [true, value, null];\n\n default:\n return [false, undefined, `Unknown type: ${baseType}`];\n }\n}\n\n/**\n * Validates a schema field value (primitive, array, or nested object).\n * Returns [success, result, errors].\n */\nfunction validateField(\n key: string,\n field: SchemaType | SchemaDefinition,\n value: unknown,\n parentPath: string = '',\n): [boolean, unknown, Record<string, string[]>] {\n const fieldPath = parentPath ? `${parentPath}.${key}` : key;\n const errors: Record<string, string[]> = {};\n\n // Handle nested object schemas.\n if (isNestedSchema(field)) {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n errors[fieldPath] = ['Expected object'];\n return [false, undefined, errors];\n }\n // Recursively validate nested schema.\n const nestedResult = validateSchema(field, value as Record<string, unknown>, fieldPath);\n return [nestedResult.success, nestedResult.data, nestedResult.errors];\n }\n\n // It's a type string.\n const typeStr = field as string;\n const isOptional = typeStr.endsWith('?');\n const isArray = typeStr.includes('[]');\n\n // Strip optional marker for base type extraction.\n let baseType = isOptional ? typeStr.slice(0, -1) : typeStr;\n\n // Strip array marker.\n if (isArray) {\n baseType = baseType.replace('[]', '');\n }\n\n // Handle missing/empty values.\n if (value === undefined || value === '') {\n if (!isOptional) {\n errors[fieldPath] = ['Required'];\n return [false, undefined, errors];\n }\n return [true, undefined, {}];\n }\n\n // Handle array types.\n if (isArray) {\n if (!Array.isArray(value)) {\n errors[fieldPath] = ['Expected array'];\n return [false, undefined, errors];\n }\n\n const resultArray: unknown[] = [];\n for (let i = 0; i < value.length; i++) {\n const [success, coerced, errorMsg] = validatePrimitive(value[i], baseType);\n if (!success) {\n errors[`${fieldPath}[${i}]`] = [errorMsg!];\n return [false, undefined, errors];\n }\n resultArray.push(coerced);\n }\n return [true, resultArray, {}];\n }\n\n // Handle primitive types.\n const [success, coerced, errorMsg] = validatePrimitive(value, baseType);\n if (!success) {\n errors[fieldPath] = [errorMsg!];\n return [false, undefined, errors];\n }\n return [true, coerced, {}];\n}\n\n/**\n * Validates a full schema against data.\n * Returns { success, data, errors }.\n */\nfunction validateSchema(\n schema: SchemaDefinition,\n data: Record<string, unknown>,\n parentPath: string = '',\n): { success: boolean; data: Record<string, unknown>; errors: Record<string, string[]> } {\n const result: Record<string, unknown> = {};\n const allErrors: Record<string, string[]> = {};\n\n for (const [key, field] of Object.entries(schema)) {\n const value = data[key];\n const [success, coerced, fieldErrors] = validateField(key, field, value, parentPath);\n\n if (!success) {\n Object.assign(allErrors, fieldErrors);\n } else if (coerced !== undefined) {\n result[key] = coerced;\n }\n }\n\n return {\n success: Object.keys(allErrors).length === 0,\n data: result,\n errors: allErrors,\n };\n}\n\n/** Validates schema definition at compile time. */\nfunction validateSchemaDefinition(schema: SchemaDefinition, path: string = ''): void {\n for (const [key, field] of Object.entries(schema)) {\n const fieldPath = path ? `${path}.${key}` : key;\n\n if (isNestedSchema(field)) {\n validateSchemaDefinition(field, fieldPath);\n } else {\n const typeStr = field as string;\n const isOptional = typeStr.endsWith('?');\n let baseType = isOptional ? typeStr.slice(0, -1) : typeStr;\n baseType = baseType.replace('[]', '');\n\n if (!PRIMITIVE_TYPES.includes(baseType)) {\n throw new Error(`Unknown type '${typeStr}' at '${fieldPath}'`);\n }\n }\n }\n}\n\n/**\n * Compiles a schema definition into a validator.\n *\n * Used internally by the router to validate query parameters and request bodies.\n * Provides a Zod-compatible `safeParse` API for consistency.\n *\n * @param schema - The schema definition object\n * @returns A compiled schema with `safeParse` method\n *\n * @example\n * ```typescript\n * const userSchema = compileSchema({\n * name: 'string',\n * age: 'number',\n * email: 'string?',\n * });\n *\n * const result = userSchema.safeParse({ name: 'Alice', age: 30 });\n * if (result.success) {\n * console.log(result.data.name); // 'Alice'\n * } else {\n * console.log(result.error.flatten().fieldErrors);\n * }\n * ```\n */\nexport function compileSchema<T extends SchemaDefinition>(\n schema: T,\n): CompiledSchema<InferSchema<T>> {\n // Validate schema structure at compile time.\n validateSchemaDefinition(schema);\n\n return {\n safeParse(data: object): ValidationResult<InferSchema<T>> {\n const {\n success,\n data: result,\n errors,\n } = validateSchema(schema, data as Record<string, unknown>);\n\n if (!success) {\n return {\n success: false,\n error: { flatten: () => ({ fieldErrors: errors }) },\n };\n }\n\n return { success: true, data: result as InferSchema<T> };\n },\n };\n}\n","/**\n * @fileoverview Core type definitions for the routing library.\n *\n * **Path Convention:**\n * - Property names = URL path segments\n * - `$param` prefix = dynamic segment (`:param`)\n * - `get`, `post`, `put`, `patch`, `delete` = HTTP method handlers\n *\n * **Structure:**\n * - `router({ ... })` - groups paths, can have middleware\n * - `route({ query?, body?, handler })` - single method with schemas\n * - Bare functions as shorthand for handlers without schemas\n */\n\nimport type { Middleware } from './middleware.js';\nimport type { InferSchema, SchemaDefinition } from './schema.js';\n\n/** Standard HTTP methods. */\nexport type Method = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'options' | 'head';\n\n/** HTTP method property names. */\nexport const HTTP_METHODS = new Set<string>([\n 'get',\n 'post',\n 'put',\n 'patch',\n 'delete',\n 'options',\n 'head',\n]);\n\n/** Symbol to mark an object as a route definition. */\nexport const ROUTE_MARKER = Symbol.for('@fresho/router:route');\n\n/** Symbol to mark an object as a router. */\nexport const ROUTER_MARKER = Symbol.for('@fresho/router:router');\n\n/**\n * Brand symbol for Router type identification across module boundaries.\n * This enables TypeScript to recognize Router types even when generic\n * type information is lost during cross-package imports.\n */\ndeclare const ROUTER_BRAND: unique symbol;\n\n/** Brand type for Router identification in conditional types. */\nexport type RouterBrand = { readonly [ROUTER_BRAND]: true };\n\n/**\n * Extracts the parameter name from a `$param` property name.\n */\nexport type ExtractParamFromProperty<T extends string> = T extends `$${infer Param}`\n ? Param\n : never;\n\n/**\n * Checks if a property name is a dynamic parameter (starts with $).\n */\nexport type IsParamProperty<T extends string> = T extends `$${string}` ? true : false;\n\n/**\n * Collects path params from a property path array.\n */\nexport type CollectPathParams<Path extends string[]> = Path extends [\n infer Head extends string,\n ...infer Rest extends string[],\n]\n ? (Head extends `$${infer Param}` ? { [K in Param]: string } : {}) & CollectPathParams<Rest>\n : {};\n\n/** Execution context for background tasks (Cloudflare Workers compatible). */\nexport interface ExecutionContext {\n waitUntil(promise: Promise<unknown>): void;\n passThroughOnException(): void;\n}\n\n/**\n * Unified context object passed to handlers.\n */\nexport type Context<\n Q = unknown,\n B = unknown,\n P extends Record<string, string> = Record<string, string>,\n Ctx = {},\n> = {\n /** The original Request. */\n request: Request;\n /** URL path parameters from `$param` segments. */\n path: P;\n /** Query string parameters. */\n query: Q;\n /** Request body. */\n body: B;\n /** Execution context for background tasks. */\n executionCtx?: ExecutionContext;\n /** Environment bindings. */\n env: Ctx extends { env: infer E } ? E : unknown;\n} & Omit<Ctx, 'env'>;\n\n/**\n * Typed response wrapper that carries the response body type.\n */\nexport type TypedResponse<T> = Response & { __responseType?: T };\n\n/**\n * Handler function type.\n */\nexport type TypedHandler<\n Q = unknown,\n B = unknown,\n P extends Record<string, string> = Record<string, string>,\n R = unknown,\n Ctx = {},\n> = (\n context: Context<Q, B, P, Ctx>,\n) => R | Response | TypedResponse<R> | Promise<R | Response | TypedResponse<R>>;\n\n/**\n * Route definition - a single HTTP method handler with optional schemas.\n *\n * Use `route()` when you need query or body validation schemas.\n * For simple handlers without schemas, use bare functions in the router.\n *\n * @example\n * ```typescript\n * // With schemas\n * get: route({\n * query: { limit: 'number?' },\n * handler: async (c) => ({ items: [], limit: c.query.limit }),\n * })\n *\n * // Without schemas (bare function shorthand)\n * get: async (c) => ({ items: [] })\n * ```\n */\nexport interface RouteDefinition<\n Q extends SchemaDefinition = {},\n B extends SchemaDefinition = {},\n R = unknown,\n P extends Record<string, string> = Record<string, string>,\n Ctx = {},\n> {\n /** Query parameter schema for validation. */\n query?: Q;\n /** Request body schema for validation. */\n body?: B;\n /** Optional description for documentation. */\n description?: string;\n /** The request handler function. */\n handler: TypedHandler<InferSchema<Q>, InferSchema<B>, P, R, Ctx>;\n}\n\n/** A bare handler function (shorthand for route without schemas). */\nexport type BareHandler = (\n context: Context<unknown, unknown, Record<string, string>, unknown>,\n) => unknown;\n\n/** Checks if a value is a function. */\nexport function isFunction(value: unknown): value is BareHandler {\n return typeof value === 'function';\n}\n\n/** Checks if entry is a Route (marked with ROUTE_MARKER). */\nexport function isRoute(entry: unknown): entry is RouteDefinition {\n return typeof entry === 'object' && entry !== null && ROUTE_MARKER in entry;\n}\n\n/** Checks if entry is a Router (marked with ROUTER_MARKER). */\nexport function isRouter(entry: unknown): entry is Router<RouterRoutes> {\n return typeof entry === 'object' && entry !== null && ROUTER_MARKER in entry;\n}\n\n/**\n * A method handler - either a route with schemas or a bare function.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type MethodEntry = RouteDefinition<any, any, any, any, any> | BareHandler;\n\n/**\n * Router routes record.\n *\n * Can contain:\n * - `get`, `post`, `put`, `patch`, `delete` - method handlers (route or function)\n * - Other property names - nested routers (path segments)\n * - `$param` properties - dynamic path segments\n */\nexport type RouterRoutes = {\n get?: MethodEntry;\n post?: MethodEntry;\n put?: MethodEntry;\n patch?: MethodEntry;\n delete?: MethodEntry;\n options?: MethodEntry;\n head?: MethodEntry;\n} & {\n [key: string]: MethodEntry | Router<RouterRoutes>;\n};\n\n/** Handler function signature for the standalone router. */\nexport type FetchHandler = (\n request: Request,\n env?: unknown,\n ctx?: ExecutionContext,\n) => Response | Promise<Response>;\n\n/**\n * Router - groups paths and can have middleware.\n *\n * @example\n * ```typescript\n * const api = router({\n * // Method handlers for this path\n * get: async (c) => [...],\n * post: route({ body: { name: 'string' }, handler: async (c) => c.body }),\n *\n * // Nested path segments\n * users: router({\n * get: async (c) => [...],\n * $id: router({\n * get: async (c) => ({ id: c.path.id }),\n * }),\n * }),\n * });\n * ```\n */\nexport interface Router<T extends RouterRoutes> extends RouterBrand {\n /** Route definitions and nested routers. */\n readonly routes: T;\n /** Middleware applied to all routes in this router. */\n readonly middleware?: Middleware[];\n /**\n * Creates a fetch handler for use with Cloudflare Workers, Deno, Bun, etc.\n */\n handler(): FetchHandler;\n}\n","/**\n * @fileoverview HTTP request handler for @fresho/router.\n *\n * Builds paths from property names:\n * - Regular properties = path segments\n * - `$param` properties = dynamic segments (`:param`)\n * - `get`, `post`, etc. = method handlers\n */\n\nimport type { Middleware, MiddlewareContext } from './middleware.js';\nimport { runMiddleware } from './middleware.js';\nimport type { CompiledSchema } from './schema.js';\nimport { compileSchema } from './schema.js';\nimport type {\n ExecutionContext,\n FetchHandler,\n RouteDefinition,\n Router,\n RouterRoutes,\n} from './types.js';\nimport { HTTP_METHODS, isFunction, isRoute, isRouter } from './types.js';\n\n/** Compiled route with pattern matcher and handler. */\ninterface CompiledRoute {\n method: string;\n pattern: RegExp;\n paramNames: string[];\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n handler: (context: any) => unknown;\n middleware: Middleware[];\n querySchema?: CompiledSchema<unknown>;\n bodySchema?: CompiledSchema<unknown>;\n}\n\n/**\n * Escapes special regex characters in a string.\n */\nfunction escapeRegex(str: string): string {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n/**\n * Converts a path with :param segments to a regex pattern.\n */\nfunction pathToRegex(path: string): { pattern: RegExp; paramNames: string[] } {\n const paramNames: string[] = [];\n const parts = path.split(/:(\\w+)/g);\n let regexStr = '';\n\n for (let i = 0; i < parts.length; i++) {\n if (i % 2 === 0) {\n regexStr += escapeRegex(parts[i]);\n } else {\n paramNames.push(parts[i]);\n regexStr += '([^/]+)';\n }\n }\n\n return {\n pattern: new RegExp(`^${regexStr}$`),\n paramNames,\n };\n}\n\n/**\n * Converts a property name to a path segment.\n * - `$param` becomes `:param`\n * - Other names become literal segments\n */\nfunction propertyToSegment(prop: string): string {\n if (prop.startsWith('$')) {\n return `:${prop.slice(1)}`;\n }\n return prop;\n}\n\n/** Collects and compiles all routes from a router tree. */\nfunction compileRoutes(\n routerDef: Router<RouterRoutes>,\n parentPath = '',\n parentMiddleware: Middleware[] = [],\n): CompiledRoute[] {\n const currentMiddleware = [...parentMiddleware, ...(routerDef.middleware || [])];\n const compiled: CompiledRoute[] = [];\n\n for (const [prop, entry] of Object.entries(routerDef.routes)) {\n // Check if entry is a nested router first (takes precedence over method name check).\n // This allows path segments named 'get', 'post', etc. when they contain routers.\n if (isRouter(entry)) {\n // Nested router - recurse with updated path.\n const segment = propertyToSegment(prop);\n const newPath = parentPath ? `${parentPath}/${segment}` : `/${segment}`;\n compiled.push(...compileRoutes(entry, newPath, currentMiddleware));\n } else if (HTTP_METHODS.has(prop)) {\n // Method handler (get, post, etc.) - only when entry is a route or function.\n const method = prop.toUpperCase();\n const path = parentPath || '/';\n const { pattern, paramNames } = pathToRegex(path);\n\n if (isFunction(entry)) {\n // Bare function handler.\n compiled.push({\n method,\n pattern,\n paramNames,\n handler: entry,\n middleware: currentMiddleware,\n });\n } else if (isRoute(entry)) {\n // Route with schemas.\n const routeDef = entry as RouteDefinition;\n compiled.push({\n method,\n pattern,\n paramNames,\n handler: routeDef.handler,\n middleware: currentMiddleware,\n querySchema: routeDef.query ? compileSchema(routeDef.query) : undefined,\n bodySchema: routeDef.body ? compileSchema(routeDef.body) : undefined,\n });\n }\n }\n }\n\n return compiled;\n}\n\n/**\n * Strips the body from a response for HEAD requests.\n */\nfunction stripBodyForHead(response: Response, isHead: boolean): Response {\n if (!isHead) return response;\n return new Response(null, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n}\n\n/**\n * Creates a fetch handler from a router definition.\n *\n * @example\n * ```typescript\n * const api = router({\n * health: router({\n * get: async () => ({ status: 'ok' }),\n * }),\n * users: router({\n * get: async () => [...],\n * $id: router({\n * get: async (c) => ({ id: c.path.id }),\n * }),\n * }),\n * });\n *\n * export default { fetch: api.handler() };\n * ```\n */\nexport function createHandler<T extends RouterRoutes>(routerDef: Router<T>): FetchHandler {\n const compiledRoutes = compileRoutes(routerDef);\n\n return async (request: Request, env?: unknown, ctx?: ExecutionContext): Promise<Response> => {\n const url = new URL(request.url);\n const method = request.method.toUpperCase();\n const isHead = method === 'HEAD';\n\n // Find matching route.\n for (const compiled of compiledRoutes) {\n const methodMatches =\n compiled.method === method ||\n method === 'OPTIONS' ||\n (method === 'HEAD' && compiled.method === 'GET');\n if (!methodMatches) continue;\n\n const match = compiled.pattern.exec(url.pathname);\n if (!match) continue;\n\n // Extract path parameters.\n const path: Record<string, string> = {};\n for (let i = 0; i < compiled.paramNames.length; i++) {\n path[compiled.paramNames[i]] = decodeURIComponent(match[i + 1]);\n }\n\n // Create middleware context.\n const context: MiddlewareContext = {\n request,\n path,\n query: {},\n body: {},\n env,\n executionCtx: ctx,\n };\n\n // Run middleware and handler.\n if (\n compiled.middleware.length > 0 ||\n compiled.handler ||\n compiled.querySchema ||\n compiled.bodySchema\n ) {\n const response = await runMiddleware(compiled.middleware, context, async () => {\n const routeId = `${compiled.method} ${url.pathname}`;\n\n // Validate query params.\n let query: unknown = {};\n if (compiled.querySchema) {\n const raw = Object.fromEntries(url.searchParams);\n const result = compiled.querySchema.safeParse(raw);\n if (!result.success) {\n return Response.json(\n {\n error: 'Invalid query parameters',\n route: routeId,\n details: result.error.flatten(),\n },\n { status: 400 },\n );\n }\n query = result.data;\n }\n\n // Validate body.\n let body: unknown = {};\n if (compiled.bodySchema && ['POST', 'PUT', 'PATCH'].includes(method)) {\n const raw = await request.json().catch(() => ({}));\n const result = compiled.bodySchema.safeParse(raw);\n if (!result.success) {\n return Response.json(\n { error: 'Invalid request body', route: routeId, details: result.error.flatten() },\n { status: 400 },\n );\n }\n body = result.data;\n }\n\n context.query = query;\n context.body = body;\n\n if (compiled.handler) {\n // Build handler context with middleware extensions.\n const handlerContext = {\n request,\n path,\n query,\n body,\n env,\n executionCtx: ctx,\n };\n\n // Copy middleware extensions.\n for (const key of Object.keys(context)) {\n if (!['request', 'path', 'query', 'body', 'env', 'executionCtx'].includes(key)) {\n (handlerContext as Record<string, unknown>)[key] = (\n context as Record<string, unknown>\n )[key];\n }\n }\n\n const result = await compiled.handler(handlerContext);\n if (result instanceof Response) {\n return result;\n }\n return Response.json(result);\n }\n\n return Response.json({});\n });\n return stripBodyForHead(response, isHead);\n }\n\n return stripBodyForHead(Response.json({}), isHead);\n }\n\n return Response.json({ error: 'Not Found' }, { status: 404 });\n };\n}\n","/**\n * @fileoverview Core route and router creation functions.\n *\n * ## Path Convention\n * - Property names = URL path segments\n * - `$param` prefix = dynamic segment (`:param`)\n * - `get`, `post`, `put`, `patch`, `delete` = HTTP method handlers\n *\n * ## Typing Best Practices\n *\n * **Schemas** (`query`/`body`) provide runtime validation AND type inference.\n * Use them for any input that needs validation:\n * ```typescript\n * get: route({\n * query: { limit: 'number?' },\n * handler: async (c) => c.query.limit, // limit: number | undefined\n * })\n * ```\n *\n * **Context** (`route.ctx<T>()`) provides types only (no validation).\n * Use it for path params, env bindings, and middleware-injected values:\n * ```typescript\n * interface MyContext {\n * path: { id: string };\n * env: { DB: Database };\n * user: { name: string }; // from auth middleware\n * }\n * get: route.ctx<MyContext>()({\n * handler: async (c) => ({ id: c.path.id, user: c.user.name }),\n * })\n * ```\n *\n * **Important:** Don't add explicit type annotations to handler parameters.\n * Let types flow from schemas and context:\n * ```typescript\n * // GOOD: types inferred from schema\n * handler: async (c) => c.query.limit\n *\n * // BAD: redundant type annotation\n * handler: async (c: { query: { limit?: number } }) => c.query.limit\n * ```\n */\n\nimport { createHandler } from './handler.js';\nimport type { Middleware } from './middleware.js';\nimport type { SchemaDefinition } from './schema.js';\nimport type { RouteDefinition, Router, RouterRoutes } from './types.js';\nimport { ROUTE_MARKER, ROUTER_MARKER } from './types.js';\n\n/**\n * Creates a route with query/body validation schemas.\n *\n * Use `route()` when you need request validation. For simple handlers\n * without validation, you can use bare functions directly in the router.\n *\n * @example\n * ```typescript\n * // Route with query validation\n * get: route({\n * query: { limit: 'number?', offset: 'number?' },\n * handler: async (c) => {\n * const items = await db.list(c.query.limit, c.query.offset);\n * return { items };\n * },\n * })\n *\n * // Route with body validation\n * post: route({\n * body: { name: 'string', email: 'string' },\n * handler: async (c) => {\n * const user = await db.create(c.body);\n * return user;\n * },\n * })\n *\n * // Simple handler without validation (bare function)\n * get: async () => ({ status: 'ok' })\n * ```\n */\nexport function route<\n const Q extends SchemaDefinition = {},\n const B extends SchemaDefinition = {},\n R = unknown,\n>(definition: RouteDefinition<Q, B, R, {}, {}>): RouteDefinition<Q, B, R, {}, {}> {\n return { ...definition, [ROUTE_MARKER]: true } as RouteDefinition<Q, B, R, {}, {}>;\n}\n\n/** Return type of route.ctx<T>() - callable and chainable. */\ninterface CtxBuilder<Ctx> {\n <const Q extends SchemaDefinition = {}, const B extends SchemaDefinition = {}, R = unknown>(\n definition: RouteDefinition<Q, B, R, {}, Ctx>,\n ): RouteDefinition<Q, B, R, {}, Ctx>;\n\n ctx<AdditionalCtx>(): CtxBuilder<Ctx & AdditionalCtx>;\n}\n\n/** Creates a chainable context builder. */\nfunction createCtxBuilder<Ctx>(): CtxBuilder<Ctx> {\n const builder = <\n const Q extends SchemaDefinition = {},\n const B extends SchemaDefinition = {},\n R = unknown,\n >(\n definition: RouteDefinition<Q, B, R, {}, Ctx>,\n ): RouteDefinition<Q, B, R, {}, Ctx> =>\n ({ ...definition, [ROUTE_MARKER]: true }) as RouteDefinition<Q, B, R, {}, Ctx>;\n\n builder.ctx = <AdditionalCtx>() => createCtxBuilder<Ctx & AdditionalCtx>();\n\n return builder as CtxBuilder<Ctx>;\n}\n\n/**\n * Creates a route with typed context for values not covered by schemas.\n *\n * Use `route.ctx<T>()` to type:\n * - **Path params**: `{ path: { id: string } }` for `$id` segments\n * - **Env bindings**: `{ env: { DB: Database } }` for runtime environment\n * - **Middleware values**: `{ user: User }` for auth middleware, etc.\n *\n * Context provides types only, not runtime validation. For validated inputs,\n * use `query` and `body` schemas instead.\n *\n * @example\n * ```typescript\n * interface AppContext {\n * path: { id: string };\n * env: { DB: D1Database };\n * user: { id: string }; // injected by auth middleware\n * }\n *\n * $id: router({\n * get: route.ctx<AppContext>()({\n * query: { include: 'string?' }, // schema for validation\n * handler: async (c) => {\n * // c.path.id, c.env.DB, c.user.id - from context\n * // c.query.include - from schema\n * return c.env.DB.get(c.path.id);\n * },\n * }),\n * })\n * ```\n */\nroute.ctx = <Ctx>(): CtxBuilder<Ctx> => createCtxBuilder<Ctx>();\n\n/**\n * Creates a router that groups paths and applies middleware.\n *\n * @example\n * ```typescript\n * const api = router({\n * health: router({\n * get: async () => ({ status: 'ok' }),\n * }),\n *\n * users: router({\n * // GET /users - list users\n * get: route({\n * query: { limit: 'number?' },\n * handler: async (c) => db.users.list(c.query.limit),\n * }),\n *\n * // POST /users - create user\n * post: route({\n * body: { name: 'string', email: 'string' },\n * handler: async (c) => db.users.create(c.body),\n * }),\n *\n * // /users/:id\n * $id: router({\n * get: async (c) => db.users.get(c.path.id),\n * delete: async (c) => db.users.delete(c.path.id),\n * }),\n * }),\n * });\n *\n * export default { fetch: api.handler() };\n * ```\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function router<T extends RouterRoutes, M extends Middleware<any>[]>(\n routes: T,\n ...middleware: M\n): Router<T> {\n // Cast needed because RouterBrand uses a type-only symbol declaration.\n const self = {\n routes,\n middleware: middleware.length > 0 ? middleware : undefined,\n handler() {\n return createHandler(self);\n },\n } as unknown as Router<T>;\n // Add marker for runtime type checking.\n (self as unknown as Record<symbol, boolean>)[ROUTER_MARKER] = true;\n return self;\n}\n","/**\n * @fileoverview OpenAPI documentation generation.\n *\n * Generates OpenAPI 3.0 documentation from router definitions.\n *\n * **Path Convention:**\n * - Property names = URL path segments\n * - `$param` prefix = dynamic segment (`{param}` in OpenAPI)\n * - `get`, `post`, `put`, `patch`, `delete` = HTTP method handlers\n */\n\nimport type { SchemaDefinition } from './schema.js';\nimport type { RouteDefinition, Router, RouterRoutes } from './types.js';\nimport { HTTP_METHODS, isFunction, isRoute, isRouter } from './types.js';\n\n/** Collected route info for documentation. */\ninterface CollectedRoute {\n path: string;\n method: string;\n route: RouteDefinition | null;\n}\n\n/** Converts property name to path segment, handling $param convention. */\nfunction propertyToSegment(prop: string): string {\n if (prop.startsWith('$')) {\n return `{${prop.slice(1)}}`;\n }\n return prop;\n}\n\n/** Collects all routes from a router tree. */\nfunction collectRoutes(routerDef: Router<RouterRoutes>, parentPath = ''): CollectedRoute[] {\n const collectedRoutes: CollectedRoute[] = [];\n\n for (const [prop, entry] of Object.entries(routerDef.routes)) {\n // Check if this is a method handler.\n if (HTTP_METHODS.has(prop)) {\n const path = parentPath || '/';\n if (isFunction(entry)) {\n collectedRoutes.push({ path, method: prop, route: null });\n } else if (isRoute(entry)) {\n collectedRoutes.push({ path, method: prop, route: entry });\n }\n } else if (isRouter(entry)) {\n // Nested router - recurse with updated path.\n const segment = propertyToSegment(prop);\n const newPath = parentPath ? `${parentPath}/${segment}` : `/${segment}`;\n collectedRoutes.push(...collectRoutes(entry, newPath));\n }\n }\n\n return collectedRoutes;\n}\n\n/** Generates OpenAPI documentation from a router. */\nexport function generateDocs(config: {\n title: string;\n version: string;\n description?: string;\n router: Router<RouterRoutes>;\n}): object {\n const paths: Record<string, Record<string, object>> = {};\n const allRoutes = collectRoutes(config.router);\n\n for (const { path, method, route } of allRoutes) {\n if (!paths[path]) {\n paths[path] = {};\n }\n\n const operation: Record<string, unknown> = {\n description: route?.description,\n responses: {\n 200: { description: 'Successful response' },\n 400: { description: 'Validation error' },\n },\n };\n\n // Add query parameters (only primitive types supported in query strings).\n if (route?.query) {\n const querySchema = route.query as SchemaDefinition;\n operation.parameters = Object.entries(querySchema)\n .filter(([, type]) => typeof type === 'string')\n .map(([name, type]) => ({\n name,\n in: 'query',\n required: !(type as string).endsWith('?'),\n schema: { type: (type as string).replace('?', '').replace('[]', '') },\n }));\n }\n\n // Add request body.\n if (route?.body && ['post', 'put', 'patch'].includes(method)) {\n const bodySchema = route.body as SchemaDefinition;\n operation.requestBody = {\n required: true,\n content: {\n 'application/json': {\n schema: {\n type: 'object',\n properties: Object.fromEntries(\n Object.entries(bodySchema).map(([name, type]) => {\n if (typeof type === 'string') {\n return [name, { type: type.replace('?', '').replace('[]', '') }];\n }\n // Nested object - simplified representation.\n return [name, { type: 'object' }];\n }),\n ),\n required: Object.entries(bodySchema)\n .filter(([, type]) => typeof type === 'string' && !type.endsWith('?'))\n .map(([name]) => name),\n },\n },\n },\n };\n }\n\n paths[path][method] = operation;\n }\n\n return {\n openapi: '3.0.0',\n info: {\n title: config.title,\n version: config.version,\n description: config.description,\n },\n paths,\n };\n}\n","import type { Method } from './types.js';\n\n// =============================================================================\n// Proxy Types\n// =============================================================================\n\nconst PREFIXED_HTTP_METHODS = new Set([\n '$get',\n '$post',\n '$put',\n '$patch',\n '$delete',\n '$options',\n '$head',\n]);\n\n/**\n * Configuration for the recursive proxy.\n */\nexport interface RecursiveProxyOptions {\n /**\n * Callback to execute when a method is invoked.\n * @param segments - The path segments accumulated so far.\n * @param method - The HTTP method to execute (e.g. 'get', 'post').\n * @param options - The arguments passed to the method execution (e.g. { query, body }).\n */\n onRequest: (segments: string[], method: Method, options?: unknown) => Promise<unknown>;\n}\n\n/**\n * Creates a recursive proxy that accumulates path segments and traps method calls.\n *\n * Use cases:\n * 1. HTTP Client: Accumulates path segments and executes HTTP requests on method calls.\n * 2. Local Client: Accumulates path segments and invokes local handlers on method calls.\n *\n * @param config - The proxy configuration.\n * @param segments - The initial path segments (default: []).\n */\nexport function createRecursiveProxy(\n config: RecursiveProxyOptions,\n segments: string[] = [],\n): unknown {\n // The proxy target is a function so that 'apply' can be intercepted (for the root call or recursive calls).\n // For the root client, this allows `client()` to be called (implicit GET /).\n // For nested paths, it allows `client.some.path()` (implicit GET /some/path).\n const callable = (options?: unknown) => {\n return config.onRequest(segments, 'get', options);\n };\n\n return new Proxy(callable, {\n get(_target, prop) {\n if (typeof prop !== 'string') return undefined;\n\n // Handle standard function methods and toJSON\n // This prevents 'apply', 'call', etc. from being treated as path segments.\n if (\n prop === 'apply' ||\n prop === 'call' ||\n prop === 'bind' ||\n prop === 'toString' ||\n prop === 'toJSON'\n ) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (_target as any)[prop];\n }\n\n // Check if this property is a method trap.\n if (PREFIXED_HTTP_METHODS.has(prop)) {\n const method = prop.slice(1) as Method;\n return (options?: unknown) => {\n return config.onRequest(segments, method, options);\n };\n }\n\n // Otherwise = nested path segment.\n return createRecursiveProxy(config, [...segments, prop]);\n },\n\n // Trap direct function calls (e.g. client() or client.path())\n apply(_target, _thisArg, args) {\n return callable(args[0]);\n },\n });\n}\n","/**\n * @fileoverview HTTP client for @fresho/router.\n *\n * Provides a typed HTTP client using type-only imports.\n * URLs are built from property access chains:\n * - Property names = path segments (including `get`, `post`, etc.)\n * - `$param` = dynamic segment (substituted from path options)\n * - `$get()`, `$post()`, etc. = HTTP method execution\n * - Direct call `()` = implicit GET\n *\n * The `$` prefix distinguishes HTTP method execution from path navigation,\n * allowing routes with path segments named after HTTP methods (e.g., `/api/get`).\n *\n * @example\n * ```typescript\n * // Type-only import - no server code in bundle!\n * import type { api } from './server/api.js';\n * import { createHttpClient } from '@fresho/router';\n *\n * const client = createHttpClient<typeof api>({\n * baseUrl: 'https://api.example.com',\n * });\n *\n * // URLs from property chains:\n * await client.health(); // GET /health (implicit)\n * await client.users.$get(); // GET /users (explicit)\n * await client.users.$post({ body: {...} }); // POST /users\n * await client.users.$id({ path: { id: '123' } }); // GET /users/123\n *\n * // Navigate to path segments named after HTTP methods:\n * await client.api.get.$get(); // GET /api/get\n * await client.resources.delete.$get(); // GET /resources/delete\n * ```\n */\n\nimport { createRecursiveProxy } from './client-proxy.js';\nimport type { HeaderValue, RequestOptions, RouterClient } from './client-types.js';\nimport type { Method, Router, RouterRoutes } from './types.js';\n\n// =============================================================================\n// Configuration Types\n// =============================================================================\n\n/** HTTP client configuration. */\nexport interface HttpClientConfig {\n baseUrl?: string;\n headers?: Record<string, HeaderValue>;\n credentials?: RequestCredentials;\n /** Custom fetch implementation for interception or environment-specific behavior. */\n fetch?: typeof fetch;\n}\n\n/** Extra options for HTTP requests (headers). */\nexport interface HttpExtraOptions {\n headers?: HeadersInit;\n /** If true, returns the raw Response object instead of parsing as JSON. */\n raw?: boolean;\n}\n\n/** Options for an HTTP request. */\nexport type HttpRequestOptions = RequestOptions<HttpExtraOptions>;\n\n// =============================================================================\n// Client Type Construction\n// =============================================================================\n\n/** Top-level HTTP client type. */\nexport type HttpClient<T extends Router<RouterRoutes>> = {\n configure(config: HttpClientConfig): void;\n} & RouterClient<T['routes'], HttpExtraOptions>;\n\n// =============================================================================\n// Implementation\n// =============================================================================\n\ninterface SharedConfig {\n current: HttpClientConfig;\n}\n\nconst BODY_METHODS = new Set(['post', 'put', 'patch']);\n\n/**\n * Creates a typed HTTP client.\n *\n * HTTP methods are prefixed with `$` to distinguish them from path segments:\n * - `.$get()`, `.$post()`, `.$put()`, `.$patch()`, `.$delete()` - execute HTTP methods\n * - `.propertyName` - navigate to path segment (works for any name including `get`, `post`, etc.)\n * - Direct call `()` - implicit GET request\n *\n * @example\n * ```typescript\n * import type { api } from './server';\n * import { createHttpClient } from '@fresho/router';\n *\n * const client = createHttpClient<typeof api>({\n * baseUrl: 'https://api.example.com',\n * headers: { Authorization: () => `Bearer ${getToken()}` },\n * });\n *\n * // GET /health (implicit)\n * await client.health();\n *\n * // GET /users (explicit)\n * await client.users.$get();\n *\n * // POST /users\n * await client.users.$post({ body: { name: 'Alice' } });\n *\n * // GET /users/123\n * await client.users.$id({ path: { id: '123' } });\n *\n * // Navigate through path segments named after HTTP methods:\n * // GET /api/get\n * await client.api.get.$get();\n * ```\n */\nexport function createHttpClient<T extends Router<RouterRoutes>>(\n config: HttpClientConfig = {},\n): HttpClient<T> {\n const sharedConfig: SharedConfig = { current: { ...config } };\n\n const client = {\n configure(newConfig: HttpClientConfig) {\n Object.assign(sharedConfig.current, newConfig);\n },\n } as HttpClient<T>;\n\n const proxy = createRecursiveProxy({\n onRequest: (segments, method, options) => {\n return executeRequest(\n sharedConfig,\n segments,\n method as Method,\n options as HttpRequestOptions,\n );\n },\n });\n\n return new Proxy(client, {\n get(target, prop) {\n if (prop === 'configure') return target.configure;\n // Delegate to recursive proxy for path building\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (proxy as any)[prop];\n },\n apply(_target, _thisArg, args) {\n // Direct call on root = GET /\n return executeRequest(sharedConfig, [], 'get', args[0] as HttpRequestOptions | undefined);\n },\n }) as HttpClient<T>;\n}\n\n/** Builds a URL path from segments, substituting $param with values. */\nfunction buildPath(segments: string[], pathParams?: Record<string, string>): string {\n const parts: string[] = [];\n\n for (const segment of segments) {\n if (segment.startsWith('$')) {\n const paramName = segment.slice(1);\n const value = pathParams?.[paramName];\n if (!value) {\n throw new Error(`Missing path parameter: ${paramName}`);\n }\n parts.push(encodeURIComponent(value));\n } else {\n parts.push(segment);\n }\n }\n\n return `/${parts.join('/')}`;\n}\n\n/** Executes an HTTP request. */\nasync function executeRequest(\n sharedConfig: SharedConfig,\n segments: string[],\n method: Method,\n options?: HttpRequestOptions,\n): Promise<unknown> {\n const config = sharedConfig.current;\n const path = buildPath(segments, options?.path);\n\n // Build URL.\n const baseUrl = config.baseUrl || (typeof window !== 'undefined' ? window.location?.origin : '');\n const url = new URL(path, baseUrl || 'http://localhost');\n\n // Add query params.\n if (options?.query) {\n for (const [key, value] of Object.entries(options.query)) {\n if (value !== undefined) {\n url.searchParams.set(key, String(value));\n }\n }\n }\n\n // Build headers.\n const headers = new Headers();\n if (config.headers) {\n for (const [key, value] of Object.entries(config.headers)) {\n const resolved = typeof value === 'function' ? await value() : value;\n if (resolved != null) {\n headers.set(key, resolved);\n }\n }\n }\n if (options?.headers) {\n new Headers(options.headers).forEach((v, k) => headers.set(k, v));\n }\n\n // Build request.\n const init: RequestInit = {\n method: method.toUpperCase(),\n headers,\n credentials: config.credentials,\n };\n\n // Add body.\n if (options?.body && BODY_METHODS.has(method)) {\n headers.set('Content-Type', 'application/json');\n init.body = JSON.stringify(options.body);\n }\n\n // Execute.\n const fetchUrl = config.baseUrl ? url.toString() : url.pathname + url.search;\n const fetchFn = config.fetch || fetch;\n const response = await fetchFn(fetchUrl, init);\n\n if (!response.ok) {\n throw new Error((await response.text()) || response.statusText);\n }\n\n if (options?.raw) {\n return response;\n }\n\n return response.json();\n}\n","/**\n * @fileoverview Local client for @fresho/router.\n *\n * Provides a typed client that invokes route handlers directly without HTTP.\n * Uses the same API as createHttpClient for consistency.\n *\n * @example\n * ```typescript\n * import { createLocalClient } from '@fresho/router';\n * import { api } from './api.js';\n *\n * const client = createLocalClient(api);\n *\n * // Same API as HTTP client\n * await client.health();\n * await client.users();\n * await client.users.post({ body: { name: 'Alice' } });\n * await client.users.$id({ path: { id: '123' } });\n * ```\n */\n\nimport { createRecursiveProxy } from './client-proxy.js';\nimport type { RequestOptions, RouterClient } from './client-types.js';\nimport { compileSchema } from './schema.js';\nimport type { ExecutionContext, RouteDefinition, Router, RouterRoutes } from './types.js';\nimport { isFunction, isRoute, isRouter } from './types.js';\n\n// =============================================================================\n// Configuration Types\n// =============================================================================\n\n/** Local client configuration. */\nexport interface LocalClientConfig {\n env?: unknown;\n ctx?: ExecutionContext;\n}\n\n/** Options for a local client request. */\nexport type LocalRequestOptions = RequestOptions<LocalClientConfig>;\n\n// =============================================================================\n// Client Type Construction (mirrors http-client types)\n// =============================================================================\n\nexport type LocalClient<T extends Router<RouterRoutes>> = {\n configure(config: LocalClientConfig): void;\n} & RouterClient<T['routes'], LocalClientConfig>;\n\n// =============================================================================\n// Implementation\n// =============================================================================\n\ninterface SharedConfig {\n current: LocalClientConfig;\n}\n\ninterface RouteInfo {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n handler: (context: any) => unknown;\n querySchema?: ReturnType<typeof compileSchema>;\n bodySchema?: ReturnType<typeof compileSchema>;\n}\n\n/**\n * Finds a method handler in a router tree.\n */\nfunction findHandler(\n routerDef: Router<RouterRoutes>,\n segments: string[],\n method: string,\n): RouteInfo | null {\n let current: Router<RouterRoutes> | undefined = routerDef;\n\n // Navigate through path segments.\n for (const segment of segments) {\n if (!current) return null;\n\n const entry: unknown = current.routes[segment];\n if (isRouter(entry)) {\n current = entry;\n } else {\n return null;\n }\n }\n\n if (!current) return null;\n\n // Find the method handler.\n const entry = current.routes[method];\n if (!entry) return null;\n\n if (isFunction(entry)) {\n return { handler: entry };\n }\n\n if (isRoute(entry)) {\n const routeDef = entry as RouteDefinition;\n return {\n handler: routeDef.handler,\n querySchema: routeDef.query ? compileSchema(routeDef.query) : undefined,\n bodySchema: routeDef.body ? compileSchema(routeDef.body) : undefined,\n };\n }\n\n return null;\n}\n\n/**\n * Collects path parameters from segments.\n */\nfunction collectPathParams(\n segments: string[],\n pathValues?: Record<string, string>,\n): Record<string, string> {\n const params: Record<string, string> = {};\n\n for (const segment of segments) {\n if (segment.startsWith('$')) {\n const paramName = segment.slice(1);\n const value = pathValues?.[paramName];\n if (!value) {\n throw new Error(`Missing path parameter: ${paramName}`);\n }\n params[paramName] = value;\n }\n }\n\n return params;\n}\n\n/**\n * Creates a typed local client from a router definition.\n *\n * @example\n * ```typescript\n * import { createLocalClient } from '@fresho/router';\n * import { api } from './api.js';\n *\n * const client = createLocalClient(api);\n * client.configure({ env: { DB: mockDatabase } });\n *\n * await client.health();\n * await client.users();\n * await client.users.post({ body: { name: 'Alice' } });\n * await client.users.$id({ path: { id: '123' } });\n * ```\n */\nexport function createLocalClient<T extends Router<RouterRoutes>>(routerDef: T): LocalClient<T> {\n const sharedConfig: SharedConfig = { current: {} };\n\n const client = {\n configure(config: LocalClientConfig) {\n Object.assign(sharedConfig.current, config);\n },\n } as LocalClient<T>;\n\n const proxy = createRecursiveProxy({\n onRequest: (segments, method, options) => {\n return invokeHandler(\n sharedConfig,\n routerDef,\n segments,\n method,\n options as LocalRequestOptions | undefined,\n );\n },\n });\n\n return new Proxy(client, {\n get(target, prop) {\n if (prop === 'configure') return target.configure;\n // Delegate to recursive proxy for path building\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (proxy as any)[prop];\n },\n apply(_target, _thisArg, args) {\n return invokeHandler(\n sharedConfig,\n routerDef,\n [],\n 'get',\n args[0] as LocalRequestOptions | undefined,\n );\n },\n }) as LocalClient<T>;\n}\n\n/** Invokes a handler directly. */\nasync function invokeHandler(\n sharedConfig: SharedConfig,\n routerDef: Router<RouterRoutes>,\n segments: string[],\n method: string,\n options?: LocalRequestOptions,\n): Promise<unknown> {\n const config = sharedConfig.current;\n const routeInfo = findHandler(routerDef, segments, method);\n\n if (!routeInfo) {\n throw new Error(`No handler found for ${method.toUpperCase()} /${segments.join('/')}`);\n }\n\n // Collect path params.\n const pathParams = collectPathParams(segments, options?.path);\n\n // Validate query.\n let query: unknown = {};\n if (routeInfo.querySchema) {\n const result = routeInfo.querySchema.safeParse(options?.query ?? {});\n if (!result.success) {\n throw new Error(`Invalid query parameters: ${JSON.stringify(result.error.flatten())}`);\n }\n query = result.data;\n }\n\n // Validate body.\n let body: unknown = {};\n if (routeInfo.bodySchema) {\n const result = routeInfo.bodySchema.safeParse((options?.body ?? {}) as object);\n if (!result.success) {\n throw new Error(`Invalid request body: ${JSON.stringify(result.error.flatten())}`);\n }\n body = result.data;\n }\n\n // Build path for synthetic request URL.\n const pathParts = segments.map((s) =>\n s.startsWith('$') ? encodeURIComponent(pathParams[s.slice(1)] || '') : s,\n );\n const urlPath = `/${pathParts.join('/')}`;\n const url = new URL(urlPath, 'http://localhost');\n if (options?.query) {\n for (const [key, value] of Object.entries(options.query)) {\n if (value !== undefined) {\n url.searchParams.set(key, String(value));\n }\n }\n }\n\n // Build request.\n const requestInit: RequestInit = {\n method: method.toUpperCase(),\n };\n if (options?.body && ['post', 'put', 'patch'].includes(method)) {\n requestInit.headers = { 'Content-Type': 'application/json' };\n requestInit.body = JSON.stringify(options.body);\n }\n\n const request = new Request(url.toString(), requestInit);\n\n // Build context.\n const context = {\n request,\n path: pathParams,\n query,\n body,\n env: options?.env ?? config.env,\n executionCtx: options?.ctx ?? config.ctx,\n };\n\n // Call handler.\n const result = await routeInfo.handler(context);\n\n // Parse response if needed.\n if (result instanceof Response) {\n return result.json();\n }\n\n return result;\n}\n","/**\n * @fileoverview Streaming response utilities for @fresho/router.\n *\n * Provides helpers for Server-Sent Events (SSE) and newline-delimited JSON (NDJSON)\n * streaming responses. These are useful for real-time updates, progress indicators,\n * and streaming large datasets.\n *\n * Available utilities:\n * - {@link sseResponse} - Server-Sent Events for real-time browser updates\n * - {@link streamJsonLines} - NDJSON for streaming JSON objects line by line\n *\n * @example\n * ```typescript\n * import { router, sseResponse, streamJsonLines } from '@fresho/router';\n *\n * const api = router({\n * // SSE for real-time updates\n * events: router({\n * get: async () => sseResponse(async (send, close) => {\n * for (let i = 0; i < 10; i++) {\n * send({ event: 'tick', data: { count: i } });\n * await sleep(1000);\n * }\n * close();\n * }),\n * }),\n *\n * // NDJSON for streaming data\n * export: router({\n * get: async () => streamJsonLines(async (send, close) => {\n * for await (const row of database.stream()) {\n * send(row);\n * }\n * close();\n * }),\n * }),\n * });\n * ```\n */\n\n/**\n * Options for SSE response.\n */\nexport interface SSEOptions {\n /** Custom headers to include in the response. */\n headers?: HeadersInit;\n /** Interval in milliseconds to send keep-alive comments (default: 30000). */\n keepAliveInterval?: number;\n}\n\n/**\n * Server-Sent Event message structure.\n */\nexport interface SSEMessage {\n /** Event type (optional). */\n event?: string;\n /** Event data. */\n data: string | object;\n /** Event ID (optional). */\n id?: string;\n /** Retry interval hint for client (optional). */\n retry?: number;\n}\n\n/**\n * Formats an SSE message for transmission.\n */\nfunction formatSSEMessage(message: SSEMessage): string {\n const lines: string[] = [];\n\n if (message.event) {\n lines.push(`event: ${message.event}`);\n }\n\n if (message.id) {\n lines.push(`id: ${message.id}`);\n }\n\n if (message.retry !== undefined) {\n lines.push(`retry: ${message.retry}`);\n }\n\n // Data can be a string or object (will be JSON stringified).\n const data = typeof message.data === 'string' ? message.data : JSON.stringify(message.data);\n\n // Split data by newlines and prefix each line with 'data: '.\n for (const line of data.split('\\n')) {\n lines.push(`data: ${line}`);\n }\n\n return `${lines.join('\\n')}\\n\\n`;\n}\n\n/**\n * Creates a Server-Sent Events (SSE) response.\n *\n * @example\n * ```typescript\n * const handler = async (c) => {\n * return sseResponse(async (send, close) => {\n * for (let i = 0; i < 5; i++) {\n * await send({ data: { count: i } });\n * await new Promise(r => setTimeout(r, 1000));\n * }\n * close();\n * });\n * };\n * ```\n */\nexport function sseResponse(\n handler: (send: (message: SSEMessage) => void, close: () => void) => void | Promise<void>,\n options: SSEOptions = {},\n): Response {\n const encoder = new TextEncoder();\n let isClosed = false;\n\n const stream = new ReadableStream({\n async start(controller) {\n // Send function for the handler.\n const send = (message: SSEMessage) => {\n if (!isClosed) {\n controller.enqueue(encoder.encode(formatSSEMessage(message)));\n }\n };\n\n // Close function for the handler.\n const close = () => {\n if (!isClosed) {\n isClosed = true;\n controller.close();\n }\n };\n\n // Optional keep-alive interval.\n const keepAliveInterval = options.keepAliveInterval ?? 30_000;\n let keepAliveTimer: ReturnType<typeof setInterval> | undefined;\n\n if (keepAliveInterval > 0) {\n keepAliveTimer = setInterval(() => {\n if (!isClosed) {\n // Send a comment as keep-alive.\n controller.enqueue(encoder.encode(': keep-alive\\n\\n'));\n }\n }, keepAliveInterval);\n }\n\n try {\n await handler(send, close);\n } finally {\n if (keepAliveTimer) {\n clearInterval(keepAliveTimer);\n }\n if (!isClosed) {\n controller.close();\n }\n }\n },\n });\n\n const headers = new Headers(options.headers);\n headers.set('Content-Type', 'text/event-stream');\n headers.set('Cache-Control', 'no-cache');\n headers.set('Connection', 'keep-alive');\n\n return new Response(stream, { headers });\n}\n\n/**\n * Creates a streaming JSON response where each line is a JSON object.\n *\n * Useful for streaming large datasets or real-time data where each item\n * can be processed as it arrives (NDJSON format).\n *\n * @example\n * ```typescript\n * const handler = async (c) => {\n * return streamJsonLines(async (send, close) => {\n * for (const item of largeDataset) {\n * await send(item);\n * }\n * close();\n * });\n * };\n * ```\n */\nexport function streamJsonLines(\n handler: (send: (data: object) => void, close: () => void) => void | Promise<void>,\n options: { headers?: HeadersInit } = {},\n): Response {\n const encoder = new TextEncoder();\n let isClosed = false;\n\n const stream = new ReadableStream({\n async start(controller) {\n const send = (data: object) => {\n if (!isClosed) {\n controller.enqueue(encoder.encode(`${JSON.stringify(data)}\\n`));\n }\n };\n\n const close = () => {\n if (!isClosed) {\n isClosed = true;\n controller.close();\n }\n };\n\n try {\n await handler(send, close);\n } finally {\n if (!isClosed) {\n controller.close();\n }\n }\n },\n });\n\n const headers = new Headers(options.headers);\n headers.set('Content-Type', 'application/x-ndjson');\n\n return new Response(stream, { headers });\n}\n"],"mappings":";;;;AA6HA,MAAM,kBAAkB;CAAC;CAAU;CAAU;CAAW;CAAU;;AAGlE,SAAS,eAAe,OAAiE;AACvF,QAAO,OAAO,UAAU,YAAY,UAAU;;;;;;AAOhD,SAAS,kBAAkB,OAAgB,UAAqD;AAC9F,SAAQ,UAAR;EACE,KAAK,SACH,QAAO;GAAC;GAAM,OAAO,MAAM;GAAE;GAAK;EAEpC,KAAK,UAAU;GACb,MAAM,MAAM,OAAO,MAAM;AACzB,OAAI,OAAO,MAAM,IAAI,CACnB,QAAO;IAAC;IAAO;IAAW;IAAkB;AAE9C,UAAO;IAAC;IAAM;IAAK;IAAK;;EAG1B,KAAK;AACH,OAAI,UAAU,UAAU,UAAU,OAAO,UAAU,KACjD,QAAO;IAAC;IAAM;IAAM;IAAK;YAChB,UAAU,WAAW,UAAU,OAAO,UAAU,MACzD,QAAO;IAAC;IAAM;IAAO;IAAK;AAE5B,UAAO;IAAC;IAAO;IAAW;IAAgC;EAG5D,KAAK,UAEH,QAAO;GAAC;GAAM;GAAO;GAAK;EAE5B,QACE,QAAO;GAAC;GAAO;GAAW,iBAAiB;GAAW;;;;;;;AAQ5D,SAAS,cACP,KACA,OACA,OACA,aAAqB,IACyB;CAC9C,MAAM,YAAY,aAAa,GAAG,WAAW,GAAG,QAAQ;CACxD,MAAMA,SAAmC,EAAE;AAG3C,KAAI,eAAe,MAAM,EAAE;AACzB,MAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,MAAM,EAAE;AACvE,UAAO,aAAa,CAAC,kBAAkB;AACvC,UAAO;IA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C,IAAI,WAAW;CAEf,MAAM,SAAS,IAAI,eAAe,EAChC,MAAM,MAAM,YAAY;EACtB,MAAM,QAAQ,SAAiB;AAC7B,OAAI,CAAC,SACH,YAAW,QAAQ,QAAQ,OAAO,GAAG,KAAK,UAAU,KAAK,CAAC,IAAI,CAAC;;EAInE,MAAM,cAAc;AAClB,OAAI,CAAC,UAAU;AACb,eAAW;AACX,eAAW,OAAO;;;AAItB,MAAI;AACF,SAAM,QAAQ,MAAM,MAAM;YAClB;AACR,OAAI,CAAC,SACH,YAAW,OAAO;;IAIzB,CAAC;CAEF,MAAM,UAAU,IAAI,QAAQ,QAAQ,QAAQ;AAC5C,SAAQ,IAAI,gBAAgB,uBAAuB;AAEnD,QAAO,IAAI,SAAS,QAAQ,EAAE,SAAS,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["errors: Record<string, string[]>","resultArray: unknown[]","success","coerced","errorMsg","result: Record<string, unknown>","allErrors: Record<string, string[]>","paramNames: string[]","propertyToSegment","compiled: CompiledRoute[]","path: Record<string, string>","context: MiddlewareContext","query: unknown","body: unknown","collectedRoutes: CollectedRoute[]","paths: Record<string, Record<string, object>>","operation: Record<string, unknown>","route","sharedConfig: SharedConfig","parts: string[]","init: RequestInit","current: Router<RouterRoutes> | undefined","entry: unknown","entry","params: Record<string, string>","sharedConfig: SharedConfig","query: unknown","result","body: unknown","requestInit: RequestInit","lines: string[]","keepAliveTimer: ReturnType<typeof setInterval> | undefined"],"sources":["../src/schema.ts","../src/types.ts","../src/handler.ts","../src/core.ts","../src/docs.ts","../src/client-proxy.ts","../src/client-response.ts","../src/http-client.ts","../src/local-client.ts","../src/streaming.ts"],"sourcesContent":["/**\n * @fileoverview Schema types and validation utilities.\n *\n * Provides shorthand schema definitions for validating query parameters and request bodies.\n * No external dependencies - uses simple string-based type definitions.\n *\n * Supported types:\n * - Primitives: `'string'`, `'number'`, `'boolean'`\n * - Optional: `'string?'`, `'number?'`, `'boolean?'`\n * - Arrays: `'string[]'`, `'number[]'`, `'boolean[]'`\n * - Optional arrays: `'string[]?'`, `'number[]?'`, `'boolean[]?'`\n * - Nested objects: `{ field: { nested: 'string' } }`\n *\n * @example\n * ```typescript\n * // In route definitions\n * const api = router({\n * users: router({\n * post: route({\n * query: { page: 'number?', limit: 'number?' },\n * body: {\n * name: 'string',\n * age: 'number',\n * tags: 'string[]?',\n * address: { city: 'string', zip: 'string?' },\n * },\n * handler: async (c) => {\n * c.query.page; // number | undefined\n * c.body.name; // string\n * c.body.address.city // string\n * },\n * }),\n * }),\n * });\n * ```\n */\n\n/** Primitive type strings. */\nexport type PrimitiveType = 'string' | 'number' | 'boolean' | 'unknown';\n\n/** Optional primitive type strings. */\nexport type OptionalPrimitiveType = 'string?' | 'number?' | 'boolean?' | 'unknown?';\n\n/** Array type strings. */\nexport type ArrayType = 'string[]' | 'number[]' | 'boolean[]' | 'unknown[]';\n\n/** Optional array type strings. */\nexport type OptionalArrayType = 'string[]?' | 'number[]?' | 'boolean[]?' | 'unknown[]?';\n\n/** All supported type strings. */\nexport type SchemaType = PrimitiveType | OptionalPrimitiveType | ArrayType | OptionalArrayType;\n\n/** Schema definition using shorthand syntax. Supports nested objects. */\nexport interface SchemaDefinition {\n [key: string]: SchemaType | SchemaDefinition;\n}\n\n/** Maps primitive type strings to TypeScript types. */\nexport type SchemaTypeMap = {\n string: string;\n 'string?': string | undefined;\n number: number;\n 'number?': number | undefined;\n boolean: boolean;\n 'boolean?': boolean | undefined;\n unknown: unknown;\n 'unknown?': unknown | undefined;\n 'string[]': string[];\n 'string[]?': string[] | undefined;\n 'number[]': number[];\n 'number[]?': number[] | undefined;\n 'boolean[]': boolean[];\n 'boolean[]?': boolean[] | undefined;\n 'unknown[]': unknown[];\n 'unknown[]?': unknown[] | undefined;\n};\n\n/** Checks if a schema field type is optional (ends with ?). */\ntype IsOptionalField<T> = T extends `${string}?` ? true : false;\n\n/** Infers TypeScript type from a schema field (type string or nested object). */\nexport type InferSchemaField<T> = T extends SchemaType\n ? SchemaTypeMap[T]\n : T extends SchemaDefinition\n ? InferSchema<T>\n : never;\n\n/** Gets keys of required fields (non-optional types). */\ntype RequiredKeys<T extends SchemaDefinition> = {\n [K in keyof T]: IsOptionalField<T[K]> extends true ? never : K;\n}[keyof T];\n\n/** Gets keys of optional fields (types ending with ?). */\ntype OptionalKeys<T extends SchemaDefinition> = {\n [K in keyof T]: IsOptionalField<T[K]> extends true ? K : never;\n}[keyof T];\n\n/**\n * Infers TypeScript type from schema definition.\n *\n * Required fields become required properties, optional fields (ending with ?)\n * become optional properties with `| undefined`.\n */\nexport type InferSchema<T extends SchemaDefinition> = {\n [K in RequiredKeys<T>]: InferSchemaField<T[K]>;\n} & {\n [K in OptionalKeys<T>]?: InferSchemaField<T[K]>;\n};\n\n/** Error object returned when validation fails. */\nexport interface ValidationError {\n flatten: () => { fieldErrors: Record<string, string[]> };\n}\n\n/** Validation result matching Zod's safeParse API for compatibility. */\nexport type ValidationResult<T> =\n | { success: true; data: T; error?: undefined }\n | { success: false; data?: undefined; error: ValidationError };\n\n/** Compiled schema with validate method. */\nexport interface CompiledSchema<T> {\n safeParse: (data: object) => ValidationResult<T>;\n}\n\n/** Valid base types for primitives and arrays. */\nconst PRIMITIVE_TYPES = ['string', 'number', 'boolean', 'unknown'];\n\n/** Checks if a schema field is a nested object (not a type string). */\nfunction isNestedSchema(field: SchemaType | SchemaDefinition): field is SchemaDefinition {\n return typeof field === 'object' && field !== null;\n}\n\n/**\n * Validates and coerces a single primitive value.\n * Returns [success, result, errorMessage].\n */\nfunction validatePrimitive(value: unknown, baseType: string): [boolean, unknown, string | null] {\n switch (baseType) {\n case 'string':\n return [true, String(value), null];\n\n case 'number': {\n const num = Number(value);\n if (Number.isNaN(num)) {\n return [false, undefined, 'Expected number'];\n }\n return [true, num, null];\n }\n\n case 'boolean': {\n if (value === 'true' || value === '1' || value === true) {\n return [true, true, null];\n } else if (value === 'false' || value === '0' || value === false) {\n return [true, false, null];\n }\n return [false, undefined, 'Expected boolean (true/false)'];\n }\n\n case 'unknown':\n // Pass through any value without validation.\n return [true, value, null];\n\n default:\n return [false, undefined, `Unknown type: ${baseType}`];\n }\n}\n\n/**\n * Validates a schema field value (primitive, array, or nested object).\n * Returns [success, result, errors].\n */\nfunction validateField(\n key: string,\n field: SchemaType | SchemaDefinition,\n value: unknown,\n parentPath: string = '',\n): [boolean, unknown, Record<string, string[]>] {\n const fieldPath = parentPath ? `${parentPath}.${key}` : key;\n const errors: Record<string, string[]> = {};\n\n // Handle nested object schemas.\n if (isNestedSchema(field)) {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n errors[fieldPath] = ['Expected object'];\n return [false, undefined, errors];\n }\n // Recursively validate nested schema.\n const nestedResult = validateSchema(field, value as Record<string, unknown>, fieldPath);\n return [nestedResult.success, nestedResult.data, nestedResult.errors];\n }\n\n // It's a type string.\n const typeStr = field as string;\n const isOptional = typeStr.endsWith('?');\n const isArray = typeStr.includes('[]');\n\n // Strip optional marker for base type extraction.\n let baseType = isOptional ? typeStr.slice(0, -1) : typeStr;\n\n // Strip array marker.\n if (isArray) {\n baseType = baseType.replace('[]', '');\n }\n\n // Handle missing/empty values.\n if (value === undefined || value === '') {\n if (!isOptional) {\n errors[fieldPath] = ['Required'];\n return [false, undefined, errors];\n }\n return [true, undefined, {}];\n }\n\n // Handle array types.\n if (isArray) {\n if (!Array.isArray(value)) {\n errors[fieldPath] = ['Expected array'];\n return [false, undefined, errors];\n }\n\n const resultArray: unknown[] = [];\n for (let i = 0; i < value.length; i++) {\n const [success, coerced, errorMsg] = validatePrimitive(value[i], baseType);\n if (!success) {\n errors[`${fieldPath}[${i}]`] = [errorMsg!];\n return [false, undefined, errors];\n }\n resultArray.push(coerced);\n }\n return [true, resultArray, {}];\n }\n\n // Handle primitive types.\n const [success, coerced, errorMsg] = validatePrimitive(value, baseType);\n if (!success) {\n errors[fieldPath] = [errorMsg!];\n return [false, undefined, errors];\n }\n return [true, coerced, {}];\n}\n\n/**\n * Validates a full schema against data.\n * Returns { success, data, errors }.\n */\nfunction validateSchema(\n schema: SchemaDefinition,\n data: Record<string, unknown>,\n parentPath: string = '',\n): { success: boolean; data: Record<string, unknown>; errors: Record<string, string[]> } {\n const result: Record<string, unknown> = {};\n const allErrors: Record<string, string[]> = {};\n\n for (const [key, field] of Object.entries(schema)) {\n const value = data[key];\n const [success, coerced, fieldErrors] = validateField(key, field, value, parentPath);\n\n if (!success) {\n Object.assign(allErrors, fieldErrors);\n } else if (coerced !== undefined) {\n result[key] = coerced;\n }\n }\n\n return {\n success: Object.keys(allErrors).length === 0,\n data: result,\n errors: allErrors,\n };\n}\n\n/** Validates schema definition at compile time. */\nfunction validateSchemaDefinition(schema: SchemaDefinition, path: string = ''): void {\n for (const [key, field] of Object.entries(schema)) {\n const fieldPath = path ? `${path}.${key}` : key;\n\n if (isNestedSchema(field)) {\n validateSchemaDefinition(field, fieldPath);\n } else {\n const typeStr = field as string;\n const isOptional = typeStr.endsWith('?');\n let baseType = isOptional ? typeStr.slice(0, -1) : typeStr;\n baseType = baseType.replace('[]', '');\n\n if (!PRIMITIVE_TYPES.includes(baseType)) {\n throw new Error(`Unknown type '${typeStr}' at '${fieldPath}'`);\n }\n }\n }\n}\n\n/**\n * Compiles a schema definition into a validator.\n *\n * Used internally by the router to validate query parameters and request bodies.\n * Provides a Zod-compatible `safeParse` API for consistency.\n *\n * @param schema - The schema definition object\n * @returns A compiled schema with `safeParse` method\n *\n * @example\n * ```typescript\n * const userSchema = compileSchema({\n * name: 'string',\n * age: 'number',\n * email: 'string?',\n * });\n *\n * const result = userSchema.safeParse({ name: 'Alice', age: 30 });\n * if (result.success) {\n * console.log(result.data.name); // 'Alice'\n * } else {\n * console.log(result.error.flatten().fieldErrors);\n * }\n * ```\n */\nexport function compileSchema<T extends SchemaDefinition>(\n schema: T,\n): CompiledSchema<InferSchema<T>> {\n // Validate schema structure at compile time.\n validateSchemaDefinition(schema);\n\n return {\n safeParse(data: object): ValidationResult<InferSchema<T>> {\n const {\n success,\n data: result,\n errors,\n } = validateSchema(schema, data as Record<string, unknown>);\n\n if (!success) {\n return {\n success: false,\n error: { flatten: () => ({ fieldErrors: errors }) },\n };\n }\n\n return { success: true, data: result as InferSchema<T> };\n },\n };\n}\n","/**\n * @fileoverview Core type definitions for the routing library.\n *\n * **Path Convention:**\n * - Property names = URL path segments\n * - `$param` prefix = dynamic segment (`:param`)\n * - `get`, `post`, `put`, `patch`, `delete` = HTTP method handlers\n *\n * **Structure:**\n * - `router({ ... })` - groups paths, can have middleware\n * - `route({ query?, body?, handler })` - single method with schemas\n * - Bare functions as shorthand for handlers without schemas\n */\n\nimport type { Middleware } from './middleware.js';\nimport type { InferSchema, SchemaDefinition } from './schema.js';\n\n/** Standard HTTP methods. */\nexport type Method = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'options' | 'head';\n\n/** HTTP method property names. */\nexport const HTTP_METHODS = new Set<string>([\n 'get',\n 'post',\n 'put',\n 'patch',\n 'delete',\n 'options',\n 'head',\n]);\n\n/** Symbol to mark an object as a route definition. */\nexport const ROUTE_MARKER = Symbol.for('@fresho/router:route');\n\n/** Symbol to mark an object as a router. */\nexport const ROUTER_MARKER = Symbol.for('@fresho/router:router');\n\n/**\n * Brand symbol for Router type identification across module boundaries.\n * This enables TypeScript to recognize Router types even when generic\n * type information is lost during cross-package imports.\n */\ndeclare const ROUTER_BRAND: unique symbol;\n\n/** Brand type for Router identification in conditional types. */\nexport type RouterBrand = { readonly [ROUTER_BRAND]: true };\n\n/**\n * Extracts the parameter name from a `$param` property name.\n */\nexport type ExtractParamFromProperty<T extends string> = T extends `$${infer Param}`\n ? Param\n : never;\n\n/**\n * Checks if a property name is a dynamic parameter (starts with $).\n */\nexport type IsParamProperty<T extends string> = T extends `$${string}` ? true : false;\n\n/**\n * Collects path params from a property path array.\n */\nexport type CollectPathParams<Path extends string[]> = Path extends [\n infer Head extends string,\n ...infer Rest extends string[],\n]\n ? (Head extends `$${infer Param}` ? { [K in Param]: string } : {}) & CollectPathParams<Rest>\n : {};\n\n/** Execution context for background tasks (Cloudflare Workers compatible). */\nexport interface ExecutionContext {\n waitUntil(promise: Promise<unknown>): void;\n passThroughOnException(): void;\n}\n\n/**\n * Unified context object passed to handlers.\n */\nexport type Context<\n Q = unknown,\n B = unknown,\n P extends Record<string, string> = Record<string, string>,\n Ctx = {},\n> = {\n /** The original Request. */\n request: Request;\n /** URL path parameters from `$param` segments. */\n path: P;\n /** Query string parameters. */\n query: Q;\n /** Request body. */\n body: B;\n /** Execution context for background tasks. */\n executionCtx?: ExecutionContext;\n /** Environment bindings. */\n env: Ctx extends { env: infer E } ? E : unknown;\n} & Omit<Ctx, 'env'>;\n\n/**\n * Typed response wrapper that carries the response body type.\n */\nexport type TypedResponse<T> = Response & { __responseType?: T };\n\n/**\n * Handler function type.\n */\nexport type TypedHandler<\n Q = unknown,\n B = unknown,\n P extends Record<string, string> = Record<string, string>,\n R = unknown,\n Ctx = {},\n> = (\n context: Context<Q, B, P, Ctx>,\n) => R | Response | TypedResponse<R> | Promise<R | Response | TypedResponse<R>>;\n\n/**\n * Route definition - a single HTTP method handler with optional schemas.\n *\n * Use `route()` when you need query or body validation schemas.\n * For simple handlers without schemas, use bare functions in the router.\n *\n * @example\n * ```typescript\n * // With schemas\n * get: route({\n * query: { limit: 'number?' },\n * handler: async (c) => ({ items: [], limit: c.query.limit }),\n * })\n *\n * // Without schemas (bare function shorthand)\n * get: async (c) => ({ items: [] })\n * ```\n */\nexport interface RouteDefinition<\n Q extends SchemaDefinition = {},\n B extends SchemaDefinition = {},\n R = unknown,\n P extends Record<string, string> = Record<string, string>,\n Ctx = {},\n> {\n /** Query parameter schema for validation. */\n query?: Q;\n /** Request body schema for validation. */\n body?: B;\n /** Optional description for documentation. */\n description?: string;\n /** The request handler function. */\n handler: TypedHandler<InferSchema<Q>, InferSchema<B>, P, R, Ctx>;\n}\n\n/** A bare handler function (shorthand for route without schemas). */\nexport type BareHandler = (\n context: Context<unknown, unknown, Record<string, string>, unknown>,\n) => unknown;\n\n/** Checks if a value is a function. */\nexport function isFunction(value: unknown): value is BareHandler {\n return typeof value === 'function';\n}\n\n/** Checks if entry is a Route (marked with ROUTE_MARKER). */\nexport function isRoute(entry: unknown): entry is RouteDefinition {\n return typeof entry === 'object' && entry !== null && ROUTE_MARKER in entry;\n}\n\n/** Checks if entry is a Router (marked with ROUTER_MARKER). */\nexport function isRouter(entry: unknown): entry is Router<RouterRoutes> {\n return typeof entry === 'object' && entry !== null && ROUTER_MARKER in entry;\n}\n\n/**\n * A method handler - either a route with schemas or a bare function.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type MethodEntry = RouteDefinition<any, any, any, any, any> | BareHandler;\n\n/**\n * Router routes record.\n *\n * Can contain:\n * - `get`, `post`, `put`, `patch`, `delete` - method handlers (route or function)\n * - Other property names - nested routers (path segments)\n * - `$param` properties - dynamic path segments\n */\nexport type RouterRoutes = {\n get?: MethodEntry;\n post?: MethodEntry;\n put?: MethodEntry;\n patch?: MethodEntry;\n delete?: MethodEntry;\n options?: MethodEntry;\n head?: MethodEntry;\n} & {\n [key: string]: MethodEntry | Router<RouterRoutes>;\n};\n\n/** Handler function signature for the standalone router. */\nexport type FetchHandler = (\n request: Request,\n env?: unknown,\n ctx?: ExecutionContext,\n) => Response | Promise<Response>;\n\n/**\n * Router - groups paths and can have middleware.\n *\n * @example\n * ```typescript\n * const api = router({\n * // Method handlers for this path\n * get: async (c) => [...],\n * post: route({ body: { name: 'string' }, handler: async (c) => c.body }),\n *\n * // Nested path segments\n * users: router({\n * get: async (c) => [...],\n * $id: router({\n * get: async (c) => ({ id: c.path.id }),\n * }),\n * }),\n * });\n * ```\n */\nexport interface Router<T extends RouterRoutes> extends RouterBrand {\n /** Route definitions and nested routers. */\n readonly routes: T;\n /** Middleware applied to all routes in this router. */\n readonly middleware?: Middleware[];\n /**\n * Creates a fetch handler for use with Cloudflare Workers, Deno, Bun, etc.\n */\n handler(): FetchHandler;\n}\n","/**\n * @fileoverview HTTP request handler for @fresho/router.\n *\n * Builds paths from property names:\n * - Regular properties = path segments\n * - `$param` properties = dynamic segments (`:param`)\n * - `get`, `post`, etc. = method handlers\n */\n\nimport type { Middleware, MiddlewareContext } from './middleware.js';\nimport { runMiddleware } from './middleware.js';\nimport type { CompiledSchema } from './schema.js';\nimport { compileSchema } from './schema.js';\nimport type {\n ExecutionContext,\n FetchHandler,\n RouteDefinition,\n Router,\n RouterRoutes,\n} from './types.js';\nimport { HTTP_METHODS, isFunction, isRoute, isRouter } from './types.js';\n\n/** Compiled route with pattern matcher and handler. */\ninterface CompiledRoute {\n method: string;\n pattern: RegExp;\n paramNames: string[];\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n handler: (context: any) => unknown;\n middleware: Middleware[];\n querySchema?: CompiledSchema<unknown>;\n bodySchema?: CompiledSchema<unknown>;\n}\n\n/**\n * Escapes special regex characters in a string.\n */\nfunction escapeRegex(str: string): string {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n/**\n * Converts a path with :param segments to a regex pattern.\n */\nfunction pathToRegex(path: string): { pattern: RegExp; paramNames: string[] } {\n const paramNames: string[] = [];\n const parts = path.split(/:(\\w+)/g);\n let regexStr = '';\n\n for (let i = 0; i < parts.length; i++) {\n if (i % 2 === 0) {\n regexStr += escapeRegex(parts[i]);\n } else {\n paramNames.push(parts[i]);\n regexStr += '([^/]+)';\n }\n }\n\n return {\n pattern: new RegExp(`^${regexStr}$`),\n paramNames,\n };\n}\n\n/**\n * Converts a property name to a path segment.\n * - `$param` becomes `:param`\n * - Other names become literal segments\n */\nfunction propertyToSegment(prop: string): string {\n if (prop.startsWith('$')) {\n return `:${prop.slice(1)}`;\n }\n return prop;\n}\n\n/** Collects and compiles all routes from a router tree. */\nfunction compileRoutes(\n routerDef: Router<RouterRoutes>,\n parentPath = '',\n parentMiddleware: Middleware[] = [],\n): CompiledRoute[] {\n const currentMiddleware = [...parentMiddleware, ...(routerDef.middleware || [])];\n const compiled: CompiledRoute[] = [];\n\n for (const [prop, entry] of Object.entries(routerDef.routes)) {\n // Check if entry is a nested router first (takes precedence over method name check).\n // This allows path segments named 'get', 'post', etc. when they contain routers.\n if (isRouter(entry)) {\n // Nested router - recurse with updated path.\n const segment = propertyToSegment(prop);\n const newPath = parentPath ? `${parentPath}/${segment}` : `/${segment}`;\n compiled.push(...compileRoutes(entry, newPath, currentMiddleware));\n } else if (HTTP_METHODS.has(prop)) {\n // Method handler (get, post, etc.) - only when entry is a route or function.\n const method = prop.toUpperCase();\n const path = parentPath || '/';\n const { pattern, paramNames } = pathToRegex(path);\n\n if (isFunction(entry)) {\n // Bare function handler.\n compiled.push({\n method,\n pattern,\n paramNames,\n handler: entry,\n middleware: currentMiddleware,\n });\n } else if (isRoute(entry)) {\n // Route with schemas.\n const routeDef = entry as RouteDefinition;\n compiled.push({\n method,\n pattern,\n paramNames,\n handler: routeDef.handler,\n middleware: currentMiddleware,\n querySchema: routeDef.query ? compileSchema(routeDef.query) : undefined,\n bodySchema: routeDef.body ? compileSchema(routeDef.body) : undefined,\n });\n }\n }\n }\n\n return compiled;\n}\n\n/**\n * Strips the body from a response for HEAD requests.\n */\nfunction stripBodyForHead(response: Response, isHead: boolean): Response {\n if (!isHead) return response;\n return new Response(null, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n}\n\n/**\n * Creates a fetch handler from a router definition.\n *\n * @example\n * ```typescript\n * const api = router({\n * health: router({\n * get: async () => ({ status: 'ok' }),\n * }),\n * users: router({\n * get: async () => [...],\n * $id: router({\n * get: async (c) => ({ id: c.path.id }),\n * }),\n * }),\n * });\n *\n * export default { fetch: api.handler() };\n * ```\n */\nexport function createHandler<T extends RouterRoutes>(routerDef: Router<T>): FetchHandler {\n const compiledRoutes = compileRoutes(routerDef);\n\n return async (request: Request, env?: unknown, ctx?: ExecutionContext): Promise<Response> => {\n const url = new URL(request.url);\n const method = request.method.toUpperCase();\n const isHead = method === 'HEAD';\n\n // Find matching route.\n for (const compiled of compiledRoutes) {\n const methodMatches =\n compiled.method === method ||\n method === 'OPTIONS' ||\n (method === 'HEAD' && compiled.method === 'GET');\n if (!methodMatches) continue;\n\n const match = compiled.pattern.exec(url.pathname);\n if (!match) continue;\n\n // Extract path parameters.\n const path: Record<string, string> = {};\n for (let i = 0; i < compiled.paramNames.length; i++) {\n path[compiled.paramNames[i]] = decodeURIComponent(match[i + 1]);\n }\n\n // Create middleware context.\n const context: MiddlewareContext = {\n request,\n path,\n query: {},\n body: {},\n env,\n executionCtx: ctx,\n };\n\n // Run middleware and handler.\n if (\n compiled.middleware.length > 0 ||\n compiled.handler ||\n compiled.querySchema ||\n compiled.bodySchema\n ) {\n const response = await runMiddleware(compiled.middleware, context, async () => {\n const routeId = `${compiled.method} ${url.pathname}`;\n\n // Validate query params.\n let query: unknown = {};\n if (compiled.querySchema) {\n const raw = Object.fromEntries(url.searchParams);\n const result = compiled.querySchema.safeParse(raw);\n if (!result.success) {\n return Response.json(\n {\n error: 'Invalid query parameters',\n route: routeId,\n details: result.error.flatten(),\n },\n { status: 400 },\n );\n }\n query = result.data;\n }\n\n // Validate body.\n let body: unknown = {};\n if (compiled.bodySchema && ['POST', 'PUT', 'PATCH'].includes(method)) {\n const raw = await request.json().catch(() => ({}));\n const result = compiled.bodySchema.safeParse(raw);\n if (!result.success) {\n return Response.json(\n { error: 'Invalid request body', route: routeId, details: result.error.flatten() },\n { status: 400 },\n );\n }\n body = result.data;\n }\n\n context.query = query;\n context.body = body;\n\n if (compiled.handler) {\n // Build handler context with middleware extensions.\n const handlerContext = {\n request,\n path,\n query,\n body,\n env,\n executionCtx: ctx,\n };\n\n // Copy middleware extensions.\n for (const key of Object.keys(context)) {\n if (!['request', 'path', 'query', 'body', 'env', 'executionCtx'].includes(key)) {\n (handlerContext as Record<string, unknown>)[key] = (\n context as Record<string, unknown>\n )[key];\n }\n }\n\n const result = await compiled.handler(handlerContext);\n if (result instanceof Response) {\n return result;\n }\n return Response.json(result);\n }\n\n return Response.json({});\n });\n return stripBodyForHead(response, isHead);\n }\n\n return stripBodyForHead(Response.json({}), isHead);\n }\n\n return Response.json({ error: 'Not Found' }, { status: 404 });\n };\n}\n","/**\n * @fileoverview Core route and router creation functions.\n *\n * ## Path Convention\n * - Property names = URL path segments\n * - `$param` prefix = dynamic segment (`:param`)\n * - `get`, `post`, `put`, `patch`, `delete` = HTTP method handlers\n *\n * ## Typing Best Practices\n *\n * **Schemas** (`query`/`body`) provide runtime validation AND type inference.\n * Use them for any input that needs validation:\n * ```typescript\n * get: route({\n * query: { limit: 'number?' },\n * handler: async (c) => c.query.limit, // limit: number | undefined\n * })\n * ```\n *\n * **Context** (`route.ctx<T>()`) provides types only (no validation).\n * Use it for path params, env bindings, and middleware-injected values:\n * ```typescript\n * interface MyContext {\n * path: { id: string };\n * env: { DB: Database };\n * user: { name: string }; // from auth middleware\n * }\n * get: route.ctx<MyContext>()({\n * handler: async (c) => ({ id: c.path.id, user: c.user.name }),\n * })\n * ```\n *\n * **Important:** Don't add explicit type annotations to handler parameters.\n * Let types flow from schemas and context:\n * ```typescript\n * // GOOD: types inferred from schema\n * handler: async (c) => c.query.limit\n *\n * // BAD: redundant type annotation\n * handler: async (c: { query: { limit?: number } }) => c.query.limit\n * ```\n */\n\nimport { createHandler } from './handler.js';\nimport type { Middleware } from './middleware.js';\nimport type { SchemaDefinition } from './schema.js';\nimport type { RouteDefinition, Router, RouterRoutes } from './types.js';\nimport { ROUTE_MARKER, ROUTER_MARKER } from './types.js';\n\n/**\n * Creates a route with query/body validation schemas.\n *\n * Use `route()` when you need request validation. For simple handlers\n * without validation, you can use bare functions directly in the router.\n *\n * @example\n * ```typescript\n * // Route with query validation\n * get: route({\n * query: { limit: 'number?', offset: 'number?' },\n * handler: async (c) => {\n * const items = await db.list(c.query.limit, c.query.offset);\n * return { items };\n * },\n * })\n *\n * // Route with body validation\n * post: route({\n * body: { name: 'string', email: 'string' },\n * handler: async (c) => {\n * const user = await db.create(c.body);\n * return user;\n * },\n * })\n *\n * // Simple handler without validation (bare function)\n * get: async () => ({ status: 'ok' })\n * ```\n */\nexport function route<\n const Q extends SchemaDefinition = {},\n const B extends SchemaDefinition = {},\n R = unknown,\n>(definition: RouteDefinition<Q, B, R, {}, {}>): RouteDefinition<Q, B, R, {}, {}> {\n return { ...definition, [ROUTE_MARKER]: true } as RouteDefinition<Q, B, R, {}, {}>;\n}\n\n/** Return type of route.ctx<T>() - callable and chainable. */\ninterface CtxBuilder<Ctx> {\n <const Q extends SchemaDefinition = {}, const B extends SchemaDefinition = {}, R = unknown>(\n definition: RouteDefinition<Q, B, R, {}, Ctx>,\n ): RouteDefinition<Q, B, R, {}, Ctx>;\n\n ctx<AdditionalCtx>(): CtxBuilder<Ctx & AdditionalCtx>;\n}\n\n/** Creates a chainable context builder. */\nfunction createCtxBuilder<Ctx>(): CtxBuilder<Ctx> {\n const builder = <\n const Q extends SchemaDefinition = {},\n const B extends SchemaDefinition = {},\n R = unknown,\n >(\n definition: RouteDefinition<Q, B, R, {}, Ctx>,\n ): RouteDefinition<Q, B, R, {}, Ctx> =>\n ({ ...definition, [ROUTE_MARKER]: true }) as RouteDefinition<Q, B, R, {}, Ctx>;\n\n builder.ctx = <AdditionalCtx>() => createCtxBuilder<Ctx & AdditionalCtx>();\n\n return builder as CtxBuilder<Ctx>;\n}\n\n/**\n * Creates a route with typed context for values not covered by schemas.\n *\n * Use `route.ctx<T>()` to type:\n * - **Path params**: `{ path: { id: string } }` for `$id` segments\n * - **Env bindings**: `{ env: { DB: Database } }` for runtime environment\n * - **Middleware values**: `{ user: User }` for auth middleware, etc.\n *\n * Context provides types only, not runtime validation. For validated inputs,\n * use `query` and `body` schemas instead.\n *\n * @example\n * ```typescript\n * interface AppContext {\n * path: { id: string };\n * env: { DB: D1Database };\n * user: { id: string }; // injected by auth middleware\n * }\n *\n * $id: router({\n * get: route.ctx<AppContext>()({\n * query: { include: 'string?' }, // schema for validation\n * handler: async (c) => {\n * // c.path.id, c.env.DB, c.user.id - from context\n * // c.query.include - from schema\n * return c.env.DB.get(c.path.id);\n * },\n * }),\n * })\n * ```\n */\nroute.ctx = <Ctx>(): CtxBuilder<Ctx> => createCtxBuilder<Ctx>();\n\n/**\n * Creates a router that groups paths and applies middleware.\n *\n * @example\n * ```typescript\n * const api = router({\n * health: router({\n * get: async () => ({ status: 'ok' }),\n * }),\n *\n * users: router({\n * // GET /users - list users\n * get: route({\n * query: { limit: 'number?' },\n * handler: async (c) => db.users.list(c.query.limit),\n * }),\n *\n * // POST /users - create user\n * post: route({\n * body: { name: 'string', email: 'string' },\n * handler: async (c) => db.users.create(c.body),\n * }),\n *\n * // /users/:id\n * $id: router({\n * get: async (c) => db.users.get(c.path.id),\n * delete: async (c) => db.users.delete(c.path.id),\n * }),\n * }),\n * });\n *\n * export default { fetch: api.handler() };\n * ```\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function router<T extends RouterRoutes, M extends Middleware<any>[]>(\n routes: T,\n ...middleware: M\n): Router<T> {\n // Cast needed because RouterBrand uses a type-only symbol declaration.\n const self = {\n routes,\n middleware: middleware.length > 0 ? middleware : undefined,\n handler() {\n return createHandler(self);\n },\n } as unknown as Router<T>;\n // Add marker for runtime type checking.\n (self as unknown as Record<symbol, boolean>)[ROUTER_MARKER] = true;\n return self;\n}\n","/**\n * @fileoverview OpenAPI documentation generation.\n *\n * Generates OpenAPI 3.0 documentation from router definitions.\n *\n * **Path Convention:**\n * - Property names = URL path segments\n * - `$param` prefix = dynamic segment (`{param}` in OpenAPI)\n * - `get`, `post`, `put`, `patch`, `delete` = HTTP method handlers\n */\n\nimport type { SchemaDefinition } from './schema.js';\nimport type { RouteDefinition, Router, RouterRoutes } from './types.js';\nimport { HTTP_METHODS, isFunction, isRoute, isRouter } from './types.js';\n\n/** Collected route info for documentation. */\ninterface CollectedRoute {\n path: string;\n method: string;\n route: RouteDefinition | null;\n}\n\n/** Converts property name to path segment, handling $param convention. */\nfunction propertyToSegment(prop: string): string {\n if (prop.startsWith('$')) {\n return `{${prop.slice(1)}}`;\n }\n return prop;\n}\n\n/** Collects all routes from a router tree. */\nfunction collectRoutes(routerDef: Router<RouterRoutes>, parentPath = ''): CollectedRoute[] {\n const collectedRoutes: CollectedRoute[] = [];\n\n for (const [prop, entry] of Object.entries(routerDef.routes)) {\n // Check if this is a method handler.\n if (HTTP_METHODS.has(prop)) {\n const path = parentPath || '/';\n if (isFunction(entry)) {\n collectedRoutes.push({ path, method: prop, route: null });\n } else if (isRoute(entry)) {\n collectedRoutes.push({ path, method: prop, route: entry });\n }\n } else if (isRouter(entry)) {\n // Nested router - recurse with updated path.\n const segment = propertyToSegment(prop);\n const newPath = parentPath ? `${parentPath}/${segment}` : `/${segment}`;\n collectedRoutes.push(...collectRoutes(entry, newPath));\n }\n }\n\n return collectedRoutes;\n}\n\n/** Generates OpenAPI documentation from a router. */\nexport function generateDocs(config: {\n title: string;\n version: string;\n description?: string;\n router: Router<RouterRoutes>;\n}): object {\n const paths: Record<string, Record<string, object>> = {};\n const allRoutes = collectRoutes(config.router);\n\n for (const { path, method, route } of allRoutes) {\n if (!paths[path]) {\n paths[path] = {};\n }\n\n const operation: Record<string, unknown> = {\n description: route?.description,\n responses: {\n 200: { description: 'Successful response' },\n 400: { description: 'Validation error' },\n },\n };\n\n // Add query parameters (only primitive types supported in query strings).\n if (route?.query) {\n const querySchema = route.query as SchemaDefinition;\n operation.parameters = Object.entries(querySchema)\n .filter(([, type]) => typeof type === 'string')\n .map(([name, type]) => ({\n name,\n in: 'query',\n required: !(type as string).endsWith('?'),\n schema: { type: (type as string).replace('?', '').replace('[]', '') },\n }));\n }\n\n // Add request body.\n if (route?.body && ['post', 'put', 'patch'].includes(method)) {\n const bodySchema = route.body as SchemaDefinition;\n operation.requestBody = {\n required: true,\n content: {\n 'application/json': {\n schema: {\n type: 'object',\n properties: Object.fromEntries(\n Object.entries(bodySchema).map(([name, type]) => {\n if (typeof type === 'string') {\n return [name, { type: type.replace('?', '').replace('[]', '') }];\n }\n // Nested object - simplified representation.\n return [name, { type: 'object' }];\n }),\n ),\n required: Object.entries(bodySchema)\n .filter(([, type]) => typeof type === 'string' && !type.endsWith('?'))\n .map(([name]) => name),\n },\n },\n },\n };\n }\n\n paths[path][method] = operation;\n }\n\n return {\n openapi: '3.0.0',\n info: {\n title: config.title,\n version: config.version,\n description: config.description,\n },\n paths,\n };\n}\n","import type { Method } from './types.js';\n\n// =============================================================================\n// Proxy Types\n// =============================================================================\n\nconst PREFIXED_HTTP_METHODS = new Set([\n '$get',\n '$post',\n '$put',\n '$patch',\n '$delete',\n '$options',\n '$head',\n]);\n\n/**\n * Configuration for the recursive proxy.\n */\nexport interface RecursiveProxyOptions {\n /**\n * Callback to execute when a method is invoked.\n * @param segments - The path segments accumulated so far.\n * @param method - The HTTP method to execute (e.g. 'get', 'post').\n * @param options - The arguments passed to the method execution (e.g. { query, body }).\n */\n onRequest: (segments: string[], method: Method, options?: unknown) => Promise<unknown>;\n /**\n * Callback to build a URL string without executing a request, invoked on `$url`.\n * @param segments - The path segments accumulated so far.\n * @param options - The arguments passed to `$url` (e.g. { path, query }).\n */\n onBuildUrl?: (segments: string[], options?: unknown) => string;\n}\n\n/**\n * Creates a recursive proxy that accumulates path segments and traps method calls.\n *\n * Use cases:\n * 1. HTTP Client: Accumulates path segments and executes HTTP requests on method calls.\n * 2. Local Client: Accumulates path segments and invokes local handlers on method calls.\n *\n * @param config - The proxy configuration.\n * @param segments - The initial path segments (default: []).\n */\nexport function createRecursiveProxy(\n config: RecursiveProxyOptions,\n segments: string[] = [],\n): unknown {\n // The proxy target is a function so that 'apply' can be intercepted (for the root call or recursive calls).\n // For the root client, this allows `client()` to be called (implicit GET /).\n // For nested paths, it allows `client.some.path()` (implicit GET /some/path).\n const callable = (options?: unknown) => {\n return config.onRequest(segments, 'get', options);\n };\n\n return new Proxy(callable, {\n get(_target, prop) {\n if (typeof prop !== 'string') return undefined;\n\n // Handle standard function methods and toJSON\n // This prevents 'apply', 'call', etc. from being treated as path segments.\n if (\n prop === 'apply' ||\n prop === 'call' ||\n prop === 'bind' ||\n prop === 'toString' ||\n prop === 'toJSON'\n ) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (_target as any)[prop];\n }\n\n // The `$url` trap builds a URL string synchronously instead of firing a request.\n if (prop === '$url' && config.onBuildUrl) {\n return (options?: unknown) => config.onBuildUrl!(segments, options);\n }\n\n // Check if this property is a method trap.\n if (PREFIXED_HTTP_METHODS.has(prop)) {\n const method = prop.slice(1) as Method;\n return (options?: unknown) => {\n return config.onRequest(segments, method, options);\n };\n }\n\n // Otherwise = nested path segment.\n return createRecursiveProxy(config, [...segments, prop]);\n },\n\n // Trap direct function calls (e.g. client() or client.path())\n apply(_target, _thisArg, args) {\n return callable(args[0]);\n },\n });\n}\n","const STREAMING_CONTENT_TYPES = new Set([\n 'text/event-stream',\n 'application/x-ndjson',\n 'application/ndjson',\n]);\n\n/**\n * Parses ordinary client responses as JSON while preserving streaming bodies.\n */\nexport async function parseClientResponse(response: Response, raw = false): Promise<unknown> {\n const contentType = response.headers.get('Content-Type')?.split(';', 1)[0].trim().toLowerCase();\n\n if (raw || (contentType && STREAMING_CONTENT_TYPES.has(contentType))) {\n return response;\n }\n\n return response.json();\n}\n","/**\n * @fileoverview HTTP client for @fresho/router.\n *\n * Provides a typed HTTP client using type-only imports.\n * URLs are built from property access chains:\n * - Property names = path segments (including `get`, `post`, etc.)\n * - `$param` = dynamic segment (substituted from path options)\n * - `$get()`, `$post()`, etc. = HTTP method execution\n * - Direct call `()` = implicit GET\n *\n * The `$` prefix distinguishes HTTP method execution from path navigation,\n * allowing routes with path segments named after HTTP methods (e.g., `/api/get`).\n *\n * @example\n * ```typescript\n * // Type-only import - no server code in bundle!\n * import type { api } from './server/api.js';\n * import { createHttpClient } from '@fresho/router';\n *\n * const client = createHttpClient<typeof api>({\n * baseUrl: 'https://api.example.com',\n * });\n *\n * // URLs from property chains:\n * await client.health(); // GET /health (implicit)\n * await client.users.$get(); // GET /users (explicit)\n * await client.users.$post({ body: {...} }); // POST /users\n * await client.users.$id({ path: { id: '123' } }); // GET /users/123\n *\n * // Navigate to path segments named after HTTP methods:\n * await client.api.get.$get(); // GET /api/get\n * await client.resources.delete.$get(); // GET /resources/delete\n * ```\n */\n\nimport { createRecursiveProxy } from './client-proxy.js';\nimport { parseClientResponse } from './client-response.js';\nimport type { HeaderValue, RequestOptions, RouterClient } from './client-types.js';\nimport type { Method, Router, RouterRoutes } from './types.js';\n\n// =============================================================================\n// Configuration Types\n// =============================================================================\n\n/** HTTP client configuration. */\nexport interface HttpClientConfig {\n baseUrl?: string;\n headers?: Record<string, HeaderValue>;\n credentials?: RequestCredentials;\n /** Custom fetch implementation for interception or environment-specific behavior. */\n fetch?: typeof fetch;\n}\n\n/** Extra options for HTTP requests (headers). */\nexport interface HttpExtraOptions {\n headers?: HeadersInit;\n /** If true, returns the raw Response object instead of parsing as JSON. */\n raw?: boolean;\n}\n\n/** Options for an HTTP request. */\nexport type HttpRequestOptions = RequestOptions<HttpExtraOptions>;\n\n// =============================================================================\n// Client Type Construction\n// =============================================================================\n\n/** Top-level HTTP client type. */\nexport type HttpClient<T extends Router<RouterRoutes>> = {\n configure(config: HttpClientConfig): void;\n} & RouterClient<T['routes'], HttpExtraOptions>;\n\n// =============================================================================\n// Implementation\n// =============================================================================\n\ninterface SharedConfig {\n current: HttpClientConfig;\n}\n\nconst BODY_METHODS = new Set(['post', 'put', 'patch']);\n\n/**\n * Creates a typed HTTP client.\n *\n * HTTP methods are prefixed with `$` to distinguish them from path segments:\n * - `.$get()`, `.$post()`, `.$put()`, `.$patch()`, `.$delete()` - execute HTTP methods\n * - `.propertyName` - navigate to path segment (works for any name including `get`, `post`, etc.)\n * - Direct call `()` - implicit GET request\n *\n * @example\n * ```typescript\n * import type { api } from './server';\n * import { createHttpClient } from '@fresho/router';\n *\n * const client = createHttpClient<typeof api>({\n * baseUrl: 'https://api.example.com',\n * headers: { Authorization: () => `Bearer ${getToken()}` },\n * });\n *\n * // GET /health (implicit)\n * await client.health();\n *\n * // GET /users (explicit)\n * await client.users.$get();\n *\n * // POST /users\n * await client.users.$post({ body: { name: 'Alice' } });\n *\n * // GET /users/123\n * await client.users.$id({ path: { id: '123' } });\n *\n * // Navigate through path segments named after HTTP methods:\n * // GET /api/get\n * await client.api.get.$get();\n * ```\n *\n * @example Router built by a dependency-injected factory:\n * ```typescript\n * import type { createServer } from './server';\n * import { createHttpClient } from '@fresho/router';\n *\n * type Api = ReturnType<typeof createServer>['api'];\n *\n * const client = createHttpClient<Api>({\n * baseUrl: 'https://api.example.com',\n * });\n * ```\n */\nexport function createHttpClient<T extends Router<RouterRoutes>>(\n config: HttpClientConfig = {},\n): HttpClient<T> {\n const sharedConfig: SharedConfig = { current: { ...config } };\n\n const client = {\n configure(newConfig: HttpClientConfig) {\n Object.assign(sharedConfig.current, newConfig);\n },\n } as HttpClient<T>;\n\n const proxy = createRecursiveProxy({\n onRequest: (segments, method, options) => {\n return executeRequest(\n sharedConfig,\n segments,\n method as Method,\n options as HttpRequestOptions,\n );\n },\n onBuildUrl: (segments, options) =>\n buildUrl(sharedConfig.current, segments, options as HttpRequestOptions | undefined),\n });\n\n return new Proxy(client, {\n get(target, prop) {\n if (prop === 'configure') return target.configure;\n // Delegate to recursive proxy for path building\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (proxy as any)[prop];\n },\n apply(_target, _thisArg, args) {\n // Direct call on root = GET /\n return executeRequest(sharedConfig, [], 'get', args[0] as HttpRequestOptions | undefined);\n },\n }) as HttpClient<T>;\n}\n\n/** Builds a URL path from segments, substituting $param with values. */\nfunction buildPath(segments: string[], pathParams?: Record<string, string>): string {\n const parts: string[] = [];\n\n for (const segment of segments) {\n if (segment.startsWith('$')) {\n const paramName = segment.slice(1);\n const value = pathParams?.[paramName];\n if (!value) {\n throw new Error(`Missing path parameter: ${paramName}`);\n }\n parts.push(encodeURIComponent(value));\n } else {\n parts.push(segment);\n }\n }\n\n return `/${parts.join('/')}`;\n}\n\n/**\n * Builds a URL string from path segments and options without executing a request.\n *\n * Returns an absolute URL when a `baseUrl` is configured, otherwise a relative\n * `pathname + search` string suitable for same-origin fetches.\n */\nfunction buildUrl(\n config: HttpClientConfig,\n segments: string[],\n options?: HttpRequestOptions,\n): string {\n const path = buildPath(segments, options?.path);\n\n // Resolve the base, falling back to the browser origin when available.\n const baseUrl = config.baseUrl || (typeof window !== 'undefined' ? window.location?.origin : '');\n const url = new URL(path, baseUrl || 'http://localhost');\n\n // Add query params, skipping undefined values.\n if (options?.query) {\n for (const [key, value] of Object.entries(options.query)) {\n if (value !== undefined) {\n url.searchParams.set(key, String(value));\n }\n }\n }\n\n // Use an absolute URL only when a baseUrl was configured.\n return config.baseUrl ? url.toString() : url.pathname + url.search;\n}\n\n/** Executes an HTTP request. */\nasync function executeRequest(\n sharedConfig: SharedConfig,\n segments: string[],\n method: Method,\n options?: HttpRequestOptions,\n): Promise<unknown> {\n const config = sharedConfig.current;\n\n // Build headers.\n const headers = new Headers();\n if (config.headers) {\n for (const [key, value] of Object.entries(config.headers)) {\n const resolved = typeof value === 'function' ? await value() : value;\n if (resolved != null) {\n headers.set(key, resolved);\n }\n }\n }\n if (options?.headers) {\n new Headers(options.headers).forEach((v, k) => headers.set(k, v));\n }\n\n // Build request.\n const init: RequestInit = {\n method: method.toUpperCase(),\n headers,\n credentials: config.credentials,\n };\n\n // Add body.\n if (options?.body && BODY_METHODS.has(method)) {\n headers.set('Content-Type', 'application/json');\n init.body = JSON.stringify(options.body);\n }\n\n // Execute.\n const fetchUrl = buildUrl(config, segments, options);\n const fetchFn = config.fetch || fetch;\n const response = await fetchFn(fetchUrl, init);\n\n if (!response.ok) {\n throw new Error((await response.text()) || response.statusText);\n }\n\n return parseClientResponse(response, options?.raw);\n}\n","/**\n * @fileoverview Local client for @fresho/router.\n *\n * Provides a typed client that invokes route handlers directly without HTTP.\n * Uses the same API as createHttpClient for consistency.\n *\n * @example\n * ```typescript\n * import { createLocalClient } from '@fresho/router';\n * import { api } from './api.js';\n *\n * const client = createLocalClient(api);\n *\n * // Same API as HTTP client\n * await client.health();\n * await client.users();\n * await client.users.post({ body: { name: 'Alice' } });\n * await client.users.$id({ path: { id: '123' } });\n * ```\n */\n\nimport { createRecursiveProxy } from './client-proxy.js';\nimport { parseClientResponse } from './client-response.js';\nimport type { RequestOptions, RouterClient } from './client-types.js';\nimport { compileSchema } from './schema.js';\nimport type { ExecutionContext, RouteDefinition, Router, RouterRoutes } from './types.js';\nimport { isFunction, isRoute, isRouter } from './types.js';\n\n// =============================================================================\n// Configuration Types\n// =============================================================================\n\n/** Local client configuration. */\nexport interface LocalClientConfig {\n env?: unknown;\n ctx?: ExecutionContext;\n}\n\n/** Options for a local client request. */\nexport type LocalRequestOptions = RequestOptions<LocalClientConfig>;\n\n// =============================================================================\n// Client Type Construction (mirrors http-client types)\n// =============================================================================\n\nexport type LocalClient<T extends Router<RouterRoutes>> = {\n configure(config: LocalClientConfig): void;\n} & RouterClient<T['routes'], LocalClientConfig>;\n\n// =============================================================================\n// Implementation\n// =============================================================================\n\ninterface SharedConfig {\n current: LocalClientConfig;\n}\n\ninterface RouteInfo {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n handler: (context: any) => unknown;\n querySchema?: ReturnType<typeof compileSchema>;\n bodySchema?: ReturnType<typeof compileSchema>;\n}\n\n/**\n * Finds a method handler in a router tree.\n */\nfunction findHandler(\n routerDef: Router<RouterRoutes>,\n segments: string[],\n method: string,\n): RouteInfo | null {\n let current: Router<RouterRoutes> | undefined = routerDef;\n\n // Navigate through path segments.\n for (const segment of segments) {\n if (!current) return null;\n\n const entry: unknown = current.routes[segment];\n if (isRouter(entry)) {\n current = entry;\n } else {\n return null;\n }\n }\n\n if (!current) return null;\n\n // Find the method handler.\n const entry = current.routes[method];\n if (!entry) return null;\n\n if (isFunction(entry)) {\n return { handler: entry };\n }\n\n if (isRoute(entry)) {\n const routeDef = entry as RouteDefinition;\n return {\n handler: routeDef.handler,\n querySchema: routeDef.query ? compileSchema(routeDef.query) : undefined,\n bodySchema: routeDef.body ? compileSchema(routeDef.body) : undefined,\n };\n }\n\n return null;\n}\n\n/**\n * Collects path parameters from segments.\n */\nfunction collectPathParams(\n segments: string[],\n pathValues?: Record<string, string>,\n): Record<string, string> {\n const params: Record<string, string> = {};\n\n for (const segment of segments) {\n if (segment.startsWith('$')) {\n const paramName = segment.slice(1);\n const value = pathValues?.[paramName];\n if (!value) {\n throw new Error(`Missing path parameter: ${paramName}`);\n }\n params[paramName] = value;\n }\n }\n\n return params;\n}\n\n/**\n * Creates a typed local client from a router definition.\n *\n * @example\n * ```typescript\n * import { createLocalClient } from '@fresho/router';\n * import { api } from './api.js';\n *\n * const client = createLocalClient(api);\n * client.configure({ env: { DB: mockDatabase } });\n *\n * await client.health();\n * await client.users();\n * await client.users.post({ body: { name: 'Alice' } });\n * await client.users.$id({ path: { id: '123' } });\n * ```\n */\nexport function createLocalClient<T extends Router<RouterRoutes>>(routerDef: T): LocalClient<T> {\n const sharedConfig: SharedConfig = { current: {} };\n\n const client = {\n configure(config: LocalClientConfig) {\n Object.assign(sharedConfig.current, config);\n },\n } as LocalClient<T>;\n\n const proxy = createRecursiveProxy({\n onRequest: (segments, method, options) => {\n return invokeHandler(\n sharedConfig,\n routerDef,\n segments,\n method,\n options as LocalRequestOptions | undefined,\n );\n },\n onBuildUrl: (segments, options) =>\n buildLocalUrl(segments, options as LocalRequestOptions | undefined),\n });\n\n return new Proxy(client, {\n get(target, prop) {\n if (prop === 'configure') return target.configure;\n // Delegate to recursive proxy for path building\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (proxy as any)[prop];\n },\n apply(_target, _thisArg, args) {\n return invokeHandler(\n sharedConfig,\n routerDef,\n [],\n 'get',\n args[0] as LocalRequestOptions | undefined,\n );\n },\n }) as LocalClient<T>;\n}\n\n/**\n * Builds a relative URL string from path segments and options.\n *\n * The local client has no baseUrl, so it returns a relative `pathname + search`\n * string. Mirrors the synthetic URL construction used in {@link invokeHandler}.\n */\nfunction buildLocalUrl(segments: string[], options?: LocalRequestOptions): string {\n const pathParams = collectPathParams(segments, options?.path);\n\n // Substitute $param segments with their encoded values.\n const pathParts = segments.map((s) =>\n s.startsWith('$') ? encodeURIComponent(pathParams[s.slice(1)]) : s,\n );\n const url = new URL(`/${pathParts.join('/')}`, 'http://localhost');\n\n // Add query params, skipping undefined values.\n if (options?.query) {\n for (const [key, value] of Object.entries(options.query)) {\n if (value !== undefined) {\n url.searchParams.set(key, String(value));\n }\n }\n }\n\n return url.pathname + url.search;\n}\n\n/** Invokes a handler directly. */\nasync function invokeHandler(\n sharedConfig: SharedConfig,\n routerDef: Router<RouterRoutes>,\n segments: string[],\n method: string,\n options?: LocalRequestOptions,\n): Promise<unknown> {\n const config = sharedConfig.current;\n const routeInfo = findHandler(routerDef, segments, method);\n\n if (!routeInfo) {\n throw new Error(`No handler found for ${method.toUpperCase()} /${segments.join('/')}`);\n }\n\n // Collect path params.\n const pathParams = collectPathParams(segments, options?.path);\n\n // Validate query.\n let query: unknown = {};\n if (routeInfo.querySchema) {\n const result = routeInfo.querySchema.safeParse(options?.query ?? {});\n if (!result.success) {\n throw new Error(`Invalid query parameters: ${JSON.stringify(result.error.flatten())}`);\n }\n query = result.data;\n }\n\n // Validate body.\n let body: unknown = {};\n if (routeInfo.bodySchema) {\n const result = routeInfo.bodySchema.safeParse((options?.body ?? {}) as object);\n if (!result.success) {\n throw new Error(`Invalid request body: ${JSON.stringify(result.error.flatten())}`);\n }\n body = result.data;\n }\n\n // Build path for synthetic request URL.\n const pathParts = segments.map((s) =>\n s.startsWith('$') ? encodeURIComponent(pathParams[s.slice(1)] || '') : s,\n );\n const urlPath = `/${pathParts.join('/')}`;\n const url = new URL(urlPath, 'http://localhost');\n if (options?.query) {\n for (const [key, value] of Object.entries(options.query)) {\n if (value !== undefined) {\n url.searchParams.set(key, String(value));\n }\n }\n }\n\n // Build request.\n const requestInit: RequestInit = {\n method: method.toUpperCase(),\n };\n if (options?.body && ['post', 'put', 'patch'].includes(method)) {\n requestInit.headers = { 'Content-Type': 'application/json' };\n requestInit.body = JSON.stringify(options.body);\n }\n\n const request = new Request(url.toString(), requestInit);\n\n // Build context.\n const context = {\n request,\n path: pathParams,\n query,\n body,\n env: options?.env ?? config.env,\n executionCtx: options?.ctx ?? config.ctx,\n };\n\n // Call handler.\n const result = await routeInfo.handler(context);\n\n // Parse response if needed.\n if (result instanceof Response) {\n return parseClientResponse(result);\n }\n\n return result;\n}\n","/**\n * @fileoverview Streaming response utilities for @fresho/router.\n *\n * Provides helpers for Server-Sent Events (SSE) and newline-delimited JSON (NDJSON)\n * streaming responses. These are useful for real-time updates, progress indicators,\n * and streaming large datasets.\n *\n * Available utilities:\n * - {@link sseResponse} - Server-Sent Events for real-time browser updates\n * - {@link streamJsonLines} - NDJSON for streaming JSON objects line by line\n *\n * @example\n * ```typescript\n * import { router, sseResponse, streamJsonLines } from '@fresho/router';\n *\n * interface Events {\n * tick: { count: number };\n * }\n *\n * const api = router({\n * // SSE for real-time updates\n * events: router({\n * get: async () => sseResponse<Events>(async (send, close) => {\n * for (let i = 0; i < 10; i++) {\n * send({ event: 'tick', data: { count: i } });\n * await sleep(1000);\n * }\n * close();\n * }),\n * }),\n *\n * // NDJSON for streaming data\n * export: router({\n * get: async () => streamJsonLines(async (send, close) => {\n * for await (const row of database.stream()) {\n * send(row);\n * }\n * close();\n * }),\n * }),\n * });\n * ```\n */\n\n/**\n * Options for SSE response.\n */\nexport interface SSEOptions {\n /** Custom headers to include in the response. */\n headers?: HeadersInit;\n /** Interval in milliseconds to send keep-alive comments (default: 30000). */\n keepAliveInterval?: number;\n}\n\n/**\n * Data supported by an SSE message.\n */\nexport type SSEData = string | object;\n\n/**\n * Untyped map of SSE event names to their payloads.\n *\n * Define a narrower map and pass it to {@link sseResponse} to type-check event\n * names and their corresponding data.\n */\nexport type SSEEventMap = Record<string, SSEData>;\n\ntype ValidSSEEventMap<Events> = {\n [Name in keyof Events]: SSEData;\n};\n\ninterface SSEMessageMetadata {\n /** Event ID (optional). */\n id?: string;\n /** Retry interval hint for client (optional). */\n retry?: number;\n}\n\n/**\n * Server-Sent Event message structure without a typed event map.\n */\nexport interface SSEMessage extends SSEMessageMetadata {\n /** Event type (optional). */\n event?: string;\n /** Event data. */\n data: SSEData;\n}\n\ntype NamedSSEMessage<Events> = {\n [Name in Exclude<keyof Events & string, 'message'>]: {\n event: Name;\n data: Events[Name];\n };\n}[Exclude<keyof Events & string, 'message'>];\n\ntype DefaultSSEMessage<Events> = 'message' extends keyof Events\n ? {\n /** Omit the event name to dispatch the default `message` event. */\n event?: 'message';\n data: Events['message'];\n }\n : never;\n\n/**\n * Server-Sent Event message structure.\n *\n * For a typed event map, each event name is coupled to its payload type. Use\n * the reserved `message` key to type messages that omit the `event` field.\n */\nexport type SSEEventMessage<Events extends ValidSSEEventMap<Events>> = (string extends keyof Events\n ? SSEMessage\n : NamedSSEMessage<Events> | DefaultSSEMessage<Events>) &\n SSEMessageMetadata;\n\ndeclare const SSE_EVENTS: unique symbol;\n\n/**\n * Response carrying its SSE event map at the type level.\n */\nexport type SSEResponse<Events extends ValidSSEEventMap<Events> = SSEEventMap> = Response & {\n readonly [SSE_EVENTS]: Events;\n};\n\n/**\n * Extracts the event map carried by an SSE response or typed client method.\n *\n * @example\n * ```typescript\n * type Events = SSEEventsOf<ReturnType<typeof client.events>>;\n * ```\n */\nexport type SSEEventsOf<T> = Awaited<T> extends SSEResponse<infer Events> ? Events : never;\n\n/**\n * Formats an SSE message for transmission.\n */\nfunction formatSSEMessage(message: SSEMessage): string {\n const lines: string[] = [];\n\n if (message.event) {\n lines.push(`event: ${message.event}`);\n }\n\n if (message.id) {\n lines.push(`id: ${message.id}`);\n }\n\n if (message.retry !== undefined) {\n lines.push(`retry: ${message.retry}`);\n }\n\n // Data can be a string or object (will be JSON stringified).\n const data = typeof message.data === 'string' ? message.data : JSON.stringify(message.data);\n\n // Split data by newlines and prefix each line with 'data: '.\n for (const line of data.split('\\n')) {\n lines.push(`data: ${line}`);\n }\n\n return `${lines.join('\\n')}\\n\\n`;\n}\n\n/**\n * Creates a Server-Sent Events (SSE) response.\n *\n * @example\n * ```typescript\n * interface CounterEvents {\n * tick: { count: number };\n * }\n *\n * const handler = async (c) => {\n * return sseResponse<CounterEvents>(async (send, close) => {\n * for (let i = 0; i < 5; i++) {\n * send({ event: 'tick', data: { count: i } });\n * await new Promise(r => setTimeout(r, 1000));\n * }\n * close();\n * });\n * };\n * ```\n */\nexport function sseResponse<Events extends ValidSSEEventMap<Events> = SSEEventMap>(\n handler: (\n send: (message: SSEEventMessage<Events>) => void,\n close: () => void,\n ) => void | Promise<void>,\n options: SSEOptions = {},\n): SSEResponse<Events> {\n const encoder = new TextEncoder();\n let isClosed = false;\n\n const stream = new ReadableStream({\n async start(controller) {\n // Send function for the handler.\n const send = (message: SSEEventMessage<Events>) => {\n if (!isClosed) {\n controller.enqueue(encoder.encode(formatSSEMessage(message)));\n }\n };\n\n // Close function for the handler.\n const close = () => {\n if (!isClosed) {\n isClosed = true;\n controller.close();\n }\n };\n\n // Optional keep-alive interval.\n const keepAliveInterval = options.keepAliveInterval ?? 30_000;\n let keepAliveTimer: ReturnType<typeof setInterval> | undefined;\n\n if (keepAliveInterval > 0) {\n keepAliveTimer = setInterval(() => {\n if (!isClosed) {\n // Send a comment as keep-alive.\n controller.enqueue(encoder.encode(': keep-alive\\n\\n'));\n }\n }, keepAliveInterval);\n }\n\n try {\n await handler(send, close);\n } finally {\n if (keepAliveTimer) {\n clearInterval(keepAliveTimer);\n }\n if (!isClosed) {\n controller.close();\n }\n }\n },\n });\n\n const headers = new Headers(options.headers);\n headers.set('Content-Type', 'text/event-stream');\n headers.set('Cache-Control', 'no-cache');\n headers.set('Connection', 'keep-alive');\n\n return new Response(stream, { headers }) as SSEResponse<Events>;\n}\n\n/**\n * Creates a streaming JSON response where each line is a JSON object.\n *\n * Useful for streaming large datasets or real-time data where each item\n * can be processed as it arrives (NDJSON format).\n *\n * @example\n * ```typescript\n * const handler = async (c) => {\n * return streamJsonLines(async (send, close) => {\n * for (const item of largeDataset) {\n * await send(item);\n * }\n * close();\n * });\n * };\n * ```\n */\nexport function streamJsonLines(\n handler: (send: (data: object) => void, close: () => void) => void | Promise<void>,\n options: { headers?: HeadersInit } = {},\n): Response {\n const encoder = new TextEncoder();\n let isClosed = false;\n\n const stream = new ReadableStream({\n async start(controller) {\n const send = (data: object) => {\n if (!isClosed) {\n controller.enqueue(encoder.encode(`${JSON.stringify(data)}\\n`));\n }\n };\n\n const close = () => {\n if (!isClosed) {\n isClosed = true;\n controller.close();\n }\n };\n\n try {\n await handler(send, close);\n } finally {\n if (!isClosed) {\n controller.close();\n }\n }\n },\n });\n\n const headers = new Headers(options.headers);\n headers.set('Content-Type', 'application/x-ndjson');\n\n return new Response(stream, { headers });\n}\n"],"mappings":";;;;AA6HA,MAAM,kBAAkB;CAAC;CAAU;CAAU;CAAW;CAAU;;AAGlE,SAAS,eAAe,OAAiE;AACvF,QAAO,OAAO,UAAU,YAAY,UAAU;;;;;;AAOhD,SAAS,kBAAkB,OAAgB,UAAqD;AAC9F,SAAQ,UAAR;EACE,KAAK,SACH,QAAO;GAAC;GAAM,OAAO,MAAM;GAAE;GAAK;EAEpC,KAAK,UAAU;GACb,MAAM,MAAM,OAAO,MAAM;AACzB,OAAI,OAAO,MAAM,IAAI,CACnB,QAAO;IAAC;IAAO;IAAW;IAAkB;AAE9C,UAAO;IAAC;IAAM;IAAK;IAAK;;EAG1B,KAAK;AACH,OAAI,UAAU,UAAU,UAAU,OAAO,UAAU,KACjD,QAAO;IAAC;IAAM;IAAM;IAAK;YAChB,UAAU,WAAW,UAAU,OAAO,UAAU,MACzD,QAAO;IAAC;IAAM;IAAO;IAAK;AAE5B,UAAO;IAAC;IAAO;IAAW;IAAgC;EAG5D,KAAK,UAEH,QAAO;GAAC;GAAM;GAAO;GAAK;EAE5B,QACE,QAAO;G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;AAqB1C,SAAgB,gBACd,SACA,UAAqC,EAAE,EAC7B;CACV,MAAM,UAAU,IAAI,aAAa;CACjC,IAAI,WAAW;CAEf,MAAM,SAAS,IAAI,eAAe,EAChC,MAAM,MAAM,YAAY;EACtB,MAAM,QAAQ,SAAiB;AAC7B,OAAI,CAAC,SACH,YAAW,QAAQ,QAAQ,OAAO,GAAG,KAAK,UAAU,KAAK,CAAC,IAAI,CAAC;;EAInE,MAAM,cAAc;AAClB,OAAI,CAAC,UAAU;AACb,eAAW;AACX,eAAW,OAAO;;;AAItB,MAAI;AACF,SAAM,QAAQ,MAAM,MAAM;YAClB;AACR,OAAI,CAAC,SACH,YAAW,OAAO;;IAIzB,CAAC;CAEF,MAAM,UAAU,IAAI,QAAQ,QAAQ,QAAQ;AAC5C,SAAQ,IAAI,gBAAgB,uBAAuB;AAEnD,QAAO,IAAI,SAAS,QAAQ,EAAE,SAAS,CAAC"}
|
|
@@ -267,6 +267,55 @@ interface ContentTypeOptions {
|
|
|
267
267
|
*/
|
|
268
268
|
declare function contentType(options: ContentTypeOptions): Middleware;
|
|
269
269
|
//#endregion
|
|
270
|
+
//#region src/middleware/cookies.d.ts
|
|
271
|
+
/** Options for serializing a cookie into a `Set-Cookie` header value. */
|
|
272
|
+
interface CookieOptions {
|
|
273
|
+
/** Lifetime in seconds, serialized as `Max-Age`. */
|
|
274
|
+
maxAge?: number;
|
|
275
|
+
/** Absolute expiry, serialized as `Expires`. */
|
|
276
|
+
expires?: Date;
|
|
277
|
+
/** Restricts the cookie to a path prefix. */
|
|
278
|
+
path?: string;
|
|
279
|
+
/** Restricts the cookie to a domain. */
|
|
280
|
+
domain?: string;
|
|
281
|
+
/** Only send the cookie over HTTPS. */
|
|
282
|
+
secure?: boolean;
|
|
283
|
+
/** Hide the cookie from client-side JavaScript. */
|
|
284
|
+
httpOnly?: boolean;
|
|
285
|
+
/** Cross-site sending policy. */
|
|
286
|
+
sameSite?: 'strict' | 'lax' | 'none';
|
|
287
|
+
}
|
|
288
|
+
/** Helper installed on the context to queue a cookie for the response. */
|
|
289
|
+
type SetCookie = (name: string, value: string, options?: CookieOptions) => void;
|
|
290
|
+
/**
|
|
291
|
+
* Parses a `Cookie` request header into a plain map of name to value.
|
|
292
|
+
*
|
|
293
|
+
* Returns an empty object for a missing or empty header. When a name appears
|
|
294
|
+
* more than once the first value wins, matching the common `cookie` package.
|
|
295
|
+
*/
|
|
296
|
+
declare function parseCookies(header: string | null): Record<string, string>;
|
|
297
|
+
/**
|
|
298
|
+
* Serializes a cookie into a `Set-Cookie` header value per RFC 6265.
|
|
299
|
+
*
|
|
300
|
+
* The value is URL-encoded; attributes are appended in a stable order.
|
|
301
|
+
*/
|
|
302
|
+
declare function serializeCookie(name: string, value: string, options?: CookieOptions): string;
|
|
303
|
+
/**
|
|
304
|
+
* Creates a middleware that parses request cookies and enables setting them.
|
|
305
|
+
*
|
|
306
|
+
* Merges the parsed cookies into `context.cookies` and installs a
|
|
307
|
+
* `context.setCookie(name, value, options)` helper. Each `setCookie` call adds
|
|
308
|
+
* a separate `Set-Cookie` header to the response (append, not overwrite), so a
|
|
309
|
+
* handler may set multiple cookies.
|
|
310
|
+
*
|
|
311
|
+
* @example
|
|
312
|
+
* ```typescript
|
|
313
|
+
* const api = router('/api', routes, cookies());
|
|
314
|
+
* // in a handler: c.cookies['session']; c.setCookie('session', id, { httpOnly: true });
|
|
315
|
+
* ```
|
|
316
|
+
*/
|
|
317
|
+
declare function cookies(): Middleware;
|
|
318
|
+
//#endregion
|
|
270
319
|
//#region src/middleware/cors.d.ts
|
|
271
320
|
/** CORS middleware configuration options. */
|
|
272
321
|
interface CorsOptions {
|
|
@@ -295,5 +344,5 @@ interface CorsOptions {
|
|
|
295
344
|
*/
|
|
296
345
|
declare function cors(options?: CorsOptions): Middleware;
|
|
297
346
|
//#endregion
|
|
298
|
-
export { type BasicAuthOptions, type BearerAuthOptions, type ContentTypeOptions, type CorsOptions, type ErrorHandlerOptions, HttpError, type JwtAlgorithm, type JwtAuthOptions, type JwtPayload, type LogInfo, type LoggerOptions, MemoryRateLimitStore, type RateLimitOptions, type RateLimitStore, type RequestIdOptions, type SignJwtOptions, type TimeoutOptions, type VerifyJwtOptions, basicAuth, bearerAuth, compose, contentType, cors, errorHandler, jwtAuth, jwtSign, jwtVerify, logger, rateLimit, requestId, timeout };
|
|
347
|
+
export { type BasicAuthOptions, type BearerAuthOptions, type ContentTypeOptions, type CookieOptions, type CorsOptions, type ErrorHandlerOptions, HttpError, type JwtAlgorithm, type JwtAuthOptions, type JwtPayload, type LogInfo, type LoggerOptions, MemoryRateLimitStore, type RateLimitOptions, type RateLimitStore, type RequestIdOptions, type SetCookie, type SignJwtOptions, type TimeoutOptions, type VerifyJwtOptions, basicAuth, bearerAuth, compose, contentType, cookies, cors, errorHandler, jwtAuth, jwtSign, jwtVerify, logger, parseCookies, rateLimit, requestId, serializeCookie, timeout };
|
|
299
348
|
//# sourceMappingURL=index.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/middleware/auth.ts","../../src/middleware/common.ts","../../src/middleware/cors.ts"],"sourcesContent":[],"mappings":";;;;;AAwDA;AA6CiB,UAzEA,gBAAA,CAyEc;EAErB;EAAyC,KAAA,CAAA,EAAA,MAAA;EAAlB;EAA2B,MAAA,EAAA,CAAA,QAAA,EAAA,MAAA,EAAA,QAAA,EAAA,MAAA,EAAA,OAAA,EApE/C,iBAoE+C,EAAA,GAnErD,OAmEqD,CAnE7C,MAmE6C,CAAA,MAAA,EAAA,OAAA,CAAA,GAAA,IAAA,CAAA,GAnEX,MAmEW,CAAA,MAAA,EAAA,OAAA,CAAA,GAAA,IAAA;;;;;;AAqC5D;;;;;;AA6DA;;;;;;AAyBA;iBA1KgB,SAAA,UAAmB,mBAAmB;;UA6CrC;ECpEJ;EA8BI,MAAA,EDwCP,SCxCO,GAAA,CAAA,CAAmB,OAAA,EDwCH,iBCxCG,CDwCe,GCxCf,CAAA,EAAA,GDwCwB,SCxCxB,CAAA;EAEpB;;;;EAIsB,MAAA,EAAA,CAAA,OAAA,EDuClB,UCvCkB,EAAA,GDuCH,MCvCG,CAAA,MAAA,EAAA,OAAA,CAAA,GAAA,IAAA;EAAsB;EAAmB,UAAA,CAAA,EDyChE,YCzCgE,EAAA;EAAR;EAAO,QAAA,CAAA,EAAA,CAAA,OAAA,ED2CvD,OC3CuD,EAAA,GAAA,MAAA,GAAA,IAAA;AAW9E;AA4CA;AAYA;AAkBA;AA2EA;;;;;AAOA;;;;;;AA8DA;;;;;;;;AAyBA;AAiEA;AAeA;AAkCiB,iBDzSD,OCySe,CAAA,MAAA,CAAA,CAAA,CAAA,CAAA,OAAA,EDzSY,cCySZ,CDzS2B,GCyS3B,CAAA,CAAA,EDzSkC,UCySlC,CDzS6C,GCyS7C,CAAA;AAe/B;AAiCiB,UD5RA,iBAAA,CC4RkB;EAiBnB;mCDzSH,sBACN,QAAQ,kCAAkC;;;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/middleware/auth.ts","../../src/middleware/common.ts","../../src/middleware/cookies.ts","../../src/middleware/cors.ts"],"sourcesContent":[],"mappings":";;;;;AAwDA;AA6CiB,UAzEA,gBAAA,CAyEc;EAErB;EAAyC,KAAA,CAAA,EAAA,MAAA;EAAlB;EAA2B,MAAA,EAAA,CAAA,QAAA,EAAA,MAAA,EAAA,QAAA,EAAA,MAAA,EAAA,OAAA,EApE/C,iBAoE+C,EAAA,GAnErD,OAmEqD,CAnE7C,MAmE6C,CAAA,MAAA,EAAA,OAAA,CAAA,GAAA,IAAA,CAAA,GAnEX,MAmEW,CAAA,MAAA,EAAA,OAAA,CAAA,GAAA,IAAA;;;;;;AAqC5D;;;;;;AA6DA;;;;;;AAyBA;iBA1KgB,SAAA,UAAmB,mBAAmB;;UA6CrC;ECpEJ;EA8BI,MAAA,EDwCP,SCxCO,GAAA,CAAA,CAAmB,OAAA,EDwCH,iBCxCG,CDwCe,GCx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OAAA,CAAA,EG1InB,WH0ImB,CAAA,EG1IA,UH0IA"}
|
|
@@ -437,6 +437,87 @@ function contentType(options) {
|
|
|
437
437
|
};
|
|
438
438
|
}
|
|
439
439
|
|
|
440
|
+
//#endregion
|
|
441
|
+
//#region src/middleware/cookies.ts
|
|
442
|
+
/**
|
|
443
|
+
* Decodes a cookie value, falling back to the raw value if it is malformed.
|
|
444
|
+
*
|
|
445
|
+
* Cookies are URL-encoded on write (see {@link serializeCookie}); decoding here
|
|
446
|
+
* keeps round-trips lossless without throwing on hand-crafted values.
|
|
447
|
+
*/
|
|
448
|
+
function tryDecode(value) {
|
|
449
|
+
try {
|
|
450
|
+
return decodeURIComponent(value);
|
|
451
|
+
} catch {
|
|
452
|
+
return value;
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
/**
|
|
456
|
+
* Parses a `Cookie` request header into a plain map of name to value.
|
|
457
|
+
*
|
|
458
|
+
* Returns an empty object for a missing or empty header. When a name appears
|
|
459
|
+
* more than once the first value wins, matching the common `cookie` package.
|
|
460
|
+
*/
|
|
461
|
+
function parseCookies(header) {
|
|
462
|
+
const cookies$1 = {};
|
|
463
|
+
if (!header) return cookies$1;
|
|
464
|
+
for (const pair of header.split(";")) {
|
|
465
|
+
const separator = pair.indexOf("=");
|
|
466
|
+
if (separator < 0) continue;
|
|
467
|
+
const name = pair.slice(0, separator).trim();
|
|
468
|
+
if (name && !(name in cookies$1)) cookies$1[name] = tryDecode(pair.slice(separator + 1).trim());
|
|
469
|
+
}
|
|
470
|
+
return cookies$1;
|
|
471
|
+
}
|
|
472
|
+
/**
|
|
473
|
+
* Serializes a cookie into a `Set-Cookie` header value per RFC 6265.
|
|
474
|
+
*
|
|
475
|
+
* The value is URL-encoded; attributes are appended in a stable order.
|
|
476
|
+
*/
|
|
477
|
+
function serializeCookie(name, value, options = {}) {
|
|
478
|
+
const parts = [`${name}=${encodeURIComponent(value)}`];
|
|
479
|
+
if (options.maxAge !== void 0) parts.push(`Max-Age=${Math.trunc(options.maxAge)}`);
|
|
480
|
+
if (options.expires) parts.push(`Expires=${options.expires.toUTCString()}`);
|
|
481
|
+
if (options.domain) parts.push(`Domain=${options.domain}`);
|
|
482
|
+
if (options.path) parts.push(`Path=${options.path}`);
|
|
483
|
+
if (options.secure) parts.push("Secure");
|
|
484
|
+
if (options.httpOnly) parts.push("HttpOnly");
|
|
485
|
+
if (options.sameSite) parts.push(`SameSite=${options.sameSite[0].toUpperCase()}${options.sameSite.slice(1)}`);
|
|
486
|
+
return parts.join("; ");
|
|
487
|
+
}
|
|
488
|
+
/**
|
|
489
|
+
* Creates a middleware that parses request cookies and enables setting them.
|
|
490
|
+
*
|
|
491
|
+
* Merges the parsed cookies into `context.cookies` and installs a
|
|
492
|
+
* `context.setCookie(name, value, options)` helper. Each `setCookie` call adds
|
|
493
|
+
* a separate `Set-Cookie` header to the response (append, not overwrite), so a
|
|
494
|
+
* handler may set multiple cookies.
|
|
495
|
+
*
|
|
496
|
+
* @example
|
|
497
|
+
* ```typescript
|
|
498
|
+
* const api = router('/api', routes, cookies());
|
|
499
|
+
* // in a handler: c.cookies['session']; c.setCookie('session', id, { httpOnly: true });
|
|
500
|
+
* ```
|
|
501
|
+
*/
|
|
502
|
+
function cookies() {
|
|
503
|
+
return async (context, next) => {
|
|
504
|
+
context.cookies = parseCookies(context.request.headers.get("Cookie"));
|
|
505
|
+
const pending = [];
|
|
506
|
+
context.setCookie = ((name, value, options) => {
|
|
507
|
+
pending.push(serializeCookie(name, value, options));
|
|
508
|
+
});
|
|
509
|
+
const response = await next();
|
|
510
|
+
if (pending.length === 0) return response;
|
|
511
|
+
const headers = new Headers(response.headers);
|
|
512
|
+
for (const cookie of pending) headers.append("Set-Cookie", cookie);
|
|
513
|
+
return new Response(response.body, {
|
|
514
|
+
status: response.status,
|
|
515
|
+
statusText: response.statusText,
|
|
516
|
+
headers
|
|
517
|
+
});
|
|
518
|
+
};
|
|
519
|
+
}
|
|
520
|
+
|
|
440
521
|
//#endregion
|
|
441
522
|
//#region src/middleware/cors.ts
|
|
442
523
|
/**
|
|
@@ -532,5 +613,5 @@ function cors(options = {}) {
|
|
|
532
613
|
}
|
|
533
614
|
|
|
534
615
|
//#endregion
|
|
535
|
-
export { HttpError, MemoryRateLimitStore, basicAuth, bearerAuth, compose, contentType, cors, errorHandler, jwtAuth, jwtSign, jwtVerify, logger, rateLimit, requestId, timeout };
|
|
616
|
+
export { HttpError, MemoryRateLimitStore, basicAuth, bearerAuth, compose, contentType, cookies, cors, errorHandler, jwtAuth, jwtSign, jwtVerify, logger, parseCookies, rateLimit, requestId, serializeCookie, timeout };
|
|
536
617
|
//# sourceMappingURL=index.mjs.map
|