@forinda/kickjs 10.6.0 → 10.8.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 (189) hide show
  1. package/dist/{adapter-9sPr_5xt.d.mts → adapter-B0Q8PzQ3.d.mts} +13 -7
  2. package/dist/adapter-B0Q8PzQ3.d.mts.map +1 -0
  3. package/dist/{app-module-Cuu-Ma_E.d.mts → app-module-Bk3glnPP.d.mts} +3 -3
  4. package/dist/{app-module-Cuu-Ma_E.d.mts.map → app-module-Bk3glnPP.d.mts.map} +1 -1
  5. package/dist/{application-BD9LQ2s4.d.mts → application-BND5VDje.d.mts} +81 -15
  6. package/dist/application-BND5VDje.d.mts.map +1 -0
  7. package/dist/application-CWPS2sst.mjs +14 -0
  8. package/dist/application-CWPS2sst.mjs.map +1 -0
  9. package/dist/{background-DSztbyc4.mjs → background-D8VpVDrH.mjs} +3 -3
  10. package/dist/{background-DSztbyc4.mjs.map → background-D8VpVDrH.mjs.map} +1 -1
  11. package/dist/{reply-BQTif5Iu.mjs → body-policy-DAoHt4Cr.mjs} +3 -3
  12. package/dist/body-policy-DAoHt4Cr.mjs.map +1 -0
  13. package/dist/{bootstrap-DdTHtS8P.mjs → bootstrap-BpRQ1_KV.mjs} +3 -3
  14. package/dist/{bootstrap-DdTHtS8P.mjs.map → bootstrap-BpRQ1_KV.mjs.map} +1 -1
  15. package/dist/{bounded-counters-Bd7X3eI5.mjs → bounded-counters-BMHzTpuZ.mjs} +2 -2
  16. package/dist/{bounded-counters-Bd7X3eI5.mjs.map → bounded-counters-BMHzTpuZ.mjs.map} +1 -1
  17. package/dist/{cache-C0qL0NSD.d.mts → cache-CdRHSXow.d.mts} +10 -7
  18. package/dist/cache-CdRHSXow.d.mts.map +1 -0
  19. package/dist/{client-ip-DxEVqZP-.mjs → client-ip-COnqHbaF.mjs} +2 -2
  20. package/dist/{client-ip-DxEVqZP-.mjs.map → client-ip-COnqHbaF.mjs.map} +1 -1
  21. package/dist/config/index.d.mts +1 -1
  22. package/dist/config/index.mjs +2 -2
  23. package/dist/{config-_YTqZtnE.mjs → config-Cq6_Qr4r.mjs} +3 -3
  24. package/dist/config-Cq6_Qr4r.mjs.map +1 -0
  25. package/dist/{context-UaQ6cv0K.mjs → context-CX0TLa4H.mjs} +3 -3
  26. package/dist/{context-UaQ6cv0K.mjs.map → context-CX0TLa4H.mjs.map} +1 -1
  27. package/dist/{context-errors-DcPmDybm.mjs → context-errors-Chi6ESHh.mjs} +2 -2
  28. package/dist/{context-errors-DcPmDybm.mjs.map → context-errors-Chi6ESHh.mjs.map} +1 -1
  29. package/dist/{contributor-runner-BHjr6qSE.mjs → contributor-runner-Da7v9Whk.mjs} +3 -3
  30. package/dist/{contributor-runner-BHjr6qSE.mjs.map → contributor-runner-Da7v9Whk.mjs.map} +1 -1
  31. package/dist/core/adapter.d.mts +1 -1
  32. package/dist/core/adapter.mjs +1 -1
  33. package/dist/core/app-module.d.mts +1 -1
  34. package/dist/core/app-module.mjs +1 -1
  35. package/dist/core/cache.d.mts +1 -1
  36. package/dist/core/cache.mjs +2 -2
  37. package/dist/core/cache.mjs.map +1 -1
  38. package/dist/core/container.mjs +2 -2
  39. package/dist/core/cron.mjs +2 -2
  40. package/dist/core/decorators.d.mts +1 -1
  41. package/dist/core/decorators.mjs +2 -2
  42. package/dist/core/decorators.mjs.map +1 -1
  43. package/dist/core/errors.mjs +1 -1
  44. package/dist/core/interfaces.mjs +1 -1
  45. package/dist/core/logger.mjs +1 -1
  46. package/dist/core/path.mjs +1 -1
  47. package/dist/core/plugin.d.mts +1 -1
  48. package/dist/core/plugin.mjs +1 -1
  49. package/dist/core/reactivity.d.mts +2 -2
  50. package/dist/core/reactivity.mjs +2 -2
  51. package/dist/core/reactivity.mjs.map +1 -1
  52. package/dist/core-CiwDroJ7.mjs +12 -0
  53. package/dist/{core-Ddq8b9hi.mjs.map → core-CiwDroJ7.mjs.map} +1 -1
  54. package/dist/{csrf-ZFOrJZhJ.d.mts → csrf-w5bc-PGs.d.mts} +2 -2
  55. package/dist/{csrf-ZFOrJZhJ.d.mts.map → csrf-w5bc-PGs.d.mts.map} +1 -1
  56. package/dist/{decorate-wrAUzCjW.mjs → decorate-DdzHOAA1.mjs} +4 -4
  57. package/dist/{decorate-wrAUzCjW.mjs.map → decorate-DdzHOAA1.mjs.map} +1 -1
  58. package/dist/{decorators-Dvy0JZ5L.d.mts → decorators-DxNb5mWw.d.mts} +15 -2
  59. package/dist/{decorators-Dvy0JZ5L.d.mts.map → decorators-DxNb5mWw.d.mts.map} +1 -1
  60. package/dist/{define-adapter-Ce1FDvEo.mjs → define-adapter-DJnPaqbo.mjs} +2 -2
  61. package/dist/{define-adapter-Ce1FDvEo.mjs.map → define-adapter-DJnPaqbo.mjs.map} +1 -1
  62. package/dist/{di-hooks-MFthA-Fs.mjs → di-hooks-rXw3zCor.mjs} +3 -3
  63. package/dist/{di-hooks-MFthA-Fs.mjs.map → di-hooks-rXw3zCor.mjs.map} +1 -1
  64. package/dist/{disposables-BgUIg4s1.mjs → disposables-Cpde_0BE.mjs} +1 -1
  65. package/dist/{error-handler-CH4PPZCK.d.mts → error-handler-C1I8a4wY.d.mts} +2 -2
  66. package/dist/{error-handler-CH4PPZCK.d.mts.map → error-handler-C1I8a4wY.d.mts.map} +1 -1
  67. package/dist/express-fiMFHEPO.mjs +12 -0
  68. package/dist/express-fiMFHEPO.mjs.map +1 -0
  69. package/dist/{express-lazy-DCYWtKZx.mjs → express-lazy-DxQzDeza.mjs} +3 -3
  70. package/dist/{express-lazy-DCYWtKZx.mjs.map → express-lazy-DxQzDeza.mjs.map} +1 -1
  71. package/dist/handler-D5QS_90y.mjs +12 -0
  72. package/dist/handler-D5QS_90y.mjs.map +1 -0
  73. package/dist/{host-lMSIGnh7.mjs → host-D7vw6t1i.mjs} +2 -2
  74. package/dist/{host-lMSIGnh7.mjs.map → host-D7vw6t1i.mjs.map} +1 -1
  75. package/dist/http/application.d.mts +2 -2
  76. package/dist/http/application.mjs +2 -2
  77. package/dist/http/bootstrap.d.mts +1 -1
  78. package/dist/http/bootstrap.mjs +2 -2
  79. package/dist/http/context.d.mts +2 -2
  80. package/dist/http/context.mjs +2 -2
  81. package/dist/http/middleware/allowed-hosts.mjs +2 -2
  82. package/dist/http/middleware/breach-padding.mjs +1 -1
  83. package/dist/http/middleware/cors.mjs +1 -1
  84. package/dist/http/middleware/csrf.d.mts +1 -1
  85. package/dist/http/middleware/csrf.mjs +2 -2
  86. package/dist/http/middleware/error-handler.d.mts +1 -1
  87. package/dist/http/middleware/error-handler.mjs +2 -2
  88. package/dist/http/middleware/helmet.mjs +1 -1
  89. package/dist/http/middleware/rate-limit.mjs +2 -2
  90. package/dist/http/middleware/request-id.mjs +1 -1
  91. package/dist/http/middleware/request-logger.mjs +2 -2
  92. package/dist/http/middleware/session.mjs +2 -2
  93. package/dist/http/middleware/spa.d.mts +1 -1
  94. package/dist/http/middleware/spa.mjs +2 -2
  95. package/dist/http/middleware/upload.d.mts +2 -2
  96. package/dist/http/middleware/upload.mjs +2 -2
  97. package/dist/http/middleware/upload.mjs.map +1 -1
  98. package/dist/http/middleware/validate.mjs +1 -1
  99. package/dist/http/middleware/views.d.mts +1 -1
  100. package/dist/http/middleware/views.mjs +2 -2
  101. package/dist/http/query/index.mjs +2 -2
  102. package/dist/http/router-builder.d.mts +1 -1
  103. package/dist/http/router-builder.mjs +2 -2
  104. package/dist/http/runtimes/express.d.mts +2 -2
  105. package/dist/http/runtimes/express.d.mts.map +1 -1
  106. package/dist/http/runtimes/express.mjs +2 -2
  107. package/dist/http/runtimes/fastify.d.mts +4 -2
  108. package/dist/http/runtimes/fastify.d.mts.map +1 -1
  109. package/dist/http/runtimes/fastify.mjs +3 -3
  110. package/dist/http/runtimes/fastify.mjs.map +1 -1
  111. package/dist/http/runtimes/h3-web.mjs +1 -1
  112. package/dist/http/runtimes/h3.d.mts +1 -1
  113. package/dist/http/runtimes/h3.mjs +2 -2
  114. package/dist/{index-B4aOLoId.d.mts → index-CNBYZDto.d.mts} +4 -4
  115. package/dist/{index-B4aOLoId.d.mts.map → index-CNBYZDto.d.mts.map} +1 -1
  116. package/dist/index.d.mts +15 -15
  117. package/dist/index.mjs +3 -3
  118. package/dist/index.mjs.map +1 -1
  119. package/dist/{is-production-MYGnN2Nv.mjs → is-production-C7DJ7c5k.mjs} +2 -2
  120. package/dist/{is-production-MYGnN2Nv.mjs.map → is-production-C7DJ7c5k.mjs.map} +1 -1
  121. package/dist/{jobs-ANHUk_Ht.mjs → jobs-Bdqz5n21.mjs} +3 -3
  122. package/dist/{jobs-ANHUk_Ht.mjs.map → jobs-Bdqz5n21.mjs.map} +1 -1
  123. package/dist/{kv-stores-Cro8JwAF.mjs → kv-stores-BM5Fcds2.mjs} +3 -3
  124. package/dist/{kv-stores-Cro8JwAF.mjs.map → kv-stores-BM5Fcds2.mjs.map} +1 -1
  125. package/dist/{kv-stores-C1sQs2Rb.d.mts → kv-stores-CISRYh_H.d.mts} +3 -3
  126. package/dist/{kv-stores-C1sQs2Rb.d.mts.map → kv-stores-CISRYh_H.d.mts.map} +1 -1
  127. package/dist/{lazy-serve-static-Zge6_pKo.mjs → lazy-serve-static-D2pf9ODr.mjs} +3 -3
  128. package/dist/{lazy-serve-static-Zge6_pKo.mjs.map → lazy-serve-static-D2pf9ODr.mjs.map} +1 -1
  129. package/dist/{metadata-_LqQme8p.mjs → metadata-Ck5f9CNm.mjs} +1 -1
  130. package/dist/{observers-Oedvuzit.mjs → observers-BV435fEL.mjs} +2 -2
  131. package/dist/{observers-Oedvuzit.mjs.map → observers-BV435fEL.mjs.map} +1 -1
  132. package/dist/{precompressed-B6wz_5tz.mjs → precompressed-DPESwDxf.mjs} +2 -2
  133. package/dist/{precompressed-B6wz_5tz.mjs.map → precompressed-DPESwDxf.mjs.map} +1 -1
  134. package/dist/{query-KMR84Kwu.mjs → query-Bs9mU4bx.mjs} +2 -2
  135. package/dist/{query-KMR84Kwu.mjs.map → query-Bs9mU4bx.mjs.map} +1 -1
  136. package/dist/{reactivity-BkMNA0kp.d.mts → reactivity-DZrc3Yhu.d.mts} +50 -15
  137. package/dist/reactivity-DZrc3Yhu.d.mts.map +1 -0
  138. package/dist/reply-BmNC0SFg.mjs +12 -0
  139. package/dist/reply-BmNC0SFg.mjs.map +1 -0
  140. package/dist/{request-scope-L71-nmRe.mjs → request-scope-DFf8XH5R.mjs} +3 -3
  141. package/dist/{request-scope-L71-nmRe.mjs.map → request-scope-DFf8XH5R.mjs.map} +1 -1
  142. package/dist/{respond-DR7zkOUf.mjs → respond-DbgwV87J.mjs} +2 -2
  143. package/dist/{respond-DR7zkOUf.mjs.map → respond-DbgwV87J.mjs.map} +1 -1
  144. package/dist/{rolldown-runtime-DouoOEDq.mjs → rolldown-runtime-BIVYCGx6.mjs} +1 -1
  145. package/dist/{route-flag-DCOS_F5A.mjs → route-flag-Dm1NxMbJ.mjs} +3 -3
  146. package/dist/{route-flag-DCOS_F5A.mjs.map → route-flag-Dm1NxMbJ.mjs.map} +1 -1
  147. package/dist/{route-policy-Cy-oSUro.mjs → route-policy-CdBgPlft.mjs} +2 -2
  148. package/dist/{route-policy-Cy-oSUro.mjs.map → route-policy-CdBgPlft.mjs.map} +1 -1
  149. package/dist/{router-builder-U-kiHlqo.mjs → router-builder-BM9t-xGP.mjs} +3 -3
  150. package/dist/router-builder-BM9t-xGP.mjs.map +1 -0
  151. package/dist/{router-builder-BfbEdxew.d.mts → router-builder-CwPowg4s.d.mts} +2 -2
  152. package/dist/{router-builder-BfbEdxew.d.mts.map → router-builder-CwPowg4s.d.mts.map} +1 -1
  153. package/dist/{settings-BnE75hnr.d.mts → settings-BFQisfqG.d.mts} +2 -2
  154. package/dist/{settings-BnE75hnr.d.mts.map → settings-BFQisfqG.d.mts.map} +1 -1
  155. package/dist/{settings-CrEgdXc0.mjs → settings-CPQhWD12.mjs} +3 -3
  156. package/dist/{settings-CrEgdXc0.mjs.map → settings-CPQhWD12.mjs.map} +1 -1
  157. package/dist/token-0ZP--xsp.d.mts +3 -0
  158. package/dist/{token-B1FRPTVt.mjs → token-tL_r-ZPP.mjs} +2 -2
  159. package/dist/{upload-Jgs9BFC4.d.mts → upload-DDDboa_F.d.mts} +3 -3
  160. package/dist/upload-DDDboa_F.d.mts.map +1 -0
  161. package/dist/upload-config-DCm8AFEW.mjs +12 -0
  162. package/dist/upload-config-DCm8AFEW.mjs.map +1 -0
  163. package/dist/{url-for-CLtZIeYd.mjs → url-for-DAVOWiQ_.mjs} +3 -3
  164. package/dist/{url-for-CLtZIeYd.mjs.map → url-for-DAVOWiQ_.mjs.map} +1 -1
  165. package/dist/{web-crypto-B6iM0yYx.mjs → web-crypto-BMaKs6M0.mjs} +2 -2
  166. package/dist/{web-crypto-B6iM0yYx.mjs.map → web-crypto-BMaKs6M0.mjs.map} +1 -1
  167. package/dist/web.d.mts +5 -5
  168. package/dist/web.d.mts.map +1 -1
  169. package/dist/web.mjs +2 -2
  170. package/dist/web.mjs.map +1 -1
  171. package/package.json +2 -2
  172. package/dist/adapter-9sPr_5xt.d.mts.map +0 -1
  173. package/dist/application-BD9LQ2s4.d.mts.map +0 -1
  174. package/dist/application-DwYTFctU.mjs +0 -14
  175. package/dist/application-DwYTFctU.mjs.map +0 -1
  176. package/dist/cache-C0qL0NSD.d.mts.map +0 -1
  177. package/dist/config-_YTqZtnE.mjs.map +0 -1
  178. package/dist/core-Ddq8b9hi.mjs +0 -12
  179. package/dist/express-BcfJgvBP.mjs +0 -12
  180. package/dist/express-BcfJgvBP.mjs.map +0 -1
  181. package/dist/handler-CS1BhG0C.mjs +0 -12
  182. package/dist/handler-CS1BhG0C.mjs.map +0 -1
  183. package/dist/reactivity-BkMNA0kp.d.mts.map +0 -1
  184. package/dist/reply-BQTif5Iu.mjs.map +0 -1
  185. package/dist/router-builder-U-kiHlqo.mjs.map +0 -1
  186. package/dist/token-D6jfTQLA.d.mts +0 -3
  187. package/dist/upload-Jgs9BFC4.d.mts.map +0 -1
  188. package/dist/upload-config-DEnNEwL4.mjs +0 -12
  189. package/dist/upload-config-DEnNEwL4.mjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"handler-CS1BhG0C.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.ts`, node bootstrap) and the\n// `@forinda/kickjs/web` fetch entry (edge/Bun/Deno).\n\nimport { stringifyJson, 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 */\n/** Edge-safe byte length — no `Buffer` on Workers. */\nconst utf8 = new TextEncoder()\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(stringifyJson(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 /** What `setHeader` recorded — `Set-Cookie` as its list, like node's `res.getHeader`. */\n getHeader(name: string): string | string[] | undefined {\n if (name.toLowerCase() === 'set-cookie') {\n const cookies = this.headers.getSetCookie()\n return cookies.length > 0 ? cookies : undefined\n }\n return this.headers.get(name) ?? undefined\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 // A buffered body has a known length: say so, as the node runtimes do —\n // no chunked encoding for a small reply, and middleware that decides by\n // size (compression's threshold) can see it.\n if (bodyAllowed && body != null && !this.headers.has('content-length')) {\n const length = typeof body === 'string' ? utf8.encode(body).byteLength : body.byteLength\n this.headers.set('content-length', String(length))\n }\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 {\n DEFAULT_BODY_LIMIT,\n classifyMediaType,\n parseByteSize,\n parseForm,\n readBodyText,\n unsupportedMediaTypeError,\n} 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 { errorHandler, notFoundHandler } from '../middleware/error-handler'\n\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 * The request object the app's connect middleware wrote to — the node\n * `req` behind a node server, the per-event shim on the fetch path.\n * Whatever it set (`session`, `user`, `requestId`, an adapter's symbol)\n * reads through on the route's request.\n */\n carry?: object\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// The same handlers Express and Fastify answer with, so an error or a request\n// nothing answered has one shape on every engine: RFC 9457 problem details,\n// the error's own headers, `requestId` on a 500.\nconst builtInError = errorHandler()\nconst builtInNotFound = notFoundHandler()\n\nfunction decodeParams(params: Record<string, string>): Record<string, string> {\n const decoded: Record<string, string> = {}\n for (const key in params) {\n const value = params[key]\n decoded[key] = value.includes('%') ? decodeURIComponent(value) : value\n }\n return decoded\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 */\n/**\n * The route's request, with anything it does not set itself read from\n * `carry` — the object connect middleware wrote to. Writes stay on the route's\n * own request. A declared-but-unset field (`requestId`) counts as not set.\n */\nexport function readThrough(shim: WebRequestShim, carry: object): WebRequestShim {\n return new Proxy(shim, {\n get(target, prop, receiver) {\n const own = Reflect.get(target, prop, receiver)\n return own !== undefined ? own : Reflect.get(carry, prop, carry)\n },\n has(target, prop) {\n return Reflect.has(target, prop) || Reflect.has(carry, prop)\n },\n })\n}\n\nexport function compileWebRoute(\n entry: RouteEntry,\n hooks?: WebRouteHooks,\n options: { bodyLimit?: number } = {},\n): (invocation: WebRouteInvocation) => Promise<Response> {\n const bodyLimit = options.bodyLimit ?? parseByteSize(DEFAULT_BODY_LIMIT)\n const validator = entry.meta.validation\n ? validate(entry.meta.validation, { validationError: entry.validationError })\n : undefined\n const upload = entry.meta.upload && entry.meta.upload.mode !== 'none' ? entry.meta.upload : null\n\n return async ({ request, url, params, carry }) => {\n const shim = new WebRequestShim(request, url)\n const req = carry ? readThrough(shim, carry) : shim\n let bodyError: unknown\n // h3 hands params over still percent-encoded; Express and Fastify decode\n // them, so `/users/a%20b` must reach the handler as `'a b'` here too.\n try {\n req.params = decodeParams(params)\n } catch {\n req.params = params\n bodyError = HttpException.badRequest('Malformed URL parameter')\n }\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 // A real Buffer where the runtime has one (Node, Bun, Deno), so\n // `file.buffer.toString()` is the content as on every other\n // engine — a bare Uint8Array stringifies as \"80,78,71,…\".\n buffer: (typeof Buffer === 'function'\n ? Buffer.from(await value.arrayBuffer())\n : new Uint8Array(await value.arrayBuffer())) as unknown as Buffer,\n })\n }\n }\n req.body = fields\n // A refused type (415) or an oversized file (413) is held like a parse\n // failure — thrown before the driver exists, it would escape the\n // route and reach the client as the host's bare error, not kick's.\n try {\n const { file, files } = applyUploadConfig(rawParts, entry.meta.upload!)\n req.file = file\n req.files = files\n } catch (err) {\n bodyError = err\n }\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 // Past the limit is a 413, held like a parse failure below.\n let raw = ''\n try {\n raw = await readBodyText(request, bodyLimit)\n } catch (err) {\n if (err instanceof HttpException) bodyError = err\n }\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 = parseForm(raw)\n } else {\n req.body = raw\n }\n }\n }\n\n // Reuse the id `requestId()` middleware already gave the request, so the\n // response header, the route's ctx and observers agree on one id.\n const store = createRequestStore(req.requestId || 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 // Middleware that reports after the response (observers, request logger)\n // reads the route off the request it was handed — the carried one.\n if (carry) publishMatchedRoute(carry, 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) await 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) await builtInError(err, req, driver, NOOP_NEXT)\n }\n }\n if (!driver.settled) {\n // Pipeline finished without responding — the catch-all's 404.\n builtInNotFound(req, driver, NOOP_NEXT)\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":";;;;;;;;;;6oBAgBA,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,CAAE,KAAM,EAAK,CAAC,EAC9E,IACT,CAGA,GAAG,MAAe,SAA4B,CAC5C,OAAO,KAAK,KAAK,MAAO,QAAQ,CAClC,CACF,EAEA,MAAM,QAAU,IAAI,YAEpB,SAAS,QAAQ,MAA4B,CAE3C,OADI,iBAAiB,WAAmB,MACjC,QAAQ,OAAO,OAAO,KAAK,CAAC,CACrC,CAiBA,MAAM,KAAO,IAA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K,IAAK,MAAM,EACnD,OAAO,SAAS,MAAM,aAAa,IAAK,IAAK,OAAQ,SAAS,EAEvE,CAKA,OAJK,OAAO,SAEV,gBAAgB,IAAK,OAAQ,SAAS,EAEjC,MAAM,OAAO,KACtB,QAAU,CAIR,QAAa,QAAQ,QAAQ,CAAC,CAC3B,UAAY,CAAC,CAAC,CAAC,CACf,SAAW,oBAAoB,KAAK,CAAC,CAC1C,CACF,CACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"reactivity-BkMNA0kp.d.mts","names":[],"sources":["../src/core/reactivity.ts"],"mappings":";;;;;;;UAgFiB,IAAI;EACnB,OAAO;;EAEP,UAAU,KAAK,UAAU,GAAG,UAAU;;;;;;;EAOtC,UAAU;;;;;;;;;;;;iBAaI,IAAI,GAAG,cAAc,IAAI,IAAI;UAuC5B,YAAY;WAClB,OAAO;;;;;;EAMhB,UAAU;;;;;;;;;EASV;;;;;;;;;;;;;;iBAec,SAAS,GAAG,cAAc,IAAI,YAAY;UA4DzC;;EAEf;;KAGG,YAAY,KAAK,IAAI,KAAK,YAAY,YAAY;;;;;;;;;;;;;;;iBAgBvC,MAAM,GACpB,QAAQ,YAAY,IACpB,WAAW,UAAU,GAAG,UAAU,YAClC,UAAU;iBAwDI,SAAS,UAAU,qBAAqB,QAAQ,IAAI;;iBA8BpD,MAAM,aAAa,SAAS;;iBAK5B,MAAM,GAAG,OAAO,IAAI,KAAK,IAAI;;iBAK7B,OAAO,UAAU,qBAAqB,KAAK,OAAO,WAAW,IAAI,IAAI,EAAE"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"reply-BQTif5Iu.mjs","names":[],"sources":["../src/http/body-policy.ts","../src/http/reply.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 * Set to `true` on a request (`req[RAW_BODY] = true`) by middleware that will\n * read the body stream itself — a tus endpoint, a proxy — so the 415 below\n * leaves it alone. Mark it in an earlier phase (an adapter's `beforeGlobal`),\n * consume it later.\n */\nexport const RAW_BODY = Symbol.for('kick/http/raw-body')\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 (req[RAW_BODY]) 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\n/** Default body size limit — Express's `express.json()` default. */\nexport const DEFAULT_BODY_LIMIT = '1mb'\n\nconst BYTE_UNITS: Record<string, number> = { b: 1, kb: 1024, mb: 1024 ** 2, gb: 1024 ** 3 }\n\n/**\n * `'1mb'` / `'512kb'` / `1048576` → bytes, the forms `express.json({ limit })`\n * accepts (1024-based, like the `bytes` package Express uses), so one\n * `jsonLimit` means the same size on every engine.\n */\nexport function parseByteSize(value: string | number): number {\n if (typeof value === 'number') return value\n const match = /^\\s*(\\d+(?:\\.\\d+)?)\\s*(b|kb|mb|gb)?\\s*$/i.exec(value)\n if (!match) throw new Error(`Invalid body size limit: '${value}'`)\n return Math.floor(Number(match[1]) * BYTE_UNITS[(match[2] ?? 'b').toLowerCase()])\n}\n\nfunction tooLarge(limit: number): HttpException {\n return new HttpException(413, `Request body is larger than the ${limit}-byte limit`)\n}\n\n/**\n * Read a web `Request` body as text, refusing more than `limit` bytes with a\n * 413 — from `Content-Length` before reading, and while streaming for a body\n * that doesn't declare one (or declares less than it sends).\n */\nexport async function readBodyText(request: Request, limit: number): Promise<string> {\n const declared = Number(request.headers.get('content-length'))\n if (declared > limit) throw tooLarge(limit)\n if (!request.body) return ''\n\n const reader = request.body.getReader()\n const decoder = new TextDecoder()\n let size = 0\n let text = ''\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n size += value.byteLength\n if (size > limit) {\n await reader.cancel().catch(() => {})\n throw tooLarge(limit)\n }\n text += decoder.decode(value, { stream: true })\n }\n return text + decoder.decode()\n}\n\n/**\n * `application/x-www-form-urlencoded` → object, with a repeated key becoming\n * an array — the same rule the query string follows on every engine, and\n * what Express's form parser does.\n */\nexport function parseForm(raw: string): Record<string, string | string[]> {\n // A Map, then fromEntries: assigning keys onto a plain object would let a\n // `__proto__` field set the result's prototype.\n const fields = new Map<string, string | string[]>()\n for (const [key, value] of new URLSearchParams(raw)) {\n const prev = fields.get(key)\n if (prev === undefined) fields.set(key, value)\n else if (Array.isArray(prev)) prev.push(value)\n else fields.set(key, [prev, value])\n }\n return Object.fromEntries(fields)\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 /** Response headers set before the body is sent. */\n readonly headers?: ReplyHeaders\n}\n\n/** Header name → value, as `ctx.setHeader` takes them. */\nexport type ReplyHeaders = Readonly<Record<string, string | number | readonly string[]>>\n\n/** Options for {@link reply}. */\nexport interface ReplyOptions {\n /** Response headers set before the body is sent. */\n headers?: ReplyHeaders\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 *\n * `options.headers` are set on the response before it is sent:\n * `reply(202, job, { headers: { 'Retry-After': 5 } })`.\n */\nexport function reply<S extends number, T>(\n status: S,\n body: T,\n options?: ReplyOptions,\n): Reply<S, T> {\n return options?.headers\n ? { [REPLY_BRAND]: true, status, body, headers: options.headers }\n : { [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/**\n * `reply(201, body)`. `location` sets the `Location` header — where the new\n * resource lives, usually built with `ctx.urlFor()`:\n *\n * ```ts\n * const task = await this.tasks.create(ctx.body)\n * return reply.created(task, { location: ctx.urlFor('TaskController.getById', { id: task.id }) })\n * ```\n */\nreply.created = <T>(body: T, options?: ReplyOptions & { location?: string }): Reply<201, T> =>\n reply(\n 201,\n body,\n options?.location === undefined\n ? options\n : { headers: { ...options.headers, Location: options.location } },\n )\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 * Key of the method a self-sending result carries. A returned value with\n * `[RESPOND](ctx)` writes its own response — how an integration (an Inertia\n * page, a rendered view) works as a return value without the framework\n * knowing its format. Registry symbol, so a second copy of the package still\n * matches.\n */\nexport const RESPOND: unique symbol = Symbol.for('kickjs.respond') as never\n\n/** A handler return value that writes its own response. */\nexport interface Respondable {\n [RESPOND](ctx: RequestContext): void | PromiseLike<void>\n}\n\nexport function isRespondable(value: unknown): value is Respondable {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as Record<symbol, unknown>)[RESPOND] === 'function'\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 * - `Respondable` → its `[RESPOND](ctx)` writes the response (may be async)\n * - `Reply` wrapper → status + body (204 → `ctx.noContent()`)\n * - anything else → `ctx.json(value)` (200)\n *\n * Returns true when a response was produced — a promise of it for an async\n * `Respondable`, which callers await so its errors reach the error handler.\n */\nexport function applyHandlerResult(\n ctx: RequestContext,\n result: unknown,\n): boolean | Promise<boolean> {\n if (result === undefined) return false\n if (isRespondable(result)) {\n const sent: unknown = result[RESPOND](ctx)\n // Any thenable, not `instanceof Promise` — a promise from another realm\n // (a VM context, an iframe-like runtime) fails that check.\n return typeof (sent as PromiseLike<void> | undefined)?.then === 'function'\n ? Promise.resolve(sent).then(() => true)\n : true\n }\n if (isReply(result)) {\n if (result.headers) {\n for (const [name, value] of Object.entries(result.headers)) ctx.setHeader(name, value)\n }\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"],"mappings":";;;;;;;;;;6CA0CA,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,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ACP,KAET,IAAI,KAAK,OAAO,KAAM,OAAO,MAAM,EAC5B,GACT,CAEA,OADA,IAAI,KAAK,MAAM,EACR,EACT"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"router-builder-U-kiHlqo.mjs","names":[],"sources":["../src/core/contributor-pipeline.ts","../src/http/router-builder.ts"],"sourcesContent":["import type { AnyContributorRegistration } from './context-decorator'\nimport {\n ContributorCycleError,\n DuplicateContributorError,\n MissingContributorError,\n} from './context-errors'\n\n/**\n * Where a contributor was registered, ordered by precedence\n * (lower index wins). Mirrors `architecture.md` §20.4.\n *\n * Levels (highest → lowest precedence):\n * - `'method'` — `@LoadX` on a controller method.\n * - `'class'` — `@LoadX` on a controller class.\n * - `'module'` — returned by `AppModule.contributors?()`. Per-module scope.\n * - `'adapter'` — returned by `AppAdapter.contributors?()`. Cross-cutting, applies\n * to every module's routes.\n * - `'global'` — `ApplicationOptions.contributors`. App-wide default.\n */\nexport type ContributorSource = 'method' | 'class' | 'module' | 'adapter' | 'global'\n\n/** Precedence-ranked source list. Index = precedence; method (0) wins ties. */\nconst PRECEDENCE_ORDER: readonly ContributorSource[] = [\n 'method',\n 'class',\n 'module',\n 'adapter',\n 'global',\n]\n\n/**\n * Input row to {@link buildPipeline}. Pairs a registration with its origin\n * so dedup can apply the precedence rule and diagnostic errors can name\n * the offending site.\n *\n * `registration` is the type-erased {@link AnyContributorRegistration}\n * — the runner doesn't care about each registration's narrow `D` /\n * `Ctx` shape, and adopters frequently mix HTTP / transport-agnostic\n * contributors in the same `externalSources` / `contributors()`\n * array. The narrow generics from `defineContextDecorator` survive\n * at the *definition* site (where `resolve` is typed); they're erased\n * here so collections compose without `as any` casts.\n */\nexport interface SourcedRegistration {\n registration: AnyContributorRegistration\n source: ContributorSource\n /** Human label surfaced in DuplicateContributorError messages. */\n label?: string\n}\n\n/**\n * Resolved, validated, topo-sorted pipeline ready for execution.\n *\n * `contributors` is in execution order — every entry's `dependsOn`\n * keys appear earlier. `keys` is the set of all keys this pipeline\n * produces; the runner uses it for fast existence checks and the\n * builder uses it for missing-dep validation.\n */\nexport interface ContributorPipeline {\n readonly contributors: readonly AnyContributorRegistration[]\n readonly keys: ReadonlySet<string>\n}\n\nexport interface BuildPipelineOptions {\n /** Optional route identifier surfaced in diagnostic errors (e.g., 'GET /projects/:id'). */\n route?: string\n}\n\n/**\n * Build, validate, and topo-sort a contributor pipeline.\n *\n * Pipeline:\n *\n * 1. Group sources by precedence (method > class > module > adapter > global).\n * 2. Within each precedence level, two contributors with the same `key`\n * raise {@link DuplicateContributorError}.\n * 3. Across levels, the highest-precedence contributor wins each key\n * (lower-precedence duplicates are silently dropped — that is the\n * documented override mechanism, not an error).\n * 4. Every key referenced by `dependsOn` must be produced by the\n * surviving set, otherwise {@link MissingContributorError}.\n * 5. Kahn's algorithm topo-sorts the survivors. Any nodes left after\n * the queue drains form a cycle → {@link ContributorCycleError}\n * with a reconstructed path.\n *\n * Pure function — no DI, no I/O. Safe to call once at startup per\n * route and cache the result.\n */\nexport function buildPipeline(\n sources: readonly SourcedRegistration[],\n options: BuildPipelineOptions = {},\n): ContributorPipeline {\n const route = options.route\n\n // Step 1: group by source.\n const bySource = new Map<ContributorSource, SourcedRegistration[]>()\n for (const src of PRECEDENCE_ORDER) bySource.set(src, [])\n for (const entry of sources) bySource.get(entry.source)!.push(entry)\n\n // Step 2 + 3: dedup with precedence. We walk highest precedence first,\n // claim its keys, and drop lower-precedence rows that conflict.\n const winners = new Map<string, SourcedRegistration>()\n for (const src of PRECEDENCE_ORDER) {\n const rows = bySource.get(src)!\n const keysAtThisLevel = new Map<string, SourcedRegistration[]>()\n for (const row of rows) {\n const key = row.registration.key\n const existing = keysAtThisLevel.get(key) ?? []\n existing.push(row)\n keysAtThisLevel.set(key, existing)\n }\n for (const [key, rowsForKey] of keysAtThisLevel) {\n if (rowsForKey.length > 1) {\n const labels = rowsForKey.map((r, i) => r.label ?? `${src}#${i}`)\n throw new DuplicateContributorError(key, labels)\n }\n if (!winners.has(key)) winners.set(key, rowsForKey[0])\n }\n }\n\n const survivors = [...winners.values()].map((r) => r.registration)\n const allKeys = new Set(survivors.map((r) => r.key))\n\n // Step 4: dependsOn validation.\n for (const reg of survivors) {\n for (const dep of reg.dependsOn) {\n if (!allKeys.has(dep)) {\n throw new MissingContributorError(dep, reg.key, route, reg.definedAt)\n }\n }\n }\n\n // Step 5: Kahn topo-sort.\n const sorted = topoSort(survivors, route)\n\n return Object.freeze({\n contributors: Object.freeze(sorted),\n keys: allKeys,\n })\n}\n\n/**\n * Split a built pipeline into the contributors that run before request\n * validation (`beforeValidation: true`) and the rest, which keep their place\n * after `@Middleware()`. Both halves stay in topo order.\n *\n * An early contributor can only depend on other early ones — its dependency\n * would not have run yet otherwise — so that fails here, at boot.\n */\nexport function splitBeforeValidation(\n pipeline: ContributorPipeline,\n route?: string,\n): { early: ContributorPipeline | null; late: ContributorPipeline | null } {\n const early = pipeline.contributors.filter((reg) => reg.beforeValidation)\n if (early.length === 0) return { early: null, late: pipeline }\n\n const earlyKeys = new Set(early.map((reg) => reg.key))\n for (const reg of early) {\n const lateDep = reg.dependsOn.find((dep) => !earlyKeys.has(dep))\n if (lateDep !== undefined) {\n throw new Error(\n `Contributor '${reg.key}'${route ? ` on ${route}` : ''} sets beforeValidation but ` +\n `depends on '${lateDep}', which runs after validation. Set beforeValidation on ` +\n `'${lateDep}' too, or remove it from '${reg.key}'.`,\n )\n }\n }\n\n const late = pipeline.contributors.filter((reg) => !reg.beforeValidation)\n return {\n early: Object.freeze({ contributors: Object.freeze(early), keys: earlyKeys }),\n late:\n late.length === 0\n ? null\n : Object.freeze({\n contributors: Object.freeze(late),\n keys: new Set(late.map((reg) => reg.key)),\n }),\n }\n}\n\n/**\n * Kahn's algorithm with deterministic ordering on ties.\n *\n * Nodes with no remaining incoming edges enter the queue in input\n * order. Cycles surface as nodes still present after the queue\n * drains; we reconstruct one cycle path for diagnostics.\n */\nfunction topoSort(\n registrations: readonly AnyContributorRegistration[],\n route: string | undefined,\n): AnyContributorRegistration[] {\n // indegree[key] = number of unresolved dependsOn entries for key\n const indegree = new Map<string, number>()\n // dependents[depKey] = list of registrations that depend on depKey\n const dependents = new Map<string, AnyContributorRegistration[]>()\n const byKey = new Map<string, AnyContributorRegistration>()\n\n for (const reg of registrations) {\n indegree.set(reg.key, reg.dependsOn.length)\n byKey.set(reg.key, reg)\n }\n for (const reg of registrations) {\n for (const dep of reg.dependsOn) {\n const list = dependents.get(dep) ?? []\n list.push(reg)\n dependents.set(dep, list)\n }\n }\n\n // Initial queue: registrations with zero indegree, preserving input order.\n const queue: AnyContributorRegistration[] = []\n for (const reg of registrations) {\n if (indegree.get(reg.key) === 0) queue.push(reg)\n }\n\n const sorted: AnyContributorRegistration[] = []\n while (queue.length > 0) {\n const node = queue.shift()!\n sorted.push(node)\n for (const dependent of dependents.get(node.key) ?? []) {\n const next = (indegree.get(dependent.key) ?? 0) - 1\n indegree.set(dependent.key, next)\n if (next === 0) queue.push(dependent)\n }\n }\n\n if (sorted.length !== registrations.length) {\n const remaining = registrations.filter((r) => (indegree.get(r.key) ?? 0) > 0)\n throw new ContributorCycleError(reconstructCycle(remaining, byKey), route)\n }\n\n return sorted\n}\n\n/**\n * Reconstruct one cycle path from the residual graph.\n *\n * Walks from any remaining node, following its first dependency that's\n * still in the residual set, until we revisit a node. The path returned\n * starts and ends with the same key so the message reads naturally:\n * `tenant → project → tenant`.\n */\nfunction reconstructCycle(\n residual: readonly AnyContributorRegistration[],\n byKey: ReadonlyMap<string, AnyContributorRegistration>,\n): string[] {\n const residualKeys = new Set(residual.map((r) => r.key))\n const start = residual[0].key\n const path: string[] = [start]\n const seen = new Set<string>([start])\n let cursor: string = start\n\n while (true) {\n const reg = byKey.get(cursor)!\n const nextDep = reg.dependsOn.find((d) => residualKeys.has(d))\n if (nextDep === undefined) break\n if (seen.has(nextDep)) {\n // Trim the prefix that isn't part of the cycle.\n const cycleStart = path.indexOf(nextDep)\n return [...path.slice(cycleStart), nextDep]\n }\n path.push(nextDep)\n seen.add(nextDep)\n cursor = nextDep\n }\n\n // Fallback — couldn't reconstruct a strict cycle, return what we walked.\n return path\n}\n","// Concrete-module imports (NOT the `../core` barrel): the barrel re-exports\n// the asset manager, whose eager `node:fs` import would poison the edge-safe\n// `@forinda/kickjs/web` entry graph that flows through this file.\nimport {\n buildPipeline,\n splitBeforeValidation,\n type SourcedRegistration,\n} from '../core/contributor-pipeline'\nimport { runContributors } from '../core/contributor-runner'\nimport { Container } from '../core/container'\nimport { METADATA } from '../core/interfaces'\nimport type { ContributorRegistration } from '../core/context-decorator'\nimport type { FileUploadConfig, MiddlewareHandler, RouteDefinition } from '../core/decorators'\nimport { getClassMeta, getMethodMeta, getMethodMetaOrUndefined } from '../core/metadata'\nimport {\n getClassFlagDeclarations,\n getMethodFlagDeclarations,\n registerMountFlags,\n resolveRouteFlags,\n toFlagDeclarations,\n type RouteFlagDeclarations,\n} from '../core/route-flag'\nimport { duplicateRouteError } from '../core/kick-errors'\nimport type { CtxHandler, RouteContributor, RouteEntry, RouteMethod } from './runtime'\n\n/**\n * Per-module SourcedRegistration[] threaded through the route-mount loop by\n * Application.setup(). Carries module + adapter + global contributors so\n * buildRouteTable() can merge them with class + method ones into a single pipeline.\n *\n * Module setup is sequential, so this slot is race-free. Cleared in a finally\n * block after each module mounts. Outside of Application setup the slot is\n * empty — direct buildRouteTable()/buildRoutes() callers (mostly tests) see only\n * class + method contributors unless they pass `externalSources` explicitly.\n *\n * Same idiom as `Container._requestStoreProvider`: an internal escape hatch for\n * cross-module wiring without inversion-of-control gymnastics.\n *\n * @internal\n */\nlet _externalContributorSources: readonly SourcedRegistration[] = []\n\n/** @internal — set by Application.setup() before each `mod.routes()` call. */\nexport function _setExternalContributorSources(sources: readonly SourcedRegistration[]): void {\n _externalContributorSources = sources\n}\n\n/**\n * Boot-time duplicate-route guard shared by the node and web mount loops.\n *\n * Registers `METHOD /mounted/path` into `registry` and throws\n * {@link duplicateRouteError} (KICK006) if another handler already claimed\n * it. Param *names* are ignored — `/tasks/:id` and `/tasks/:taskId` are the\n * same route at dispatch time, so they collide here too.\n *\n * @internal\n */\nexport function assertRouteUnique(\n registry: Map<string, string>,\n method: string,\n fullPath: string,\n owner: string,\n): void {\n const key = `${method.toUpperCase()} ${fullPath.replace(/:[^/]+/g, ':*')}`\n const prior = registry.get(key)\n if (prior !== undefined) {\n throw duplicateRouteError(method.toUpperCase(), fullPath, owner, prior)\n }\n registry.set(key, owner)\n}\n\nexport interface BuildRoutesOptions {\n /**\n * Extra contributors to merge into the per-route pipeline at their declared\n * precedence levels. Pass explicitly when calling buildRouteTable/buildRoutes\n * outside the Application route-mount loop (typically in tests). When omitted,\n * falls back to the slot set by Application.setup().\n */\n externalSources?: readonly SourcedRegistration[]\n /**\n * Flags the mounting module declares for every route on this controller\n * (`ModuleRoutes.flags`). Lowest precedence — a class or method declaration\n * of the same name wins, and `@Flag.off` on a method removes it.\n */\n mountFlags?: RouteFlagDeclarations\n}\n\n/**\n * Turn a controller class decorated with @Get, @Post, etc. into a plain-data\n * {@link RouteEntry}[] — the engine-neutral route table an {@link HttpRuntime}\n * materializes.\n *\n * What used to be per-handler Express `(req, res, next)` closures is now\n * captured as data: `middlewares` keep their `(ctx, next)` shape, the contributor\n * pipeline is pre-built into a `contributorRunner` closure, validation / upload\n * stay as metadata, and the terminal `handler` resolves the controller per-request\n * (to respect DI scoping) and invokes it. The runtime owns how these get wrapped\n * onto its engine.\n *\n * Routes use only the method-level decorator paths (e.g. @Get('/me') → '/me').\n * The @Controller path is NOT baked in — it is metadata for Swagger/introspection.\n * The module's routes().path is the single source of truth for the mount prefix,\n * which avoids path doubling when both the module and controller specify the path.\n *\n * The contributor pipeline is built here, so a cycle or missing `dependsOn`\n * throws at table-build time (boot) rather than on first request.\n */\nexport function buildRouteTable(\n controllerClass: any,\n options: BuildRoutesOptions = {},\n): RouteEntry[] {\n const container = Container.getInstance()\n const externalSources = options.externalSources ?? _externalContributorSources\n const routes: RouteDefinition[] = getClassMeta<RouteDefinition[]>(\n METADATA.ROUTES,\n controllerClass,\n [],\n )\n\n // Class-level middleware\n const classMiddlewares: MiddlewareHandler[] = getClassMeta<MiddlewareHandler[]>(\n METADATA.CLASS_MIDDLEWARES,\n controllerClass,\n [],\n )\n\n // Class-level Context Contributors (#107) — applied to every method on the\n // controller. Method-level contributors are added per-route below.\n const classContributors: ContributorRegistration[] = getClassMeta<ContributorRegistration[]>(\n METADATA.CLASS_CONTRIBUTORS,\n controllerClass,\n [],\n )\n\n // Route flags declared on the controller — inherited by every method below\n // unless a method declares the same flag `false` (see core/route-flag.ts).\n const classFlagDeclarations = getClassFlagDeclarations(controllerClass)\n\n // Flags the module declared for this whole mount. Recorded against the class\n // so `getRouteFlags()` — the resolver Swagger and DevTools use, which sees no\n // mount — reports what the runtime actually resolved.\n const mountFlagDeclarations = toFlagDeclarations(\n options.mountFlags,\n `${controllerClass?.name ?? 'controller'} mount flags`,\n )\n registerMountFlags(controllerClass, mountFlagDeclarations)\n\n const entries: RouteEntry[] = []\n\n for (const route of routes) {\n const method = route.method.toUpperCase() as RouteMethod\n const fullPath = route.path || '/'\n\n // Method-level middleware\n const methodMiddlewares: MiddlewareHandler[] = getMethodMeta<MiddlewareHandler[]>(\n METADATA.METHOD_MIDDLEWARES,\n controllerClass,\n route.handlerName,\n [],\n )\n\n // @FileUpload decorator — runtime supplies the upload backend.\n const fileUploadConfig = getMethodMetaOrUndefined<FileUploadConfig>(\n METADATA.FILE_UPLOAD,\n controllerClass,\n route.handlerName,\n )\n\n // Context Contributor pipeline (#107) — class + method contributors,\n // built once at mount time so cycle/missing-dep failures abort boot.\n const methodContributors: ContributorRegistration[] = getMethodMeta<ContributorRegistration[]>(\n METADATA.METHOD_CONTRIBUTORS,\n controllerClass,\n route.handlerName,\n [],\n )\n\n // Flags in force for THIS route: class declarations overridden by method\n // ones. Resolved at build time so the per-request cost is a map lookup.\n const flags = resolveRouteFlags(\n classFlagDeclarations,\n getMethodFlagDeclarations(controllerClass, route.handlerName),\n mountFlagDeclarations,\n )\n\n let contributorRunner: CtxHandler | null = null\n let earlyContributorRunner: CtxHandler | null = null\n let contributors: RouteContributor[] | undefined\n if (\n classContributors.length > 0 ||\n methodContributors.length > 0 ||\n externalSources.length > 0\n ) {\n // Labels are surfaced in DuplicateContributorError messages — include\n // the registration's key + the original index so a same-key collision\n // at one precedence level points at the conflicting decorator slot,\n // not just the host method/class.\n const sources: SourcedRegistration[] = [\n ...methodContributors.map((registration, i): SourcedRegistration => ({\n source: 'method',\n registration,\n label: `${controllerClass.name}.${String(route.handlerName)}#${i}(${registration.key})`,\n })),\n ...classContributors.map((registration, i): SourcedRegistration => ({\n source: 'class',\n registration,\n label: `${controllerClass.name}.@class#${i}(${registration.key})`,\n })),\n ...externalSources,\n ]\n const routeLabel = `${method} ${fullPath}`\n const pipeline = buildPipeline(sources, { route: routeLabel })\n contributors = describePipeline(pipeline.contributors, sources)\n const { early, late } = splitBeforeValidation(pipeline, routeLabel)\n if (early) {\n earlyContributorRunner = (ctx) =>\n runContributors({ pipeline: early, ctx, container, flags })\n }\n if (late) {\n contributorRunner = (ctx) => runContributors({ pipeline: late, ctx, container, flags })\n }\n }\n\n // Terminal handler — resolve controller per-request to respect DI scoping.\n const handler: CtxHandler = (ctx) => container.resolve(controllerClass)[route.handlerName](ctx)\n\n entries.push({\n method,\n path: fullPath,\n middlewares: [...classMiddlewares, ...methodMiddlewares],\n contributorRunner,\n earlyContributorRunner,\n handler,\n meta: {\n controller: controllerClass,\n handlerName: route.handlerName,\n validation: route.validation,\n upload: fileUploadConfig,\n flags,\n ...(contributors ? { contributors } : {}),\n },\n })\n }\n\n return entries\n}\n\n/**\n * The pipeline as introspection shows it. The built pipeline keeps only the\n * registrations; their sources and labels are recovered from the inputs by\n * identity, along with the lower-precedence registrations each one replaced.\n */\nfunction describePipeline(\n ordered: readonly SourcedRegistration['registration'][],\n sources: readonly SourcedRegistration[],\n): RouteContributor[] {\n const bySource = new Map(sources.map((s) => [s.registration, s]))\n // Execution order: the pipeline is split at run time — `beforeValidation`\n // ones run first, ahead of middleware and validation, then the rest. Each\n // half keeps its dependency order.\n const runOrder = [\n ...ordered.filter((r) => r.beforeValidation === true),\n ...ordered.filter((r) => r.beforeValidation !== true),\n ]\n return runOrder.map((registration) => {\n const winner = bySource.get(registration)\n const described: RouteContributor = {\n key: registration.key,\n source: winner?.source ?? 'global',\n dependsOn: registration.dependsOn,\n beforeValidation: registration.beforeValidation === true,\n overrides: sources\n .filter((s) => s.registration !== registration && s.registration.key === registration.key)\n .map((s) => (s.label ? { source: s.source, label: s.label } : { source: s.source })),\n }\n if (winner?.label) described.label = winner.label\n return described\n })\n}\n"],"mappings":";;;;;;;;;;+mBAsBA,MAAM,iBAAiD,CACrD,SACA,QACA,SACA,UACA,QACF,EA4DA,SAAgB,cACd,QACA,QAAgC,CAAC,EACZ,CACrB,IAAM,MAAQ,QAAQ,MAGhB,yBAAW,IAAI,IACrB,IAAK,IAAM,OAAO,iBAAkB,SAAS,IAAI,IAAK,CAAC,CAAC,EACxD,IAAK,IAAM,SAAS,QAAS,SAAS,IAAI,MAAM,MAAM,CAAC,CAAE,KAAK,KAAK,EAInE,IAAM,wBAAU,IAAI,IACpB,IAAK,IAAM,OAAO,iBAAkB,CAClC,IAAM,KAAO,SAAS,IAAI,GAAG,EACvB,gCAAkB,IAAI,IAC5B,IAAK,IAAM,OAAO,KAAM,CACtB,IAAM,IAAM,IAAI,aAAa,IACvB,SAAW,gBAAgB,IAAI,GAAG,GAAK,CAAC,EAC9C,SAAS,KAAK,GAAG,EACjB,gBAAgB,IAAI,IAAK,QAAQ,CACnC,CACA,IAAK,GAAM,CAAC,IAAK,cAAe,gBAAiB,CAC/C,GAAI,WAAW,OAAS,EAAG,CACzB,IAAM,OAAS,WAAW,KAAK,EAAG,IAAM,EAAE,OAAS,GAAG,IAAI,GAAG,GAAG,EAChE,MAAM,IAAI,0BAA0B,IAAK,MAAM,CACjD,CACK,QAAQ,IAAI,GAAG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,OAAQ,iBACR,MACA,GAAI,aAAe,CAAE,YAAa,EAAI,CAAC,CACzC,CACF,CAAC,CACH,CAEA,OAAO,OACT,CAOA,SAAS,iBACP,QACA,QACoB,CACpB,IAAM,SAAW,IAAI,IAAI,QAAQ,IAAK,GAAM,CAAC,EAAE,aAAc,CAAC,CAAC,CAAC,EAQhE,MAAO,CAHL,GAAG,QAAQ,OAAQ,GAAM,EAAE,mBAAqB,EAAI,EACpD,GAAG,QAAQ,OAAQ,GAAM,EAAE,mBAAqB,EAAI,CAExC,CAAC,CAAC,IAAK,cAAiB,CACpC,IAAM,OAAS,SAAS,IAAI,YAAY,EAClC,UAA8B,CAClC,IAAK,aAAa,IAClB,OAAQ,QAAQ,QAAU,SAC1B,UAAW,aAAa,UACxB,iBAAkB,aAAa,mBAAqB,GACpD,UAAW,QACR,OAAQ,GAAM,EAAE,eAAiB,cAAgB,EAAE,aAAa,MAAQ,aAAa,GAAG,CAAC,CACzF,IAAK,GAAO,EAAE,MAAQ,CAAE,OAAQ,EAAE,OAAQ,MAAO,EAAE,KAAM,EAAI,CAAE,OAAQ,EAAE,MAAO,CAAE,CACvF,EAEA,OADI,QAAQ,QAAO,UAAU,MAAQ,OAAO,OACrC,SACT,CAAC,CACH"}
@@ -1,3 +0,0 @@
1
-
2
- import { INJECTION_TOKEN, InjectionToken, createToken, isInjectionToken } from "@forinda/kickjs-di";
3
- export { isInjectionToken as i, InjectionToken as n, createToken as r, INJECTION_TOKEN as t };
@@ -1 +0,0 @@
1
- {"version":3,"file":"upload-Jgs9BFC4.d.mts","names":["RequestHandler","Request","Response","NextFunction"],"sources":["../src/http/middleware/upload.ts"],"mappings":";;;;;;;;;;UAmDiB,sBAAsB;;EAErC,UAAU;;EAEV;;iBA6HO,OAAO,mBAAmB,UAAS,gBAAqBA;;;;iBAQxD,MAAM,mBAAmB,mBAAe,UAAS,gBAAqBA;;;;iBAQtE,KAAK,UAAS,gBAAqBA;;;;;;;;;;;;;;;iBAmB5B,iBAAY,KACbC,gBAAO,KAAOC,iBAAQ,MAAQC;;;;;;iBA+B7B,sBAAsB,QAAQ,mBAAmBH;;cAmBpD"}
@@ -1,12 +0,0 @@
1
- /**
2
- * @forinda/kickjs v10.6.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{HttpException,HttpStatus}from"./core/errors.mjs";const MIME_MAP={jpg:`image/jpeg`,jpeg:`image/jpeg`,png:`image/png`,gif:`image/gif`,webp:`image/webp`,svg:`image/svg+xml`,bmp:`image/bmp`,ico:`image/x-icon`,tiff:`image/tiff`,tif:`image/tiff`,avif:`image/avif`,pdf:`application/pdf`,doc:`application/msword`,docx:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,xls:`application/vnd.ms-excel`,xlsx:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,ppt:`application/vnd.ms-powerpoint`,pptx:`application/vnd.openxmlformats-officedocument.presentationml.presentation`,odt:`application/vnd.oasis.opendocument.text`,ods:`application/vnd.oasis.opendocument.spreadsheet`,odp:`application/vnd.oasis.opendocument.presentation`,rtf:`application/rtf`,txt:`text/plain`,csv:`text/csv`,zip:`application/zip`,gz:`application/gzip`,tar:`application/x-tar`,rar:`application/vnd.rar`,"7z":`application/x-7z-compressed`,mp3:`audio/mpeg`,wav:`audio/wav`,ogg:`audio/ogg`,flac:`audio/flac`,aac:`audio/aac`,mp4:`video/mp4`,webm:`video/webm`,avi:`video/x-msvideo`,mov:`video/quicktime`,mkv:`video/x-matroska`,json:`application/json`,xml:`application/xml`,html:`text/html`};function resolveMimeTypes(types){return types.map(t=>{let lower=t.toLowerCase().replace(/^\./,``);return MIME_MAP[lower]??t})}function buildFileTypeFilter(allowedTypes,customMimeMap){if(!allowedTypes)return()=>!0;if(typeof allowedTypes==`function`)return allowedTypes;let mimeMap=customMimeMap?{...MIME_MAP,...customMimeMap}:MIME_MAP,resolved=allowedTypes.map(t=>mimeMap[t.toLowerCase().replace(/^\./,``)]??t);return mimetype=>resolved.some(type=>type.endsWith(`/*`)?mimetype.startsWith(type.replace(`/*`,`/`)):mimetype===type)}function applyUploadConfig(parts,config){if(config.mode===`none`)return{};let field=config.fieldName??`file`,maxSize=config.maxSize??5242880,typeAllowed=buildFileTypeFilter(config.allowedTypes,config.customMimeMap),files=parts.filter(p=>p.fieldname===field).map(p=>{if(!typeAllowed(p.mimetype,p.filename))throw new HttpException(HttpStatus.UNSUPPORTED_MEDIA_TYPE,`File type ${p.mimetype} is not allowed`);if(p.buffer.length>maxSize)throw new HttpException(HttpStatus.PAYLOAD_TOO_LARGE,`File ${p.filename} exceeds the ${maxSize}-byte limit`);return{fieldname:p.fieldname,originalname:p.filename,encoding:`7bit`,mimetype:p.mimetype,size:p.buffer.length,buffer:p.buffer}});if(config.mode===`single`)return{file:files[0]};let maxCount=config.maxCount??10;return{files:files.slice(0,maxCount)}}export{buildFileTypeFilter as n,resolveMimeTypes as r,applyUploadConfig as t};
12
- //# sourceMappingURL=upload-config-DEnNEwL4.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"upload-config-DEnNEwL4.mjs","names":[],"sources":["../src/http/middleware/upload-config.ts"],"sourcesContent":["// Pure (edge-safe) upload core — the engine-neutral half of the upload\n// middleware. Extracted from `upload.ts` so the `@forinda/kickjs/web` entry\n// graph can validate/shape buffered multipart parts WITHOUT dragging in\n// upload.ts's node-only surface (multer peer loading via `node:module`,\n// disk cleanup via `node:fs/promises`). `upload.ts` re-exports everything\n// here, so existing import sites are unchanged.\n\nimport { HttpException, HttpStatus } from '../../core/errors'\nimport type { BaseUploadOptions, FileUploadConfig } from '../../core/decorators'\n\nexport const MIME_MAP: Record<string, string> = {\n // Images\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n png: 'image/png',\n gif: 'image/gif',\n webp: 'image/webp',\n svg: 'image/svg+xml',\n bmp: 'image/bmp',\n ico: 'image/x-icon',\n tiff: 'image/tiff',\n tif: 'image/tiff',\n avif: 'image/avif',\n // Documents\n pdf: 'application/pdf',\n doc: 'application/msword',\n docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n xls: 'application/vnd.ms-excel',\n xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n ppt: 'application/vnd.ms-powerpoint',\n pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n odt: 'application/vnd.oasis.opendocument.text',\n ods: 'application/vnd.oasis.opendocument.spreadsheet',\n odp: 'application/vnd.oasis.opendocument.presentation',\n rtf: 'application/rtf',\n txt: 'text/plain',\n csv: 'text/csv',\n // Archives\n zip: 'application/zip',\n gz: 'application/gzip',\n tar: 'application/x-tar',\n rar: 'application/vnd.rar',\n '7z': 'application/x-7z-compressed',\n // Audio\n mp3: 'audio/mpeg',\n wav: 'audio/wav',\n ogg: 'audio/ogg',\n flac: 'audio/flac',\n aac: 'audio/aac',\n // Video\n mp4: 'video/mp4',\n webm: 'video/webm',\n avi: 'video/x-msvideo',\n mov: 'video/quicktime',\n mkv: 'video/x-matroska',\n // Other\n json: 'application/json',\n xml: 'application/xml',\n html: 'text/html',\n}\n\n/**\n * Resolves a list of file type identifiers to MIME type strings.\n * Accepts short extensions (`'jpg'`, `'pdf'`) or full MIME types (`'image/jpeg'`).\n *\n * @example\n * ```ts\n * resolveMimeTypes(['jpg', 'png', 'application/pdf'])\n * // → ['image/jpeg', 'image/png', 'application/pdf']\n * ```\n */\nexport function resolveMimeTypes(types: string[]): string[] {\n return types.map((t) => {\n const lower = t.toLowerCase().replace(/^\\./, '')\n return MIME_MAP[lower] ?? t\n })\n}\n\n/**\n * Build a runtime-agnostic `(mimetype, filename) => boolean` file-type filter\n * from `allowedTypes` (a predicate, or a list of extensions / MIME types /\n * wildcards). Returned by both the multer middleware (Express) and the\n * Fastify / h3 / web multipart paths so the accept/reject rule stays\n * identical across engines. No `allowedTypes` → accept everything.\n */\nexport function buildFileTypeFilter(\n allowedTypes: BaseUploadOptions['allowedTypes'],\n customMimeMap?: Record<string, string>,\n): (mimetype: string, filename: string) => boolean {\n if (!allowedTypes) return () => true\n if (typeof allowedTypes === 'function') return allowedTypes\n const mimeMap = customMimeMap ? { ...MIME_MAP, ...customMimeMap } : MIME_MAP\n const resolved = allowedTypes.map((t) => mimeMap[t.toLowerCase().replace(/^\\./, '')] ?? t)\n return (mimetype: string) =>\n resolved.some((type) =>\n type.endsWith('/*') ? mimetype.startsWith(type.replace('/*', '/')) : mimetype === type,\n )\n}\n\n/** A multer-shaped uploaded file — what `ctx.file` / `ctx.files` expose. */\nexport interface UploadedFileLike {\n fieldname: string\n originalname: string\n encoding: string\n mimetype: string\n size: number\n buffer: Buffer\n}\n\n/**\n * An uploaded file as `ctx.file` / `ctx.files` hold it, on every runtime —\n * multer's shape, declared here so the typings need no `@types/multer`. The\n * disk fields are set only by `upload({ dest })` / a multer `diskStorage`\n * (Express), which leaves `buffer` unset, as multer does.\n */\nexport interface UploadedFile extends UploadedFileLike {\n destination?: string\n filename?: string\n path?: string\n}\n\n/**\n * A multer storage engine — `multer.diskStorage()`, `multer.memoryStorage()` or\n * your own — declared here so the typings need no `@types/multer`.\n */\nexport interface UploadStorageEngine {\n _handleFile(req: any, file: any, callback: (error?: any, info?: any) => void): void\n _removeFile(req: any, file: any, callback: (error: Error | null) => void): void\n}\n\n/** A buffered multipart file part, as the runtime hands it to {@link applyUploadConfig}. */\nexport interface RawUploadPart {\n fieldname: string\n filename: string\n mimetype: string\n buffer: Buffer\n}\n\nconst DEFAULT_MAX_SIZE = 5 * 1024 * 1024\n\n/**\n * Apply a `@FileUpload` config to already-buffered multipart parts and return\n * the multer-shaped `file` / `files` for `ctx`. Enforces the field name, type\n * filter, per-file size limit, and (array mode) max count — throwing\n * `HttpException` on a violation, mirroring the Express/multer error path.\n * Used by the Fastify, h3 and web runtimes; Express keeps using multer directly.\n */\nexport function applyUploadConfig(\n parts: RawUploadPart[],\n config: FileUploadConfig,\n): { file?: UploadedFileLike; files?: UploadedFileLike[] } {\n if (config.mode === 'none') return {}\n\n const field = config.fieldName ?? 'file'\n const maxSize = config.maxSize ?? DEFAULT_MAX_SIZE\n const typeAllowed = buildFileTypeFilter(config.allowedTypes, config.customMimeMap)\n\n const matched = parts.filter((p) => p.fieldname === field)\n const files: UploadedFileLike[] = matched.map((p) => {\n if (!typeAllowed(p.mimetype, p.filename)) {\n throw new HttpException(\n HttpStatus.UNSUPPORTED_MEDIA_TYPE,\n `File type ${p.mimetype} is not allowed`,\n )\n }\n if (p.buffer.length > maxSize) {\n throw new HttpException(\n HttpStatus.PAYLOAD_TOO_LARGE,\n `File ${p.filename} exceeds the ${maxSize}-byte limit`,\n )\n }\n return {\n fieldname: p.fieldname,\n originalname: p.filename,\n encoding: '7bit',\n mimetype: p.mimetype,\n size: p.buffer.length,\n buffer: p.buffer,\n }\n })\n\n if (config.mode === 'single') return { file: files[0] }\n const maxCount = config.maxCount ?? 10\n return { files: files.slice(0, maxCount) }\n}\n"],"mappings":";;;;;;;;;;wDAUA,MAAa,SAAmC,CAE9C,IAAK,aACL,KAAM,aACN,IAAK,YACL,IAAK,YACL,KAAM,aACN,IAAK,gBACL,IAAK,YACL,IAAK,eACL,KAAM,aACN,IAAK,aACL,KAAM,aAEN,IAAK,kBACL,IAAK,qBACL,KAAM,0EACN,IAAK,2BACL,KAAM,oEACN,IAAK,gCACL,KAAM,4EACN,IAAK,0CACL,IAAK,iDACL,IAAK,kDACL,IAAK,kBACL,IAAK,aACL,IAAK,WAEL,IAAK,kBACL,GAAI,mBACJ,IAAK,oBACL,IAAK,sBACL,KAAM,8BAEN,IAAK,aACL,IAAK,YACL,IAAK,YACL,KAAM,aACN,IAAK,YAEL,IAAK,YACL,KAAM,aACN,IAAK,kBACL,IAAK,kBACL,IAAK,mBAEL,KAAM,mBACN,IAAK,kBACL,KAAM,WACR,EAYA,SAAgB,iBAAiB,MAA2B,CAC1D,OAAO,MAAM,IAAK,GAAM,CACtB,IAAM,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