@forinda/kickjs 9.1.0 → 9.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/dist/{adapter-DhjoIYVI.d.mts → adapter-DjfRMob8.d.mts} +3 -13
  2. package/dist/{adapter-DhjoIYVI.d.mts.map → adapter-DjfRMob8.d.mts.map} +1 -1
  3. package/dist/application-BSJpaiSY.mjs +12 -0
  4. package/dist/{application-nDj-76EX.mjs.map → application-BSJpaiSY.mjs.map} +1 -1
  5. package/dist/{application-DqD58rhF.d.mts → application-CGxZCYl1.d.mts} +8 -8
  6. package/dist/{application-DqD58rhF.d.mts.map → application-CGxZCYl1.d.mts.map} +1 -1
  7. package/dist/{bootstrap-BqcT1h9H.mjs → bootstrap-CbTF6xvv.mjs} +3 -3
  8. package/dist/{bootstrap-BqcT1h9H.mjs.map → bootstrap-CbTF6xvv.mjs.map} +1 -1
  9. package/dist/{client-ip-DMKc-Trg.mjs → client-ip-pcINkkPr.mjs} +2 -2
  10. package/dist/{client-ip-DMKc-Trg.mjs.map → client-ip-pcINkkPr.mjs.map} +1 -1
  11. package/dist/config/index.d.mts +1 -1
  12. package/dist/config/index.mjs +2 -2
  13. package/dist/{config-DrgIbebd.mjs → config-DmGiAIuH.mjs} +3 -3
  14. package/dist/{config-DrgIbebd.mjs.map → config-DmGiAIuH.mjs.map} +1 -1
  15. package/dist/{container-ZnfelY_a.mjs → container-CAPN7pBG.mjs} +3 -3
  16. package/dist/{container-ZnfelY_a.mjs.map → container-CAPN7pBG.mjs.map} +1 -1
  17. package/dist/{context-errors-Cgtrrqfs.mjs → context-errors-DYJjhalQ.mjs} +2 -2
  18. package/dist/{context-errors-Cgtrrqfs.mjs.map → context-errors-DYJjhalQ.mjs.map} +1 -1
  19. package/dist/context-gpvcMlG5.mjs +12 -0
  20. package/dist/context-gpvcMlG5.mjs.map +1 -0
  21. package/dist/{contributor-runner-BSpshfPN.mjs → contributor-runner-vk9XlOED.mjs} +3 -3
  22. package/dist/{contributor-runner-BSpshfPN.mjs.map → contributor-runner-vk9XlOED.mjs.map} +1 -1
  23. package/dist/core/adapter.d.mts +1 -1
  24. package/dist/core/adapter.mjs +1 -1
  25. package/dist/core/app-module.mjs +1 -1
  26. package/dist/core/cache.mjs +1 -1
  27. package/dist/core/container.mjs +2 -2
  28. package/dist/core/cron.mjs +2 -2
  29. package/dist/core/decorators.d.mts +1 -1
  30. package/dist/core/decorators.mjs +2 -2
  31. package/dist/core/decorators.mjs.map +1 -1
  32. package/dist/core/errors.mjs +1 -1
  33. package/dist/core/interfaces.mjs +1 -1
  34. package/dist/core/logger.mjs +1 -1
  35. package/dist/core/path.mjs +1 -1
  36. package/dist/core/plugin.d.mts +1 -1
  37. package/dist/core/plugin.mjs +1 -1
  38. package/dist/core/reactivity.mjs +1 -1
  39. package/dist/{core-_WNyghl_.mjs → core-DKrKVLfj.mjs} +3 -3
  40. package/dist/{core-_WNyghl_.mjs.map → core-DKrKVLfj.mjs.map} +1 -1
  41. package/dist/{csrf-COFjRrUz.d.mts → csrf-C73UkRgc.d.mts} +2 -2
  42. package/dist/{csrf-COFjRrUz.d.mts.map → csrf-C73UkRgc.d.mts.map} +1 -1
  43. package/dist/{csrf-BcxqzCZW.mjs → csrf-CxJItZVa.mjs} +3 -3
  44. package/dist/{csrf-BcxqzCZW.mjs.map → csrf-CxJItZVa.mjs.map} +1 -1
  45. package/dist/{decorate-BBwu7--P.mjs → decorate-DfH1NIqV.mjs} +1 -1
  46. package/dist/{decorators-DOcWsXci.d.mts → decorators-BxNSz9Qt.d.mts} +4 -4
  47. package/dist/{decorators-DOcWsXci.d.mts.map → decorators-BxNSz9Qt.d.mts.map} +1 -1
  48. package/dist/{define-adapter-CajLeMzM.mjs → define-adapter-C6lFhCL-.mjs} +2 -2
  49. package/dist/{define-adapter-CajLeMzM.mjs.map → define-adapter-C6lFhCL-.mjs.map} +1 -1
  50. package/dist/{disposables-DIXt8ze-.mjs → disposables-NlW6Mibk.mjs} +2 -2
  51. package/dist/{disposables-DIXt8ze-.mjs.map → disposables-NlW6Mibk.mjs.map} +1 -1
  52. package/dist/{env-DtJ-6gyL.mjs → env-__fzPsHD.mjs} +3 -3
  53. package/dist/{env-DtJ-6gyL.mjs.map → env-__fzPsHD.mjs.map} +1 -1
  54. package/dist/{error-handler-DiueQHes.d.mts → error-handler-itG65lj0.d.mts} +2 -2
  55. package/dist/{error-handler-DiueQHes.d.mts.map → error-handler-itG65lj0.d.mts.map} +1 -1
  56. package/dist/handler-DnZbcleS.mjs +13 -0
  57. package/dist/handler-DnZbcleS.mjs.map +1 -0
  58. package/dist/http/application.d.mts +1 -1
  59. package/dist/http/application.mjs +2 -2
  60. package/dist/http/bootstrap.d.mts +1 -1
  61. package/dist/http/bootstrap.mjs +2 -2
  62. package/dist/http/context.d.mts +1 -1
  63. package/dist/http/context.mjs +2 -2
  64. package/dist/http/middleware/cors.mjs +1 -1
  65. package/dist/http/middleware/csrf.d.mts +1 -1
  66. package/dist/http/middleware/csrf.mjs +2 -2
  67. package/dist/http/middleware/error-handler.d.mts +1 -1
  68. package/dist/http/middleware/error-handler.mjs +2 -2
  69. package/dist/http/middleware/helmet.mjs +1 -1
  70. package/dist/http/middleware/rate-limit.mjs +2 -2
  71. package/dist/http/middleware/request-id.mjs +1 -1
  72. package/dist/http/middleware/request-logger.mjs +2 -2
  73. package/dist/http/middleware/session.mjs +2 -2
  74. package/dist/http/middleware/spa.d.mts +1 -1
  75. package/dist/http/middleware/spa.mjs +2 -2
  76. package/dist/http/middleware/upload.d.mts +1 -1
  77. package/dist/http/middleware/upload.mjs +2 -2
  78. package/dist/http/middleware/validate.mjs +1 -1
  79. package/dist/http/middleware/views.d.mts +1 -1
  80. package/dist/http/middleware/views.mjs +2 -2
  81. package/dist/http/query/index.mjs +2 -2
  82. package/dist/http/router-builder.d.mts +1 -1
  83. package/dist/http/router-builder.mjs +2 -2
  84. package/dist/http/runtimes/fastify.d.mts +3 -1
  85. package/dist/http/runtimes/fastify.d.mts.map +1 -1
  86. package/dist/http/runtimes/fastify.mjs +2 -2
  87. package/dist/http/runtimes/fastify.mjs.map +1 -1
  88. package/dist/http/runtimes/h3-web.d.mts +1 -1
  89. package/dist/http/runtimes/h3-web.mjs +2 -2
  90. package/dist/http/runtimes/h3.d.mts +1 -1
  91. package/dist/http/runtimes/h3.mjs +2 -2
  92. package/dist/http/runtimes/h3.mjs.map +1 -1
  93. package/dist/{index-CDn-p3tq.d.mts → index-CNHSbZTE.d.mts} +4 -4
  94. package/dist/{index-CDn-p3tq.d.mts.map → index-CNHSbZTE.d.mts.map} +1 -1
  95. package/dist/index.d.mts +9 -9
  96. package/dist/index.mjs +2 -2
  97. package/dist/index.mjs.map +1 -1
  98. package/dist/{jobs-dx-MTUUb.mjs → jobs-BmpeFvi0.mjs} +3 -3
  99. package/dist/{jobs-dx-MTUUb.mjs.map → jobs-BmpeFvi0.mjs.map} +1 -1
  100. package/dist/{kv-stores-CetFF9N_.d.mts → kv-stores-BZTe23Tw.d.mts} +3 -3
  101. package/dist/{kv-stores-CetFF9N_.d.mts.map → kv-stores-BZTe23Tw.d.mts.map} +1 -1
  102. package/dist/{kv-stores-Ba5_rcz-.mjs → kv-stores-DJwxntyw.mjs} +3 -3
  103. package/dist/{kv-stores-Ba5_rcz-.mjs.map → kv-stores-DJwxntyw.mjs.map} +1 -1
  104. package/dist/{metadata-CW4I35nN.mjs → metadata-CzzRUnAx.mjs} +2 -2
  105. package/dist/{metadata-CW4I35nN.mjs.map → metadata-CzzRUnAx.mjs.map} +1 -1
  106. package/dist/{module-registry-kqozOSo0.mjs → module-registry-BnmRNy-3.mjs} +2 -2
  107. package/dist/{module-registry-kqozOSo0.mjs.map → module-registry-BnmRNy-3.mjs.map} +1 -1
  108. package/dist/{observers-CC3sO1BM.mjs → observers-COlQfinD.mjs} +2 -2
  109. package/dist/{observers-CC3sO1BM.mjs.map → observers-COlQfinD.mjs.map} +1 -1
  110. package/dist/{query-DPlkWOw6.mjs → query-B5DTq_4W.mjs} +2 -2
  111. package/dist/{query-DPlkWOw6.mjs.map → query-B5DTq_4W.mjs.map} +1 -1
  112. package/dist/reply-CbTYIj_e.mjs +12 -0
  113. package/dist/reply-CbTYIj_e.mjs.map +1 -0
  114. package/dist/{respond-DjxNwGnN.mjs → respond-wbMSqHYo.mjs} +2 -2
  115. package/dist/{respond-DjxNwGnN.mjs.map → respond-wbMSqHYo.mjs.map} +1 -1
  116. package/dist/{route-flag-sIYXay3q.mjs → route-flag-Bb7n9Mnp.mjs} +3 -3
  117. package/dist/{route-flag-sIYXay3q.mjs.map → route-flag-Bb7n9Mnp.mjs.map} +1 -1
  118. package/dist/{route-policy-B6_toGJW.mjs → route-policy-C_Wsc-b1.mjs} +2 -2
  119. package/dist/{route-policy-B6_toGJW.mjs.map → route-policy-C_Wsc-b1.mjs.map} +1 -1
  120. package/dist/{router-builder-BSBSYgYW.d.mts → router-builder-CDkW88KQ.d.mts} +2 -2
  121. package/dist/{router-builder-BSBSYgYW.d.mts.map → router-builder-CDkW88KQ.d.mts.map} +1 -1
  122. package/dist/{router-builder-CzVjPs5y.mjs → router-builder-DawnRzlp.mjs} +3 -3
  123. package/dist/{router-builder-CzVjPs5y.mjs.map → router-builder-DawnRzlp.mjs.map} +1 -1
  124. package/dist/{upload-DjhnyHHm.d.mts → upload-Cy7qQy7M.d.mts} +3 -3
  125. package/dist/{upload-DjhnyHHm.d.mts.map → upload-Cy7qQy7M.d.mts.map} +1 -1
  126. package/dist/{upload-config-d0pisVsK.mjs → upload-config-D01Ty40f.mjs} +2 -2
  127. package/dist/{upload-config-d0pisVsK.mjs.map → upload-config-D01Ty40f.mjs.map} +1 -1
  128. package/dist/web.d.mts +3 -3
  129. package/dist/web.mjs +2 -2
  130. package/dist/web.mjs.map +1 -1
  131. package/package.json +2 -2
  132. package/dist/application-nDj-76EX.mjs +0 -12
  133. package/dist/context-BGPof8bs.mjs +0 -12
  134. package/dist/context-BGPof8bs.mjs.map +0 -1
  135. package/dist/handler-2OebsoPr.mjs +0 -13
  136. package/dist/handler-2OebsoPr.mjs.map +0 -1
  137. package/dist/runtime-CDz5ayBt.mjs +0 -12
  138. package/dist/runtime-CDz5ayBt.mjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"context-BGPof8bs.mjs","names":[],"sources":["../src/http/request-store.ts","../src/http/background.ts","../src/http/context.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks'\nimport type { ContextMetaKey, MetaValue } from '../core/execution-context'\n\n/** Per-request storage for REQUEST-scoped DI and request context propagation */\nexport interface RequestStore {\n /** Unique request identifier */\n requestId: string\n /**\n * Per-request singleton cache for REQUEST-scoped services. Keys are\n * heterogeneous (class constructors, `InjectionToken` objects, raw\n * strings), so the map type stays `Map<any, any>`.\n */\n instances: Map<any, any>\n /**\n * Per-request key/value bag. Canonical backing store for\n * `RequestContext.set/get` and the Context Contributor pipeline (#107)\n * since Phase 3. Anything written here is visible to every concrete\n * execution context constructed for the same request, regardless of\n * which middleware/contributor wrote it.\n *\n * Keys are constrained to `string` per the locked decision in\n * `architecture.md` §20.12 (#4); the value type is `unknown` because\n * the concrete shape at each key is determined by the consumer's\n * `ContextMeta` augmentation, not by the store itself.\n *\n * Prefer the {@link getRequestValue} helper over reaching into this\n * map directly — it threads the augmented `ContextMeta` shape through\n * `MetaValue<K>` so consumers get typed reads without an `as` cast.\n * Writes should flow through `ctx.set(key, value)` or a Context\n * Contributor's return value — see the `setRequestValue` note below\n * for why this package intentionally does NOT ship a service-level\n * write helper.\n */\n values: Map<string, unknown>\n /** Set once {@link disposeRequestStore} has run — guards double-dispose. */\n disposed?: boolean\n}\n\n/** AsyncLocalStorage instance shared across the framework */\nexport const requestStore = new AsyncLocalStorage<RequestStore>()\n\n/**\n * Get the current request store. Throws if called outside a request context.\n * Used by the Container to resolve REQUEST-scoped dependencies.\n */\nexport function getRequestStore(): RequestStore {\n const store = requestStore.getStore()\n if (!store) {\n throw new Error(\n 'No active request context. REQUEST-scoped services can only be resolved during an HTTP request.',\n )\n }\n return store\n}\n\n/**\n * Read a per-request `ContextMeta`-keyed value from outside a controller\n * (services, repositories, anywhere with no `ctx` reference). Returns\n * the augmented type for the key — `MetaValue<K>` — so consumers get the\n * same static safety as `ctx.get(key)` without holding the context.\n *\n * Returns `undefined` outside an active request frame (background jobs,\n * startup code, tests without `requestScopeMiddleware()`) — the helper\n * is intentionally null-tolerant so calling it from a service that\n * runs in both request and non-request paths doesn't throw.\n *\n * @example\n * ```ts\n * declare module '@forinda/kickjs' {\n * interface ContextMeta { tenant: { id: string; name: string } }\n * }\n *\n * @Service()\n * class AuditService {\n * log(action: string) {\n * const tenant = getRequestValue('tenant') // typed: { id; name } | undefined\n * db.audit.insert({ action, tenantId: tenant?.id })\n * }\n * }\n * ```\n */\nexport function getRequestValue<K extends ContextMetaKey>(key: K): MetaValue<K> | undefined {\n return requestStore.getStore()?.values.get(key) as MetaValue<K> | undefined\n}\n\n// Intentionally NO `setRequestValue` export.\n//\n// Writes are deliberately context-scoped — only the controlled write\n// surfaces should mutate the per-request Map:\n//\n// 1. A Context Contributor's `resolve()` / `onError()` return value\n// (the runner does `ctx.set(reg.key, value)` on the contributor's\n// behalf). This is the canonical way to populate a key.\n// 2. A controller / middleware / contributor that holds a\n// `RequestContext` instance can call `ctx.set(key, value)`\n// directly. The write is auditable inline at the call site.\n//\n// Letting arbitrary services reach in and mutate the store from\n// anywhere produces \"spooky action at a distance\" — keys appear in\n// the request bag without an obvious source, and tracing which\n// service polluted what becomes a grep exercise. Services that need\n// to publish per-request state should return the value to the caller\n// (controller or contributor) and let *that* layer write it via\n// `ctx.set`. If a future need genuinely requires a service-level\n// write surface, expose a narrow function (`recordTrace`,\n// `markStartTime`) on a service that captures the side effect, not a\n// generic `setRequestValue`.\n","/**\n * Work that outlives the response — `waitUntil(promise)`.\n *\n * A handler that fires off an audit log, an email, or an analytics call and\n * answers without awaiting it leaves that promise unowned: on serverless the\n * platform freezes or kills the instance once the response is sent, and on a\n * Node server `SIGTERM` exits before it settles. `waitUntil` registers the\n * promise so something waits for it:\n *\n * - on the Node server, `shutdown()` awaits it (within `shutdownTimeout`);\n * - through `createHandler()` and the web entry, it is handed to the\n * platform's own `waitUntil` (Workers `ctx`, Netlify `context`, Vercel's\n * `waitUntil`) when you pass it in.\n *\n * Process-wide, like the DI container: one app per process.\n *\n * @module @forinda/kickjs/http/background\n */\nimport { createLogger } from '../core/logger'\nimport { reportError } from '../core/observers'\nimport { requestStore } from './request-store'\n\nconst log = createLogger('waitUntil')\nconst pending = new Set<Promise<void>>()\n\n/**\n * Keep `promise` alive past the response. A rejection is logged (with the\n * request id when called during a request), never left unhandled.\n *\n * @example\n * ```ts\n * @Post('/')\n * async create(ctx: RequestContext) {\n * const order = await this.orders.create(ctx.body)\n * ctx.waitUntil(this.mailer.sendReceipt(order)) // or waitUntil(...) outside a handler\n * return order\n * }\n * ```\n */\nexport function waitUntil(promise: Promise<unknown>): void {\n const requestId = requestStore.getStore()?.requestId\n const tracked: Promise<void> = Promise.resolve(promise).then(\n () => {},\n (err: unknown) => {\n log.error({ err, requestId }, 'Background work passed to waitUntil() failed')\n reportError(err, { source: 'background', requestId })\n },\n )\n pending.add(tracked)\n void tracked.finally(() => pending.delete(tracked))\n}\n\n/**\n * Resolve once every registered promise has settled — including work\n * registered while waiting. Never rejects.\n */\nexport async function settleBackgroundWork(): Promise<void> {\n while (pending.size > 0) await Promise.all(pending)\n}\n\n/** How many `waitUntil` promises have not settled yet. */\nexport function pendingBackgroundWork(): number {\n return pending.size\n}\n\n/**\n * The platform hook `createHandler()` and the web entry forward background\n * work to. Cloudflare Workers' `ctx`, Netlify's `context`, and `{ waitUntil }`\n * from `@vercel/functions` all have this shape.\n */\nexport interface PlatformContext {\n waitUntil?(promise: Promise<unknown>): void\n}\n\n/** Hand every pending (and later-registered) promise to the platform. */\nexport function forwardBackgroundWork(platform: PlatformContext | undefined): void {\n platform?.waitUntil?.(settleBackgroundWork())\n}\n","/// <reference types=\"multer\" />\nimport type { Request, NextFunction } from 'express'\nimport { ROUTE_SLOT } from '../core/route-flag'\nimport type { ActiveRuntime, MatchedRoute, RuntimeResponse } from './runtime'\nimport {\n type ContextMetaKey,\n type ExecutionContext,\n type MetaValue,\n} from '../core/execution-context'\nimport { normalizeProblem, type ProblemDetails, type ValidationError } from '../core/errors'\nimport { MissingContextValueError } from '../core/context-errors'\nimport { requestStore } from './request-store'\nimport { waitUntil } from './background'\nimport { resolveClientIp, type ClientRequestLike } from './client-ip'\nimport type { Session } from './middleware/session'\nimport {\n parseQuery,\n type ParseQueryOptions,\n type QueryFieldConfig,\n type PaginatedResponse,\n type TypedParsedQuery,\n} from './query'\n\n/**\n * Input shape for the typed problem-detail convenience methods on\n * {@link ProblemSender} (`ctx.problem.notFound`, `.badRequest`, etc.) —\n * RFC 9457 details minus the `status`, which each method pre-fills.\n */\ntype ProblemInput = Omit<ProblemDetails, 'status'>\n\n/**\n * Callable response helper for RFC 9457 — Problem Details responses.\n * Returned by `ctx.problem`. Invoke directly for a fully-specified\n * payload, or use the named convenience methods to pre-fill `status` +\n * `title` for the common codes.\n *\n * Each call sets `Content-Type: application/problem+json` and serializes\n * the canonical shape (defaulting `type` to `about:blank` and `title` to\n * the IANA reason phrase per RFC 9457 §3.1.1 / §3.1.4).\n *\n * @example\n * ```ts\n * ctx.problem({\n * type: 'https://api.example.com/problems/out-of-credit',\n * status: 403,\n * detail: 'Your balance is 30, but that costs 50.',\n * balance: 30, // extension per §3.2\n * })\n *\n * ctx.problem.notFound({ detail: 'User abc not found' })\n * ctx.problem.validation(zodResult.error.issues)\n * ```\n */\ninterface ProblemSender {\n (input: ProblemDetails): RuntimeResponse\n /** 400 Bad Request — RFC 9457. */\n badRequest(input?: ProblemInput): RuntimeResponse\n /** 401 Unauthorized — RFC 9457. */\n unauthorized(input?: ProblemInput): RuntimeResponse\n /** 403 Forbidden — RFC 9457. */\n forbidden(input?: ProblemInput): RuntimeResponse\n /** 404 Not Found — RFC 9457. */\n notFound(input?: ProblemInput): RuntimeResponse\n /** 409 Conflict — RFC 9457. */\n conflict(input?: ProblemInput): RuntimeResponse\n /** 422 Unprocessable Entity — RFC 9457. */\n unprocessable(input?: ProblemInput): RuntimeResponse\n /** 429 Too Many Requests — RFC 9457. */\n tooManyRequests(input?: ProblemInput): RuntimeResponse\n /** 500 Internal Server Error — RFC 9457. */\n internal(input?: ProblemInput): RuntimeResponse\n /**\n * 422 with Zod issues serialized into the `errors` extension per\n * RFC 9457 §3.2's array convention. Pass `error.issues` from a Zod\n * `safeParse` failure or `error.issues` from a thrown ZodError.\n */\n validation(issues: any[], input?: ProblemInput): RuntimeResponse\n}\n\n/**\n * Recursively marks every property of `T` as `readonly`. Preserves\n * `Function`, `Date`, and `RegExp` unchanged, and converts `Map` / `Set`\n * to `ReadonlyMap` / `ReadonlySet` so their mutating methods (`set`,\n * `delete`, `add`, `clear`) are removed from the public surface.\n * Tuples keep their positional element types — only their per-element\n * mutability is locked.\n *\n * Exposed as a utility for adopters who want to opt into compile-time\n * sealing of their own shapes. **No longer applied to\n * `RequestContext.{body,params,query,headers,file,files}`** — that\n * broke TS narrowing / discriminated-union drilldowns on typed request\n * payloads. Runtime read-only enforcement now lives in\n * {@link makeReadOnlyProxy} (dev-only Proxy that warns on writes,\n * no-op in production).\n *\n * Type-only. No runtime cost. `DeepReadonly<any>` is `any` (TS\n * distributes conditional types over `any`).\n */\nexport type DeepReadonly<T> = T extends (...args: never[]) => unknown\n ? T\n : T extends Date | RegExp\n ? T\n : T extends Map<infer K, infer V>\n ? ReadonlyMap<DeepReadonly<K>, DeepReadonly<V>>\n : T extends Set<infer V>\n ? ReadonlySet<DeepReadonly<V>>\n : T extends readonly (infer U)[]\n ? // Distinguish a regular array from a tuple. A regular `T[]` widens\n // its `length` to `number`; a tuple's `length` is a literal\n // (e.g. `2`). The literal branch maps over `keyof T` so each\n // positional slot keeps its own type — `DeepReadonly<[1, 2]>` →\n // `readonly [1, 2]`, not `readonly (1 | 2)[]`.\n number extends T['length']\n ? ReadonlyArray<DeepReadonly<U>>\n : { readonly [K in keyof T]: DeepReadonly<T[K]> }\n : T extends object\n ? { readonly [K in keyof T]: DeepReadonly<T[K]> }\n : T\n\n/**\n * Re-export the augmentable {@link ContextMeta} registry from core/.\n * Declared in `core/execution-context.ts` so non-HTTP transports\n * (WS/queue/cron, V2) share one declaration site. Apps still augment\n * via the canonical `declare module '@forinda/kickjs'` form.\n */\nexport type { ContextMeta } from '../core/execution-context'\n\n/**\n * Symbol key under which the per-request `AbortController` backing\n * `RequestContext.signal` is cached on the Express `req` object.\n * Shared across every `RequestContext` instance built for the same\n * request (router-builder constructs separate wrappers for\n * middleware, the contributor pipeline, and the main handler — they\n * all need the same signal).\n */\nconst signalControllerKey = Symbol.for('kickjs.requestContext.signalController')\n\n/**\n * Symbol key under which per-target read-only Proxy wrappers are\n * cached on the Express `req` object. Used by {@link makeReadOnlyProxy}\n * so repeat access of `ctx.body` / `ctx.params` / etc. returns the same\n * Proxy instance (cheap, and stable under `===` for adopters comparing\n * values across middleware).\n */\nconst readOnlyProxyCacheKey = Symbol.for('kickjs.requestContext.readOnlyProxyCache')\n\n/**\n * `true` iff `v` is a plain object (`{}` / `Object.create(null)`) or an\n * array — the two shapes JSON.parse / Express body-parser produce and\n * the only ones the read-only Proxy recurses into. Class instances,\n * `Date`, `RegExp`, `Map`, `Set`, `Buffer`, streams, and functions\n * pass through unwrapped so their method dispatch and `instanceof`\n * checks keep working.\n */\nfunction isPlainObjectOrArray(v: unknown): v is object {\n if (v === null || typeof v !== 'object') return false\n if (Array.isArray(v)) return true\n const proto = Object.getPrototypeOf(v)\n return proto === Object.prototype || proto === null\n}\n\n/**\n * In dev, wrap `target` in a `Proxy` whose `set` / `deleteProperty` /\n * `defineProperty` traps log a warning and otherwise leave the\n * underlying object untouched. A `get` trap recursively wraps nested\n * plain objects and arrays on access, so deep mutations\n * (`ctx.body.user.name = 'x'`, `ctx.files[0].fieldname = 'y'`,\n * `ctx.body.tags.push(...)`) all surface a warning — matching the\n * prior `DeepReadonly<T>` contract at runtime instead of at the type\n * level. In production (`process.env.NODE_ENV === 'production'`) the\n * proxy is bypassed entirely and `target` is returned as-is so the\n * hot path stays zero-cost.\n *\n * Why a Proxy instead of `DeepReadonly<T>` at the type level: the\n * recursive conditional type interfered with TS narrowing (notably\n * discriminated unions on `ctx.body`) and slowed type-checking on\n * deeply-nested Zod-inferred shapes. Compile-time sealing is gone;\n * runtime warning catches the same class of bug during dev and tests.\n *\n * Trap returns `true` so strict-mode call sites (which is all of them\n * — ES modules are strict) don't *throw* on assignment — they just\n * get a warning + the underlying value stays untouched. Adopters\n * discover the violation when the subsequent read returns the\n * original value, not the one they \"set\".\n *\n * Targets are cached per-`req` under {@link readOnlyProxyCacheKey} so\n * (1) repeat getter access returns the same proxy (`ctx.body ===\n * ctx.body`, `ctx.body.user === ctx.body.user`); and (2) cyclic refs\n * (`body.self = body`) terminate via the cache hit on the second\n * visit. Primitives, `null`, and non-plain values pass through.\n */\nfunction makeReadOnlyProxy<T>(target: T, req: object, label: string): T {\n if (process.env.NODE_ENV === 'production') return target\n if (!isPlainObjectOrArray(target)) return target\n\n type Cache = WeakMap<object, unknown>\n const reqObj = req as Record<symbol, Cache | undefined>\n let cache = reqObj[readOnlyProxyCacheKey]\n if (!cache) {\n cache = new WeakMap()\n reqObj[readOnlyProxyCacheKey] = cache\n }\n const targetObj = target as unknown as object\n const cached = cache.get(targetObj)\n if (cached) return cached as T\n\n const warnWrite = (verb: string, prop: PropertyKey) => {\n console.warn(\n `[kickjs] Attempted to ${verb} \\`ctx.${label}.${String(prop)}\\` — ` +\n `request data is read-only. ` +\n `Stash computed values via \\`ctx.set('key', value)\\` or a Context Contributor, ` +\n `or reach \\`ctx.req.${label}\\` if you genuinely need the raw mutable handle.`,\n )\n }\n\n const proxy = new Proxy(targetObj, {\n get(t, prop, receiver) {\n const value = Reflect.get(t, prop, receiver)\n // Recurse only into plain objects / arrays. Functions (incl.\n // array methods like `.push`) pass through with `receiver` as\n // their `this`, so internal `this[i] = x` writes still hit the\n // `set` trap and warn.\n if (isPlainObjectOrArray(value)) {\n return makeReadOnlyProxy(value, req, `${label}.${String(prop)}`)\n }\n return value\n },\n set(_t, prop) {\n warnWrite('assign', prop)\n return true\n },\n deleteProperty(_t, prop) {\n warnWrite('delete', prop)\n return true\n },\n defineProperty(_t, prop) {\n warnWrite('Object.defineProperty on', prop)\n return true\n },\n })\n cache.set(targetObj, proxy)\n return proxy as T\n}\n\n/**\n * The shape of a single route entry in `KickRoutes`. Generated by\n * `kick typegen` and consumed via the `Ctx<T>` helper. Each field is\n * `unknown` by default and is filled in as the typegen learns more\n * about the route (URL params from the path, body/query from validation\n * schemas, etc.).\n */\nexport interface RouteShape {\n params?: unknown\n body?: unknown\n query?: unknown\n response?: unknown\n /**\n * Union of context keys `kick typegen` proved are populated for this\n * route — the keys of every context contributor applied at method or\n * class level. Drives {@link RequestContext.require} narrowing, so\n * calling `ctx.require()` for a key this route doesn't carry is a\n * compile error instead of a request-time throw.\n *\n * `string` (the default) means \"not proven\", not \"no keys\". Typegen\n * emits `string` whenever it cannot see the full picture — a\n * contributor registered at module / adapter / bootstrap level, or an\n * unrecognised decorator that might bundle contributors of its own.\n * Narrowing an unprovable route would produce compile errors for keys\n * that really are present.\n */\n contextKeys?: string\n}\n\n/**\n * Unified request/response abstraction passed to every controller method.\n * Shields handlers from raw Express objects and provides convenience methods.\n *\n * Implements {@link ExecutionContext} so the transport-agnostic Context\n * Contributor pipeline (#107) can run against this concrete HTTP context\n * the same way it will run against future WS / queue / cron contexts.\n */\nexport class RequestContext<\n TBody = any,\n TParams = any,\n TQuery = any,\n /**\n * Context keys proven present for this route. Defaults to\n * {@link ContextMetaKey} — every key the project has registered — which\n * collapses to `string` when neither registry has been augmented, so a\n * handler typed as plain `RequestContext` keeps today's behaviour. That\n * default is also the deliberate escape hatch when typegen's view of a\n * route is incomplete.\n */\n TKeys extends ContextMetaKey = ContextMetaKey,\n> implements ExecutionContext<TKeys> {\n /**\n * Engine-agnostic response driver the response helpers write through. Under\n * the Express runtime it IS `res` (Express's Response satisfies\n * {@link RuntimeResponse} structurally); other runtimes pass a thin wrapper\n * over their native reply as the optional fourth argument.\n */\n private readonly _response: RuntimeResponse\n\n /**\n * The route this request matched: its method, path, controller, handler name\n * and resolved {@link MatchedRoute.flags}.\n *\n * Available to anything running inside the matched route — route middleware,\n * contributors, guards, the handler. Global middleware runs before route\n * matching, so it sees `undefined` there.\n *\n * ```ts\n * if (ctx.route?.flags.has('auth.public')) return next()\n * ```\n */\n get route(): MatchedRoute | undefined {\n return (this.req as unknown as Record<symbol, MatchedRoute | undefined>)?.[ROUTE_SLOT]\n }\n\n constructor(\n public readonly req: ActiveRuntime['request'],\n public readonly res: ActiveRuntime['response'],\n public readonly next: NextFunction,\n responseDriver?: RuntimeResponse,\n ) {\n // Under the Express runtime `res` IS a RuntimeResponse (structural); other\n // runtimes pass an explicit driver wrapping their native reply.\n this._response = responseDriver ?? (res as RuntimeResponse)\n }\n\n /**\n * Memo of the most recent {@link qs} call this request. The query\n * object is immutable for a request's lifetime, so a repeat call with\n * the same `(fieldConfig, options)` references returns the cached\n * parse instead of re-walking the filter/sort strings.\n */\n private _qsMemo?: { config: unknown; options: unknown; result: unknown }\n\n /** Memoized {@link problem} sender — built lazily on first access. */\n private _problem?: ProblemSender\n\n /**\n * Read-side accessor for the per-request metadata map.\n *\n * Returns the AsyncLocalStorage map (`requestStore.getStore().values`)\n * shared with the Context Contributor pipeline when an ALS frame is\n * active. Returns `null` outside any frame — read-side callers\n * (`ctx.get`, `ctx.user`, `ctx.tenantId`, `ctx.roles`) treat that as\n * \"no metadata\" and fall through to their `req.*` defaults. Reads\n * never throw because outside an ALS frame nobody could have written\n * via `ctx.set` anyway, so an empty answer is the truthful one.\n */\n private metadataReadOnly(): Map<string, any> | null {\n return (requestStore.getStore()?.values as Map<string, any> | undefined) ?? null\n }\n\n /**\n * Write-side accessor for the per-request metadata map.\n *\n * Returns the same map as {@link metadataReadOnly} when an ALS frame\n * is active. Throws otherwise — writing to a fallback map outside\n * the ALS frame would silently lose data because other call sites\n * (downstream contributors, request-logger, etc.) read from the\n * canonical store and would never see it. Mount\n * `requestScopeMiddleware()` (Application does this for you in\n * `'auto'` mode) or wrap your test setup in\n * `requestStore.run({...}, () => …)` to fix.\n */\n private metadataForWrite(): Map<string, any> {\n const store = requestStore.getStore()\n if (store) return store.values as Map<string, any>\n throw new Error(\n 'RequestContext.set called outside an AsyncLocalStorage frame. ' +\n 'Mount requestScopeMiddleware() before constructing RequestContext, ' +\n 'or wrap test setup in requestStore.run({ requestId, instances: new Map(), values: new Map() }, () => ...).',\n )\n }\n\n // ── Request Data ────────────────────────────────────────────────────\n\n /**\n * Parsed request body. Wrapped in a dev-only Proxy that warns when\n * adopters try to mutate Zod-validated payloads in place — compute\n * new values and stash them via `ctx.set('key', value)` or a Context\n * Contributor instead. Reach for `ctx.req.body` if you genuinely\n * need the raw, mutable Express handle (rare).\n *\n * In production the Proxy is bypassed and `this.req.body` is\n * returned as-is — no runtime cost on the hot path.\n */\n get body(): TBody {\n return makeReadOnlyProxy<TBody>(this.req.body, this.req, 'body')\n }\n\n /** Path parameters parsed from the route — read-only, see {@link body}. */\n get params(): TParams {\n return makeReadOnlyProxy<TParams>(this.req.params as TParams, this.req, 'params')\n }\n\n /** Parsed query string — read-only, see {@link body}. */\n get query(): TQuery {\n return makeReadOnlyProxy<TQuery>(this.req.query as TQuery, this.req, 'query')\n }\n\n /** Inbound HTTP headers — read-only, see {@link body}. */\n get headers(): Request['headers'] {\n return makeReadOnlyProxy<Request['headers']>(this.req.headers, this.req, 'headers')\n }\n\n get requestId(): string | undefined {\n return (this.req as any).requestId ?? (this.req.headers['x-request-id'] as string | undefined)\n }\n\n /**\n * `AbortSignal` that fires when the underlying HTTP request is\n * closed — either because the client disconnected before the\n * response was sent, or because Node's socket-close event ran\n * after a normal response. Multiple `RequestContext` wrappers for\n * the same request (router-builder constructs one per\n * middleware/contributor pipeline / main handler) share a single\n * `AbortController` cached on the underlying `req` object, so the\n * signal is stable across the request lifecycle.\n *\n * Thread it through anything that takes an `AbortSignal` so the\n * work cancels as soon as the client gives up — e.g. a kickjs-db\n * relational query:\n *\n * ```ts\n * @Get('/:id/full')\n * async show(ctx: RequestContext) {\n * const row = await this.repo.findFullById(ctx.params.id, ctx.signal)\n * if (!row) return ctx.notFound()\n * ctx.json(row)\n * }\n * ```\n *\n * The repo passes `signal` to `db.query.<table>.findUnique({ signal })`;\n * if the client disconnects mid-flight, the in-flight query rejects\n * with `RelationalQueryCancelledError` instead of consuming the\n * connection until completion.\n *\n * Implementation note — both `req.on('close')` and `res.on('close')`\n * are wired so the signal aborts regardless of whether the close\n * event lands on the request stream or the response stream first.\n * Subsequent fires are no-ops (`AbortController.abort()` is\n * idempotent).\n */\n get signal(): AbortSignal {\n const req = this.req as Request & { [signalControllerKey]?: AbortController }\n const cached = req[signalControllerKey]\n if (cached) return cached.signal\n\n const ctrl = new AbortController()\n req[signalControllerKey] = ctrl\n const abort = () => ctrl.abort('request closed')\n this.req.once('close', abort)\n this._response.once('close', abort)\n return ctrl.signal\n }\n\n /**\n * The request's session — set by the `session()` middleware, which must be\n * installed. Type your keys once by augmenting `SessionData`:\n *\n * ```ts\n * declare module '@forinda/kickjs' {\n * interface SessionData { userId?: string }\n * }\n * ```\n */\n get session(): Session {\n return (this.req as { session?: Session }).session as Session\n }\n\n /**\n * The authenticated user set by AuthAdapter.\n * Reads from the per-request metadata store first (`ctx.set('user', ...)`),\n * then falls back to `req.user` (set directly by AuthAdapter middleware).\n *\n * Extend the `AuthUser` interface via module augmentation in your own auth\n * module — see the BYO Auth recipe in the docs\n * to get full typing.\n *\n * @example\n * ```ts\n * @Get('/me')\n * @Authenticated()\n * getProfile(ctx: RequestContext) {\n * const user = ctx.user\n * if (!user) return ctx.notFound()\n * return ctx.json({ user })\n * }\n * ```\n */\n get user(): MetaValue<'user', Record<string, any>> | undefined {\n return this.metadataReadOnly()?.get('user') ?? (this.req as any).user\n }\n\n /**\n * Tenant identifier for multi-tenant apps. Reads `user.tenantId` —\n * populated either by `AuthAdapter.testMode({ tenantId })`, a tenant\n * resolver middleware, or manually on the strategy's `mapPayload`.\n *\n * Augment `AuthUser` (or `ContextMeta['user']`) to widen the return\n * type if your user shape guarantees a non-`string | undefined` id.\n */\n get tenantId(): string | undefined {\n const u = this.user as Record<string, any> | undefined\n return u?.tenantId\n }\n\n /**\n * Effective role list for the current user. Prefers `user.tenantRoles`\n * (populated by `AuthAdapterOptions.roleResolver` under a tenant) and\n * falls back to `user.roles`. Returns an empty array when the user is\n * absent or the shape has neither field.\n */\n get roles(): string[] {\n const u = this.user as Record<string, any> | undefined\n return u?.tenantRoles ?? u?.roles ?? []\n }\n\n // ── Query String Parsing ───────────────────────────────────────────\n\n /**\n * Parse the request query string into structured filters, sort, pagination, and search.\n * Pass the result to an ORM query builder adapter (Drizzle, Prisma, Sequelize, etc.).\n *\n * Generic over the field config: when passed an inline literal (or\n * `as const`), `filters[].field` and `sort[].field` are narrowed to\n * the exact whitelisted field names. Pass nothing or a non-literal\n * config and you get the loose `string` fallback.\n *\n * @param fieldConfig - Optional whitelist for filterable, sortable, and searchable fields\n * @param options - Limits (`maxLimit`, `defaultLimit`, `maxSearchLength`) and an\n * `onReject` hook. By default a rejected/over-broad field is logged via\n * `console.warn` with the request id; pass an explicit `onReject` to override\n * (e.g. throw to return a 400), or `onReject: () => {}` to silence.\n *\n * @example\n * ```ts\n * @Get('/')\n * async list(ctx: RequestContext) {\n * const parsed = ctx.qs({\n * filterable: ['status', 'priority'],\n * sortable: ['createdAt', 'title'],\n * } as const)\n * parsed.filters[0].field // typed as 'status' | 'priority'\n * parsed.sort[0].field // typed as 'createdAt' | 'title'\n * }\n * ```\n */\n qs<TConfig extends QueryFieldConfig | undefined = undefined>(\n fieldConfig?: TConfig,\n options?: ParseQueryOptions,\n ): TypedParsedQuery<TConfig> {\n // Cheap per-request memo — repeat calls with the same args (the\n // common controller pattern) skip re-parsing. `req.query` is fixed\n // for the request's lifetime, so caching is always sound.\n const memo = this._qsMemo\n if (memo && memo.config === fieldConfig && memo.options === options) {\n return memo.result as TypedParsedQuery<TConfig>\n }\n const effective: ParseQueryOptions = {\n ...options,\n onReject:\n options?.onReject ??\n ((rejection) => {\n const id = this.requestId ? `[${this.requestId}] ` : ''\n console.warn(\n `${id}query ${rejection.kind} '${rejection.field}' rejected (${rejection.reason})`,\n )\n }),\n }\n const result = parseQuery<TConfig>(\n this.req.query as Record<string, any>,\n fieldConfig,\n effective,\n )\n this._qsMemo = { config: fieldConfig, options, result }\n return result\n }\n\n // ── File Uploads ────────────────────────────────────────────────────\n\n /**\n * Single uploaded file (requires `@FileUpload({ mode: 'single' })`).\n * Wrapped in a dev-only Proxy that warns on mutation — see {@link body}.\n * File metadata is set by the upload middleware and shouldn't be\n * mutated downstream.\n */\n get file(): Express.Multer.File | undefined {\n const f = this.req.file\n return f ? makeReadOnlyProxy<Express.Multer.File>(f, this.req, 'file') : undefined\n }\n\n /**\n * Array of uploaded files (requires `@FileUpload({ mode: 'array' })`).\n * The array (and each entry in dev) is wrapped in a read-only Proxy\n * that warns on `push`/`pop` and per-file mutation. Use\n * `ctx.req.files` if you genuinely need the mutable Express handle.\n */\n get files(): Express.Multer.File[] | undefined {\n // multer's `Request['files']` is a union — array (mode: 'array' /\n // 'any') or `{ [fieldname]: File[] }` (mode: 'fields'). The\n // `@FileUpload({ mode: 'array' })` decorator only sets the array\n // shape, but `Request['files']` is the broad union. Narrow back to\n // `File[]` here for the common-case getter; adopters using\n // `mode: 'fields'` can read `ctx.req.files` directly for the\n // dictionary shape.\n const f = this.req.files\n if (!Array.isArray(f)) return undefined\n return makeReadOnlyProxy<Express.Multer.File[]>(f, this.req, 'files')\n }\n\n // ── Metadata Store ──────────────────────────────────────────────────\n\n /**\n * Read a value from the per-request metadata store.\n *\n * The key is constrained to {@link ContextMetaKey} — the keys registered in\n * `ContextMeta` / `ContextKeys` — so a typo is a compile error rather than a\n * permanent `undefined`. Projects that have augmented neither registry get\n * `string`, exactly as before.\n *\n * Constrained by `ContextMetaKey` and deliberately NOT by `TKeys`: \"does this\n * key exist in the app\" is a different question from \"does this route carry\n * it\", and narrowing by the latter would turn an incomplete typegen view into\n * false errors for keys written by middleware. Presence is `require`'s job;\n * this always returns `| undefined`.\n *\n * When `ContextMeta` has a matching key the return type is inferred\n * automatically. For ad-hoc keys, pass a generic: `ctx.get<MyType>('custom')`.\n */\n get<K extends ContextMetaKey>(key: K): MetaValue<K> | undefined {\n return this.metadataReadOnly()?.get(key) as MetaValue<K> | undefined\n }\n\n /**\n * Read a value that a contributor is expected to have produced, and\n * throw {@link MissingContextValueError} when it hasn't.\n *\n * Use this instead of `ctx.get(key)!` anywhere the value is a\n * precondition rather than an optional extra — permissions, tenants,\n * the resolved subject of the route. The non-null assertion compiles\n * whether or not the producing contributor is actually applied to the\n * route, so a dropped `@LoadTenant` turns into `undefined` flowing\n * silently into an auth check. `require()` fails loudly at that point\n * instead, naming the key.\n *\n * ```ts\n * // before — compiles even if @OperatorPerm was never applied\n * const perm = ctx.get('operatorPerm')!\n *\n * // after — throws MissingContextValueError naming the key + route\n * const perm = ctx.require('operatorPerm')\n * ```\n *\n * When `TKeys` is narrowed — which it is for a handler typed as\n * `Ctx<KickRoutes…>`, from typegen's per-route `contextKeys` — asking\n * for a key the route doesn't carry is a compile error, so a dropped\n * decorator fails the build. `TKeys` stays `string` (no narrowing) for\n * a plain `RequestContext` and for any route typegen couldn't prove\n * complete; there this is a runtime guarantee only.\n * See `architecture.md` §20.14.\n *\n * `null` counts as present; only `undefined` (or a missing entry)\n * throws. A contributor that deliberately resolves to `null` is\n * expressing \"looked, found nothing\", which is a real value — which\n * is why the return type is `Exclude<…, undefined>` and NOT\n * `NonNullable<…>`. The latter would strip `null` from the type while\n * the runtime still hands it back, so a caller would be told a value\n * is non-null and then get `null`.\n */\n require<K extends TKeys>(key: K): Exclude<MetaValue<K>, undefined> {\n const value = this.metadataReadOnly()?.get(key)\n if (value === undefined) {\n throw new MissingContextValueError(key, this.routeLabel())\n }\n return value as Exclude<MetaValue<K>, undefined>\n }\n\n /**\n * Best-effort `\"GET /path\"` label for error messages. Runtime-agnostic:\n * express/fastify requests and web-standard `Request` all expose\n * `method` + `url`, but none of them are guaranteed here, so every\n * access is defensive and the whole thing is optional.\n */\n private routeLabel(): string | undefined {\n const req = this.req as { method?: unknown; url?: unknown } | undefined\n const method = typeof req?.method === 'string' ? req.method : undefined\n const url = typeof req?.url === 'string' ? req.url : undefined\n if (method && url) return `${method} ${url}`\n return method ?? url\n }\n\n /**\n * Write a value to the per-request metadata store. Throws when no\n * AsyncLocalStorage frame is active — see {@link metadataForWrite}\n * for why a silent fallback is the wrong default.\n */\n set<K extends ContextMetaKey>(key: K, value: MetaValue<K>): void {\n this.metadataForWrite().set(key, value)\n }\n\n // ── Response Helpers ────────────────────────────────────────────────\n\n /**\n * Set a response header. Runtime-neutral — works on every engine and on\n * the web/edge entry. No-op guards are the runtime's job (headers set\n * after the response settles are ignored or throw per engine).\n */\n setHeader(name: string, value: string | number | readonly string[]): this {\n this._response.setHeader(name, value)\n return this\n }\n\n json(data: any, status = 200) {\n return this._response.status(status).json(data)\n }\n\n created(data: any) {\n return this._response.status(201).json(data)\n }\n\n noContent() {\n return this._response.status(204).end()\n }\n\n /**\n * @deprecated Prefer {@link ProblemSender.notFound | ctx.problem.notFound()},\n * which emits an RFC 9457 — Problem Details response. This helper stays\n * for backward compatibility and will not be removed.\n */\n notFound(message = 'Not Found') {\n return this._response.status(404).json({ message })\n }\n\n /**\n * @deprecated Prefer {@link ProblemSender.badRequest | ctx.problem.badRequest()},\n * which emits an RFC 9457 — Problem Details response. This helper stays\n * for backward compatibility and will not be removed.\n */\n badRequest(message: string) {\n return this._response.status(400).json({ message })\n }\n\n // ── RFC 9457 Problem Details ───────────────────────────────────────\n\n /**\n * RFC 9457 — Problem Details for HTTP APIs response helper.\n * https://datatracker.ietf.org/doc/html/rfc9457\n *\n * `ctx.problem(...)` sends a canonical problem-detail response with\n * `Content-Type: application/problem+json`. The convenience methods\n * (`ctx.problem.notFound`, `.badRequest`, etc.) pre-fill `status` +\n * `title` for the common codes.\n *\n * `type` defaults to `about:blank` (§3.1.1); `title` defaults to the\n * IANA reason phrase for `status` (§3.1.4). Extension members per §3.2\n * pass through unchanged.\n *\n * @example\n * ```ts\n * ctx.problem({\n * type: 'https://api.example.com/problems/out-of-credit',\n * status: 403,\n * detail: 'Your balance is 30, but that costs 50.',\n * instance: `/account/${ctx.user.id}/messages/${ctx.params.id}`,\n * balance: 30,\n * })\n *\n * ctx.problem.notFound({ detail: 'User abc not found' })\n * ctx.problem.validation(zodResult.error.issues)\n * ```\n *\n * @see {@link ProblemException} for the exception-throwing equivalent\n * (use it from services where `ctx` isn't in scope).\n */\n get problem(): ProblemSender {\n // Memoized — building the sender allocates ~10 closures, so pay that only\n // on the first access per context instead of per `ctx.problem.*` call.\n if (this._problem) return this._problem\n const send = (input: ProblemDetails): RuntimeResponse => this.sendProblem(input)\n send.badRequest = (input: ProblemInput = {}): RuntimeResponse =>\n this.sendProblem({ status: 400, ...input })\n send.unauthorized = (input: ProblemInput = {}): RuntimeResponse =>\n this.sendProblem({ status: 401, ...input })\n send.forbidden = (input: ProblemInput = {}): RuntimeResponse =>\n this.sendProblem({ status: 403, ...input })\n send.notFound = (input: ProblemInput = {}): RuntimeResponse =>\n this.sendProblem({ status: 404, ...input })\n send.conflict = (input: ProblemInput = {}): RuntimeResponse =>\n this.sendProblem({ status: 409, ...input })\n send.unprocessable = (input: ProblemInput = {}): RuntimeResponse =>\n this.sendProblem({ status: 422, ...input })\n send.tooManyRequests = (input: ProblemInput = {}): RuntimeResponse =>\n this.sendProblem({ status: 429, ...input })\n send.internal = (input: ProblemInput = {}): RuntimeResponse =>\n this.sendProblem({ status: 500, ...input })\n send.validation = (issues: any[], input: ProblemInput = {}): RuntimeResponse => {\n const errors: ValidationError[] = (issues || []).map((issue: any) => ({\n field: issue.path?.join?.('.') ?? '',\n message: issue.message ?? '',\n code: issue.code,\n }))\n return this.sendProblem({\n status: 422,\n detail: issues?.[0]?.message,\n ...input,\n errors,\n })\n }\n this._problem = send as ProblemSender\n return this._problem\n }\n\n private sendProblem(input: ProblemDetails): RuntimeResponse {\n const body = normalizeProblem(input)\n this._response.setHeader('Content-Type', 'application/problem+json')\n return this._response.status(body.status).json(body)\n }\n\n /**\n * Send an HTML response.\n *\n * Passes the full MIME type rather than the `'html'` shorthand. The\n * shorthand is an Express affordance — `res.type()` runs it through a MIME\n * lookup — but the Fastify and h3 drivers forward the string to their own\n * `type()` / `setHeader()` verbatim, so `'html'` reached the wire as a\n * malformed `Content-Type: html` on those engines. Fastify 5.10 started\n * normalising that invalid value to `text/plain`, which is what surfaced it.\n *\n * Express produces `text/html; charset=utf-8` for `.type('html')`, so\n * spelling it out here is byte-identical there and correct everywhere else.\n */\n /**\n * The client's IP address, or `undefined` when it cannot be determined.\n *\n * Prefers the value the runtime computed (Express derives `req.ip` from the\n * app's `trust proxy` setting; Fastify from `trustProxy`), because raw\n * forwarded headers are client-SPOOFABLE on deployments that do not\n * normalize them. The header fallbacks exist for runtimes with no `ip`\n * field at all — notably the web/edge entry.\n *\n * `ctx.req.ip` is Express-only, so reaching for it directly broke on\n * Fastify and h3.\n */\n get ip(): string | undefined {\n return resolveClientIp(this.req as ClientRequestLike)\n }\n\n /**\n * Redirect the client. Works on every runtime.\n *\n * Every engine spells this differently — Express and Fastify have\n * `res.redirect()`, h3 has `sendRedirect(event, location, code)` — and none\n * of them is shared, so this writes the status and `Location` header through\n * the runtime response surface, which all four expose.\n *\n * The response carries no body. Express sends a short text line and h3 an\n * HTML meta-refresh fallback; a bare `Location` with a 3xx is sufficient per\n * RFC 9110, and interpolating the URL into an HTML body would add an\n * injection surface to a value this method already warns is dangerous.\n *\n * ::: warning\n * Never pass an unvalidated user-supplied `url`. An attacker-controlled\n * destination turns this into an open redirect, which is a common phishing\n * primitive. Allow-list the target or keep it relative.\n * :::\n */\n redirect(url: string, status = 302) {\n this._response.status(status).setHeader('location', url)\n return this._response.end()\n }\n\n html(content: string, status = 200) {\n return this._response.status(status).type('text/html; charset=utf-8').send(content)\n }\n\n /**\n * Send `buffer` as a file download named `filename`. The name is written\n * per RFC 6266 — an ASCII fallback plus `filename*` in UTF-8 — so a name\n * from an upload (quotes, line breaks, non-Latin text) can't break the header.\n */\n download(buffer: Buffer, filename: string, contentType = 'application/octet-stream') {\n this._response.setHeader('Content-Disposition', contentDisposition(filename))\n this._response.setHeader('Content-Type', contentType)\n return this._response.send(buffer)\n }\n\n /**\n * Render a template using the registered view engine (EJS, Pug, Handlebars, etc.).\n * Requires a ViewAdapter to be configured in bootstrap().\n *\n * @param template - Template name (without extension, relative to viewsDir)\n * @param data - Data to pass to the template\n *\n * @example\n * ```ts\n * ctx.render('dashboard', { user, title: 'Dashboard' })\n * ctx.render('emails/welcome', { name: 'Alice' })\n * ```\n */\n render(template: string, data: Record<string, any> = {}) {\n return this._response.render(template, data)\n }\n\n /**\n * Parse query params and return a standardized paginated response.\n * Calls `ctx.qs()` internally, then wraps your data with pagination meta.\n *\n * @param fetcher - Async function that receives ParsedQuery and returns `{ data, total }`\n * @param fieldConfig - Optional whitelist for filterable, sortable, searchable fields\n *\n * @example\n * ```ts\n * @Get('/')\n * async list(ctx: RequestContext) {\n * return ctx.paginate(\n * async (parsed) => {\n * const data = await db.select().from(users)\n * .where(query.where).limit(parsed.pagination.limit)\n * .offset(parsed.pagination.offset).all()\n * const total = await db.select({ count: count() }).from(users).get()\n * return { data, total: total?.count ?? 0 }\n * },\n * { filterable: ['name', 'role'], sortable: ['createdAt'] },\n * )\n * }\n * ```\n */\n async paginate<T, TConfig extends QueryFieldConfig | undefined = undefined>(\n fetcher: (parsed: TypedParsedQuery<TConfig>) => Promise<{ data: T[]; total: number }>,\n fieldConfig?: TConfig,\n ): Promise<PaginatedResponse<T>> {\n const parsed = this.qs<TConfig>(fieldConfig)\n const { data, total } = await fetcher(parsed)\n const { page, limit } = parsed.pagination\n const totalPages = Math.ceil(total / limit) || 1\n\n const response: PaginatedResponse<T> = {\n data,\n meta: {\n page,\n limit,\n total,\n totalPages,\n hasNext: page < totalPages,\n hasPrev: page > 1,\n },\n }\n\n this.json(response)\n // Sends AND returns the payload. Returning `this.json(...)` handed back\n // the engine's `RuntimeResponse`, so the documented usage —\n // `return ctx.paginate(...)` — emitted `response: RuntimeResponse` into\n // `KickRoutes`, and the typed client offered `.status()` / `.setHeader()`\n // where the caller expected `data` and `meta`.\n //\n // Returning the payload rather than tagging the response reuses the\n // existing return-value inference (the same path `return user` and\n // `return reply(201, user)` take) instead of adding a second mechanism\n // beside `reply`. Sending here is kept for handlers that call `paginate`\n // without returning it; the runtimes only auto-send a returned value when\n // nothing was written (`if (!res.headersSent)`), so there is no double\n // send.\n return response\n }\n\n // ── Server-Sent Events ──────────────────────────────────────────────\n\n /**\n * Start an SSE (Server-Sent Events) stream.\n * Sets the correct headers and returns helpers to send events.\n *\n * Pass a payload type to get typed sends — and `return sse` from the\n * handler so `kick typegen` carries the event type into\n * `KickRoutes.Api`, where `@forinda/kickjs-client`'s `api.stream()`\n * picks it up (the returned handler is ignored at runtime — the\n * response is already streaming).\n *\n * @example\n * ```ts\n * interface Tick { time: string }\n *\n * @Get('/events')\n * async stream(ctx: RequestContext) {\n * const sse = ctx.sse<Tick>()\n *\n * const interval = setInterval(() => {\n * sse.send({ time: new Date().toISOString() }, 'tick')\n * }, 1000)\n *\n * sse.onClose(() => clearInterval(interval))\n * return sse // typed as SseHandler<Tick> → response inference\n * }\n * ```\n */\n /**\n * Send a web-standard `Response` — status, headers (every `Set-Cookie`\n * kept) and body, streamed chunk by chunk — on any runtime. For handing off\n * to libraries that speak `Request`/`Response`, such as the MCP SDK's\n * web-standard transport.\n *\n * Resolves once the body is fully written. Stops reading the body when the\n * client disconnects.\n *\n * @example\n * ```ts\n * @Post('/mcp')\n * async mcp(ctx: RequestContext) {\n * await ctx.sendResponse(await transport.handleRequest(webRequest))\n * }\n * ```\n */\n async sendResponse(response: Response): Promise<void> {\n const headers: Record<string, string | string[]> = {}\n response.headers.forEach((value, name) => {\n if (name !== 'set-cookie') headers[name] = value\n })\n const cookies = response.headers.getSetCookie()\n if (cookies.length > 0) headers['set-cookie'] = cookies\n\n if (!response.body) {\n // Not writeHead() + end(): on the web driver writeHead switches to a\n // streamed Response, which a 204/304 cannot be, and on Fastify end()\n // bypasses the headers set on the reply. send() is each runtime's own\n // buffered reply path.\n this._response.status(response.status)\n for (const [name, value] of Object.entries(headers)) this._response.setHeader(name, value)\n this._response.send('')\n return\n }\n this._response.writeHead(response.status, headers as Record<string, string>)\n // Send the headers now: a stream whose first chunk comes later (SSE)\n // would otherwise leave the client waiting to see the response open.\n this._response.flushHeaders()\n const reader = response.body.getReader()\n const stop = () => {\n reader.cancel().catch(() => {})\n }\n this.signal.addEventListener('abort', stop, { once: true })\n try {\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n // Honour backpressure: on a slow client, wait for the socket to drain\n // (or the client to go away) before reading more of the body.\n if (this._response.write(Buffer.from(value)) === false && !this.signal.aborted) {\n await new Promise<void>((resolve) => {\n const resume = () => {\n this.signal.removeEventListener('abort', resume)\n resolve()\n }\n this._response.once('drain', resume)\n this.signal.addEventListener('abort', resume, { once: true })\n })\n }\n }\n } finally {\n this.signal.removeEventListener('abort', stop)\n this._response.end()\n }\n }\n\n /**\n * Keep `promise` running after the response is sent — an audit log, an\n * email, an analytics call. The Node server's `shutdown()` waits for it;\n * `createHandler()` and the web entry hand it to the platform's\n * `waitUntil` when you pass the platform context in. A rejection is\n * logged, never unhandled. Same as the standalone `waitUntil()` export.\n */\n waitUntil(promise: Promise<unknown>): void {\n waitUntil(promise)\n }\n\n sse<T = unknown>(): SseHandler<T> {\n this._response.writeHead(200, {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache',\n Connection: 'keep-alive',\n 'X-Accel-Buffering': 'no',\n })\n this._response.flushHeaders()\n\n const closeCallbacks: Array<() => void> = []\n\n this.req.on('close', () => {\n for (const cb of closeCallbacks) cb()\n })\n\n return {\n /** Send an SSE event with optional event name and id */\n send: (data: T, event?: string, id?: string) => {\n if (id) this._response.write(`id: ${id}\\n`)\n if (event) this._response.write(`event: ${event}\\n`)\n this._response.write(`data: ${JSON.stringify(data)}\\n\\n`)\n },\n /** Send a comment (keeps connection alive) */\n comment: (text: string) => {\n this._response.write(`: ${text}\\n\\n`)\n },\n /** Register a callback when the client disconnects */\n onClose: (fn: () => void) => {\n closeCallbacks.push(fn)\n },\n /** End the SSE stream */\n close: () => {\n this._response.end()\n },\n }\n }\n}\n\n/**\n * The handle {@link RequestContext.sse} returns. The optional phantom\n * `__sse` property carries the event payload type STRUCTURALLY — never set\n * at runtime — so `kick typegen`'s response inference (handler `return sse`)\n * flows it into `KickRoutes.Api`, and `@forinda/kickjs-client` detects SSE\n * routes without importing any server types.\n */\nexport interface SseHandler<T = unknown> {\n /** Phantom event-payload type marker — never assigned at runtime. */\n readonly __sse?: T\n /** Send an SSE event with optional event name and id. */\n send(data: T, event?: string, id?: string): void\n /** Send a comment line (keeps the connection alive through proxies). */\n comment(text: string): void\n /** Register a callback for client disconnect. */\n onClose(fn: () => void): void\n /** End the SSE stream. */\n close(): void\n}\n\n/**\n * Short alias for `RequestContext` parameterised by a route shape.\n *\n * Use with `kick typegen`'s generated `KickRoutes` namespace for\n * fully-typed `ctx.params`, `ctx.body`, and `ctx.query`. Metadata\n * typing (`ctx.get()`, `ctx.set()`, `ctx.user`) comes from\n * `ContextMeta` augmentation and works on all `RequestContext` instances.\n *\n * @example\n * ```ts\n * @Get('/:id')\n * getUser(ctx: Ctx<KickRoutes.UserController['getUser']>) {\n * ctx.params.id // typed from RouteShape\n * ctx.body // typed from RouteShape\n * ctx.user // typed from ContextMeta\n * ctx.get('tenant') // typed from ContextMeta\n * }\n * ```\n */\nexport type Ctx<TRoute extends RouteShape = RouteShape> = RequestContext<\n TRoute extends { body: infer B } ? B : any,\n TRoute extends { params: infer P } ? P : any,\n TRoute extends { query: infer Q } ? Q : any,\n // Falls back to `string` (no narrowing) whenever typegen couldn't prove\n // the route's full contributor set — see `RouteShape.contextKeys`.\n TRoute extends { contextKeys: infer K }\n ? K extends ContextMetaKey\n ? K\n : ContextMetaKey\n : ContextMetaKey\n>\n\n/**\n * Global ambient registry of typed routes, populated by `kick typegen`.\n *\n * Interfaces inside `KickRoutes` correspond to controller classes (each\n * property one route method, conforming to `RouteShape`) — plus the\n * reserved `KickRoutes.Api`: a flat `'METHOD /mounted/path'` map over the\n * same shapes, consumed by `@forinda/kickjs-client`. Don't name a\n * controller class `Api` — it would declaration-merge into that map.\n *\n * Empty by default — declarations come from `.kickjs/types/kick__routes.ts`\n * generated alongside the rest of the typegen output.\n */\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace KickRoutes {}\n}\n\n/** `attachment; filename=\"…\"; filename*=UTF-8''…` for any file name (RFC 6266 / RFC 8187). */\nexport function contentDisposition(filename: string): string {\n const fallback = filename.replace(/[^\\x20-\\x7e]|[\"\\\\]/g, '_')\n const encoded = encodeURIComponent(filename).replace(\n /['()*]/g,\n (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,\n )\n return `attachment; filename=\"${fallback}\"; filename*=UTF-8''${encoded}`\n}\n"],"mappings":";;;;;;;;;;gbAuCA,MAAa,aAAe,IAAI,kBAMhC,SAAgB,iBAAgC,CAC9C,IAAM,MAAQ,aAAa,SAAS,EACpC,GAAI,CAAC,MACH,MAAU,MACR,iGACF,EAEF,OAAO,KACT,CA4BA,SAAgB,gBAA0C,IAAkC,CAC1F,OAAO,aAAa,SAAS,CAAC,EAAE,OAAO,IAAI,GAAG,CAChD,CC7DA,MAAM,IAAM,aAAa,WAAW,EAC9B,QAAU,IAAI,IAgBpB,SAAgB,UAAU,QAAiC,CACzD,IAAM,UAAY,aAAa,SAAS,CAAC,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AM,KAAK,KAAK,KAAK,CACtC,EAEA,QAAU,IAAmB,CAC3B,eAAe,KAAK,EAAE,CACxB,EAEA,UAAa,CACX,KAAK,UAAU,IAAI,CACrB,CACF,CACF,CACF,EAwEA,SAAgB,mBAAmB,SAA0B,CAM3D,MAAO,yBALU,SAAS,QAAQ,sBAAuB,GAKlB,EAAE,sBAJzB,mBAAmB,QAAQ,CAAC,CAAC,QAC3C,UACC,GAAM,IAAI,EAAE,WAAW,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,YAAY,GAEe,GACvE"}
@@ -1,13 +0,0 @@
1
- /**
2
- * @forinda/kickjs v9.1.0
3
- *
4
- * Copyright (c) Felix Orinda
5
- *
6
- * This source code is licensed under the MIT license found in the
7
- * LICENSE file in the root directory of this source tree.
8
- *
9
- * @license MIT
10
- */
11
- import{createLogger,describeError}from"./core/logger.mjs";import{HttpException}from"./core/errors.mjs";import{a as createRequestStore,f as unsupportedMediaTypeError,n as applyHandlerResult,o as disposeRequestStore,t as publishMatchedRoute,u as classifyMediaType}from"./runtime-CDz5ayBt.mjs";import{l as requestStore,t as RequestContext}from"./context-BGPof8bs.mjs";import{validate}from"./http/middleware/validate.mjs";import{t as applyUploadConfig}from"./upload-config-d0pisVsK.mjs";var WebRequestShim=class{method;url;headers;body;params={};query={};requestId;file;files;signal;constructor(request,url){this.method=request.method,this.url=url.pathname+url.search,this.signal=request.signal;let headers={};request.headers.forEach((value,key)=>{headers[key]=value}),this.headers=headers;let query={};for(let key of url.searchParams.keys()){let all=url.searchParams.getAll(key);query[key]=all.length>1?all:all[0]}this.query=query}once(event,listener){return event===`close`&&this.signal.addEventListener(`abort`,listener,{once:!0}),this}on(event,listener){return this.once(event,listener)}};const encoder=new TextEncoder;function toBytes(chunk){return chunk instanceof Uint8Array?chunk:encoder.encode(String(chunk))}var WebResponseDriver=class{signal;ready;settled=!1;_status=200;headers=new Headers;_headersSent=!1;writer;resolveReady;constructor(signal){this.signal=signal,this.ready=new Promise(resolve=>{this.resolveReady=resolve})}status(code){return this._status=code,this}json(data){return this.headers.has(`content-type`)||this.headers.set(`content-type`,`application/json; charset=utf-8`),this.finish(JSON.stringify(data))}send(data){return typeof data==`object`&&data&&!(data instanceof Uint8Array)?this.json(data):this.finish(data)}type(contentType){return this.headers.set(`content-type`,contentType),this}setHeader(name,value){if(Array.isArray(value)){this.headers.delete(name);for(let v of value)this.headers.append(name,String(v))}else this.headers.set(name,String(value));return this}render(){throw Error(`ctx.render() is not supported on the web runtime (no view engine).`)}writeHead(statusCode,headers){if(this._status=statusCode,headers)for(let[name,value]of Object.entries(headers))this.setHeader(name,value);return this.startStream(),this}flushHeaders(){return this.startStream(),this}write(chunk){return this.startStream(),this.writer.write(toBytes(chunk)).catch(()=>{}),!0}end(data){return this.writer?(data!==void 0&&this.write(data),this.writer.close().catch(()=>{}),this.writer=void 0,this):this.finish(data)}once(event,listener){return event===`close`&&this.signal&&this.signal.addEventListener(`abort`,listener,{once:!0}),this}get headersSent(){return this._headersSent}finish(body){if(this.settled)return this;this.settled=!0,this._headersSent=!0;let bodyAllowed=this._status!==204&&this._status!==304;return this.resolveReady(new Response(bodyAllowed?body??null:null,{status:this._status,headers:this.headers})),this}startStream(){if(this.writer||this.settled)return;let{readable,writable}=new TransformStream;this.writer=writable.getWriter(),this.settled=!0,this._headersSent=!0,this.signal?.addEventListener(`abort`,()=>{this.writer?.abort().catch(()=>{}),this.writer=void 0},{once:!0}),this.resolveReady(new Response(readable,{status:this._status,headers:this.headers}))}};const log=createLogger(`WebPipeline`),NOOP_NEXT=()=>{},BODY_METHODS=new Set([`POST`,`PUT`,`PATCH`,`DELETE`]);function defaultErrorResponse(err,driver){let status=typeof err?.status==`number`?err.status:typeof err?.statusCode==`number`?err.statusCode:500;if(status>=500){log.error(err,`Unhandled error in web pipeline — ${describeError(err)}`);let stack=err?.stack;driver.status(status).json({error:`Internal Server Error`,...isProduction()?{}:{message:describeError(err),...typeof stack==`string`?{stack:stack.split(`
12
- `)}:{}}});return}driver.status(status).json({error:err?.message??`Request failed`})}function isProduction(){return typeof process<`u`&&process.env?.NODE_ENV===`production`}function compileWebRoute(entry,hooks){let validator=entry.meta.validation?validate(entry.meta.validation):void 0,upload=entry.meta.upload&&entry.meta.upload.mode!==`none`?entry.meta.upload:null;return async({request,url,params})=>{let req=new WebRequestShim(request,url);req.params=params;let bodyError;if(upload){let form=await request.formData().catch(()=>void 0);if(form){let rawParts=[],fields={};for(let[name,value]of form.entries())typeof value==`string`?fields[name]=value:rawParts.push({fieldname:name,filename:value.name??``,mimetype:value.type||`application/octet-stream`,buffer:new Uint8Array(await value.arrayBuffer())});let{file,files}=applyUploadConfig(rawParts,entry.meta.upload);req.file=file,req.files=files,req.body=fields}}else if(BODY_METHODS.has(request.method)){let raw=request.body===null?``:await request.text().catch(()=>``),kind=classifyMediaType(req.headers[`content-type`]);if(raw!==``&&kind===`unsupported`)bodyError=unsupportedMediaTypeError(req.headers[`content-type`]);else if(raw!==``&&kind!==`multipart`){if(kind===`json`)try{req.body=JSON.parse(raw)}catch(err){bodyError=HttpException.badRequest(err instanceof Error?err.message:`Request body could not be parsed`)}else req.body=kind===`urlencoded`?Object.fromEntries(new URLSearchParams(raw)):raw}}let store=createRequestStore(req.headers[`x-request-id`]);req.requestId=store.requestId;let driver=new WebResponseDriver(request.signal);driver.setHeader(`x-request-id`,store.requestId),publishMatchedRoute(req,entry);let pipeline=requestStore.run(store,async()=>{if(bodyError)throw bodyError;let ctx=new RequestContext(req,driver,NOOP_NEXT,driver);if(entry.earlyContributorRunner&&(await entry.earlyContributorRunner(ctx),driver.settled))return;validator&&await new Promise((resolve,reject)=>{validator(req,void 0,err=>err?reject(err):resolve())});for(let mw of entry.middlewares){let advanced=!1;if(await new Promise((resolve,reject)=>{Promise.resolve(mw(ctx,err=>{advanced=!0,err?reject(err):resolve()})).catch(reject)}),!advanced||driver.settled)return}if(entry.contributorRunner&&await entry.contributorRunner(ctx),driver.settled)return;let result=await entry.handler(ctx);driver.settled||applyHandlerResult(ctx,result)});try{try{await Promise.race([pipeline,driver.ready])}catch(err){driver.settled||(hooks?.onError&&await hooks.onError(err,req,driver),driver.settled||defaultErrorResponse(err,driver))}return driver.settled||driver.status(404).json({error:`Not Found`}),await driver.ready}finally{Promise.resolve(pipeline).catch(()=>{}).then(()=>disposeRequestStore(store))}}}export{WebRequestShim as n,WebResponseDriver as r,compileWebRoute as t};
13
- //# sourceMappingURL=handler-2OebsoPr.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"handler-2OebsoPr.mjs","names":[],"sources":["../src/http/web/driver.ts","../src/http/web/handler.ts"],"sourcesContent":["// Web-standard driver pair — the request/response bridge between web\n// primitives (WHATWG Request/Response) and the KickJS RequestContext surface.\n//\n// Deliberately imports NOTHING from node: this module is the edge-safe core\n// shared by the h3 v2 runtime (`runtimes/h3-web.ts`, node bootstrap) and the\n// `@forinda/kickjs/web` fetch entry (edge/Bun/Deno).\n\nimport type { RuntimeResponse } from '../runtime'\n\n/**\n * Presents a web `Request` as the express-shaped `req` object that\n * `RequestContext` (and route validation) reads: plain-object `headers`,\n * assignable `body`/`params`/`query`, and `on/once('close')` bridged from\n * the request's `AbortSignal` — the only EventEmitter surface the context\n * layer uses (`ctx.signal`, SSE close).\n */\nexport class WebRequestShim {\n readonly method: string\n readonly url: string\n /** Lower-cased plain header object (RequestContext indexes it directly). */\n readonly headers: Record<string, string>\n body: unknown\n params: Record<string, string> = {}\n query: Record<string, unknown> = {}\n requestId?: string\n file?: unknown\n files?: unknown;\n // Ad-hoc props middleware may set (session, user, ...) — index signature\n // keeps assignment open like a node req object.\n [key: string]: unknown\n\n private readonly signal: AbortSignal\n\n constructor(request: Request, url: URL) {\n this.method = request.method\n // Express-shaped `req.url` is path + search, not the absolute URL.\n this.url = url.pathname + url.search\n this.signal = request.signal\n const headers: Record<string, string> = {}\n request.headers.forEach((value, key) => {\n headers[key] = value\n })\n this.headers = headers\n const query: Record<string, unknown> = {}\n for (const key of url.searchParams.keys()) {\n const all = url.searchParams.getAll(key)\n query[key] = all.length > 1 ? all : all[0]\n }\n this.query = query\n }\n\n /** `req.once('close')` — abort of the underlying request signal. */\n once(event: string, listener: () => void): this {\n if (event === 'close') this.signal.addEventListener('abort', listener, { once: true })\n return this\n }\n\n /** `req.on('close')` — same bridge; signals only abort once anyway. */\n on(event: string, listener: () => void): this {\n return this.once(event, listener)\n }\n}\n\nconst encoder = new TextEncoder()\n\nfunction toBytes(chunk: unknown): Uint8Array {\n if (chunk instanceof Uint8Array) return chunk\n return encoder.encode(String(chunk))\n}\n\n/**\n * `RuntimeResponse` over a web `Response`.\n *\n * Two modes:\n * - **Buffered** (default): `status/json/send/type/setHeader` record state;\n * the terminal call resolves {@link ready} with a complete `Response`.\n * - **Streaming**: the first `writeHead`/`flushHeaders`/`write` call switches\n * to a `TransformStream` and resolves {@link ready} IMMEDIATELY with a\n * streamed `Response` — SSE works on edge this way; `write` feeds the\n * writer, `end` closes it.\n *\n * A class so the method table lives on a shared prototype (one allocation\n * per request — same rationale as the Fastify/h3 driver classes).\n */\nexport class WebResponseDriver implements RuntimeResponse {\n /** Resolves with the final (or streamed) Response. */\n readonly ready: Promise<Response>\n /** True once a terminal/streaming action produced the Response. */\n settled = false\n\n private _status = 200\n private readonly headers = new Headers()\n private _headersSent = false\n private writer?: WritableStreamDefaultWriter<Uint8Array>\n private resolveReady!: (response: Response) => void\n\n constructor(private readonly signal?: AbortSignal) {\n this.ready = new Promise<Response>((resolve) => {\n this.resolveReady = resolve\n })\n }\n\n status(code: number): this {\n this._status = code\n return this\n }\n\n json(data: unknown): this {\n if (!this.headers.has('content-type'))\n this.headers.set('content-type', 'application/json; charset=utf-8')\n return this.finish(JSON.stringify(data))\n }\n\n send(data: unknown): this {\n if (\n data !== undefined &&\n data !== null &&\n typeof data === 'object' &&\n !(data instanceof Uint8Array)\n ) {\n return this.json(data)\n }\n return this.finish(data as string | Uint8Array | null | undefined)\n }\n\n type(contentType: string): this {\n this.headers.set('content-type', contentType)\n return this\n }\n\n setHeader(name: string, value: unknown): this {\n if (Array.isArray(value)) {\n this.headers.delete(name)\n for (const v of value) this.headers.append(name, String(v))\n } else {\n this.headers.set(name, String(value))\n }\n return this\n }\n\n render(): never {\n throw new Error('ctx.render() is not supported on the web runtime (no view engine).')\n }\n\n writeHead(statusCode: number, headers?: Record<string, string | number | string[]>): this {\n this._status = statusCode\n if (headers) {\n for (const [name, value] of Object.entries(headers)) this.setHeader(name, value)\n }\n this.startStream()\n return this\n }\n\n flushHeaders(): this {\n this.startStream()\n return this\n }\n\n write(chunk: unknown): boolean {\n this.startStream()\n // Fire-and-forget: backpressure is absorbed by the stream's queue. Write\n // failures (client gone) surface via the abort listener, not here.\n void this.writer!.write(toBytes(chunk)).catch(() => {})\n return true\n }\n\n end(data?: unknown): this {\n if (this.writer) {\n if (data !== undefined) this.write(data)\n void this.writer.close().catch(() => {})\n this.writer = undefined\n return this\n }\n return this.finish(data as string | Uint8Array | null | undefined)\n }\n\n once(event: string, listener: (...args: unknown[]) => void): this {\n if (event === 'close' && this.signal)\n this.signal.addEventListener('abort', listener as () => void, { once: true })\n return this\n }\n\n get headersSent(): boolean {\n return this._headersSent\n }\n\n /** Buffered terminal: build the final Response exactly once. */\n private finish(body?: string | Uint8Array | null): this {\n if (this.settled) return this\n this.settled = true\n this._headersSent = true\n // 204/304 must not carry a body per the Response constructor contract.\n const bodyAllowed = this._status !== 204 && this._status !== 304\n this.resolveReady(\n new Response(bodyAllowed ? (body ?? null) : null, {\n status: this._status,\n headers: this.headers,\n }),\n )\n return this\n }\n\n /** Switch to streaming mode and resolve `ready` with the streamed Response. */\n private startStream(): void {\n if (this.writer || this.settled) return\n const { readable, writable } = new TransformStream<Uint8Array, Uint8Array>()\n this.writer = writable.getWriter()\n this.settled = true\n this._headersSent = true\n // Abort from the client tears the stream down so the writer stops queueing.\n this.signal?.addEventListener(\n 'abort',\n () => {\n void this.writer?.abort().catch(() => {})\n this.writer = undefined\n },\n { once: true },\n )\n this.resolveReady(new Response(readable, { status: this._status, headers: this.headers }))\n }\n}\n","// Engine-neutral web pipeline: run one KickJS RouteEntry against a WHATWG\n// Request and produce a WHATWG Response. Shared by the h3 v2 runtime\n// (node bootstrap) and the `@forinda/kickjs/web` fetch entry (edge/Bun/Deno).\n// Edge-safe: no node imports beyond the sanctioned ALS request store.\n\nimport { HttpException } from '../../core/errors'\nimport { classifyMediaType, unsupportedMediaTypeError } from '../body-policy'\nimport { RequestContext } from '../context'\nimport { publishMatchedRoute } from '../runtime'\nimport { applyHandlerResult } from '../reply'\nimport { requestStore } from '../request-store'\nimport { createRequestStore, disposeRequestStore } from '../middleware/request-scope'\nimport { validate } from '../middleware/validate'\nimport { applyUploadConfig, type RawUploadPart } from '../middleware/upload-config'\nimport type { RouteEntry, RuntimeResponse } from '../runtime'\nimport { WebRequestShim, WebResponseDriver } from './driver'\nimport { createLogger, describeError } from '../../core/logger'\n\nconst log = createLogger('WebPipeline')\nconst NOOP_NEXT = (): void => {}\nconst BODY_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])\n\nexport interface WebRouteInvocation {\n request: Request\n url: URL\n params: Record<string, string>\n}\n\nexport interface WebRouteHooks {\n /**\n * Error bridge — receives pipeline rejections (validation failures,\n * handler throws) with the shim + driver so an engine can dispatch the\n * framework's connect-style error handler. When absent (or when it\n * doesn't settle the driver), a minimal JSON error is produced from\n * `err.status`/`err.statusCode` (500 default).\n */\n onError?: (err: unknown, req: WebRequestShim, res: WebResponseDriver) => void | Promise<void>\n}\n\n/**\n * Fallback error shape when no engine error handler settles the response.\n *\n * This path used to be completely silent: a bare\n * `{ error: 'Internal Server Error' }` with no log line anywhere, so a\n * failure that reached here left no trace on either side. It is a\n * last-resort branch, which is exactly when diagnostics matter most.\n */\nfunction defaultErrorResponse(err: unknown, driver: WebResponseDriver): void {\n const status =\n typeof (err as { status?: number })?.status === 'number'\n ? (err as { status: number }).status\n : typeof (err as { statusCode?: number })?.statusCode === 'number'\n ? (err as { statusCode: number }).statusCode\n : 500\n\n if (status >= 500) {\n log.error(err, `Unhandled error in web pipeline — ${describeError(err)}`)\n const stack = (err as Error)?.stack\n driver.status(status).json({\n error: 'Internal Server Error',\n ...(isProduction()\n ? {}\n : {\n message: describeError(err),\n ...(typeof stack === 'string' ? { stack: stack.split('\\n') } : {}),\n }),\n })\n return\n }\n\n driver.status(status).json({ error: (err as Error)?.message ?? 'Request failed' })\n}\n\n/**\n * Read per-call, not at module scope: the web entry is imported once and\n * reused across invocations, and edge runtimes may not expose `process`.\n */\nfunction isProduction(): boolean {\n return typeof process !== 'undefined' && process.env?.NODE_ENV === 'production'\n}\n\n/**\n * Compile a RouteEntry into a `(invocation) => Promise<Response>` function.\n * Everything derivable at route-build time (validator, upload config) is\n * hoisted here — per-request work is shim + store + pipeline only.\n */\nexport function compileWebRoute(\n entry: RouteEntry,\n hooks?: WebRouteHooks,\n): (invocation: WebRouteInvocation) => Promise<Response> {\n const validator = entry.meta.validation ? validate(entry.meta.validation) : undefined\n const upload = entry.meta.upload && entry.meta.upload.mode !== 'none' ? entry.meta.upload : null\n\n return async ({ request, url, params }) => {\n const req = new WebRequestShim(request, url)\n req.params = params\n let bodyError: unknown\n\n // Body: uploads consume the stream as FormData; everything else parses\n // by content-type.\n if (upload) {\n const form = await request.formData().catch(() => undefined)\n if (form) {\n const rawParts: RawUploadPart[] = []\n const fields: Record<string, unknown> = {}\n for (const [name, value] of form.entries()) {\n if (typeof value === 'string') {\n fields[name] = value\n } else {\n rawParts.push({\n fieldname: name,\n filename: value.name ?? '',\n mimetype: value.type || 'application/octet-stream',\n buffer: new Uint8Array(await value.arrayBuffer()) as unknown as Buffer,\n })\n }\n }\n const { file, files } = applyUploadConfig(rawParts, entry.meta.upload!)\n req.file = file\n req.files = files\n req.body = fields\n }\n } else if (BODY_METHODS.has(request.method)) {\n // Read once — a Request body is a stream and cannot be consumed twice.\n // A read that fails (client aborted mid-flight) is treated as an absent\n // body: there is nobody left to answer, and it is not a malformed one.\n const raw = request.body === null ? '' : await request.text().catch(() => '')\n\n // An empty body is ABSENT, not unparseable — the same call the node h3\n // runtime makes on `content-length: 0`. Distinguishing the two is the\n // whole point: `.catch(() => undefined)` around the parse could not,\n // so a malformed payload answered 200 with the handler running against\n // `undefined` (#605), the defect #586 removed from the node runtime.\n const kind = classifyMediaType(req.headers['content-type'])\n if (raw !== '' && kind === 'unsupported') {\n // Held for the same reason as a parse failure: no driver yet.\n bodyError = unsupportedMediaTypeError(req.headers['content-type'])\n } else if (raw !== '' && kind !== 'multipart') {\n if (kind === 'json') {\n try {\n req.body = JSON.parse(raw)\n } catch (err) {\n // Held, not thrown: the driver that turns an error into a response\n // does not exist yet, so throwing here escapes the route entirely\n // and surfaces as a 500. Rethrown as the pipeline's first act.\n bodyError = HttpException.badRequest(\n err instanceof Error ? err.message : 'Request body could not be parsed',\n )\n }\n } else if (kind === 'urlencoded') {\n req.body = Object.fromEntries(new URLSearchParams(raw))\n } else {\n req.body = raw\n }\n }\n }\n\n const store = createRequestStore(req.headers['x-request-id'])\n req.requestId = store.requestId\n\n const driver = new WebResponseDriver(request.signal)\n driver.setHeader('x-request-id', store.requestId)\n\n publishMatchedRoute(req, entry)\n\n const pipeline = requestStore.run(store, async () => {\n if (bodyError) throw bodyError\n\n const ctx = new RequestContext(\n req as never,\n driver as never,\n NOOP_NEXT,\n driver as RuntimeResponse,\n )\n\n // `beforeValidation` contributors (#677) — ahead of validation and middleware.\n if (entry.earlyContributorRunner) {\n await entry.earlyContributorRunner(ctx)\n if (driver.settled) return\n }\n\n if (validator) {\n await new Promise<void>((resolve, reject) => {\n validator(req as never, undefined as never, (err?: unknown) =>\n err ? reject(err) : resolve(),\n )\n })\n }\n\n for (const mw of entry.middlewares) {\n let advanced = false\n await new Promise<void>((resolve, reject) => {\n const next = (err?: unknown): void => {\n advanced = true\n if (err) reject(err)\n else resolve()\n }\n Promise.resolve(mw(ctx, next)).catch(reject)\n })\n if (!advanced || driver.settled) return\n }\n\n if (entry.contributorRunner) await entry.contributorRunner(ctx)\n if (driver.settled) return\n const result = await entry.handler(ctx)\n // Return-value handlers (reply.ts): auto-send when nothing was written.\n // `undefined` falls through to the canonical 404 below.\n if (!driver.settled) applyHandlerResult(ctx, result)\n })\n\n try {\n // Streaming responses resolve `ready` mid-pipeline (SSE); buffered ones\n // resolve at the terminal ctx call. Race so both shapes return promptly.\n try {\n await Promise.race([pipeline, driver.ready])\n } catch (err) {\n if (!driver.settled) {\n if (hooks?.onError) await hooks.onError(err, req, driver)\n if (!driver.settled) defaultErrorResponse(err, driver)\n }\n }\n if (!driver.settled) {\n // Pipeline finished without responding — canonical 404 shape.\n driver.status(404).json({ error: 'Not Found' })\n }\n return await driver.ready\n } finally {\n // @PreDestroy teardown. For buffered responses this runs post-response;\n // for streams it runs when the pipeline (not the stream) completes —\n // stream lifetime is governed by the client abort signal.\n void Promise.resolve(pipeline)\n .catch(() => {})\n .then(() => disposeRequestStore(store))\n }\n }\n}\n"],"mappings":";;;;;;;;;;meAgBA,IAAa,eAAb,KAA4B,CAC1B,OACA,IAEA,QACA,KACA,OAAiC,CAAC,EAClC,MAAiC,CAAC,EAClC,UACA,KACA,MAKA,OAEA,YAAY,QAAkB,IAAU,CACtC,KAAK,OAAS,QAAQ,OAEtB,KAAK,IAAM,IAAI,SAAW,IAAI,OAC9B,KAAK,OAAS,QAAQ,OACtB,IAAM,QAAkC,CAAC,EACzC,QAAQ,QAAQ,SAAS,MAAO,MAAQ,CACtC,QAAQ,KAAO,KACjB,CAAC,EACD,KAAK,QAAU,QACf,IAAM,MAAiC,CAAC,EACxC,IAAK,IAAM,OAAO,IAAI,aAAa,KAAK,EAAG,CACzC,IAAM,IAAM,IAAI,aAAa,OAAO,GAAG,EACvC,MAAM,KAAO,IAAI,OAAS,EAAI,IAAM,IAAI,EAC1C,CACA,KAAK,MAAQ,KACf,CAGA,KAAK,MAAe,SAA4B,CAE9C,OADI,QAAU,SAAS,KAAK,OAAO,iBAAiB,QAAS,SAAU,CAA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OAAO,SAAS,OAGlB,WACF,MAAM,IAAI,SAAe,QAAS,SAAW,CAC3C,UAAU,IAAc,IAAA,GAAqB,KAC3C,IAAM,OAAO,GAAG,EAAI,QAAQ,CAC9B,CACF,CAAC,EAGH,IAAK,IAAM,MAAM,MAAM,YAAa,CAClC,IAAI,SAAW,GASf,GARA,MAAM,IAAI,SAAe,QAAS,SAAW,CAM3C,QAAQ,QAAQ,GAAG,IALL,KAAwB,CACpC,SAAW,GACP,IAAK,OAAO,GAAG,EACd,QAAQ,CACf,CAC4B,CAAC,CAAC,CAAC,MAAM,MAAM,CAC7C,CAAC,EACG,CAAC,UAAY,OAAO,QAAS,MACnC,CAGA,GADI,MAAM,mBAAmB,MAAM,MAAM,kBAAkB,GAAG,EAC1D,OAAO,QAAS,OACpB,IAAM,OAAS,MAAM,MAAM,QAAQ,GAAG,EAGjC,OAAO,SAAS,mBAAmB,IAAK,MAAM,CACrD,CAAC,EAED,GAAI,CAGF,GAAI,CACF,MAAM,QAAQ,KAAK,CAAC,SAAU,OAAO,KAAK,CAAC,CAC7C,OAAS,IAAK,CACP,OAAO,UACN,OAAO,SAAS,MAAM,MAAM,QAAQ,IAAK,IAAK,MAAM,EACnD,OAAO,SAAS,qBAAqB,IAAK,MAAM,EAEzD,CAKA,OAJK,OAAO,SAEV,OAAO,OAAO,GAAG,CAAC,CAAC,KAAK,CAAE,MAAO,WAAY,CAAC,EAEzC,MAAM,OAAO,KACtB,QAAU,CAIR,QAAa,QAAQ,QAAQ,CAAC,CAC3B,UAAY,CAAC,CAAC,CAAC,CACf,SAAW,oBAAoB,KAAK,CAAC,CAC1C,CACF,CACF"}
@@ -1,12 +0,0 @@
1
- /**
2
- * @forinda/kickjs v9.1.0
3
- *
4
- * Copyright (c) Felix Orinda
5
- *
6
- * This source code is licensed under the MIT license found in the
7
- * LICENSE file in the root directory of this source tree.
8
- *
9
- * @license MIT
10
- */
11
- import{METADATA}from"./core/interfaces.mjs";import{createLogger}from"./core/logger.mjs";import{n as getClassMetaOrUndefined}from"./metadata-CW4I35nN.mjs";import{HttpException}from"./core/errors.mjs";import{t as ROUTE_SLOT}from"./route-flag-sIYXay3q.mjs";import{l as requestStore}from"./context-BGPof8bs.mjs";function normalizeMediaType(contentType){return((Array.isArray(contentType)?contentType[0]:contentType)??``).split(`;`)[0].trim().toLowerCase()}function isJsonMediaType(mediaType){return mediaType===`application/json`||/^application\/[\w.+-]+\+json$/.test(mediaType)}function classifyMediaType(contentType){let mediaType=normalizeMediaType(contentType);return mediaType?isJsonMediaType(mediaType)?`json`:mediaType===`application/x-www-form-urlencoded`?`urlencoded`:mediaType.startsWith(`multipart/`)?`multipart`:mediaType.startsWith(`text/`)?`text`:`unsupported`:`unsupported`}const EXPRESS_JSON_TYPES=[`application/json`,`application/*+json`],SUPPORTED_BODY_TYPES=[`application/json`,`application/*+json`,`application/x-www-form-urlencoded`,`text/*`,`multipart/form-data`];function unsupportedMediaTypeError(contentType){let mediaType=normalizeMediaType(contentType);return new HttpException(415,mediaType?`Unsupported Media Type: ${mediaType}`:`Unsupported Media Type: request has a body but no Content-Type`,void 0,{Accept:SUPPORTED_BODY_TYPES.join(`, `)})}const BODY_METHODS=new Set([`POST`,`PUT`,`PATCH`,`DELETE`]);function rejectUnsupportedBody(){return(req,_res,next)=>{if(!BODY_METHODS.has((req.method??`GET`).toUpperCase())||classifyMediaType(req.headers?.[`content-type`])!==`unsupported`)return next();let reject=()=>next(unsupportedMediaTypeError(req.headers?.[`content-type`])),length=req.headers?.[`content-length`];if(length!==void 0)return length===`0`?next():reject();if(req.headers?.[`transfer-encoding`]===void 0)return next();let decided=!1,settle=fn=>()=>{decided||(decided=!0,req.off?.(`data`,onData),req.off?.(`end`,onEnd),fn())},onData=settle(reject),onEnd=settle(()=>next());req.on?.(`data`,onData),req.on?.(`end`,onEnd)}}const log=createLogger(`RequestScope`),preDestroyCache=new Map;function preDestroyMethod(ctor){let method=preDestroyCache.get(ctor);return method===void 0&&(method=getClassMetaOrUndefined(METADATA.PRE_DESTROY,ctor.prototype)??null,preDestroyCache.set(ctor,method)),method}function disposeRequestStore(store){if(!store.disposed&&(store.disposed=!0,store.instances.size!==0)){for(let instance of store.instances.values()){if(typeof instance!=`object`||!instance)continue;let method=preDestroyMethod(instance.constructor);if(method&&typeof instance[method]==`function`)try{let result=instance[method]();result&&typeof result.then==`function`&&result.catch(err=>log.error(err,`@PreDestroy on ${instance.constructor.name} rejected`))}catch(err){log.error(err,`@PreDestroy on ${instance.constructor.name} threw`)}}store.instances.clear()}}const REQUEST_SCOPE_MIDDLEWARE_MARKER=Symbol.for(`@kickjs/requestScopeMiddleware`);function createRequestStore(requestId){return{requestId:requestId||crypto.randomUUID(),instances:new Map,values:new Map}}function requestScopeMiddleware(){let mw=(req,res,next)=>{let requestIdHeader=req.headers[`x-request-id`],requestId=(Array.isArray(requestIdHeader)?requestIdHeader[0]:requestIdHeader)||crypto.randomUUID(),store=createRequestStore(requestId);req.requestId=requestId,res.once(`close`,()=>disposeRequestStore(store)),requestStore.run(store,next)};return mw[REQUEST_SCOPE_MIDDLEWARE_MARKER]=!0,mw}function isRequestScopeMiddleware(value){return typeof value==`function`&&value[REQUEST_SCOPE_MIDDLEWARE_MARKER]===!0}const REPLY_BRAND=Symbol.for(`kickjs.reply`);function reply(status,body){return{[REPLY_BRAND]:!0,status,body}}reply.ok=body=>reply(200,body),reply.created=body=>reply(201,body),reply.accepted=body=>reply(202,body),reply.noContent=()=>reply(204,void 0);function isReply(value){return typeof value==`object`&&!!value&&value[REPLY_BRAND]===!0}function applyHandlerResult(ctx,result){return result===void 0?!1:isReply(result)?result.status===204?(ctx.noContent(),!0):(ctx.json(result.body,result.status),!0):(ctx.json(result),!0)}function publishMatchedRoute(req,entry){req[ROUTE_SLOT]={method:entry.method,path:entry.path,controller:entry.meta.controller,handlerName:entry.meta.handlerName,flags:entry.meta.flags??EMPTY_FLAGS,pattern:entry.meta.pattern??entry.path}}const EMPTY_FLAGS=new Map;export{createRequestStore as a,requestScopeMiddleware as c,rejectUnsupportedBody as d,unsupportedMediaTypeError as f,reply as i,EXPRESS_JSON_TYPES as l,applyHandlerResult as n,disposeRequestStore as o,isReply as r,isRequestScopeMiddleware as s,publishMatchedRoute as t,classifyMediaType as u};
12
- //# sourceMappingURL=runtime-CDz5ayBt.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"runtime-CDz5ayBt.mjs","names":[],"sources":["../src/http/body-policy.ts","../src/http/middleware/request-scope.ts","../src/http/reply.ts","../src/http/runtime.ts"],"sourcesContent":["/**\n * How a request body is interpreted, decided in ONE place for every runtime.\n *\n * Before this, each engine brought its own library's opinion: Express parsed\n * only exact `application/json` and silently left everything else `undefined`,\n * Fastify answered 415 for anything it had no parser for, and h3 routed\n * unrecognised types through `destr` — so the same request produced a parsed\n * object, an empty body, or a 415 depending on which engine the app was\n * configured with. The runtime is meant to be swappable; that made it not\n * swappable for any app accepting a body outside `application/json` (#590).\n *\n * @module @forinda/kickjs/http/body-policy\n */\n\nimport { HttpException } from '../core/errors'\n\n/**\n * A header as the runtimes hand it over. Node's `IncomingHttpHeaders` and\n * Fastify's normalised map both allow `string[]`, so take the union here\n * rather than casting at every call site.\n */\nexport type HeaderValue = string | string[] | undefined\n\n/** What the framework does with a body of a given media type. */\nexport type BodyKind =\n /** Parse as JSON, strictly. */\n | 'json'\n /** Parse as `application/x-www-form-urlencoded` into an object. */\n | 'urlencoded'\n /** Hand the handler the raw string. Never JSON — see `classifyMediaType`. */\n | 'text'\n /** Left to the upload path, which consumes the stream itself. */\n | 'multipart'\n /** Not parsed. `ctx.body` stays undefined. */\n | 'unsupported'\n\n/**\n * Strip parameters and normalise: `Application/JSON; charset=utf-8` →\n * `application/json`. h3's own check is `===` against the bare type, which is\n * why `application/json; charset=utf-8` — what most clients actually send —\n * missed it and fell to a non-strict branch.\n */\nexport function normalizeMediaType(contentType: HeaderValue): string {\n const value = Array.isArray(contentType) ? contentType[0] : contentType\n return (value ?? '').split(';')[0].trim().toLowerCase()\n}\n\n/**\n * `application/*+json` is JSON, and this is not a judgement call: RFC 6838\n * §4.2.8 says a media type \"MUST NOT be given names incorporating suffixes for\n * structured syntaxes they do not actually employ\", and RFC 6839 §2 exists so\n * receivers can \"do generic processing of the underlying representation\".\n * Spring, ASP.NET Core and Hono's validator all match the suffix by default.\n *\n * So `application/merge-patch+json` (RFC 7396) and `application/problem+json`\n * (RFC 9457) parse as JSON — which the framework already emits for every\n * problem response, and previously could not read back.\n */\nfunction isJsonMediaType(mediaType: string): boolean {\n return mediaType === 'application/json' || /^application\\/[\\w.+-]+\\+json$/.test(mediaType)\n}\n\n/**\n * Decide how to treat a body, from its declared media type alone.\n *\n * `text/*` deliberately yields the raw string and is NEVER JSON-parsed.\n * `text/plain` is one of three CORS-safelisted content types, so it crosses\n * origins without a preflight; JSON-parsing it would re-open the simple-request\n * CSRF that requiring `application/json` closes. h3's own source carries this\n * warning, and h3 v2 pulled back from `destr` partly because of it.\n */\nexport function classifyMediaType(contentType: HeaderValue): BodyKind {\n const mediaType = normalizeMediaType(contentType)\n if (!mediaType) return 'unsupported'\n if (isJsonMediaType(mediaType)) return 'json'\n if (mediaType === 'application/x-www-form-urlencoded') return 'urlencoded'\n if (mediaType.startsWith('multipart/')) return 'multipart'\n if (mediaType.startsWith('text/')) return 'text'\n return 'unsupported'\n}\n\n/**\n * Media types Express should hand to its JSON body parser. `express.json()`\n * defaults to the exact string `application/json`, and `type-is` will not match\n * `application/json` against a bare wildcard-plus-json pattern (a length guard rejects\n * it), so BOTH entries are required — passing only the wildcard silently stops\n * parsing ordinary JSON.\n */\nexport const EXPRESS_JSON_TYPES = ['application/json', 'application/*+json'] as const\n\n/** Media types the framework claims to parse, for diagnostics and docs. */\nexport const SUPPORTED_BODY_TYPES = [\n 'application/json',\n 'application/*+json',\n 'application/x-www-form-urlencoded',\n 'text/*',\n 'multipart/form-data',\n] as const\n\n/**\n * The 415 for a body whose media type the framework does not parse.\n *\n * Only ever raised when a body was actually SENT. An absent or empty body is\n * treated as absent regardless of its declared type — the same call Spring's\n * `readWithMessageConverters` and ASP.NET's `BodyModelBinder` both make, and\n * the reason neither rejects a bodyless POST. A bare `POST` with no payload is\n * a legitimate request, not an unsupported one.\n *\n * Carries `Accept`, which RFC 9110 §15.5.16 says a 415 \"can\" use to indicate\n * which media types would have been accepted.\n */\nexport function unsupportedMediaTypeError(contentType: HeaderValue): HttpException {\n const mediaType = normalizeMediaType(contentType)\n return new HttpException(\n 415,\n mediaType\n ? `Unsupported Media Type: ${mediaType}`\n : 'Unsupported Media Type: request has a body but no Content-Type',\n undefined,\n { Accept: SUPPORTED_BODY_TYPES.join(', ') },\n )\n}\n\n/** Verbs whose body the framework reads. */\nconst BODY_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])\n\n/**\n * Did this request actually carry a body? Decided from the framing headers\n * rather than from whether a parser produced anything — the distinction that\n * separates \"nothing was sent\" from \"something was sent that we could not\n * read\", which is the whole basis for answering 415 on one and 200 on the other.\n */\nexport function hasRequestBody(headers: Record<string, unknown>): boolean {\n const length = headers['content-length'] as string | undefined\n const encoding = headers['transfer-encoding'] as string | undefined\n return encoding !== undefined || (length !== undefined && length !== '0')\n}\n\n/**\n * Connect middleware that answers 415 for a body Express's parsers left\n * untouched.\n *\n * Express has no concept of an unsupported type: a parser whose `type` does not\n * match simply calls `next()` and leaves `req.body` undefined, indistinguishable\n * from a request that sent nothing. Mounted after the parsers, this restores the\n * distinction so Express agrees with the other runtimes.\n */\nexport function rejectUnsupportedBody() {\n return (req: any, _res: unknown, next: (err?: unknown) => void): void => {\n if (!BODY_METHODS.has((req.method ?? 'GET').toUpperCase())) return next()\n if (classifyMediaType(req.headers?.['content-type']) !== 'unsupported') return next()\n\n const reject = (): void => next(unsupportedMediaTypeError(req.headers?.['content-type']))\n const length = req.headers?.['content-length'] as string | undefined\n if (length !== undefined) return length === '0' ? next() : reject()\n if (req.headers?.['transfer-encoding'] === undefined) return next()\n\n // Chunked: the framing headers say a body MAY follow, but an empty chunked\n // post sends none. Deciding on the headers alone would 415 a request that\n // sent nothing, so wait to see whether a byte actually arrives — the same\n // distinction the other runtimes make by inspecting the read body.\n let decided = false\n const settle = (fn: () => void) => (): void => {\n if (decided) return\n decided = true\n req.off?.('data', onData)\n req.off?.('end', onEnd)\n fn()\n }\n const onData = settle(reject)\n const onEnd = settle(() => next())\n req.on?.('data', onData)\n req.on?.('end', onEnd)\n }\n}\n","// Web Crypto via globalThis.crypto (randomUUID) — portable across\n// node/bun/deno/workers; node:crypto deliberately NOT imported here so this\n// module stays on the edge-safe request path.\nimport type { Request, Response, NextFunction } from 'express'\nimport { requestStore, type RequestStore } from '../request-store'\nimport { METADATA } from '../../core/interfaces'\nimport { getClassMetaOrUndefined } from '../../core/metadata'\nimport { createLogger } from '../../core/logger'\n\nconst log = createLogger('RequestScope')\n\n// Per-class @PreDestroy method-name cache: the metadata is immutable after\n// class definition, so pay the Reflect read once per class, not once per\n// instance per request. `null` = \"checked, none declared\".\nconst preDestroyCache = new Map<Function, string | symbol | null>()\n\nfunction preDestroyMethod(ctor: Function): string | symbol | null {\n let method = preDestroyCache.get(ctor)\n if (method === undefined) {\n method =\n getClassMetaOrUndefined<string | symbol>(METADATA.PRE_DESTROY, (ctor as any).prototype) ??\n null\n preDestroyCache.set(ctor, method)\n }\n return method\n}\n\n/**\n * Run `@PreDestroy` hooks on every REQUEST-scoped instance the request\n * created, then drop them. Called when the response closes (finished or\n * aborted) — the counterpart to `@PostConstruct`, closing the lifecycle gap\n * where per-request services holding transactions/handles/subscriptions were\n * silently dropped with no cleanup callback.\n *\n * Idempotent (guarded by `store.disposed`); hook errors are logged and\n * swallowed so one failing teardown can't break request completion. Async\n * hooks are fired without being awaited — the response is already gone.\n */\nexport function disposeRequestStore(store: RequestStore): void {\n if (store.disposed) return\n store.disposed = true\n if (store.instances.size === 0) return\n for (const instance of store.instances.values()) {\n if (instance === null || typeof instance !== 'object') continue\n const method = preDestroyMethod(instance.constructor)\n if (!method || typeof instance[method] !== 'function') continue\n try {\n const result = instance[method]()\n if (result && typeof result.then === 'function') {\n ;(result as Promise<void>).catch((err) =>\n log.error(err, `@PreDestroy on ${instance.constructor.name} rejected`),\n )\n }\n } catch (err) {\n log.error(err, `@PreDestroy on ${instance.constructor.name} threw`)\n }\n }\n store.instances.clear()\n}\n\n/**\n * Marker symbol stamped on the function returned by {@link requestScopeMiddleware}.\n *\n * `Application.setup()` uses {@link isRequestScopeMiddleware} to detect whether\n * the user-supplied middleware list already contains the request-scope wrapper,\n * and skips its automatic auto-mount when one is found. Lets adopters control\n * the exact position of the ALS frame in their pipeline (e.g., after a custom\n * tracing wrapper) without ending up with two nested frames.\n */\n// `Symbol.for(...)` returns a plain `symbol` (not `unique symbol`), but the\n// runtime detection marker doesn't need the unique nominal property — it only\n// needs the interned-slot reference equality that `Symbol.for` already provides.\nconst REQUEST_SCOPE_MIDDLEWARE_MARKER = Symbol.for('@kickjs/requestScopeMiddleware')\n\n/**\n * Build a fresh per-request store. Shared by {@link requestScopeMiddleware}\n * (Express) and by runtimes whose handler runs outside the connect-middleware\n * chain (e.g. Fastify), so both establish an identical ALS frame.\n */\nexport function createRequestStore(requestId?: string): RequestStore {\n return {\n requestId: requestId || crypto.randomUUID(),\n instances: new Map(),\n // Explicit generic locks the \"string keys only\" decision.\n values: new Map<string, unknown>(),\n }\n}\n\n/**\n * Wraps each request in an AsyncLocalStorage context.\n * Enables REQUEST-scoped DI and automatic requestId propagation to logs.\n *\n * Should be mounted early in the middleware pipeline (before route handlers).\n * `Application` mounts this automatically unless `contextStore: 'manual'` is set\n * or the user already includes one in their middleware list.\n */\nexport function requestScopeMiddleware() {\n const mw = (req: Request, res: Response, next: NextFunction) => {\n const requestIdHeader = req.headers['x-request-id']\n const requestId =\n (Array.isArray(requestIdHeader) ? requestIdHeader[0] : requestIdHeader) || crypto.randomUUID()\n const store = createRequestStore(requestId)\n // Surface the requestId on req so the standalone requestId() middleware\n // (when also mounted) reuses this value instead of generating a divergent\n // second one. Without this, log lines that read from the ALS store would\n // disagree with the X-Request-Id response header for any request that\n // didn't carry an inbound x-request-id header.\n ;(req as Request & { requestId?: string }).requestId = requestId\n // 'close' fires once the response finished OR the client aborted — run\n // @PreDestroy teardown for the request's scoped instances either way.\n res.once('close', () => disposeRequestStore(store))\n // Pass `next` directly — `run` invokes it with no args, so the arrow\n // wrapper previously allocated per request added nothing.\n requestStore.run(store, next)\n }\n ;(mw as unknown as Record<symbol, unknown>)[REQUEST_SCOPE_MIDDLEWARE_MARKER] = true\n return mw\n}\n\n/**\n * Returns `true` when `value` is the function produced by {@link requestScopeMiddleware}.\n *\n * Detection uses a `Symbol.for(...)` marker so the check survives different\n * copies of `@forinda/kickjs` loaded under different module identities (e.g.,\n * a published package alongside a workspace-linked one during local dev).\n */\nexport function isRequestScopeMiddleware(value: unknown): boolean {\n if (typeof value !== 'function') return false\n return (value as unknown as Record<symbol, unknown>)[REQUEST_SCOPE_MIDDLEWARE_MARKER] === true\n}\n","// Return-value handler support.\n//\n// Handlers may RETURN their response payload instead of calling `ctx.json`:\n// the runtime auto-sends it when the pipeline finishes with nothing written.\n// `reply(status, body)` wraps a payload with a non-200 status while staying\n// transparent to type inference (`Reply<201, Task>` carries both statically).\n//\n// Edge-safe: no node imports — shared by all four runtimes including the\n// `@forinda/kickjs/web` entry.\n\nimport type { RequestContext } from './context'\nimport type { RuntimeResponse } from './runtime'\n\n// `Symbol.for` so the brand survives duplicate module copies (workspace-linked\n// + published package in one process — same rationale as the request-scope\n// middleware marker).\nconst REPLY_BRAND = Symbol.for('kickjs.reply')\n\n/**\n * A status-carrying response payload for return-value handlers. Create via\n * {@link reply} — the brand is what runtimes detect, and the generics are\n * what the `kick/routes` response typegen unwraps (`Reply<S, T>` → `T`).\n */\nexport interface Reply<S extends number = number, T = unknown> {\n readonly [REPLY_BRAND]: true\n readonly status: S\n readonly body: T\n}\n\n/**\n * Wrap a return-value handler's payload with an explicit status code:\n *\n * ```ts\n * @Post('/')\n * async create(ctx: RequestContext) {\n * return reply(201, await this.tasks.create(ctx.body))\n * }\n * ```\n */\nexport function reply<S extends number, T>(status: S, body: T): Reply<S, T> {\n return { [REPLY_BRAND]: true, status, body }\n}\n\n/** `reply(200, body)` — explicit form of a bare `return body`. */\nreply.ok = <T>(body: T): Reply<200, T> => reply(200, body)\n/** `reply(201, body)` */\nreply.created = <T>(body: T): Reply<201, T> => reply(201, body)\n/** `reply(202, body)` */\nreply.accepted = <T>(body: T): Reply<202, T> => reply(202, body)\n/** Empty 204 — maps to `ctx.noContent()`. */\nreply.noContent = (): Reply<204, undefined> => reply(204, undefined)\n\n/**\n * The statically-inferred response type of a controller handler — what\n * `kick typegen` emits into `KickRoutes[...].response`:\n *\n * - `Awaited<ReturnType>` of the method\n * - `Reply<S, T>` unwraps to `T`\n * - `void`/`undefined` members are dropped (imperative `ctx.json` branches);\n * a handler that never returns a value stays `unknown`, matching the\n * pre-inference emission\n *\n * ```ts\n * type R = InferHandlerResponse<UsersController['get']> // → User\n * ```\n */\nexport type InferHandlerResponse<H> = H extends (...args: never[]) => infer R\n ? [Exclude<Awaited<R>, void | undefined>] extends [never]\n ? unknown\n : UnwrapReply<Exclude<Awaited<R>, void | undefined>>\n : unknown\n\ntype UnwrapReply<A> =\n A extends Reply<number, infer B>\n ? B\n : A extends RuntimeResponse\n ? // The engine's own response object says nothing about the body, so a\n // handler ending `return ctx.json(...)` degrades to `unknown` — which is\n // what the typegen comment always claimed happened. It did not: the bare\n // `RuntimeResponse` leaked into `KickRoutes[...].response`, offering\n // `.status()` / `.setHeader()` to a client expecting a payload.\n // Confidently wrong is worse than unknown.\n //\n // To carry a payload, return it (`return user`) or wrap it\n // (`return reply(201, user)`) — that is what `reply` is for.\n unknown\n : A\n\nexport function isReply(value: unknown): value is Reply {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as Record<symbol, unknown>)[REPLY_BRAND] === true\n )\n}\n\n/**\n * Send a handler's RETURN value when the pipeline finished without anything\n * having written a response. Callers guard on \"driver/response unsettled\" —\n * this only decides how to send:\n *\n * - `undefined` → not handled (returns false; runtime keeps today's behavior)\n * - `Reply` wrapper → status + body (204 → `ctx.noContent()`)\n * - anything else → `ctx.json(value)` (200)\n *\n * Returns true when a response was produced.\n */\nexport function applyHandlerResult(ctx: RequestContext, result: unknown): boolean {\n if (result === undefined) return false\n if (isReply(result)) {\n // Only 204 maps to noContent — an undefined body must NOT coerce the\n // declared status (reply(304, undefined) keeps its 304; the json body\n // is simply empty).\n if (result.status === 204) {\n ctx.noContent()\n return true\n }\n ctx.json(result.body, result.status)\n return true\n }\n ctx.json(result)\n return true\n}\n","// The HttpRuntime seam.\n//\n// Decorators no longer emit an `express.Router` directly. `buildRouteTable()`\n// turns controller metadata into a plain-data `RouteEntry[]`; an `HttpRuntime`\n// materializes that table onto whatever engine it owns. Express is the default\n// runtime and the only one shipped in M1 — its materializer reproduces the exact\n// handler chain the old `buildRoutes()` built, so behavior is unchanged.\n//\n// Fastify / h3 runtimes (later milestones) consume the SAME `RouteEntry` data\n// and the SAME `HttpRuntime` contract; the request/response driver abstraction\n// that lets `RequestContext` run engine-agnostically lands with them (M3), since\n// under Express the drivers ARE the Express request/response objects already.\n//\n// Why a seam: running Fastify / h3 behind an Express-compat layer\n// (`@fastify/express`, h3's node bridge) bypasses their router and\n// serialization, and rebuilding `ctx` over web-standard Request/Response\n// would break SSE / streaming, multer uploads and `ctx.res` for every adopter.\n// The seam keeps `ctx` and swaps only the engine underneath it.\n\nimport { ROUTE_SLOT, type RouteFlags } from '../core/route-flag'\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport type {\n RequestHandler,\n ErrorRequestHandler,\n Express,\n Request as ExpressRequest,\n Response as ExpressResponse,\n} from 'express'\n\nimport type { Constructor, FileUploadConfig, MiddlewareHandler, RouteDefinition } from '../core'\nimport type { RequestContext } from './context'\n\n/** HTTP verbs the router emits. Mirrors the decorator surface (@Get/@Post/...). */\nexport type RouteMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'\n\n/**\n * A context-based handler: the runtime-neutral unit of the request pipeline.\n * Contributors, route middleware (via {@link MiddlewareHandler}), and the\n * terminal controller call all reduce to this shape. The runtime owns how a\n * `CtxHandler` is wrapped onto its engine (Express wraps it in `(req, res,\n * next)`; Fastify in its own handler).\n */\nexport type CtxHandler = (ctx: RequestContext) => unknown | Promise<unknown>\n\n/**\n * Connect-style middleware — the portable middleware format. Built-in\n * middleware and adopter-supplied Express middleware are this shape. The\n * Express runtime hands them straight to `app.use`; later runtimes bridge\n * them (Fastify via `@fastify/middie`, h3 via its node adapter).\n *\n * Typed as the Express handler union for M1 (Express is the only runtime);\n * a future milestone narrows this to bare node `(req, res, next)` primitives\n * once the driver layer lands.\n */\nexport type ConnectMiddleware = RequestHandler | ErrorRequestHandler\n\n/**\n * One materialized route, as plain data. Produced by {@link buildRouteTable}\n * from decorator metadata; consumed by {@link HttpRuntime.mountRoutes}.\n *\n * The shape is deliberately richer than a flat `CtxHandler[]`: `middlewares`\n * keep the `(ctx, next)` signature (they may short-circuit or call `next(err)`),\n * `contributorRunner` is a closure over the pre-built pipeline + container (the\n * pipeline is built — and any cycle / missing-dep error thrown — at table-build\n * time, i.e. boot), and `validation` / `upload` stay as metadata the runtime\n * materializes its own way. Faithfully reproducing the legacy Express chain —\n * not collapsing it — is what keeps M1 behavior-neutral.\n */\nexport interface RouteEntry {\n method: RouteMethod\n /** Path with `:param` segments — the portable subset all engines accept. */\n path: string\n /** Class + method middleware, in execution order; each receives `(ctx, next)`. */\n middlewares: MiddlewareHandler[]\n /**\n * Runs the contributor pipeline against `ctx` (populates `ctx.set(...)`),\n * or `null` when no contributors apply. Closes over the built pipeline and\n * the DI container so it stays engine-neutral; the runtime advances the\n * chain (Express: call `next()`) once it resolves.\n */\n contributorRunner: CtxHandler | null\n /**\n * Contributors registered with `beforeValidation: true`. Runtimes run this\n * right after publishing the matched route — before validation, upload and\n * middleware — so a rejection (401) lands before a malformed body's 422.\n * Absent or `null` when no contributor asks for it.\n */\n earlyContributorRunner?: CtxHandler | null\n /** Terminal handler: resolves the controller per-request and invokes it. */\n handler: CtxHandler\n /** Introspection + runtime-materialized concerns (swagger/typegen read this). */\n meta: RouteMeta\n}\n\n/** Per-route metadata: introspection refs plus runtime-materialized concerns. */\nexport interface RouteMeta {\n /**\n * Owning controller class — for DI resolution and adapter introspection.\n * Absent for ad-hoc routes registered through {@link AdapterHttp.route},\n * which have no controller class behind them.\n */\n controller?: Constructor\n /** Handler method name on the controller, when there is one. */\n handlerName?: string\n /** Zod/JSON-schema validation config from the route decorator, if any. */\n validation?: RouteDefinition['validation']\n /** `@FileUpload` config, if present — the runtime supplies the backend. */\n upload?: FileUploadConfig\n /**\n * Route flags in force here, resolved at build time (method over class).\n * Enabled flags only: a flag declared `false` at a higher-precedence site is\n * absent rather than present-and-false, so `has()` is always the right\n * question. See `core/route-flag.ts`.\n */\n flags?: RouteFlags\n /**\n * The full mounted pattern (`/api/v1/users/:id`) — set by the Application\n * for controller routes. `path` is relative to the module mount.\n */\n pattern?: string\n}\n\n/**\n * The route a request matched, published on `ctx.route`.\n *\n * Everything that holds a {@link RequestContext} — handlers, `@Middleware()`,\n * guards, contributors — can read it, which is what lets one declaration on a\n * route serve every consumer.\n */\n/**\n * Publish the matched route on the request, for `ctx.route` to read.\n *\n * Called by each runtime once per dispatch, before it builds a RequestContext.\n * It lives on `req` rather than on the ctx because the Express runtime\n * constructs a fresh RequestContext per middleware step — anything written to\n * one ctx would be invisible to the next and to the handler.\n */\nexport function publishMatchedRoute(req: unknown, entry: RouteEntry): void {\n ;(req as Record<symbol, MatchedRoute>)[ROUTE_SLOT] = {\n method: entry.method,\n path: entry.path,\n controller: entry.meta.controller,\n handlerName: entry.meta.handlerName,\n flags: entry.meta.flags ?? EMPTY_FLAGS,\n pattern: entry.meta.pattern ?? entry.path,\n }\n}\n\nconst EMPTY_FLAGS: RouteFlags = new Map() as RouteFlags\n\nexport interface MatchedRoute {\n method: RouteMethod\n /** Path as declared on the handler, e.g. `/:id`. */\n path: string\n /**\n * The full route pattern including the mount prefix and version, e.g.\n * `/api/v1/users/:id` — what metrics and spans should be keyed by. Falls\n * back to `path` for routes registered without a mount.\n */\n pattern: string\n controller?: Constructor\n handlerName?: string\n /** Enabled flags only — see {@link RouteMeta.flags}. */\n flags: RouteFlags\n}\n\n/** A controller's routes grouped under the module mount prefix. */\nexport type RouteTable = { mountPath: string; routes: RouteEntry[] }[]\n\n/**\n * The response surface {@link RequestContext}'s helpers (`json` / `html` /\n * `sse` / `download` / `render` / `problem`) drive, instead of calling Express\n * `res` methods directly (spec §4.3). Sized so `express.Response` satisfies it\n * structurally — under the Express runtime the driver IS the Express response,\n * so there is no wrapping and no behavior change. Other runtimes (Fastify / h3)\n * provide a thin object implementing this over their native reply.\n *\n * The terminal methods return `RuntimeResponse` for fluent chaining (Express's\n * `Response` is assignable, since it is a superset).\n */\nexport interface RuntimeResponse {\n status(code: number): RuntimeResponse\n json(data: unknown): RuntimeResponse\n send(data: unknown): RuntimeResponse\n type(contentType: string): RuntimeResponse\n setHeader(name: string, value: string | number | readonly string[]): unknown\n render(view: string, data?: Record<string, unknown>): unknown\n writeHead(statusCode: number, headers?: Record<string, string>): unknown\n flushHeaders(): unknown\n write(chunk: string | Buffer): boolean\n end(data?: unknown): unknown\n once(event: 'close' | 'drain', listener: () => void): unknown\n readonly headersSent: boolean\n}\n\n// ── Runtime-typed escape hatches (spec §4.3b) ─────────────────────────────\n\n/**\n * Per-runtime type map: the engine-native request / response / app types an\n * `HttpRuntime` exposes through `ctx.req.raw` / `ctx.res.raw` / `AdapterContext.app`.\n */\nexport interface RuntimeTypeMap {\n request: unknown\n response: unknown\n app: unknown\n}\n\n/** The Express runtime's native types — the default when nothing is augmented. */\nexport interface ExpressRuntimeTypes {\n request: ExpressRequest\n response: ExpressResponse\n app: Express\n}\n\n/**\n * Augmentable runtime registry. Empty by default; the `kick/runtime` typegen\n * plugin emits a `{ runtime: <RuntimeTypeMap> }` augmentation from the configured\n * runtime, which flips the engine-native escape-hatch types — `AdapterContext.app`,\n * `getRuntimeApp()`, and (once the driver layer lands) `ctx.req.raw` / `ctx.res.raw`\n * — to that runtime. Mirrors `KickDbRegister` / `KickEnv`, so the type story is\n * uniform with `kick/db` and env typing.\n *\n * @example\n * ```ts\n * // .kickjs/types/kick__runtime.d.ts — generated by typegen\n * declare module '@forinda/kickjs' {\n * interface KickRuntimeRegister {\n * runtime: import('@forinda/kickjs/fastify').FastifyRuntimeTypes\n * }\n * }\n * ```\n */\n\nexport interface KickRuntimeRegister {}\n\n/** The active runtime's type map — the augmented one, or Express by default. */\nexport type ActiveRuntime = KickRuntimeRegister extends { runtime: infer R extends RuntimeTypeMap }\n ? R\n : ExpressRuntimeTypes\n\n/** Options passed to {@link HttpRuntime.createApp}. */\nexport interface RuntimeAppOptions {\n /**\n * Express `trust proxy` setting (and the equivalent on other engines). The\n * function form is Express-specific; other runtimes interpret the simpler\n * shapes (or normalize X-Forwarded-For themselves — see spec §10 Q1).\n */\n trustProxy?: boolean | string | number | string[] | ((ip: string, hopIndex: number) => boolean)\n}\n\n/** Where a connect middleware sits and what it scopes to. */\nexport interface UseConnectOptions {\n path?: string | RegExp | ReadonlyArray<string | RegExp>\n}\n\n/**\n * Optional engine capabilities. Absence means the corresponding `ctx` feature\n * raises a clear error on that runtime rather than failing obscurely.\n */\nexport interface RuntimeCapabilities {\n /** View-engine rendering (`ctx.render`). Express: true; Fastify/h3: false initially. */\n render: boolean\n /** File uploads (`ctx.file` / `@FileUpload`). All engines, different backends. */\n uploads: boolean\n /** Connect-style middleware. Express/Fastify(middie): true; h3: best-effort. */\n connectMiddleware: boolean\n /**\n * The engine parses request bodies itself (Fastify, h3). When true, the\n * Application skips its default `express.json()` so the body stream isn't\n * consumed twice (which would deadlock the engine's own parser). Express:\n * false — it relies on the `express.json()` connect middleware.\n */\n nativeBodyParsing: boolean\n /**\n * The engine's `nodeHandler` works behind `node:http2` (the HTTP/2\n * compatibility API), so `server: { http2: true }` may use it. Fastify/h3:\n * true. Express: false — it does not run on that layer. Absent = false, so\n * custom runtimes opt in explicitly.\n */\n http2?: boolean\n}\n\n/**\n * The engine driver. KickJS owns decorators → {@link RouteTable}, the\n * contributor pipeline, the `RequestContext` surface, and error mapping. The\n * runtime owns app/server creation, route materialization, connect-middleware\n * registration, static serving, and the terminal not-found / error handlers.\n *\n * `expressRuntime()` is the default and the M1 reference implementation.\n */\nexport interface HttpRuntime<TApp = unknown> {\n readonly name: 'express' | 'fastify' | 'h3' | (string & {})\n\n /** Create the engine app. Called once per Application (and per HMR rebuild). */\n createApp(options?: RuntimeAppOptions): TApp\n\n /**\n * Node-compatible request listener — the transport contract.\n * `http.createServer(handler)` in prod, Vite post-middleware in dev. MUST\n * invoke `next` (when given) instead of 404-ing if no route matched — the\n * Vite dev chain depends on fall-through.\n */\n nodeHandler(\n app: TApp,\n ): (req: IncomingMessage, res: ServerResponse, next?: (err?: unknown) => void) => void\n\n /** Materialize the framework-built route table onto the engine. */\n mountRoutes(app: TApp, table: RouteTable): void\n\n /** Register a connect-style middleware (built-ins + adopter middleware). */\n useConnect(app: TApp, mw: ConnectMiddleware, opts?: UseConnectOptions): void\n\n /** Serve a static directory (swagger-ui assets, devtools SPA). */\n serveStatic(app: TApp, prefix: string, dir: string): void\n\n /** Terminal not-found handler. */\n setNotFound(app: TApp, mw: ConnectMiddleware): void\n\n /** Terminal error handler. */\n setErrorHandler(app: TApp, mw: ConnectMiddleware): void\n\n readonly capabilities: RuntimeCapabilities\n}\n\n/**\n * The supported surface adapters use to add HTTP routes, mounts, static dirs,\n * and middleware — engine-agnostic, in place of reaching for the raw Express\n * `app` (spec §4.4). Exposed as {@link AdapterContext.http}. Built by the\n * Application over the active {@link HttpRuntime}, so an adapter written against\n * this works under any runtime; the raw `app` escape hatch stays available for\n * the rare engine-specific need.\n */\nexport interface AdapterHttp {\n /** Register a single context-handler route (e.g. a docs or transport endpoint). */\n route(method: RouteMethod, path: string, handler: CtxHandler): void\n /** Mount a pre-built route table under a path prefix. */\n mount(prefix: string, routes: RouteEntry[]): void\n /** Serve a static directory under a path prefix. */\n serveStatic(prefix: string, dir: string): void\n /** Register a connect-style middleware (optionally path-scoped). */\n use(mw: ConnectMiddleware, opts?: UseConnectOptions): void\n}\n"],"mappings":";;;;;;;;;;oTA0CA,SAAgB,mBAAmB,YAAkC,CAEnE,QADc,MAAM,QAAQ,WAAW,EAAI,YAAY,GAAK,cAC3C,GAAA,CAAI,MAAM,GAAG,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC,YAAY,CACxD,CAaA,SAAS,gBAAgB,UAA4B,CACnD,OAAO,YAAc,oBAAsB,gCAAgC,KAAK,SAAS,CAC3F,CAWA,SAAgB,kBAAkB,YAAoC,CACpE,IAAM,UAAY,mBAAmB,WAAW,EAMhD,OALK,UACD,gBAAgB,SAAS,EAAU,OACnC,YAAc,oCAA4C,aAC1D,UAAU,WAAW,YAAY,EAAU,YAC3C,UAAU,WAAW,OAAO,EAAU,OACnC,cALgB,aAMzB,CASA,MAAa,mBAAqB,CAAC,mBAAoB,oBAAoB,EAG9D,qBAAuB,CAClC,mBACA,qBACA,oCACA,SACA,qBACF,EAcA,SAAgB,0BAA0B,YAAyC,CACjF,IAAM,UAAY,mBAAmB,WAAW,EAChD,OAAO,IAAI,cACT,IACA,UACI,2BAA2B,YAC3B,iEACJ,IAAA,GACA,CAAE,OAAQ,qBAAqB,KAAK,IAAI,CAAE,CAC5C,CACF,CAGA,MAAM,aAAe,IAAI,IAAI,CAAC,OAAQ,MAAO,QAAS,QAAQ,CAAC,EAuB/D,SAAgB,uBAAwB,CACtC,OAAQ,IAAU,KAAe,OAAwC,CAEvE,GADI,CAAC,aAAa,KAAK,IAAI,QAAU,MAAA,CAAO,YAAY,CAAC,GACrD,kBAAkB,IAAI,UAAU,eAAe,IAAM,cAAe,OAAO,KAAK,EAEpF,IAAM,WAAqB,KAAK,0BAA0B,IAAI,UAAU,eAAe,CAAC,EAClF,OAAS,IA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