@fresho/router 0.6.0 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["status: number","info: LogInfo","windowMs: number","contentType","cookies: Record<string, string>","cookies","pending: string[]","config: Required<CorsOptions>","headers: Record<string, string>","response","headers"],"sources":["../../src/middleware/auth.ts","../../src/middleware/common.ts","../../src/middleware/cookies.ts","../../src/middleware/cors.ts"],"sourcesContent":["/**\n * @fileoverview Authentication middleware for @fresho/router.\n *\n * Provides middleware wrappers for Basic HTTP, JWT, and Bearer token authentication.\n * The underlying authentication utilities are in `@fresho/router/auth`.\n */\n\nimport { parseBasicAuth } from '../auth/basic.js';\nimport { type JwtAlgorithm, type JwtPayload, type JwtSecret, jwtVerify } from '../auth/jwt.js';\nimport type { Middleware, MiddlewareContext } from '../middleware.js';\n\n// Re-export types that middleware users need\nexport type {\n Jwks,\n JwtAlgorithm,\n JwtPayload,\n JwtSecret,\n SignJwtOptions,\n VerifyJwtOptions,\n} from '../auth/jwt.js';\n\n// Re-export utilities that are commonly used alongside middleware\nexport { createJwks, jwtSign, jwtVerify } from '../auth/jwt.js';\n\n// =============================================================================\n// Basic Auth Middleware\n// =============================================================================\n\n/** Basic authentication middleware configuration. */\nexport interface BasicAuthOptions {\n /** Realm name for the authentication challenge. */\n realm?: string;\n /** Function to validate credentials. Returns claims to merge into context, or null to reject. */\n verify: (\n username: string,\n password: string,\n context: MiddlewareContext,\n ) => Promise<Record<string, unknown> | null> | Record<string, unknown> | null;\n}\n\n/**\n * Creates a Basic HTTP authentication middleware.\n *\n * @example\n * ```typescript\n * const adminRouter = router('/admin', routes,\n * basicAuth({\n * verify: async (username, password) => {\n * if (username === 'admin' && password === 'secret') {\n * return { user: { name: username } };\n * }\n * return null;\n * }\n * })\n * );\n * ```\n */\nexport function basicAuth(options: BasicAuthOptions): Middleware {\n const realm = options.realm || 'Secure Area';\n\n return async (context, next) => {\n const { request } = context;\n\n const credentials = parseBasicAuth(request.headers.get('Authorization'));\n if (!credentials) {\n return new Response('Unauthorized', {\n status: 401,\n headers: {\n 'WWW-Authenticate': `Basic realm=\"${realm}\", charset=\"UTF-8\"`,\n },\n });\n }\n\n try {\n const claims = await options.verify(credentials.username, credentials.password, context);\n if (claims === null) {\n return new Response('Invalid credentials', {\n status: 401,\n headers: {\n 'WWW-Authenticate': `Basic realm=\"${realm}\", charset=\"UTF-8\"`,\n },\n });\n }\n\n Object.assign(context, claims);\n return next();\n } catch (_error) {\n return new Response('Invalid credentials', {\n status: 401,\n headers: {\n 'WWW-Authenticate': `Basic realm=\"${realm}\", charset=\"UTF-8\"`,\n },\n });\n }\n };\n}\n\n// =============================================================================\n// JWT Auth Middleware\n// =============================================================================\n\n/** JWT authentication middleware configuration. */\nexport interface JwtAuthOptions<Ctx = {}> {\n /** Secret key or function to get the secret from context. */\n secret: JwtSecret | ((context: MiddlewareContext<Ctx>) => JwtSecret);\n /**\n * Map JWT payload to context properties. Return null to reject the token.\n * The returned object is merged into the middleware context.\n */\n claims: (payload: JwtPayload) => Record<string, unknown> | null;\n /** Allowed algorithms (default: ['HS256'] for HMAC secrets, ['RS256'] otherwise). */\n algorithms?: JwtAlgorithm[];\n /** Required issuer (`iss`). */\n issuer?: string | string[];\n /** Required audience (`aud`); the token must contain at least one of the given values. */\n audience?: string | string[];\n /** Seconds of clock skew allowed when checking `exp` and `nbf` (default: 0). */\n clockTolerance?: number;\n /** Function to extract token from request (default: Authorization header or 'token' cookie). */\n getToken?: (request: Request) => string | null;\n}\n\n/**\n * Creates a JWT authentication middleware.\n *\n * @example\n * ```typescript\n * interface AppContext {\n * env: { JWT_SECRET: string };\n * user: { id: string; email: string };\n * }\n *\n * jwtAuth<AppContext>({\n * secret: (ctx) => ctx.env.JWT_SECRET, // ctx.env is typed\n * claims: (payload) => ({\n * user: { id: payload.sub, email: payload.email },\n * }),\n * })\n *\n * // In your route handler:\n * route.ctx<AppContext>()({\n * handler: async (c) => {\n * return { email: c.user.email }; // Fully typed\n * },\n * })\n * ```\n */\nexport function jwtAuth<Ctx = {}>(options: JwtAuthOptions<Ctx>): Middleware<Ctx> {\n const getToken =\n options.getToken ||\n ((req) => {\n const auth = req.headers.get('Authorization');\n if (auth?.startsWith('Bearer ')) {\n return auth.slice(7);\n }\n // Also check for token in cookie.\n const cookie = req.headers.get('Cookie');\n if (cookie) {\n const match = cookie.match(/(?:^|;\\s*)token=([^;]*)/);\n if (match) {\n return match[1];\n }\n }\n return null;\n });\n\n return async (context, next) => {\n const { request } = context;\n\n const token = getToken(request);\n if (!token) {\n return new Response('Missing token', {\n status: 401,\n headers: { 'WWW-Authenticate': 'Bearer' },\n });\n }\n\n try {\n const secret =\n typeof options.secret === 'function' ? options.secret(context) : options.secret;\n\n const payload = await jwtVerify(token, secret, {\n algorithms: options.algorithms,\n issuer: options.issuer,\n audience: options.audience,\n clockTolerance: options.clockTolerance,\n });\n\n // Map payload to context properties.\n const claims = options.claims(payload);\n if (claims === null) {\n throw new Error('Token validation failed');\n }\n Object.assign(context, claims);\n\n return next();\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Invalid token';\n return new Response(message, {\n status: 401,\n headers: {\n // Fixed value: messages can carry token or JWKS content, unsafe in a header.\n 'WWW-Authenticate': 'Bearer error=\"invalid_token\"',\n },\n });\n }\n };\n}\n\n// =============================================================================\n// Bearer Token Auth Middleware (Simple)\n// =============================================================================\n\n/** Bearer token authentication options. */\nexport interface BearerAuthOptions {\n /** Function to validate the token. Returns claims to merge into context, or null to reject. */\n verify: (\n token: string,\n context: MiddlewareContext,\n ) => Promise<Record<string, unknown> | null> | Record<string, unknown> | null;\n}\n\n/**\n * Creates a simple bearer token authentication middleware.\n *\n * @example\n * ```typescript\n * const apiRouter = router('/api', routes,\n * bearerAuth({\n * verify: async (token) => {\n * if (token === process.env.API_TOKEN) {\n * return { apiClient: 'trusted' };\n * }\n * return null;\n * }\n * })\n * );\n * ```\n */\nexport function bearerAuth(options: BearerAuthOptions): Middleware {\n return async (context, next) => {\n const { request } = context;\n\n const authHeader = request.headers.get('Authorization');\n if (!authHeader?.startsWith('Bearer ')) {\n return new Response('Missing token', {\n status: 401,\n headers: { 'WWW-Authenticate': 'Bearer' },\n });\n }\n\n const token = authHeader.slice(7);\n const claims = await options.verify(token, context);\n\n if (claims === null) {\n return new Response('Invalid token', {\n status: 401,\n headers: { 'WWW-Authenticate': 'Bearer error=\"invalid_token\"' },\n });\n }\n\n Object.assign(context, claims);\n return next();\n };\n}\n","/**\n * @fileoverview Common middleware utilities for @fresho/router.\n *\n * Provides error handling, logging, rate limiting, and other utilities.\n */\n\nimport type { Middleware, MiddlewareContext } from '../middleware.js';\n\n// =============================================================================\n// Error Handler\n// =============================================================================\n\n/**\n * HTTP error with status code for use with errorHandler middleware.\n *\n * Throw this in route handlers to return a specific HTTP status code.\n * The errorHandler middleware will catch it and format the response.\n *\n * @example\n * ```typescript\n * import { HttpError } from '@fresho/router/middleware';\n *\n * const getUser = route({\n * method: 'get',\n * path: '/users/:id',\n * handler: async (c) => {\n * const user = await db.findUser(c.path.id);\n * if (!user) throw new HttpError('User not found', 404);\n * return user;\n * },\n * });\n * ```\n */\nexport class HttpError extends Error {\n constructor(\n message: string,\n public status: number,\n ) {\n super(message);\n this.name = 'HttpError';\n }\n}\n\n/**\n * Extracts HTTP status code from an error object.\n *\n * Supports errors with `status` or `statusCode` properties (common patterns\n * in frameworks like Express, Koa, Hono, and custom HTTP error classes).\n */\nfunction getErrorStatus(error: unknown): number {\n if (typeof error !== 'object' || error === null) {\n return 500;\n }\n if ('status' in error && typeof error.status === 'number') {\n return error.status;\n }\n if ('statusCode' in error && typeof error.statusCode === 'number') {\n return error.statusCode;\n }\n return 500;\n}\n\n/** Error handler middleware configuration. */\nexport interface ErrorHandlerOptions {\n /** Custom error logger. */\n log?: (error: Error, context: MiddlewareContext) => void | Promise<void>;\n /** Expose error details in response (dangerous in production). */\n expose?: boolean;\n /** Custom error response formatter. */\n formatter?: (error: Error, context: MiddlewareContext) => Response | Promise<Response>;\n}\n\n/**\n * Creates an error handling middleware that catches and formats errors.\n *\n * @example\n * ```typescript\n * const apiRouter = router('/api', routes, errorHandler({ expose: false }));\n * ```\n */\nexport function errorHandler(options: ErrorHandlerOptions = {}): Middleware {\n return async (context, next) => {\n try {\n return await next();\n } catch (error) {\n const err = error as Error;\n\n // Log error if logger provided\n if (options.log) {\n await options.log(err, context);\n } else {\n console.error(`Error in ${context.request.method} ${context.request.url}:`, err);\n }\n\n // Use custom formatter if provided\n if (options.formatter) {\n return await options.formatter(err, context);\n }\n\n // Default error response\n const message = options.expose ? err.message : 'Internal Server Error';\n const status = getErrorStatus(error);\n\n const errorBody = {\n error: message,\n ...(options.expose && {\n stack: err.stack,\n name: err.name,\n }),\n };\n\n return new Response(JSON.stringify(errorBody), {\n status,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n };\n}\n\n// =============================================================================\n// Logger\n// =============================================================================\n\n/** Logger middleware configuration. */\nexport interface LoggerOptions {\n /** Custom logger function. */\n log?: (message: string) => void;\n /** Include request headers in log. */\n includeHeaders?: boolean;\n /** Include request body in log. */\n includeBody?: boolean;\n /** Custom log formatter. */\n formatter?: (info: LogInfo) => string;\n}\n\n/** Information logged for each request. */\nexport interface LogInfo {\n method: string;\n url: string;\n status: number;\n duration: number;\n headers?: Record<string, string>;\n body?: unknown;\n error?: Error;\n}\n\n/**\n * Creates a request/response logging middleware.\n *\n * @example\n * ```typescript\n * const apiRouter = router('/api', routes, logger({ includeHeaders: true }));\n * ```\n */\nexport function logger(options: LoggerOptions = {}): Middleware {\n const log = options.log || console.log;\n\n return async (context, next) => {\n const { request } = context;\n const start = Date.now();\n const url = new URL(request.url);\n\n // Collect request info\n const info: LogInfo = {\n method: request.method,\n url: `${url.pathname}${url.search}`,\n status: 0,\n duration: 0,\n };\n\n if (options.includeHeaders) {\n info.headers = Object.fromEntries(request.headers.entries());\n }\n\n if (options.includeBody && request.body) {\n try {\n const clonedRequest = request.clone();\n const text = await clonedRequest.text();\n try {\n info.body = JSON.parse(text);\n } catch {\n info.body = text;\n }\n } catch {\n info.body = '[Body not readable]';\n }\n }\n\n // Log request\n const requestMessage = options.formatter\n ? options.formatter({ ...info, status: 0, duration: 0 })\n : `→ ${info.method} ${info.url}`;\n log(requestMessage);\n\n try {\n // Process request\n const response = await next();\n\n // Log response\n info.status = response.status;\n info.duration = Date.now() - start;\n\n const responseMessage = options.formatter\n ? options.formatter(info)\n : `← ${info.status} ${response.statusText || 'OK'} (${info.duration}ms)`;\n log(responseMessage);\n\n return response;\n } catch (error) {\n // Log error\n info.status = 500;\n info.duration = Date.now() - start;\n info.error = error as Error;\n\n const errorMessage = options.formatter\n ? options.formatter(info)\n : `✗ ${info.status} Error: ${(error as Error).message} (${info.duration}ms)`;\n log(errorMessage);\n\n throw error;\n }\n };\n}\n\n// =============================================================================\n// Rate Limiter\n// =============================================================================\n\n/** Rate limit store interface. */\nexport interface RateLimitStore {\n increment(key: string): Promise<number>;\n decrement(key: string): Promise<void>;\n reset(key: string): Promise<void>;\n}\n\n/** In-memory rate limit store with periodic cleanup of expired entries. */\nexport class MemoryRateLimitStore implements RateLimitStore {\n private counts = new Map<string, { count: number; resetAt: number }>();\n private lastCleanup = Date.now();\n\n /** Interval between cleanups (default: 60 seconds). */\n private readonly cleanupIntervalMs: number;\n\n constructor(\n private windowMs: number,\n options?: { cleanupIntervalMs?: number },\n ) {\n // Default cleanup interval is the window duration or 60 seconds, whichever is larger.\n this.cleanupIntervalMs = options?.cleanupIntervalMs ?? Math.max(windowMs, 60_000);\n }\n\n async increment(key: string): Promise<number> {\n const now = Date.now();\n\n // Periodic cleanup to prevent memory leaks.\n if (now - this.lastCleanup > this.cleanupIntervalMs) {\n this.cleanup(now);\n }\n\n const record = this.counts.get(key);\n\n if (!record || now > record.resetAt) {\n this.counts.set(key, { count: 1, resetAt: now + this.windowMs });\n return 1;\n }\n\n record.count++;\n return record.count;\n }\n\n async decrement(key: string): Promise<void> {\n const record = this.counts.get(key);\n if (record && record.count > 0) {\n record.count--;\n }\n }\n\n async reset(key: string): Promise<void> {\n this.counts.delete(key);\n }\n\n /** Removes all expired entries from the store. */\n private cleanup(now: number): void {\n for (const [key, record] of this.counts) {\n if (now > record.resetAt) {\n this.counts.delete(key);\n }\n }\n this.lastCleanup = now;\n }\n\n /** Returns the current number of tracked keys (useful for testing). */\n get size(): number {\n return this.counts.size;\n }\n}\n\n/** Rate limiter middleware configuration. */\nexport interface RateLimitOptions {\n /** Time window in milliseconds. */\n windowMs?: number;\n /** Maximum requests per window. */\n max?: number;\n /** Function to generate a unique key for each client. */\n keyGenerator?: (context: MiddlewareContext) => string;\n /** Store for rate limit data. */\n store?: RateLimitStore;\n /** Skip successful requests from rate limit. */\n skipSuccessfulRequests?: boolean;\n /** Skip failed requests from rate limit. */\n skipFailedRequests?: boolean;\n /** Custom handler for rate limited requests. */\n handler?: (context: MiddlewareContext) => Response | Promise<Response>;\n}\n\n/**\n * Creates a rate limiting middleware.\n *\n * @example\n * ```typescript\n * const apiRouter = router('/api', routes, rateLimit({ max: 100, windowMs: 60000 }));\n * ```\n */\nexport function rateLimit(options: RateLimitOptions = {}): Middleware {\n const config = {\n windowMs: 60 * 1000, // 1 minute\n max: 100,\n keyGenerator: (ctx: MiddlewareContext) => {\n // Use IP address as default key\n const cfIp = ctx.request.headers.get('CF-Connecting-IP');\n const xForwardedFor = ctx.request.headers.get('X-Forwarded-For');\n const xRealIp = ctx.request.headers.get('X-Real-IP');\n return cfIp || xForwardedFor?.split(',')[0] || xRealIp || 'unknown';\n },\n ...options,\n };\n\n const store = config.store || new MemoryRateLimitStore(config.windowMs);\n\n return async (context, next) => {\n const key = config.keyGenerator(context);\n const current = await store.increment(key);\n\n if (current > config.max) {\n if (config.handler) {\n return await config.handler(context);\n }\n\n return new Response('Too many requests', {\n status: 429,\n headers: {\n 'Retry-After': String(Math.ceil(config.windowMs / 1000)),\n 'X-RateLimit-Limit': String(config.max),\n 'X-RateLimit-Remaining': '0',\n 'X-RateLimit-Reset': new Date(Date.now() + config.windowMs).toISOString(),\n },\n });\n }\n\n const response = await next();\n\n // Optionally don't count successful/failed requests\n if (\n (config.skipSuccessfulRequests && response.status < 400) ||\n (config.skipFailedRequests && response.status >= 400)\n ) {\n await store.decrement(key);\n }\n\n // Add rate limit headers\n const headers = new Headers(response.headers);\n headers.set('X-RateLimit-Limit', String(config.max));\n headers.set('X-RateLimit-Remaining', String(Math.max(0, config.max - current)));\n headers.set('X-RateLimit-Reset', new Date(Date.now() + config.windowMs).toISOString());\n\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n };\n}\n\n// =============================================================================\n// Request ID\n// =============================================================================\n\n/** Request ID middleware configuration. */\nexport interface RequestIdOptions {\n /** Header name for request ID. */\n headerName?: string;\n /** Function to generate request ID. */\n generator?: () => string;\n}\n\n/**\n * Creates a middleware that adds a unique request ID to each request.\n *\n * @example\n * ```typescript\n * const apiRouter = router('/api', routes, requestId({ headerName: 'X-Request-ID' }));\n * ```\n */\nexport function requestId(options: RequestIdOptions = {}): Middleware {\n const headerName = options.headerName || 'X-Request-ID';\n const generator = options.generator || (() => crypto.randomUUID());\n\n return async (context, next) => {\n // Check if request already has an ID\n let id = context.request.headers.get(headerName);\n if (!id) {\n id = generator();\n }\n\n // Add to context\n context.requestId = id;\n\n // Process request\n const response = await next();\n\n // Add request ID to response headers\n const headers = new Headers(response.headers);\n headers.set(headerName, id);\n\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n };\n}\n\n// =============================================================================\n// Timeout\n// =============================================================================\n\n/** Timeout middleware configuration. */\nexport interface TimeoutOptions {\n /** Timeout in milliseconds. */\n timeout: number;\n /** Custom timeout response. */\n message?: string;\n}\n\n/**\n * Creates a middleware that times out requests after a specified duration.\n *\n * @example\n * ```typescript\n * const apiRouter = router('/api', routes, timeout({ timeout: 5000 }));\n * ```\n */\nexport function timeout(options: TimeoutOptions): Middleware {\n return async (context, next) => {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), options.timeout);\n\n try {\n const responsePromise = next();\n const timeoutPromise = new Promise<Response>((_, reject) => {\n controller.signal.addEventListener('abort', () => {\n reject(new Error('Request timeout'));\n });\n });\n\n const response = await Promise.race([responsePromise, timeoutPromise]);\n clearTimeout(timeoutId);\n return response;\n } catch (error) {\n clearTimeout(timeoutId);\n if ((error as Error).message === 'Request timeout') {\n return new Response(options.message || 'Request timeout', {\n status: 408,\n });\n }\n throw error;\n }\n };\n}\n\n// =============================================================================\n// Content Type Validation\n// =============================================================================\n\n/** Content type validation options. */\nexport interface ContentTypeOptions {\n /** Expected content types. */\n types: string[];\n /** Skip validation for these methods. */\n skipMethods?: string[];\n /** Custom error message. */\n message?: string;\n}\n\n/**\n * Creates a middleware that validates request content type.\n *\n * @example\n * ```typescript\n * const apiRouter = router('/api', routes, contentType({ types: ['application/json'] }));\n * ```\n */\nexport function contentType(options: ContentTypeOptions): Middleware {\n const skipMethods = new Set(\n options.skipMethods?.map((m) => m.toUpperCase()) || ['GET', 'HEAD', 'OPTIONS'],\n );\n\n return async (context, next) => {\n if (skipMethods.has(context.request.method.toUpperCase())) {\n return next();\n }\n\n const contentType = context.request.headers.get('Content-Type');\n if (!contentType) {\n return new Response(options.message || 'Missing Content-Type header', {\n status: 415,\n });\n }\n\n const matches = options.types.some((type) => contentType.includes(type));\n if (!matches) {\n return new Response(\n options.message || `Unsupported Media Type. Expected: ${options.types.join(', ')}`,\n { status: 415 },\n );\n }\n\n return next();\n };\n}\n","/**\n * @fileoverview Cookie parsing/serialization and the cookies() middleware.\n *\n * Reads the request `Cookie` header into `context.cookies` and installs a\n * `context.setCookie` helper that serializes per RFC 6265 and appends\n * `Set-Cookie` headers to the outgoing response. Dependency-free, Web APIs only.\n */\n\nimport type { Middleware } from '../middleware.js';\n\n/** Options for serializing a cookie into a `Set-Cookie` header value. */\nexport interface CookieOptions {\n /** Lifetime in seconds, serialized as `Max-Age`. */\n maxAge?: number;\n /** Absolute expiry, serialized as `Expires`. */\n expires?: Date;\n /** Restricts the cookie to a path prefix. */\n path?: string;\n /** Restricts the cookie to a domain. */\n domain?: string;\n /** Only send the cookie over HTTPS. */\n secure?: boolean;\n /** Hide the cookie from client-side JavaScript. */\n httpOnly?: boolean;\n /** Cross-site sending policy. */\n sameSite?: 'strict' | 'lax' | 'none';\n}\n\n/** Helper installed on the context to queue a cookie for the response. */\nexport type SetCookie = (name: string, value: string, options?: CookieOptions) => void;\n\n/**\n * Decodes a cookie value, falling back to the raw value if it is malformed.\n *\n * Cookies are URL-encoded on write (see {@link serializeCookie}); decoding here\n * keeps round-trips lossless without throwing on hand-crafted values.\n */\nfunction tryDecode(value: string): string {\n try {\n return decodeURIComponent(value);\n } catch {\n return value;\n }\n}\n\n/**\n * Parses a `Cookie` request header into a plain map of name to value.\n *\n * Returns an empty object for a missing or empty header. When a name appears\n * more than once the first value wins, matching the common `cookie` package.\n */\nexport function parseCookies(header: string | null): Record<string, string> {\n const cookies: Record<string, string> = {};\n if (!header) {\n return cookies;\n }\n\n // Split on the standard \"; \" delimiter, tolerating arbitrary surrounding space.\n for (const pair of header.split(';')) {\n const separator = pair.indexOf('=');\n if (separator < 0) {\n continue;\n }\n\n // Split on the first \"=\" only so values may themselves contain \"=\".\n const name = pair.slice(0, separator).trim();\n if (name && !(name in cookies)) {\n cookies[name] = tryDecode(pair.slice(separator + 1).trim());\n }\n }\n\n return cookies;\n}\n\n/**\n * Serializes a cookie into a `Set-Cookie` header value per RFC 6265.\n *\n * The value is URL-encoded; attributes are appended in a stable order.\n */\nexport function serializeCookie(name: string, value: string, options: CookieOptions = {}): string {\n const parts = [`${name}=${encodeURIComponent(value)}`];\n\n // Attributes, in the conventional Set-Cookie order.\n if (options.maxAge !== undefined) {\n parts.push(`Max-Age=${Math.trunc(options.maxAge)}`);\n }\n if (options.expires) {\n parts.push(`Expires=${options.expires.toUTCString()}`);\n }\n if (options.domain) {\n parts.push(`Domain=${options.domain}`);\n }\n if (options.path) {\n parts.push(`Path=${options.path}`);\n }\n if (options.secure) {\n parts.push('Secure');\n }\n if (options.httpOnly) {\n parts.push('HttpOnly');\n }\n if (options.sameSite) {\n // Capitalize to match the spec's token casing (Strict / Lax / None).\n parts.push(`SameSite=${options.sameSite[0].toUpperCase()}${options.sameSite.slice(1)}`);\n }\n\n return parts.join('; ');\n}\n\n/**\n * Creates a middleware that parses request cookies and enables setting them.\n *\n * Merges the parsed cookies into `context.cookies` and installs a\n * `context.setCookie(name, value, options)` helper. Each `setCookie` call adds\n * a separate `Set-Cookie` header to the response (append, not overwrite), so a\n * handler may set multiple cookies.\n *\n * @example\n * ```typescript\n * const api = router('/api', routes, cookies());\n * // in a handler: c.cookies['session']; c.setCookie('session', id, { httpOnly: true });\n * ```\n */\nexport function cookies(): Middleware {\n return async (context, next) => {\n // Read side: parse the incoming Cookie header once.\n context.cookies = parseCookies(context.request.headers.get('Cookie'));\n\n // Write side: queue serialized cookies for the outgoing response.\n const pending: string[] = [];\n context.setCookie = ((name, value, options) => {\n pending.push(serializeCookie(name, value, options));\n }) satisfies SetCookie;\n\n const response = await next();\n\n // Leave the response untouched when no cookies were set.\n if (pending.length === 0) {\n return response;\n }\n\n // Append each cookie as its own Set-Cookie header.\n const headers = new Headers(response.headers);\n for (const cookie of pending) {\n headers.append('Set-Cookie', cookie);\n }\n\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n };\n}\n","/**\n * @fileoverview CORS middleware for @fresho/router.\n *\n * Provides Cross-Origin Resource Sharing support with configurable options.\n */\n\nimport type { Middleware } from '../middleware.js';\n\n/** CORS middleware configuration options. */\nexport interface CorsOptions {\n /** Allowed origins. Can be string, array, regex, or function. */\n origin?: string | string[] | RegExp | ((origin: string) => boolean);\n /** Allowed HTTP methods. */\n methods?: string[];\n /** Allowed request headers. */\n allowedHeaders?: string[];\n /** Headers to expose to the browser. */\n exposedHeaders?: string[];\n /** Allow credentials (cookies, authorization headers). */\n credentials?: boolean;\n /** Max age for preflight cache (seconds). */\n maxAge?: number;\n /** Pass the CORS preflight response to the next handler. */\n preflightContinue?: boolean;\n}\n\n/**\n * Determines if an origin is allowed based on the configuration.\n */\nfunction getAllowedOrigin(\n requestOrigin: string | null,\n configOrigin: CorsOptions['origin'],\n): string {\n if (!requestOrigin) {\n return '*';\n }\n\n if (!configOrigin || configOrigin === '*') {\n return '*';\n }\n\n if (typeof configOrigin === 'string') {\n return configOrigin === requestOrigin ? configOrigin : 'false';\n }\n\n if (Array.isArray(configOrigin)) {\n return configOrigin.includes(requestOrigin) ? requestOrigin : 'false';\n }\n\n if (configOrigin instanceof RegExp) {\n return configOrigin.test(requestOrigin) ? requestOrigin : 'false';\n }\n\n if (typeof configOrigin === 'function') {\n return configOrigin(requestOrigin) ? requestOrigin : 'false';\n }\n\n return 'false';\n}\n\n/**\n * Creates a CORS middleware with the specified options.\n *\n * @example\n * ```typescript\n * const apiRouter = router('/api', routes, cors({ origin: 'https://example.com', credentials: true }));\n * ```\n */\nexport function cors(options: CorsOptions = {}): Middleware {\n const config: Required<CorsOptions> = {\n origin: '*',\n methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', 'HEAD'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n exposedHeaders: [],\n credentials: false,\n maxAge: 86400,\n preflightContinue: false,\n ...options,\n };\n\n return async (context, next) => {\n const { request } = context;\n const requestOrigin = request.headers.get('Origin');\n const allowedOrigin = getAllowedOrigin(requestOrigin, config.origin);\n\n // Handle preflight request\n if (request.method === 'OPTIONS') {\n const headers: Record<string, string> = {\n 'Access-Control-Allow-Origin': allowedOrigin,\n 'Access-Control-Allow-Methods': config.methods.join(', '),\n Vary: 'Origin',\n };\n\n if (config.allowedHeaders.length > 0) {\n const requestHeaders = request.headers.get('Access-Control-Request-Headers');\n if (requestHeaders) {\n // Allow requested headers if they're in the allowed list\n const requested = requestHeaders.split(',').map((h) => h.trim().toLowerCase());\n const allowed = config.allowedHeaders.map((h) => h.toLowerCase());\n const toAllow = requested.filter((h) => allowed.includes(h));\n if (toAllow.length > 0) {\n headers['Access-Control-Allow-Headers'] = toAllow.join(', ');\n }\n } else {\n headers['Access-Control-Allow-Headers'] = config.allowedHeaders.join(', ');\n }\n }\n\n if (config.exposedHeaders.length > 0) {\n headers['Access-Control-Expose-Headers'] = config.exposedHeaders.join(', ');\n }\n\n if (config.credentials) {\n headers['Access-Control-Allow-Credentials'] = 'true';\n }\n\n if (config.maxAge) {\n headers['Access-Control-Max-Age'] = String(config.maxAge);\n }\n\n const response = new Response(null, {\n status: 204,\n headers,\n });\n\n if (config.preflightContinue) {\n // Continue to next middleware/handler even for preflight\n const nextResponse = await next();\n // Merge headers from next response\n const mergedHeaders = new Headers(nextResponse.headers);\n Object.entries(headers).forEach(([key, value]) => {\n mergedHeaders.set(key, value);\n });\n return new Response(nextResponse.body, {\n status: nextResponse.status,\n statusText: nextResponse.statusText,\n headers: mergedHeaders,\n });\n }\n\n return response;\n }\n\n // Handle actual request\n const response = await next();\n\n // Add CORS headers to response\n const headers = new Headers(response.headers);\n headers.set('Access-Control-Allow-Origin', allowedOrigin);\n headers.set('Vary', 'Origin');\n\n if (config.credentials && allowedOrigin !== '*') {\n headers.set('Access-Control-Allow-Credentials', 'true');\n }\n\n if (config.exposedHeaders.length > 0) {\n headers.set('Access-Control-Expose-Headers', config.exposedHeaders.join(', '));\n }\n\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAyDA,SAAgB,UAAU,SAAuC;CAC/D,MAAM,QAAQ,QAAQ,SAAS;AAE/B,QAAO,OAAO,SAAS,SAAS;EAC9B,MAAM,EAAE,YAAY;EAEpB,MAAM,cAAc,eAAe,QAAQ,QAAQ,IAAI,gBAAgB,CAAC;AACxE,MAAI,CAAC,YACH,QAAO,IAAI,SAAS,gBAAgB;GAClC,Q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WAAQ,sCAAsC;AAGhD,OAAI,OAAO,OACT,WAAQ,4BAA4B,OAAO,OAAO,OAAO;GAG3D,MAAMC,aAAW,IAAI,SAAS,MAAM;IAClC,QAAQ;IACR;IACD,CAAC;AAEF,OAAI,OAAO,mBAAmB;IAE5B,MAAM,eAAe,MAAM,MAAM;IAEjC,MAAM,gBAAgB,IAAI,QAAQ,aAAa,QAAQ;AACvD,WAAO,QAAQC,UAAQ,CAAC,SAAS,CAAC,KAAK,WAAW;AAChD,mBAAc,IAAI,KAAK,MAAM;MAC7B;AACF,WAAO,IAAI,SAAS,aAAa,MAAM;KACrC,QAAQ,aAAa;KACrB,YAAY,aAAa;KACzB,SAAS;KACV,CAAC;;AAGJ,UAAOD;;EAIT,MAAM,WAAW,MAAM,MAAM;EAG7B,MAAM,UAAU,IAAI,QAAQ,SAAS,QAAQ;AAC7C,UAAQ,IAAI,+BAA+B,cAAc;AACzD,UAAQ,IAAI,QAAQ,SAAS;AAE7B,MAAI,OAAO,eAAe,kBAAkB,IAC1C,SAAQ,IAAI,oCAAoC,OAAO;AAGzD,MAAI,OAAO,eAAe,SAAS,EACjC,SAAQ,IAAI,iCAAiC,OAAO,eAAe,KAAK,KAAK,CAAC;AAGhF,SAAO,IAAI,SAAS,SAAS,MAAM;GACjC,QAAQ,SAAS;GACjB,YAAY,SAAS;GACrB;GACD,CAAC"}
1
+ {"version":3,"file":"index.mjs","names":["status: number","info: LogInfo","windowMs: number","contentType","cookies: Record<string, string>","cookies","pending: string[]","config: Required<CorsOptions>","headers: Record<string, string>","response","headers"],"sources":["../../src/middleware/auth.ts","../../src/middleware/common.ts","../../src/middleware/cookies.ts","../../src/middleware/cors.ts"],"sourcesContent":["/**\n * @fileoverview Authentication middleware for @fresho/router.\n *\n * Provides middleware wrappers for Basic HTTP, JWT, and Bearer token authentication.\n * The underlying authentication utilities are in `@fresho/router/auth`.\n */\n\nimport { parseBasicAuth } from '../auth/basic.js';\nimport { type JwtAlgorithm, type JwtPayload, type JwtSecret, jwtVerify } from '../auth/jwt.js';\nimport type { Middleware, MiddlewareContext } from '../middleware.js';\n\n// Re-export types that middleware users need\nexport type {\n Jwks,\n JwtAlgorithm,\n JwtPayload,\n JwtSecret,\n SignJwtOptions,\n VerifyJwtOptions,\n} from '../auth/jwt.js';\n\n// Re-export utilities that are commonly used alongside middleware\nexport { createJwks, jwtSign, jwtVerify } from '../auth/jwt.js';\n\n// =============================================================================\n// Basic Auth Middleware\n// =============================================================================\n\n/** Basic authentication middleware configuration. */\nexport interface BasicAuthOptions {\n /** Realm name for the authentication challenge. */\n realm?: string;\n /** Function to validate credentials. Returns claims to merge into context, or null to reject. */\n verify: (\n username: string,\n password: string,\n context: MiddlewareContext,\n ) => Promise<Record<string, unknown> | null> | Record<string, unknown> | null;\n}\n\n/**\n * Creates a Basic HTTP authentication middleware.\n *\n * @example\n * ```typescript\n * const adminRouter = router('/admin', routes,\n * basicAuth({\n * verify: async (username, password) => {\n * if (username === 'admin' && password === 'secret') {\n * return { user: { name: username } };\n * }\n * return null;\n * }\n * })\n * );\n * ```\n */\nexport function basicAuth(options: BasicAuthOptions): Middleware {\n const realm = options.realm || 'Secure Area';\n\n return async (context, next) => {\n const { request } = context;\n\n const credentials = parseBasicAuth(request.headers.get('Authorization'));\n if (!credentials) {\n return new Response('Unauthorized', {\n status: 401,\n headers: {\n 'WWW-Authenticate': `Basic realm=\"${realm}\", charset=\"UTF-8\"`,\n },\n });\n }\n\n try {\n const claims = await options.verify(credentials.username, credentials.password, context);\n if (claims === null) {\n return new Response('Invalid credentials', {\n status: 401,\n headers: {\n 'WWW-Authenticate': `Basic realm=\"${realm}\", charset=\"UTF-8\"`,\n },\n });\n }\n\n Object.assign(context, claims);\n return next();\n } catch (_error) {\n return new Response('Invalid credentials', {\n status: 401,\n headers: {\n 'WWW-Authenticate': `Basic realm=\"${realm}\", charset=\"UTF-8\"`,\n },\n });\n }\n };\n}\n\n// =============================================================================\n// JWT Auth Middleware\n// =============================================================================\n\n/** JWT authentication middleware configuration. */\nexport interface JwtAuthOptions<Ctx = {}> {\n /** Secret key or function to get the secret from context. */\n secret: JwtSecret | ((context: MiddlewareContext<Ctx>) => JwtSecret);\n /**\n * Map JWT payload to context properties. Return null to reject the token.\n * The returned object is merged into the middleware context.\n */\n claims: (payload: JwtPayload) => Record<string, unknown> | null;\n /** Allowed algorithms (default: ['HS256'] for HMAC secrets, ['RS256'] otherwise). */\n algorithms?: JwtAlgorithm[];\n /** Required issuer (`iss`). */\n issuer?: string | string[];\n /** Required audience (`aud`); the token must contain at least one of the given values. */\n audience?: string | string[];\n /** Seconds of clock skew allowed when checking `exp` and `nbf` (default: 0). */\n clockTolerance?: number;\n /** Function to extract token from request (default: Authorization header or 'token' cookie). */\n getToken?: (request: Request) => string | null;\n}\n\n/**\n * Creates a JWT authentication middleware.\n *\n * @example\n * ```typescript\n * interface AppContext {\n * env: { JWT_SECRET: string };\n * user: { id: string; email: string };\n * }\n *\n * jwtAuth<AppContext>({\n * secret: (ctx) => ctx.env.JWT_SECRET, // ctx.env is typed\n * claims: (payload) => ({\n * user: { id: payload.sub, email: payload.email },\n * }),\n * })\n *\n * // In your route handler:\n * route.ctx<AppContext>()({\n * handler: async (c) => {\n * return { email: c.user.email }; // Fully typed\n * },\n * })\n * ```\n */\nexport function jwtAuth<Ctx = {}>(options: JwtAuthOptions<Ctx>): Middleware<Ctx> {\n const getToken =\n options.getToken ||\n ((req) => {\n const auth = req.headers.get('Authorization');\n if (auth?.startsWith('Bearer ')) {\n return auth.slice(7);\n }\n // Also check for token in cookie.\n const cookie = req.headers.get('Cookie');\n if (cookie) {\n const match = cookie.match(/(?:^|;\\s*)token=([^;]*)/);\n if (match) {\n return match[1];\n }\n }\n return null;\n });\n\n return async (context, next) => {\n const { request } = context;\n\n const token = getToken(request);\n if (!token) {\n return new Response('Missing token', {\n status: 401,\n headers: { 'WWW-Authenticate': 'Bearer' },\n });\n }\n\n try {\n const secret =\n typeof options.secret === 'function' ? options.secret(context) : options.secret;\n\n const payload = await jwtVerify(token, secret, {\n algorithms: options.algorithms,\n issuer: options.issuer,\n audience: options.audience,\n clockTolerance: options.clockTolerance,\n });\n\n // Map payload to context properties.\n const claims = options.claims(payload);\n if (claims === null) {\n throw new Error('Token validation failed');\n }\n Object.assign(context, claims);\n\n return next();\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Invalid token';\n return new Response(message, {\n status: 401,\n headers: {\n // Fixed value: messages can carry token or JWKS content, unsafe in a header.\n 'WWW-Authenticate': 'Bearer error=\"invalid_token\"',\n },\n });\n }\n };\n}\n\n// =============================================================================\n// Bearer Token Auth Middleware (Simple)\n// =============================================================================\n\n/** Bearer token authentication options. */\nexport interface BearerAuthOptions {\n /** Function to validate the token. Returns claims to merge into context, or null to reject. */\n verify: (\n token: string,\n context: MiddlewareContext,\n ) => Promise<Record<string, unknown> | null> | Record<string, unknown> | null;\n}\n\n/**\n * Creates a simple bearer token authentication middleware.\n *\n * @example\n * ```typescript\n * const apiRouter = router('/api', routes,\n * bearerAuth({\n * verify: async (token) => {\n * if (token === process.env.API_TOKEN) {\n * return { apiClient: 'trusted' };\n * }\n * return null;\n * }\n * })\n * );\n * ```\n */\nexport function bearerAuth(options: BearerAuthOptions): Middleware {\n return async (context, next) => {\n const { request } = context;\n\n const authHeader = request.headers.get('Authorization');\n if (!authHeader?.startsWith('Bearer ')) {\n return new Response('Missing token', {\n status: 401,\n headers: { 'WWW-Authenticate': 'Bearer' },\n });\n }\n\n const token = authHeader.slice(7);\n const claims = await options.verify(token, context);\n\n if (claims === null) {\n return new Response('Invalid token', {\n status: 401,\n headers: { 'WWW-Authenticate': 'Bearer error=\"invalid_token\"' },\n });\n }\n\n Object.assign(context, claims);\n return next();\n };\n}\n","/**\n * @fileoverview Common middleware utilities for @fresho/router.\n *\n * Provides error handling, logging, rate limiting, and other utilities.\n */\n\nimport type { Middleware, MiddlewareContext } from '../middleware.js';\n\n// =============================================================================\n// Error Handler\n// =============================================================================\n\n/**\n * HTTP error with status code for use with errorHandler middleware.\n *\n * Throw this in route handlers to return a specific HTTP status code.\n * The errorHandler middleware will catch it and format the response.\n *\n * @example\n * ```typescript\n * import { HttpError } from '@fresho/router/middleware';\n *\n * const getUser = route({\n * method: 'get',\n * path: '/users/:id',\n * handler: async (c) => {\n * const user = await db.findUser(c.path.id);\n * if (!user) throw new HttpError('User not found', 404);\n * return user;\n * },\n * });\n * ```\n */\nexport class HttpError extends Error {\n constructor(\n message: string,\n public status: number,\n ) {\n super(message);\n this.name = 'HttpError';\n }\n}\n\n/**\n * Extracts HTTP status code from an error object.\n *\n * Supports errors with `status` or `statusCode` properties (common patterns\n * in frameworks like Express, Koa, Hono, and custom HTTP error classes).\n */\nfunction getErrorStatus(error: unknown): number {\n if (typeof error !== 'object' || error === null) {\n return 500;\n }\n if ('status' in error && typeof error.status === 'number') {\n return error.status;\n }\n if ('statusCode' in error && typeof error.statusCode === 'number') {\n return error.statusCode;\n }\n return 500;\n}\n\n/** Error handler middleware configuration. */\nexport interface ErrorHandlerOptions {\n /** Custom error logger. */\n log?: (error: Error, context: MiddlewareContext) => void | Promise<void>;\n /** Expose error details in response (dangerous in production). */\n expose?: boolean;\n /** Custom error response formatter. */\n formatter?: (error: Error, context: MiddlewareContext) => Response | Promise<Response>;\n}\n\n/**\n * Creates an error handling middleware that catches and formats errors.\n *\n * @example\n * ```typescript\n * const apiRouter = router('/api', routes, errorHandler({ expose: false }));\n * ```\n */\nexport function errorHandler(options: ErrorHandlerOptions = {}): Middleware {\n return async (context, next) => {\n try {\n return await next();\n } catch (error) {\n const err = error as Error;\n\n // Log error if logger provided\n if (options.log) {\n await options.log(err, context);\n } else {\n console.error(`Error in ${context.request.method} ${context.request.url}:`, err);\n }\n\n // Use custom formatter if provided\n if (options.formatter) {\n return await options.formatter(err, context);\n }\n\n // Default error response\n const message = options.expose ? err.message : 'Internal Server Error';\n const status = getErrorStatus(error);\n\n const errorBody = {\n error: message,\n ...(options.expose && {\n stack: err.stack,\n name: err.name,\n }),\n };\n\n return new Response(JSON.stringify(errorBody), {\n status,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n };\n}\n\n// =============================================================================\n// Logger\n// =============================================================================\n\n/** Logger middleware configuration. */\nexport interface LoggerOptions {\n /** Custom logger function. */\n log?: (message: string) => void;\n /** Include request headers in log. */\n includeHeaders?: boolean;\n /** Include request body in log. */\n includeBody?: boolean;\n /** Custom log formatter. */\n formatter?: (info: LogInfo) => string;\n}\n\n/** Information logged for each request. */\nexport interface LogInfo {\n method: string;\n url: string;\n status: number;\n duration: number;\n headers?: Record<string, string>;\n body?: unknown;\n error?: Error;\n}\n\n/**\n * Creates a request/response logging middleware.\n *\n * @example\n * ```typescript\n * const apiRouter = router('/api', routes, logger({ includeHeaders: true }));\n * ```\n */\nexport function logger(options: LoggerOptions = {}): Middleware {\n const log = options.log || console.log;\n\n return async (context, next) => {\n const { request } = context;\n const start = Date.now();\n const url = new URL(request.url);\n\n // Collect request info\n const info: LogInfo = {\n method: request.method,\n url: `${url.pathname}${url.search}`,\n status: 0,\n duration: 0,\n };\n\n if (options.includeHeaders) {\n info.headers = Object.fromEntries(request.headers.entries());\n }\n\n if (options.includeBody && request.body) {\n try {\n const clonedRequest = request.clone();\n const text = await clonedRequest.text();\n try {\n info.body = JSON.parse(text);\n } catch {\n info.body = text;\n }\n } catch {\n info.body = '[Body not readable]';\n }\n }\n\n // Log request\n const requestMessage = options.formatter\n ? options.formatter({ ...info, status: 0, duration: 0 })\n : `→ ${info.method} ${info.url}`;\n log(requestMessage);\n\n try {\n // Process request\n const response = await next();\n\n // Log response\n info.status = response.status;\n info.duration = Date.now() - start;\n\n const responseMessage = options.formatter\n ? options.formatter(info)\n : `← ${info.status} ${response.statusText || 'OK'} (${info.duration}ms)`;\n log(responseMessage);\n\n return response;\n } catch (error) {\n // Log error\n info.status = 500;\n info.duration = Date.now() - start;\n info.error = error as Error;\n\n const errorMessage = options.formatter\n ? options.formatter(info)\n : `✗ ${info.status} Error: ${(error as Error).message} (${info.duration}ms)`;\n log(errorMessage);\n\n throw error;\n }\n };\n}\n\n// =============================================================================\n// Rate Limiter\n// =============================================================================\n\n/** Rate limit store interface. */\nexport interface RateLimitStore {\n increment(key: string): Promise<number>;\n decrement(key: string): Promise<void>;\n reset(key: string): Promise<void>;\n}\n\n/** In-memory rate limit store with periodic cleanup of expired entries. */\nexport class MemoryRateLimitStore implements RateLimitStore {\n private counts = new Map<string, { count: number; resetAt: number }>();\n private lastCleanup = Date.now();\n\n /** Interval between cleanups (default: 60 seconds). */\n private readonly cleanupIntervalMs: number;\n\n constructor(\n private windowMs: number,\n options?: { cleanupIntervalMs?: number },\n ) {\n // Default cleanup interval is the window duration or 60 seconds, whichever is larger.\n this.cleanupIntervalMs = options?.cleanupIntervalMs ?? Math.max(windowMs, 60_000);\n }\n\n async increment(key: string): Promise<number> {\n const now = Date.now();\n\n // Periodic cleanup to prevent memory leaks.\n if (now - this.lastCleanup > this.cleanupIntervalMs) {\n this.cleanup(now);\n }\n\n const record = this.counts.get(key);\n\n if (!record || now > record.resetAt) {\n this.counts.set(key, { count: 1, resetAt: now + this.windowMs });\n return 1;\n }\n\n record.count++;\n return record.count;\n }\n\n async decrement(key: string): Promise<void> {\n const record = this.counts.get(key);\n if (record && record.count > 0) {\n record.count--;\n }\n }\n\n async reset(key: string): Promise<void> {\n this.counts.delete(key);\n }\n\n /** Removes all expired entries from the store. */\n private cleanup(now: number): void {\n for (const [key, record] of this.counts) {\n if (now > record.resetAt) {\n this.counts.delete(key);\n }\n }\n this.lastCleanup = now;\n }\n\n /** Returns the current number of tracked keys (useful for testing). */\n get size(): number {\n return this.counts.size;\n }\n}\n\n/** Rate limiter middleware configuration. */\nexport interface RateLimitOptions {\n /** Time window in milliseconds. */\n windowMs?: number;\n /** Maximum requests per window. */\n max?: number;\n /** Function to generate a unique key for each client. */\n keyGenerator?: (context: MiddlewareContext) => string;\n /** Store for rate limit data. */\n store?: RateLimitStore;\n /** Skip successful requests from rate limit. */\n skipSuccessfulRequests?: boolean;\n /** Skip failed requests from rate limit. */\n skipFailedRequests?: boolean;\n /** Custom handler for rate limited requests. */\n handler?: (context: MiddlewareContext) => Response | Promise<Response>;\n}\n\n/**\n * Creates a rate limiting middleware.\n *\n * @example\n * ```typescript\n * const apiRouter = router('/api', routes, rateLimit({ max: 100, windowMs: 60000 }));\n * ```\n */\nexport function rateLimit(options: RateLimitOptions = {}): Middleware {\n const config = {\n windowMs: 60 * 1000, // 1 minute\n max: 100,\n keyGenerator: (ctx: MiddlewareContext) => {\n // Use IP address as default key\n const cfIp = ctx.request.headers.get('CF-Connecting-IP');\n const xForwardedFor = ctx.request.headers.get('X-Forwarded-For');\n const xRealIp = ctx.request.headers.get('X-Real-IP');\n return cfIp || xForwardedFor?.split(',')[0] || xRealIp || 'unknown';\n },\n ...options,\n };\n\n const store = config.store || new MemoryRateLimitStore(config.windowMs);\n\n return async (context, next) => {\n const key = config.keyGenerator(context);\n const current = await store.increment(key);\n\n if (current > config.max) {\n if (config.handler) {\n return await config.handler(context);\n }\n\n return new Response('Too many requests', {\n status: 429,\n headers: {\n 'Retry-After': String(Math.ceil(config.windowMs / 1000)),\n 'X-RateLimit-Limit': String(config.max),\n 'X-RateLimit-Remaining': '0',\n 'X-RateLimit-Reset': new Date(Date.now() + config.windowMs).toISOString(),\n },\n });\n }\n\n const response = await next();\n\n // Optionally don't count successful/failed requests\n if (\n (config.skipSuccessfulRequests && response.status < 400) ||\n (config.skipFailedRequests && response.status >= 400)\n ) {\n await store.decrement(key);\n }\n\n // Add rate limit headers\n const headers = new Headers(response.headers);\n headers.set('X-RateLimit-Limit', String(config.max));\n headers.set('X-RateLimit-Remaining', String(Math.max(0, config.max - current)));\n headers.set('X-RateLimit-Reset', new Date(Date.now() + config.windowMs).toISOString());\n\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n };\n}\n\n// =============================================================================\n// Request ID\n// =============================================================================\n\n/** Request ID middleware configuration. */\nexport interface RequestIdOptions {\n /** Header name for request ID. */\n headerName?: string;\n /** Function to generate request ID. */\n generator?: () => string;\n}\n\n/**\n * Creates a middleware that adds a unique request ID to each request.\n *\n * @example\n * ```typescript\n * const apiRouter = router('/api', routes, requestId({ headerName: 'X-Request-ID' }));\n * ```\n */\nexport function requestId(options: RequestIdOptions = {}): Middleware {\n const headerName = options.headerName || 'X-Request-ID';\n const generator = options.generator || (() => crypto.randomUUID());\n\n return async (context, next) => {\n // Check if request already has an ID\n let id = context.request.headers.get(headerName);\n if (!id) {\n id = generator();\n }\n\n // Add to context\n context.requestId = id;\n\n // Process request\n const response = await next();\n\n // Add request ID to response headers\n const headers = new Headers(response.headers);\n headers.set(headerName, id);\n\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n };\n}\n\n// =============================================================================\n// Timeout\n// =============================================================================\n\n/** Timeout middleware configuration. */\nexport interface TimeoutOptions {\n /** Timeout in milliseconds. */\n timeout: number;\n /** Custom timeout response. */\n message?: string;\n}\n\n/**\n * Creates a middleware that times out requests after a specified duration.\n *\n * @example\n * ```typescript\n * const apiRouter = router('/api', routes, timeout({ timeout: 5000 }));\n * ```\n */\nexport function timeout(options: TimeoutOptions): Middleware {\n return async (context, next) => {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), options.timeout);\n\n try {\n const responsePromise = next();\n const timeoutPromise = new Promise<Response>((_, reject) => {\n controller.signal.addEventListener('abort', () => {\n reject(new Error('Request timeout'));\n });\n });\n\n const response = await Promise.race([responsePromise, timeoutPromise]);\n clearTimeout(timeoutId);\n return response;\n } catch (error) {\n clearTimeout(timeoutId);\n if ((error as Error).message === 'Request timeout') {\n return new Response(options.message || 'Request timeout', {\n status: 408,\n });\n }\n throw error;\n }\n };\n}\n\n// =============================================================================\n// Content Type Validation\n// =============================================================================\n\n/** Content type validation options. */\nexport interface ContentTypeOptions {\n /** Expected content types. */\n types: string[];\n /** Skip validation for these methods. */\n skipMethods?: string[];\n /** Custom error message. */\n message?: string;\n}\n\n/**\n * Creates a middleware that validates request content type.\n *\n * @example\n * ```typescript\n * const apiRouter = router('/api', routes, contentType({ types: ['application/json'] }));\n * ```\n */\nexport function contentType(options: ContentTypeOptions): Middleware {\n const skipMethods = new Set(\n options.skipMethods?.map((m) => m.toUpperCase()) || ['GET', 'HEAD', 'OPTIONS'],\n );\n\n return async (context, next) => {\n if (skipMethods.has(context.request.method.toUpperCase())) {\n return next();\n }\n\n const contentType = context.request.headers.get('Content-Type');\n if (!contentType) {\n return new Response(options.message || 'Missing Content-Type header', {\n status: 415,\n });\n }\n\n const matches = options.types.some((type) => contentType.includes(type));\n if (!matches) {\n return new Response(\n options.message || `Unsupported Media Type. Expected: ${options.types.join(', ')}`,\n { status: 415 },\n );\n }\n\n return next();\n };\n}\n","/**\n * @fileoverview Cookie parsing/serialization and the cookies() middleware.\n *\n * Reads the request `Cookie` header into `context.cookies` and installs a\n * `context.setCookie` helper that serializes per RFC 6265 and appends\n * `Set-Cookie` headers to the outgoing response. Dependency-free, Web APIs only.\n */\n\nimport type { Middleware } from '../middleware.js';\n\n/** Options for serializing a cookie into a `Set-Cookie` header value. */\nexport interface CookieOptions {\n /** Lifetime in seconds, serialized as `Max-Age`. */\n maxAge?: number;\n /** Absolute expiry, serialized as `Expires`. */\n expires?: Date;\n /** Restricts the cookie to a path prefix. */\n path?: string;\n /** Restricts the cookie to a domain. */\n domain?: string;\n /** Only send the cookie over HTTPS. */\n secure?: boolean;\n /** Hide the cookie from client-side JavaScript. */\n httpOnly?: boolean;\n /** Cross-site sending policy. */\n sameSite?: 'strict' | 'lax' | 'none';\n}\n\n/** Helper installed on the context to queue a cookie for the response. */\nexport type SetCookie = (name: string, value: string, options?: CookieOptions) => void;\n\n/**\n * Decodes a cookie value, falling back to the raw value if it is malformed.\n *\n * Cookies are URL-encoded on write (see {@link serializeCookie}); decoding here\n * keeps round-trips lossless without throwing on hand-crafted values.\n */\nfunction tryDecode(value: string): string {\n try {\n return decodeURIComponent(value);\n } catch {\n return value;\n }\n}\n\n/**\n * Parses a `Cookie` request header into a plain map of name to value.\n *\n * Returns an empty object for a missing or empty header. When a name appears\n * more than once the first value wins, matching the common `cookie` package.\n */\nexport function parseCookies(header: string | null): Record<string, string> {\n const cookies: Record<string, string> = {};\n if (!header) {\n return cookies;\n }\n\n // Split on the standard \"; \" delimiter, tolerating arbitrary surrounding space.\n for (const pair of header.split(';')) {\n const separator = pair.indexOf('=');\n if (separator < 0) {\n continue;\n }\n\n // Split on the first \"=\" only so values may themselves contain \"=\".\n const name = pair.slice(0, separator).trim();\n if (name && !(name in cookies)) {\n cookies[name] = tryDecode(pair.slice(separator + 1).trim());\n }\n }\n\n return cookies;\n}\n\n/**\n * Serializes a cookie into a `Set-Cookie` header value per RFC 6265.\n *\n * The value is URL-encoded; attributes are appended in a stable order.\n */\nexport function serializeCookie(name: string, value: string, options: CookieOptions = {}): string {\n const safeName = name.replace(/[\\r\\n;]/g, '');\n const parts = [`${safeName}=${encodeURIComponent(value)}`];\n\n // Attributes, in the conventional Set-Cookie order.\n if (options.maxAge !== undefined) {\n parts.push(`Max-Age=${Math.trunc(options.maxAge)}`);\n }\n if (options.expires) {\n parts.push(`Expires=${options.expires.toUTCString()}`);\n }\n if (options.domain) {\n parts.push(`Domain=${options.domain.replace(/[\\r\\n;]/g, '')}`);\n }\n if (options.path) {\n parts.push(`Path=${options.path.replace(/[\\r\\n;]/g, '')}`);\n }\n if (options.secure) {\n parts.push('Secure');\n }\n if (options.httpOnly) {\n parts.push('HttpOnly');\n }\n if (options.sameSite) {\n // Capitalize to match the spec's token casing (Strict / Lax / None).\n parts.push(`SameSite=${options.sameSite[0].toUpperCase()}${options.sameSite.slice(1)}`);\n }\n\n return parts.join('; ');\n}\n\n/**\n * Creates a middleware that parses request cookies and enables setting them.\n *\n * Merges the parsed cookies into `context.cookies` and installs a\n * `context.setCookie(name, value, options)` helper. Each `setCookie` call adds\n * a separate `Set-Cookie` header to the response (append, not overwrite), so a\n * handler may set multiple cookies.\n *\n * @example\n * ```typescript\n * const api = router('/api', routes, cookies());\n * // in a handler: c.cookies['session']; c.setCookie('session', id, { httpOnly: true });\n * ```\n */\nexport function cookies(): Middleware {\n return async (context, next) => {\n // Read side: parse the incoming Cookie header once.\n context.cookies = parseCookies(context.request.headers.get('Cookie'));\n\n // Write side: queue serialized cookies for the outgoing response.\n const pending: string[] = [];\n context.setCookie = ((name, value, options) => {\n pending.push(serializeCookie(name, value, options));\n }) satisfies SetCookie;\n\n const response = await next();\n\n // Leave the response untouched when no cookies were set.\n if (pending.length === 0) {\n return response;\n }\n\n // Append each cookie as its own Set-Cookie header.\n const headers = new Headers(response.headers);\n for (const cookie of pending) {\n headers.append('Set-Cookie', cookie);\n }\n\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n };\n}\n","/**\n * @fileoverview CORS middleware for @fresho/router.\n *\n * Provides Cross-Origin Resource Sharing support with configurable options.\n */\n\nimport type { Middleware } from '../middleware.js';\n\n/** CORS middleware configuration options. */\nexport interface CorsOptions {\n /** Allowed origins. Can be string, array, regex, or function. */\n origin?: string | string[] | RegExp | ((origin: string) => boolean);\n /** Allowed HTTP methods. */\n methods?: string[];\n /** Allowed request headers. */\n allowedHeaders?: string[];\n /** Headers to expose to the browser. */\n exposedHeaders?: string[];\n /** Allow credentials (cookies, authorization headers). */\n credentials?: boolean;\n /** Max age for preflight cache (seconds). */\n maxAge?: number;\n /** Pass the CORS preflight response to the next handler. */\n preflightContinue?: boolean;\n}\n\n/**\n * Determines if an origin is allowed based on the configuration.\n */\nfunction getAllowedOrigin(\n requestOrigin: string | null,\n configOrigin: CorsOptions['origin'],\n): string | false {\n if (!configOrigin || configOrigin === '*') {\n return '*';\n }\n\n if (!requestOrigin) {\n return false;\n }\n\n if (typeof configOrigin === 'string') {\n return configOrigin === requestOrigin ? configOrigin : false;\n }\n\n if (Array.isArray(configOrigin)) {\n return configOrigin.includes(requestOrigin) ? requestOrigin : false;\n }\n\n if (configOrigin instanceof RegExp) {\n return configOrigin.test(requestOrigin) ? requestOrigin : false;\n }\n\n if (typeof configOrigin === 'function') {\n return configOrigin(requestOrigin) ? requestOrigin : false;\n }\n\n return false;\n}\n\n/**\n * Creates a CORS middleware with the specified options.\n *\n * @example\n * ```typescript\n * const apiRouter = router('/api', routes, cors({ origin: 'https://example.com', credentials: true }));\n * ```\n */\nexport function cors(options: CorsOptions = {}): Middleware {\n const config: Required<CorsOptions> = {\n origin: '*',\n methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', 'HEAD'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n exposedHeaders: [],\n credentials: false,\n maxAge: 86400,\n preflightContinue: false,\n ...options,\n };\n\n return async (context, next) => {\n const { request } = context;\n const requestOrigin = request.headers.get('Origin');\n const allowedOrigin = getAllowedOrigin(requestOrigin, config.origin);\n\n // Handle preflight request\n if (request.method === 'OPTIONS') {\n const headers: Record<string, string> = {\n 'Access-Control-Allow-Methods': config.methods.join(', '),\n Vary: 'Origin',\n };\n\n if (allowedOrigin) {\n headers['Access-Control-Allow-Origin'] = allowedOrigin;\n }\n\n if (config.allowedHeaders.length > 0) {\n const requestHeaders = request.headers.get('Access-Control-Request-Headers');\n if (requestHeaders) {\n // Allow requested headers if they're in the allowed list\n const requested = requestHeaders.split(',').map((h) => h.trim().toLowerCase());\n const allowed = config.allowedHeaders.map((h) => h.toLowerCase());\n const toAllow = requested.filter((h) => allowed.includes(h));\n if (toAllow.length > 0) {\n headers['Access-Control-Allow-Headers'] = toAllow.join(', ');\n }\n } else {\n headers['Access-Control-Allow-Headers'] = config.allowedHeaders.join(', ');\n }\n }\n\n if (config.exposedHeaders.length > 0) {\n headers['Access-Control-Expose-Headers'] = config.exposedHeaders.join(', ');\n }\n\n if (config.credentials && allowedOrigin && allowedOrigin !== '*') {\n headers['Access-Control-Allow-Credentials'] = 'true';\n }\n\n if (config.maxAge) {\n headers['Access-Control-Max-Age'] = String(config.maxAge);\n }\n\n const response = new Response(null, {\n status: 204,\n headers,\n });\n\n if (config.preflightContinue) {\n // Continue to next middleware/handler even for preflight\n const nextResponse = await next();\n // Merge headers from next response\n const mergedHeaders = new Headers(nextResponse.headers);\n Object.entries(headers).forEach(([key, value]) => {\n mergedHeaders.set(key, value);\n });\n return new Response(nextResponse.body, {\n status: nextResponse.status,\n statusText: nextResponse.statusText,\n headers: mergedHeaders,\n });\n }\n\n return response;\n }\n\n // Handle actual request\n const response = await next();\n\n // Add CORS headers to response\n const headers = new Headers(response.headers);\n if (allowedOrigin) {\n headers.set('Access-Control-Allow-Origin', allowedOrigin);\n }\n headers.set('Vary', 'Origin');\n\n if (config.credentials && allowedOrigin && allowedOrigin !== '*') {\n headers.set('Access-Control-Allow-Credentials', 'true');\n }\n\n if (config.exposedHeaders.length > 0) {\n headers.set('Access-Control-Expose-Headers', config.exposedHeaders.join(', '));\n }\n\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAyDA,SAAgB,UAAU,SAAuC;CAC/D,MAAM,QAAQ,QAAQ,SAAS;AAE/B,QAAO,OAAO,SAAS,SAAS;EAC9B,MAAM,EAAE,YAAY;EAEpB,MAAM,cAAc,eAAe,QAAQ,QAAQ,IAAI,gBAAgB,CAAC;AACxE,MAAI,CAAC,YACH,QAAO,IAAI,SAAS,gBAAgB;GAClC,QAAQ;GACR,SAAS,EACP,oBAAoB,gBAAgB,MAAM,qBAC3C;GACF,CAAC;AAGJ,MAAI;GACF,MAAM,SAAS,MAAM,QAAQ,OAAO,YAAY,UAAU,YAAY,UAAU,QAAQ;AACxF,OAAI,WAAW,KACb,QAAO,IAAI,SAAS,uBAAuB;IACzC,QAAQ;IACR,SAAS,EACP,oBAAoB,gBAAgB,MAAM,qBAC3C;IACF,CAAC;AAGJ,UAAO,OAAO,SAAS,OAAO;AAC9B,UAAO,MAAM;WACN,QAAQ;AACf,UAAO,IAAI,SAAS,uBAAuB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Aa,QAAQ;AACvD,WAAO,QAAQC,UAAQ,CAAC,SAAS,CAAC,KAAK,WAAW;AAChD,mBAAc,IAAI,KAAK,MAAM;MAC7B;AACF,WAAO,IAAI,SAAS,aAAa,MAAM;KACrC,QAAQ,aAAa;KACrB,YAAY,aAAa;KACzB,SAAS;KACV,CAAC;;AAGJ,UAAOD;;EAIT,MAAM,WAAW,MAAM,MAAM;EAG7B,MAAM,UAAU,IAAI,QAAQ,SAAS,QAAQ;AAC7C,MAAI,cACF,SAAQ,IAAI,+BAA+B,cAAc;AAE3D,UAAQ,IAAI,QAAQ,SAAS;AAE7B,MAAI,OAAO,eAAe,iBAAiB,kBAAkB,IAC3D,SAAQ,IAAI,oCAAoC,OAAO;AAGzD,MAAI,OAAO,eAAe,SAAS,EACjC,SAAQ,IAAI,iCAAiC,OAAO,eAAe,KAAK,KAAK,CAAC;AAGhF,SAAO,IAAI,SAAS,SAAS,MAAM;GACjC,QAAQ,SAAS;GACjB,YAAY,SAAS;GACrB;GACD,CAAC"}
@@ -10,6 +10,7 @@
10
10
  * - Optional: `'string?'`, `'number?'`, `'boolean?'`
11
11
  * - Arrays: `'string[]'`, `'number[]'`, `'boolean[]'`
12
12
  * - Optional arrays: `'string[]?'`, `'number[]?'`, `'boolean[]?'`
13
+ * - Described fields: `['string', 'Description']`, `['number?', 'Optional count']`
13
14
  * - Nested objects: `{ field: { nested: 'string' } }`
14
15
  *
15
16
  * @example
@@ -18,9 +19,9 @@
18
19
  * const api = router({
19
20
  * users: router({
20
21
  * post: route({
21
- * query: { page: 'number?', limit: 'number?' },
22
+ * query: { page: 'number?', limit: ['number?', 'Max results'] },
22
23
  * body: {
23
- * name: 'string',
24
+ * name: ['string', 'Full name'],
24
25
  * age: 'number',
25
26
  * tags: 'string[]?',
26
27
  * address: { city: 'string', zip: 'string?' },
@@ -45,9 +46,11 @@ type ArrayType = 'string[]' | 'number[]' | 'boolean[]' | 'unknown[]';
45
46
  type OptionalArrayType = 'string[]?' | 'number[]?' | 'boolean[]?' | 'unknown[]?';
46
47
  /** All supported type strings. */
47
48
  type SchemaType = PrimitiveType | OptionalPrimitiveType | ArrayType | OptionalArrayType;
49
+ /** A schema field: a type string, or a `[type, description]` tuple. */
50
+ type SchemaField = SchemaType | readonly [type: SchemaType, description: string];
48
51
  /** Schema definition using shorthand syntax. Supports nested objects. */
49
52
  interface SchemaDefinition {
50
- [key: string]: SchemaType | SchemaDefinition;
53
+ [key: string]: SchemaField | SchemaDefinition;
51
54
  }
52
55
  /** Maps primitive type strings to TypeScript types. */
53
56
  type SchemaTypeMap = {
@@ -69,9 +72,9 @@ type SchemaTypeMap = {
69
72
  'unknown[]?': unknown[] | undefined;
70
73
  };
71
74
  /** Checks if a schema field type is optional (ends with ?). */
72
- type IsOptionalField<T> = T extends `${string}?` ? true : false;
73
- /** Infers TypeScript type from a schema field (type string or nested object). */
74
- type InferSchemaField<T> = T extends SchemaType ? SchemaTypeMap[T] : T extends SchemaDefinition ? InferSchema<T> : never;
75
+ type IsOptionalField<T> = T extends `${string}?` ? true : T extends readonly [`${string}?`, string] ? true : false;
76
+ /** Infers TypeScript type from a schema field (type string, tuple, or nested object). */
77
+ type InferSchemaField<T> = T extends SchemaType ? SchemaTypeMap[T] : T extends readonly [infer S extends SchemaType, string] ? SchemaTypeMap[S] : T extends SchemaDefinition ? InferSchema<T> : never;
75
78
  /** Gets keys of required fields (non-optional types). */
76
79
  type RequiredKeys<T extends SchemaDefinition> = { [K in keyof T]: IsOptionalField<T[K]> extends true ? never : K }[keyof T];
77
80
  /** Gets keys of optional fields (types ending with ?). */
@@ -128,7 +131,7 @@ interface CompiledSchema<T> {
128
131
  * }
129
132
  * ```
130
133
  */
131
- declare function compileSchema<T extends SchemaDefinition>(schema: T): CompiledSchema<InferSchema<T>>;
134
+ declare function compileSchema<const T extends SchemaDefinition>(schema: T): CompiledSchema<InferSchema<T>>;
132
135
  //#endregion
133
136
  //#region src/types.d.ts
134
137
  /** Standard HTTP methods. */
@@ -221,8 +224,6 @@ interface RouteDefinition<Q extends SchemaDefinition = {}, B extends SchemaDefin
221
224
  description?: string;
222
225
  /** Operation name, used as the OpenAPI `operationId` and the MCP tool name. */
223
226
  operationId?: string;
224
- /** Field descriptions for docs and MCP, keyed by name (`address.city` for nested fields). */
225
- descriptions?: Record<string, string>;
226
227
  /** MCP tool settings. */
227
228
  mcp?: {
228
229
  annotations?: ToolAnnotations;
@@ -399,5 +400,5 @@ declare function runMiddleware(middleware: Middleware[], context: MiddlewareCont
399
400
  */
400
401
  declare function compose(...middleware: Middleware[]): Middleware;
401
402
  //#endregion
402
- export { InferSchema as C, ValidationResult as D, SchemaTypeMap as E, compileSchema as O, CompiledSchema as S, SchemaType as T, TypedHandler as _, runMiddleware as a, isRoute as b, ExecutionContext as c, MethodEntry as d, RouteDefinition as f, ToolAnnotations as g, RouterRoutes as h, compose as i, FetchHandler as l, RouterBrand as m, MiddlewareContext as n, CollectPathParams as o, Router as p, MiddlewareNext as r, Context as s, Middleware as t, Method as u, TypedResponse as v, SchemaDefinition as w, isRouter as x, isFunction as y };
403
- //# sourceMappingURL=middleware-zRMBpTLe.d.mts.map
403
+ export { InferSchema as C, SchemaTypeMap as D, SchemaType as E, ValidationResult as O, CompiledSchema as S, SchemaField as T, TypedHandler as _, runMiddleware as a, isRoute as b, ExecutionContext as c, MethodEntry as d, RouteDefinition as f, ToolAnnotations as g, RouterRoutes as h, compose as i, compileSchema as k, FetchHandler as l, RouterBrand as m, MiddlewareContext as n, CollectPathParams as o, Router as p, MiddlewareNext as r, Context as s, Middleware as t, Method as u, TypedResponse as v, SchemaDefinition as w, isRouter as x, isFunction as y };
404
+ //# sourceMappingURL=middleware-Cj1yHSJF.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"middleware-Cj1yHSJF.d.mts","names":[],"sources":["../src/schema.ts","../src/types.ts","../src/middleware.ts"],"sourcesContent":[],"mappings":";;AAuCA;AAGA;AAGA;AAGA;AAGA;;;;;;AAGA;AAGA;AAKA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AAA,KAAA,EAAA;EAAgB,CAAA,GExDL,CFwDK,GAAA,OAAA;AAI3C,CAAA,GE3DI,OF2Da,CE3DL,IF2DK,CE3DA,GF2DA,EAAe,KAAA,CAAA,CAAA,GAAA;EAKpB,CAAA,GAAA,EAAA,MAAA,CAAA,EAAA,OAAgB;AAK5B,CAAA;AA4NA;;;AAE8B,KE5RlB,cAAA,GF4RkB,GAAA,GE5RK,OF4RL,CE5Ra,QF4Rb,CAAA;;;;;;;AC9U9B;AAiBiE;AAUjE;AAiBA;;;;;;;AAQA;AAQA;;;;;;;;AAiBO,KCAK,UDAL,CAAA,MAAA,CAAA,CAAA,CAAA,GAAA,CAAA,OAAA,ECCI,iBDDJ,CCCsB,GDDtB,CAAA,EAAA,IAAA,ECEC,cDFD,EAAA,GCGF,ODHE,CCGM,QDHN,CAAA,GCGkB,QDHlB;;;;;AAMP;AAKA;;;;;;;AAOW,iBCDW,aAAA,CDCX,UAAA,ECAG,UDAH,EAAA,EAAA,OAAA,ECCA,iBDDA,EAAA,YAAA,EAAA,GAAA,GCEW,ODFX,CCEmB,QDFnB,CAAA,CAAA,ECGR,ODHQ,CCGA,QDHA,CAAA;;;;;;;;;;;AAIX;AA+BA;;;;;;;;AAkBoC,iBChBpB,OAAA,CDgBoB,GAAA,UAAA,EChBG,UDgBH,EAAA,CAAA,EChBkB,UDgBlB"}
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "bun": ">=1.3.14",
5
5
  "node": ">=22"
6
6
  },
7
- "version": "0.6.0",
7
+ "version": "0.6.2",
8
8
  "description": "Type-safe route definitions with auto-generated clients and OpenAPI docs",
9
9
  "license": "MIT",
10
10
  "author": "fresho.dev",
@@ -1 +0,0 @@
1
- {"version":3,"file":"docs-B1IFBS_w.mjs","names":["errors: Record<string, string[]>","resultArray: unknown[]","success","coerced","errorMsg","result: Record<string, unknown>","allErrors: Record<string, string[]>","properties: Record<string, unknown>","required: 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"],"sources":["../src/schema.ts","../src/types.ts","../src/handler.ts","../src/core.ts","../src/docs.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/** JSON Schema object produced by {@link toJsonSchema}. */\nexport interface JsonSchemaObject {\n type: 'object';\n properties: Record<string, unknown>;\n /** Omitted when empty, as OpenAPI 3.0 requires. */\n required?: string[];\n}\n\n/**\n * Converts a schema definition to JSON Schema, recursing into nested objects.\n *\n * @param descriptions - Field descriptions keyed by name, dotted for nested fields\n * @param prefix - Dotted path of `schema` within the root, for nested lookups\n */\nexport function toJsonSchema(\n schema: SchemaDefinition,\n descriptions: Record<string, string> = {},\n prefix = '',\n): JsonSchemaObject {\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n for (const [key, field] of Object.entries(schema)) {\n const description = descriptions[`${prefix}${key}`];\n const described = description === undefined ? {} : { description };\n if (isNestedSchema(field)) {\n const nested = toJsonSchema(field, descriptions, `${prefix}${key}.`);\n properties[key] = { ...nested, ...described };\n required.push(key);\n continue;\n }\n const optional = field.endsWith('?');\n const base = optional ? field.slice(0, -1) : field;\n const primitive = base.replace('[]', '');\n const item = primitive === 'unknown' ? {} : { type: primitive };\n properties[key] = base.endsWith('[]')\n ? { type: 'array', items: item, ...described }\n : { ...item, ...described };\n if (!optional) required.push(key);\n }\n return { type: 'object', properties, ...(required.length > 0 && { required }) };\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/** MCP tool behavior hints; defaults come from the HTTP method. */\nexport interface ToolAnnotations {\n /** Human-readable tool title. */\n title?: string;\n /** The tool does not modify its environment. */\n readOnlyHint?: boolean;\n /** The tool may perform destructive updates. */\n destructiveHint?: boolean;\n /** Repeating the call with the same arguments has no additional effect. */\n idempotentHint?: boolean;\n /** The tool interacts with external entities. */\n openWorldHint?: boolean;\n}\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 /** Operation name, used as the OpenAPI `operationId` and the MCP tool name. */\n operationId?: string;\n /** Field descriptions for docs and MCP, keyed by name (`address.city` for nested fields). */\n descriptions?: Record<string, string>;\n /** MCP tool settings. */\n mcp?: { annotations?: ToolAnnotations };\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, toJsonSchema } 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. */\nexport interface 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, with `{param}` path segments. */\nexport function 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 operationId: route?.operationId,\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 description: route.descriptions?.[name],\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 operation.requestBody = {\n required: true,\n content: {\n 'application/json': {\n schema: toJsonSchema(route.body as SchemaDefinition, route.descriptions),\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"],"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,M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