@lithia-js/core 1.0.0-canary.2 → 1.0.0-canary.21

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.
Files changed (102) hide show
  1. package/README.md +26 -43
  2. package/dist/_index.d.ts +245 -0
  3. package/dist/_index.mjs +2106 -0
  4. package/dist/_index.mjs.map +1 -0
  5. package/dist/index.d.ts +824 -0
  6. package/dist/index.mjs +856 -0
  7. package/dist/index.mjs.map +1 -0
  8. package/dist/protocol-DBwVPJYN.d.ts +332 -0
  9. package/dist/tasks-X-3clDS8.d.ts +31 -0
  10. package/dist/workers/app-worker.d.ts +2 -0
  11. package/dist/workers/app-worker.mjs +1907 -0
  12. package/dist/workers/app-worker.mjs.map +1 -0
  13. package/dist/workers/task-worker.d.ts +45 -0
  14. package/dist/workers/task-worker.mjs +146 -0
  15. package/dist/workers/task-worker.mjs.map +1 -0
  16. package/package.json +47 -23
  17. package/CHANGELOG.md +0 -31
  18. package/dist/config.d.ts +0 -101
  19. package/dist/config.js +0 -113
  20. package/dist/config.js.map +0 -1
  21. package/dist/context/event-context.d.ts +0 -53
  22. package/dist/context/event-context.js +0 -42
  23. package/dist/context/event-context.js.map +0 -1
  24. package/dist/context/index.d.ts +0 -16
  25. package/dist/context/index.js +0 -29
  26. package/dist/context/index.js.map +0 -1
  27. package/dist/context/lithia-context.d.ts +0 -47
  28. package/dist/context/lithia-context.js +0 -43
  29. package/dist/context/lithia-context.js.map +0 -1
  30. package/dist/context/route-context.d.ts +0 -74
  31. package/dist/context/route-context.js +0 -42
  32. package/dist/context/route-context.js.map +0 -1
  33. package/dist/env.d.ts +0 -1
  34. package/dist/env.js +0 -32
  35. package/dist/env.js.map +0 -1
  36. package/dist/errors.d.ts +0 -51
  37. package/dist/errors.js +0 -80
  38. package/dist/errors.js.map +0 -1
  39. package/dist/hooks/dependency-hooks.d.ts +0 -105
  40. package/dist/hooks/dependency-hooks.js +0 -96
  41. package/dist/hooks/dependency-hooks.js.map +0 -1
  42. package/dist/hooks/event-hooks.d.ts +0 -61
  43. package/dist/hooks/event-hooks.js +0 -70
  44. package/dist/hooks/event-hooks.js.map +0 -1
  45. package/dist/hooks/index.d.ts +0 -41
  46. package/dist/hooks/index.js +0 -59
  47. package/dist/hooks/index.js.map +0 -1
  48. package/dist/hooks/route-hooks.d.ts +0 -154
  49. package/dist/hooks/route-hooks.js +0 -174
  50. package/dist/hooks/route-hooks.js.map +0 -1
  51. package/dist/lib.d.ts +0 -10
  52. package/dist/lib.js +0 -30
  53. package/dist/lib.js.map +0 -1
  54. package/dist/lithia.d.ts +0 -447
  55. package/dist/lithia.js +0 -649
  56. package/dist/lithia.js.map +0 -1
  57. package/dist/logger.d.ts +0 -11
  58. package/dist/logger.js +0 -55
  59. package/dist/logger.js.map +0 -1
  60. package/dist/module-loader.d.ts +0 -12
  61. package/dist/module-loader.js +0 -78
  62. package/dist/module-loader.js.map +0 -1
  63. package/dist/server/event-processor.d.ts +0 -195
  64. package/dist/server/event-processor.js +0 -253
  65. package/dist/server/event-processor.js.map +0 -1
  66. package/dist/server/http-server.d.ts +0 -196
  67. package/dist/server/http-server.js +0 -295
  68. package/dist/server/http-server.js.map +0 -1
  69. package/dist/server/middlewares/validation.d.ts +0 -12
  70. package/dist/server/middlewares/validation.js +0 -34
  71. package/dist/server/middlewares/validation.js.map +0 -1
  72. package/dist/server/request-processor.d.ts +0 -400
  73. package/dist/server/request-processor.js +0 -652
  74. package/dist/server/request-processor.js.map +0 -1
  75. package/dist/server/request.d.ts +0 -73
  76. package/dist/server/request.js +0 -207
  77. package/dist/server/request.js.map +0 -1
  78. package/dist/server/response.d.ts +0 -69
  79. package/dist/server/response.js +0 -173
  80. package/dist/server/response.js.map +0 -1
  81. package/src/config.ts +0 -212
  82. package/src/context/event-context.ts +0 -66
  83. package/src/context/index.ts +0 -32
  84. package/src/context/lithia-context.ts +0 -59
  85. package/src/context/route-context.ts +0 -89
  86. package/src/env.ts +0 -31
  87. package/src/errors.ts +0 -96
  88. package/src/hooks/dependency-hooks.ts +0 -122
  89. package/src/hooks/event-hooks.ts +0 -69
  90. package/src/hooks/index.ts +0 -58
  91. package/src/hooks/route-hooks.ts +0 -177
  92. package/src/lib.ts +0 -27
  93. package/src/lithia.ts +0 -777
  94. package/src/logger.ts +0 -66
  95. package/src/module-loader.ts +0 -45
  96. package/src/server/event-processor.ts +0 -344
  97. package/src/server/http-server.ts +0 -371
  98. package/src/server/middlewares/validation.ts +0 -46
  99. package/src/server/request-processor.ts +0 -860
  100. package/src/server/request.ts +0 -247
  101. package/src/server/response.ts +0 -204
  102. package/tsconfig.json +0 -8
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/errors/base.ts","../../src/errors/internal/loader.ts","../../src/context/lithia-context.ts","../../src/context/request-context.ts","../../src/errors/app/client.ts","../../src/errors/app/server.ts","../../src/transport/http/request.ts","../../src/shared/module-loader.ts","../../src/shared/pipeline.ts","../../src/transport/http/cors-policy.ts","../../src/transport/http/openapi-assets.ts","../../src/shared/digest.ts","../../src/transport/http/request-error-handler.ts","../../src/transport/http/route-matcher.ts","../../src/transport/http/static-assets.ts","../../src/transport/http/request-pipeline.ts","../../src/transport/http/response.ts","../../src/transport/socket/event-error-handler.ts","../../src/transport/socket/event-pipeline.ts","../../src/context/event-context.ts","../../src/transport/socket/socket-server.ts","../../src/transport/server.ts","../../src/runtime/app/dependency-container.ts","../../src/runtime/app/middleware-registry.ts","../../src/shared/filesystem.ts","../../src/runtime/app/server-bootstrap.ts","../../src/runtime/app/task-scheduler.ts","../../src/runtime/app/app-runtime.ts","../../src/runtime/workers/app-worker.ts"],"names":["AsyncLocalStorage","parseCookie","red","logger","join","serializeCookie","SocketServer","createHttpsServer","createHttpServer","access","readFile","path","bootstrap","parentPort"],"mappings":";;;;;;;;;;;;;;;;;;;AAGO,IAAM,WAAA,GAAN,cAA0B,KAAA,CAAM;AAAA,EACtB,aAAA,GAAgB,IAAA;AAAA,EAChC,YAAY,OAAA,EAAkB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\n * Base error type for Lithia-specific failures.\n */\nexport class LithiaError extends Error {\n\tpublic readonly isLithiaError = true;\n\tconstructor(message?: string) {\n\t\tsuper(message);\n\t\tthis.name = this.constructor.name;\n\t\tObject.setPrototypeOf(this, new.target.prototype); // Fixes inheritance in older environments\n\t}\n}\n\n/**\n * HTTP-oriented application error with a status code and optional details.\n *\n * Throw this from routes when you want Lithia to return a structured client\n * error response.\n */\nexport class LithiaClientError extends LithiaError {\n\tpublic readonly timestamp = new Date();\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic readonly statusCode: number,\n\t\tpublic readonly details?: any,\n\t) {\n\t\tsuper(message);\n\t}\n}\n\n/**\n * Event-oriented error that captures the event name and optional details.\n *\n * Used when socket event handling needs to surface a structured failure.\n */\nexport class LithiaEventError extends LithiaError {\n\tpublic readonly timestamp = new Date();\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic readonly eventName: string,\n\t\tpublic readonly details?: any,\n\t) {\n\t\tsuper(message);\n\t}\n}\n","import { LithiaError } from \"../base\";\n\n/** Raised when manifest versions do not match during startup. */\nexport class ManifestVersionMismatchError extends LithiaError {\n\tconstructor(expectedVersion: string, foundVersion: string) {\n\t\tsuper(\n\t\t\t`Manifest version mismatch: expected '${expectedVersion}', but found '${foundVersion}'. Rebuild required.`,\n\t\t);\n\t}\n}\n\n/** Raised when a required module is missing a default export. */\nexport class NoDefaultExportError extends LithiaError {\n\tconstructor(filePath: string) {\n\t\tsuper(`Module at '${filePath}' is missing a default export.`);\n\t}\n}\n\n/** Raised when a default export exists but is not an async function. */\nexport class NoAsyncDefaultExportError extends LithiaError {\n\tconstructor(filePath: string) {\n\t\tsuper(`Default export at '${filePath}' must be an async function.`);\n\t}\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { LithiaOptions } from \"../config\";\nimport { NotInLithiaContextError } from \"../errors/internal/index\";\n\nexport interface LithiaContext {\n\tcontainer: Map<any, any>;\n\tconfig: LithiaOptions;\n}\n\nconst LITHIA_CONTEXT_KEY = Symbol.for(\"lithia.base_context.v1\");\n\nfunction getGlobalLithiaStore(): AsyncLocalStorage<LithiaContext> {\n\tconst globalAny = globalThis as any;\n\tif (!globalAny[LITHIA_CONTEXT_KEY]) {\n\t\tglobalAny[LITHIA_CONTEXT_KEY] = new AsyncLocalStorage<LithiaContext>();\n\t}\n\treturn globalAny[LITHIA_CONTEXT_KEY];\n}\n\nexport const lithiaContextStore = getGlobalLithiaStore();\n\nexport function getLithiaContext(): LithiaContext {\n\tconst ctx = lithiaContextStore.getStore();\n\tif (!ctx) {\n\t\tthrow new NotInLithiaContextError();\n\t}\n\treturn ctx;\n}\n\nexport function runInLithiaContext<T>(context: LithiaContext, fn: () => T): T {\n\treturn lithiaContextStore.run(context, fn);\n}\n","/**\n * @fileoverview Route Context Management for Lithia.js.\n * Provides the execution scope for HTTP requests, wrapping the request,\n * response, and server metadata in a thread-safe AsyncLocalStorage container.\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { Server as SocketServer } from \"socket.io\";\nimport type { Route } from \"../discovery/routes\";\nimport { NotInRequestContextError } from \"../errors/internal/index\";\nimport type { LithiaRequest } from \"../transport/http/request\";\nimport type { LithiaResponse } from \"../transport/http/response\";\n\nexport interface RouteContext {\n\treq: LithiaRequest;\n\tres: LithiaResponse;\n\troute?: Route;\n\tsocketServer: SocketServer;\n}\n\nconst ROUTE_CONTEXT_KEY = Symbol.for(\"lithia.route_context.v1\");\n\nfunction getGlobalRouteStore(): AsyncLocalStorage<RouteContext> {\n\tconst globalAny = globalThis as any;\n\tif (!globalAny[ROUTE_CONTEXT_KEY]) {\n\t\tglobalAny[ROUTE_CONTEXT_KEY] = new AsyncLocalStorage<RouteContext>();\n\t}\n\treturn globalAny[ROUTE_CONTEXT_KEY];\n}\n\nexport const routeContextStore = getGlobalRouteStore();\n\nexport function getRouteContext(): RouteContext {\n\tconst ctx = routeContextStore.getStore();\n\tif (!ctx) {\n\t\tthrow new NotInRequestContextError();\n\t}\n\treturn ctx;\n}\n\nexport function runInRouteContext<T>(context: RouteContext, fn: () => T): T {\n\treturn routeContextStore.run(context, fn);\n}\n","import { LithiaClientError } from \"../base\";\n\n/**\n * Indicates that the client sent an invalid request.\n */\nexport class BadRequestError extends LithiaClientError {\n\tconstructor(m: string, d?: any) {\n\t\tsuper(m, 400, d);\n\t}\n}\n/**\n * Indicates that authentication is required or invalid.\n */\nexport class UnauthorizedError extends LithiaClientError {\n\tconstructor(m: string, d?: any) {\n\t\tsuper(m, 401, d);\n\t}\n}\n/**\n * Indicates that the authenticated client is not allowed to perform the action.\n */\nexport class ForbiddenError extends LithiaClientError {\n\tconstructor(m: string, d?: any) {\n\t\tsuper(m, 403, d);\n\t}\n}\n/**\n * Indicates that no matching route was found for the current request.\n */\nexport class RouteNotFoundError extends LithiaClientError {\n\tconstructor(m: string, d?: any) {\n\t\tsuper(m, 404, d);\n\t}\n}\n/**\n * Indicates that a requested resource does not exist.\n */\nexport class NotFoundError extends LithiaClientError {\n\tconstructor(m: string, d?: any) {\n\t\tsuper(m, 404, d);\n\t}\n}\n/**\n * Indicates that the request conflicts with the current server state.\n */\nexport class ConflictError extends LithiaClientError {\n\tconstructor(m: string, d?: any) {\n\t\tsuper(m, 409, d);\n\t}\n}\n","import { LithiaClientError } from \"../base\";\n\n/**\n * Indicates that the server hit an unexpected internal failure.\n */\nexport class InternalServerError extends LithiaClientError {\n\tconstructor(m: string, d?: any) {\n\t\tsuper(m, 500, d);\n\t}\n}\n/**\n * Indicates that the service is temporarily unavailable.\n */\nexport class ServiceUnavailableError extends LithiaClientError {\n\tconstructor(m: string, d?: any) {\n\t\tsuper(m, 503, d);\n\t}\n}\n/**\n * Indicates that an upstream operation timed out.\n */\nexport class GatewayTimeoutError extends LithiaClientError {\n\tconstructor(m: string, d?: any) {\n\t\tsuper(m, 504, d);\n\t}\n}\n","import type { IncomingHttpHeaders, IncomingMessage } from \"node:http\";\nimport busboy, { type FileInfo } from \"busboy\";\nimport { type Cookies, parse as parseCookie } from \"cookie\";\nimport { BadRequestError } from \"../../errors/app/index\";\n\n/**\n * Route params object populated by the route matcher.\n *\n * Keys correspond to dynamic segments extracted from the matched route pattern.\n * The values are assigned by the HTTP transport before the handler runs and\n * remain mutable for the lifetime of the current request context.\n */\nexport type Params = Record<string, any>;\n\n/**\n * Query object parsed from the incoming request URL.\n *\n * Each value is currently stored as the last string value observed for a given\n * query key during URL parsing.\n */\nexport type Query = Record<string, any>;\n\n/**\n * Uploaded multipart file returned by `req.files()`.\n *\n * Each file entry contains the metadata reported by Busboy plus the fully\n * buffered file contents collected while the multipart stream is parsed.\n */\nexport interface UploadedFile extends FileInfo {\n\tfieldname: string;\n\tbuffer: Buffer;\n}\n\n/**\n * Lithia wrapper around Node's `IncomingMessage`.\n *\n * Provides helpers for reading params, query, body, cookies, and multipart\n * uploads from route handlers and middleware.\n *\n * The wrapper parses URL-derived data eagerly in the constructor and reads the\n * request stream lazily only when `body()` or `files()` is called. Parsed\n * payloads are cached so route handlers and middleware can safely reuse the\n * same request wrapper without reparsing the stream.\n *\n * Related docs:\n * - https://lithiajs.org/docs/latest/routes\n * - https://lithiajs.org/docs/latest/project-structure\n */\nexport class LithiaRequest {\n\tpublic readonly headers: Readonly<IncomingHttpHeaders>;\n\tpublic readonly method: Readonly<string>;\n\tpublic readonly pathname: Readonly<string>;\n\tpublic query: Query;\n\tpublic params: Params;\n\n\tprivate readonly storage = new Map<string, unknown>();\n\tprivate _bodyCache: unknown | null = null;\n\tprivate _filesCache: UploadedFile[] | null = null;\n\tprivate _cookies: Cookies | null = null;\n\n\t/**\n\t * Creates a request wrapper for the current HTTP transaction.\n\t *\n\t * The constructor captures headers, reconstructs a best-effort absolute URL,\n\t * normalizes the HTTP method to uppercase, and initializes parsed query and\n\t * route-param containers for later middleware and handler use.\n\t *\n\t * @param {IncomingMessage} req - Raw Node.js request object received by the\n\t * HTTP server.\n\t * @param {{ maxBodySize?: number }} opts - Per-request parsing options used\n\t * when consuming the request body stream.\n\t */\n\tconstructor(\n\t\tprivate readonly req: IncomingMessage,\n\t\tprivate readonly opts: { maxBodySize?: number },\n\t) {\n\t\tthis.headers = req.headers;\n\t\tconst isSecure = this.isSecure();\n\t\tconst host = this.headers.host || req.headers.host || \"unknown\";\n\t\tconst fullUrl = `${isSecure ? \"https\" : \"http\"}://${host}${req.url || \"/\"}`;\n\t\tconst url = new URL(fullUrl);\n\n\t\tthis.pathname = url.pathname;\n\t\tthis.method = (req.method || \"GET\").toUpperCase();\n\t\tthis.query = parseQueryToObject(url.searchParams);\n\t\tthis.params = {};\n\t}\n\n\t/**\n\t * Returns the best-effort client IP address for the current request.\n\t *\n\t * The lookup prefers proxy-forwarded headers before falling back to the raw\n\t * socket address, which makes the result suitable for deployments behind\n\t * reverse proxies that preserve `x-forwarded-for` or `x-real-ip`.\n\t *\n\t * @returns {string} The resolved client IP address, or `\"unknown\"` when no\n\t * address can be derived.\n\t */\n\tpublic ip(): string {\n\t\treturn (\n\t\t\t(this.headers[\"x-forwarded-for\"] as string)?.split(\",\")[0]?.trim() ||\n\t\t\t(this.headers[\"x-real-ip\"] as string) ||\n\t\t\t(this.req.socket as any)?.remoteAddress ||\n\t\t\t\"unknown\"\n\t\t);\n\t}\n\n\t/**\n\t * Returns the current request user-agent string.\n\t *\n\t * @returns {string} The raw `user-agent` header value, or an empty string\n\t * when the header is missing.\n\t */\n\tpublic userAgent(): string {\n\t\treturn (this.headers[\"user-agent\"] as string) || \"\";\n\t}\n\n\t/**\n\t * Returns whether the current request is using HTTPS.\n\t *\n\t * The check prefers `x-forwarded-proto` for proxy-aware deployments and then\n\t * falls back to the encrypted state of the underlying socket.\n\t *\n\t * @returns {boolean} `true` when the request should be treated as HTTPS.\n\t */\n\tpublic isSecure(): boolean {\n\t\treturn (\n\t\t\t(this.headers[\"x-forwarded-proto\"] as string) === \"https\" ||\n\t\t\t(this.req.socket as any)?.encrypted === true\n\t\t);\n\t}\n\n\t/**\n\t * Returns the request host header.\n\t *\n\t * @returns {string} The current host header value, or `\"unknown\"` when it is\n\t * not available.\n\t */\n\tpublic host(): string {\n\t\treturn (this.headers.host as string) || \"unknown\";\n\t}\n\n\t/**\n\t * Returns the absolute request URL reconstructed from the current request.\n\t *\n\t * This helper rebuilds the URL from the current security state, host header,\n\t * and parsed pathname. It does not append the original query string.\n\t *\n\t * @returns {string} Absolute URL for the current request pathname.\n\t */\n\tpublic url(): string {\n\t\treturn `${this.isSecure() ? \"https\" : \"http\"}://${this.host()}${this.pathname}`;\n\t}\n\n\t/**\n\t * Parses and returns the request body.\n\t *\n\t * JSON and plain text bodies are supported automatically. Multipart requests\n\t * populate both `body()` and `files()` through a shared parsing pass. The\n\t * parsed value is cached after the first read so later consumers do not touch\n\t * the underlying stream again.\n\t *\n\t * Requests whose method is not one of `POST`, `PUT`, `PATCH`, or `DELETE`\n\t * resolve to an empty object without reading the stream.\n\t *\n\t * @returns {Promise<T>} Parsed request body, multipart field map, raw text, or\n\t * an empty object for methods that do not consume a body by default.\n\t * @throws {BadRequestError} Thrown when the declared or streamed body size\n\t * exceeds `maxBodySize`, or when JSON parsing fails.\n\t */\n\tpublic async body<T>(): Promise<T> {\n\t\tconst methodsWithBody = [\"POST\", \"PUT\", \"PATCH\", \"DELETE\"];\n\t\tif (!methodsWithBody.includes(this.method)) {\n\t\t\treturn {} as T;\n\t\t}\n\n\t\tif (this._bodyCache !== null) return this._bodyCache as T;\n\n\t\tconst contentType = (this.headers[\"content-type\"] || \"\") as string;\n\n\t\tif (contentType.includes(\"multipart/form-data\")) {\n\t\t\tawait this.parseMultipart();\n\t\t\treturn this._bodyCache as T;\n\t\t}\n\n\t\tconst contentLength = parseInt(\n\t\t\t(this.headers[\"content-length\"] as string) || \"0\",\n\t\t\t10,\n\t\t);\n\t\tconst maxBodySize = this.opts.maxBodySize || 1024 * 1024;\n\n\t\tif (contentLength > maxBodySize) {\n\t\t\tthrow new BadRequestError(\"Request body too large.\");\n\t\t}\n\n\t\tconst body = await new Promise<T>((resolve, reject) => {\n\t\t\tconst chunks: Buffer[] = [];\n\t\t\tlet currentSize = 0;\n\n\t\t\tthis.req.on(\"data\", (chunk: Buffer) => {\n\t\t\t\tcurrentSize += chunk.length;\n\t\t\t\tif (currentSize > maxBodySize) {\n\t\t\t\t\treject(new BadRequestError(\"Request body too large.\"));\n\t\t\t\t}\n\t\t\t\tchunks.push(chunk);\n\t\t\t});\n\n\t\t\tthis.req.on(\"end\", () => {\n\t\t\t\tif (chunks.length === 0) return resolve({} as T);\n\n\t\t\t\tconst rawBody = Buffer.concat(chunks).toString(\"utf-8\");\n\t\t\t\ttry {\n\t\t\t\t\tif (contentType.includes(\"application/json\")) {\n\t\t\t\t\t\tresolve(JSON.parse(rawBody) as T);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresolve(rawBody as unknown as T);\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\treject(new BadRequestError(\"Invalid request body format.\"));\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tthis.req.on(\"error\", (err) => reject(err));\n\t\t});\n\n\t\tthis._bodyCache = body;\n\t\tthis.storage.set(\"body\", body);\n\t\treturn body;\n\t}\n\n\t/**\n\t * Returns uploaded files for multipart/form-data requests.\n\t *\n\t * `files()` shares the same multipart parsing pass used by `body()`. The\n\t * first call buffers every uploaded file into memory and caches both the\n\t * parsed field object and file array for later access.\n\t *\n\t * @returns {Promise<UploadedFile[]>} Buffered multipart files, or an empty\n\t * array when the request is not multipart.\n\t */\n\tpublic async files(): Promise<UploadedFile[]> {\n\t\tconst contentType = (this.headers[\"content-type\"] || \"\") as string;\n\t\tif (!contentType.includes(\"multipart/form-data\")) return [];\n\n\t\tif (this._filesCache !== null) return this._filesCache;\n\n\t\tawait this.parseMultipart();\n\t\treturn this._filesCache || [];\n\t}\n\n\t/**\n\t * Overrides the cached body value for the current request context.\n\t *\n\t * This mutates only the wrapper cache and the internal storage map. It does\n\t * not modify the underlying Node.js request stream.\n\t *\n\t * @param {unknown} value - Replacement body value to expose through `body()`\n\t * and internal request storage.\n\t */\n\tpublic setBody(value: unknown): void {\n\t\tthis._bodyCache = value;\n\t\tthis.storage.set(\"body\", value);\n\t}\n\n\t/**\n\t * Returns all parsed cookies from the request.\n\t *\n\t * Cookies are parsed lazily on first access and cached for the remainder of\n\t * the request lifecycle.\n\t *\n\t * @returns {Cookies} Parsed cookie map for the current request.\n\t */\n\tpublic cookies(): Cookies {\n\t\tif (this._cookies === null) {\n\t\t\tconst cookieHeader = this.headers.cookie;\n\t\t\tthis._cookies = cookieHeader ? parseCookie(cookieHeader) : {};\n\t\t}\n\t\treturn this._cookies;\n\t}\n\n\t/**\n\t * Returns a single cookie value by name.\n\t *\n\t * @param {string} name - Cookie name to read from the parsed cookie map.\n\t * @returns {string | undefined} The cookie value when present.\n\t */\n\tpublic cookie(name: string): string | undefined {\n\t\treturn this.cookies()[name];\n\t}\n\n\t/**\n\t * Returns a value stored in the per-request internal storage map.\n\t *\n\t * This storage is local to the current request wrapper and can be used by\n\t * middleware and handlers to exchange derived values without mutating the\n\t * typed request surface.\n\t *\n\t * @param {string} key - Storage key associated with the requested value.\n\t * @returns {T | undefined} Stored value for the key, if one exists.\n\t */\n\tpublic get<T>(key: string): T | undefined {\n\t\treturn this.storage.get(key) as T | undefined;\n\t}\n\n\t/**\n\t * Stores a value in the per-request internal storage map.\n\t *\n\t * @param {string} key - Storage key to create or overwrite.\n\t * @param {unknown} value - Arbitrary value to retain for the lifetime of the\n\t * current request wrapper.\n\t */\n\tpublic set(key: string, value: unknown): void {\n\t\tthis.storage.set(key, value);\n\t}\n\n\t/**\n\t * Parses a multipart/form-data request into cached fields and file buffers.\n\t *\n\t * The request stream is piped into Busboy exactly once. Field values are\n\t * collected into a plain object, file contents are buffered fully in memory,\n\t * and both results are stored in the request cache and internal storage map.\n\t *\n\t * @returns {Promise<void>} Resolves after Busboy finishes consuming the\n\t * multipart stream and caches the parsed payload.\n\t */\n\tprivate async parseMultipart(): Promise<void> {\n\t\tif (this._bodyCache !== null && this._filesCache !== null) return;\n\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst bb = busboy({ headers: this.headers });\n\t\t\tconst fields: Record<string, any> = {};\n\t\t\tconst files: UploadedFile[] = [];\n\n\t\t\tbb.on(\"file\", (name, file, info) => {\n\t\t\t\tconst chunks: Buffer[] = [];\n\t\t\t\tfile.on(\"data\", (data) => chunks.push(data));\n\t\t\t\tfile.on(\"end\", () => {\n\t\t\t\t\tfiles.push({\n\t\t\t\t\t\tfieldname: name,\n\t\t\t\t\t\tbuffer: Buffer.concat(chunks),\n\t\t\t\t\t\t...info,\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t});\n\n\t\t\tbb.on(\"field\", (name, value) => {\n\t\t\t\tfields[name] = value;\n\t\t\t});\n\n\t\t\tbb.on(\"finish\", () => {\n\t\t\t\tthis._bodyCache = fields;\n\t\t\t\tthis._filesCache = files;\n\t\t\t\tthis.storage.set(\"body\", fields);\n\t\t\t\tthis.storage.set(\"files\", files);\n\t\t\t\tresolve();\n\t\t\t});\n\n\t\t\tbb.on(\"error\", reject);\n\t\t\tthis.req.pipe(bb);\n\t\t});\n\t}\n}\n\n/**\n * Converts URL search parameters into the mutable query object exposed by the\n * request wrapper.\n *\n * When the same key appears multiple times, the last encountered value wins.\n *\n * @param {URLSearchParams} searchParams - Parsed search parameters from the\n * request URL.\n * @returns {Query} Plain object representation of the query string.\n */\nfunction parseQueryToObject(searchParams: URLSearchParams): Query {\n\tconst query: Query = {};\n\tfor (const [key, value] of searchParams.entries()) {\n\t\tquery[key] = value;\n\t}\n\treturn query;\n}\n","import { access, constants } from \"node:fs/promises\";\nimport { pathToFileURL } from \"node:url\";\nimport { isAsyncFunction } from \"node:util/types\";\nimport { LithiaError } from \"../errors/base\";\nimport {\n\tNoAsyncDefaultExportError,\n\tNoDefaultExportError,\n} from \"../errors/internal/index\";\n\n/**\n * Runtime contract for modules loaded by Lithia discovery/runtime helpers.\n *\n * Lithia expects a default async function export and permits additional named\n * exports for metadata such as middleware or route information.\n */\nexport type LithiaModule = {\n\tdefault: (...args: any[]) => Promise<any>;\n\t[key: string]: unknown;\n};\n\n/**\n * Loads a compiled module and validates that it exposes an async default\n * export.\n *\n * The helper checks filesystem accessibility first, imports the compiled module\n * through a file URL, and then enforces Lithia's runtime contract that the\n * default export must exist and must be an async function.\n *\n * @param {string} filePath - Absolute path to the compiled module file.\n * @returns {Promise<T>} Imported module after runtime contract validation.\n * @throws {LithiaError} Thrown when the file does not exist, cannot be\n * imported, or violates Lithia's default-export expectations.\n */\nexport async function loadModule<T extends LithiaModule>(\n\tfilePath: string,\n): Promise<T> {\n\tconst exists = await access(filePath, constants.F_OK)\n\t\t.then(() => true)\n\t\t.catch(() => false);\n\n\tif (!exists) {\n\t\tthrow new LithiaError(\n\t\t\t`The module at '${filePath}' could not be found or is not accessible.`,\n\t\t);\n\t}\n\n\tlet mod: T;\n\ttry {\n\t\tmod = await import(pathToFileURL(filePath).href);\n\t} catch (err: any) {\n\t\tthrow new LithiaError(\n\t\t\t`Failed to import module at '${filePath}': ${err.message}`,\n\t\t);\n\t}\n\n\tif (!mod || !mod.default) {\n\t\tthrow new NoDefaultExportError(filePath);\n\t}\n\n\tconst isFunction = typeof mod.default === \"function\";\n\tconst isAsync = isAsyncFunction(mod.default);\n\n\tif (!isFunction || !isAsync) {\n\t\tthrow new NoAsyncDefaultExportError(filePath);\n\t}\n\n\treturn mod;\n}\n","/**\n * Single middleware-style step executed by the shared pipeline runner.\n *\n * Each step receives a continuation that advances to the next step or final\n * handler.\n */\nexport type PipelineStep = (next: () => Promise<void>) => Promise<void> | void;\n\n/**\n * Executes an ordered middleware pipeline followed by a final handler.\n *\n * The runner prevents backward re-entry by ignoring calls that try to dispatch\n * an already executed index. Each step must call its provided continuation if\n * it wants the pipeline to proceed.\n *\n * @param {PipelineStep[]} steps - Ordered pipeline steps to execute.\n * @param {() => Promise<void>} handler - Final handler executed after the last\n * step calls its continuation.\n * @returns {Promise<void>} Resolves after the pipeline reaches its terminal\n * step.\n */\nexport async function executePipeline(\n\tsteps: PipelineStep[],\n\thandler: () => Promise<void>,\n): Promise<void> {\n\tlet index = -1;\n\n\tconst dispatch = async (stepIndex: number): Promise<void> => {\n\t\tif (stepIndex <= index) return;\n\t\tindex = stepIndex;\n\n\t\tif (stepIndex === steps.length) {\n\t\t\treturn handler();\n\t\t}\n\n\t\tconst step = steps[stepIndex];\n\t\tif (step) {\n\t\t\tawait step(() => dispatch(stepIndex + 1));\n\t\t}\n\t};\n\n\tawait dispatch(0);\n}\n","import type { LithiaOptions } from \"../../config\";\nimport type { LithiaRequest } from \"./request\";\nimport type { LithiaResponse } from \"./response\";\n\n/**\n * Applies the configured CORS policy to the current HTTP request.\n *\n * The policy is request-driven: it only runs when CORS origins are configured\n * and the incoming request includes an `Origin` header. For allowed origins, it\n * writes the relevant CORS response headers and, for preflight `OPTIONS`\n * requests, terminates the response with `204 No Content`.\n *\n * When the request does not match an allowed origin or does not require CORS\n * handling, the function leaves the response untouched and returns `false`.\n *\n * Related docs:\n * - https://lithiajs.org/docs/latest/routes\n * - https://lithiajs.org/docs/latest/project-structure\n *\n * @param {LithiaOptions} config - Fully resolved runtime configuration that\n * provides the HTTP CORS policy.\n * @param {LithiaRequest} req - Current request wrapper used to inspect origin\n * and method information.\n * @param {LithiaResponse} res - Current response wrapper mutated with CORS\n * headers and, for preflight requests, the terminal `204` response.\n * @returns {boolean} `true` when the function fully handled a preflight request\n * and ended the response, or `false` when normal route processing should\n * continue.\n */\nexport function applyCorsPolicy(\n\tconfig: LithiaOptions,\n\treq: LithiaRequest,\n\tres: LithiaResponse,\n): boolean {\n\tconst { cors } = config.http;\n\tif (!cors?.origin?.length) return false;\n\n\tconst requestOrigin = req.headers.origin as string | undefined;\n\tif (!requestOrigin) return false;\n\n\tconst isOriginAllowed =\n\t\tcors.origin.includes(\"*\") ||\n\t\tcors.origin.some((allowed) => allowed === requestOrigin);\n\n\tif (!isOriginAllowed) return false;\n\n\tconst allowedOrigin = cors.origin.includes(\"*\")\n\t\t? cors.credentials\n\t\t\t? requestOrigin\n\t\t\t: \"*\"\n\t\t: requestOrigin;\n\n\tres.setHeader(\"Access-Control-Allow-Origin\", allowedOrigin);\n\tres.setHeader(\"Vary\", \"Origin\");\n\n\tif (cors.credentials) {\n\t\tres.setHeader(\"Access-Control-Allow-Credentials\", \"true\");\n\t}\n\n\tif (cors.exposedHeaders?.length) {\n\t\tres.setHeader(\n\t\t\t\"Access-Control-Expose-Headers\",\n\t\t\tcors.exposedHeaders.join(\", \"),\n\t\t);\n\t}\n\n\tif (req.method !== \"OPTIONS\") return false;\n\n\tif (cors.methods?.length) {\n\t\tres.setHeader(\"Access-Control-Allow-Methods\", cors.methods.join(\", \"));\n\t}\n\tif (cors.allowedHeaders?.length) {\n\t\tres.setHeader(\n\t\t\t\"Access-Control-Allow-Headers\",\n\t\t\tcors.allowedHeaders.join(\", \"),\n\t\t);\n\t}\n\tif (cors.maxAge != null) {\n\t\tres.setHeader(\"Access-Control-Max-Age\", String(cors.maxAge));\n\t}\n\n\tres.status(204).end();\n\treturn true;\n}\n","import { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { LithiaOptions } from \"../../config\";\nimport type { LithiaRequest } from \"./request\";\nimport type { LithiaResponse } from \"./response\";\n\nconst DOCS_FILE = path.join(\"_lithia\", \"scalar.html\");\nconst SPEC_FILE = path.join(\"_lithia\", \"openapi.json\");\n\n/**\n * Serves generated OpenAPI artifacts through the configured public docs routes.\n *\n * When OpenAPI support is enabled, this helper intercepts `GET` and `HEAD`\n * requests for the configured Scalar UI path and OpenAPI spec path, reads the\n * generated artifact from the current build output, and writes the appropriate\n * content type to the response.\n *\n * A missing artifact is treated as \"not handled\" so the caller can continue\n * through the normal HTTP pipeline instead of failing the request here.\n *\n * Related docs:\n * - https://lithiajs.org/docs/latest/openapi\n * - https://lithiajs.org/docs/latest/routes\n *\n * @param {LithiaOptions} config - Fully resolved runtime configuration that\n * provides the output directory and OpenAPI route settings.\n * @param {LithiaRequest} req - Current HTTP request wrapper used to resolve the\n * request pathname and method.\n * @param {LithiaResponse} res - Current HTTP response wrapper used to send the\n * docs HTML or generated spec.\n * @returns {Promise<boolean>} `true` when the request matched a configured\n * OpenAPI asset route and a response was written, or `false` when the request\n * should continue through normal route/static handling.\n */\nexport async function serveOpenAPIAsset(\n\tconfig: LithiaOptions,\n\treq: LithiaRequest,\n\tres: LithiaResponse,\n): Promise<boolean> {\n\tif (!config.openapi?.enabled) return false;\n\tif (req.method !== \"GET\" && req.method !== \"HEAD\") return false;\n\n\tconst docsPath = normalizeOpenAPIPath(config.openapi.docsPath || \"/docs\");\n\tconst specPath = normalizeOpenAPIPath(\n\t\tconfig.openapi.specPath || \"/openapi.json\",\n\t);\n\tconst pathname = normalizeOpenAPIPath(req.pathname);\n\n\tif (pathname === docsPath) {\n\t\tconst html = await readOpenAPIArtifact(config.outDir, DOCS_FILE);\n\t\tif (!html) return false;\n\t\tres.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n\t\tres.send(req.method === \"HEAD\" ? undefined : html);\n\t\treturn true;\n\t}\n\n\tif (pathname === specPath) {\n\t\tconst spec = await readOpenAPIArtifact(config.outDir, SPEC_FILE);\n\t\tif (!spec) return false;\n\t\tres.setHeader(\"Content-Type\", \"application/json; charset=utf-8\");\n\t\tres.send(req.method === \"HEAD\" ? undefined : spec);\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\n/**\n * Normalizes a public OpenAPI route path for stable route comparison.\n *\n * The helper guarantees a leading slash and removes a trailing slash from\n * non-root paths so configured docs/spec paths and request pathnames can be\n * compared without ambiguity.\n *\n * @param {string} input - Configured or incoming pathname to normalize.\n * @returns {string} Normalized absolute pathname.\n */\nexport function normalizeOpenAPIPath(input: string): string {\n\tif (!input) return \"/\";\n\n\tconst normalized = input.startsWith(\"/\") ? input : `/${input}`;\n\tif (normalized.length > 1 && normalized.endsWith(\"/\")) {\n\t\treturn normalized.slice(0, -1);\n\t}\n\n\treturn normalized;\n}\n\n/**\n * Reads a generated OpenAPI artifact from the current build output directory.\n *\n * Artifacts are resolved relative to `process.cwd()` and the configured\n * runtime `outDir`. Read failures are collapsed into `null` so callers can\n * treat missing OpenAPI output as an unhandled request.\n *\n * @param {string} outDir - Build output directory that contains generated\n * Lithia artifacts.\n * @param {string} relativePath - Artifact path relative to the output\n * directory.\n * @returns {Promise<string | null>} UTF-8 file contents, or `null` when the\n * artifact cannot be read.\n */\nasync function readOpenAPIArtifact(\n\toutDir: string,\n\trelativePath: string,\n): Promise<string | null> {\n\ttry {\n\t\treturn await readFile(\n\t\t\tpath.join(process.cwd(), outDir, relativePath),\n\t\t\t\"utf-8\",\n\t\t);\n\t} catch {\n\t\treturn null;\n\t}\n}\n","import { createHash } from \"node:crypto\";\n\n/**\n * Produces a short non-deterministic digest for error reporting.\n *\n * The digest is derived from the error stack or message plus time- and\n * randomness-based entropy, so repeated failures do not generate a stable\n * identifier across executions.\n *\n * @param {unknown} err - Original error or thrown value.\n * @returns {string} Short hexadecimal digest suitable for logs and client error\n * payloads.\n */\nexport function produceDigest(err: unknown): string {\n\tconst errString =\n\t\terr instanceof Error ? err.stack || err.message : String(err);\n\n\tconst hash = createHash(\"sha256\")\n\t\t.update(`${errString}${Date.now()}${Math.random()}`)\n\t\t.digest(\"hex\");\n\n\treturn hash.slice(0, 12);\n}\n","import { logger, red } from \"@lithia-js/utils\";\nimport { InternalServerError } from \"../../errors/app/index\";\nimport { LithiaClientError } from \"../../errors/base\";\nimport { produceDigest } from \"../../shared/digest\";\nimport type { Environment } from \"../../types\";\nimport type { LithiaRequest } from \"./request\";\nimport type { LithiaResponse } from \"./response\";\n\n/**\n * Converts an uncaught HTTP request error into a structured JSON response.\n *\n * Client-facing framework errors preserve their declared status code and\n * message. Unknown errors are wrapped as internal server errors, and production\n * mode hides 5xx messages behind a generic `\"Internal Server Error\"` payload.\n *\n * The handler is a no-op when the response has already been finalized.\n *\n * Related docs:\n * - https://lithiajs.org/docs/latest/routes\n *\n * @param {Environment} environment - Current runtime environment used to decide\n * whether internal error messages should be exposed.\n * @param {LithiaRequest} req - Current request wrapper used to include request\n * metadata in the error payload.\n * @param {LithiaResponse} res - Current response wrapper used to send the error\n * response.\n * @param {any} err - Original thrown value captured from the request pipeline.\n */\nexport function handleRequestError(\n\tenvironment: Environment,\n\treq: LithiaRequest,\n\tres: LithiaResponse,\n\terr: any,\n): void {\n\tif (res._ended) return;\n\n\tconst error =\n\t\terr instanceof LithiaClientError ? err : new InternalServerError(err);\n\tconst isProd = environment === \"production\";\n\tconst statusCode = error.statusCode || 500;\n\tconst digest = produceDigest(err);\n\tconst message =\n\t\tisProd && statusCode >= 500 ? \"Internal Server Error\" : error.message;\n\n\tres.status(statusCode).json({\n\t\terror: {\n\t\t\tstatusCode,\n\t\t\tmessage,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tdigest,\n\t\t\tpath: req.pathname,\n\t\t\tmethod: req.method,\n\t\t\tdetails: error.details,\n\t\t},\n\t});\n\n\tif (statusCode >= 500) {\n\t\tlogger.error(`Digest: ${red(digest)}`);\n\t\tlogger.info(`Path: ${req.method} ${req.pathname}`);\n\t\tlogger.info(err.stack || err);\n\t}\n}\n","import { routeContextStore } from \"../../context/request-context\";\nimport type { Route } from \"../../discovery/routes\";\nimport type { LithiaRequest, Params } from \"./request\";\n\n/**\n * Matches incoming HTTP requests against discovered route manifests.\n *\n * The matcher reuses compiled regular expressions, selects the first route\n * whose HTTP method and path regex match the request, and populates request\n * params plus route context for dynamic matches.\n *\n * Related docs:\n * - https://lithiajs.org/docs/latest/routes\n * - https://lithiajs.org/docs/latest/project-structure\n */\nexport class RouteMatcher {\n\tprivate readonly regexCache = new Map<string, RegExp>();\n\n\t/**\n\t * Finds the first discovered route that matches the current request.\n\t *\n\t * Method-specific routes only match the corresponding request method, while\n\t * method-agnostic routes can match any method. Path matching is delegated to\n\t * the route manifest regex generated during discovery.\n\t *\n\t * @param {LithiaRequest} req - Current request wrapper.\n\t * @param {Route[]} routes - Discovered route manifests to scan in order.\n\t * @returns {Route | undefined} The first matching route manifest, if one\n\t * exists.\n\t */\n\tpublic findRoute(req: LithiaRequest, routes: Route[]): Route | undefined {\n\t\tconst method = req.method.toLowerCase();\n\n\t\treturn routes.find((route) => {\n\t\t\tconst methodMatches =\n\t\t\t\t!route.method || route.method.toLowerCase() === method;\n\t\t\tif (!methodMatches) return false;\n\n\t\t\tconst regex = this.getOrCreateRegex(route.regex);\n\t\t\treturn regex.test(req.pathname);\n\t\t});\n\t}\n\n\t/**\n\t * Synchronizes route-specific context after a route match is selected.\n\t *\n\t * When a request context store is active, the matched route manifest is\n\t * attached to it. Dynamic routes also populate `req.params` by extracting\n\t * capture groups from the request pathname.\n\t *\n\t * @param {Route} route - Matched route manifest.\n\t * @param {LithiaRequest} req - Current request wrapper whose params may be\n\t * updated.\n\t */\n\tpublic setupContext(route: Route, req: LithiaRequest): void {\n\t\tconst store = routeContextStore.getStore();\n\t\tif (store) {\n\t\t\tstore.route = route;\n\t\t}\n\n\t\tif (route.dynamic) {\n\t\t\treq.params = this.extractParams(req.pathname, route);\n\t\t}\n\t}\n\n\t/**\n\t * Extracts decoded dynamic params from a matched pathname.\n\t *\n\t * Param names are derived from `route.path` segments such as `:id`, while\n\t * values are read from the corresponding regex capture groups in the actual\n\t * request pathname.\n\t *\n\t * @param {string} pathname - Incoming request pathname.\n\t * @param {Route} route - Matched route manifest that supplies the paramized\n\t * path and regex pattern.\n\t * @returns {Params} Decoded param object for the current request.\n\t */\n\tprivate extractParams(pathname: string, route: Route): Params {\n\t\tconst regex = this.getOrCreateRegex(route.regex);\n\t\tconst match = pathname.match(regex);\n\n\t\tif (!match) return {};\n\n\t\tconst paramNames = (route.path.match(/:([^/]+)/g) || []).map((segment) =>\n\t\t\tsegment.slice(1),\n\t\t);\n\n\t\treturn paramNames.reduce((params, name, index) => {\n\t\t\tconst value = match[index + 1];\n\t\t\tparams[name] = value ? decodeURIComponent(value) : value;\n\t\t\treturn params;\n\t\t}, {} as Params);\n\t}\n\n\t/**\n\t * Returns a cached regular expression for a route manifest pattern.\n\t *\n\t * @param {string} pattern - Serialized regex pattern generated during route\n\t * discovery.\n\t * @returns {RegExp} Cached or newly compiled regular expression.\n\t */\n\tprivate getOrCreateRegex(pattern: string): RegExp {\n\t\tlet regex = this.regexCache.get(pattern);\n\t\tif (!regex) {\n\t\t\tregex = new RegExp(pattern);\n\t\t\tthis.regexCache.set(pattern, regex);\n\t\t}\n\t\treturn regex;\n\t}\n}\n","import { stat } from \"node:fs/promises\";\nimport { extname, join, normalize } from \"node:path\";\nimport type { LithiaOptions } from \"../../config\";\nimport type { LithiaRequest } from \"./request\";\nimport type { LithiaResponse } from \"./response\";\n\n/**\n * Serves configured static files before the dynamic route pipeline runs.\n *\n * The helper only handles `GET` and `HEAD` requests, optionally strips a static\n * URL prefix, normalizes the remaining path to reduce directory traversal risk,\n * and serves the file only when it exists and a MIME type mapping is available\n * for its extension.\n *\n * Any miss, unsupported extension, or filesystem failure is treated as\n * \"not handled\" so the caller can continue through the rest of the HTTP\n * pipeline.\n *\n * Related docs:\n * - https://lithiajs.org/docs/latest/routes\n * - https://lithiajs.org/docs/latest/project-structure\n *\n * @param {LithiaOptions} config - Fully resolved runtime configuration that\n * provides static asset and MIME-type settings.\n * @param {LithiaRequest} req - Current request wrapper used to inspect method\n * and pathname.\n * @param {LithiaResponse} res - Current response wrapper used to send the file.\n * @returns {Promise<boolean>} `true` when a static asset response was written,\n * or `false` when request processing should continue.\n */\nexport async function serveStaticAsset(\n\tconfig: LithiaOptions,\n\treq: LithiaRequest,\n\tres: LithiaResponse,\n): Promise<boolean> {\n\tconst { static: staticConfig, http } = config;\n\n\tif (!staticConfig?.root || (req.method !== \"GET\" && req.method !== \"HEAD\")) {\n\t\treturn false;\n\t}\n\n\tlet relativePath = req.pathname;\n\tif (staticConfig.prefix) {\n\t\tif (!relativePath.startsWith(staticConfig.prefix)) return false;\n\t\trelativePath = relativePath.slice(staticConfig.prefix.length);\n\t}\n\n\tconst safePath = normalize(relativePath).replace(/^(\\.\\.(\\/|\\\\|$))+/, \"\");\n\tconst fullPath = join(staticConfig.root, safePath);\n\n\ttry {\n\t\tconst stats = await stat(fullPath);\n\t\tif (!stats.isFile()) return false;\n\n\t\tconst ext = extname(fullPath).toLowerCase();\n\t\tconst mime = http.mimeTypes?.[ext];\n\t\tif (!mime) return false;\n\n\t\tres.setHeader(\"Content-Type\", mime);\n\t\tres.send(fullPath);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n","import { green, logger, red, yellow } from \"@lithia-js/utils\";\nimport { RouteNotFoundError } from \"../../errors/app/index\";\nimport type { LithiaApp } from \"../../runtime/app/app-runtime\";\nimport { loadModule } from \"../../shared/module-loader\";\nimport { executePipeline } from \"../../shared/pipeline\";\nimport { applyCorsPolicy } from \"./cors-policy\";\nimport { serveOpenAPIAsset } from \"./openapi-assets\";\nimport type { LithiaRequest } from \"./request\";\nimport { handleRequestError } from \"./request-error-handler\";\nimport type { LithiaResponse } from \"./response\";\nimport { RouteMatcher } from \"./route-matcher\";\nimport type { RouteMetadata } from \"./route-metadata\";\nimport { serveStaticAsset } from \"./static-assets\";\n\n/**\n * Continuation used by route middleware to hand control to the next step in\n * the pipeline.\n *\n * Calling `next()` transfers control to the next middleware or, once the stack\n * is exhausted, to the route handler itself.\n */\nexport type NextRoute = () => Promise<void> | void;\n\n/**\n * Middleware executed before a route handler.\n *\n * Route middleware can inspect or mutate the request/response and may stop the\n * pipeline by not calling `next()`.\n *\n * @param {LithiaRequest} req - Current request wrapper shared across the route\n * pipeline.\n * @param {LithiaResponse} res - Current response wrapper shared across the\n * route pipeline.\n * @param {NextRoute} next - Continuation that advances execution to the next\n * middleware or the final route handler.\n * @returns {Promise<void>} Resolves after the middleware finishes its work.\n */\nexport type RouteMiddleware = (\n\treq: LithiaRequest,\n\tres: LithiaResponse,\n\tnext: NextRoute,\n) => Promise<void>;\n\n/**\n * Error middleware shape reserved for route-level error handling.\n *\n * This type documents the intended contract for route-scoped error middleware,\n * although this file currently executes request errors through\n * `handleRequestError()` instead of a route-local error middleware chain.\n *\n * @param {Error} err - Error being handled for the current request.\n * @param {LithiaRequest} req - Current request wrapper.\n * @param {LithiaResponse} res - Current response wrapper.\n * @param {NextRoute} next - Continuation that would advance the error-handling\n * chain.\n * @returns {Promise<void>} Resolves after error handling completes.\n */\nexport type RouteErrorMiddleware = (\n\terr: Error,\n\treq: LithiaRequest,\n\tres: LithiaResponse,\n\tnext: NextRoute,\n) => Promise<void>;\n\n/**\n * Route module default export signature.\n *\n * Route handlers are the terminal HTTP boundary for a matched route module and\n * receive the current request and response wrappers.\n *\n * @param {LithiaRequest} req - Current request wrapper.\n * @param {LithiaResponse} res - Current response wrapper.\n * @returns {Promise<void>} Resolves after the handler finishes shaping the HTTP\n * response.\n */\nexport type RouteHandler = (\n\treq: LithiaRequest,\n\tres: LithiaResponse,\n) => Promise<void>;\n\n/**\n * Full module contract for a file-based route.\n *\n * A discovered route module must provide a default handler and may optionally\n * contribute route-scoped middleware and explicit route metadata.\n */\nexport type RouteModule = {\n\tdefault: RouteHandler;\n\tmiddlewares?: RouteMiddleware[];\n\tmetadata?: RouteMetadata;\n};\n\n/**\n * Executes the HTTP request pipeline for a Lithia application.\n *\n * The processor applies framework-managed concerns in a fixed order:\n * initial headers, CORS handling, OpenAPI assets, static assets, route\n * matching, route-context setup, middleware execution, and finally the matched\n * route handler. Any uncaught error is delegated to `handleRequestError()`, and\n * request logging runs in a `finally` block so it always records the terminal\n * status.\n *\n * Related docs:\n * - https://lithiajs.org/docs/latest/routes\n * - https://lithiajs.org/docs/latest/project-structure\n */\nexport class LithiaRequestProcessor {\n\tprivate readonly matcher = new RouteMatcher();\n\n\t/**\n\t * Creates an HTTP request processor bound to a running Lithia app instance.\n\t *\n\t * @param {LithiaApp} app - Runtime app state that provides config, manifests,\n\t * middleware registries, and environment information for request execution.\n\t */\n\tconstructor(private readonly app: LithiaApp) {}\n\n\t/**\n\t * Processes a single HTTP request through the Lithia route pipeline.\n\t *\n\t * The method may terminate early when CORS preflight handling, OpenAPI asset\n\t * serving, or static asset serving fully handles the request. Otherwise it\n\t * resolves the matching route, prepares request params through the route\n\t * matcher, loads the route module, executes global and route-local middleware,\n\t * and then runs the route handler.\n\t *\n\t * If the handler and middleware chain complete without ending the response,\n\t * the processor closes the response automatically with `res.end()`.\n\t *\n\t * @param {LithiaRequest} req - Current request wrapper.\n\t * @param {LithiaResponse} res - Current response wrapper.\n\t * @returns {Promise<void>} Resolves after the request reaches a terminal\n\t * response or the error handler completes.\n\t */\n\tpublic async process(req: LithiaRequest, res: LithiaResponse): Promise<void> {\n\t\tconst startTime = performance.now();\n\n\t\ttry {\n\t\t\tthis.setInitialHeaders(res);\n\n\t\t\tif (applyCorsPolicy(this.app.config, req, res)) return;\n\t\t\tif (await serveOpenAPIAsset(this.app.config, req, res)) return;\n\t\t\tif (await serveStaticAsset(this.app.config, req, res)) return;\n\n\t\t\tconst route = this.matcher.findRoute(req, this.app.routes);\n\t\t\tif (!route) {\n\t\t\t\tthrow new RouteNotFoundError(\n\t\t\t\t\t`The requested resource '${req.pathname}' does not exist on this server.`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tthis.matcher.setupContext(route, req);\n\n\t\t\tconst mod = await loadModule<RouteModule>(route.filePath);\n\t\t\tconst pipeline = [\n\t\t\t\t...this.app.globalRouteMiddlewares,\n\t\t\t\t...(mod.middlewares || []),\n\t\t\t];\n\n\t\t\tawait this.runRoutePipeline(pipeline, req, res, async () => {\n\t\t\t\tawait mod.default(req, res);\n\t\t\t});\n\n\t\t\tif (!res._ended) res.end();\n\t\t} catch (error) {\n\t\t\thandleRequestError(this.app.environment, req, res, error);\n\t\t} finally {\n\t\t\tthis.logRequest(req, res, performance.now() - startTime);\n\t\t}\n\t}\n\n\t/**\n\t * Executes the composed route middleware chain and then the final handler.\n\t *\n\t * Middleware functions are adapted to the generic shared pipeline runner,\n\t * which guarantees in-order execution as long as each middleware calls its\n\t * `next()` continuation.\n\t *\n\t * @param {RouteMiddleware[]} middlewares - Global and route-scoped middleware\n\t * stack to execute before the handler.\n\t * @param {LithiaRequest} req - Current request wrapper shared across the\n\t * entire pipeline.\n\t * @param {LithiaResponse} res - Current response wrapper shared across the\n\t * entire pipeline.\n\t * @param {RouteHandler} handler - Final route handler invoked after all\n\t * middleware completes.\n\t * @returns {Promise<void>} Resolves after the middleware chain and handler\n\t * finish.\n\t */\n\tprivate async runRoutePipeline(\n\t\tmiddlewares: RouteMiddleware[],\n\t\treq: LithiaRequest,\n\t\tres: LithiaResponse,\n\t\thandler: RouteHandler,\n\t): Promise<void> {\n\t\tawait executePipeline(\n\t\t\tmiddlewares.map(\n\t\t\t\t(middleware) => (next) => middleware(req, res, () => next()),\n\t\t\t),\n\t\t\t() => handler(req, res),\n\t\t);\n\t}\n\n\t/**\n\t * Applies framework-default headers before any route logic runs.\n\t *\n\t * @param {LithiaResponse} res - Response wrapper mutated with initial\n\t * framework headers.\n\t */\n\tprivate setInitialHeaders(res: LithiaResponse): void {\n\t\tres.setHeader(\"X-Powered-By\", \"Lithia\");\n\t}\n\n\t/**\n\t * Logs the completed HTTP request when request logging is enabled.\n\t *\n\t * The status code is color-coded according to its category and the log is\n\t * emitted only after the request has reached a terminal state.\n\t *\n\t * @param {LithiaRequest} req - Request wrapper used for method and pathname\n\t * fields.\n\t * @param {LithiaResponse} res - Response wrapper used for the final status\n\t * code.\n\t * @param {number} elapsed - Total request processing time in milliseconds.\n\t */\n\tprivate logRequest(\n\t\treq: LithiaRequest,\n\t\tres: LithiaResponse,\n\t\telapsed: number,\n\t): void {\n\t\tif (!this.app.config.logging.requests) return;\n\n\t\tconst status = res.statusCode;\n\t\tconst colorFunc = status >= 500 ? red : status >= 400 ? yellow : green;\n\n\t\tlogger.info(\n\t\t\t`${req.method} ${req.pathname} ${colorFunc(status.toString())} - ${elapsed.toFixed(2)}ms`,\n\t\t);\n\t}\n}\n","import { createReadStream, statSync } from \"node:fs\";\nimport type { OutgoingHttpHeaders, ServerResponse } from \"node:http\";\nimport { join } from \"node:path\";\nimport { logger } from \"@lithia-js/utils\";\nimport { serialize as serializeCookie } from \"cookie\";\n\n/**\n * Cookie attributes accepted by `LithiaResponse.cookie()`.\n *\n * These options are forwarded to the cookie serializer when pending cookies\n * are flushed into the `Set-Cookie` header.\n */\nexport interface CookieOptions {\n\tdomain?: string;\n\texpires?: Date;\n\thttpOnly?: boolean;\n\tmaxAge?: number;\n\tpath?: string;\n\tsameSite?: boolean | \"lax\" | \"strict\" | \"none\";\n\tsecure?: boolean;\n}\n\n/**\n * Cookie entry queued until the response writes headers.\n */\ninterface PendingCookie {\n\tname: string;\n\tvalue: string;\n\toptions?: CookieOptions;\n}\n\n/**\n * Lithia wrapper around Node's `ServerResponse`.\n *\n * Provides helpers for status management, JSON/text responses, redirects,\n * cookies, and file responses.\n *\n * The wrapper keeps response mutations centralized until one of the terminal\n * methods sends or streams the response. After that point, further mutations\n * are rejected to preserve a single-write HTTP lifecycle.\n *\n * Related docs:\n * - https://lithiajs.org/docs/latest/routes\n * - https://lithiajs.org/docs/latest/project-structure\n */\nexport class LithiaResponse {\n\tpublic _ended = false;\n\n\tprivate _cookies: PendingCookie[] = [];\n\tpublic on: (event: string, listener: (chunk: unknown) => void) => void;\n\n\t/**\n\t * Creates a response wrapper for the current HTTP transaction.\n\t *\n\t * The wrapper binds a pass-through `on()` helper to the underlying Node.js\n\t * response object so route-adjacent code can subscribe to response events\n\t * without holding the raw `ServerResponse`.\n\t *\n\t * @param {ServerResponse} res - Raw Node.js response object associated with\n\t * the current request.\n\t */\n\tconstructor(private readonly res: ServerResponse) {\n\t\tthis.on = this.res.on.bind(this.res);\n\t}\n\n\t/**\n\t * Returns the current HTTP status code.\n\t *\n\t * @returns {number} Status code currently assigned to the underlying\n\t * response.\n\t */\n\tpublic get statusCode(): number {\n\t\treturn this.res.statusCode;\n\t}\n\n\t/**\n\t * Sets the HTTP status code for the response.\n\t *\n\t * This mutates the underlying response only while it is still active.\n\t *\n\t * @param {number} status - HTTP status code to assign before the response is\n\t * sent.\n\t * @returns {this} The current response wrapper for fluent chaining.\n\t * @throws {Error} Thrown when the response has already ended or when the\n\t * supplied status code falls outside the valid HTTP range.\n\t */\n\tpublic status(status: number): this {\n\t\tthis.ensureActive();\n\t\tif (status < 100 || status > 599) {\n\t\t\tthrow new Error(`Invalid HTTP status code: ${status}`);\n\t\t}\n\t\tthis.res.statusCode = status;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Returns the currently assigned response headers.\n\t *\n\t * @returns {Readonly<OutgoingHttpHeaders>} Snapshot of the headers currently\n\t * stored on the underlying response.\n\t */\n\tpublic headers(): Readonly<OutgoingHttpHeaders> {\n\t\treturn this.res.getHeaders();\n\t}\n\n\t/**\n\t * Sets multiple response headers at once.\n\t *\n\t * @param {OutgoingHttpHeaders} headers - Header entries to assign to the\n\t * response before it is sent.\n\t * @returns {this} The current response wrapper for fluent chaining.\n\t * @throws {Error} Thrown when the response has already ended.\n\t */\n\tpublic setHeaders(headers: OutgoingHttpHeaders): this {\n\t\tthis.ensureActive();\n\t\tObject.entries(headers).forEach(([key, value]) => {\n\t\t\tthis.res.setHeader(key, value as any);\n\t\t});\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets a single response header.\n\t *\n\t * @param {string} name - Header name to create or overwrite.\n\t * @param {string | number | string[]} value - Header value written to the\n\t * underlying response.\n\t * @returns {this} The current response wrapper for fluent chaining.\n\t * @throws {Error} Thrown when the response has already ended.\n\t */\n\tpublic setHeader(name: string, value: string | number | string[]): this {\n\t\tthis.ensureActive();\n\t\tthis.res.setHeader(name, value as any);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Removes a response header.\n\t *\n\t * @param {string} name - Header name to remove.\n\t * @returns {this} The current response wrapper for fluent chaining.\n\t * @throws {Error} Thrown when the response has already ended.\n\t */\n\tpublic removeHeader(name: string): this {\n\t\tthis.ensureActive();\n\t\tthis.res.removeHeader(name);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Queues a cookie to be written when the response is sent.\n\t *\n\t * Cookies are accumulated in memory and serialized only when a terminal\n\t * response method flushes headers.\n\t *\n\t * @param {string} name - Cookie name.\n\t * @param {string} value - Cookie value.\n\t * @param {CookieOptions} [options={}] - Cookie serialization options.\n\t * @returns {this} The current response wrapper for fluent chaining.\n\t * @throws {Error} Thrown when the response has already ended.\n\t */\n\tpublic cookie(\n\t\tname: string,\n\t\tvalue: string,\n\t\toptions: CookieOptions = {},\n\t): this {\n\t\tthis.ensureActive();\n\t\tthis._cookies.push({ name, value, options });\n\t\treturn this;\n\t}\n\n\t/**\n\t * Clears a cookie by expiring it immediately.\n\t *\n\t * @param {string} name - Cookie name to expire.\n\t * @param {CookieOptions} [options={}] - Additional cookie attributes that\n\t * must match the original cookie scope.\n\t * @returns {this} The current response wrapper for fluent chaining.\n\t */\n\tpublic clearCookie(name: string, options: CookieOptions = {}): this {\n\t\treturn this.cookie(name, \"\", { ...options, expires: new Date(0) });\n\t}\n\n\t/**\n\t * Sends a response body using a best-effort content type.\n\t *\n\t * The method flushes pending cookies before writing, chooses a default\n\t * content type when none is set, and treats plain objects as JSON by\n\t * delegating to `json()`. Calling `send()` is a terminal operation for the\n\t * response lifecycle.\n\t *\n\t * @param {unknown} [data] - Response payload to send.\n\t * @throws {Error} Thrown when the response has already ended.\n\t */\n\tpublic send(data?: unknown): void {\n\t\tthis.applyPendingCookies();\n\t\tthis.ensureActive();\n\n\t\ttry {\n\t\t\tif (data === undefined || data === null) {\n\t\t\t\tthis.end();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (Buffer.isBuffer(data)) {\n\t\t\t\tif (!this.res.getHeader(\"Content-Type\")) {\n\t\t\t\t\tthis.setHeader(\"Content-Type\", \"application/octet-stream\");\n\t\t\t\t}\n\t\t\t\tthis.res.end(data);\n\t\t\t} else if (typeof data === \"object\") {\n\t\t\t\tthis.json(data as object);\n\t\t\t\treturn;\n\t\t\t} else {\n\t\t\t\tif (!this.res.getHeader(\"Content-Type\")) {\n\t\t\t\t\tthis.setHeader(\"Content-Type\", \"text/plain; charset=utf-8\");\n\t\t\t\t}\n\t\t\t\tthis.res.end(String(data));\n\t\t\t}\n\t\t} finally {\n\t\t\tthis._ended = true;\n\t\t}\n\t}\n\n\t/**\n\t * Sends a JSON response.\n\t *\n\t * Pending cookies are flushed before serialization. If JSON serialization\n\t * throws, the method logs the failure and falls back to a `500 Internal\n\t * Server Error` response body.\n\t *\n\t * @param {object} obj - Plain object to serialize as JSON.\n\t */\n\tpublic json(obj: object): void {\n\t\tthis.applyPendingCookies();\n\t\tthis.ensureActive();\n\n\t\ttry {\n\t\t\tconst body = JSON.stringify(obj);\n\t\t\tthis.res.setHeader(\"Content-Type\", \"application/json; charset=utf-8\");\n\t\t\tthis.res.end(body);\n\t\t} catch (err) {\n\t\t\tlogger.error(\"Failed to serialize JSON response:\", err);\n\t\t\tthis.res.statusCode = 500;\n\t\t\tthis.res.end(\"Internal Server Error\");\n\t\t} finally {\n\t\t\tthis._ended = true;\n\t\t}\n\t}\n\n\t/**\n\t * Sends a redirect response.\n\t *\n\t * This sets the status code, writes the `Location` header, and then ends the\n\t * response.\n\t *\n\t * @param {string} url - Redirect target written to the `Location` header.\n\t * @param {number} [status=302] - Redirect status code.\n\t */\n\tpublic redirect(url: string, status = 302): void {\n\t\tthis.status(status).setHeader(\"Location\", url).end();\n\t}\n\n\t/**\n\t * Ends the response without sending additional data.\n\t *\n\t * Pending cookies are flushed before the underlying response is closed.\n\t *\n\t * @throws {Error} Thrown when the response has already ended.\n\t */\n\tpublic end(): void {\n\t\tthis.applyPendingCookies();\n\t\tthis.ensureActive();\n\t\tthis.res.end();\n\t\tthis._ended = true;\n\t}\n\n\t/**\n\t * Streams a file to the client.\n\t *\n\t * The method resolves the final path, verifies that it points to a regular\n\t * file, sets `Content-Length`, flushes pending cookies, and pipes the file\n\t * stream into the underlying response. Missing files and stream failures fall\n\t * back to a `404` JSON error payload.\n\t *\n\t * @param {string} filePath - File path to stream. When `opts.root` is set, it\n\t * is resolved relative to that root.\n\t * @param {{ root?: string }} [opts={}] - Optional root directory used to\n\t * resolve relative file paths.\n\t */\n\tpublic sendFile(filePath: string, opts: { root?: string } = {}): void {\n\t\tthis.ensureActive();\n\t\ttry {\n\t\t\tconst fullPath = opts.root ? join(opts.root, filePath) : filePath;\n\t\t\tconst stats = statSync(fullPath);\n\n\t\t\tif (!stats.isFile()) throw new Error(\"Target is not a file\");\n\n\t\t\tthis.setHeader(\"Content-Length\", String(stats.size));\n\t\t\tconst stream = createReadStream(fullPath);\n\n\t\t\tthis.applyPendingCookies();\n\t\t\tstream.pipe(this.res);\n\n\t\t\tstream.on(\"error\", () => {\n\t\t\t\tthis.status(404).send({ error: \"File not found\" });\n\t\t\t});\n\t\t} catch {\n\t\t\tthis.status(404).send({ error: \"File not found\" });\n\t\t} finally {\n\t\t\tthis._ended = true;\n\t\t}\n\t}\n\n\t/**\n\t * Serializes queued cookies into the response headers and clears the queue.\n\t *\n\t * Existing `Set-Cookie` headers are preserved and extended so multiple\n\t * middleware and handler calls can contribute cookies before the response is\n\t * finalized.\n\t */\n\tprivate applyPendingCookies(): void {\n\t\tif (this._cookies.length === 0) return;\n\n\t\tconst existing = (this.res.getHeader(\"Set-Cookie\") as string[]) || [];\n\t\tconst serialized = this._cookies.map((cookie) =>\n\t\t\tserializeCookie(cookie.name, cookie.value, cookie.options as any),\n\t\t);\n\n\t\tthis.res.setHeader(\"Set-Cookie\", [...existing, ...serialized]);\n\t\tthis._cookies = [];\n\t}\n\n\t/**\n\t * Ensures the response has not already been finalized.\n\t *\n\t * @throws {Error} Thrown when a terminal response method has already sent or\n\t * ended the response.\n\t */\n\tprivate ensureActive(): void {\n\t\tif (this._ended) {\n\t\t\tthrow new Error(\"Response has already been sent.\");\n\t\t}\n\t}\n}\n","import { logger, red } from \"@lithia-js/utils\";\nimport type { Socket } from \"socket.io\";\nimport { InternalServerError } from \"../../errors/app/index\";\nimport { LithiaClientError } from \"../../errors/base\";\nimport { produceDigest } from \"../../shared/digest\";\nimport type { Environment } from \"../../types\";\n\n/**\n * Converts an uncaught socket event failure into the standard Lithia error\n * event payload.\n *\n * Client-facing framework errors preserve their declared status code and\n * message. Unknown failures are wrapped as internal server errors, and\n * production mode hides 5xx details behind a generic message before emitting\n * the error to the active socket.\n *\n * Related docs:\n * - https://lithiajs.org/docs/latest/events\n *\n * @param {Environment} environment - Current runtime environment used to decide\n * whether internal messages should be exposed.\n * @param {Socket} socket - Active socket that receives the emitted `\"error\"`\n * event payload.\n * @param {string} eventName - Name of the event being processed when the\n * failure occurred.\n * @param {any} err - Original thrown value captured from the event pipeline.\n */\nexport function handleEventError(\n\tenvironment: Environment,\n\tsocket: Socket,\n\teventName: string,\n\terr: any,\n): void {\n\tconst error =\n\t\terr instanceof LithiaClientError\n\t\t\t? err\n\t\t\t: new InternalServerError(\n\t\t\t\t\t\"An internal server error occurred during event processing.\",\n\t\t\t\t\terr,\n\t\t\t\t);\n\n\tconst isProd = environment === \"production\";\n\tconst statusCode = error.statusCode || 500;\n\tconst digest = produceDigest(err);\n\tconst message =\n\t\tisProd && statusCode >= 500 ? \"Internal Server Error\" : error.message;\n\n\tsocket.emit(\"error\", {\n\t\terror: {\n\t\t\tstatusCode,\n\t\t\tmessage,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tdigest,\n\t\t\tevent: eventName,\n\t\t\tdetails: error.details,\n\t\t},\n\t});\n\n\tif (statusCode >= 500) {\n\t\tlogger.error(`Digest: ${red(digest)}`);\n\t\tlogger.info(`Event: ${eventName}`);\n\t\tlogger.info(`Socket ID: ${socket.id}`);\n\t\tlogger.info(err.stack || err);\n\t}\n}\n","import type { Socket } from \"socket.io\";\nimport type { Event } from \"../../discovery/events\";\nimport type { LithiaApp } from \"../../runtime/app/app-runtime\";\nimport { loadModule } from \"../../shared/module-loader\";\nimport { executePipeline } from \"../../shared/pipeline\";\nimport { handleEventError } from \"./event-error-handler\";\n\n/**\n * Continuation used by event middleware to hand control to the next step in\n * the event pipeline.\n *\n * Calling `next()` transfers control to the next middleware or, once the stack\n * is exhausted, to the final event handler.\n */\nexport type NextEvent = () => Promise<void> | void;\n\n/**\n * Middleware executed before a socket event handler.\n *\n * @param {Socket} socket - Active socket associated with the event execution.\n * @param {NextEvent} next - Continuation that advances to the next middleware\n * or event handler.\n * @returns {Promise<void>} Resolves after the middleware completes.\n */\nexport type EventMiddleware = (\n\tsocket: Socket,\n\tnext: NextEvent,\n) => Promise<void>;\n\n/**\n * Event module default export signature.\n *\n * @param {Socket} socket - Active socket for the current event.\n * @param {any} [data] - Event payload forwarded from Socket.IO.\n * @returns {Promise<void>} Resolves after the event handler completes.\n */\nexport type EventHandler = (socket: Socket, data?: any) => Promise<void>;\n\n/**\n * Full module contract for a file-based event handler.\n *\n * Discovered event modules must provide a default handler and may optionally\n * export event-scoped middleware.\n */\nexport type EventModule = {\n\tdefault: EventHandler;\n\tmiddlewares?: EventMiddleware[];\n};\n\n/**\n * Executes the realtime event pipeline for Lithia event handlers.\n *\n * The processor loads the matched event module, composes global and\n * event-scoped middleware, and runs the final event handler through the shared\n * pipeline runner. Uncaught failures are translated into a socket `\"error\"`\n * event through `handleEventError()`.\n *\n * Related docs:\n * - https://lithiajs.org/docs/latest/events\n * - https://lithiajs.org/docs/latest/project-structure\n */\nexport class LithiaEventProcessor {\n\t/**\n\t * Creates an event processor bound to a running Lithia app instance.\n\t *\n\t * @param {LithiaApp} app - Runtime app state that provides environment and\n\t * global event middleware.\n\t */\n\tconstructor(private readonly app: LithiaApp) {}\n\n\t/**\n\t * Processes a single discovered realtime event.\n\t *\n\t * @param {Socket} socket - Active socket that triggered the event.\n\t * @param {Event} event - Discovered event manifest selected by the socket\n\t * transport.\n\t * @param {any} [data] - Event payload forwarded from Socket.IO.\n\t * @returns {Promise<void>} Resolves after middleware and the event handler\n\t * complete, or after the error handler emits a failure payload.\n\t */\n\tpublic async process(\n\t\tsocket: Socket,\n\t\tevent: Event,\n\t\tdata?: any,\n\t): Promise<void> {\n\t\ttry {\n\t\t\tconst module = await loadModule<EventModule>(event.filePath);\n\t\t\tconst pipeline = [\n\t\t\t\t...this.app.globalEventMiddlewares,\n\t\t\t\t...(module.middlewares || []),\n\t\t\t];\n\n\t\t\tawait executePipeline(\n\t\t\t\tpipeline.map(\n\t\t\t\t\t(middleware) => (next) => middleware(socket, () => next()),\n\t\t\t\t),\n\t\t\t\t() => module.default(socket, data),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\thandleEventError(this.app.environment, socket, event.name, error);\n\t\t}\n\t}\n}\n","/**\n * @fileoverview Event Context Management for Lithia.js.\n * Utilizes AsyncLocalStorage to provide a thread-safe way to access\n * event-specific data (socket, payload, dependencies) without prop-drilling.\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { Socket } from \"socket.io\";\nimport type { Event } from \"../discovery/events\";\nimport { NotInEventContextError } from \"../errors/internal/index\";\n\nexport interface EventContext {\n\tdata: any;\n\tsocket: Socket;\n\tevent: Event;\n}\n\nconst CONTEXT_GLOBAL_KEY = Symbol.for(\"lithia.event_context.v1\");\n\nfunction getGlobalStore(): AsyncLocalStorage<EventContext> {\n\tconst globalAny = globalThis as any;\n\tif (!globalAny[CONTEXT_GLOBAL_KEY]) {\n\t\tglobalAny[CONTEXT_GLOBAL_KEY] = new AsyncLocalStorage<EventContext>();\n\t}\n\treturn globalAny[CONTEXT_GLOBAL_KEY];\n}\n\nexport const eventContextStore = getGlobalStore();\n\nexport function getEventContext(): EventContext {\n\tconst ctx = eventContextStore.getStore();\n\tif (!ctx) {\n\t\tthrow new NotInEventContextError();\n\t}\n\treturn ctx;\n}\n\nexport function runInEventContext<T>(context: EventContext, fn: () => T): T {\n\treturn eventContextStore.run(context, fn);\n}\n","import type { Server as HttpServer, Server as HttpsServer } from \"node:http\";\nimport { type Socket, Server as SocketServer } from \"socket.io\";\nimport {\n\ttype EventContext,\n\teventContextStore,\n} from \"../../context/event-context\";\nimport type { Event } from \"../../discovery/events\";\nimport type { LithiaApp } from \"../../runtime/app/app-runtime\";\nimport type { LithiaEventProcessor } from \"./event-pipeline\";\n\n/**\n * Owns the Socket.IO transport used for Lithia realtime event handlers.\n *\n * The transport bridges Socket.IO connection lifecycle events and custom\n * socket events into the discovered Lithia event manifest set, while also\n * establishing the per-event execution context used by event hooks.\n *\n * Related docs:\n * - https://lithiajs.org/docs/latest/events\n * - https://lithiajs.org/docs/latest/project-structure\n */\nexport class LithiaSocketTransport {\n\tprivate readonly io: SocketServer;\n\n\t/**\n\t * Creates the Socket.IO transport and registers connection listeners.\n\t *\n\t * The constructor configures Socket.IO CORS from the app's HTTP settings and\n\t * immediately wires connection, disconnect, and custom event dispatch into\n\t * the Lithia event processor.\n\t *\n\t * @param {LithiaApp} app - Running app instance that provides config and the\n\t * discovered event manifest list.\n\t * @param {HttpServer | HttpsServer} httpServer - Underlying HTTP server used\n\t * as the Socket.IO transport base.\n\t * @param {LithiaEventProcessor} processor - Event processor responsible for\n\t * executing event middleware and handlers.\n\t */\n\tconstructor(\n\t\tprivate readonly app: LithiaApp,\n\t\thttpServer: HttpServer | HttpsServer,\n\t\tprivate readonly processor: LithiaEventProcessor,\n\t) {\n\t\tconst { cors } = this.app.config.http;\n\n\t\tthis.io = new SocketServer(httpServer, {\n\t\t\tcors: {\n\t\t\t\torigin: cors.origin,\n\t\t\t\tmethods: cors.methods,\n\t\t\t\tcredentials: cors.credentials,\n\t\t\t},\n\t\t});\n\n\t\tthis.io.on(\"connection\", (socket: Socket) => {\n\t\t\tconst eventMap = new Map(\n\t\t\t\tthis.app.events.map((event) => [event.name, event]),\n\t\t\t);\n\n\t\t\tconst connectionEvent = eventMap.get(\"connection\");\n\t\t\tif (connectionEvent) this.dispatch(socket, connectionEvent);\n\n\t\t\tsocket.on(\"disconnect\", (...args: any[]) => {\n\t\t\t\tconst disconnectEvent = eventMap.get(\"disconnect\");\n\t\t\t\tif (disconnectEvent) this.dispatch(socket, disconnectEvent, ...args);\n\t\t\t});\n\n\t\t\tsocket.onAny((eventName: string, ...args: any[]) => {\n\t\t\t\tconst customEvent = this.app.events.find(\n\t\t\t\t\t(event) => event.name === eventName,\n\t\t\t\t);\n\t\t\t\tif (customEvent) this.dispatch(socket, customEvent, ...args);\n\t\t\t});\n\t\t});\n\t}\n\n\t/**\n\t * Returns the underlying Socket.IO server instance.\n\t *\n\t * @returns {SocketServer} Active Socket.IO server.\n\t */\n\tpublic get server(): SocketServer {\n\t\treturn this.io;\n\t}\n\n\t/**\n\t * Closes the Socket.IO transport and disconnects active sockets.\n\t *\n\t * @returns {Promise<void>} Resolves after Socket.IO finishes shutting down.\n\t */\n\tpublic async close(): Promise<void> {\n\t\tawait this.io.close();\n\t}\n\n\t/**\n\t * Dispatches a discovered Lithia event inside the correct runtime contexts.\n\t *\n\t * The call first enters the app-level async context and then the event\n\t * context store so event hooks can access the active socket, payload, and\n\t * event metadata during middleware and handler execution.\n\t *\n\t * @param {Socket} socket - Active socket associated with the dispatch.\n\t * @param {Event} event - Discovered event manifest to execute.\n\t * @param {any[]} args - Raw Socket.IO event arguments forwarded to the event\n\t * processor.\n\t */\n\tprivate dispatch(socket: Socket, event: Event, ...args: any[]): void {\n\t\tvoid this.app.runWithContext(async () => {\n\t\t\tconst context: EventContext = {\n\t\t\t\tdata: args[0],\n\t\t\t\tsocket,\n\t\t\t\tevent,\n\t\t\t};\n\n\t\t\teventContextStore.run(context, async () => {\n\t\t\t\tawait this.processor.process(socket, event, ...args);\n\t\t\t});\n\t\t});\n\t}\n}\n","import {\n\tcreateServer as createHttpServer,\n\ttype Server as HttpServer,\n\ttype IncomingMessage,\n\ttype ServerResponse,\n} from \"node:http\";\nimport {\n\tcreateServer as createHttpsServer,\n\ttype Server as HttpsServer,\n} from \"node:https\";\nimport type { Socket as ActiveRequest } from \"node:net\";\nimport { logger } from \"@lithia-js/utils\";\nimport {\n\ttype RouteContext,\n\trouteContextStore,\n} from \"../context/request-context\";\nimport type { LithiaApp } from \"../runtime/app/app-runtime\";\nimport { LithiaRequest } from \"./http/request\";\nimport { LithiaRequestProcessor } from \"./http/request-pipeline\";\nimport { LithiaResponse } from \"./http/response\";\nimport { LithiaEventProcessor } from \"./socket/event-pipeline\";\nimport { LithiaSocketTransport } from \"./socket/socket-server\";\n\n/**\n * Runtime HTTP server options used by Lithia.\n *\n * This interface describes the low-level network settings required to listen\n * for HTTP or HTTPS traffic.\n */\nexport interface LithiaServerOpts {\n\t/**\n\t * TCP port used by the transport server.\n\t */\n\tport: number;\n\t/**\n\t * Hostname or interface address used by the transport server.\n\t */\n\thost: string;\n\t/**\n\t * Optional HTTPS certificate material. When present, Lithia creates an HTTPS\n\t * server instead of a plain HTTP server.\n\t */\n\tssl?: {\n\t\t/**\n\t\t * PEM-encoded private key contents.\n\t\t */\n\t\tkey: string;\n\t\t/**\n\t\t * PEM-encoded certificate contents.\n\t\t */\n\t\tcert: string;\n\t\t/**\n\t\t * Optional passphrase for the private key.\n\t\t */\n\t\tpassphrase?: string;\n\t};\n}\n\n/**\n * Owns the HTTP/HTTPS server, request pipeline, and Socket.IO transport for a\n * running Lithia app.\n *\n * The server is the transport boundary for the runtime: it initializes the\n * HTTP request processor, the realtime event processor, tracks active TCP\n * connections, and coordinates startup and shutdown for both HTTP and Socket.IO.\n *\n * Related docs:\n * - https://lithiajs.org/docs/latest/routes\n * - https://lithiajs.org/docs/latest/events\n * - https://lithiajs.org/docs/latest/project-structure\n */\nexport class LithiaServer {\n\tprivate readonly _httpServer: HttpServer | HttpsServer;\n\tprivate readonly requestProcessor: LithiaRequestProcessor;\n\tprivate readonly eventProcessor: LithiaEventProcessor;\n\tprivate readonly socketTransport: LithiaSocketTransport;\n\tprivate readonly _activeRequests = new Set<ActiveRequest>();\n\n\t/**\n\t * Creates the transport server for a running app instance.\n\t *\n\t * @param {LithiaApp} app - Runtime app that provides config, route/event\n\t * manifests, and async context helpers.\n\t */\n\tconstructor(private readonly app: LithiaApp) {\n\t\tthis.requestProcessor = new LithiaRequestProcessor(this.app);\n\t\tthis.eventProcessor = new LithiaEventProcessor(this.app);\n\t\tthis._httpServer = this.createServer();\n\t\tthis.socketTransport = new LithiaSocketTransport(\n\t\t\tthis.app,\n\t\t\tthis._httpServer,\n\t\t\tthis.eventProcessor,\n\t\t);\n\t}\n\n\t/**\n\t * Returns the set of currently open TCP connections tracked by the server.\n\t *\n\t * The set is updated from the Node.js `\"connection\"` event and is used during\n\t * shutdown to forcefully destroy lingering sockets after the server stops\n\t * accepting new traffic.\n\t *\n\t * @returns {Set<ActiveRequest>} Tracked open TCP sockets.\n\t */\n\tpublic get activeRequests(): Set<ActiveRequest> {\n\t\treturn this._activeRequests;\n\t}\n\n\t/**\n\t * Returns the underlying Node.js HTTP or HTTPS server instance.\n\t *\n\t * @returns {HttpServer | HttpsServer} Active low-level server instance.\n\t */\n\tpublic get httpServer(): HttpServer | HttpsServer {\n\t\treturn this._httpServer;\n\t}\n\n\t/**\n\t * Returns the Socket.IO server attached to the transport.\n\t *\n\t * @returns {ReturnType<LithiaSocketTransport[\"server\"]>} Active Socket.IO\n\t * server instance.\n\t */\n\tpublic get socketServer() {\n\t\treturn this.socketTransport.server;\n\t}\n\n\t/**\n\t * Starts listening on the configured host and port.\n\t *\n\t * Repeated calls are idempotent while the underlying server is already\n\t * listening. The returned promise resolves on the low-level `\"listening\"`\n\t * event and rejects on the first startup error emitted by Node.js.\n\t *\n\t * @returns {Promise<void>} Resolves after the transport begins accepting\n\t * connections.\n\t */\n\tpublic async listen(): Promise<void> {\n\t\tconst { port, host } = this.app.config.http;\n\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (this._httpServer.listening) {\n\t\t\t\treturn resolve();\n\t\t\t}\n\n\t\t\tconst handleError = (error: Error) => {\n\t\t\t\tthis._httpServer.off(\"listening\", handleListening);\n\t\t\t\treject(error);\n\t\t\t};\n\n\t\t\tconst handleListening = () => {\n\t\t\t\tthis._httpServer.off(\"error\", handleError);\n\t\t\t\tresolve();\n\t\t\t};\n\n\t\t\tthis._httpServer.once(\"error\", handleError);\n\t\t\tthis._httpServer.once(\"listening\", handleListening);\n\t\t\tthis._httpServer.listen(port, host);\n\t\t});\n\t}\n\n\t/**\n\t * Closes the Socket.IO transport, stops accepting HTTP traffic, and destroys\n\t * any remaining active connections.\n\t *\n\t * Socket.IO shutdown is attempted first so realtime traffic stops before the\n\t * underlying HTTP server is closed. Remaining sockets are then destroyed to\n\t * avoid hanging shutdown on keep-alive connections.\n\t *\n\t * @returns {Promise<void>} Resolves after the transport has been shut down and\n\t * tracked connections have been cleared.\n\t */\n\tpublic async close(): Promise<void> {\n\t\tawait this.socketTransport.close().catch((error) => {\n\t\t\tlogger.error(\"Failed to close Socket.IO transport cleanly:\", error);\n\t\t});\n\n\t\tif (!this._httpServer.listening) {\n\t\t\tfor (const socket of this._activeRequests) {\n\t\t\t\tsocket.destroy();\n\t\t\t}\n\t\t\tthis._activeRequests.clear();\n\t\t\treturn;\n\t\t}\n\n\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\tthis._httpServer.close((error) => {\n\t\t\t\tif (error) return reject(error);\n\t\t\t\tresolve();\n\t\t\t});\n\t\t});\n\n\t\tfor (const socket of this._activeRequests) {\n\t\t\tsocket.destroy();\n\t\t}\n\n\t\tthis._activeRequests.clear();\n\t}\n\n\t/**\n\t * Creates the underlying HTTP or HTTPS server instance.\n\t *\n\t * The returned server also tracks active sockets so shutdown can destroy\n\t * lingering keep-alive connections after `close()`.\n\t *\n\t * @returns {HttpServer | HttpsServer} Low-level server configured for the\n\t * current app transport.\n\t */\n\tprivate createServer(): HttpServer | HttpsServer {\n\t\tconst handler = this.handleRequest();\n\t\tconst sslConfig = this.app.config.http.ssl;\n\n\t\tconst server = sslConfig\n\t\t\t? createHttpsServer(sslConfig, handler)\n\t\t\t: createHttpServer(handler);\n\n\t\tserver.on(\"connection\", (socket: ActiveRequest) => {\n\t\t\tthis._activeRequests.add(socket);\n\t\t\tsocket.on(\"close\", () => this._activeRequests.delete(socket));\n\t\t});\n\n\t\treturn server;\n\t}\n\n\t/**\n\t * Creates the low-level Node request handler and bridges it into Lithia's\n\t * request context and request pipeline.\n\t *\n\t * Each incoming Node.js request is wrapped into `LithiaRequest` and\n\t * `LithiaResponse`, associated with a route context store, and then processed\n\t * inside the app-level async context so route hooks can access the active\n\t * request state.\n\t *\n\t * If request initialization itself fails before the normal request pipeline\n\t * takes over, the handler falls back to a minimal JSON `500` response.\n\t *\n\t * @returns {(req: IncomingMessage, res: ServerResponse) => void} Node.js\n\t * request listener bound to the current app instance.\n\t */\n\tprivate handleRequest() {\n\t\treturn (req: IncomingMessage, res: ServerResponse) => {\n\t\t\ttry {\n\t\t\t\tconst lithiaReq = new LithiaRequest(req, {\n\t\t\t\t\tmaxBodySize: this.app.config.http.maxBodySize,\n\t\t\t\t});\n\t\t\t\tconst lithiaRes = new LithiaResponse(res);\n\n\t\t\t\tconst routeContext: RouteContext = {\n\t\t\t\t\treq: lithiaReq,\n\t\t\t\t\tres: lithiaRes,\n\t\t\t\t\tsocketServer: this.socketTransport.server,\n\t\t\t\t};\n\n\t\t\t\tvoid this.app.runWithContext(async () => {\n\t\t\t\t\trouteContextStore.run(routeContext, async () => {\n\t\t\t\t\t\tawait this.requestProcessor.process(lithiaReq, lithiaRes);\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tlogger.error(\"Failed to initialize request context:\", error);\n\t\t\t\tif (!res.headersSent) {\n\t\t\t\t\tres.statusCode = 500;\n\t\t\t\t\tres.setHeader(\"Content-Type\", \"application/json\");\n\t\t\t\t}\n\t\t\t\tif (!res.writableEnded) {\n\t\t\t\t\tres.end(\n\t\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\t\tstatusCode: 500,\n\t\t\t\t\t\t\t\tmessage: \"Failed to initialize request handling.\",\n\t\t\t\t\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t}\n}\n","/**\n * Small mutable container used to store app-scoped dependencies.\n *\n * The app runtime uses this container as the backing store for `provide()`,\n * `useDependency()`, and `useOptionalDependency()`. Immutable snapshots are\n * used for request-time and task-time execution, while the mutable map is used\n * during bootstrap.\n */\nexport class DependencyContainer {\n\tprivate readonly dependencies = new Map<any, any>();\n\n\t/**\n\t * Stores a dependency by its injection key.\n\t *\n\t * @param {any} key - Injection token used to identify the dependency.\n\t * @param {T} value - Dependency instance stored under `key`.\n\t */\n\tpublic set<T>(key: any, value: T): void {\n\t\tthis.dependencies.set(key, value);\n\t}\n\n\t/**\n\t * Returns whether a dependency has been registered.\n\t *\n\t * @param {any} key - Injection token to test.\n\t * @returns {boolean} `true` when the container includes `key`.\n\t */\n\tpublic has(key: any): boolean {\n\t\treturn this.dependencies.has(key);\n\t}\n\n\t/**\n\t * Resolves a dependency by key.\n\t *\n\t * @param {any} key - Injection token to resolve.\n\t * @returns {T | undefined} Registered dependency instance, or `undefined`\n\t * when the key is absent.\n\t */\n\tpublic get<T>(key: any): T | undefined {\n\t\treturn this.dependencies.get(key) as T | undefined;\n\t}\n\n\t/**\n\t * Returns an immutable snapshot of the container contents.\n\t *\n\t * The returned `Map` is detached from future container mutations, which lets\n\t * the runtime execute work against a stable dependency view.\n\t *\n\t * @returns {Map<any, any>} Shallow copy of the current container contents.\n\t */\n\tpublic snapshot(): Map<any, any> {\n\t\treturn new Map(this.dependencies);\n\t}\n\n\t/**\n\t * Returns the underlying mutable container.\n\t *\n\t * Mutating the returned `Map` mutates the container itself.\n\t *\n\t * @returns {Map<any, any>} Backing dependency map used by the runtime.\n\t */\n\tpublic mutable(): Map<any, any> {\n\t\treturn this.dependencies;\n\t}\n}\n","/**\n * Stores app-wide route and event middlewares.\n *\n * The registry keeps both middleware pipelines separate while preserving\n * registration order inside each one.\n */\nexport class MiddlewareRegistry<TRouteMiddleware, TEventMiddleware> {\n\tprivate readonly routeMiddlewares: TRouteMiddleware[] = [];\n\tprivate readonly eventMiddlewares: TEventMiddleware[] = [];\n\n\t/**\n\t * Registers a middleware for either the route or event pipeline.\n\t *\n\t * Route middleware is appended to the global HTTP pipeline. Event\n\t * middleware is appended to the global socket event pipeline.\n\t *\n\t * @param {\"route\" | \"event\"} context - Pipeline that should receive the\n\t * middleware.\n\t * @param {TRouteMiddleware | TEventMiddleware} middleware - Middleware\n\t * instance appended to the selected pipeline.\n\t */\n\tpublic use(\n\t\tcontext: \"route\" | \"event\",\n\t\tmiddleware: TRouteMiddleware | TEventMiddleware,\n\t): void {\n\t\tif (context === \"route\") {\n\t\t\tthis.routeMiddlewares.push(middleware as TRouteMiddleware);\n\t\t\treturn;\n\t\t}\n\n\t\tthis.eventMiddlewares.push(middleware as TEventMiddleware);\n\t}\n\n\t/**\n\t * Returns the registered global route middlewares.\n\t *\n\t * The returned array is the live registry array and preserves registration\n\t * order.\n\t *\n\t * @returns {TRouteMiddleware[]} Registered route middlewares.\n\t */\n\tpublic getRoutes(): TRouteMiddleware[] {\n\t\treturn this.routeMiddlewares;\n\t}\n\n\t/**\n\t * Returns the registered global event middlewares.\n\t *\n\t * The returned array is the live registry array and preserves registration\n\t * order.\n\t *\n\t * @returns {TEventMiddleware[]} Registered event middlewares.\n\t */\n\tpublic getEvents(): TEventMiddleware[] {\n\t\treturn this.eventMiddlewares;\n\t}\n}\n","import { access, readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\n\n/**\n * Checks whether a filesystem entry is accessible at the provided path.\n *\n * @param {string} filePath - Absolute or relative path to test.\n * @returns {Promise<boolean>} `true` when the path can be accessed.\n */\nexport async function fileExists(filePath: string): Promise<boolean> {\n\treturn await access(filePath)\n\t\t.then(() => true)\n\t\t.catch(() => false);\n}\n\n/**\n * Determines whether a source file contains anything beyond whitespace and\n * comments.\n *\n * The heuristic strips block comments and line comments before checking whether\n * any meaningful source text remains.\n *\n * @param {string} filePath - Source file to inspect.\n * @returns {Promise<boolean>} `true` when the file still contains code or other\n * non-comment text after comment removal.\n */\nexport async function fileHasMeaningfulModuleContent(\n\tfilePath: string,\n): Promise<boolean> {\n\tconst source = await readFile(filePath, \"utf8\");\n\tconst withoutComments = source\n\t\t.replace(/\\/\\*[\\s\\S]*?\\*\\//g, \"\")\n\t\t.replace(/^\\s*\\/\\/.*$/gm, \"\");\n\n\treturn withoutComments.trim().length > 0;\n}\n\n/**\n * Maps a source-relative TypeScript path to its emitted JavaScript output path.\n *\n * The helper preserves the relative directory structure under the provided root\n * while converting `.ts` files to `.js` and `.mts` files to `.mjs`.\n *\n * @param {string} root - Output root directory.\n * @param {string} relativePath - Source-relative file path.\n * @returns {string} Emitted output file path under the output root.\n */\nexport function toOutputFilePath(root: string, relativePath: string): string {\n\treturn path\n\t\t.join(root, relativePath)\n\t\t.replace(/\\.ts$/, \".js\")\n\t\t.replace(/\\.mts$/, \".mjs\");\n}\n","import path from \"node:path\";\nimport {\n\tfileExists,\n\tfileHasMeaningfulModuleContent,\n} from \"../../shared/filesystem\";\nimport { loadModule } from \"../../shared/module-loader\";\n\n/**\n * Optional cleanup returned by `app/server.ts`.\n *\n * The cleanup callback runs during controlled shutdown after the startup\n * bootstrap has completed successfully.\n */\nexport type LithiaServerCleanup = void | (() => void | Promise<void>);\n\n/**\n * Bootstrap contract for `src/app/server.ts`.\n *\n * The function runs before the app starts accepting traffic and may return an\n * optional cleanup callback that runs during shutdown and reload. Startup\n * lifecycle details are described in\n * [Project Structure](https://lithiajs.org/docs/latest/project-structure) and\n * [Deploying](https://lithiajs.org/docs/latest/deploying).\n */\nexport type LithiaServerBootstrap = () => Promise<LithiaServerCleanup>;\n\n/**\n * Resolves the compiled `app/server` bootstrap file inside the output\n * directory.\n *\n * Empty or non-meaningful modules are ignored so placeholder files do not\n * participate in runtime startup.\n *\n * @param {string} outDir - Build output directory that may contain the\n * compiled bootstrap file.\n * @param {string} cwd - Project root used to resolve the output directory.\n * Defaults to `process.cwd()`.\n * @returns {Promise<string | null>} Absolute path to the compiled bootstrap\n * module, or `null` when no usable bootstrap file exists.\n */\nexport async function resolveServerBootstrapPath(\n\toutDir: string,\n\tcwd = process.cwd(),\n): Promise<string | null> {\n\tconst candidates = [\n\t\tpath.join(cwd, outDir, \"app\", \"server.js\"),\n\t\tpath.join(cwd, outDir, \"app\", \"server.mjs\"),\n\t];\n\n\tfor (const candidate of candidates) {\n\t\tif (\n\t\t\t(await fileExists(candidate)) &&\n\t\t\t(await fileHasMeaningfulModuleContent(candidate))\n\t\t) {\n\t\t\treturn candidate;\n\t\t}\n\t}\n\n\treturn null;\n}\n\n/**\n * Loads the compiled `app/server` bootstrap module.\n *\n * @param {string} filePath - Absolute path to the compiled bootstrap module.\n * @returns {Promise<LithiaServerBootstrap>} Default-exported bootstrap\n * function.\n * @throws {Error} Throws when the module cannot be loaded or does not match\n * the expected shape.\n */\nexport async function loadServerBootstrap(\n\tfilePath: string,\n): Promise<LithiaServerBootstrap> {\n\tconst mod = await loadModule<{ default: LithiaServerBootstrap }>(filePath);\n\treturn mod.default;\n}\n\n/**\n * Normalizes the bootstrap return value into an async cleanup callback.\n *\n * `undefined` means no cleanup should run. Function values are wrapped in an\n * async callback so the runtime can await both sync and async cleanup\n * implementations uniformly.\n *\n * @param {LithiaServerCleanup} value - Value returned by the bootstrap\n * function.\n * @returns {(() => Promise<void>) | null} Normalized async cleanup callback,\n * or `null` when the bootstrap does not register cleanup.\n * @throws {Error} Throws when the bootstrap returns a value other than\n * `undefined` or a function.\n */\nexport function normalizeServerBootstrapCleanup(\n\tvalue: LithiaServerCleanup,\n): (() => Promise<void>) | null {\n\tif (value === undefined) return null;\n\n\tif (typeof value !== \"function\") {\n\t\tthrow new Error(\n\t\t\t\"`app/server.ts` must return either nothing or a cleanup function.\",\n\t\t);\n\t}\n\n\treturn async () => {\n\t\tawait value();\n\t};\n}\n","import cron from \"node-cron\";\nimport type { TaskCore } from \"../../discovery/tasks\";\n\n/**\n * Scheduled job handle returned by `node-cron`.\n */\ntype ScheduledCronJob = ReturnType<typeof cron.schedule>;\n\n/**\n * Registers and manages CRON-backed Lithia tasks inside the app worker.\n *\n * The scheduler only handles tasks already resolved as `CRON` in the task\n * manifest. CRON task semantics are described in\n * [Async Tasks](https://lithiajs.org/docs/latest/async-tasks) and\n * [Deploying](https://lithiajs.org/docs/latest/deploying).\n */\nexport class TaskScheduler {\n\tprivate readonly cronJobs: ScheduledCronJob[] = [];\n\n\t/**\n\t * Creates a scheduler for the task manifest loaded into the current app\n\t * worker.\n\t *\n\t * @param {TaskCore[]} tasks - Task manifest entries available to the app\n\t * runtime.\n\t */\n\tconstructor(private readonly tasks: TaskCore[]) {}\n\n\t/**\n\t * Starts all CRON tasks and invokes the callback when a schedule fires.\n\t *\n\t * Each CRON task must already include a validated `schedule` string. When a\n\t * schedule triggers, the scheduler invokes `onTrigger` with the original\n\t * task metadata.\n\t *\n\t * @param {(task: TaskCore) => void} onTrigger - Callback invoked when a CRON\n\t * task schedule fires.\n\t * @throws {Error} Throws when a CRON task is missing its resolved\n\t * `schedule`.\n\t */\n\tpublic start(onTrigger: (task: TaskCore) => void): void {\n\t\tconst cronTasks = this.tasks.filter((task) => task.trigger === \"CRON\");\n\n\t\tfor (const task of cronTasks) {\n\t\t\tif (!task.schedule) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`CRON task '${task.id}' is missing a resolved schedule.`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst job = cron.schedule(task.schedule, () => {\n\t\t\t\tonTrigger(task);\n\t\t\t});\n\n\t\t\tthis.cronJobs.push(job);\n\t\t}\n\t}\n\n\t/**\n\t * Stops and destroys all registered CRON jobs.\n\t *\n\t * This is used during app shutdown to ensure scheduled tasks no longer fire\n\t * after the runtime begins closing.\n\t */\n\tpublic stop(): void {\n\t\tfor (const job of this.cronJobs.splice(0)) {\n\t\t\tjob.stop();\n\t\t\tif (\"destroy\" in job && typeof job.destroy === \"function\") {\n\t\t\t\tjob.destroy();\n\t\t\t}\n\t\t}\n\t}\n}\n","import { randomUUID } from \"node:crypto\";\nimport { isMainThread, parentPort, workerData } from \"node:worker_threads\";\nimport { logger } from \"@lithia-js/utils\";\nimport type { LithiaOptions } from \"../../config\";\nimport {\n\ttype LithiaContext,\n\trunInLithiaContext,\n} from \"../../context/lithia-context\";\nimport type { Event } from \"../../discovery/events\";\nimport type { Route } from \"../../discovery/routes\";\nimport type { TaskCore } from \"../../discovery/tasks\";\nimport type { RouteMiddleware } from \"../../transport/http/request-pipeline\";\nimport { LithiaServer } from \"../../transport/server\";\nimport type { EventMiddleware } from \"../../transport/socket/event-pipeline\";\nimport type { Environment } from \"../../types\";\nimport { DependencyContainer } from \"./dependency-container\";\nimport { MiddlewareRegistry } from \"./middleware-registry\";\nimport {\n\ttype LithiaServerCleanup,\n\tloadServerBootstrap,\n\tnormalizeServerBootstrapCleanup,\n\tresolveServerBootstrapPath,\n} from \"./server-bootstrap\";\nimport { TaskScheduler } from \"./task-scheduler\";\n\n/**\n * Token used to register or resolve a dependency from the app container.\n */\nexport type InjectionKey<T> = symbol | string | { new (...args: any[]): T };\n\n/**\n * Runtime representation of a Lithia application inside the app worker.\n *\n * `LithiaApp` owns the dependency container, global middleware registries,\n * startup bootstrap, HTTP/socket server, and CRON task scheduling.\n */\nexport class LithiaApp {\n\tprivate readonly _environment: Environment;\n\tprivate readonly _config: LithiaOptions;\n\tprivate readonly _routes: Route[];\n\tprivate readonly _events: Event[];\n\tprivate readonly _tasks: TaskCore[];\n\tprivate readonly _isFirstApp: boolean;\n\n\tprivate readonly dependencies = new DependencyContainer();\n\tprivate readonly middlewares = new MiddlewareRegistry<\n\t\tRouteMiddleware,\n\t\tEventMiddleware\n\t>();\n\tprivate serverBootstrapCleanup: (() => Promise<void>) | null = null;\n\tprivate readonly _server: LithiaServer;\n\tprivate readonly taskScheduler: TaskScheduler;\n\n\t/**\n\t * Creates the app runtime from the worker payload prepared by the Lithia CLI.\n\t *\n\t * The constructor reads routes, events, tasks, config, and environment from\n\t * `workerData`, then initializes the server and task scheduler that run\n\t * inside the worker thread.\n\t *\n\t * @throws {Error} Throws when the runtime is instantiated outside a\n\t * Lithia-managed worker thread.\n\t */\n\tconstructor() {\n\t\tthis.validateExecutionContext();\n\n\t\tthis._config = workerData.config;\n\t\tthis._routes = workerData.routes;\n\t\tthis._events = workerData.events;\n\t\tthis._tasks = workerData.tasks;\n\t\tthis._environment = workerData.environment;\n\t\tthis._isFirstApp = workerData.isFirstApp;\n\n\t\tthis._server = new LithiaServer(this);\n\t\tthis.taskScheduler = new TaskScheduler(this._tasks);\n\t}\n\n\t/**\n\t * Returns the resolved application configuration for this runtime instance.\n\t */\n\tpublic get config(): LithiaOptions {\n\t\treturn this._config;\n\t}\n\n\t/**\n\t * Returns the environment mode assigned to this app worker.\n\t */\n\tpublic get environment(): Environment {\n\t\treturn this._environment;\n\t}\n\n\t/**\n\t * Returns the discovered route manifest loaded into this app worker.\n\t */\n\tpublic get routes(): Route[] {\n\t\treturn this._routes;\n\t}\n\n\t/**\n\t * Returns the discovered socket event manifest loaded into this app worker.\n\t */\n\tpublic get events(): Event[] {\n\t\treturn this._events;\n\t}\n\n\t/**\n\t * Returns the discovered task manifest loaded into this app worker.\n\t *\n\t * Cron-backed tasks follow the conventions described in\n\t * [Async Tasks](https://lithiajs.org/docs/latest/async-tasks).\n\t */\n\tpublic get tasks(): TaskCore[] {\n\t\treturn this._tasks;\n\t}\n\n\t/**\n\t * Returns the global HTTP middlewares registered for every route pipeline.\n\t */\n\tpublic get globalRouteMiddlewares(): RouteMiddleware[] {\n\t\treturn this.middlewares.getRoutes();\n\t}\n\n\t/**\n\t * Returns the global socket middlewares registered for every event pipeline.\n\t */\n\tpublic get globalEventMiddlewares(): EventMiddleware[] {\n\t\treturn this.middlewares.getEvents();\n\t}\n\n\t/**\n\t * Returns whether this worker is the first app instance in the current\n\t * process lifecycle.\n\t *\n\t * Lithia uses this flag to limit one-time logs and similar side effects to a\n\t * single runtime instance.\n\t */\n\tpublic get isFirstApp(): boolean {\n\t\treturn this._isFirstApp;\n\t}\n\n\t/**\n\t * Runs work inside an immutable snapshot of the app dependency container.\n\t *\n\t * Use this for request handling or background work that should only resolve\n\t * dependencies that were already registered during bootstrap.\n\t *\n\t * @param {() => Promise<T>} fn - Async work to execute inside the Lithia\n\t * context.\n\t * @returns {Promise<T>} The value resolved by `fn`.\n\t */\n\tpublic runWithContext<T>(fn: () => Promise<T>): Promise<T> {\n\t\treturn this.runWithContainer(this.dependencies.snapshot(), fn);\n\t}\n\n\t/**\n\t * Runs work inside the mutable app dependency container.\n\t *\n\t * This is primarily used during app bootstrap, when new dependencies may be\n\t * registered with `provide()`.\n\t *\n\t * This method is typically used while running `src/app/server.ts`. See\n\t * [Project Structure](https://lithiajs.org/docs/latest/project-structure)\n\t * and [Deploying](https://lithiajs.org/docs/latest/deploying).\n\t *\n\t * @param {() => Promise<T>} fn - Async work to execute inside the mutable\n\t * Lithia context.\n\t * @returns {Promise<T>} The value resolved by `fn`.\n\t */\n\tpublic runWithMutableContext<T>(fn: () => Promise<T>): Promise<T> {\n\t\treturn this.runWithContainer(this.dependencies.mutable(), fn);\n\t}\n\n\t/**\n\t * Runs work inside a Lithia context backed by the provided dependency\n\t * container.\n\t *\n\t * @param {Map<any, any>} container - Dependency container exposed to the\n\t * current context.\n\t * @param {() => Promise<T>} fn - Async work to execute inside the context.\n\t * @returns {Promise<T>} The value resolved by `fn`.\n\t */\n\tprivate runWithContainer<T>(\n\t\tcontainer: Map<any, any>,\n\t\tfn: () => Promise<T>,\n\t): Promise<T> {\n\t\tconst context: LithiaContext = {\n\t\t\tcontainer,\n\t\t\tconfig: this.config,\n\t\t};\n\n\t\treturn runInLithiaContext(context, fn);\n\t}\n\n\t/**\n\t * Registers a dependency in the app container.\n\t *\n\t * Dependencies registered here become available through the Lithia context\n\t * for routes, events, tasks, and startup hooks.\n\t *\n\t * @param {InjectionKey<T>} key - Token used to store and resolve the\n\t * dependency.\n\t * @param {T} value - Dependency instance associated with `key`.\n\t */\n\tpublic provide<T>(key: InjectionKey<T>, value: T): void {\n\t\tthis.dependencies.set(key, value);\n\t}\n\n\t/**\n\t * Registers a global middleware for routes or events.\n\t *\n\t * Route middlewares run for every HTTP route. Event middlewares run for\n\t * every socket event.\n\t *\n\t * @param {\"route\" | \"event\"} context - Middleware pipeline that should\n\t * receive the registration.\n\t * @param {K extends \"route\" ? RouteMiddleware : EventMiddleware} middleware\n\t * - Middleware implementation to append to the selected global pipeline.\n\t */\n\tpublic use<K extends \"route\" | \"event\">(\n\t\tcontext: K,\n\t\tmiddleware: K extends \"route\" ? RouteMiddleware : EventMiddleware,\n\t): void {\n\t\tthis.middlewares.use(context, middleware);\n\t}\n\n\t/**\n\t * Starts the app runtime.\n\t *\n\t * The startup sequence is:\n\t * 1. run optional `app/server.ts`\n\t * 2. start the HTTP/socket server\n\t * 3. register CRON-backed tasks\n\t * 4. announce readiness\n\t *\n\t * `app/server.ts` participates in the startup lifecycle described in\n\t * [Deploying](https://lithiajs.org/docs/latest/deploying) and\n\t * [Project Structure](https://lithiajs.org/docs/latest/project-structure).\n\t *\n\t * @returns {Promise<void>} Resolves after the server is listening and cron\n\t * tasks have been registered.\n\t * @throws {unknown} Rethrows any startup failure from bootstrap loading,\n\t * server startup, or task registration.\n\t */\n\tpublic async start(): Promise<void> {\n\t\tthis.executeOnce(() => logger.info(\"Starting Lithia server...\"));\n\n\t\ttry {\n\t\t\tawait this.runServerBootstrapIfPresent();\n\t\t\tawait this._server.listen();\n\t\t\tthis.taskScheduler.start((task) => {\n\t\t\t\tparentPort?.postMessage({\n\t\t\t\t\ttype: \"invoke\",\n\t\t\t\t\ttaskId: task.id,\n\t\t\t\t\tasync: true,\n\t\t\t\t\texecutionId: randomUUID(),\n\t\t\t\t\targs: [],\n\t\t\t\t\tsource: \"CRON\",\n\t\t\t\t\tattempt: 0,\n\t\t\t\t});\n\t\t\t});\n\t\t\tthis.executeOnce(() =>\n\t\t\t\tlogger.ready(`Lithia is ready on port ${this.config.http.port}`),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tthis.executeOnce(() => logger.error(\"Failed to start Lithia server.\"));\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Stops the app runtime and runs all registered cleanup hooks.\n\t *\n\t * The shutdown sequence runs the optional cleanup returned by\n\t * `src/app/server.ts`, stops cron scheduling, and then closes the server.\n\t *\n\t * @returns {Promise<void>} Resolves after cleanup hooks and server shutdown\n\t * finish.\n\t */\n\tpublic async stop(): Promise<void> {\n\t\tawait this.runServerBootstrapCleanup();\n\t\tthis.taskScheduler.stop();\n\t\tawait this._server.close();\n\t}\n\n\t/**\n\t * Loads and runs `app/server.ts` when the file exists in the build output.\n\t *\n\t * If the bootstrap exports a cleanup callback, the callback is normalized\n\t * and stored for `stop()`.\n\t *\n\t * @returns {Promise<void>} Resolves after the bootstrap has finished.\n\t */\n\tprivate async runServerBootstrapIfPresent(): Promise<void> {\n\t\tconst filePath = await resolveServerBootstrapPath(this.config.outDir);\n\t\tif (!filePath) return;\n\n\t\tconst bootstrap = await loadServerBootstrap(filePath);\n\t\tconst cleanup = await this.runWithMutableContext(() => bootstrap());\n\t\tthis.serverBootstrapCleanup = normalizeServerBootstrapCleanup(\n\t\t\tcleanup as LithiaServerCleanup,\n\t\t);\n\t}\n\n\t/**\n\t * Runs the cleanup returned by `app/server.ts`, if one was registered.\n\t *\n\t * Cleanup errors are logged and do not prevent the runtime from continuing\n\t * its shutdown flow.\n\t *\n\t * @returns {Promise<void>} Resolves after the cleanup callback completes or\n\t * is skipped.\n\t */\n\tprivate async runServerBootstrapCleanup(): Promise<void> {\n\t\tif (!this.serverBootstrapCleanup) return;\n\n\t\ttry {\n\t\t\tawait this.serverBootstrapCleanup();\n\t\t} catch (error) {\n\t\t\tlogger.error(\"Failed to clean up app/server.ts bootstrap.\", error);\n\t\t} finally {\n\t\t\tthis.serverBootstrapCleanup = null;\n\t\t}\n\t}\n\n\t/**\n\t * Restricts one-time logs to the first app instance for a given lifecycle.\n\t *\n\t * This prevents duplicated startup and failure logs when multiple app\n\t * workers share the same lifecycle but only one instance should announce\n\t * framework-level state changes.\n\t *\n\t * @param {() => void} fn - Side effect to run only for the first app\n\t * instance.\n\t */\n\tprivate executeOnce(fn: () => void): void {\n\t\tif (this.isFirstApp) {\n\t\t\tfn();\n\t\t}\n\t}\n\n\t/**\n\t * Ensures the app runtime only executes inside a Lithia-managed worker.\n\t *\n\t * The runtime depends on `workerData` prepared by the Lithia CLI and on the\n\t * worker messaging model used by the app worker entrypoint. Direct\n\t * instantiation on the main thread or inside an unrelated worker is not\n\t * supported.\n\t *\n\t * @throws {Error} Throws when the runtime runs on the main thread or inside\n\t * a worker not created by the Lithia CLI.\n\t */\n\tprivate validateExecutionContext(): void {\n\t\tif (isMainThread) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Execution Error: LithiaApp cannot be instantiated on the main thread. It must run within a Worker Thread.\",\n\t\t\t);\n\t\t}\n\n\t\tif (workerData?.managedBy !== \"lithia\") {\n\t\t\tthrow new Error(\n\t\t\t\t\"Compatibility Error: LithiaApp must be managed by the Lithia CLI. Independent execution is not supported.\",\n\t\t\t);\n\t\t}\n\t}\n}\n","import { parentPort } from \"node:worker_threads\";\nimport { logger } from \"@lithia-js/utils\";\nimport { LithiaError } from \"../../errors/base\";\nimport { LithiaApp } from \"../app/app-runtime\";\n\nlet isInitialized = false;\n\n/**\n * Boots the app worker exactly once and reports readiness or startup failure\n * back to the host.\n *\n * The worker creates a fresh `LithiaApp`, starts it, and posts either a\n * `\"ready\"` message or a serialized startup failure to the parent thread.\n * After successful startup it also installs process signal handlers so worker\n * shutdown attempts to stop the app cleanly before exiting.\n *\n * @returns {Promise<void>} Resolves after startup succeeds or a Lithia startup\n * failure has been reported to the host.\n * @throws {unknown} Re-throws non-Lithia startup failures after notifying the\n * host so the worker can crash loudly.\n */\nasync function bootstrap(): Promise<void> {\n\tif (isInitialized) return;\n\tisInitialized = true;\n\n\tlogger.debug(\"Initializing Lithia background worker...\");\n\n\tconst app = new LithiaApp();\n\n\ttry {\n\t\tawait app.start();\n\t\tparentPort?.postMessage({ type: \"ready\" });\n\t} catch (error: any) {\n\t\ttry {\n\t\t\tawait app.stop();\n\t\t} catch (stopError) {\n\t\t\tlogger.error(\n\t\t\t\t\"Failed to stop Lithia app cleanly after startup failure:\",\n\t\t\t\tstopError,\n\t\t\t);\n\t\t}\n\n\t\tconst errorPayload =\n\t\t\terror instanceof LithiaError\n\t\t\t\t? {\n\t\t\t\t\t\tname: error.name,\n\t\t\t\t\t\tmessage: error.message,\n\t\t\t\t\t\tcontext: (error as any).context,\n\t\t\t\t\t\tstack: error.stack,\n\t\t\t\t\t}\n\t\t\t\t: {\n\t\t\t\t\t\tname: error?.name ?? \"UnknownWorkerError\",\n\t\t\t\t\t\tmessage: String(error?.message ?? error),\n\t\t\t\t\t\tstack: error?.stack,\n\t\t\t\t\t};\n\n\t\tparentPort?.postMessage({ type: \"error\", error: errorPayload });\n\n\t\tif (!(error instanceof LithiaError)) {\n\t\t\tthrow error;\n\t\t}\n\t\treturn;\n\t}\n\n\t/**\n\t * Handles process-level shutdown for the app worker.\n\t *\n\t * @returns {Promise<void>} Resolves only long enough to await `app.stop()`\n\t * before forcing process exit.\n\t */\n\tconst shutdown = async (): Promise<void> => {\n\t\ttry {\n\t\t\tawait app.stop();\n\t\t} catch {\n\t\t} finally {\n\t\t\tprocess.exit(0);\n\t\t}\n\t};\n\n\tprocess.once(\"SIGINT\", shutdown);\n\tprocess.once(\"SIGTERM\", shutdown);\n}\n\nbootstrap().catch((error) => {\n\tlogger.error(\"Fatal exception in Lithia worker:\", error);\n\tprocess.exit(1);\n});\n"]}
@@ -0,0 +1,45 @@
1
+ import { T as TaskCore } from '../tasks-X-3clDS8.js';
2
+
3
+ /**
4
+ * Ensures the task worker only runs inside a Lithia-managed worker context.
5
+ *
6
+ * @throws {Error} Thrown when the module is executed on the main thread or in a
7
+ * worker that was not created by Lithia's host runtime.
8
+ */
9
+ declare function validateExecutionContext(): void;
10
+ /**
11
+ * Executes a dedicated one-shot task worker.
12
+ *
13
+ * Dedicated workers read the task manifest entry and serialized arguments from
14
+ * `workerData`, run exactly one invocation, post the terminal result back to
15
+ * the host, and then schedule process exit.
16
+ *
17
+ * @returns {Promise<void>} Resolves after the result has been posted to the
18
+ * parent port.
19
+ */
20
+ declare function run(): Promise<void>;
21
+ /**
22
+ * Executes a single task invocation inside a warm pooled worker.
23
+ *
24
+ * Warm pooled workers stay alive across invocations, so this helper only
25
+ * handles one invocation and reports its outcome back to the host without
26
+ * exiting the process.
27
+ *
28
+ * @param {TaskCore} task - Task manifest entry describing the module to load.
29
+ * @param {unknown[]} args - Serialized arguments forwarded to the task.
30
+ * @param {string} [executionId] - Correlation identifier for awaited tasks.
31
+ * @returns {Promise<void>} Resolves after the result payload has been posted.
32
+ * @throws {unknown} Re-throws the original task error after posting the
33
+ * serialized error payload so the pooled loop can decide whether to continue.
34
+ */
35
+ declare function executeTask(task: TaskCore, args: unknown[], executionId?: string): Promise<void>;
36
+ /**
37
+ * Starts the pooled worker loop and waits for invocation messages from the
38
+ * host.
39
+ *
40
+ * The loop keeps the worker alive indefinitely and delegates each `"invoke"`
41
+ * message to `executeTask()`.
42
+ */
43
+ declare function runPooled(): void;
44
+
45
+ export { executeTask, run, runPooled, validateExecutionContext };
@@ -0,0 +1,146 @@
1
+ import { workerData, parentPort, isMainThread } from 'worker_threads';
2
+ import { logger } from '@lithia-js/utils';
3
+ import { access, constants } from 'fs/promises';
4
+ import { pathToFileURL } from 'url';
5
+ import { isAsyncFunction } from 'util/types';
6
+
7
+ // src/runtime/workers/task-worker.ts
8
+
9
+ // src/errors/base.ts
10
+ var LithiaError = class extends Error {
11
+ isLithiaError = true;
12
+ constructor(message) {
13
+ super(message);
14
+ this.name = this.constructor.name;
15
+ Object.setPrototypeOf(this, new.target.prototype);
16
+ }
17
+ };
18
+
19
+ // src/errors/internal/loader.ts
20
+ var NoDefaultExportError = class extends LithiaError {
21
+ constructor(filePath) {
22
+ super(`Module at '${filePath}' is missing a default export.`);
23
+ }
24
+ };
25
+ var NoAsyncDefaultExportError = class extends LithiaError {
26
+ constructor(filePath) {
27
+ super(`Default export at '${filePath}' must be an async function.`);
28
+ }
29
+ };
30
+
31
+ // src/shared/module-loader.ts
32
+ async function loadModule(filePath) {
33
+ const exists = await access(filePath, constants.F_OK).then(() => true).catch(() => false);
34
+ if (!exists) {
35
+ throw new LithiaError(
36
+ `The module at '${filePath}' could not be found or is not accessible.`
37
+ );
38
+ }
39
+ let mod;
40
+ try {
41
+ mod = await import(pathToFileURL(filePath).href);
42
+ } catch (err) {
43
+ throw new LithiaError(
44
+ `Failed to import module at '${filePath}': ${err.message}`
45
+ );
46
+ }
47
+ if (!mod || !mod.default) {
48
+ throw new NoDefaultExportError(filePath);
49
+ }
50
+ const isFunction = typeof mod.default === "function";
51
+ const isAsync = isAsyncFunction(mod.default);
52
+ if (!isFunction || !isAsync) {
53
+ throw new NoAsyncDefaultExportError(filePath);
54
+ }
55
+ return mod;
56
+ }
57
+
58
+ // src/runtime/workers/task-worker.ts
59
+ function validateExecutionContext() {
60
+ if (isMainThread) {
61
+ throw new Error(
62
+ "Execution Error: TaskWorker cannot run on the main thread."
63
+ );
64
+ }
65
+ if (workerData?.managedBy !== "lithia") {
66
+ throw new Error(
67
+ "Compatibility Error: TaskWorker must be managed by the HostSupervisor."
68
+ );
69
+ }
70
+ }
71
+ function serializeTaskError(error) {
72
+ if (error instanceof Error) {
73
+ return {
74
+ name: error.name,
75
+ message: error.message,
76
+ stack: error.stack,
77
+ cause: "cause" in error ? error.cause : void 0
78
+ };
79
+ }
80
+ return {
81
+ name: "UnknownTaskError",
82
+ message: String(error)
83
+ };
84
+ }
85
+ async function run() {
86
+ const { task, args } = workerData;
87
+ validateExecutionContext();
88
+ logger.debug(`[task:${task.id}] Starting execution...`);
89
+ try {
90
+ const mod = await loadModule(task.filePath);
91
+ const result = await mod.default(...args);
92
+ parentPort?.postMessage({
93
+ type: "success",
94
+ result
95
+ });
96
+ logger.debug(`[task:${task.id}] Execution completed successfully.`);
97
+ setImmediate(() => process.exit(0));
98
+ } catch (error) {
99
+ parentPort?.postMessage({
100
+ type: "error",
101
+ error: serializeTaskError(error)
102
+ });
103
+ setImmediate(() => process.exit(1));
104
+ }
105
+ }
106
+ async function executeTask(task, args, executionId) {
107
+ logger.debug(`[task:${task.id}] Starting execution...`);
108
+ try {
109
+ const mod = await loadModule(task.filePath);
110
+ const result = await mod.default(...args);
111
+ parentPort?.postMessage({
112
+ type: "success",
113
+ executionId,
114
+ result
115
+ });
116
+ logger.debug(`[task:${task.id}] Execution completed successfully.`);
117
+ } catch (error) {
118
+ parentPort?.postMessage({
119
+ type: "error",
120
+ executionId,
121
+ error: serializeTaskError(error)
122
+ });
123
+ throw error;
124
+ }
125
+ }
126
+ function runPooled() {
127
+ validateExecutionContext();
128
+ parentPort?.on("message", async (message) => {
129
+ if (message.type !== "invoke") return;
130
+ try {
131
+ await executeTask(message.task, message.args, message.executionId);
132
+ } catch {
133
+ }
134
+ });
135
+ }
136
+ if (!process.env.LITHIA_TEST_MODE) {
137
+ if (workerData?.pooled) {
138
+ runPooled();
139
+ } else {
140
+ await run();
141
+ }
142
+ }
143
+
144
+ export { executeTask, run, runPooled, validateExecutionContext };
145
+ //# sourceMappingURL=task-worker.mjs.map
146
+ //# sourceMappingURL=task-worker.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/errors/base.ts","../../src/errors/internal/loader.ts","../../src/shared/module-loader.ts","../../src/runtime/workers/task-worker.ts"],"names":[],"mappings":";;;;;;;;;AAGO,IAAM,WAAA,GAAN,cAA0B,KAAA,CAAM;AAAA,EACtB,aAAA,GAAgB,IAAA;AAAA,EAChC,YAAY,OAAA,EAAkB;AAC7B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,KAAK,WAAA,CAAY,IAAA;AAC7B,IAAA,MAA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A,MAAM,KAAA;AAAA,EACP;AACD;AASA,SAAS,SAAA,GAAY;AACpB,EAAA,wBAAA,EAAyB;AAEzB,EAAA,UAAA,EAAY,EAAA,CAAG,SAAA,EAAW,OAAO,OAAA,KAAyC;AACzE,IAAA,IAAI,OAAA,CAAQ,SAAS,QAAA,EAAU;AAE/B,IAAA,IAAI;AACH,MAAA,MAAM,YAAY,OAAA,CAAQ,IAAA,EAAM,OAAA,CAAQ,IAAA,EAAM,QAAQ,WAAW,CAAA;AAAA,IAClE,CAAA,CAAA,MAAQ;AAAA,IAER;AAAA,EACD,CAAC,CAAA;AACF;AAEA,IAAI,CAAC,OAAA,CAAQ,GAAA,CAAI,gBAAA,EAAkB;AAClC,EAAA,IAAI,YAAY,MAAA,EAAQ;AACvB,IAAA,SAAA,EAAU;AAAA,EACX,CAAA,MAAO;AACN,IAAA,MAAM,GAAA,EAAI;AAAA,EACX;AACD","file":"task-worker.mjs","sourcesContent":["/**\n * Base error type for Lithia-specific failures.\n */\nexport class LithiaError extends Error {\n\tpublic readonly isLithiaError = true;\n\tconstructor(message?: string) {\n\t\tsuper(message);\n\t\tthis.name = this.constructor.name;\n\t\tObject.setPrototypeOf(this, new.target.prototype); // Fixes inheritance in older environments\n\t}\n}\n\n/**\n * HTTP-oriented application error with a status code and optional details.\n *\n * Throw this from routes when you want Lithia to return a structured client\n * error response.\n */\nexport class LithiaClientError extends LithiaError {\n\tpublic readonly timestamp = new Date();\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic readonly statusCode: number,\n\t\tpublic readonly details?: any,\n\t) {\n\t\tsuper(message);\n\t}\n}\n\n/**\n * Event-oriented error that captures the event name and optional details.\n *\n * Used when socket event handling needs to surface a structured failure.\n */\nexport class LithiaEventError extends LithiaError {\n\tpublic readonly timestamp = new Date();\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic readonly eventName: string,\n\t\tpublic readonly details?: any,\n\t) {\n\t\tsuper(message);\n\t}\n}\n","import { LithiaError } from \"../base\";\n\n/** Raised when manifest versions do not match during startup. */\nexport class ManifestVersionMismatchError extends LithiaError {\n\tconstructor(expectedVersion: string, foundVersion: string) {\n\t\tsuper(\n\t\t\t`Manifest version mismatch: expected '${expectedVersion}', but found '${foundVersion}'. Rebuild required.`,\n\t\t);\n\t}\n}\n\n/** Raised when a required module is missing a default export. */\nexport class NoDefaultExportError extends LithiaError {\n\tconstructor(filePath: string) {\n\t\tsuper(`Module at '${filePath}' is missing a default export.`);\n\t}\n}\n\n/** Raised when a default export exists but is not an async function. */\nexport class NoAsyncDefaultExportError extends LithiaError {\n\tconstructor(filePath: string) {\n\t\tsuper(`Default export at '${filePath}' must be an async function.`);\n\t}\n}\n","import { access, constants } from \"node:fs/promises\";\nimport { pathToFileURL } from \"node:url\";\nimport { isAsyncFunction } from \"node:util/types\";\nimport { LithiaError } from \"../errors/base\";\nimport {\n\tNoAsyncDefaultExportError,\n\tNoDefaultExportError,\n} from \"../errors/internal/index\";\n\n/**\n * Runtime contract for modules loaded by Lithia discovery/runtime helpers.\n *\n * Lithia expects a default async function export and permits additional named\n * exports for metadata such as middleware or route information.\n */\nexport type LithiaModule = {\n\tdefault: (...args: any[]) => Promise<any>;\n\t[key: string]: unknown;\n};\n\n/**\n * Loads a compiled module and validates that it exposes an async default\n * export.\n *\n * The helper checks filesystem accessibility first, imports the compiled module\n * through a file URL, and then enforces Lithia's runtime contract that the\n * default export must exist and must be an async function.\n *\n * @param {string} filePath - Absolute path to the compiled module file.\n * @returns {Promise<T>} Imported module after runtime contract validation.\n * @throws {LithiaError} Thrown when the file does not exist, cannot be\n * imported, or violates Lithia's default-export expectations.\n */\nexport async function loadModule<T extends LithiaModule>(\n\tfilePath: string,\n): Promise<T> {\n\tconst exists = await access(filePath, constants.F_OK)\n\t\t.then(() => true)\n\t\t.catch(() => false);\n\n\tif (!exists) {\n\t\tthrow new LithiaError(\n\t\t\t`The module at '${filePath}' could not be found or is not accessible.`,\n\t\t);\n\t}\n\n\tlet mod: T;\n\ttry {\n\t\tmod = await import(pathToFileURL(filePath).href);\n\t} catch (err: any) {\n\t\tthrow new LithiaError(\n\t\t\t`Failed to import module at '${filePath}': ${err.message}`,\n\t\t);\n\t}\n\n\tif (!mod || !mod.default) {\n\t\tthrow new NoDefaultExportError(filePath);\n\t}\n\n\tconst isFunction = typeof mod.default === \"function\";\n\tconst isAsync = isAsyncFunction(mod.default);\n\n\tif (!isFunction || !isAsync) {\n\t\tthrow new NoAsyncDefaultExportError(filePath);\n\t}\n\n\treturn mod;\n}\n","import { isMainThread, parentPort, workerData } from \"node:worker_threads\";\nimport { logger } from \"@lithia-js/utils\";\nimport type { TaskCore } from \"../../discovery/tasks\";\nimport { loadModule } from \"../../shared/module-loader\";\nimport type { TaskErrorPayload } from \"../host/protocol\";\n\n/**\n * Messages emitted by a task worker back to the host.\n *\n * Dedicated workers omit `executionId` because they handle exactly one\n * invocation. Warm pooled workers include it so the host can correlate the\n * response with the currently awaited execution.\n */\ntype TaskWorkerMessage =\n\t| {\n\t\t\ttype: \"success\";\n\t\t\texecutionId?: string;\n\t\t\tresult: unknown;\n\t }\n\t| {\n\t\t\ttype: \"error\";\n\t\t\texecutionId?: string;\n\t\t\terror: TaskErrorPayload;\n\t };\n\n/**\n * Invocation payload sent to a pooled warm task worker.\n *\n * The host posts this message into a long-lived pooled worker whenever an\n * awaited task needs execution.\n */\ntype PooledTaskInvocationMessage = {\n\ttype: \"invoke\";\n\texecutionId: string;\n\ttask: TaskCore;\n\targs: unknown[];\n};\n\n/**\n * Ensures the task worker only runs inside a Lithia-managed worker context.\n *\n * @throws {Error} Thrown when the module is executed on the main thread or in a\n * worker that was not created by Lithia's host runtime.\n */\nfunction validateExecutionContext(): void {\n\tif (isMainThread) {\n\t\tthrow new Error(\n\t\t\t\"Execution Error: TaskWorker cannot run on the main thread.\",\n\t\t);\n\t}\n\n\tif (workerData?.managedBy !== \"lithia\") {\n\t\tthrow new Error(\n\t\t\t\"Compatibility Error: TaskWorker must be managed by the HostSupervisor.\",\n\t\t);\n\t}\n}\n\n/**\n * Converts an unknown thrown value into a serializable task error payload.\n *\n * @param {unknown} error - Original thrown value.\n * @returns {TaskErrorPayload} Serializable error payload safe to send across\n * the worker boundary.\n */\nfunction serializeTaskError(error: unknown): TaskErrorPayload {\n\tif (error instanceof Error) {\n\t\treturn {\n\t\t\tname: error.name,\n\t\t\tmessage: error.message,\n\t\t\tstack: error.stack,\n\t\t\tcause:\n\t\t\t\t\"cause\" in error\n\t\t\t\t\t? (error as Error & { cause?: unknown }).cause\n\t\t\t\t\t: undefined,\n\t\t};\n\t}\n\n\treturn {\n\t\tname: \"UnknownTaskError\",\n\t\tmessage: String(error),\n\t};\n}\n\n/**\n * Executes a dedicated one-shot task worker.\n *\n * Dedicated workers read the task manifest entry and serialized arguments from\n * `workerData`, run exactly one invocation, post the terminal result back to\n * the host, and then schedule process exit.\n *\n * @returns {Promise<void>} Resolves after the result has been posted to the\n * parent port.\n */\nasync function run() {\n\tconst { task, args } = workerData;\n\n\tvalidateExecutionContext();\n\n\tlogger.debug(`[task:${task.id}] Starting execution...`);\n\n\ttry {\n\t\tconst mod = await loadModule(task.filePath);\n\t\tconst result = await mod.default(...args);\n\n\t\tparentPort?.postMessage({\n\t\t\ttype: \"success\",\n\t\t\tresult,\n\t\t} satisfies TaskWorkerMessage);\n\n\t\tlogger.debug(`[task:${task.id}] Execution completed successfully.`);\n\n\t\tsetImmediate(() => process.exit(0));\n\t} catch (error) {\n\t\tparentPort?.postMessage({\n\t\t\ttype: \"error\",\n\t\t\terror: serializeTaskError(error),\n\t\t} satisfies TaskWorkerMessage);\n\n\t\tsetImmediate(() => process.exit(1));\n\t}\n}\n\n/**\n * Executes a single task invocation inside a warm pooled worker.\n *\n * Warm pooled workers stay alive across invocations, so this helper only\n * handles one invocation and reports its outcome back to the host without\n * exiting the process.\n *\n * @param {TaskCore} task - Task manifest entry describing the module to load.\n * @param {unknown[]} args - Serialized arguments forwarded to the task.\n * @param {string} [executionId] - Correlation identifier for awaited tasks.\n * @returns {Promise<void>} Resolves after the result payload has been posted.\n * @throws {unknown} Re-throws the original task error after posting the\n * serialized error payload so the pooled loop can decide whether to continue.\n */\nasync function executeTask(\n\ttask: TaskCore,\n\targs: unknown[],\n\texecutionId?: string,\n): Promise<void> {\n\tlogger.debug(`[task:${task.id}] Starting execution...`);\n\n\ttry {\n\t\tconst mod = await loadModule(task.filePath);\n\t\tconst result = await mod.default(...args);\n\n\t\tparentPort?.postMessage({\n\t\t\ttype: \"success\",\n\t\t\texecutionId,\n\t\t\tresult,\n\t\t} satisfies TaskWorkerMessage);\n\n\t\tlogger.debug(`[task:${task.id}] Execution completed successfully.`);\n\t} catch (error) {\n\t\tparentPort?.postMessage({\n\t\t\ttype: \"error\",\n\t\t\texecutionId,\n\t\t\terror: serializeTaskError(error),\n\t\t} satisfies TaskWorkerMessage);\n\n\t\tthrow error;\n\t}\n}\n\n/**\n * Starts the pooled worker loop and waits for invocation messages from the\n * host.\n *\n * The loop keeps the worker alive indefinitely and delegates each `\"invoke\"`\n * message to `executeTask()`.\n */\nfunction runPooled() {\n\tvalidateExecutionContext();\n\n\tparentPort?.on(\"message\", async (message: PooledTaskInvocationMessage) => {\n\t\tif (message.type !== \"invoke\") return;\n\n\t\ttry {\n\t\t\tawait executeTask(message.task, message.args, message.executionId);\n\t\t} catch {\n\t\t\t// Error payload is already posted back to the host.\n\t\t}\n\t});\n}\n\nif (!process.env.LITHIA_TEST_MODE) {\n\tif (workerData?.pooled) {\n\t\trunPooled();\n\t} else {\n\t\tawait run();\n\t}\n}\n\nexport { executeTask, run, runPooled, validateExecutionContext };\n"]}