blaizejs 0.2.0 → 0.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/index.cjs +1976 -1560
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +731 -22
- package/dist/index.d.ts +731 -22
- package/dist/index.js +1981 -1560
- package/dist/index.js.map +1 -1
- package/package.json +6 -5
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/middleware/create.ts","../src/middleware/execute.ts","../src/middleware/compose.ts","../src/plugins/create.ts","../src/router/discovery/finder.ts","../src/router/discovery/parser.ts","../src/router/discovery/loader.ts","../src/router/discovery/index.ts","../src/router/discovery/watchers.ts","../src/router/handlers/error.ts","../src/router/validation/body.ts","../src/router/validation/params.ts","../src/router/validation/query.ts","../src/router/validation/response.ts","../src/router/validation/schema.ts","../src/router/handlers/executor.ts","../src/router/matching/params.ts","../src/router/matching/matcher.ts","../src/router/router.ts","../src/config.ts","../src/router/create.ts","../src/server/create.ts","../src/server/start.ts","../src/server/dev-certificate.ts","../src/context/errors.ts","../src/context/store.ts","../src/context/create.ts","../src/server/request-handler.ts","../src/server/stop.ts","../src/server/validation.ts","../src/plugins/lifecycle.ts","../src/plugins/errors.ts","../src/plugins/validation.ts"],"sourcesContent":["/**\n * BlaizeJS Core\n *\n * A blazing-fast, type-safe Node.js framework with file-based routing,\n * powerful middleware, and end-to-end type safety.\n *\n * @package blaizejs\n */\n\n// Explicit imports to avoid using values without importing\nimport type { BuildRoutesRegistry } from '@blaizejs/types';\n\nimport { create as createMiddleware, compose } from './middleware';\nimport { create as createPlugin } from './plugins';\nimport {\n createDeleteRoute,\n createGetRoute,\n createHeadRoute,\n createOptionsRoute,\n createPatchRoute,\n createPostRoute,\n createPutRoute,\n} from './router/';\nimport { create as createServer } from './server';\n\n// Re-export everything\n// Server module exports\nexport { createServer };\n\n// Router module exports\nexport {\n createDeleteRoute,\n createGetRoute,\n createHeadRoute,\n createOptionsRoute,\n createPatchRoute,\n createPostRoute,\n createPutRoute,\n};\n\n// Middleware module exports\nexport { createMiddleware, compose };\n\n// Plugins module exports\nexport { createPlugin };\n\n// Version information\nexport const VERSION = '0.1.0';\n\n// Namespaced exports with different names to avoid conflicts\nexport const ServerAPI = { createServer };\nexport const RouterAPI = {\n createDeleteRoute,\n createGetRoute,\n createHeadRoute,\n createOptionsRoute,\n createPatchRoute,\n createPostRoute,\n createPutRoute,\n};\nexport const MiddlewareAPI = { createMiddleware, compose };\nexport const PluginsAPI = { createPlugin };\n\n// Default export\nconst Blaize = {\n // Core functions\n createServer,\n createMiddleware,\n createPlugin,\n\n // Namespaces (using the non-conflicting names)\n Server: ServerAPI,\n Router: RouterAPI,\n Middleware: MiddlewareAPI,\n Plugins: PluginsAPI,\n\n // Constants\n VERSION,\n};\n\nexport type { BuildRoutesRegistry };\nexport default Blaize;\nexport { Blaize };\n","import { Middleware, MiddlewareFunction, MiddlewareOptions } from '@blaizejs/types';\n\n/**\n * Create a middleware\n */\nexport function create(handlerOrOptions: MiddlewareFunction | MiddlewareOptions): Middleware {\n // If handlerOrOptions is a function, convert it to our middleware object format\n if (typeof handlerOrOptions === 'function') {\n return {\n name: 'anonymous', // Default name for function middleware\n execute: handlerOrOptions,\n debug: false,\n };\n }\n\n // Otherwise, handle it as middleware options\n const { name = 'anonymous', handler, skip, debug = false } = handlerOrOptions;\n\n // Create base middleware object with required properties\n const middleware: Middleware = {\n name,\n execute: handler,\n debug,\n };\n\n if (skip !== undefined) {\n return {\n ...middleware,\n skip,\n };\n }\n\n return middleware;\n}\n","import { Context, Middleware, NextFunction } from '@blaizejs/types';\n\n/**\n * Execute a single middleware, handling both function and object forms\n */\nexport function execute(\n middleware: Middleware | undefined,\n ctx: Context,\n next: NextFunction\n): Promise<void> {\n // Handle undefined middleware (safety check)\n if (!middleware) {\n return Promise.resolve(next());\n }\n\n // Handle middleware with skip function\n if (middleware.skip && middleware.skip(ctx)) {\n return Promise.resolve(next());\n }\n\n try {\n // Execute middleware\n const result = middleware.execute(ctx, next);\n\n // Handle both Promise and non-Promise returns\n if (result instanceof Promise) {\n // Return the promise directly to allow errors to propagate\n return result;\n } else {\n // Only wrap non-Promise returns\n return Promise.resolve(result);\n }\n } catch (error) {\n // Handle synchronous errors\n return Promise.reject(error);\n }\n}\n","import { Context, Middleware, MiddlewareFunction, NextFunction } from '@blaizejs/types';\n\nimport { execute } from './execute';\n\n/**\n * Compose multiple middleware functions into a single middleware function\n */\nexport function compose(middlewareStack: Middleware[]): MiddlewareFunction {\n // No middleware? Return a pass-through function\n if (middlewareStack.length === 0) {\n return async (_, next) => {\n await Promise.resolve(next());\n };\n }\n\n // Return a function that executes the middleware stack\n return async function (ctx: Context, finalHandler: NextFunction): Promise<void> {\n // Keep track of which \"next\" functions have been called\n const called = new Set<number>();\n\n // Create dispatch function to process middleware stack\n const dispatch = async (i: number): Promise<void> => {\n // If we've reached the end of the stack, execute the final handler\n if (i >= middlewareStack.length) {\n // Ensure we're returning a Promise regardless of what finalHandler returns\n return Promise.resolve(finalHandler());\n }\n\n // Get current middleware\n const middleware = middlewareStack[i];\n\n // Create a next function that can only be called once\n const nextDispatch = () => {\n if (called.has(i)) {\n throw new Error('next() called multiple times');\n }\n\n // Mark this middleware's next as called\n called.add(i);\n\n // Move to the next middleware\n return dispatch(i + 1);\n };\n\n // Use the executeMiddleware function we defined\n return execute(middleware, ctx, nextDispatch);\n };\n\n // Start middleware chain execution\n return dispatch(0);\n };\n}\n","import { Plugin, PluginFactory, PluginHooks, Server } from '@blaizejs/types';\n\n/**\n * Create a plugin with the given name, version, and setup function\n */\nexport function create<T = any>(\n name: string,\n version: string,\n setup: (\n app: Server,\n options: T\n ) => void | Partial<PluginHooks> | Promise<void> | Promise<Partial<PluginHooks>>,\n defaultOptions: Partial<T> = {}\n): PluginFactory<T> {\n // Input validation\n if (!name || typeof name !== 'string') {\n throw new Error('Plugin name must be a non-empty string');\n }\n\n if (!version || typeof version !== 'string') {\n throw new Error('Plugin version must be a non-empty string');\n }\n\n if (typeof setup !== 'function') {\n throw new Error('Plugin setup must be a function');\n }\n\n // Return the factory function\n return function pluginFactory(userOptions?: Partial<T>) {\n // Merge default options with user options\n const mergedOptions = { ...defaultOptions, ...userOptions } as T;\n\n // Create the base plugin object\n const plugin: Plugin = {\n name,\n version,\n\n // The register hook calls the user's setup function\n register: async (app: Server) => {\n const result = await setup(app, mergedOptions);\n\n // If setup returns hooks, merge them into this plugin\n if (result && typeof result === 'object') {\n // Now we explicitly assign to our plugin object\n Object.assign(plugin, result);\n }\n },\n };\n\n return plugin;\n };\n}\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\n\ninterface FindRouteFilesOptions {\n /** Directories to ignore */\n ignore?: string[] | undefined;\n}\n\n/**\n * Find all route files in the specified directory\n */\nexport async function findRouteFiles(\n routesDir: string,\n options: FindRouteFilesOptions = {}\n): Promise<string[]> {\n // Convert to absolute path if it's relative\n const absoluteDir = path.isAbsolute(routesDir)\n ? routesDir\n : path.resolve(process.cwd(), routesDir);\n\n console.log('Creating router with routes directory:', absoluteDir);\n\n // Check if directory exists\n try {\n const stats = await fs.stat(absoluteDir);\n if (!stats.isDirectory()) {\n throw new Error(`Route directory is not a directory: ${absoluteDir}`);\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new Error(`Route directory not found: ${absoluteDir}`);\n }\n throw error;\n }\n\n const routeFiles: string[] = [];\n const ignore = options.ignore || ['node_modules', '.git'];\n\n async function scanDirectory(dir: string) {\n const entries = await fs.readdir(dir, { withFileTypes: true });\n\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n\n // Skip ignored directories\n if (entry.isDirectory() && ignore.includes(entry.name)) {\n continue;\n }\n\n if (entry.isDirectory()) {\n await scanDirectory(fullPath);\n } else if (isRouteFile(entry.name)) {\n routeFiles.push(fullPath);\n }\n }\n }\n\n await scanDirectory(absoluteDir);\n return routeFiles;\n}\n\n/**\n * Check if a file is a valid route file\n */\nfunction isRouteFile(filename: string): boolean {\n // Route files are TypeScript/JavaScript files that don't start with underscore\n return !filename.startsWith('_') && (filename.endsWith('.ts') || filename.endsWith('.js'));\n}\n","import * as path from 'node:path';\n\nimport { ParsedRoute } from '@blaizejs/types';\n\n/**\n * Parse a file path into a route path\n * Works consistently across Windows and Unix-like file systems\n */\nexport function parseRoutePath(filePath: string, basePath: string): ParsedRoute {\n // Clean file:// URLs if present\n if (filePath.startsWith('file://')) {\n filePath = filePath.replace('file://', '');\n }\n if (basePath.startsWith('file://')) {\n basePath = basePath.replace('file://', '');\n }\n\n // Convert all backslashes to forward slashes for consistent handling\n const forwardSlashFilePath = filePath.replace(/\\\\/g, '/');\n const forwardSlashBasePath = basePath.replace(/\\\\/g, '/');\n\n // Ensure the base path ends with a slash for proper prefix removal\n const normalizedBasePath = forwardSlashBasePath.endsWith('/')\n ? forwardSlashBasePath\n : `${forwardSlashBasePath}/`;\n\n // Remove the base path to get the relative path\n let relativePath = forwardSlashFilePath;\n if (forwardSlashFilePath.startsWith(normalizedBasePath)) {\n relativePath = forwardSlashFilePath.substring(normalizedBasePath.length);\n } else if (forwardSlashFilePath.startsWith(forwardSlashBasePath)) {\n relativePath = forwardSlashFilePath.substring(forwardSlashBasePath.length);\n // If base path didn't end with a slash but we still matched, ensure relative path doesn't start with a slash\n if (relativePath.startsWith('/')) {\n relativePath = relativePath.substring(1);\n }\n } else {\n // If base path isn't a prefix of file path, use path.relative as a fallback\n // But convert to forward slashes for consistency\n relativePath = path.relative(forwardSlashBasePath, forwardSlashFilePath).replace(/\\\\/g, '/');\n }\n\n // Remove file extension (anything after the last dot)\n relativePath = relativePath.replace(/\\.[^.]+$/, '');\n\n // Split the path into segments\n const segments = relativePath.split('/').filter(Boolean);\n const params: string[] = [];\n\n // Transform file path segments to route path segments\n const routeSegments = segments.map(segment => {\n // Handle dynamic parameters ([param])\n if (segment.startsWith('[') && segment.endsWith(']')) {\n const paramName = segment.slice(1, -1);\n params.push(paramName);\n return `:${paramName}`;\n }\n return segment;\n });\n\n // Create the final route path\n let routePath = routeSegments.length > 0 ? `/${routeSegments.join('/')}` : '/';\n\n // Handle index routes\n if (routePath.endsWith('/index')) {\n routePath = routePath.slice(0, -6) || '/';\n }\n\n return {\n filePath,\n routePath,\n params,\n };\n}\n","import { Route, RouteDefinition } from '@blaizejs/types';\n\nimport { parseRoutePath } from './parser';\n\nexport async function dynamicImport(filePath: string) {\n return import(filePath);\n}\n\n/**\n * Load route modules from a file - supports both default export and named exports\n */\nexport async function loadRouteModule(filePath: string, basePath: string): Promise<Route[]> {\n try {\n // Parse the route path from the file path\n const parsedRoute = parseRoutePath(filePath, basePath);\n console.log('parsedRoute:', parsedRoute);\n\n // Dynamically import the module\n const module = await dynamicImport(filePath);\n console.log('Module exports:', Object.keys(module));\n\n const routes: Route[] = [];\n\n // Method 1: Check for default export (existing pattern)\n if (module.default && typeof module.default === 'object') {\n console.log('Found default export:', module.default);\n\n const route: Route = {\n ...(module.default as RouteDefinition),\n path: parsedRoute.routePath,\n };\n\n routes.push(route);\n }\n\n // Method 2: Check for named exports that look like routes\n Object.entries(module).forEach(([exportName, exportValue]) => {\n // Skip default export (already handled) and non-objects\n if (exportName === 'default' || !exportValue || typeof exportValue !== 'object') {\n return;\n }\n\n // Check if this export looks like a route (has path property and HTTP methods)\n const potentialRoute = exportValue as any;\n\n if (isValidRoute(potentialRoute)) {\n console.log(`Found named route export: ${exportName}`, potentialRoute);\n\n // For named exports, we might want to use the export name or the route's path\n const route: Route = {\n ...potentialRoute,\n // Use the route's own path if it has one, otherwise derive from file\n path: parsedRoute.routePath,\n };\n\n routes.push(route);\n }\n });\n\n if (routes.length === 0) {\n console.warn(`Route file ${filePath} does not export any valid route definitions`);\n return [];\n }\n\n console.log(`Loaded ${routes.length} route(s) from ${filePath}`);\n return routes;\n } catch (error) {\n console.error(`Failed to load route module ${filePath}:`, error);\n return [];\n }\n}\n\n/**\n * Check if an object looks like a valid route\n */\nfunction isValidRoute(obj: any): boolean {\n if (!obj || typeof obj !== 'object') {\n return false;\n }\n\n // Check if it has at least one HTTP method\n const httpMethods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'];\n const hasHttpMethod = httpMethods.some(\n method => obj[method] && typeof obj[method] === 'object' && obj[method].handler\n );\n\n return hasHttpMethod;\n}\n","import { Route } from '@blaizejs/types';\n\nimport { findRouteFiles } from './finder';\nimport { loadRouteModule } from './loader';\n\nexport interface FindRoutesOptions {\n /** Base path for routes */\n basePath?: string;\n /** Ignore patterns for directory scanning */\n ignore?: string[];\n}\n\n/**\n * Find all routes in the specified directory\n */\nexport async function findRoutes(\n routesDir: string,\n options: FindRoutesOptions = {}\n): Promise<Route[]> {\n // Find all route files\n const routeFiles = await findRouteFiles(routesDir, {\n ignore: options.ignore,\n });\n\n // Load all route modules\n const routes: Route[] = [];\n for (const filePath of routeFiles) {\n const moduleRoutes = await loadRouteModule(filePath, routesDir);\n if (moduleRoutes.length > 0) {\n routes.push(...moduleRoutes);\n }\n }\n\n return routes;\n}\n","import * as path from 'node:path';\n\nimport { watch } from 'chokidar';\n\nimport { Route } from '@blaizejs/types';\n\nimport { findRouteFiles } from './finder';\nimport { loadRouteModule } from './loader';\n\nexport interface WatchOptions {\n /** Directories to ignore */\n ignore?: string[];\n /** Callback for new routes */\n onRouteAdded?: (routes: Route[]) => void;\n /** Callback for changed routes */\n onRouteChanged?: (routes: Route[]) => void;\n /** Callback for removed routes */\n onRouteRemoved?: (filePath: string, routes: Route[]) => void;\n /** Callback for errors */\n onError?: (error: Error) => void;\n}\n\n/**\n * Watch for route file changes\n */\nexport function watchRoutes(routesDir: string, options: WatchOptions = {}) {\n // Track loaded routes by file path - now stores arrays of routes\n const routesByPath = new Map<string, Route[]>();\n\n // Initial loading of routes\n async function loadInitialRoutes() {\n try {\n const files = await findRouteFiles(routesDir, {\n ignore: options.ignore,\n });\n\n for (const filePath of files) {\n await loadAndNotify(filePath);\n }\n } catch (error) {\n handleError(error);\n }\n }\n\n // Load a route module and notify listeners\n async function loadAndNotify(filePath: string) {\n try {\n const routes = await loadRouteModule(filePath, routesDir);\n\n if (!routes || routes.length === 0) {\n return;\n }\n\n const existingRoutes = routesByPath.get(filePath);\n\n if (existingRoutes) {\n // Routes changed\n routesByPath.set(filePath, routes);\n\n if (options.onRouteChanged) {\n options.onRouteChanged(routes);\n }\n } else {\n // New routes\n routesByPath.set(filePath, routes);\n\n if (options.onRouteAdded) {\n options.onRouteAdded(routes);\n }\n }\n } catch (error) {\n handleError(error);\n }\n }\n\n // Handle route file removal\n function handleRemoved(filePath: string) {\n const normalizedPath = path.normalize(filePath);\n const routes = routesByPath.get(normalizedPath);\n\n if (routes && routes.length > 0 && options.onRouteRemoved) {\n options.onRouteRemoved(normalizedPath, routes);\n }\n\n routesByPath.delete(normalizedPath);\n }\n\n // Handle errors\n function handleError(error: unknown) {\n if (options.onError && error instanceof Error) {\n options.onError(error);\n } else {\n console.error('Route watcher error:', error);\n }\n }\n\n // Start file watcher\n const watcher = watch(routesDir, {\n ignored: [\n /(^|[/\\\\])\\../, // Ignore dot files\n /node_modules/,\n ...(options.ignore || []),\n ],\n persistent: true,\n ignoreInitial: false,\n awaitWriteFinish: {\n stabilityThreshold: 300,\n pollInterval: 100,\n },\n });\n\n // Set up event handlers\n watcher\n .on('add', loadAndNotify)\n .on('change', loadAndNotify)\n .on('unlink', handleRemoved)\n .on('error', handleError);\n\n // Load initial routes\n loadInitialRoutes().catch(handleError);\n\n // Return control methods\n return {\n /**\n * Close the watcher\n */\n close: () => watcher.close(),\n\n /**\n * Get all currently loaded routes (flattened)\n */\n getRoutes: () => {\n const allRoutes: Route[] = [];\n for (const routes of routesByPath.values()) {\n allRoutes.push(...routes);\n }\n return allRoutes;\n },\n\n /**\n * Get routes organized by file path\n */\n getRoutesByFile: () => new Map(routesByPath),\n };\n}\n","import { Context, ErrorHandlerOptions } from '@blaizejs/types';\n\n/**\n * Handle a route error\n */\nexport function handleRouteError(\n ctx: Context,\n error: unknown,\n options: ErrorHandlerOptions = {}\n): void {\n // Log error if enabled\n if (options.log) {\n console.error('Route error:', error);\n }\n\n // Determine error status code\n const status = getErrorStatus(error);\n\n // Build error response\n const response: Record<string, unknown> = {\n error: getErrorType(error),\n message: getErrorMessage(error),\n };\n\n // Add details if enabled\n if (options.detailed) {\n // Add stack trace for Error instances\n if (error instanceof Error) {\n response.stack = error.stack;\n }\n\n // Add validation details if available (for any type of error)\n if (error && typeof error === 'object' && 'details' in error && error.details) {\n response.details = error.details;\n }\n }\n\n // Send error response\n ctx.response.status(status).json(response);\n}\n\n/**\n * Get the HTTP status code for an error\n */\nfunction getErrorStatus(error: unknown): number {\n if (error && typeof error === 'object') {\n // Check for status property\n if ('status' in error && typeof error.status === 'number') {\n return error.status;\n }\n\n // Check for statusCode property\n if ('statusCode' in error && typeof error.statusCode === 'number') {\n return error.statusCode;\n }\n\n // Check for code property that maps to status\n if ('code' in error && typeof error.code === 'string') {\n return getStatusFromCode(error.code);\n }\n }\n\n // Default to 500 for unknown errors\n return 500;\n}\n\n/**\n * Get a status code from an error code\n */\nfunction getStatusFromCode(code: string): number {\n switch (code) {\n case 'NOT_FOUND':\n return 404;\n case 'UNAUTHORIZED':\n return 401;\n case 'FORBIDDEN':\n return 403;\n case 'BAD_REQUEST':\n return 400;\n case 'CONFLICT':\n return 409;\n default:\n return 500;\n }\n}\n\n/**\n * Get the error type\n */\nfunction getErrorType(error: unknown): string {\n if (error && typeof error === 'object') {\n if ('type' in error && typeof error.type === 'string') {\n return error.type;\n }\n\n if ('name' in error && typeof error.name === 'string') {\n return error.name;\n }\n\n if (error instanceof Error) {\n return error.constructor.name;\n }\n }\n\n return 'Error';\n}\n\n/**\n * Get the error message\n */\nfunction getErrorMessage(error: unknown): string {\n if (error instanceof Error) {\n return error.message;\n }\n\n if (error && typeof error === 'object') {\n if ('message' in error && typeof error.message === 'string') {\n return error.message;\n }\n }\n\n return String(error);\n}\n","import { z } from 'zod';\n\n/**\n * Validate request body\n */\nexport function validateBody<T>(body: unknown, schema: z.ZodType<T>): T {\n if (schema instanceof z.ZodObject) {\n return schema.strict().parse(body) as T;\n }\n // Parse and validate with the provided schema\n return schema.parse(body);\n}\n","import { z } from 'zod';\n\n/**\n * Validate request parameters\n */\nexport function validateParams<T>(\n params: Record<string, string>,\n schema: z.ZodType<T, z.ZodTypeDef, unknown>\n): T {\n if (schema instanceof z.ZodObject) {\n // If schema is an object, ensure strict parsing\n return schema.strict().parse(params) as T;\n }\n // Parse and validate with the provided schema\n return schema.parse(params);\n}\n","import { z } from 'zod';\n\n/**\n * Validate query parameters\n */\nexport function validateQuery<T>(\n query: Record<string, string | string[] | undefined>,\n schema: z.ZodType<T, z.ZodTypeDef, unknown>\n): T {\n if (schema instanceof z.ZodObject) {\n // If schema is an object, ensure strict parsing\n return schema.strict().parse(query) as T;\n }\n // Parse and validate with the provided schema\n return schema.parse(query);\n}\n","import { z } from 'zod';\n\n/**\n * Validate response body\n */\nexport function validateResponse<T>(\n response: unknown,\n schema: z.ZodType<T, z.ZodTypeDef, unknown>\n): T {\n if (schema instanceof z.ZodObject) {\n return schema.strict().parse(response) as T;\n }\n // Parse and validate with the provided schema\n return schema.parse(response);\n}\n","import { z } from 'zod';\n\nimport {\n RouteSchema,\n Context,\n Middleware,\n MiddlewareFunction,\n NextFunction,\n} from '@blaizejs/types';\n\nimport { validateBody } from './body';\nimport { validateParams } from './params';\nimport { validateQuery } from './query';\nimport { validateResponse } from './response';\n\n/**\n * Create a validation middleware for request data\n */\nexport function createRequestValidator(schema: RouteSchema, debug: boolean = false): Middleware {\n const middlewareFn: MiddlewareFunction = async (ctx: Context, next: NextFunction) => {\n const errors: Record<string, unknown> = {};\n\n // Validate params if schema exists\n if (schema.params && ctx.request.params) {\n try {\n ctx.request.params = validateParams(ctx.request.params, schema.params);\n } catch (error) {\n errors.params = formatValidationError(error);\n }\n }\n\n // Validate query if schema exists\n if (schema.query && ctx.request.query) {\n try {\n ctx.request.query = validateQuery(ctx.request.query, schema.query);\n } catch (error) {\n errors.query = formatValidationError(error);\n }\n }\n\n // FIXED: Validate body if schema exists (regardless of body content)\n if (schema.body) {\n try {\n ctx.request.body = validateBody(ctx.request.body, schema.body);\n } catch (error) {\n errors.body = formatValidationError(error);\n }\n }\n\n // Handle validation errors\n if (Object.keys(errors).length > 0) {\n ctx.response.status(400).json({\n error: 'Validation Error',\n details: errors,\n });\n return;\n }\n\n // Continue if validation passed\n await next();\n };\n\n return {\n name: 'RequestValidator',\n execute: middlewareFn,\n debug,\n };\n}\n\n/**\n * Create a validation middleware for response data\n */\nexport function createResponseValidator<T>(\n responseSchema: z.ZodType<T, z.ZodTypeDef, unknown>,\n debug: boolean = false\n): Middleware {\n const middlewareFn: MiddlewareFunction = async (ctx, next) => {\n // Store the original json method\n const originalJson = ctx.response.json;\n\n // Override the json method to validate the response\n ctx.response.json = (body: unknown, status?: number) => {\n try {\n // Validate the response body\n const validatedBody = validateResponse(body, responseSchema);\n\n // Restore the original json method\n ctx.response.json = originalJson;\n\n // Send the validated response\n return originalJson.call(ctx.response, validatedBody, status);\n } catch (error) {\n // Restore the original json method\n ctx.response.json = originalJson;\n\n // Log validation error but don't expose to client\n console.error('Response validation error:', error);\n\n // Send an error response\n ctx.response.status(500).json({\n error: 'Internal Server Error',\n message: 'Response validation failed',\n });\n\n return ctx.response;\n }\n };\n\n await next();\n };\n\n return {\n name: 'ResponseValidator',\n execute: middlewareFn,\n debug,\n };\n}\n\n/**\n * Format a validation error\n */\nexport function formatValidationError(error: unknown): unknown {\n // Handle Zod errors\n if (\n error &&\n typeof error === 'object' &&\n 'format' in error &&\n typeof error.format === 'function'\n ) {\n return error.format();\n }\n\n // Handle other error types\n return error instanceof Error ? error.message : String(error);\n}\n","import { Context, RouteMethodOptions } from '@blaizejs/types';\n\nimport { compose } from '../../middleware/compose';\nimport { createRequestValidator, createResponseValidator } from '../validation';\n\n/**\n * Execute a route handler with its middleware\n */\nexport async function executeHandler(\n ctx: Context,\n routeOptions: RouteMethodOptions,\n params: Record<string, string>\n): Promise<void> {\n // Set up middleware chain\n const middleware = [...(routeOptions.middleware || [])];\n\n // Add validation middleware if schemas are defined\n if (routeOptions.schema) {\n if (routeOptions.schema.params || routeOptions.schema.query || routeOptions.schema.body) {\n middleware.unshift(createRequestValidator(routeOptions.schema));\n }\n\n if (routeOptions.schema.response) {\n middleware.push(createResponseValidator(routeOptions.schema.response));\n }\n }\n\n // Compose middleware with the final handler\n const handler = compose([...middleware]);\n\n // Execute the middleware chain\n await handler(ctx, async () => {\n // Execute the handler with the new argument style\n const result = await routeOptions.handler(ctx, params);\n\n // Handle the result if it wasn't already handled by the handler\n if (!ctx.response.sent && result !== undefined) {\n ctx.response.json(result);\n }\n });\n}\n","/**\n * Extract parameter values from a URL path\n */\nexport function extractParams(\n path: string,\n pattern: RegExp,\n paramNames: string[]\n): Record<string, string> {\n const match = pattern.exec(path);\n if (!match) {\n return {};\n }\n\n const params: Record<string, string> = {};\n\n // Extract parameter values from regex match groups\n for (let i = 0; i < paramNames.length; i++) {\n // Add 1 to index since the first capture group is at index 1\n params[paramNames[i]!] = match[i + 1] || '';\n }\n\n return params;\n}\n\n/**\n * Compile a path pattern with parameters\n */\nexport function compilePathPattern(path: string): { pattern: RegExp; paramNames: string[] } {\n const paramNames: string[] = [];\n\n // Special case for root path\n if (path === '/') {\n return {\n pattern: /^\\/$/,\n paramNames: [],\n };\n }\n\n // First escape special regex characters (except for : and [ ] which we process specially)\n let patternString = path.replace(/([.+*?^$(){}|\\\\])/g, '\\\\$1');\n\n // Replace route parameters with regex capture groups\n patternString = patternString\n // Replace :param syntax with capture groups\n .replace(/\\/:([^/]+)/g, (_, paramName) => {\n paramNames.push(paramName);\n return '/([^/]+)';\n })\n // Replace [param] syntax (for file-based routing)\n .replace(/\\/\\[([^\\]]+)\\]/g, (_, paramName) => {\n paramNames.push(paramName);\n return '/([^/]+)';\n });\n\n // Make the trailing slash optional (if not already the root path)\n // This adds an optional trailing slash to the end of the pattern\n patternString = `${patternString}(?:/)?`;\n\n // Create the regex pattern\n // This is safe because we've escaped special RegExp characters and\n // we're using developer-defined routes, not user input\n const pattern = new RegExp(`^${patternString}$`);\n\n return {\n pattern,\n paramNames,\n };\n}\n\n/**\n * Convert parameters object to URL query string\n */\nexport function paramsToQuery(params: Record<string, string | number | boolean>): string {\n const parts: string[] = [];\n\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined && value !== null) {\n const encodedKey = encodeURIComponent(key);\n const encodedValue = encodeURIComponent(String(value));\n parts.push(`${encodedKey}=${encodedValue}`);\n }\n }\n\n return parts.length > 0 ? `?${parts.join('&')}` : '';\n}\n\n/**\n * Build a URL with path parameters\n */\nexport function buildUrl(\n pathPattern: string,\n params: Record<string, string | number | boolean> = {},\n query: Record<string, string | number | boolean> = {}\n): string {\n // Extract path parameters and query parameters\n const pathParams: Record<string, string | number | boolean> = {};\n const queryParams: Record<string, string | number | boolean> = { ...query };\n\n // Find all parameter names in the path\n const paramNames: string[] = [];\n pathPattern.replace(/\\/:([^/]+)/g, (_, paramName) => {\n paramNames.push(paramName);\n return '/';\n });\n\n // Separate params into path params and additional query params\n for (const [key, value] of Object.entries(params)) {\n if (paramNames.includes(key)) {\n pathParams[key] = value;\n } else {\n queryParams[key] = value;\n }\n }\n\n // Replace path parameters\n let url = pathPattern;\n for (const [key, value] of Object.entries(pathParams)) {\n url = url.replace(`:${key}`, encodeURIComponent(String(value)));\n }\n\n // Add query string if needed\n const queryString = paramsToQuery(queryParams);\n\n return url + queryString;\n}\n","import { HttpMethod, RouteMethodOptions, RouteMatch, Matcher, RouteEntry } from '@blaizejs/types';\n\nimport { compilePathPattern, extractParams } from './params';\n\n/**\n * Create a route matcher\n */\nexport function createMatcher(): Matcher {\n // Private state\n const routes: RouteEntry[] = [];\n\n return {\n /**\n * Add a route to the matcher\n */\n add(path: string, method: HttpMethod, routeOptions: RouteMethodOptions) {\n const { pattern, paramNames } = compilePathPattern(path);\n\n const newRoute: RouteEntry = {\n path,\n method,\n pattern,\n paramNames,\n routeOptions,\n };\n\n // Find the insertion point using findIndex\n const insertIndex = routes.findIndex(route => paramNames.length < route.paramNames.length);\n\n // If no insertion point found, append to end\n if (insertIndex === -1) {\n routes.push(newRoute);\n } else {\n routes.splice(insertIndex, 0, newRoute);\n }\n },\n\n /**\n * Match a URL path to a route\n */\n match(path: string, method: HttpMethod): RouteMatch | null {\n // First, try to find an exact match for the method\n const pathname = path.split('?')[0];\n if (!pathname) return null;\n\n for (const route of routes) {\n // Skip routes that don't match the method\n if (route.method !== method) continue;\n\n // Try to match the path\n const match = route.pattern.exec(pathname);\n if (match) {\n // Extract parameters from the match\n const params = extractParams(path, route.pattern, route.paramNames);\n\n return {\n route: route.routeOptions,\n params,\n };\n }\n }\n\n // If no exact method match, check if path exists but method is different\n // This allows returning 405 Method Not Allowed instead of 404 Not Found\n const matchingPath = routes.find(\n route => route.method !== method && route.pattern.test(path)\n );\n\n if (matchingPath) {\n // Return null but with allowedMethods to indicate method not allowed\n return {\n route: null,\n params: {},\n methodNotAllowed: true,\n allowedMethods: routes\n .filter(route => route.pattern.test(path))\n .map(route => route.method),\n } as unknown as RouteMatch; // Type assertion for the extended return type\n }\n\n return null; // No match found\n },\n\n /**\n * Get all registered routes\n */\n getRoutes(): { path: string; method: HttpMethod }[] {\n return routes.map(route => ({\n path: route.path,\n method: route.method,\n }));\n },\n\n /**\n * Find routes matching a specific path\n */\n findRoutes(\n path: string\n ): { path: string; method: HttpMethod; params: Record<string, string> }[] {\n return routes\n .filter(route => route.pattern.test(path))\n .map(route => ({\n path: route.path,\n method: route.method,\n params: extractParams(path, route.pattern, route.paramNames),\n }));\n },\n };\n}\n","import {\n Context,\n HttpMethod,\n Route,\n RouteMethodOptions,\n RouterOptions,\n Router,\n} from '@blaizejs/types';\n\nimport { findRoutes } from './discovery';\nimport { watchRoutes } from './discovery/watchers';\nimport { executeHandler } from './handlers';\nimport { handleRouteError } from './handlers/error';\nimport { createMatcher } from './matching';\n\nconst DEFAULT_ROUTER_OPTIONS = {\n routesDir: './routes',\n basePath: '/',\n watchMode: process.env.NODE_ENV === 'development',\n};\n\n/**\n * Create a router instance\n */\nexport function createRouter(options: RouterOptions): Router {\n // Merge with default options\n const routerOptions = {\n ...DEFAULT_ROUTER_OPTIONS,\n ...options,\n };\n\n if (options.basePath && !options.basePath.startsWith('/')) {\n console.warn('Base path does nothing');\n }\n // Internal state\n const routes: Route[] = [];\n const matcher = createMatcher();\n\n // Initialize routes\n let initialized = false;\n let initializationPromise: Promise<void> | null = null;\n let _watchers: Map<string, ReturnType<typeof watchRoutes>> | null = null; // For plugin directories\n\n // Track route sources for conflict detection\n const routeSources = new Map<string, string[]>(); // path -> [source1, source2, ...]\n const routeDirectories = new Set<string>([routerOptions.routesDir]);\n\n /**\n * Add a route with source tracking\n */\n function addRouteWithSource(route: Route, source: string) {\n const existingSources = routeSources.get(route.path) || [];\n\n // Check if this exact route from this exact source already exists\n if (existingSources.includes(source)) {\n console.warn(`Skipping duplicate route: ${route.path} from ${source}`);\n return;\n }\n\n // Check for real conflicts (different sources)\n if (existingSources.length > 0) {\n const conflictError = new Error(\n `Route conflict for path \"${route.path}\": ` +\n `already defined in ${existingSources.join(', ')}, ` +\n `now being added from ${source}`\n );\n console.error(conflictError.message);\n throw conflictError;\n }\n\n // Track the source\n routeSources.set(route.path, [...existingSources, source]);\n\n // Add to router\n addRouteInternal(route);\n }\n\n /**\n * Load routes from a directory\n */\n async function loadRoutesFromDirectory(directory: string, source: string, prefix?: string) {\n try {\n const discoveredRoutes = await findRoutes(directory, {\n basePath: routerOptions.basePath,\n });\n\n for (const route of discoveredRoutes) {\n // Apply prefix if provided\n const finalRoute = prefix\n ? {\n ...route,\n path: `${prefix}${route.path}`,\n }\n : route;\n\n addRouteWithSource(finalRoute, source);\n }\n\n console.log(\n `Loaded ${discoveredRoutes.length} routes from ${source}${prefix ? ` with prefix ${prefix}` : ''}`\n );\n } catch (error) {\n console.error(`Failed to load routes from ${source}:`, error);\n throw error;\n }\n }\n\n /**\n * Initialize the router by loading routes from the filesystem\n */\n async function initialize() {\n if (initialized || initializationPromise) {\n return initializationPromise;\n }\n\n initializationPromise = (async () => {\n try {\n // Load routes from all registered directories\n for (const directory of routeDirectories) {\n await loadRoutesFromDirectory(directory, directory);\n }\n\n // Set up file watching in development if enabled\n if (routerOptions.watchMode) {\n setupWatcherForAllDirectories();\n }\n\n initialized = true;\n } catch (error) {\n console.error('Failed to initialize router:', error);\n throw error;\n }\n })();\n\n return initializationPromise;\n }\n\n /**\n * Add a route to the router\n */\n function addRouteInternal(route: Route) {\n routes.push(route);\n\n // Add each method to the matcher\n Object.entries(route).forEach(([method, methodOptions]) => {\n if (method === 'path' || !methodOptions) return;\n\n matcher.add(route.path, method as HttpMethod, methodOptions as RouteMethodOptions);\n });\n }\n\n /**\n * Create watcher callbacks for a specific directory\n */\n function createWatcherCallbacks(directory: string, source: string, prefix?: string) {\n return {\n onRouteAdded: (addedRoutes: Route[]) => {\n console.log(\n `${addedRoutes.length} route(s) added from ${directory}:`,\n addedRoutes.map(r => r.path)\n );\n addedRoutes.forEach(route => {\n const finalRoute = prefix ? { ...route, path: `${prefix}${route.path}` } : route;\n addRouteWithSource(finalRoute, source);\n });\n },\n\n onRouteChanged: (changedRoutes: Route[]) => {\n console.log(\n `${changedRoutes.length} route(s) changed in ${directory}:`,\n changedRoutes.map(r => r.path)\n );\n\n changedRoutes.forEach(route => {\n const finalPath = prefix ? `${prefix}${route.path}` : route.path;\n\n // Remove existing route with the same final path\n const index = routes.findIndex(r => r.path === finalPath);\n if (index >= 0) {\n routes.splice(index, 1);\n\n // Update source tracking\n const sources = routeSources.get(finalPath) || [];\n const filteredSources = sources.filter(s => s !== source);\n if (filteredSources.length > 0) {\n routeSources.set(finalPath, filteredSources);\n } else {\n routeSources.delete(finalPath);\n }\n }\n\n // Add the updated route\n const finalRoute = prefix ? { ...route, path: finalPath } : route;\n addRouteWithSource(finalRoute, source);\n });\n },\n\n onRouteRemoved: (filePath: string, removedRoutes: Route[]) => {\n console.log(\n `File removed from ${directory}: ${filePath} with ${removedRoutes.length} route(s):`,\n removedRoutes.map(r => r.path)\n );\n\n removedRoutes.forEach(route => {\n const finalPath = prefix ? `${prefix}${route.path}` : route.path;\n\n // Remove route from routes array\n const index = routes.findIndex(r => r.path === finalPath);\n if (index >= 0) {\n routes.splice(index, 1);\n }\n\n // Update source tracking\n const sources = routeSources.get(finalPath) || [];\n const filteredSources = sources.filter(s => s !== source);\n if (filteredSources.length > 0) {\n routeSources.set(finalPath, filteredSources);\n } else {\n routeSources.delete(finalPath);\n }\n });\n },\n\n onError: (error: Error) => {\n console.error(`Route watcher error for ${directory}:`, error);\n },\n };\n }\n\n /**\n * Set up file watcher for a specific directory\n */\n function setupWatcherForDirectory(directory: string, source: string, prefix?: string) {\n const callbacks = createWatcherCallbacks(directory, source, prefix);\n\n const watcher = watchRoutes(directory, {\n ignore: ['node_modules', '.git'],\n ...callbacks,\n });\n\n // Store watcher reference for cleanup\n if (!_watchers) {\n _watchers = new Map();\n }\n _watchers.set(directory, watcher);\n\n return watcher;\n }\n\n /**\n * Set up file watcher for all directories\n */\n function setupWatcherForAllDirectories() {\n for (const directory of routeDirectories) {\n setupWatcherForDirectory(directory, directory);\n }\n }\n\n initialize().catch(error => {\n console.error('Failed to initialize router on creation:', error);\n });\n // Public API\n return {\n /**\n * Handle an incoming request\n */\n async handleRequest(ctx: Context) {\n // Ensure router is initialized\n if (!initialized) {\n await initialize();\n }\n\n const { method, path } = ctx.request;\n\n // Find matching route\n const match = matcher.match(path, method as HttpMethod);\n\n if (!match) {\n // Handle 404 Not Found\n ctx.response.status(404).json({ error: 'Not Found' });\n return;\n }\n\n // Check for method not allowed\n if (match.methodNotAllowed) {\n // Handle 405 Method Not Allowed\n ctx.response.status(405).json({\n error: 'Method Not Allowed',\n allowed: match.allowedMethods,\n });\n\n // Set Allow header with allowed methods\n if (match.allowedMethods && match.allowedMethods.length > 0) {\n ctx.response.header('Allow', match.allowedMethods.join(', '));\n }\n\n return;\n }\n\n // Extract route parameters\n ctx.request.params = match.params;\n\n // Execute the route handler with middleware\n try {\n await executeHandler(ctx, match.route!, match.params);\n } catch (error) {\n // Handle errors\n handleRouteError(ctx, error, {\n detailed: process.env.NODE_ENV !== 'production',\n log: true,\n });\n }\n },\n\n /**\n * Get all registered routes\n */\n getRoutes() {\n return [...routes];\n },\n\n /**\n * Add a route programmatically\n */\n addRoute(route: Route) {\n addRouteInternal(route);\n },\n\n /**\n * Add a route directory (for plugins)\n */\n async addRouteDirectory(directory: string, options: { prefix?: string } = {}) {\n if (routeDirectories.has(directory)) {\n console.warn(`Route directory ${directory} already registered`);\n return;\n }\n\n routeDirectories.add(directory);\n\n // If already initialized, load routes immediately\n if (initialized) {\n await loadRoutesFromDirectory(directory, directory, options.prefix);\n\n // Set up watching for this directory if in watch mode\n if (routerOptions.watchMode) {\n setupWatcherForDirectory(directory, directory, options.prefix);\n }\n }\n },\n /**\n * Get route conflicts\n */\n getRouteConflicts() {\n const conflicts: Array<{ path: string; sources: string[] }> = [];\n\n for (const [path, sources] of routeSources.entries()) {\n if (sources.length > 1) {\n conflicts.push({ path, sources });\n }\n }\n\n return conflicts;\n },\n };\n}\n","// config/runtime-config.ts\ninterface RuntimeConfig {\n routesDir?: string;\n basePath?: string;\n // Add other runtime configuration as needed\n}\n\n// Internal state - not exported\nlet config: RuntimeConfig = {};\n\n/**\n * Set runtime configuration\n */\nexport function setRuntimeConfig(newConfig: Partial<RuntimeConfig>): void {\n config = { ...config, ...newConfig };\n}\n\n/**\n * Get full runtime configuration\n */\nexport function getRuntimeConfig(): RuntimeConfig {\n return { ...config };\n}\n\n/**\n * Get the configured routes directory\n */\nexport function getRoutesDir(): string {\n if (!config.routesDir) {\n throw new Error('Routes directory not configured. Make sure server is properly initialized.');\n }\n return config.routesDir;\n}\n\n/**\n * Get the configured base path\n */\nexport function getBasePath(): string {\n return config.basePath || '';\n}\n\n/**\n * Clear configuration (useful for testing)\n */\nexport function clearRuntimeConfig(): void {\n config = {};\n}\n","import {\n CreateGetRoute,\n CreatePostRoute,\n CreatePutRoute,\n CreateDeleteRoute,\n CreatePatchRoute,\n CreateHeadRoute,\n CreateOptionsRoute,\n} from '@blaizejs/types';\n\nimport { getRoutesDir } from '../config';\nimport { parseRoutePath } from './discovery/parser';\n\n/**\n * Get the file path of the function that called createXRoute\n */\nfunction getCallerFilePath(): string {\n const originalPrepareStackTrace = Error.prepareStackTrace;\n\n try {\n Error.prepareStackTrace = (_, stack) => stack;\n const stack = new Error().stack as unknown as NodeJS.CallSite[];\n\n // Stack: getCallerFilePath -> createXRoute -> route file\n const callerFrame = stack[3];\n if (!callerFrame || typeof callerFrame.getFileName !== 'function') {\n throw new Error('Unable to determine caller file frame');\n }\n const fileName = callerFrame.getFileName();\n\n if (!fileName) {\n throw new Error('Unable to determine caller file name');\n }\n\n return fileName;\n } finally {\n Error.prepareStackTrace = originalPrepareStackTrace;\n }\n}\n\n/**\n * Convert caller file path to route path using existing parsing logic\n */\nfunction getRoutePath(): string {\n console.log('getRoutePath called');\n const callerPath = getCallerFilePath();\n const routesDir = getRoutesDir();\n\n const parsedRoute = parseRoutePath(callerPath, routesDir);\n console.log(`Parsed route path: ${parsedRoute.routePath} from file: ${callerPath}`);\n\n return parsedRoute.routePath;\n}\n\n/**\n * Create a GET route\n */\nexport const createGetRoute: CreateGetRoute = config => {\n validateMethodConfig('GET', config);\n\n const path = getRoutePath();\n\n return {\n GET: config,\n path,\n };\n};\n\n/**\n * Create a POST route\n */\nexport const createPostRoute: CreatePostRoute = config => {\n validateMethodConfig('POST', config);\n\n const path = getRoutePath();\n\n return {\n POST: config,\n path,\n };\n};\n\n/**\n * Create a PUT route\n */\nexport const createPutRoute: CreatePutRoute = config => {\n validateMethodConfig('PUT', config);\n\n const path = getRoutePath();\n\n return {\n PUT: config,\n path,\n };\n};\n\n/**\n * Create a DELETE route\n */\nexport const createDeleteRoute: CreateDeleteRoute = config => {\n validateMethodConfig('DELETE', config);\n\n const path = getRoutePath();\n\n return {\n DELETE: config,\n path,\n };\n};\n\n/**\n * Create a PATCH route\n */\nexport const createPatchRoute: CreatePatchRoute = config => {\n validateMethodConfig('PATCH', config);\n\n const path = getRoutePath();\n\n return {\n PATCH: config,\n path,\n };\n};\n\n/**\n * Create a HEAD route (same signature as GET - no body)\n */\nexport const createHeadRoute: CreateHeadRoute = config => {\n validateMethodConfig('HEAD', config);\n\n const path = getRoutePath();\n\n return {\n HEAD: config,\n path,\n };\n};\n\n/**\n * Create an OPTIONS route (same signature as GET - no body)\n */\nexport const createOptionsRoute: CreateOptionsRoute = config => {\n validateMethodConfig('OPTIONS', config);\n\n const path = getRoutePath();\n\n return {\n OPTIONS: config,\n path,\n };\n};\n\n/**\n * Validate a method configuration\n */\nfunction validateMethodConfig(method: string, config: any): void {\n if (!config.handler || typeof config.handler !== 'function') {\n throw new Error(`Handler for method ${method} must be a function`);\n }\n\n if (config.middleware && !Array.isArray(config.middleware)) {\n throw new Error(`Middleware for method ${method} must be an array`);\n }\n\n // Validate schema if provided\n if (config.schema) {\n validateSchema(method, config.schema);\n }\n\n // Method-specific warnings\n switch (method) {\n case 'GET':\n case 'HEAD':\n case 'DELETE':\n if (config.schema?.body) {\n console.warn(`Warning: ${method} requests typically don't have request bodies`);\n }\n break;\n }\n}\n\n/**\n * Validate schema structure\n */\nfunction validateSchema(method: string, schema: any): void {\n const { params, query, body, response } = schema;\n\n // Basic validation - ensure they look like Zod schemas\n if (params && (!params._def || typeof params.parse !== 'function')) {\n throw new Error(`Params schema for ${method} must be a valid Zod schema`);\n }\n\n if (query && (!query._def || typeof query.parse !== 'function')) {\n throw new Error(`Query schema for ${method} must be a valid Zod schema`);\n }\n\n if (body && (!body._def || typeof body.parse !== 'function')) {\n throw new Error(`Body schema for ${method} must be a valid Zod schema`);\n }\n\n if (response && (!response._def || typeof response.parse !== 'function')) {\n throw new Error(`Response schema for ${method} must be a valid Zod schema`);\n }\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\nimport EventEmitter from 'node:events';\n\nimport {\n Context,\n Middleware,\n Plugin,\n Server,\n ServerOptions,\n ServerOptionsInput,\n StopOptions,\n} from '@blaizejs/types';\n\nimport { setRuntimeConfig } from '../config';\nimport { startServer } from './start';\nimport { registerSignalHandlers, stopServer } from './stop';\nimport { validateServerOptions } from './validation';\nimport { createPluginLifecycleManager } from '../plugins/lifecycle';\nimport { validatePlugin } from '../plugins/validation';\nimport { createRouter } from '../router';\n\nexport const DEFAULT_OPTIONS: ServerOptions = {\n port: 3000,\n host: 'localhost',\n routesDir: './routes',\n http2: {\n enabled: true,\n },\n middleware: [],\n plugins: [],\n};\n\n/**\n * Creates the configuration options by merging defaults with user-provided options\n */\nfunction createServerOptions(options: ServerOptionsInput = {}): ServerOptions {\n const baseOptions: ServerOptions = { ...DEFAULT_OPTIONS };\n setRuntimeConfig({ routesDir: options.routesDir || baseOptions.routesDir });\n\n return {\n port: options.port ?? baseOptions.port,\n host: options.host ?? baseOptions.host,\n routesDir: options.routesDir ?? baseOptions.routesDir,\n http2: {\n enabled: options.http2?.enabled ?? baseOptions.http2?.enabled,\n keyFile: options.http2?.keyFile ?? baseOptions.http2?.keyFile,\n certFile: options.http2?.certFile ?? baseOptions.http2?.certFile,\n },\n middleware: [...(baseOptions.middleware || []), ...(options.middleware || [])],\n plugins: [...(baseOptions.plugins || []), ...(options.plugins || [])],\n };\n}\n\n/**\n * Creates the server listen method\n */\nfunction createListenMethod(\n serverInstance: Server,\n validatedOptions: ServerOptions,\n initialMiddleware: Middleware[],\n initialPlugins: Plugin[]\n): Server['listen'] {\n return async () => {\n // Initialize middleware and plugins\n await initializeComponents(serverInstance, initialMiddleware, initialPlugins);\n\n // Use the functional manager\n await serverInstance.pluginManager.initializePlugins(serverInstance);\n\n // Start the server\n await startServer(serverInstance, validatedOptions);\n\n await serverInstance.pluginManager.onServerStart(serverInstance, serverInstance.server);\n\n // Setup signal handlers and emit events\n setupServerLifecycle(serverInstance);\n\n return serverInstance;\n };\n}\n\n/**\n * Initializes middleware and plugins\n */\nasync function initializeComponents(\n serverInstance: Server,\n initialMiddleware: Middleware[],\n initialPlugins: Plugin[]\n): Promise<void> {\n // Initialize middleware from options\n for (const mw of initialMiddleware) {\n serverInstance.use(mw);\n }\n\n // Register plugins from options\n for (const p of initialPlugins) {\n await serverInstance.register(p);\n }\n}\n\n/**\n * Sets up server lifecycle (signal handlers, events)\n */\nfunction setupServerLifecycle(serverInstance: Server): void {\n // Register signal handlers for graceful shutdown\n const signalHandlers = registerSignalHandlers(() => serverInstance.close());\n\n // Store handlers to unregister when server closes\n serverInstance._signalHandlers = signalHandlers;\n\n // Emit started event\n serverInstance.events.emit('started');\n}\n\n/**\n * Creates the server close method\n */\nfunction createCloseMethod(serverInstance: Server): Server['close'] {\n return async (stopOptions?: StopOptions) => {\n if (!serverInstance.server) {\n return;\n }\n\n // Prepare options\n const options: StopOptions = { ...stopOptions };\n\n // Unregister signal handlers if they exist\n if (serverInstance._signalHandlers) {\n serverInstance._signalHandlers.unregister();\n delete serverInstance._signalHandlers;\n }\n\n // Call stopServer with the server instance\n await stopServer(serverInstance, options);\n };\n}\n\n/**\n * Creates the server use method for adding middleware\n */\nfunction createUseMethod(serverInstance: Server): Server['use'] {\n return middleware => {\n const middlewareArray = Array.isArray(middleware) ? middleware : [middleware];\n serverInstance.middleware.push(...middlewareArray);\n return serverInstance;\n };\n}\n\n/**\n * Creates the server register method for plugins\n */\nfunction createRegisterMethod(serverInstance: Server): Server['register'] {\n return async plugin => {\n validatePlugin(plugin);\n serverInstance.plugins.push(plugin);\n await plugin.register(serverInstance);\n return serverInstance;\n };\n}\n\n/**\n * Creates a BlaizeJS server instance\n */\nexport function create(options: ServerOptionsInput = {}): Server {\n // Create and validate options\n const mergedOptions = createServerOptions(options);\n\n let validatedOptions: ServerOptions;\n try {\n validatedOptions = validateServerOptions(mergedOptions);\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to create server: ${error.message}`);\n }\n throw new Error(`Failed to create server: ${String(error)}`);\n }\n\n // Extract options and prepare initial components\n const { port, host, middleware, plugins } = validatedOptions;\n // TODO: create registries to manage middleware and plugins\n const initialMiddleware = Array.isArray(middleware) ? [...middleware] : [];\n const initialPlugins = Array.isArray(plugins) ? [...plugins] : [];\n\n // Initialize core server components\n const contextStorage = new AsyncLocalStorage<Context>();\n const router = createRouter({\n routesDir: validatedOptions.routesDir,\n watchMode: process.env.NODE_ENV === 'development',\n });\n // Create plugin lifecycle manager\n const pluginManager = createPluginLifecycleManager({\n debug: process.env.NODE_ENV === 'development',\n continueOnError: true,\n });\n const events = new EventEmitter();\n\n // Create server instance with minimal properties\n const serverInstance: Server = {\n server: null as any,\n port,\n host,\n context: contextStorage,\n events,\n plugins: [],\n middleware: [],\n _signalHandlers: { unregister: () => {} },\n use: () => serverInstance,\n register: async () => serverInstance,\n listen: async () => serverInstance,\n close: async () => {},\n router,\n pluginManager,\n };\n\n // Add methods to the server instance\n serverInstance.listen = createListenMethod(\n serverInstance,\n validatedOptions,\n initialMiddleware,\n initialPlugins\n );\n serverInstance.close = createCloseMethod(serverInstance);\n serverInstance.use = createUseMethod(serverInstance);\n serverInstance.register = createRegisterMethod(serverInstance);\n\n return serverInstance;\n}\n","import * as fs from 'node:fs';\nimport * as http from 'node:http';\nimport * as http2 from 'node:http2';\n\nimport { Http2Options, Server, ServerOptions } from '@blaizejs/types';\n\nimport { generateDevCertificates } from './dev-certificate';\nimport { createRequestHandler } from './request-handler';\n\n// Extract certificate handling to a separate function\nasync function prepareCertificates(\n http2Options: Http2Options\n): Promise<{ keyFile?: string; certFile?: string }> {\n // Not using HTTP/2? No certificates needed\n if (!http2Options.enabled) {\n return {};\n }\n\n const { keyFile, certFile } = http2Options;\n\n // If certificates are missing and in development, generate them\n const isDevMode = process.env.NODE_ENV === 'development';\n const certificatesMissing = !keyFile || !certFile;\n\n if (certificatesMissing && isDevMode) {\n const devCerts = await generateDevCertificates();\n return devCerts;\n }\n\n // If certificates are still missing, throw error\n if (certificatesMissing) {\n throw new Error(\n 'HTTP/2 requires SSL certificates. Provide keyFile and certFile in http2 options. ' +\n 'In development, set NODE_ENV=development to generate them automatically.'\n );\n }\n\n return { keyFile, certFile };\n}\n\n// Create server based on protocol\nfunction createServerInstance(\n isHttp2: boolean,\n certOptions: { keyFile?: string; certFile?: string }\n): http.Server | http2.Http2SecureServer {\n if (!isHttp2) {\n return http.createServer();\n }\n\n // Create HTTP/2 server options\n const http2ServerOptions: http2.SecureServerOptions = {\n allowHTTP1: true, // Allow fallback to HTTP/1.1\n };\n\n // Read certificate files\n try {\n if (certOptions.keyFile) {\n http2ServerOptions.key = fs.readFileSync(certOptions.keyFile);\n }\n if (certOptions.certFile) {\n http2ServerOptions.cert = fs.readFileSync(certOptions.certFile);\n }\n } catch (err) {\n throw new Error(\n `Failed to read certificate files: ${err instanceof Error ? err.message : String(err)}`\n );\n }\n\n return http2.createSecureServer(http2ServerOptions);\n}\n\n// Start listening on the specified port and host\nfunction listenOnPort(\n server: http.Server | http2.Http2SecureServer,\n port: number,\n host: string,\n isHttp2: boolean\n): Promise<void> {\n return new Promise((resolve, reject) => {\n server.listen(port, host, () => {\n const protocol = isHttp2 ? 'https' : 'http';\n const url = `${protocol}://${host}:${port}`;\n console.log(`\n🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥\n\n ⚡ BlaizeJS DEVELOPMENT SERVER HOT AND READY ⚡\n \n 🚀 Server: ${url}\n 🔥 Hot Reload: Enabled\n 🛠️ Mode: Development\n \n Time to build something amazing! 🚀\n\n🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥\n`);\n resolve();\n });\n\n server.on('error', err => {\n console.error('Server error:', err);\n reject(err);\n });\n });\n}\n\nasync function initializePlugins(serverInstance: Server): Promise<void> {\n for (const plugin of serverInstance.plugins) {\n if (typeof plugin.initialize === 'function') {\n await plugin.initialize(serverInstance);\n }\n }\n}\n\n// Main server start function - now with much lower complexity\nexport async function startServer(\n serverInstance: Server,\n serverOptions: ServerOptions\n): Promise<void> {\n // Server already running? Do nothing.\n if (serverInstance.server) {\n return;\n }\n\n try {\n // Get effective port and host\n const port = serverOptions.port;\n const host = serverOptions.host;\n\n // Initialize all registered plugins\n await initializePlugins(serverInstance);\n\n // Determine if using HTTP/2\n const http2Options = serverOptions.http2 || { enabled: true };\n const isHttp2 = !!http2Options.enabled;\n\n // Prepare certificates if needed\n const certOptions = await prepareCertificates(http2Options);\n\n // Update the server options if we generated certificates\n if (serverOptions.http2 && certOptions.keyFile && certOptions.certFile) {\n serverOptions.http2.keyFile = certOptions.keyFile;\n serverOptions.http2.certFile = certOptions.certFile;\n }\n\n // Create the server instance\n const server = createServerInstance(isHttp2, certOptions);\n\n // Store the server in the instance\n serverInstance.server = server;\n\n // Update server instance properties\n serverInstance.port = port;\n serverInstance.host = host;\n\n // Configure request handling\n const requestHandler = createRequestHandler(serverInstance);\n server.on('request', requestHandler);\n\n // Start listening\n await listenOnPort(server, port, host, isHttp2);\n } catch (error) {\n console.error('Failed to start server:', error);\n throw error;\n }\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\n\nimport * as selfsigned from 'selfsigned';\n\nexport interface DevCertificates {\n keyFile: string;\n certFile: string;\n}\n\nexport async function generateDevCertificates(): Promise<DevCertificates> {\n const certDir = path.join(process.cwd(), '.blaizejs', 'certs');\n const keyPath = path.join(certDir, 'dev.key');\n const certPath = path.join(certDir, 'dev.cert');\n \n // Check if certificates already exist\n if (fs.existsSync(keyPath) && fs.existsSync(certPath)) {\n return {\n keyFile: keyPath,\n certFile: certPath\n };\n }\n \n // Create directory if it doesn't exist\n if (!fs.existsSync(certDir)) {\n fs.mkdirSync(certDir, { recursive: true });\n }\n \n // Generate self-signed certificate\n const attrs = [{ name: 'commonName', value: 'localhost' }];\n const options = {\n days: 365,\n algorithm: 'sha256',\n keySize: 2048,\n extensions: [\n { name: 'basicConstraints', cA: true },\n {\n name: 'keyUsage',\n keyCertSign: true,\n digitalSignature: true,\n nonRepudiation: true,\n keyEncipherment: true,\n dataEncipherment: true\n },\n {\n name: 'extKeyUsage',\n serverAuth: true,\n clientAuth: true\n },\n {\n name: 'subjectAltName',\n altNames: [\n { type: 2, value: 'localhost' },\n { type: 7, ip: '127.0.0.1' }\n ]\n }\n ]\n };\n \n // Generate the certificates\n const pems = selfsigned.generate(attrs, options);\n \n // Write the key and certificate to files\n fs.writeFileSync(keyPath, Buffer.from(pems.private, 'utf-8'));\n fs.writeFileSync(certPath, Buffer.from(pems.cert, 'utf-8'));\n \n console.log(`\\n🔒 Generated self-signed certificates for development at ${certDir}\\n`);\n \n return {\n keyFile: keyPath,\n certFile: certPath\n };\n}","export class ResponseSentError extends Error {\n constructor(message: string = '❌ Response has already been sent') {\n super(message);\n this.name = 'ResponseSentError';\n }\n}\n\nexport class ResponseSentHeaderError extends ResponseSentError {\n constructor(message: string = 'Cannot set header after response has been sent') {\n super(message);\n }\n}\n\nexport class ResponseSentContentError extends ResponseSentError {\n constructor(message: string = 'Cannot set content type after response has been sent') {\n super(message);\n }\n}\n\nexport class ParseUrlError extends ResponseSentError {\n constructor(message: string = 'Invalide URL') {\n super(message);\n }\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\n\nimport { Context, QueryParams, State, UnknownFunction } from '@blaizejs/types';\n\n/**\n * AsyncLocalStorage instance for storing request context\n */\nexport const contextStorage = new AsyncLocalStorage<Context>();\n\n/**\n * Returns the current context from AsyncLocalStorage\n */\nexport function getContext<S extends State = State, TBody = unknown, TQuery = QueryParams>():\n | Context<S, TBody, TQuery>\n | undefined {\n return contextStorage.getStore() as Context<S, TBody, TQuery> | undefined;\n}\n\n/**\n * Wraps a callback function with a context\n */\nexport function runWithContext<T>(\n context: Context,\n callback: () => T | Promise<T>\n): T | Promise<T> {\n return contextStorage.run(context, callback);\n}\n\n/**\n * Middleware function that ensures a context is available in AsyncLocalStorage\n */\nexport async function contextMiddleware(\n context: Context,\n next: () => Promise<void>\n): Promise<void> {\n return runWithContext(context, next);\n}\n\n/**\n * Utility to check if code is running within a context\n */\nexport function hasContext(): boolean {\n return contextStorage.getStore() !== undefined;\n}\n\n/**\n * Creates a function that will run with the current context\n *\n * @param fn The function to bind to the current context\n * @returns A function that will execute with the bound context\n */\nexport function bindContext<TFunction extends UnknownFunction>(fn: TFunction): TFunction {\n const context = getContext();\n if (!context) {\n return fn;\n }\n\n // Using function instead of arrow function to preserve 'this'\n return function (this: unknown, ...args: Parameters<TFunction>): ReturnType<TFunction> {\n return runWithContext(context, () => fn.apply(this, args)) as ReturnType<TFunction>;\n } as TFunction;\n}\n","import {\n Context,\n ContextOptions,\n QueryParams,\n RequestParams,\n State,\n StreamOptions,\n UnifiedRequest,\n UnifiedResponse,\n} from '@blaizejs/types';\n\nimport {\n ParseUrlError,\n ResponseSentContentError,\n ResponseSentError,\n ResponseSentHeaderError,\n} from './errors';\nimport { hasContext, getContext } from './store';\n\nconst CONTENT_TYPE_HEADER = 'Content-Type';\n\n/**\n * Parse URL and extract path and query parameters using modern URL API\n */\nfunction parseRequestUrl(req: UnifiedRequest): {\n path: string;\n url: URL | null;\n query: QueryParams;\n} {\n const originalUrl = (req as any).url || '/';\n\n // Construct full URL for parsing\n const host = req.headers.host || 'localhost';\n const protocol = req.socket && (req.socket as any).encrypted ? 'https' : 'http';\n const fullUrl = `${protocol}://${host}${originalUrl.startsWith('/') ? '' : '/'}${originalUrl}`;\n try {\n const url = new URL(fullUrl);\n\n // Extract path\n const path = url.pathname;\n\n // Parse query parameters using URLSearchParams\n const query: QueryParams = {};\n url.searchParams.forEach((value, key) => {\n // Handle array parameters (key=value1&key=value2)\n if (query[key] !== undefined) {\n if (Array.isArray(query[key])) {\n (query[key] as string[]).push(value);\n } else {\n query[key] = [query[key] as string, value];\n }\n } else {\n query[key] = value;\n }\n });\n\n return { path, url, query };\n } catch (error) {\n // Fallback for invalid URLs\n console.warn(`Invalid URL: ${fullUrl}`, error);\n throw new ParseUrlError(`Invalid URL: ${fullUrl}`);\n }\n}\n\n/**\n * Determine if the request is using HTTP/2\n */\nfunction isHttp2Request(req: UnifiedRequest): boolean {\n // Check for HTTP/2 specific properties\n return 'stream' in req || ('httpVersionMajor' in req && (req as any).httpVersionMajor === 2);\n}\n\n/**\n * Get the HTTP protocol (http or https)\n */\nfunction getProtocol(req: UnifiedRequest): string {\n // Check for encrypted socket\n const encrypted = req.socket && (req.socket as any).encrypted;\n // Check for X-Forwarded-Proto header (common in proxy environments)\n const forwardedProto = req.headers['x-forwarded-proto'];\n\n if (forwardedProto) {\n if (Array.isArray(forwardedProto)) {\n // Handle array of header values (uncommon but possible)\n return forwardedProto[0]?.split(',')[0]?.trim() || 'http';\n } else {\n // Handle string header value (typical case)\n return forwardedProto.split(',')[0]?.trim() || 'http';\n }\n }\n\n // Default protocol based on socket encryption\n return encrypted ? 'https' : 'http';\n}\n\n/**\n * Create a new context object for a request/response cycle\n */\nexport async function createContext<TBody = unknown, TQuery = QueryParams>(\n req: UnifiedRequest,\n res: UnifiedResponse,\n options: ContextOptions = {}\n): Promise<Context<State, TBody, TQuery>> {\n // Extract basic request information\n const { path, url, query } = parseRequestUrl(req);\n const method = req.method || 'GET';\n const isHttp2 = isHttp2Request(req);\n const protocol = getProtocol(req);\n\n // Initialize state\n const params: RequestParams = {};\n const state = { ...(options.initialState || {}) };\n\n // Track response status\n const responseState = { sent: false };\n\n // Create the context object with its components\n const ctx: Context<State, TBody, TQuery> = {\n request: createRequestObject<TBody, TQuery>(req, {\n path,\n url,\n query: query as TQuery,\n params,\n method,\n isHttp2,\n protocol,\n }),\n response: {} as Context<State, TBody, TQuery>['response'],\n state,\n };\n\n ctx.response = createResponseObject(res, responseState, ctx);\n\n // Parse body if requested\n if (options.parseBody) {\n await parseBodyIfNeeded(req, ctx);\n }\n\n return ctx;\n}\n\n/**\n * Create the request object portion of the context\n */\nfunction createRequestObject<TBody = unknown, TQuery = QueryParams>(\n req: UnifiedRequest,\n info: {\n path: string;\n url: URL | null;\n query: TQuery;\n params: RequestParams;\n method: string;\n isHttp2: boolean;\n protocol: string;\n }\n): Context<State, TBody, TQuery>['request'] {\n return {\n raw: req,\n ...info,\n header: createRequestHeaderGetter(req),\n headers: createRequestHeadersGetter(req),\n body: undefined as unknown as TBody,\n };\n}\n\n/**\n * Create a function to get a single request header\n */\nfunction createRequestHeaderGetter(req: UnifiedRequest) {\n return (name: string): string | undefined => {\n const value = req.headers[name.toLowerCase()];\n if (Array.isArray(value)) {\n return value.join(', ');\n }\n return value || undefined;\n };\n}\n\n/**\n * Create a function to get multiple request headers\n */\nfunction createRequestHeadersGetter(req: UnifiedRequest) {\n const headerGetter = createRequestHeaderGetter(req);\n\n return (names?: string[]): Record<string, string | undefined> => {\n if (names && Array.isArray(names) && names.length > 0) {\n return names.reduce<Record<string, string | undefined>>((acc, name) => {\n acc[name] = headerGetter(name);\n return acc;\n }, {});\n } else {\n return Object.entries(req.headers).reduce<Record<string, string | undefined>>(\n (acc, [key, value]) => {\n acc[key] = Array.isArray(value) ? value.join(', ') : value || undefined;\n return acc;\n },\n {}\n );\n }\n };\n}\n\n/**\n * Create the response object portion of the context\n */\nfunction createResponseObject<S extends State = State, TBody = unknown, TQuery = QueryParams>(\n res: UnifiedResponse,\n responseState: { sent: boolean },\n ctx: Context<S, TBody, TQuery>\n): Context<S, TBody, TQuery>['response'] {\n return {\n raw: res,\n\n get sent() {\n return responseState.sent;\n },\n\n status: createStatusSetter(res, responseState, ctx),\n header: createHeaderSetter(res, responseState, ctx),\n headers: createHeadersSetter(res, responseState, ctx),\n type: createContentTypeSetter(res, responseState, ctx),\n\n json: createJsonResponder(res, responseState),\n text: createTextResponder(res, responseState),\n html: createHtmlResponder(res, responseState),\n redirect: createRedirectResponder(res, responseState),\n stream: createStreamResponder(res, responseState),\n };\n}\n\n/**\n * Create a function to set response status\n */\nfunction createStatusSetter<S extends State = State, TBody = unknown, TQuery = QueryParams>(\n res: UnifiedResponse,\n responseState: { sent: boolean },\n ctx: Context<S, TBody, TQuery>\n) {\n return function statusSetter(code: number): Context['response'] {\n if (responseState.sent) {\n throw new ResponseSentError();\n }\n res.statusCode = code;\n return ctx.response;\n };\n}\n\n/**\n * Create a function to set a response header\n */\nfunction createHeaderSetter<S extends State = State, TBody = unknown, TQuery = QueryParams>(\n res: UnifiedResponse,\n responseState: { sent: boolean },\n ctx: Context<S, TBody, TQuery>\n) {\n return function headerSetter(name: string, value: string) {\n if (responseState.sent) {\n throw new ResponseSentHeaderError();\n }\n res.setHeader(name, value);\n return ctx.response;\n };\n}\n\n/**\n * Create a function to set multiple response headers\n */\nfunction createHeadersSetter<S extends State = State, TBody = unknown, TQuery = QueryParams>(\n res: UnifiedResponse,\n responseState: { sent: boolean },\n ctx: Context<S, TBody, TQuery>\n) {\n return function headersSetter(headers: Record<string, string>) {\n if (responseState.sent) {\n throw new ResponseSentHeaderError();\n }\n for (const [name, value] of Object.entries(headers)) {\n res.setHeader(name, value);\n }\n return ctx.response;\n };\n}\n\n/**\n * Create a function to set content type header\n */\nfunction createContentTypeSetter<S extends State = State, TBody = unknown, TQuery = QueryParams>(\n res: UnifiedResponse,\n responseState: { sent: boolean },\n ctx: Context<S, TBody, TQuery>\n) {\n return function typeSetter(type: string) {\n if (responseState.sent) {\n throw new ResponseSentContentError();\n }\n res.setHeader(CONTENT_TYPE_HEADER, type);\n return ctx.response;\n };\n}\n\n/**\n * Create a function to send JSON response\n */\nfunction createJsonResponder(res: UnifiedResponse, responseState: { sent: boolean }) {\n return function jsonResponder(body: unknown, status?: number) {\n if (responseState.sent) {\n throw new ResponseSentError();\n }\n\n if (status !== undefined) {\n res.statusCode = status;\n }\n\n res.setHeader(CONTENT_TYPE_HEADER, 'application/json');\n res.end(JSON.stringify(body));\n responseState.sent = true;\n };\n}\n\n/**\n * Create a function to send text response\n */\nfunction createTextResponder(res: UnifiedResponse, responseState: { sent: boolean }) {\n return function textResponder(body: string, status?: number) {\n if (responseState.sent) {\n throw new ResponseSentError();\n }\n\n if (status !== undefined) {\n res.statusCode = status;\n }\n\n res.setHeader(CONTENT_TYPE_HEADER, 'text/plain');\n res.end(body);\n responseState.sent = true;\n };\n}\n\n/**\n * Create a function to send HTML response\n */\nfunction createHtmlResponder(res: UnifiedResponse, responseState: { sent: boolean }) {\n return function htmlResponder(body: string, status?: number) {\n if (responseState.sent) {\n throw new ResponseSentError();\n }\n\n if (status !== undefined) {\n res.statusCode = status;\n }\n\n res.setHeader(CONTENT_TYPE_HEADER, 'text/html');\n res.end(body);\n responseState.sent = true;\n };\n}\n\n/**\n * Create a function to send redirect response\n */\nfunction createRedirectResponder(res: UnifiedResponse, responseState: { sent: boolean }) {\n return function redirectResponder(url: string, status = 302) {\n if (responseState.sent) {\n throw new ResponseSentError();\n }\n\n res.statusCode = status;\n res.setHeader('Location', url);\n res.end();\n responseState.sent = true;\n };\n}\n\n/**\n * Create a function to stream response\n */\nfunction createStreamResponder(res: UnifiedResponse, responseState: { sent: boolean }) {\n return function streamResponder(readable: NodeJS.ReadableStream, options: StreamOptions = {}) {\n if (responseState.sent) {\n throw new ResponseSentError();\n }\n\n if (options.status !== undefined) {\n res.statusCode = options.status;\n }\n\n if (options.contentType) {\n res.setHeader(CONTENT_TYPE_HEADER, options.contentType);\n }\n\n if (options.headers) {\n for (const [name, value] of Object.entries(options.headers)) {\n res.setHeader(name, value);\n }\n }\n\n // Handle streaming\n readable.pipe(res);\n\n // Mark as sent when the stream ends\n readable.on('end', () => {\n responseState.sent = true;\n });\n\n // Handle errors\n readable.on('error', err => {\n console.error('Stream error:', err);\n if (!responseState.sent) {\n res.statusCode = 500;\n res.end('Stream error');\n responseState.sent = true;\n }\n });\n };\n}\n\n/**\n * Parse request body if enabled in options\n */\nasync function parseBodyIfNeeded<TBody = unknown, TQuery = QueryParams>(\n req: UnifiedRequest,\n ctx: Context<State, TBody, TQuery>\n): Promise<void> {\n // Skip parsing for methods that typically don't have bodies\n if (shouldSkipParsing(req.method)) {\n return;\n }\n\n const contentType = req.headers['content-type'] || '';\n const contentLength = parseInt(req.headers['content-length'] || '0', 10);\n\n // Skip if no content or very large (can be handled by dedicated middleware)\n if (contentLength === 0 || contentLength > 1048576) {\n // 1MB limit for built-in parser\n return;\n }\n\n try {\n await parseBodyByContentType(req, ctx, contentType);\n } catch (error) {\n setBodyError(ctx, 'body_read_error', 'Error reading request body', error);\n }\n}\n\n/**\n * Determine if body parsing should be skipped based on HTTP method\n */\nfunction shouldSkipParsing(method?: string): boolean {\n const skipMethods = ['GET', 'HEAD', 'OPTIONS'];\n return skipMethods.includes(method || 'GET');\n}\n\n/**\n * Parse the body based on content type\n */\nasync function parseBodyByContentType<TBody = unknown, TQuery = QueryParams>(\n req: UnifiedRequest,\n ctx: Context<State, TBody, TQuery>,\n contentType: string\n): Promise<void> {\n if (contentType.includes('application/json')) {\n await parseJsonBody(req, ctx);\n } else if (contentType.includes('application/x-www-form-urlencoded')) {\n await parseFormUrlEncodedBody(req, ctx);\n } else if (contentType.includes('text/')) {\n await parseTextBody(req, ctx);\n }\n // For other content types, do nothing (let specialized middleware handle it)\n}\n\n/**\n * Parse JSON request body\n */\nasync function parseJsonBody<TBody = unknown, TQuery = QueryParams>(\n req: UnifiedRequest,\n ctx: Context<State, TBody, TQuery>\n): Promise<void> {\n const body = await readRequestBody(req);\n\n if (!body) {\n console.warn('Empty body, skipping JSON parsing');\n return;\n }\n\n // Check if the body is actually \"null\" string\n if (body.trim() === 'null') {\n console.warn('Body is the string \"null\"');\n ctx.request.body = null as TBody;\n return;\n }\n\n try {\n const json = JSON.parse(body);\n ctx.request.body = json as TBody;\n } catch (error) {\n ctx.request.body = null as TBody;\n setBodyError(ctx, 'json_parse_error', 'Invalid JSON in request body', error);\n }\n}\n\n/**\n * Parse URL-encoded form data\n */\nasync function parseFormUrlEncodedBody<TBody = unknown, TQuery = QueryParams>(\n req: UnifiedRequest,\n ctx: Context<State, TBody, TQuery>\n): Promise<void> {\n const body = await readRequestBody(req);\n if (!body) return;\n\n try {\n ctx.request.body = parseUrlEncodedData(body) as TBody;\n } catch (error) {\n ctx.request.body = null as TBody;\n setBodyError(ctx, 'form_parse_error', 'Invalid form data in request body', error);\n }\n}\n\n/**\n * Parse URL-encoded data into an object\n */\nfunction parseUrlEncodedData(body: string): Record<string, string | string[]> {\n const params = new URLSearchParams(body);\n const formData: Record<string, string | string[]> = {};\n\n params.forEach((value, key) => {\n if (formData[key] !== undefined) {\n if (Array.isArray(formData[key])) {\n (formData[key] as string[]).push(value);\n } else {\n formData[key] = [formData[key] as string, value];\n }\n } else {\n formData[key] = value;\n }\n });\n\n return formData;\n}\n\n/**\n * Parse plain text body\n */\nasync function parseTextBody<TBody = null, TQuery = QueryParams>(\n req: UnifiedRequest,\n ctx: Context<State, TBody, TQuery>\n): Promise<void> {\n const body = await readRequestBody(req);\n if (body) {\n ctx.request.body = body as TBody;\n }\n}\n\n/**\n * Set body parsing error in context state\n */\nfunction setBodyError<TBody = unknown, TQuery = QueryParams>(\n ctx: Context<State, TBody, TQuery>,\n type: string,\n message: string,\n error: unknown\n): void {\n ctx.state._bodyError = { type, message, error };\n}\n\n/**\n * Read the entire request body as a string\n */\nasync function readRequestBody(req: UnifiedRequest): Promise<string> {\n return new Promise<string>((resolve, reject) => {\n const chunks: Buffer[] = [];\n\n req.on('data', (chunk: Buffer | string) => {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n });\n\n req.on('end', () => {\n resolve(Buffer.concat(chunks).toString('utf8'));\n });\n\n req.on('error', err => {\n reject(err);\n });\n });\n}\n\n/**\n * Get the current context or throw an error if none exists\n */\nexport function getCurrentContext<\n S extends State = State,\n TBody = unknown,\n TQuery = QueryParams,\n>(): Context<S, TBody, TQuery> {\n const ctx = getContext<S, TBody, TQuery>();\n if (!ctx) {\n throw new Error(\n 'No context found. Ensure this function is called within a request handler, ' +\n 'middleware, or function wrapped with runWithContext().'\n );\n }\n return ctx;\n}\n\n/**\n * Check if we're currently in a request context\n */\nexport function isInRequestContext(): boolean {\n return hasContext();\n}\n","import { RequestHandler, Server } from '@blaizejs/types';\n\nimport { createContext } from '../context/create';\nimport { runWithContext } from '../context/store';\nimport { compose } from '../middleware/compose';\n\nexport function createRequestHandler(serverInstance: Server): RequestHandler {\n return async (req, res) => {\n try {\n // Create context for this request\n const context = await createContext(req, res, {\n parseBody: true, // Enable automatic body parsing\n });\n\n // Compose all middleware into a single function\n const handler = compose(serverInstance.middleware);\n\n // Run the request with context in AsyncLocalStorage\n await runWithContext(context, async () => {\n try {\n // Execute the middleware chain\n await handler(context, async () => {\n if (!context.response.sent) {\n // Let the router handle the request\n await serverInstance.router.handleRequest(context);\n // If router didn't handle it either, send a 404\n if (!context.response.sent) {\n context.response.status(404).json({\n error: 'Not Found',\n message: `Route not found: ${context.request.method} ${context.request.path}`,\n });\n }\n }\n });\n } catch (error) {\n // Handle errors in middleware chain\n console.error('Error processing request:', error);\n\n // Only send error response if one hasn't been sent already\n if (!context.response.sent) {\n context.response.json(\n {\n error: 'Internal Server Error',\n message:\n process.env.NODE_ENV === 'development'\n ? error || 'Unknown error'\n : 'An error occurred processing your request',\n },\n 500\n );\n }\n }\n });\n } catch (error) {\n // Handle errors in context creation\n console.error('Error creating context:', error);\n res.writeHead(500, { 'Content-Type': 'application/json' });\n res.end(\n JSON.stringify({\n error: 'Internal Server Error',\n message: 'Failed to process request',\n })\n );\n }\n };\n}\n","import { Server, StopOptions } from '@blaizejs/types';\n\nexport async function stopServer(serverInstance: Server, options: StopOptions = {}): Promise<void> {\n // Get the HTTP server from the server instance\n const server = serverInstance.server;\n const events = serverInstance.events;\n\n // If no server is running, do nothing\n if (!server) {\n return;\n }\n\n const timeout = options.timeout || 30000; // 30 seconds default\n\n try {\n // Execute pre-stop hook if provided\n if (options.onStopping) {\n await options.onStopping();\n }\n\n // Emit stopping event\n events.emit('stopping');\n\n // Notify plugins that server is stopping\n await serverInstance.pluginManager.onServerStop(serverInstance, server);\n\n // Set a timeout to ensure we don't wait forever\n const timeoutPromise = new Promise<never>((_, reject) => {\n setTimeout(() => {\n reject(new Error('Server shutdown timed out waiting for requests to complete'));\n }, timeout);\n });\n\n // Create server close promise\n const closePromise = new Promise<void>((resolve, reject) => {\n server.close((err?: Error) => {\n if (err) {\n return reject(err);\n }\n resolve();\n });\n });\n\n // Wait for server to close with timeout\n await Promise.race([closePromise, timeoutPromise]);\n\n // Use plugin lifecycle manager to terminate plugins\n await serverInstance.pluginManager.terminatePlugins(serverInstance);\n\n // Execute post-stop hook if provided\n if (options.onStopped) {\n await options.onStopped();\n }\n\n // Emit stopped event\n events.emit('stopped');\n\n // Clear server reference\n serverInstance.server = null as any;\n } catch (error) {\n // Emit error event and rethrow\n events.emit('error', error);\n throw error;\n }\n}\n\n/**\n * Register signal handlers for graceful shutdown\n */\nexport function registerSignalHandlers(stopFn: () => Promise<void>): { unregister: () => void } {\n // Create bound handler functions\n const sigintHandler = () => stopFn().catch(console.error);\n const sigtermHandler = () => stopFn().catch(console.error);\n\n // Register handlers\n process.on('SIGINT', sigintHandler);\n process.on('SIGTERM', sigtermHandler);\n\n // Return function to unregister handlers\n return {\n unregister: () => {\n process.removeListener('SIGINT', sigintHandler);\n process.removeListener('SIGTERM', sigtermHandler);\n },\n };\n}\n","import { z } from 'zod';\n\nimport { ServerOptions, ServerOptionsInput, Middleware, Plugin } from '@blaizejs/types';\n\n// Create a more flexible validation for the middleware function type\nconst middlewareSchema = z.custom<Middleware>(\n data =>\n data !== null &&\n typeof data === 'object' &&\n 'execute' in data &&\n typeof data.execute === 'function',\n {\n message: 'Expected middleware to have an execute function',\n }\n);\n\n// Create a schema for plugins\nconst pluginSchema = z.custom<Plugin>(\n data =>\n data !== null &&\n typeof data === 'object' &&\n 'register' in data &&\n typeof data.register === 'function',\n {\n message: 'Expected a valid plugin object with a register method',\n }\n);\n\n// Create a schema for HTTP/2 options with conditional validation\nconst http2Schema = z\n .object({\n enabled: z.boolean().optional().default(true),\n keyFile: z.string().optional(),\n certFile: z.string().optional(),\n })\n .refine(\n data => {\n // If HTTP/2 is enabled and not in development mode,\n // both keyFile and certFile must be provided\n if (data.enabled && process.env.NODE_ENV === 'production') {\n return data.keyFile && data.certFile;\n }\n return true;\n },\n {\n message:\n 'When HTTP/2 is enabled (outside of development mode), both keyFile and certFile must be provided',\n }\n );\n\n// Validation schema for server options\nexport const serverOptionsSchema = z.object({\n port: z.number().int().positive().optional().default(3000),\n host: z.string().optional().default('localhost'),\n routesDir: z.string().optional().default('./routes'),\n http2: http2Schema.optional().default({\n enabled: true,\n }),\n middleware: z.array(middlewareSchema).optional().default([]),\n plugins: z.array(pluginSchema).optional().default([]),\n});\n\nexport function validateServerOptions(options: ServerOptionsInput): ServerOptions {\n try {\n return serverOptionsSchema.parse(options);\n } catch (error) {\n // Properly type the error as Zod validation error\n if (error instanceof z.ZodError) {\n // Format the Zod error for better readability\n const formattedError = error.format();\n throw new Error(`Invalid server options: ${JSON.stringify(formattedError, null, 2)}`);\n }\n // For other types of errors\n throw new Error(`Invalid server options: ${String(error)}`);\n }\n}\n","import type {\n Server,\n Plugin,\n PluginLifecycleManager,\n PluginLifecycleOptions,\n} from '@blaizejs/types';\n\n/**\n * Create a plugin lifecycle manager\n */\nexport function createPluginLifecycleManager(\n options: PluginLifecycleOptions = {}\n): PluginLifecycleManager {\n const { continueOnError = true, debug = false, onError } = options;\n\n /**\n * Log debug messages if enabled\n */\n function log(message: string, ...args: any[]) {\n if (debug) {\n console.log(`[PluginLifecycle] ${message}`, ...args);\n }\n }\n\n /**\n * Handle plugin errors\n */\n function handleError(plugin: Plugin, phase: string, error: Error) {\n const errorMessage = `Plugin ${plugin.name} failed during ${phase}: ${error.message}`;\n\n if (onError) {\n onError(plugin, phase, error);\n } else {\n console.error(errorMessage, error);\n }\n\n if (!continueOnError) {\n throw new Error(errorMessage);\n }\n }\n\n return {\n /**\n * Initialize all plugins\n */\n async initializePlugins(server: Server): Promise<void> {\n log('Initializing plugins...');\n\n for (const plugin of server.plugins) {\n if (plugin.initialize) {\n try {\n log(`Initializing plugin: ${plugin.name}`);\n await plugin.initialize(server);\n } catch (error) {\n handleError(plugin, 'initialize', error as Error);\n }\n }\n }\n\n log(`Initialized ${server.plugins.length} plugins`);\n },\n\n /**\n * Terminate all plugins in reverse order\n */\n async terminatePlugins(server: Server): Promise<void> {\n log('Terminating plugins...');\n\n const pluginsToTerminate = [...server.plugins].reverse();\n\n for (const plugin of pluginsToTerminate) {\n if (plugin.terminate) {\n try {\n log(`Terminating plugin: ${plugin.name}`);\n await plugin.terminate(server);\n } catch (error) {\n handleError(plugin, 'terminate', error as Error);\n }\n }\n }\n\n log(`Terminated ${pluginsToTerminate.length} plugins`);\n },\n\n /**\n * Notify plugins that the server has started\n */\n async onServerStart(server: Server, httpServer: any): Promise<void> {\n log('Notifying plugins of server start...');\n\n for (const plugin of server.plugins) {\n if (plugin.onServerStart) {\n try {\n log(`Notifying plugin of server start: ${plugin.name}`);\n await plugin.onServerStart(httpServer);\n } catch (error) {\n handleError(plugin, 'onServerStart', error as Error);\n }\n }\n }\n },\n\n /**\n * Notify plugins that the server is stopping\n */\n async onServerStop(server: Server, httpServer: any): Promise<void> {\n log('Notifying plugins of server stop...');\n\n const pluginsToNotify = [...server.plugins].reverse();\n\n for (const plugin of pluginsToNotify) {\n if (plugin.onServerStop) {\n try {\n log(`Notifying plugin of server stop: ${plugin.name}`);\n await plugin.onServerStop(httpServer);\n } catch (error) {\n handleError(plugin, 'onServerStop', error as Error);\n }\n }\n }\n },\n };\n}\n","export class PluginError extends Error {\n constructor(\n public pluginName: string,\n message: string,\n public cause?: Error\n ) {\n super(`Plugin \"${pluginName}\": ${message}`);\n this.name = 'PluginError';\n }\n}\n\nexport class PluginLifecycleError extends PluginError {\n constructor(\n pluginName: string,\n public phase: 'register' | 'initialize' | 'terminate' | 'start' | 'stop',\n cause: Error\n ) {\n super(pluginName, `Failed during ${phase} phase: ${cause.message}`, cause);\n this.name = 'PluginLifecycleError';\n }\n}\n\nexport class PluginDependencyError extends PluginError {\n constructor(\n pluginName: string,\n public missingDependency: string\n ) {\n super(pluginName, `Missing dependency: ${missingDependency}`);\n this.name = 'PluginDependencyError';\n }\n}\n\n// packages/blaizejs/src/plugins/errors.ts (or add to existing errors file)\n\nexport class PluginValidationError extends Error {\n constructor(\n public pluginName: string,\n message: string\n ) {\n super(`Plugin validation error${pluginName ? ` for \"${pluginName}\"` : ''}: ${message}`);\n this.name = 'PluginValidationError';\n }\n}\n\nexport class PluginRegistrationError extends Error {\n constructor(\n public pluginName: string,\n message: string\n ) {\n super(`Plugin registration error for \"${pluginName}\": ${message}`);\n this.name = 'PluginRegistrationError';\n }\n}\n","import type { Plugin } from '@blaizejs/types';\n\nimport { PluginValidationError } from './errors';\n\nexport interface PluginValidationOptions {\n /** Require specific plugin properties */\n requireVersion?: boolean;\n /** Validate plugin name format */\n validateNameFormat?: boolean;\n /** Check for reserved plugin names */\n checkReservedNames?: boolean;\n}\n\n/**\n * Reserved plugin names that cannot be used\n */\nconst RESERVED_NAMES = new Set([\n 'core',\n 'server',\n 'router',\n 'middleware',\n 'context',\n 'blaize',\n 'blaizejs',\n]);\n\n/**\n * Valid plugin name pattern (lowercase, letters, numbers, hyphens)\n */\nconst VALID_NAME_PATTERN = /^[a-z]([a-z0-9-]*[a-z0-9])?$/;\n\n/**\n * Valid semantic version pattern\n */\nconst VALID_VERSION_PATTERN = /^\\d+\\.\\d+\\.\\d+(?:-[a-zA-Z0-9-.]+)?(?:\\+[a-zA-Z0-9-.]+)?$/;\n\n/**\n * Validate a plugin object\n */\nexport function validatePlugin(\n plugin: unknown,\n options: PluginValidationOptions = {}\n): asserts plugin is Plugin {\n const { requireVersion = true, validateNameFormat = true, checkReservedNames = true } = options;\n\n // Basic type validation\n if (!plugin || typeof plugin !== 'object') {\n throw new PluginValidationError('', 'Plugin must be an object');\n }\n\n const p = plugin as any;\n\n // Validate name\n if (!p.name || typeof p.name !== 'string') {\n throw new PluginValidationError('', 'Plugin must have a name (string)');\n }\n\n // Validate name format\n if (validateNameFormat && !VALID_NAME_PATTERN.test(p.name)) {\n throw new PluginValidationError(\n p.name,\n 'Plugin name must be lowercase letters, numbers, and hyphens only'\n );\n }\n\n // Check reserved names\n if (checkReservedNames && RESERVED_NAMES.has(p.name.toLowerCase())) {\n throw new PluginValidationError(p.name, `Plugin name \"${p.name}\" is reserved`);\n }\n\n // Validate version\n if (requireVersion) {\n if (!p.version || typeof p.version !== 'string') {\n throw new PluginValidationError(p.name, 'Plugin must have a version (string)');\n }\n\n if (!VALID_VERSION_PATTERN.test(p.version)) {\n throw new PluginValidationError(\n p.name,\n 'Plugin version must follow semantic versioning (e.g., \"1.0.0\")'\n );\n }\n }\n\n // Validate register method\n if (!p.register || typeof p.register !== 'function') {\n throw new PluginValidationError(p.name, 'Plugin must have a register method (function)');\n }\n\n // Validate optional lifecycle methods\n const lifecycleMethods = ['initialize', 'terminate', 'onServerStart', 'onServerStop'];\n\n for (const method of lifecycleMethods) {\n if (p[method] && typeof p[method] !== 'function') {\n throw new PluginValidationError(p.name, `Plugin ${method} must be a function if provided`);\n }\n }\n\n // Validate dependencies if present\n // if (p.dependencies) {\n // if (!Array.isArray(p.dependencies) && typeof p.dependencies !== 'string') {\n // throw new PluginValidationError(\n // p.name,\n // 'Plugin dependencies must be a string or array of strings'\n // );\n // }\n\n // const deps = Array.isArray(p.dependencies) ? p.dependencies : [p.dependencies];\n // for (const dep of deps) {\n // if (typeof dep !== 'string') {\n // throw new PluginValidationError(p.name, 'Plugin dependencies must be strings');\n // }\n // }\n // }\n}\n\n/**\n * Validate plugin options object\n */\nexport function validatePluginOptions(pluginName: string, options: unknown, schema?: any): void {\n // Basic validation\n if (options !== undefined && typeof options !== 'object') {\n throw new PluginValidationError(pluginName, 'Plugin options must be an object');\n }\n\n // If a schema is provided, validate against it\n if (schema && options) {\n try {\n schema.parse(options);\n } catch (error) {\n throw new PluginValidationError(\n pluginName,\n `Plugin options validation failed: ${(error as Error).message}`\n );\n }\n }\n}\n\n/**\n * Validate plugin factory function\n */\nexport function validatePluginFactory(\n factory: unknown\n): asserts factory is (...args: any[]) => any {\n if (typeof factory !== 'function') {\n throw new PluginValidationError('', 'Plugin factory must be a function');\n }\n}\n\n/**\n * Check if a plugin name is valid\n */\nexport function isValidPluginName(name: string): boolean {\n return (\n typeof name === 'string' &&\n name.length > 0 &&\n VALID_NAME_PATTERN.test(name) &&\n !RESERVED_NAMES.has(name.toLowerCase())\n );\n}\n\n/**\n * Check if a version string is valid\n */\nexport function isValidVersion(version: string): boolean {\n return typeof version === 'string' && VALID_VERSION_PATTERN.test(version);\n}\n\n/**\n * Sanitize plugin name (remove invalid characters)\n */\nexport function sanitizePluginName(name: string): string {\n return name\n .toLowerCase()\n .replace(/[^a-z0-9-]/g, '-')\n .replace(/^-+|-+$/g, '')\n .replace(/-+/g, '-');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,sBAAAA;AAAA,EAAA;AAAA;AAAA,sBAAAA;AAAA,EAAA;AAAA;AAAA;;;ACKO,SAAS,OAAO,kBAAsE;AAE3F,MAAI,OAAO,qBAAqB,YAAY;AAC1C,WAAO;AAAA,MACL,MAAM;AAAA;AAAA,MACN,SAAS;AAAA,MACT,OAAO;AAAA,IACT;AAAA,EACF;AAGA,QAAM,EAAE,OAAO,aAAa,SAAS,MAAM,QAAQ,MAAM,IAAI;AAG7D,QAAM,aAAyB;AAAA,IAC7B;AAAA,IACA,SAAS;AAAA,IACT;AAAA,EACF;AAEA,MAAI,SAAS,QAAW;AACtB,WAAO;AAAA,MACL,GAAG;A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AA,EACR,YAAY;AAAA,EACZ,SAAS;AAAA;AAAA,EAGT;AACF;AAGA,IAAO,gBAAQ;","names":["create","create","path","module","path","import_zod","import_zod","import_zod","path","path","path","options","stack","config","path","import_node_async_hooks","fs","fs","path","path","resolve","resolve","resolve","import_zod","create","contextStorage","EventEmitter","create"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/middleware/execute.ts","../src/middleware/compose.ts","../src/middleware/create.ts","../src/plugins/create.ts","../src/router/create.ts","../src/config.ts","../src/router/discovery/parser.ts","../src/server/create.ts","../src/server/start.ts","../src/server/dev-certificate.ts","../src/context/errors.ts","../src/context/store.ts","../src/context/create.ts","../src/server/request-handler.ts","../src/server/stop.ts","../src/server/validation.ts","../src/plugins/lifecycle.ts","../src/plugins/errors.ts","../src/plugins/validation.ts","../src/router/discovery/cache.ts","../src/router/discovery/loader.ts","../src/router/discovery/parallel.ts","../src/router/discovery/finder.ts","../src/router/discovery/profiler.ts","../src/router/discovery/watchers.ts","../src/router/handlers/error.ts","../src/router/validation/body.ts","../src/router/validation/params.ts","../src/router/validation/query.ts","../src/router/validation/response.ts","../src/router/validation/schema.ts","../src/router/handlers/executor.ts","../src/router/matching/params.ts","../src/router/matching/matcher.ts","../src/router/registry/fast-registry.ts","../src/router/utils/matching-helpers.ts","../src/router/router.ts"],"sourcesContent":["/**\n * BlaizeJS Core\n *\n * A blazing-fast, type-safe Node.js framework with file-based routing,\n * powerful middleware, and end-to-end type safety.\n *\n * @package blaizejs\n */\n\nimport { compose } from './middleware/compose';\nimport { create as createMiddleware } from './middleware/create';\nimport { create as createPlugin } from './plugins/create';\nimport {\n createDeleteRoute,\n createGetRoute,\n createHeadRoute,\n createOptionsRoute,\n createPatchRoute,\n createPostRoute,\n createPutRoute,\n} from './router/create';\nimport { create as createServer } from './server/create';\n\n// TODO: ideally this could be import as an npm package, but for now we use a relative path\n// Explicit imports to avoid using values without importing\nexport type * from '../../blaize-types/src/index.ts';\n\n// Re-export everything\n// Server module exports\nexport { createServer };\n\n// Router module exports\nexport {\n createDeleteRoute,\n createGetRoute,\n createHeadRoute,\n createOptionsRoute,\n createPatchRoute,\n createPostRoute,\n createPutRoute,\n};\n\n// Middleware module exports\nexport { createMiddleware, compose };\n\n// Plugins module exports\nexport { createPlugin };\n\n// Version information\nexport const VERSION = '0.1.0';\n\n// Namespaced exports with different names to avoid conflicts\nexport const ServerAPI = { createServer };\nexport const RouterAPI = {\n createDeleteRoute,\n createGetRoute,\n createHeadRoute,\n createOptionsRoute,\n createPatchRoute,\n createPostRoute,\n createPutRoute,\n};\nexport const MiddlewareAPI = { createMiddleware, compose };\nexport const PluginsAPI = { createPlugin };\n\n// Default export\nconst Blaize = {\n // Core functions\n createServer,\n createMiddleware,\n createPlugin,\n\n // Namespaces (using the non-conflicting names)\n Server: ServerAPI,\n Router: RouterAPI,\n Middleware: MiddlewareAPI,\n Plugins: PluginsAPI,\n\n // Constants\n VERSION,\n};\n\nexport default Blaize;\nexport { Blaize };\n","import type { Context, Middleware, NextFunction } from '../index';\n\n/**\n * Execute a single middleware, handling both function and object forms\n */\nexport function execute(\n middleware: Middleware | undefined,\n ctx: Context,\n next: NextFunction\n): Promise<void> {\n // Handle undefined middleware (safety check)\n if (!middleware) {\n return Promise.resolve(next());\n }\n\n // Handle middleware with skip function\n if (middleware.skip && middleware.skip(ctx)) {\n return Promise.resolve(next());\n }\n\n try {\n // Execute middleware\n const result = middleware.execute(ctx, next);\n\n // Handle both Promise and non-Promise returns\n if (result instanceof Promise) {\n // Return the promise directly to allow errors to propagate\n return result;\n } else {\n // Only wrap non-Promise returns\n return Promise.resolve(result);\n }\n } catch (error) {\n // Handle synchronous errors\n return Promise.reject(error);\n }\n}\n","import { execute } from './execute';\n\nimport type { Context, Middleware, MiddlewareFunction, NextFunction } from '../index';\n\n/**\n * Compose multiple middleware functions into a single middleware function\n */\nexport function compose(middlewareStack: Middleware[]): MiddlewareFunction {\n // No middleware? Return a pass-through function\n if (middlewareStack.length === 0) {\n return async (_, next) => {\n await Promise.resolve(next());\n };\n }\n\n // Return a function that executes the middleware stack\n return async function (ctx: Context, finalHandler: NextFunction): Promise<void> {\n // Keep track of which \"next\" functions have been called\n const called = new Set<number>();\n\n // Create dispatch function to process middleware stack\n const dispatch = async (i: number): Promise<void> => {\n // If we've reached the end of the stack, execute the final handler\n if (i >= middlewareStack.length) {\n // Ensure we're returning a Promise regardless of what finalHandler returns\n return Promise.resolve(finalHandler());\n }\n\n // Get current middleware\n const middleware = middlewareStack[i];\n\n // Create a next function that can only be called once\n const nextDispatch = () => {\n if (called.has(i)) {\n throw new Error('next() called multiple times');\n }\n\n // Mark this middleware's next as called\n called.add(i);\n\n // Move to the next middleware\n return dispatch(i + 1);\n };\n\n // Use the executeMiddleware function we defined\n return execute(middleware, ctx, nextDispatch);\n };\n\n // Start middleware chain execution\n return dispatch(0);\n };\n}\n","import type { Middleware, MiddlewareFunction, MiddlewareOptions } from '../index';\n\n/**\n * Create a middleware\n */\nexport function create(handlerOrOptions: MiddlewareFunction | MiddlewareOptions): Middleware {\n // If handlerOrOptions is a function, convert it to our middleware object format\n if (typeof handlerOrOptions === 'function') {\n return {\n name: 'anonymous', // Default name for function middleware\n execute: handlerOrOptions,\n debug: false,\n };\n }\n\n // Otherwise, handle it as middleware options\n const { name = 'anonymous', handler, skip, debug = false } = handlerOrOptions;\n\n // Create base middleware object with required properties\n const middleware: Middleware = {\n name,\n execute: handler,\n debug,\n };\n\n if (skip !== undefined) {\n return {\n ...middleware,\n skip,\n };\n }\n\n return middleware;\n}\n","import type { Plugin, PluginFactory, PluginHooks, Server } from '../index';\n\n/**\n * Create a plugin with the given name, version, and setup function\n */\nexport function create<T = any>(\n name: string,\n version: string,\n setup: (\n app: Server,\n options: T\n ) => void | Partial<PluginHooks> | Promise<void> | Promise<Partial<PluginHooks>>,\n defaultOptions: Partial<T> = {}\n): PluginFactory<T> {\n // Input validation\n if (!name || typeof name !== 'string') {\n throw new Error('Plugin name must be a non-empty string');\n }\n\n if (!version || typeof version !== 'string') {\n throw new Error('Plugin version must be a non-empty string');\n }\n\n if (typeof setup !== 'function') {\n throw new Error('Plugin setup must be a function');\n }\n\n // Return the factory function\n return function pluginFactory(userOptions?: Partial<T>) {\n // Merge default options with user options\n const mergedOptions = { ...defaultOptions, ...userOptions } as T;\n\n // Create the base plugin object\n const plugin: Plugin = {\n name,\n version,\n\n // The register hook calls the user's setup function\n register: async (app: Server) => {\n const result = await setup(app, mergedOptions);\n\n // If setup returns hooks, merge them into this plugin\n if (result && typeof result === 'object') {\n // Now we explicitly assign to our plugin object\n Object.assign(plugin, result);\n }\n },\n };\n\n return plugin;\n };\n}\n","import { fileURLToPath } from 'node:url';\n\nimport { getRoutesDir } from '../config';\nimport { parseRoutePath } from './discovery/parser';\n\nimport type {\n CreateGetRoute,\n CreatePostRoute,\n CreatePutRoute,\n CreateDeleteRoute,\n CreatePatchRoute,\n CreateHeadRoute,\n CreateOptionsRoute,\n} from '../index';\n\n/**\n * Get the file path of the function that called createXRoute\n */\nfunction getCallerFilePath(): string {\n const originalPrepareStackTrace = Error.prepareStackTrace;\n\n try {\n Error.prepareStackTrace = (_, stack) => stack;\n const stack = new Error().stack as unknown as NodeJS.CallSite[];\n\n // Stack: getCallerFilePath -> createXRoute -> route file\n const callerFrame = stack[3];\n if (!callerFrame || typeof callerFrame.getFileName !== 'function') {\n throw new Error('Unable to determine caller file frame');\n }\n const fileName = callerFrame.getFileName();\n\n if (!fileName) {\n throw new Error('Unable to determine caller file name');\n }\n\n if (fileName.startsWith('file://')) {\n return fileURLToPath(fileName);\n }\n\n return fileName;\n } finally {\n Error.prepareStackTrace = originalPrepareStackTrace;\n }\n}\n\n/**\n * Convert caller file path to route path using existing parsing logic\n */\nfunction getRoutePath(): string {\n const callerPath = getCallerFilePath();\n const routesDir = getRoutesDir();\n\n const parsedRoute = parseRoutePath(callerPath, routesDir);\n console.log(`🔎 Parsed route path: ${parsedRoute.routePath} from file: ${callerPath}`);\n\n return parsedRoute.routePath;\n}\n\n/**\n * Create a GET route\n */\nexport const createGetRoute: CreateGetRoute = config => {\n validateMethodConfig('GET', config);\n\n const path = getRoutePath();\n\n return {\n GET: config,\n path,\n };\n};\n\n/**\n * Create a POST route\n */\nexport const createPostRoute: CreatePostRoute = config => {\n validateMethodConfig('POST', config);\n\n const path = getRoutePath();\n\n return {\n POST: config,\n path,\n };\n};\n\n/**\n * Create a PUT route\n */\nexport const createPutRoute: CreatePutRoute = config => {\n validateMethodConfig('PUT', config);\n\n const path = getRoutePath();\n\n return {\n PUT: config,\n path,\n };\n};\n\n/**\n * Create a DELETE route\n */\nexport const createDeleteRoute: CreateDeleteRoute = config => {\n validateMethodConfig('DELETE', config);\n\n const path = getRoutePath();\n\n return {\n DELETE: config,\n path,\n };\n};\n\n/**\n * Create a PATCH route\n */\nexport const createPatchRoute: CreatePatchRoute = config => {\n validateMethodConfig('PATCH', config);\n\n const path = getRoutePath();\n\n return {\n PATCH: config,\n path,\n };\n};\n\n/**\n * Create a HEAD route (same signature as GET - no body)\n */\nexport const createHeadRoute: CreateHeadRoute = config => {\n validateMethodConfig('HEAD', config);\n\n const path = getRoutePath();\n\n return {\n HEAD: config,\n path,\n };\n};\n\n/**\n * Create an OPTIONS route (same signature as GET - no body)\n */\nexport const createOptionsRoute: CreateOptionsRoute = config => {\n validateMethodConfig('OPTIONS', config);\n\n const path = getRoutePath();\n\n return {\n OPTIONS: config,\n path,\n };\n};\n\n/**\n * Validate a method configuration\n */\nfunction validateMethodConfig(method: string, config: any): void {\n if (!config.handler || typeof config.handler !== 'function') {\n throw new Error(`Handler for method ${method} must be a function`);\n }\n\n if (config.middleware && !Array.isArray(config.middleware)) {\n throw new Error(`Middleware for method ${method} must be an array`);\n }\n\n // Validate schema if provided\n if (config.schema) {\n validateSchema(method, config.schema);\n }\n\n // Method-specific warnings\n switch (method) {\n case 'GET':\n case 'HEAD':\n case 'DELETE':\n if (config.schema?.body) {\n console.warn(`Warning: ${method} requests typically don't have request bodies`);\n }\n break;\n }\n}\n\n/**\n * Validate schema structure\n */\nfunction validateSchema(method: string, schema: any): void {\n const { params, query, body, response } = schema;\n\n // Basic validation - ensure they look like Zod schemas\n if (params && (!params._def || typeof params.parse !== 'function')) {\n throw new Error(`Params schema for ${method} must be a valid Zod schema`);\n }\n\n if (query && (!query._def || typeof query.parse !== 'function')) {\n throw new Error(`Query schema for ${method} must be a valid Zod schema`);\n }\n\n if (body && (!body._def || typeof body.parse !== 'function')) {\n throw new Error(`Body schema for ${method} must be a valid Zod schema`);\n }\n\n if (response && (!response._def || typeof response.parse !== 'function')) {\n throw new Error(`Response schema for ${method} must be a valid Zod schema`);\n }\n}\n","// config/runtime-config.ts\ninterface RuntimeConfig {\n routesDir?: string;\n basePath?: string;\n // Add other runtime configuration as needed\n}\n\n// Internal state - not exported\nlet config: RuntimeConfig = {};\n\n/**\n * Set runtime configuration\n */\nexport function setRuntimeConfig(newConfig: Partial<RuntimeConfig>): void {\n config = { ...config, ...newConfig };\n}\n\n/**\n * Get full runtime configuration\n */\nexport function getRuntimeConfig(): RuntimeConfig {\n return { ...config };\n}\n\n/**\n * Get the configured routes directory\n */\nexport function getRoutesDir(): string {\n if (!config.routesDir) {\n throw new Error('Routes directory not configured. Make sure server is properly initialized.');\n }\n return config.routesDir;\n}\n\n/**\n * Get the configured base path\n */\nexport function getBasePath(): string {\n return config.basePath || '';\n}\n\n/**\n * Clear configuration (useful for testing)\n */\nexport function clearRuntimeConfig(): void {\n config = {};\n}\n","import * as path from 'node:path';\n\nimport type { ParsedRoute } from '../../index';\n\n/**\n * Parse a file path into a route path\n * Works consistently across Windows and Unix-like file systems\n */\nexport function parseRoutePath(filePath: string, basePath: string): ParsedRoute {\n // Clean file:// URLs if present\n if (filePath.startsWith('file://')) {\n filePath = filePath.replace('file://', '');\n }\n if (basePath.startsWith('file://')) {\n basePath = basePath.replace('file://', '');\n }\n\n // Convert all backslashes to forward slashes for consistent handling\n const forwardSlashFilePath = filePath.replace(/\\\\/g, '/');\n const forwardSlashBasePath = basePath.replace(/\\\\/g, '/');\n\n // Ensure the base path ends with a slash for proper prefix removal\n const normalizedBasePath = forwardSlashBasePath.endsWith('/')\n ? forwardSlashBasePath\n : `${forwardSlashBasePath}/`;\n\n // Remove the base path to get the relative path\n let relativePath = forwardSlashFilePath;\n if (forwardSlashFilePath.startsWith(normalizedBasePath)) {\n relativePath = forwardSlashFilePath.substring(normalizedBasePath.length);\n } else if (forwardSlashFilePath.startsWith(forwardSlashBasePath)) {\n relativePath = forwardSlashFilePath.substring(forwardSlashBasePath.length);\n // If base path didn't end with a slash but we still matched, ensure relative path doesn't start with a slash\n if (relativePath.startsWith('/')) {\n relativePath = relativePath.substring(1);\n }\n } else {\n // If base path isn't a prefix of file path, use path.relative as a fallback\n // But convert to forward slashes for consistency\n relativePath = path.relative(forwardSlashBasePath, forwardSlashFilePath).replace(/\\\\/g, '/');\n }\n\n // Remove file extension (anything after the last dot)\n relativePath = relativePath.replace(/\\.[^.]+$/, '');\n\n // Split the path into segments\n const segments = relativePath.split('/').filter(Boolean);\n const params: string[] = [];\n\n // Transform file path segments to route path segments\n const routeSegments = segments.map(segment => {\n // Handle dynamic parameters ([param])\n if (segment.startsWith('[') && segment.endsWith(']')) {\n const paramName = segment.slice(1, -1);\n params.push(paramName);\n return `:${paramName}`;\n }\n return segment;\n });\n\n // Create the final route path\n let routePath = routeSegments.length > 0 ? `/${routeSegments.join('/')}` : '/';\n\n // Handle index routes\n if (routePath.endsWith('/index')) {\n routePath = routePath.slice(0, -6) || '/';\n }\n\n return {\n filePath,\n routePath,\n params,\n };\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\nimport EventEmitter from 'node:events';\n\nimport { setRuntimeConfig } from '../config';\nimport { startServer } from './start';\nimport { registerSignalHandlers, stopServer } from './stop';\nimport { validateServerOptions } from './validation';\nimport { createPluginLifecycleManager } from '../plugins/lifecycle';\nimport { validatePlugin } from '../plugins/validation';\nimport { createRouter } from '../router/router';\n\nimport type {\n Context,\n Middleware,\n Plugin,\n Server,\n ServerOptions,\n ServerOptionsInput,\n StopOptions,\n} from '../index';\n\nexport const DEFAULT_OPTIONS: ServerOptions = {\n port: 3000,\n host: 'localhost',\n routesDir: './routes',\n http2: {\n enabled: true,\n },\n middleware: [],\n plugins: [],\n};\n\n/**\n * Creates the configuration options by merging defaults with user-provided options\n */\nfunction createServerOptions(options: ServerOptionsInput = {}): ServerOptions {\n const baseOptions: ServerOptions = { ...DEFAULT_OPTIONS };\n setRuntimeConfig({ routesDir: options.routesDir || baseOptions.routesDir });\n\n return {\n port: options.port ?? baseOptions.port,\n host: options.host ?? baseOptions.host,\n routesDir: options.routesDir ?? baseOptions.routesDir,\n http2: {\n enabled: options.http2?.enabled ?? baseOptions.http2?.enabled,\n keyFile: options.http2?.keyFile ?? baseOptions.http2?.keyFile,\n certFile: options.http2?.certFile ?? baseOptions.http2?.certFile,\n },\n middleware: [...(baseOptions.middleware || []), ...(options.middleware || [])],\n plugins: [...(baseOptions.plugins || []), ...(options.plugins || [])],\n };\n}\n\n/**\n * Creates the server listen method\n */\nfunction createListenMethod(\n serverInstance: Server,\n validatedOptions: ServerOptions,\n initialMiddleware: Middleware[],\n initialPlugins: Plugin[]\n): Server['listen'] {\n return async () => {\n // Initialize middleware and plugins\n await initializeComponents(serverInstance, initialMiddleware, initialPlugins);\n\n // Use the functional manager\n await serverInstance.pluginManager.initializePlugins(serverInstance);\n\n // Start the server\n await startServer(serverInstance, validatedOptions);\n\n await serverInstance.pluginManager.onServerStart(serverInstance, serverInstance.server);\n\n // Setup signal handlers and emit events\n setupServerLifecycle(serverInstance);\n\n return serverInstance;\n };\n}\n\n/**\n * Initializes middleware and plugins\n */\nasync function initializeComponents(\n serverInstance: Server,\n initialMiddleware: Middleware[],\n initialPlugins: Plugin[]\n): Promise<void> {\n // Initialize middleware from options\n for (const mw of initialMiddleware) {\n serverInstance.use(mw);\n }\n\n // Register plugins from options\n for (const p of initialPlugins) {\n await serverInstance.register(p);\n }\n}\n\n/**\n * Sets up server lifecycle (signal handlers, events)\n */\nfunction setupServerLifecycle(serverInstance: Server): void {\n // Register signal handlers for graceful shutdown\n const signalHandlers = registerSignalHandlers(() => serverInstance.close());\n\n // Store handlers to unregister when server closes\n serverInstance._signalHandlers = signalHandlers;\n\n // Emit started event\n serverInstance.events.emit('started');\n}\n\n/**\n * Creates the server close method\n */\nfunction createCloseMethod(serverInstance: Server): Server['close'] {\n return async (stopOptions?: StopOptions) => {\n if (!serverInstance.server) {\n return;\n }\n\n // Prepare options\n const options: StopOptions = { ...stopOptions };\n\n // Unregister signal handlers if they exist\n if (serverInstance._signalHandlers) {\n serverInstance._signalHandlers.unregister();\n delete serverInstance._signalHandlers;\n }\n\n // Call stopServer with the server instance\n await stopServer(serverInstance, options);\n };\n}\n\n/**\n * Creates the server use method for adding middleware\n */\nfunction createUseMethod(serverInstance: Server): Server['use'] {\n return middleware => {\n const middlewareArray = Array.isArray(middleware) ? middleware : [middleware];\n serverInstance.middleware.push(...middlewareArray);\n return serverInstance;\n };\n}\n\n/**\n * Creates the server register method for plugins\n */\nfunction createRegisterMethod(serverInstance: Server): Server['register'] {\n return async plugin => {\n validatePlugin(plugin);\n serverInstance.plugins.push(plugin);\n await plugin.register(serverInstance);\n return serverInstance;\n };\n}\n\n/**\n * Creates a BlaizeJS server instance\n */\nexport function create(options: ServerOptionsInput = {}): Server {\n // Create and validate options\n const mergedOptions = createServerOptions(options);\n\n let validatedOptions: ServerOptions;\n try {\n validatedOptions = validateServerOptions(mergedOptions);\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to create server: ${error.message}`);\n }\n throw new Error(`Failed to create server: ${String(error)}`);\n }\n\n // Extract options and prepare initial components\n const { port, host, middleware, plugins } = validatedOptions;\n // TODO: create registries to manage middleware and plugins\n const initialMiddleware = Array.isArray(middleware) ? [...middleware] : [];\n const initialPlugins = Array.isArray(plugins) ? [...plugins] : [];\n\n // Initialize core server components\n const contextStorage = new AsyncLocalStorage<Context>();\n const router = createRouter({\n routesDir: validatedOptions.routesDir,\n watchMode: process.env.NODE_ENV === 'development',\n });\n // Create plugin lifecycle manager\n const pluginManager = createPluginLifecycleManager({\n debug: process.env.NODE_ENV === 'development',\n continueOnError: true,\n });\n const events = new EventEmitter();\n\n // Create server instance with minimal properties\n const serverInstance: Server = {\n server: null as any,\n port,\n host,\n context: contextStorage,\n events,\n plugins: [],\n middleware: [],\n _signalHandlers: { unregister: () => {} },\n use: () => serverInstance,\n register: async () => serverInstance,\n listen: async () => serverInstance,\n close: async () => {},\n router,\n pluginManager,\n };\n\n // Add methods to the server instance\n serverInstance.listen = createListenMethod(\n serverInstance,\n validatedOptions,\n initialMiddleware,\n initialPlugins\n );\n serverInstance.close = createCloseMethod(serverInstance);\n serverInstance.use = createUseMethod(serverInstance);\n serverInstance.register = createRegisterMethod(serverInstance);\n\n return serverInstance;\n}\n","import * as fs from 'node:fs';\nimport * as http from 'node:http';\nimport * as http2 from 'node:http2';\n\nimport { generateDevCertificates } from './dev-certificate';\nimport { createRequestHandler } from './request-handler';\n\nimport type { Http2Options, Server, ServerOptions } from '../index';\n\n// Extract certificate handling to a separate function\nasync function prepareCertificates(\n http2Options: Http2Options\n): Promise<{ keyFile?: string; certFile?: string }> {\n // Not using HTTP/2? No certificates needed\n if (!http2Options.enabled) {\n return {};\n }\n\n const { keyFile, certFile } = http2Options;\n\n // If certificates are missing and in development, generate them\n const isDevMode = process.env.NODE_ENV === 'development';\n const certificatesMissing = !keyFile || !certFile;\n\n if (certificatesMissing && isDevMode) {\n const devCerts = await generateDevCertificates();\n return devCerts;\n }\n\n // If certificates are still missing, throw error\n if (certificatesMissing) {\n throw new Error(\n 'HTTP/2 requires SSL certificates. Provide keyFile and certFile in http2 options. ' +\n 'In development, set NODE_ENV=development to generate them automatically.'\n );\n }\n\n return { keyFile, certFile };\n}\n\n// Create server based on protocol\nfunction createServerInstance(\n isHttp2: boolean,\n certOptions: { keyFile?: string; certFile?: string }\n): http.Server | http2.Http2SecureServer {\n if (!isHttp2) {\n return http.createServer();\n }\n\n // Create HTTP/2 server options\n const http2ServerOptions: http2.SecureServerOptions = {\n allowHTTP1: true, // Allow fallback to HTTP/1.1\n };\n\n // Read certificate files\n try {\n if (certOptions.keyFile) {\n http2ServerOptions.key = fs.readFileSync(certOptions.keyFile);\n }\n if (certOptions.certFile) {\n http2ServerOptions.cert = fs.readFileSync(certOptions.certFile);\n }\n } catch (err) {\n throw new Error(\n `Failed to read certificate files: ${err instanceof Error ? err.message : String(err)}`\n );\n }\n\n return http2.createSecureServer(http2ServerOptions);\n}\n\n// Start listening on the specified port and host\nfunction listenOnPort(\n server: http.Server | http2.Http2SecureServer,\n port: number,\n host: string,\n isHttp2: boolean\n): Promise<void> {\n return new Promise((resolve, reject) => {\n server.listen(port, host, () => {\n const protocol = isHttp2 ? 'https' : 'http';\n const url = `${protocol}://${host}:${port}`;\n console.log(`\n🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥\n\n ⚡ BlaizeJS DEVELOPMENT SERVER HOT AND READY ⚡\n \n 🚀 Server: ${url}\n 🔥 Hot Reload: Enabled\n 🛠️ Mode: Development\n \n Time to build something amazing! 🚀\n\n🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥\n`);\n resolve();\n });\n\n server.on('error', err => {\n console.error('Server error:', err);\n reject(err);\n });\n });\n}\n\nasync function initializePlugins(serverInstance: Server): Promise<void> {\n for (const plugin of serverInstance.plugins) {\n if (typeof plugin.initialize === 'function') {\n await plugin.initialize(serverInstance);\n }\n }\n}\n\n// Main server start function - now with much lower complexity\nexport async function startServer(\n serverInstance: Server,\n serverOptions: ServerOptions\n): Promise<void> {\n // Server already running? Do nothing.\n if (serverInstance.server) {\n return;\n }\n\n try {\n // Get effective port and host\n const port = serverOptions.port;\n const host = serverOptions.host;\n\n // Initialize all registered plugins\n await initializePlugins(serverInstance);\n\n // Determine if using HTTP/2\n const http2Options = serverOptions.http2 || { enabled: true };\n const isHttp2 = !!http2Options.enabled;\n\n // Prepare certificates if needed\n const certOptions = await prepareCertificates(http2Options);\n\n // Update the server options if we generated certificates\n if (serverOptions.http2 && certOptions.keyFile && certOptions.certFile) {\n serverOptions.http2.keyFile = certOptions.keyFile;\n serverOptions.http2.certFile = certOptions.certFile;\n }\n\n // Create the server instance\n const server = createServerInstance(isHttp2, certOptions);\n\n // Store the server in the instance\n serverInstance.server = server;\n\n // Update server instance properties\n serverInstance.port = port;\n serverInstance.host = host;\n\n // Configure request handling\n const requestHandler = createRequestHandler(serverInstance);\n server.on('request', requestHandler);\n\n // Start listening\n await listenOnPort(server, port, host, isHttp2);\n } catch (error) {\n console.error('Failed to start server:', error);\n throw error;\n }\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\n\nimport * as selfsigned from 'selfsigned';\n\nexport interface DevCertificates {\n keyFile: string;\n certFile: string;\n}\n\nexport async function generateDevCertificates(): Promise<DevCertificates> {\n const certDir = path.join(process.cwd(), '.blaizejs', 'certs');\n const keyPath = path.join(certDir, 'dev.key');\n const certPath = path.join(certDir, 'dev.cert');\n \n // Check if certificates already exist\n if (fs.existsSync(keyPath) && fs.existsSync(certPath)) {\n return {\n keyFile: keyPath,\n certFile: certPath\n };\n }\n \n // Create directory if it doesn't exist\n if (!fs.existsSync(certDir)) {\n fs.mkdirSync(certDir, { recursive: true });\n }\n \n // Generate self-signed certificate\n const attrs = [{ name: 'commonName', value: 'localhost' }];\n const options = {\n days: 365,\n algorithm: 'sha256',\n keySize: 2048,\n extensions: [\n { name: 'basicConstraints', cA: true },\n {\n name: 'keyUsage',\n keyCertSign: true,\n digitalSignature: true,\n nonRepudiation: true,\n keyEncipherment: true,\n dataEncipherment: true\n },\n {\n name: 'extKeyUsage',\n serverAuth: true,\n clientAuth: true\n },\n {\n name: 'subjectAltName',\n altNames: [\n { type: 2, value: 'localhost' },\n { type: 7, ip: '127.0.0.1' }\n ]\n }\n ]\n };\n \n // Generate the certificates\n const pems = selfsigned.generate(attrs, options);\n \n // Write the key and certificate to files\n fs.writeFileSync(keyPath, Buffer.from(pems.private, 'utf-8'));\n fs.writeFileSync(certPath, Buffer.from(pems.cert, 'utf-8'));\n \n console.log(`\\n🔒 Generated self-signed certificates for development at ${certDir}\\n`);\n \n return {\n keyFile: keyPath,\n certFile: certPath\n };\n}","export class ResponseSentError extends Error {\n constructor(message: string = '❌ Response has already been sent') {\n super(message);\n this.name = 'ResponseSentError';\n }\n}\n\nexport class ResponseSentHeaderError extends ResponseSentError {\n constructor(message: string = 'Cannot set header after response has been sent') {\n super(message);\n }\n}\n\nexport class ResponseSentContentError extends ResponseSentError {\n constructor(message: string = 'Cannot set content type after response has been sent') {\n super(message);\n }\n}\n\nexport class ParseUrlError extends ResponseSentError {\n constructor(message: string = 'Invalide URL') {\n super(message);\n }\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\n\nimport type { Context, QueryParams, State, UnknownFunction } from '../index';\n\n/**\n * AsyncLocalStorage instance for storing request context\n */\nexport const contextStorage = new AsyncLocalStorage<Context>();\n\n/**\n * Returns the current context from AsyncLocalStorage\n */\nexport function getContext<S extends State = State, TBody = unknown, TQuery = QueryParams>():\n | Context<S, TBody, TQuery>\n | undefined {\n return contextStorage.getStore() as Context<S, TBody, TQuery> | undefined;\n}\n\n/**\n * Wraps a callback function with a context\n */\nexport function runWithContext<T>(\n context: Context,\n callback: () => T | Promise<T>\n): T | Promise<T> {\n return contextStorage.run(context, callback);\n}\n\n/**\n * Middleware function that ensures a context is available in AsyncLocalStorage\n */\nexport async function contextMiddleware(\n context: Context,\n next: () => Promise<void>\n): Promise<void> {\n return runWithContext(context, next);\n}\n\n/**\n * Utility to check if code is running within a context\n */\nexport function hasContext(): boolean {\n return contextStorage.getStore() !== undefined;\n}\n\n/**\n * Creates a function that will run with the current context\n *\n * @param fn The function to bind to the current context\n * @returns A function that will execute with the bound context\n */\nexport function bindContext<TFunction extends UnknownFunction>(fn: TFunction): TFunction {\n const context = getContext();\n if (!context) {\n return fn;\n }\n\n // Using function instead of arrow function to preserve 'this'\n return function (this: unknown, ...args: Parameters<TFunction>): ReturnType<TFunction> {\n return runWithContext(context, () => fn.apply(this, args)) as ReturnType<TFunction>;\n } as TFunction;\n}\n","import {\n ParseUrlError,\n ResponseSentContentError,\n ResponseSentError,\n ResponseSentHeaderError,\n} from './errors';\nimport { hasContext, getContext } from './store';\n\nimport type {\n Context,\n ContextOptions,\n QueryParams,\n RequestParams,\n State,\n StreamOptions,\n UnifiedRequest,\n UnifiedResponse,\n} from '../index';\n\nconst CONTENT_TYPE_HEADER = 'Content-Type';\n\n/**\n * Parse URL and extract path and query parameters using modern URL API\n */\nfunction parseRequestUrl(req: UnifiedRequest): {\n path: string;\n url: URL | null;\n query: QueryParams;\n} {\n const originalUrl = (req as any).url || '/';\n\n // Construct full URL for parsing\n const host = req.headers.host || 'localhost';\n const protocol = req.socket && (req.socket as any).encrypted ? 'https' : 'http';\n const fullUrl = `${protocol}://${host}${originalUrl.startsWith('/') ? '' : '/'}${originalUrl}`;\n try {\n const url = new URL(fullUrl);\n\n // Extract path\n const path = url.pathname;\n\n // Parse query parameters using URLSearchParams\n const query: QueryParams = {};\n url.searchParams.forEach((value, key) => {\n // Handle array parameters (key=value1&key=value2)\n if (query[key] !== undefined) {\n if (Array.isArray(query[key])) {\n (query[key] as string[]).push(value);\n } else {\n query[key] = [query[key] as string, value];\n }\n } else {\n query[key] = value;\n }\n });\n\n return { path, url, query };\n } catch (error) {\n // Fallback for invalid URLs\n console.warn(`Invalid URL: ${fullUrl}`, error);\n throw new ParseUrlError(`Invalid URL: ${fullUrl}`);\n }\n}\n\n/**\n * Determine if the request is using HTTP/2\n */\nfunction isHttp2Request(req: UnifiedRequest): boolean {\n // Check for HTTP/2 specific properties\n return 'stream' in req || ('httpVersionMajor' in req && (req as any).httpVersionMajor === 2);\n}\n\n/**\n * Get the HTTP protocol (http or https)\n */\nfunction getProtocol(req: UnifiedRequest): string {\n // Check for encrypted socket\n const encrypted = req.socket && (req.socket as any).encrypted;\n // Check for X-Forwarded-Proto header (common in proxy environments)\n const forwardedProto = req.headers['x-forwarded-proto'];\n\n if (forwardedProto) {\n if (Array.isArray(forwardedProto)) {\n // Handle array of header values (uncommon but possible)\n return forwardedProto[0]?.split(',')[0]?.trim() || 'http';\n } else {\n // Handle string header value (typical case)\n return forwardedProto.split(',')[0]?.trim() || 'http';\n }\n }\n\n // Default protocol based on socket encryption\n return encrypted ? 'https' : 'http';\n}\n\n/**\n * Create a new context object for a request/response cycle\n */\nexport async function createContext<TBody = unknown, TQuery = QueryParams>(\n req: UnifiedRequest,\n res: UnifiedResponse,\n options: ContextOptions = {}\n): Promise<Context<State, TBody, TQuery>> {\n // Extract basic request information\n const { path, url, query } = parseRequestUrl(req);\n const method = req.method || 'GET';\n const isHttp2 = isHttp2Request(req);\n const protocol = getProtocol(req);\n\n // Initialize state\n const params: RequestParams = {};\n const state = { ...(options.initialState || {}) };\n\n // Track response status\n const responseState = { sent: false };\n\n // Create the context object with its components\n const ctx: Context<State, TBody, TQuery> = {\n request: createRequestObject<TBody, TQuery>(req, {\n path,\n url,\n query: query as TQuery,\n params,\n method,\n isHttp2,\n protocol,\n }),\n response: {} as Context<State, TBody, TQuery>['response'],\n state,\n };\n\n ctx.response = createResponseObject(res, responseState, ctx);\n\n // Parse body if requested\n if (options.parseBody) {\n await parseBodyIfNeeded(req, ctx);\n }\n\n return ctx;\n}\n\n/**\n * Create the request object portion of the context\n */\nfunction createRequestObject<TBody = unknown, TQuery = QueryParams>(\n req: UnifiedRequest,\n info: {\n path: string;\n url: URL | null;\n query: TQuery;\n params: RequestParams;\n method: string;\n isHttp2: boolean;\n protocol: string;\n }\n): Context<State, TBody, TQuery>['request'] {\n return {\n raw: req,\n ...info,\n header: createRequestHeaderGetter(req),\n headers: createRequestHeadersGetter(req),\n body: undefined as unknown as TBody,\n };\n}\n\n/**\n * Create a function to get a single request header\n */\nfunction createRequestHeaderGetter(req: UnifiedRequest) {\n return (name: string): string | undefined => {\n const value = req.headers[name.toLowerCase()];\n if (Array.isArray(value)) {\n return value.join(', ');\n }\n return value || undefined;\n };\n}\n\n/**\n * Create a function to get multiple request headers\n */\nfunction createRequestHeadersGetter(req: UnifiedRequest) {\n const headerGetter = createRequestHeaderGetter(req);\n\n return (names?: string[]): Record<string, string | undefined> => {\n if (names && Array.isArray(names) && names.length > 0) {\n return names.reduce<Record<string, string | undefined>>((acc, name) => {\n acc[name] = headerGetter(name);\n return acc;\n }, {});\n } else {\n return Object.entries(req.headers).reduce<Record<string, string | undefined>>(\n (acc, [key, value]) => {\n acc[key] = Array.isArray(value) ? value.join(', ') : value || undefined;\n return acc;\n },\n {}\n );\n }\n };\n}\n\n/**\n * Create the response object portion of the context\n */\nfunction createResponseObject<S extends State = State, TBody = unknown, TQuery = QueryParams>(\n res: UnifiedResponse,\n responseState: { sent: boolean },\n ctx: Context<S, TBody, TQuery>\n): Context<S, TBody, TQuery>['response'] {\n return {\n raw: res,\n\n get sent() {\n return responseState.sent;\n },\n\n status: createStatusSetter(res, responseState, ctx),\n header: createHeaderSetter(res, responseState, ctx),\n headers: createHeadersSetter(res, responseState, ctx),\n type: createContentTypeSetter(res, responseState, ctx),\n\n json: createJsonResponder(res, responseState),\n text: createTextResponder(res, responseState),\n html: createHtmlResponder(res, responseState),\n redirect: createRedirectResponder(res, responseState),\n stream: createStreamResponder(res, responseState),\n };\n}\n\n/**\n * Create a function to set response status\n */\nfunction createStatusSetter<S extends State = State, TBody = unknown, TQuery = QueryParams>(\n res: UnifiedResponse,\n responseState: { sent: boolean },\n ctx: Context<S, TBody, TQuery>\n) {\n return function statusSetter(code: number): Context['response'] {\n if (responseState.sent) {\n throw new ResponseSentError();\n }\n res.statusCode = code;\n return ctx.response;\n };\n}\n\n/**\n * Create a function to set a response header\n */\nfunction createHeaderSetter<S extends State = State, TBody = unknown, TQuery = QueryParams>(\n res: UnifiedResponse,\n responseState: { sent: boolean },\n ctx: Context<S, TBody, TQuery>\n) {\n return function headerSetter(name: string, value: string) {\n if (responseState.sent) {\n throw new ResponseSentHeaderError();\n }\n res.setHeader(name, value);\n return ctx.response;\n };\n}\n\n/**\n * Create a function to set multiple response headers\n */\nfunction createHeadersSetter<S extends State = State, TBody = unknown, TQuery = QueryParams>(\n res: UnifiedResponse,\n responseState: { sent: boolean },\n ctx: Context<S, TBody, TQuery>\n) {\n return function headersSetter(headers: Record<string, string>) {\n if (responseState.sent) {\n throw new ResponseSentHeaderError();\n }\n for (const [name, value] of Object.entries(headers)) {\n res.setHeader(name, value);\n }\n return ctx.response;\n };\n}\n\n/**\n * Create a function to set content type header\n */\nfunction createContentTypeSetter<S extends State = State, TBody = unknown, TQuery = QueryParams>(\n res: UnifiedResponse,\n responseState: { sent: boolean },\n ctx: Context<S, TBody, TQuery>\n) {\n return function typeSetter(type: string) {\n if (responseState.sent) {\n throw new ResponseSentContentError();\n }\n res.setHeader(CONTENT_TYPE_HEADER, type);\n return ctx.response;\n };\n}\n\n/**\n * Create a function to send JSON response\n */\nfunction createJsonResponder(res: UnifiedResponse, responseState: { sent: boolean }) {\n return function jsonResponder(body: unknown, status?: number) {\n if (responseState.sent) {\n throw new ResponseSentError();\n }\n\n if (status !== undefined) {\n res.statusCode = status;\n }\n\n res.setHeader(CONTENT_TYPE_HEADER, 'application/json');\n res.end(JSON.stringify(body));\n responseState.sent = true;\n };\n}\n\n/**\n * Create a function to send text response\n */\nfunction createTextResponder(res: UnifiedResponse, responseState: { sent: boolean }) {\n return function textResponder(body: string, status?: number) {\n if (responseState.sent) {\n throw new ResponseSentError();\n }\n\n if (status !== undefined) {\n res.statusCode = status;\n }\n\n res.setHeader(CONTENT_TYPE_HEADER, 'text/plain');\n res.end(body);\n responseState.sent = true;\n };\n}\n\n/**\n * Create a function to send HTML response\n */\nfunction createHtmlResponder(res: UnifiedResponse, responseState: { sent: boolean }) {\n return function htmlResponder(body: string, status?: number) {\n if (responseState.sent) {\n throw new ResponseSentError();\n }\n\n if (status !== undefined) {\n res.statusCode = status;\n }\n\n res.setHeader(CONTENT_TYPE_HEADER, 'text/html');\n res.end(body);\n responseState.sent = true;\n };\n}\n\n/**\n * Create a function to send redirect response\n */\nfunction createRedirectResponder(res: UnifiedResponse, responseState: { sent: boolean }) {\n return function redirectResponder(url: string, status = 302) {\n if (responseState.sent) {\n throw new ResponseSentError();\n }\n\n res.statusCode = status;\n res.setHeader('Location', url);\n res.end();\n responseState.sent = true;\n };\n}\n\n/**\n * Create a function to stream response\n */\nfunction createStreamResponder(res: UnifiedResponse, responseState: { sent: boolean }) {\n return function streamResponder(readable: NodeJS.ReadableStream, options: StreamOptions = {}) {\n if (responseState.sent) {\n throw new ResponseSentError();\n }\n\n if (options.status !== undefined) {\n res.statusCode = options.status;\n }\n\n if (options.contentType) {\n res.setHeader(CONTENT_TYPE_HEADER, options.contentType);\n }\n\n if (options.headers) {\n for (const [name, value] of Object.entries(options.headers)) {\n res.setHeader(name, value);\n }\n }\n\n // Handle streaming\n readable.pipe(res);\n\n // Mark as sent when the stream ends\n readable.on('end', () => {\n responseState.sent = true;\n });\n\n // Handle errors\n readable.on('error', err => {\n console.error('Stream error:', err);\n if (!responseState.sent) {\n res.statusCode = 500;\n res.end('Stream error');\n responseState.sent = true;\n }\n });\n };\n}\n\n/**\n * Parse request body if enabled in options\n */\nasync function parseBodyIfNeeded<TBody = unknown, TQuery = QueryParams>(\n req: UnifiedRequest,\n ctx: Context<State, TBody, TQuery>\n): Promise<void> {\n // Skip parsing for methods that typically don't have bodies\n if (shouldSkipParsing(req.method)) {\n return;\n }\n\n const contentType = req.headers['content-type'] || '';\n const contentLength = parseInt(req.headers['content-length'] || '0', 10);\n\n // Skip if no content or very large (can be handled by dedicated middleware)\n if (contentLength === 0 || contentLength > 1048576) {\n // 1MB limit for built-in parser\n return;\n }\n\n try {\n await parseBodyByContentType(req, ctx, contentType);\n } catch (error) {\n setBodyError(ctx, 'body_read_error', 'Error reading request body', error);\n }\n}\n\n/**\n * Determine if body parsing should be skipped based on HTTP method\n */\nfunction shouldSkipParsing(method?: string): boolean {\n const skipMethods = ['GET', 'HEAD', 'OPTIONS'];\n return skipMethods.includes(method || 'GET');\n}\n\n/**\n * Parse the body based on content type\n */\nasync function parseBodyByContentType<TBody = unknown, TQuery = QueryParams>(\n req: UnifiedRequest,\n ctx: Context<State, TBody, TQuery>,\n contentType: string\n): Promise<void> {\n if (contentType.includes('application/json')) {\n await parseJsonBody(req, ctx);\n } else if (contentType.includes('application/x-www-form-urlencoded')) {\n await parseFormUrlEncodedBody(req, ctx);\n } else if (contentType.includes('text/')) {\n await parseTextBody(req, ctx);\n }\n // For other content types, do nothing (let specialized middleware handle it)\n}\n\n/**\n * Parse JSON request body\n */\nasync function parseJsonBody<TBody = unknown, TQuery = QueryParams>(\n req: UnifiedRequest,\n ctx: Context<State, TBody, TQuery>\n): Promise<void> {\n const body = await readRequestBody(req);\n\n if (!body) {\n console.warn('Empty body, skipping JSON parsing');\n return;\n }\n\n // Check if the body is actually \"null\" string\n if (body.trim() === 'null') {\n console.warn('Body is the string \"null\"');\n ctx.request.body = null as TBody;\n return;\n }\n\n try {\n const json = JSON.parse(body);\n ctx.request.body = json as TBody;\n } catch (error) {\n ctx.request.body = null as TBody;\n setBodyError(ctx, 'json_parse_error', 'Invalid JSON in request body', error);\n }\n}\n\n/**\n * Parse URL-encoded form data\n */\nasync function parseFormUrlEncodedBody<TBody = unknown, TQuery = QueryParams>(\n req: UnifiedRequest,\n ctx: Context<State, TBody, TQuery>\n): Promise<void> {\n const body = await readRequestBody(req);\n if (!body) return;\n\n try {\n ctx.request.body = parseUrlEncodedData(body) as TBody;\n } catch (error) {\n ctx.request.body = null as TBody;\n setBodyError(ctx, 'form_parse_error', 'Invalid form data in request body', error);\n }\n}\n\n/**\n * Parse URL-encoded data into an object\n */\nfunction parseUrlEncodedData(body: string): Record<string, string | string[]> {\n const params = new URLSearchParams(body);\n const formData: Record<string, string | string[]> = {};\n\n params.forEach((value, key) => {\n if (formData[key] !== undefined) {\n if (Array.isArray(formData[key])) {\n (formData[key] as string[]).push(value);\n } else {\n formData[key] = [formData[key] as string, value];\n }\n } else {\n formData[key] = value;\n }\n });\n\n return formData;\n}\n\n/**\n * Parse plain text body\n */\nasync function parseTextBody<TBody = null, TQuery = QueryParams>(\n req: UnifiedRequest,\n ctx: Context<State, TBody, TQuery>\n): Promise<void> {\n const body = await readRequestBody(req);\n if (body) {\n ctx.request.body = body as TBody;\n }\n}\n\n/**\n * Set body parsing error in context state\n */\nfunction setBodyError<TBody = unknown, TQuery = QueryParams>(\n ctx: Context<State, TBody, TQuery>,\n type: string,\n message: string,\n error: unknown\n): void {\n ctx.state._bodyError = { type, message, error };\n}\n\n/**\n * Read the entire request body as a string\n */\nasync function readRequestBody(req: UnifiedRequest): Promise<string> {\n return new Promise<string>((resolve, reject) => {\n const chunks: Buffer[] = [];\n\n req.on('data', (chunk: Buffer | string) => {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n });\n\n req.on('end', () => {\n resolve(Buffer.concat(chunks).toString('utf8'));\n });\n\n req.on('error', err => {\n reject(err);\n });\n });\n}\n\n/**\n * Get the current context or throw an error if none exists\n */\nexport function getCurrentContext<\n S extends State = State,\n TBody = unknown,\n TQuery = QueryParams,\n>(): Context<S, TBody, TQuery> {\n const ctx = getContext<S, TBody, TQuery>();\n if (!ctx) {\n throw new Error(\n 'No context found. Ensure this function is called within a request handler, ' +\n 'middleware, or function wrapped with runWithContext().'\n );\n }\n return ctx;\n}\n\n/**\n * Check if we're currently in a request context\n */\nexport function isInRequestContext(): boolean {\n return hasContext();\n}\n","import { createContext } from '../context/create';\nimport { runWithContext } from '../context/store';\nimport { compose } from '../middleware/compose';\n\nimport type { RequestHandler, Server } from '../index';\n\nexport function createRequestHandler(serverInstance: Server): RequestHandler {\n return async (req, res) => {\n try {\n // Create context for this request\n const context = await createContext(req, res, {\n parseBody: true, // Enable automatic body parsing\n });\n\n // Compose all middleware into a single function\n const handler = compose(serverInstance.middleware);\n\n // Run the request with context in AsyncLocalStorage\n await runWithContext(context, async () => {\n try {\n // Execute the middleware chain\n await handler(context, async () => {\n if (!context.response.sent) {\n // Let the router handle the request\n await serverInstance.router.handleRequest(context);\n // If router didn't handle it either, send a 404\n if (!context.response.sent) {\n context.response.status(404).json({\n error: 'Not Found',\n message: `Route not found: ${context.request.method} ${context.request.path}`,\n });\n }\n }\n });\n } catch (error) {\n // Handle errors in middleware chain\n console.error('Error processing request:', error);\n\n // Only send error response if one hasn't been sent already\n if (!context.response.sent) {\n context.response.json(\n {\n error: 'Internal Server Error',\n message:\n process.env.NODE_ENV === 'development'\n ? error || 'Unknown error'\n : 'An error occurred processing your request',\n },\n 500\n );\n }\n }\n });\n } catch (error) {\n // Handle errors in context creation\n console.error('Error creating context:', error);\n res.writeHead(500, { 'Content-Type': 'application/json' });\n res.end(\n JSON.stringify({\n error: 'Internal Server Error',\n message: 'Failed to process request',\n })\n );\n }\n };\n}\n","import type { Server, StopOptions } from '../index';\n\n// Add a global flag to prevent multiple shutdowns\nlet isShuttingDown = false;\n\n// Replace the stopServer function in stop.ts with this version:\n\nexport async function stopServer(serverInstance: Server, options: StopOptions = {}): Promise<void> {\n const server = serverInstance.server;\n const events = serverInstance.events;\n\n if (isShuttingDown) {\n console.log('⚠️ Shutdown already in progress, ignoring duplicate shutdown request');\n return;\n }\n\n if (!server) {\n return;\n }\n\n isShuttingDown = true;\n const timeout = options.timeout || 5000; // Reduced to 5 seconds for faster restarts\n\n try {\n if (options.onStopping) {\n await options.onStopping();\n }\n\n events.emit('stopping');\n\n // Close router watchers with timeout\n if (serverInstance.router && typeof serverInstance.router.close === 'function') {\n console.log('🔌 Closing router watchers...');\n try {\n // Add timeout to router close\n await Promise.race([\n serverInstance.router.close(),\n new Promise((_, reject) =>\n setTimeout(() => reject(new Error('Router close timeout')), 2000)\n ),\n ]);\n console.log('✅ Router watchers closed');\n } catch (error) {\n console.error('❌ Error closing router watchers:', error);\n // Continue with shutdown\n }\n }\n\n // Notify plugins with timeout\n try {\n await Promise.race([\n serverInstance.pluginManager.onServerStop(serverInstance, server),\n new Promise((_, reject) =>\n setTimeout(() => reject(new Error('Plugin stop timeout')), 2000)\n ),\n ]);\n } catch (error) {\n console.error('❌ Plugin stop timeout:', error);\n // Continue with shutdown\n }\n\n // Create server close promise with shorter timeout\n const closePromise = new Promise<void>((resolve, reject) => {\n server.close((err?: Error) => {\n if (err) return reject(err);\n resolve();\n });\n });\n\n const timeoutPromise = new Promise<never>((_, reject) => {\n setTimeout(() => {\n reject(new Error('Server shutdown timeout'));\n }, timeout);\n });\n\n await Promise.race([closePromise, timeoutPromise]);\n\n // Terminate plugins with timeout\n try {\n await Promise.race([\n serverInstance.pluginManager.terminatePlugins(serverInstance),\n new Promise((_, reject) =>\n setTimeout(() => reject(new Error('Plugin terminate timeout')), 1000)\n ),\n ]);\n } catch (error) {\n console.error('❌ Plugin terminate timeout:', error);\n // Continue with shutdown\n }\n\n if (options.onStopped) {\n await options.onStopped();\n }\n\n events.emit('stopped');\n serverInstance.server = null as any;\n\n console.log('✅ Graceful shutdown completed');\n isShuttingDown = false;\n } catch (error) {\n isShuttingDown = false;\n console.error('⚠️ Shutdown error (forcing exit):', error);\n\n // Force close the server if graceful shutdown fails\n if (server && typeof server.close === 'function') {\n server.close();\n }\n\n // In development, force exit to allow tsx to restart\n if (process.env.NODE_ENV === 'development') {\n console.log('🔄 Forcing exit for development restart...');\n process.exit(0);\n }\n\n events.emit('error', error);\n throw error;\n }\n}\n\n/**\n * Register signal handlers for graceful shutdown\n */\nexport function registerSignalHandlers(stopFn: () => Promise<void>): { unregister: () => void } {\n const isDevelopment = process.env.NODE_ENV === 'development';\n\n if (isDevelopment) {\n // Development: Force exit for fast restarts\n const sigintHandler = () => {\n console.log('📤 SIGINT received, forcing exit for development restart...');\n process.exit(0);\n };\n\n const sigtermHandler = () => {\n console.log('📤 SIGTERM received, forcing exit for development restart...');\n process.exit(0);\n };\n\n process.on('SIGINT', sigintHandler);\n process.on('SIGTERM', sigtermHandler);\n\n return {\n unregister: () => {\n process.removeListener('SIGINT', sigintHandler);\n process.removeListener('SIGTERM', sigtermHandler);\n },\n };\n } else {\n // Production: Graceful shutdown\n const sigintHandler = () => {\n console.log('📤 SIGINT received, starting graceful shutdown...');\n stopFn().catch(console.error);\n };\n\n const sigtermHandler = () => {\n console.log('📤 SIGTERM received, starting graceful shutdown...');\n stopFn().catch(console.error);\n };\n\n process.on('SIGINT', sigintHandler);\n process.on('SIGTERM', sigtermHandler);\n\n return {\n unregister: () => {\n process.removeListener('SIGINT', sigintHandler);\n process.removeListener('SIGTERM', sigtermHandler);\n },\n };\n }\n}\n","import { z } from 'zod';\n\nimport type { ServerOptions, ServerOptionsInput, Middleware, Plugin } from '../index';\n\n// Create a more flexible validation for the middleware function type\nconst middlewareSchema = z.custom<Middleware>(\n data =>\n data !== null &&\n typeof data === 'object' &&\n 'execute' in data &&\n typeof data.execute === 'function',\n {\n message: 'Expected middleware to have an execute function',\n }\n);\n\n// Create a schema for plugins\nconst pluginSchema = z.custom<Plugin>(\n data =>\n data !== null &&\n typeof data === 'object' &&\n 'register' in data &&\n typeof data.register === 'function',\n {\n message: 'Expected a valid plugin object with a register method',\n }\n);\n\n// Create a schema for HTTP/2 options with conditional validation\nconst http2Schema = z\n .object({\n enabled: z.boolean().optional().default(true),\n keyFile: z.string().optional(),\n certFile: z.string().optional(),\n })\n .refine(\n data => {\n // If HTTP/2 is enabled and not in development mode,\n // both keyFile and certFile must be provided\n if (data.enabled && process.env.NODE_ENV === 'production') {\n return data.keyFile && data.certFile;\n }\n return true;\n },\n {\n message:\n 'When HTTP/2 is enabled (outside of development mode), both keyFile and certFile must be provided',\n }\n );\n\n// Validation schema for server options\nexport const serverOptionsSchema = z.object({\n port: z.number().int().positive().optional().default(3000),\n host: z.string().optional().default('localhost'),\n routesDir: z.string().optional().default('./routes'),\n http2: http2Schema.optional().default({\n enabled: true,\n }),\n middleware: z.array(middlewareSchema).optional().default([]),\n plugins: z.array(pluginSchema).optional().default([]),\n});\n\nexport function validateServerOptions(options: ServerOptionsInput): ServerOptions {\n try {\n return serverOptionsSchema.parse(options);\n } catch (error) {\n // Properly type the error as Zod validation error\n if (error instanceof z.ZodError) {\n // Format the Zod error for better readability\n const formattedError = error.format();\n throw new Error(`Invalid server options: ${JSON.stringify(formattedError, null, 2)}`);\n }\n // For other types of errors\n throw new Error(`Invalid server options: ${String(error)}`);\n }\n}\n","import type { Server, Plugin, PluginLifecycleManager, PluginLifecycleOptions } from '../index';\n\n/**\n * Create a plugin lifecycle manager\n */\nexport function createPluginLifecycleManager(\n options: PluginLifecycleOptions = {}\n): PluginLifecycleManager {\n const { continueOnError = true, debug = false, onError } = options;\n\n /**\n * Log debug messages if enabled\n */\n function log(message: string, ...args: any[]) {\n if (debug) {\n console.log(`[PluginLifecycle] ${message}`, ...args);\n }\n }\n\n /**\n * Handle plugin errors\n */\n function handleError(plugin: Plugin, phase: string, error: Error) {\n const errorMessage = `Plugin ${plugin.name} failed during ${phase}: ${error.message}`;\n\n if (onError) {\n onError(plugin, phase, error);\n } else {\n console.error(errorMessage, error);\n }\n\n if (!continueOnError) {\n throw new Error(errorMessage);\n }\n }\n\n return {\n /**\n * Initialize all plugins\n */\n async initializePlugins(server: Server): Promise<void> {\n log('Initializing plugins...');\n\n for (const plugin of server.plugins) {\n if (plugin.initialize) {\n try {\n log(`Initializing plugin: ${plugin.name}`);\n await plugin.initialize(server);\n } catch (error) {\n handleError(plugin, 'initialize', error as Error);\n }\n }\n }\n\n log(`Initialized ${server.plugins.length} plugins`);\n },\n\n /**\n * Terminate all plugins in reverse order\n */\n async terminatePlugins(server: Server): Promise<void> {\n log('Terminating plugins...');\n\n const pluginsToTerminate = [...server.plugins].reverse();\n\n for (const plugin of pluginsToTerminate) {\n if (plugin.terminate) {\n try {\n log(`Terminating plugin: ${plugin.name}`);\n await plugin.terminate(server);\n } catch (error) {\n handleError(plugin, 'terminate', error as Error);\n }\n }\n }\n\n log(`Terminated ${pluginsToTerminate.length} plugins`);\n },\n\n /**\n * Notify plugins that the server has started\n */\n async onServerStart(server: Server, httpServer: any): Promise<void> {\n log('Notifying plugins of server start...');\n\n for (const plugin of server.plugins) {\n if (plugin.onServerStart) {\n try {\n log(`Notifying plugin of server start: ${plugin.name}`);\n await plugin.onServerStart(httpServer);\n } catch (error) {\n handleError(plugin, 'onServerStart', error as Error);\n }\n }\n }\n },\n\n /**\n * Notify plugins that the server is stopping\n */\n async onServerStop(server: Server, httpServer: any): Promise<void> {\n log('Notifying plugins of server stop...');\n\n const pluginsToNotify = [...server.plugins].reverse();\n\n for (const plugin of pluginsToNotify) {\n if (plugin.onServerStop) {\n try {\n log(`Notifying plugin of server stop: ${plugin.name}`);\n await plugin.onServerStop(httpServer);\n } catch (error) {\n handleError(plugin, 'onServerStop', error as Error);\n }\n }\n }\n },\n };\n}\n","export class PluginError extends Error {\n constructor(\n public pluginName: string,\n message: string,\n public cause?: Error\n ) {\n super(`Plugin \"${pluginName}\": ${message}`);\n this.name = 'PluginError';\n }\n}\n\nexport class PluginLifecycleError extends PluginError {\n constructor(\n pluginName: string,\n public phase: 'register' | 'initialize' | 'terminate' | 'start' | 'stop',\n cause: Error\n ) {\n super(pluginName, `Failed during ${phase} phase: ${cause.message}`, cause);\n this.name = 'PluginLifecycleError';\n }\n}\n\nexport class PluginDependencyError extends PluginError {\n constructor(\n pluginName: string,\n public missingDependency: string\n ) {\n super(pluginName, `Missing dependency: ${missingDependency}`);\n this.name = 'PluginDependencyError';\n }\n}\n\n// packages/blaizejs/src/plugins/errors.ts (or add to existing errors file)\n\nexport class PluginValidationError extends Error {\n constructor(\n public pluginName: string,\n message: string\n ) {\n super(`Plugin validation error${pluginName ? ` for \"${pluginName}\"` : ''}: ${message}`);\n this.name = 'PluginValidationError';\n }\n}\n\nexport class PluginRegistrationError extends Error {\n constructor(\n public pluginName: string,\n message: string\n ) {\n super(`Plugin registration error for \"${pluginName}\": ${message}`);\n this.name = 'PluginRegistrationError';\n }\n}\n","import { PluginValidationError } from './errors';\n\nimport type { Plugin } from '../index';\n\nexport interface PluginValidationOptions {\n /** Require specific plugin properties */\n requireVersion?: boolean;\n /** Validate plugin name format */\n validateNameFormat?: boolean;\n /** Check for reserved plugin names */\n checkReservedNames?: boolean;\n}\n\n/**\n * Reserved plugin names that cannot be used\n */\nconst RESERVED_NAMES = new Set([\n 'core',\n 'server',\n 'router',\n 'middleware',\n 'context',\n 'blaize',\n 'blaizejs',\n]);\n\n/**\n * Valid plugin name pattern (lowercase, letters, numbers, hyphens)\n */\nconst VALID_NAME_PATTERN = /^[a-z]([a-z0-9-]*[a-z0-9])?$/;\n\n/**\n * Valid semantic version pattern\n */\nconst VALID_VERSION_PATTERN = /^\\d+\\.\\d+\\.\\d+(?:-[a-zA-Z0-9-.]+)?(?:\\+[a-zA-Z0-9-.]+)?$/;\n\n/**\n * Validate a plugin object\n */\nexport function validatePlugin(\n plugin: unknown,\n options: PluginValidationOptions = {}\n): asserts plugin is Plugin {\n const { requireVersion = true, validateNameFormat = true, checkReservedNames = true } = options;\n\n // Basic type validation\n if (!plugin || typeof plugin !== 'object') {\n throw new PluginValidationError('', 'Plugin must be an object');\n }\n\n const p = plugin as any;\n\n // Validate name\n if (!p.name || typeof p.name !== 'string') {\n throw new PluginValidationError('', 'Plugin must have a name (string)');\n }\n\n // Validate name format\n if (validateNameFormat && !VALID_NAME_PATTERN.test(p.name)) {\n throw new PluginValidationError(\n p.name,\n 'Plugin name must be lowercase letters, numbers, and hyphens only'\n );\n }\n\n // Check reserved names\n if (checkReservedNames && RESERVED_NAMES.has(p.name.toLowerCase())) {\n throw new PluginValidationError(p.name, `Plugin name \"${p.name}\" is reserved`);\n }\n\n // Validate version\n if (requireVersion) {\n if (!p.version || typeof p.version !== 'string') {\n throw new PluginValidationError(p.name, 'Plugin must have a version (string)');\n }\n\n if (!VALID_VERSION_PATTERN.test(p.version)) {\n throw new PluginValidationError(\n p.name,\n 'Plugin version must follow semantic versioning (e.g., \"1.0.0\")'\n );\n }\n }\n\n // Validate register method\n if (!p.register || typeof p.register !== 'function') {\n throw new PluginValidationError(p.name, 'Plugin must have a register method (function)');\n }\n\n // Validate optional lifecycle methods\n const lifecycleMethods = ['initialize', 'terminate', 'onServerStart', 'onServerStop'];\n\n for (const method of lifecycleMethods) {\n if (p[method] && typeof p[method] !== 'function') {\n throw new PluginValidationError(p.name, `Plugin ${method} must be a function if provided`);\n }\n }\n\n // Validate dependencies if present\n // if (p.dependencies) {\n // if (!Array.isArray(p.dependencies) && typeof p.dependencies !== 'string') {\n // throw new PluginValidationError(\n // p.name,\n // 'Plugin dependencies must be a string or array of strings'\n // );\n // }\n\n // const deps = Array.isArray(p.dependencies) ? p.dependencies : [p.dependencies];\n // for (const dep of deps) {\n // if (typeof dep !== 'string') {\n // throw new PluginValidationError(p.name, 'Plugin dependencies must be strings');\n // }\n // }\n // }\n}\n\n/**\n * Validate plugin options object\n */\nexport function validatePluginOptions(pluginName: string, options: unknown, schema?: any): void {\n // Basic validation\n if (options !== undefined && typeof options !== 'object') {\n throw new PluginValidationError(pluginName, 'Plugin options must be an object');\n }\n\n // If a schema is provided, validate against it\n if (schema && options) {\n try {\n schema.parse(options);\n } catch (error) {\n throw new PluginValidationError(\n pluginName,\n `Plugin options validation failed: ${(error as Error).message}`\n );\n }\n }\n}\n\n/**\n * Validate plugin factory function\n */\nexport function validatePluginFactory(\n factory: unknown\n): asserts factory is (...args: any[]) => any {\n if (typeof factory !== 'function') {\n throw new PluginValidationError('', 'Plugin factory must be a function');\n }\n}\n\n/**\n * Check if a plugin name is valid\n */\nexport function isValidPluginName(name: string): boolean {\n return (\n typeof name === 'string' &&\n name.length > 0 &&\n VALID_NAME_PATTERN.test(name) &&\n !RESERVED_NAMES.has(name.toLowerCase())\n );\n}\n\n/**\n * Check if a version string is valid\n */\nexport function isValidVersion(version: string): boolean {\n return typeof version === 'string' && VALID_VERSION_PATTERN.test(version);\n}\n\n/**\n * Sanitize plugin name (remove invalid characters)\n */\nexport function sanitizePluginName(name: string): string {\n return name\n .toLowerCase()\n .replace(/[^a-z0-9-]/g, '-')\n .replace(/^-+|-+$/g, '')\n .replace(/-+/g, '-');\n}\n","import * as crypto from 'node:crypto';\nimport * as fs from 'node:fs/promises';\nimport { createRequire } from 'node:module';\nimport * as path from 'node:path';\n\nimport { loadRouteModule } from './loader';\n\nimport type { FileCache, Route } from '../../index';\n\nconst fileRouteCache = new Map<string, FileCache>();\n\nexport async function processChangedFile(\n filePath: string,\n routesDir: string,\n updateCache: boolean = true\n): Promise<Route[]> {\n const stat = await fs.stat(filePath);\n const lastModified = stat.mtime.getTime();\n const cachedEntry = fileRouteCache.get(filePath);\n\n // Skip if file hasn't changed by timestamp (only when updating cache)\n if (updateCache && cachedEntry && cachedEntry.timestamp === lastModified) {\n return cachedEntry.routes;\n }\n\n // Clear module cache for this specific file\n invalidateModuleCache(filePath);\n\n // Load only this file\n const routes = await loadRouteModule(filePath, routesDir);\n\n // Only update cache if requested\n if (updateCache) {\n // Calculate content hash for change detection\n const hash = hashRoutes(routes);\n\n // Update cache\n fileRouteCache.set(filePath, {\n routes,\n timestamp: lastModified,\n hash,\n });\n }\n\n return routes;\n}\n\nexport function hasRouteContentChanged(filePath: string, newRoutes: Route[]): boolean {\n const cachedEntry = fileRouteCache.get(filePath);\n if (!cachedEntry) {\n return true;\n }\n\n const newHash = hashRoutes(newRoutes);\n\n return cachedEntry.hash !== newHash;\n}\n\nexport function clearFileCache(filePath?: string): void {\n if (filePath) {\n fileRouteCache.delete(filePath);\n } else {\n fileRouteCache.clear();\n }\n}\n\nfunction hashRoutes(routes: Route[]): string {\n const routeData = routes.map(route => ({\n path: route.path,\n methods: Object.keys(route)\n .filter(key => key !== 'path')\n .sort()\n .map(method => {\n const methodDef = route[method as keyof Route] as any;\n const handlerString = methodDef?.handler ? methodDef.handler.toString() : null;\n return {\n method,\n // Include handler function string for change detection\n handler: handlerString,\n // Include middleware if present\n middleware: methodDef?.middleware ? methodDef.middleware.length : 0,\n // Include schema structure (but not full serialization which can be unstable)\n hasSchema: !!methodDef?.schema,\n schemaKeys: methodDef?.schema ? Object.keys(methodDef.schema).sort() : [],\n };\n }),\n }));\n\n const dataString = JSON.stringify(routeData);\n const hash = crypto.createHash('md5').update(dataString).digest('hex');\n\n return hash;\n}\n\nfunction invalidateModuleCache(filePath: string): void {\n try {\n // Try to resolve the absolute path\n const absolutePath = path.resolve(filePath);\n\n // Check if we're in a CommonJS environment (require is available)\n if (typeof require !== 'undefined') {\n // Delete from require cache if it exists\n delete require.cache[absolutePath];\n\n // Also try to resolve using require.resolve if the file exists\n try {\n const resolvedPath = require.resolve(absolutePath);\n delete require.cache[resolvedPath];\n } catch (resolveError) {\n // Type guard to ensure resolveError is an Error object\n const errorMessage =\n resolveError instanceof Error ? resolveError.message : String(resolveError);\n console.log(`⚠️ Could not resolve path: ${errorMessage}`);\n }\n } else {\n // In pure ESM environment, try to use createRequire for cache invalidation\n try {\n const require = createRequire(import.meta.url);\n delete require.cache[absolutePath];\n\n try {\n const resolvedPath = require.resolve(absolutePath);\n delete require.cache[resolvedPath];\n } catch {\n console.log(`⚠️ Could not resolve ESM path`);\n }\n } catch {\n console.log(`⚠️ createRequire not available in pure ESM`);\n }\n }\n } catch (error) {\n console.log(`⚠️ Error during module cache invalidation for ${filePath}:`, error);\n }\n}\n","import { parseRoutePath } from './parser';\n\nimport type { Route, RouteDefinition } from '../../index';\n\nexport async function dynamicImport(filePath: string) {\n // Add a cache-busting query parameter for ESM\n const cacheBuster = `?t=${Date.now()}`;\n const importPath = filePath + cacheBuster;\n\n try {\n const module = await import(importPath);\n console.log(`✅ Successfully imported module`);\n return module;\n } catch (error) {\n // Type guard to ensure resolveError is an Error object\n const errorMessage = error instanceof Error ? error.message : String(error);\n console.log(`⚠️ Error importing with cache buster, trying original path:`, errorMessage);\n // Fallback to original path\n return import(filePath);\n }\n}\n\n/**\n * Load route modules from a file - supports both default export and named exports\n */\nexport async function loadRouteModule(filePath: string, basePath: string): Promise<Route[]> {\n try {\n // Parse the route path from the file path\n const parsedRoute = parseRoutePath(filePath, basePath);\n // Dynamically import the module\n const module = await dynamicImport(filePath);\n console.log('📦 Module exports:', Object.keys(module));\n\n const routes: Route[] = [];\n\n // Method 1: Check for default export (existing pattern)\n if (module.default && typeof module.default === 'object') {\n const route: Route = {\n ...(module.default as RouteDefinition),\n path: parsedRoute.routePath,\n };\n\n routes.push(route);\n }\n\n // Method 2: Check for named exports that look like routes\n Object.entries(module).forEach(([exportName, exportValue]) => {\n // Skip default export (already handled) and non-objects\n if (exportName === 'default' || !exportValue || typeof exportValue !== 'object') {\n return;\n }\n\n // Check if this export looks like a route (has path property and HTTP methods)\n const potentialRoute = exportValue as any;\n\n if (isValidRoute(potentialRoute)) {\n // For named exports, we might want to use the export name or the route's path\n const route: Route = {\n ...potentialRoute,\n // Use the route's own path if it has one, otherwise derive from file\n path: parsedRoute.routePath,\n };\n\n routes.push(route);\n }\n });\n\n if (routes.length === 0) {\n console.warn(`Route file ${filePath} does not export any valid route definitions`);\n return [];\n }\n\n console.log(`✅ Successfully Loaded ${routes.length} route(s)`);\n return routes;\n } catch (error) {\n console.error(`Failed to load route module ${filePath}:`, error);\n return [];\n }\n}\n\n/**\n * Check if an object looks like a valid route\n */\nfunction isValidRoute(obj: any): boolean {\n if (!obj || typeof obj !== 'object') {\n return false;\n }\n\n // Check if it has at least one HTTP method\n const httpMethods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'];\n const hasHttpMethod = httpMethods.some(\n method => obj[method] && typeof obj[method] === 'object' && obj[method].handler\n );\n\n return hasHttpMethod;\n}\n","import * as os from 'node:os';\n\nimport { processChangedFile } from './cache';\nimport { findRouteFiles } from './finder';\n\nimport type { Route } from '../../index';\n\nexport async function processFilesInParallel(\n filePaths: string[],\n processor: (filePath: string) => Promise<Route[]>,\n concurrency: number = Math.max(1, Math.floor(os.cpus().length / 2))\n): Promise<Route[][]> {\n const chunks = chunkArray(filePaths, concurrency);\n const results: Route[][] = [];\n\n for (const chunk of chunks) {\n const chunkResults = await Promise.allSettled(chunk.map(filePath => processor(filePath)));\n\n const successfulResults = chunkResults\n .filter(result => result.status === 'fulfilled')\n .map(result => (result as PromiseFulfilledResult<Route[]>).value);\n\n results.push(...successfulResults);\n }\n\n return results;\n}\n\nexport async function loadInitialRoutesParallel(routesDir: string): Promise<Route[]> {\n const files = await findRouteFiles(routesDir);\n const routeArrays = await processFilesInParallel(files, filePath =>\n processChangedFile(filePath, routesDir)\n );\n\n return routeArrays.flat();\n}\n\nfunction chunkArray<T>(array: T[], chunkSize: number): T[][] {\n const chunks: T[][] = [];\n for (let i = 0; i < array.length; i += chunkSize) {\n chunks.push(array.slice(i, i + chunkSize));\n }\n return chunks;\n}\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\n\ninterface FindRouteFilesOptions {\n /** Directories to ignore */\n ignore?: string[] | undefined;\n}\n\n/**\n * Find all route files in the specified directory\n */\nexport async function findRouteFiles(\n routesDir: string,\n options: FindRouteFilesOptions = {}\n): Promise<string[]> {\n // Convert to absolute path if it's relative\n const absoluteDir = path.isAbsolute(routesDir)\n ? routesDir\n : path.resolve(process.cwd(), routesDir);\n\n console.log('Creating router with routes directory:', absoluteDir);\n\n // Check if directory exists\n try {\n const stats = await fs.stat(absoluteDir);\n if (!stats.isDirectory()) {\n throw new Error(`Route directory is not a directory: ${absoluteDir}`);\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new Error(`Route directory not found: ${absoluteDir}`);\n }\n throw error;\n }\n\n const routeFiles: string[] = [];\n const ignore = options.ignore || ['node_modules', '.git'];\n\n async function scanDirectory(dir: string) {\n const entries = await fs.readdir(dir, { withFileTypes: true });\n\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n\n // Skip ignored directories\n if (entry.isDirectory() && ignore.includes(entry.name)) {\n continue;\n }\n\n if (entry.isDirectory()) {\n await scanDirectory(fullPath);\n } else if (isRouteFile(entry.name)) {\n routeFiles.push(fullPath);\n }\n }\n }\n\n await scanDirectory(absoluteDir);\n return routeFiles;\n}\n\n/**\n * Check if a file is a valid route file\n */\nfunction isRouteFile(filename: string): boolean {\n // Route files are TypeScript/JavaScript files that don't start with underscore\n return !filename.startsWith('_') && (filename.endsWith('.ts') || filename.endsWith('.js'));\n}\n","import type { ReloadMetrics } from '../../index';\n\nconst profilerState: ReloadMetrics = {\n fileChanges: 0,\n totalReloadTime: 0,\n averageReloadTime: 0,\n slowReloads: [],\n};\n\nexport function trackReloadPerformance(filePath: string, startTime: number): void {\n const duration = Date.now() - startTime;\n\n profilerState.fileChanges++;\n profilerState.totalReloadTime += duration;\n profilerState.averageReloadTime = profilerState.totalReloadTime / profilerState.fileChanges;\n\n if (duration > 100) {\n profilerState.slowReloads.push({ file: filePath, time: duration });\n if (profilerState.slowReloads.length > 10) {\n profilerState.slowReloads.shift();\n }\n }\n\n if (process.env.NODE_ENV === 'development') {\n const emoji = duration < 50 ? '⚡' : duration < 100 ? '🔄' : '🐌';\n console.log(`${emoji} Route reload: ${filePath} (${duration}ms)`);\n }\n}\n\nexport function getReloadMetrics(): Readonly<ReloadMetrics> {\n return { ...profilerState };\n}\n\nexport function resetReloadMetrics(): void {\n profilerState.fileChanges = 0;\n profilerState.totalReloadTime = 0;\n profilerState.averageReloadTime = 0;\n profilerState.slowReloads = [];\n}\n\nexport function withPerformanceTracking<T extends (...args: any[]) => Promise<any>>(\n fn: T,\n filePath: string\n): T {\n console.log(`Tracking performance for: ${filePath}`);\n return (async (...args: Parameters<T>) => {\n const startTime = Date.now();\n try {\n const result = await fn(...args);\n trackReloadPerformance(filePath, startTime);\n return result;\n } catch (error) {\n trackReloadPerformance(filePath, startTime);\n throw error;\n }\n }) as T;\n}\n","import * as path from 'node:path';\n\nimport { watch } from 'chokidar';\n\nimport { hasRouteContentChanged, processChangedFile } from './cache';\nimport { findRouteFiles } from './finder';\n\nimport type { Route, WatchOptions } from '../../index';\n\n/**\n * Watch for route file changes\n */\nexport function watchRoutes(routesDir: string, options: WatchOptions = {}) {\n // Debounce rapid file changes\n const debounceMs = options.debounceMs || 16;\n const debouncedCallbacks = new Map<string, NodeJS.Timeout>();\n\n function createDebouncedCallback<T extends (...args: any[]) => void>(\n fn: T,\n filePath: string\n ): (...args: Parameters<T>) => void {\n return (...args: Parameters<T>) => {\n // Clear existing timeout for this file\n const existingTimeout = debouncedCallbacks.get(filePath);\n if (existingTimeout) {\n clearTimeout(existingTimeout);\n }\n\n // Set new timeout\n const timeoutId = setTimeout(() => {\n fn(...args);\n debouncedCallbacks.delete(filePath);\n }, debounceMs);\n\n debouncedCallbacks.set(filePath, timeoutId);\n };\n }\n // Track loaded routes by file path - now stores arrays of routes\n const routesByPath = new Map<string, Route[]>();\n\n // Initial loading of routes\n async function loadInitialRoutes() {\n try {\n const files = await findRouteFiles(routesDir, {\n ignore: options.ignore,\n });\n\n for (const filePath of files) {\n await loadAndNotify(filePath);\n }\n } catch (error) {\n handleError(error);\n }\n }\n\n // Optimized load and notify function\n async function loadAndNotify(filePath: string) {\n try {\n const existingRoutes = routesByPath.get(filePath);\n\n // Step 1: Load new routes WITHOUT updating cache\n const newRoutes = await processChangedFile(filePath, routesDir, false);\n\n if (!newRoutes || newRoutes.length === 0) {\n return;\n }\n\n // Step 2: Check if content has actually changed (cache still has old data)\n if (existingRoutes && !hasRouteContentChanged(filePath, newRoutes)) {\n return;\n }\n\n // Step 3: Content changed! Now update the cache\n await processChangedFile(filePath, routesDir, true);\n\n const normalizedPath = path.normalize(filePath);\n\n if (existingRoutes) {\n routesByPath.set(filePath, newRoutes);\n if (options.onRouteChanged) {\n options.onRouteChanged(normalizedPath, newRoutes);\n }\n } else {\n routesByPath.set(filePath, newRoutes);\n if (options.onRouteAdded) {\n options.onRouteAdded(normalizedPath, newRoutes);\n }\n }\n } catch (error) {\n console.log(`⚠️ Error processing file ${filePath}:`, error);\n handleError(error);\n }\n }\n\n // Handle route file removal\n function handleRemoved(filePath: string) {\n const normalizedPath = path.normalize(filePath);\n const routes = routesByPath.get(normalizedPath);\n\n if (routes && routes.length > 0 && options.onRouteRemoved) {\n options.onRouteRemoved(normalizedPath, routes);\n }\n\n routesByPath.delete(normalizedPath);\n }\n\n // Handle errors\n function handleError(error: unknown) {\n if (options.onError && error instanceof Error) {\n options.onError(error);\n } else {\n console.error('⚠️ Route watcher error:', error);\n }\n }\n\n // Start file watcher\n // Create optimized watcher\n const watcher = watch(routesDir, {\n // Much faster response times\n awaitWriteFinish: {\n stabilityThreshold: 50, // Reduced from 300ms\n pollInterval: 10, // Reduced from 100ms\n },\n\n // Performance optimizations\n usePolling: false,\n atomic: true,\n followSymlinks: false,\n depth: 10,\n\n // More aggressive ignoring\n ignored: [\n /(^|[/\\\\])\\../,\n /node_modules/,\n /\\.git/,\n /\\.DS_Store/,\n /Thumbs\\.db/,\n /\\.(test|spec)\\.(ts|js)$/,\n /\\.d\\.ts$/,\n /\\.map$/,\n /~$/,\n ...(options.ignore || []),\n ],\n });\n\n // Set up event handlers\n watcher\n .on('add', filePath => {\n const debouncedLoad = createDebouncedCallback(loadAndNotify, filePath);\n debouncedLoad(filePath);\n })\n .on('change', filePath => {\n const debouncedLoad = createDebouncedCallback(loadAndNotify, filePath);\n\n // Call debounced load for changed file\n debouncedLoad(filePath);\n })\n .on('unlink', filePath => {\n const debouncedRemove = createDebouncedCallback(handleRemoved, filePath);\n debouncedRemove(filePath);\n })\n .on('error', handleError);\n\n // Load initial routes\n loadInitialRoutes().catch(handleError);\n\n // Return control methods\n return {\n close: () => {\n // Clear any pending debounced callbacks\n debouncedCallbacks.forEach(timeout => clearTimeout(timeout));\n debouncedCallbacks.clear();\n\n return watcher.close();\n },\n getRoutes: () => {\n const allRoutes: Route[] = [];\n for (const routes of routesByPath.values()) {\n allRoutes.push(...routes);\n }\n return allRoutes;\n },\n getRoutesByFile: () => new Map(routesByPath),\n };\n}\n","import type { Context, ErrorHandlerOptions } from '../../index';\n\n/**\n * Handle a route error\n */\nexport function handleRouteError(\n ctx: Context,\n error: unknown,\n options: ErrorHandlerOptions = {}\n): void {\n // Log error if enabled\n if (options.log) {\n console.error('Route error:', error);\n }\n\n // Determine error status code\n const status = getErrorStatus(error);\n\n // Build error response\n const response: Record<string, unknown> = {\n error: getErrorType(error),\n message: getErrorMessage(error),\n };\n\n // Add details if enabled\n if (options.detailed) {\n // Add stack trace for Error instances\n if (error instanceof Error) {\n response.stack = error.stack;\n }\n\n // Add validation details if available (for any type of error)\n if (error && typeof error === 'object' && 'details' in error && error.details) {\n response.details = error.details;\n }\n }\n\n // Send error response\n ctx.response.status(status).json(response);\n}\n\n/**\n * Get the HTTP status code for an error\n */\nfunction getErrorStatus(error: unknown): number {\n if (error && typeof error === 'object') {\n // Check for status property\n if ('status' in error && typeof error.status === 'number') {\n return error.status;\n }\n\n // Check for statusCode property\n if ('statusCode' in error && typeof error.statusCode === 'number') {\n return error.statusCode;\n }\n\n // Check for code property that maps to status\n if ('code' in error && typeof error.code === 'string') {\n return getStatusFromCode(error.code);\n }\n }\n\n // Default to 500 for unknown errors\n return 500;\n}\n\n/**\n * Get a status code from an error code\n */\nfunction getStatusFromCode(code: string): number {\n switch (code) {\n case 'NOT_FOUND':\n return 404;\n case 'UNAUTHORIZED':\n return 401;\n case 'FORBIDDEN':\n return 403;\n case 'BAD_REQUEST':\n return 400;\n case 'CONFLICT':\n return 409;\n default:\n return 500;\n }\n}\n\n/**\n * Get the error type\n */\nfunction getErrorType(error: unknown): string {\n if (error && typeof error === 'object') {\n if ('type' in error && typeof error.type === 'string') {\n return error.type;\n }\n\n if ('name' in error && typeof error.name === 'string') {\n return error.name;\n }\n\n if (error instanceof Error) {\n return error.constructor.name;\n }\n }\n\n return 'Error';\n}\n\n/**\n * Get the error message\n */\nfunction getErrorMessage(error: unknown): string {\n if (error instanceof Error) {\n return error.message;\n }\n\n if (error && typeof error === 'object') {\n if ('message' in error && typeof error.message === 'string') {\n return error.message;\n }\n }\n\n return String(error);\n}\n","import { z } from 'zod';\n\n/**\n * Validate request body\n */\nexport function validateBody<T>(body: unknown, schema: z.ZodType<T>): T {\n if (schema instanceof z.ZodObject) {\n return schema.strict().parse(body) as T;\n }\n // Parse and validate with the provided schema\n return schema.parse(body);\n}\n","import { z } from 'zod';\n\n/**\n * Validate request parameters\n */\nexport function validateParams<T>(\n params: Record<string, string>,\n schema: z.ZodType<T, z.ZodTypeDef, unknown>\n): T {\n if (schema instanceof z.ZodObject) {\n // If schema is an object, ensure strict parsing\n return schema.strict().parse(params) as T;\n }\n // Parse and validate with the provided schema\n return schema.parse(params);\n}\n","import { z } from 'zod';\n\n/**\n * Validate query parameters\n */\nexport function validateQuery<T>(\n query: Record<string, string | string[] | undefined>,\n schema: z.ZodType<T, z.ZodTypeDef, unknown>\n): T {\n if (schema instanceof z.ZodObject) {\n // If schema is an object, ensure strict parsing\n return schema.strict().parse(query) as T;\n }\n // Parse and validate with the provided schema\n return schema.parse(query);\n}\n","import { z } from 'zod';\n\n/**\n * Validate response body\n */\nexport function validateResponse<T>(\n response: unknown,\n schema: z.ZodType<T, z.ZodTypeDef, unknown>\n): T {\n if (schema instanceof z.ZodObject) {\n return schema.strict().parse(response) as T;\n }\n // Parse and validate with the provided schema\n return schema.parse(response);\n}\n","import { z } from 'zod';\n\nimport { validateBody } from './body';\nimport { validateParams } from './params';\nimport { validateQuery } from './query';\nimport { validateResponse } from './response';\n\nimport type {\n RouteSchema,\n Context,\n Middleware,\n MiddlewareFunction,\n NextFunction,\n} from '../../index';\n\n/**\n * Create a validation middleware for request data\n */\nexport function createRequestValidator(schema: RouteSchema, debug: boolean = false): Middleware {\n const middlewareFn: MiddlewareFunction = async (ctx: Context, next: NextFunction) => {\n const errors: Record<string, unknown> = {};\n\n // Validate params if schema exists\n if (schema.params && ctx.request.params) {\n try {\n ctx.request.params = validateParams(ctx.request.params, schema.params);\n } catch (error) {\n errors.params = formatValidationError(error);\n }\n }\n\n // Validate query if schema exists\n if (schema.query && ctx.request.query) {\n try {\n ctx.request.query = validateQuery(ctx.request.query, schema.query);\n } catch (error) {\n errors.query = formatValidationError(error);\n }\n }\n\n // FIXED: Validate body if schema exists (regardless of body content)\n if (schema.body) {\n try {\n ctx.request.body = validateBody(ctx.request.body, schema.body);\n } catch (error) {\n errors.body = formatValidationError(error);\n }\n }\n\n // Handle validation errors\n if (Object.keys(errors).length > 0) {\n ctx.response.status(400).json({\n error: 'Validation Error',\n details: errors,\n });\n return;\n }\n\n // Continue if validation passed\n await next();\n };\n\n return {\n name: 'RequestValidator',\n execute: middlewareFn,\n debug,\n };\n}\n\n/**\n * Create a validation middleware for response data\n */\nexport function createResponseValidator<T>(\n responseSchema: z.ZodType<T, z.ZodTypeDef, unknown>,\n debug: boolean = false\n): Middleware {\n const middlewareFn: MiddlewareFunction = async (ctx, next) => {\n // Store the original json method\n const originalJson = ctx.response.json;\n\n // Override the json method to validate the response\n ctx.response.json = (body: unknown, status?: number) => {\n try {\n // Validate the response body\n const validatedBody = validateResponse(body, responseSchema);\n\n // Restore the original json method\n ctx.response.json = originalJson;\n\n // Send the validated response\n return originalJson.call(ctx.response, validatedBody, status);\n } catch (error) {\n // Restore the original json method\n ctx.response.json = originalJson;\n\n // Log validation error but don't expose to client\n console.error('Response validation error:', error);\n\n // Send an error response\n ctx.response.status(500).json({\n error: 'Internal Server Error',\n message: 'Response validation failed',\n });\n\n return ctx.response;\n }\n };\n\n await next();\n };\n\n return {\n name: 'ResponseValidator',\n execute: middlewareFn,\n debug,\n };\n}\n\n/**\n * Format a validation error\n */\nexport function formatValidationError(error: unknown): unknown {\n // Handle Zod errors\n if (\n error &&\n typeof error === 'object' &&\n 'format' in error &&\n typeof error.format === 'function'\n ) {\n return error.format();\n }\n\n // Handle other error types\n return error instanceof Error ? error.message : String(error);\n}\n","import { compose } from '../../middleware/compose';\nimport { createRequestValidator, createResponseValidator } from '../validation';\n\nimport type { Context, RouteMethodOptions } from '../../index';\n/**\n * Execute a route handler with its middleware\n */\nexport async function executeHandler(\n ctx: Context,\n routeOptions: RouteMethodOptions,\n params: Record<string, string>\n): Promise<void> {\n // Set up middleware chain\n const middleware = [...(routeOptions.middleware || [])];\n\n // Add validation middleware if schemas are defined\n if (routeOptions.schema) {\n if (routeOptions.schema.params || routeOptions.schema.query || routeOptions.schema.body) {\n middleware.unshift(createRequestValidator(routeOptions.schema));\n }\n\n if (routeOptions.schema.response) {\n middleware.push(createResponseValidator(routeOptions.schema.response));\n }\n }\n\n // Compose middleware with the final handler\n const handler = compose([...middleware]);\n\n // Execute the middleware chain\n await handler(ctx, async () => {\n // Execute the handler with the new argument style\n const result = await routeOptions.handler(ctx, params);\n\n // Handle the result if it wasn't already handled by the handler\n if (!ctx.response.sent && result !== undefined) {\n ctx.response.json(result);\n }\n });\n}\n","/**\n * Extract parameter values from a URL path\n */\nexport function extractParams(\n path: string,\n pattern: RegExp,\n paramNames: string[]\n): Record<string, string> {\n const match = pattern.exec(path);\n if (!match) {\n return {};\n }\n\n const params: Record<string, string> = {};\n\n // Extract parameter values from regex match groups\n for (let i = 0; i < paramNames.length; i++) {\n // Add 1 to index since the first capture group is at index 1\n params[paramNames[i]!] = match[i + 1] || '';\n }\n\n return params;\n}\n\n/**\n * Compile a path pattern with parameters\n */\nexport function compilePathPattern(path: string): { pattern: RegExp; paramNames: string[] } {\n const paramNames: string[] = [];\n\n // Special case for root path\n if (path === '/') {\n return {\n pattern: /^\\/$/,\n paramNames: [],\n };\n }\n\n // First escape special regex characters (except for : and [ ] which we process specially)\n let patternString = path.replace(/([.+*?^$(){}|\\\\])/g, '\\\\$1');\n\n // Replace route parameters with regex capture groups\n patternString = patternString\n // Replace :param syntax with capture groups\n .replace(/\\/:([^/]+)/g, (_, paramName) => {\n paramNames.push(paramName);\n return '/([^/]+)';\n })\n // Replace [param] syntax (for file-based routing)\n .replace(/\\/\\[([^\\]]+)\\]/g, (_, paramName) => {\n paramNames.push(paramName);\n return '/([^/]+)';\n });\n\n // Make the trailing slash optional (if not already the root path)\n // This adds an optional trailing slash to the end of the pattern\n patternString = `${patternString}(?:/)?`;\n\n // Create the regex pattern\n // This is safe because we've escaped special RegExp characters and\n // we're using developer-defined routes, not user input\n const pattern = new RegExp(`^${patternString}$`);\n\n return {\n pattern,\n paramNames,\n };\n}\n\n/**\n * Convert parameters object to URL query string\n */\nexport function paramsToQuery(params: Record<string, string | number | boolean>): string {\n const parts: string[] = [];\n\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined && value !== null) {\n const encodedKey = encodeURIComponent(key);\n const encodedValue = encodeURIComponent(String(value));\n parts.push(`${encodedKey}=${encodedValue}`);\n }\n }\n\n return parts.length > 0 ? `?${parts.join('&')}` : '';\n}\n\n/**\n * Build a URL with path parameters\n */\nexport function buildUrl(\n pathPattern: string,\n params: Record<string, string | number | boolean> = {},\n query: Record<string, string | number | boolean> = {}\n): string {\n // Extract path parameters and query parameters\n const pathParams: Record<string, string | number | boolean> = {};\n const queryParams: Record<string, string | number | boolean> = { ...query };\n\n // Find all parameter names in the path\n const paramNames: string[] = [];\n pathPattern.replace(/\\/:([^/]+)/g, (_, paramName) => {\n paramNames.push(paramName);\n return '/';\n });\n\n // Separate params into path params and additional query params\n for (const [key, value] of Object.entries(params)) {\n if (paramNames.includes(key)) {\n pathParams[key] = value;\n } else {\n queryParams[key] = value;\n }\n }\n\n // Replace path parameters\n let url = pathPattern;\n for (const [key, value] of Object.entries(pathParams)) {\n url = url.replace(`:${key}`, encodeURIComponent(String(value)));\n }\n\n // Add query string if needed\n const queryString = paramsToQuery(queryParams);\n\n return url + queryString;\n}\n","import { compilePathPattern, extractParams } from './params';\n\nimport type {\n HttpMethod,\n RouteMethodOptions,\n RouteMatch,\n Matcher,\n RouteEntry,\n Route,\n} from '../../index';\n\n/**\n * Create a route matcher\n */\nexport function createMatcher(): Matcher {\n // Private state\n const routes: RouteEntry[] = [];\n\n return {\n /**\n * Add a route to the matcher\n */\n add(path: string, method: HttpMethod, routeOptions: RouteMethodOptions) {\n const { pattern, paramNames } = compilePathPattern(path);\n\n const newRoute: RouteEntry = {\n path,\n method,\n pattern,\n paramNames,\n routeOptions,\n };\n\n // Find the insertion point using findIndex\n const insertIndex = routes.findIndex(route => paramNames.length < route.paramNames.length);\n\n // If no insertion point found, append to end\n if (insertIndex === -1) {\n routes.push(newRoute);\n } else {\n routes.splice(insertIndex, 0, newRoute);\n }\n },\n\n /**\n * Remove a route from the matcher by path\n */\n remove(path: string) {\n // Remove all routes that match the given path\n for (let i = routes.length - 1; i >= 0; i--) {\n if ((routes[i] as Route).path === path) {\n routes.splice(i, 1);\n }\n }\n },\n\n /**\n * Clear all routes from the matcher\n */\n clear() {\n routes.length = 0;\n },\n\n /**\n * Match a URL path to a route\n */\n match(path: string, method: HttpMethod): RouteMatch | null {\n // First, try to find an exact match for the method\n const pathname = path.split('?')[0];\n if (!pathname) return null;\n\n for (const route of routes) {\n // Skip routes that don't match the method\n if (route.method !== method) continue;\n\n // Try to match the path\n const match = route.pattern.exec(pathname);\n if (match) {\n // Extract parameters from the match\n const params = extractParams(path, route.pattern, route.paramNames);\n\n return {\n route: route.routeOptions,\n params,\n };\n }\n }\n\n // If no exact method match, check if path exists but method is different\n // This allows returning 405 Method Not Allowed instead of 404 Not Found\n const matchingPath = routes.find(\n route => route.method !== method && route.pattern.test(path)\n );\n\n if (matchingPath) {\n // Return null but with allowedMethods to indicate method not allowed\n return {\n route: null,\n params: {},\n methodNotAllowed: true,\n allowedMethods: routes\n .filter(route => route.pattern.test(path))\n .map(route => route.method),\n } as unknown as RouteMatch; // Type assertion for the extended return type\n }\n\n return null; // No match found\n },\n\n /**\n * Get all registered routes\n */\n getRoutes(): { path: string; method: HttpMethod }[] {\n return routes.map(route => ({\n path: route.path,\n method: route.method,\n }));\n },\n\n /**\n * Find routes matching a specific path\n */\n findRoutes(\n path: string\n ): { path: string; method: HttpMethod; params: Record<string, string> }[] {\n return routes\n .filter(route => route.pattern.test(path))\n .map(route => ({\n path: route.path,\n method: route.method,\n params: extractParams(path, route.pattern, route.paramNames),\n }));\n },\n };\n}\n","import type { Route, RouteRegistry } from '../../index';\n\nexport function createRouteRegistry(): RouteRegistry {\n return {\n routesByPath: new Map(),\n routesByFile: new Map(),\n pathToFile: new Map(),\n };\n}\n\nexport function updateRoutesFromFile(\n registry: RouteRegistry,\n filePath: string,\n newRoutes: Route[]\n): { added: Route[]; removed: string[]; changed: Route[] } {\n console.log(`Updating routes from file: ${filePath}`);\n const oldPaths = registry.routesByFile.get(filePath) || new Set();\n const newPaths = new Set(newRoutes.map(r => r.path));\n\n // Fast diff calculation\n const added = newRoutes.filter(r => !oldPaths.has(r.path));\n const removed = Array.from(oldPaths).filter(p => !newPaths.has(p));\n const potentiallyChanged = newRoutes.filter(r => oldPaths.has(r.path));\n\n // Check for actual content changes\n const changed = potentiallyChanged.filter(route => {\n const existingRoute = registry.routesByPath.get(route.path);\n return !existingRoute || !routesEqual(existingRoute, route);\n });\n\n // Apply updates\n applyRouteUpdates(registry, filePath, { added, removed, changed });\n\n return { added, removed, changed };\n}\n\nexport function getRouteFromRegistry(registry: RouteRegistry, path: string): Route | undefined {\n return registry.routesByPath.get(path);\n}\n\nexport function getAllRoutesFromRegistry(registry: RouteRegistry): Route[] {\n return Array.from(registry.routesByPath.values());\n}\n\nexport function getFileRoutes(registry: RouteRegistry, filePath: string): Route[] {\n const paths = registry.routesByFile.get(filePath) || new Set();\n return Array.from(paths)\n .map(path => registry.routesByPath.get(path)!)\n .filter(Boolean);\n}\n\nfunction applyRouteUpdates(\n registry: RouteRegistry,\n filePath: string,\n updates: { added: Route[]; removed: string[]; changed: Route[] }\n): void {\n const { added, removed, changed } = updates;\n\n // Remove old routes\n removed.forEach(path => {\n registry.routesByPath.delete(path);\n registry.pathToFile.delete(path);\n });\n\n // Add/update routes\n [...added, ...changed].forEach(route => {\n registry.routesByPath.set(route.path, route);\n registry.pathToFile.set(route.path, filePath);\n });\n\n // Update file -> paths mapping\n const allPathsForFile = new Set([\n ...added.map(r => r.path),\n ...changed.map(r => r.path),\n ...Array.from(registry.routesByFile.get(filePath) || []).filter(p => !removed.includes(p)),\n ]);\n\n if (allPathsForFile.size > 0) {\n registry.routesByFile.set(filePath, allPathsForFile);\n } else {\n registry.routesByFile.delete(filePath);\n }\n}\n\nfunction routesEqual(route1: Route, route2: Route): boolean {\n if (route1.path !== route2.path) return false;\n\n const methods1 = Object.keys(route1)\n .filter(k => k !== 'path')\n .sort();\n const methods2 = Object.keys(route2)\n .filter(k => k !== 'path')\n .sort();\n\n if (methods1.length !== methods2.length) return false;\n\n return methods1.every(method => {\n const handler1 = route1[method as keyof Route];\n const handler2 = route2[method as keyof Route];\n\n // Compare handler signatures/structure rather than function references\n return typeof handler1 === typeof handler2;\n });\n}\n","import type { Route, HttpMethod, RouteMethodOptions, Matcher } from '../../index';\n\nexport function addRouteToMatcher(route: Route, matcher: Matcher): void {\n Object.entries(route).forEach(([method, methodOptions]) => {\n if (method === 'path' || !methodOptions) return;\n matcher.add(route.path, method as HttpMethod, methodOptions as RouteMethodOptions);\n });\n}\n\nexport function removeRouteFromMatcher(path: string, matcher: Matcher): void {\n // Use matcher's remove method if available, otherwise fallback to clear/rebuild\n if ('remove' in matcher && typeof matcher.remove === 'function') {\n matcher.remove(path);\n } else {\n // This requires rebuilding the matcher - could be optimized\n console.warn('Matcher does not support selective removal, consider adding remove() method');\n }\n}\n\nexport function updateRouteInMatcher(route: Route, matcher: Matcher): void {\n removeRouteFromMatcher(route.path, matcher);\n addRouteToMatcher(route, matcher);\n}\n\nexport function rebuildMatcherWithRoutes(routes: Route[], matcher: Matcher): void {\n if ('clear' in matcher && typeof matcher.clear === 'function') {\n matcher.clear();\n }\n\n routes.forEach(route => addRouteToMatcher(route, matcher));\n}\n","import { clearFileCache } from './discovery/cache';\nimport { loadInitialRoutesParallel } from './discovery/parallel';\nimport { withPerformanceTracking } from './discovery/profiler';\nimport { watchRoutes } from './discovery/watchers';\nimport { executeHandler } from './handlers';\nimport { handleRouteError } from './handlers/error';\nimport { createMatcher } from './matching';\nimport {\n createRouteRegistry,\n updateRoutesFromFile,\n getAllRoutesFromRegistry,\n} from './registry/fast-registry';\nimport {\n addRouteToMatcher,\n removeRouteFromMatcher,\n updateRouteInMatcher,\n} from './utils/matching-helpers';\n\nimport type { Context, HttpMethod, Route, RouterOptions, Router } from '../index';\n\nconst DEFAULT_ROUTER_OPTIONS = {\n routesDir: './routes',\n basePath: '/',\n watchMode: process.env.NODE_ENV === 'development',\n};\n\n/**\n * Create an optimized router instance with fast hot reload\n */\nexport function createRouter(options: RouterOptions): Router {\n // Merge with default options\n const routerOptions = {\n ...DEFAULT_ROUTER_OPTIONS,\n ...options,\n };\n\n if (options.basePath && !options.basePath.startsWith('/')) {\n console.warn('Base path does nothing');\n }\n\n // Use optimized registry instead of simple array\n const registry = createRouteRegistry();\n const matcher = createMatcher();\n\n // Initialize routes\n let initialized = false;\n let initializationPromise: Promise<void> | null = null;\n let _watchers: Map<string, ReturnType<typeof watchRoutes>> | null = null;\n\n const routeDirectories = new Set<string>([routerOptions.routesDir]);\n\n /**\n * Apply registry changes to matcher efficiently\n */\n function applyMatcherChanges(changes: { added: Route[]; removed: string[]; changed: Route[] }) {\n console.log('\\n🔧 APPLYING MATCHER CHANGES:');\n console.log(` Adding ${changes.added.length} routes`);\n console.log(` Removing ${changes.removed.length} routes`);\n console.log(` Updating ${changes.changed.length} routes`);\n\n // Remove routes first\n changes.removed.forEach(routePath => {\n console.log(` ➖ Removing: ${routePath}`);\n removeRouteFromMatcher(routePath, matcher);\n });\n\n // Add new routes\n changes.added.forEach(route => {\n const methods = Object.keys(route).filter(key => key !== 'path');\n console.log(` ➕ Adding: ${route.path} [${methods.join(', ')}]`);\n addRouteToMatcher(route, matcher);\n });\n\n // Update changed routes\n changes.changed.forEach(route => {\n const methods = Object.keys(route).filter(key => key !== 'path');\n console.log(` 🔄 Updating: ${route.path} [${methods.join(', ')}]`);\n updateRouteInMatcher(route, matcher);\n });\n\n console.log('✅ Matcher changes applied\\n');\n }\n\n /**\n * Add multiple routes with batch processing\n */\n function addRoutesWithSource(routes: Route[], source: string) {\n try {\n // Use registry for batch conflict detection and management\n const changes = updateRoutesFromFile(registry, source, routes);\n\n // Apply all changes to matcher in one operation\n applyMatcherChanges(changes);\n\n return changes;\n } catch (error) {\n console.error(`⚠️ Route conflicts from ${source}:`, error);\n throw error;\n }\n }\n\n /**\n * Optimized route loading with parallel processing\n */\n async function loadRoutesFromDirectory(directory: string, source: string, prefix?: string) {\n try {\n // Use parallel loading for better performance\n const discoveredRoutes = await loadInitialRoutesParallel(directory);\n\n // Apply prefix if provided\n const finalRoutes = discoveredRoutes.map(route =>\n prefix ? { ...route, path: `${prefix}${route.path}` } : route\n );\n\n // Batch add all routes from this directory\n const changes = addRoutesWithSource(finalRoutes, source);\n\n console.log(\n `Loaded ${discoveredRoutes.length} routes from ${source}${prefix ? ` with prefix ${prefix}` : ''} ` +\n `(${changes.added.length} added, ${changes.changed.length} changed, ${changes.removed.length} removed)`\n );\n } catch (error) {\n console.error(`⚠️ Failed to load routes from ${source}:`, error);\n throw error;\n }\n }\n\n /**\n * Initialize the router with parallel route loading\n */\n async function initialize() {\n if (initialized || initializationPromise) {\n return initializationPromise;\n }\n\n initializationPromise = (async () => {\n try {\n // Load routes from all directories in parallel\n await Promise.all(\n Array.from(routeDirectories).map(directory =>\n loadRoutesFromDirectory(directory, directory)\n )\n );\n\n // Set up optimized watching\n if (routerOptions.watchMode) {\n setupOptimizedWatching();\n }\n\n initialized = true;\n } catch (error) {\n console.error('⚠️ Failed to initialize router:', error);\n throw error;\n }\n })();\n\n return initializationPromise;\n }\n\n /**\n * Setup optimized file watching with fast updates\n */\n function setupOptimizedWatching() {\n if (!_watchers) {\n _watchers = new Map();\n }\n\n for (const directory of routeDirectories) {\n if (!_watchers.has(directory)) {\n const watcher = watchRoutes(directory, {\n debounceMs: 16, // ~60fps debouncing\n ignore: ['node_modules', '.git'],\n\n onRouteAdded: (filepath: string, addedRoutes: Route[]) => {\n // Batch process all added routes\n try {\n const changes = updateRoutesFromFile(registry, filepath, addedRoutes);\n applyMatcherChanges(changes);\n } catch (error) {\n console.error(`Error adding routes from ${directory}:`, error);\n }\n },\n\n onRouteChanged: withPerformanceTracking(\n async (filepath: string, changedRoutes: Route[]) => {\n // console.log(`${changedRoutes.length} route(s) changed in ${directory}`);\n\n try {\n console.log(`Processing changes for ${filepath}`);\n // Process all changed routes in one batch operation\n const changes = updateRoutesFromFile(registry, filepath, changedRoutes);\n\n console.log(\n `Changes detected: ${changes.added.length} added, ` +\n `${changes.changed.length} changed, ${changes.removed.length} removed`\n );\n\n // Apply matcher updates efficiently\n applyMatcherChanges(changes);\n\n console.log(\n `Route changes applied: ${changes.added.length} added, ` +\n `${changes.changed.length} changed, ${changes.removed.length} removed`\n );\n } catch (error) {\n console.error(`⚠️ Error updating routes from ${directory}:`, error);\n }\n },\n directory\n ),\n\n onRouteRemoved: (filePath: string, removedRoutes: Route[]) => {\n console.log(`File removed: ${filePath} with ${removedRoutes.length} routes`);\n\n try {\n // Remove all routes from this file\n removedRoutes.forEach(route => {\n removeRouteFromMatcher(route.path, matcher);\n });\n\n // Clear cache for removed file\n clearFileCache(filePath);\n } catch (error) {\n console.error(`⚠️ Error removing routes from ${filePath}:`, error);\n }\n },\n\n onError: (error: Error) => {\n console.error(`⚠️ Route watcher error for ${directory}:`, error);\n },\n });\n\n _watchers.set(directory, watcher);\n }\n }\n }\n\n /**\n * Setup watcher for newly added directory\n */\n function setupWatcherForNewDirectory(directory: string, prefix?: string) {\n if (!_watchers) {\n _watchers = new Map();\n }\n\n const watcher = watchRoutes(directory, {\n debounceMs: 16,\n ignore: ['node_modules', '.git'],\n\n onRouteAdded: (filePath: string, addedRoutes: Route[]) => {\n try {\n // Apply prefix to all routes\n const finalRoutes = addedRoutes.map(route =>\n prefix ? { ...route, path: `${prefix}${route.path}` } : route\n );\n\n // Batch process all added routes\n const changes = updateRoutesFromFile(registry, filePath, finalRoutes);\n applyMatcherChanges(changes);\n } catch (error) {\n console.error(`⚠️ Error adding routes from ${directory}:`, error);\n }\n },\n\n onRouteChanged: withPerformanceTracking(async (filePath: string, changedRoutes: Route[]) => {\n try {\n // Apply prefix to all routes\n const finalRoutes = changedRoutes.map(route =>\n prefix ? { ...route, path: `${prefix}${route.path}` } : route\n );\n\n // Process all changed routes in one batch operation\n const changes = updateRoutesFromFile(registry, filePath, finalRoutes);\n applyMatcherChanges(changes);\n } catch (error) {\n console.error(`⚠️ Error updating routes from ${directory}:`, error);\n }\n }, directory),\n\n onRouteRemoved: (filePath: string, removedRoutes: Route[]) => {\n try {\n removedRoutes.forEach(route => {\n const finalPath = prefix ? `${prefix}${route.path}` : route.path;\n removeRouteFromMatcher(finalPath, matcher);\n });\n clearFileCache(filePath);\n } catch (error) {\n console.error(`Error removing routes from ${filePath}:`, error);\n }\n },\n\n onError: (error: Error) => {\n console.error(`⚠️ Route watcher error for ${directory}:`, error);\n },\n });\n\n _watchers.set(directory, watcher);\n return watcher;\n }\n\n // Initialize router on creation\n initialize().catch(error => {\n console.error('⚠️ Failed to initialize router on creation:', error);\n });\n\n // Public API\n return {\n /**\n * Handle an incoming request\n */\n async handleRequest(ctx: Context) {\n // Ensure router is initialized\n if (!initialized) {\n console.log('🔄 Router not initialized, initializing...');\n await initialize();\n }\n\n const { method, path } = ctx.request;\n console.log(`\\n📥 Handling request: ${method} ${path}`);\n\n // Find matching route\n const match = matcher.match(path, method as HttpMethod);\n\n if (!match) {\n console.log(`❌ No match found for: ${method} ${path}`);\n // Handle 404 Not Found\n ctx.response.status(404).json({ error: 'Not Found' });\n return;\n }\n\n console.log(`✅ Route matched: ${method} ${path}`);\n console.log(` Params: ${JSON.stringify(match.params)}`);\n\n // Check for method not allowed\n if (match.methodNotAllowed) {\n // Handle 405 Method Not Allowed\n ctx.response.status(405).json({\n error: '❌ Method Not Allowed',\n allowed: match.allowedMethods,\n });\n\n // Set Allow header with allowed methods\n if (match.allowedMethods && match.allowedMethods.length > 0) {\n ctx.response.header('Allow', match.allowedMethods.join(', '));\n }\n\n return;\n }\n\n // Extract route parameters\n ctx.request.params = match.params;\n\n // Execute the route handler with middleware\n try {\n await executeHandler(ctx, match.route!, match.params);\n } catch (error) {\n // Handle errors\n handleRouteError(ctx, error, {\n detailed: process.env.NODE_ENV !== 'production',\n log: true,\n });\n }\n },\n\n /**\n * Get all registered routes (using optimized registry)\n */\n getRoutes() {\n return getAllRoutesFromRegistry(registry);\n },\n\n /**\n * Add a route programmatically\n */\n addRoute(route: Route) {\n const changes = updateRoutesFromFile(registry, 'programmatic', [route]);\n applyMatcherChanges(changes);\n },\n\n /**\n * Add multiple routes programmatically with batch processing\n */\n addRoutes(routes: Route[]) {\n const changes = updateRoutesFromFile(registry, 'programmatic', routes);\n applyMatcherChanges(changes);\n return changes;\n },\n\n /**\n * Add a route directory (for plugins) with optimized loading\n */\n async addRouteDirectory(directory: string, options: { prefix?: string } = {}) {\n if (routeDirectories.has(directory)) {\n console.warn(`Route directory ${directory} already registered`);\n return;\n }\n\n routeDirectories.add(directory);\n\n // If already initialized, load routes immediately\n if (initialized) {\n await loadRoutesFromDirectory(directory, directory, options.prefix);\n\n // Set up watching for this directory if in watch mode\n if (routerOptions.watchMode) {\n setupWatcherForNewDirectory(directory, options.prefix);\n }\n }\n },\n\n /**\n * Get route conflicts (using registry)\n */\n getRouteConflicts() {\n // Registry handles conflict detection internally\n // This could be enhanced to expose more detailed conflict info\n const conflicts: Array<{ path: string; sources: string[] }> = [];\n // Implementation would depend on registry's conflict tracking\n return conflicts;\n },\n\n /**\n * Close watchers and cleanup (useful for testing)\n */\n async close() {\n if (_watchers) {\n for (const watcher of _watchers.values()) {\n await watcher.close();\n }\n _watchers.clear();\n }\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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cAAc;AACnD,iBAAe,WAAW,qBAAqB,cAAc;AAE7D,SAAO;AACT;;;ARjLO,IAAM,UAAU;AAGhB,IAAM,YAAY,EAAE,cAAAE,QAAa;AACjC,IAAM,YAAY;AAAA,EACvB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AACO,IAAM,gBAAgB,EAAE,0BAAkB,QAAQ;AAClD,IAAM,aAAa,EAAE,cAAAA,QAAa;AAGzC,IAAM,SAAS;AAAA;AAAA,EAEb,cAAAA;AAAA,EACA;AAAA,EACA,cAAAA;AAAA;AAAA,EAGA,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,SAAS;AAAA;AAAA,EAGT;AACF;AAEA,IAAO,gBAAQ;","names":["create","create","stack","config","path","import_node_async_hooks","fs","path","path","resolve","resolve","resolve","fs","path","module","stat","require","fs","path","path","import_zod","import_zod","import_zod","import_zod","path","path","path","path","path","options","create","contextStorage","EventEmitter","create"]}
|