@forinda/kickjs 8.6.0 → 9.0.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 (173) hide show
  1. package/README.md +27 -164
  2. package/dist/{adapter-2bnoYEPX.d.mts → adapter-DhjoIYVI.d.mts} +122 -106
  3. package/dist/adapter-DhjoIYVI.d.mts.map +1 -0
  4. package/dist/application-BnFA6J97.mjs +12 -0
  5. package/dist/application-BnFA6J97.mjs.map +1 -0
  6. package/dist/{application-_QOiAVx2.d.mts → application-DqD58rhF.d.mts} +104 -15
  7. package/dist/application-DqD58rhF.d.mts.map +1 -0
  8. package/dist/bootstrap-K1PcxSTg.mjs +12 -0
  9. package/dist/bootstrap-K1PcxSTg.mjs.map +1 -0
  10. package/dist/cache-C0qL0NSD.d.mts.map +1 -1
  11. package/dist/{client-ip-DF_smNX7.mjs → client-ip-DAnYuS54.mjs} +2 -2
  12. package/dist/{client-ip-DF_smNX7.mjs.map → client-ip-DAnYuS54.mjs.map} +1 -1
  13. package/dist/config/index.d.mts +2 -2
  14. package/dist/config/index.mjs +2 -2
  15. package/dist/config-16yw-Mxk.mjs +12 -0
  16. package/dist/config-16yw-Mxk.mjs.map +1 -0
  17. package/dist/container-Dw45sa0Y.mjs +132 -0
  18. package/dist/container-Dw45sa0Y.mjs.map +1 -0
  19. package/dist/context-DlIdXA6I.mjs +12 -0
  20. package/dist/context-DlIdXA6I.mjs.map +1 -0
  21. package/dist/{context-errors-Ch0DuUQo.mjs → context-errors-BqOFD7UE.mjs} +2 -2
  22. package/dist/{context-errors-Ch0DuUQo.mjs.map → context-errors-BqOFD7UE.mjs.map} +1 -1
  23. package/dist/{contributor-runner-DujKZy4N.mjs → contributor-runner-DLvBA96K.mjs} +3 -3
  24. package/dist/{contributor-runner-DujKZy4N.mjs.map → contributor-runner-DLvBA96K.mjs.map} +1 -1
  25. package/dist/core/adapter.d.mts +2 -2
  26. package/dist/core/adapter.mjs +1 -1
  27. package/dist/core/app-module.mjs +1 -1
  28. package/dist/core/cache.mjs +2 -2
  29. package/dist/core/cache.mjs.map +1 -1
  30. package/dist/core/container.mjs +2 -2
  31. package/dist/core/cron.d.mts +2 -2
  32. package/dist/core/cron.mjs +2 -2
  33. package/dist/core/cron.mjs.map +1 -1
  34. package/dist/core/decorators.d.mts +1 -1
  35. package/dist/core/decorators.mjs +2 -2
  36. package/dist/core/decorators.mjs.map +1 -1
  37. package/dist/core/errors.mjs +1 -1
  38. package/dist/core/interfaces.mjs +1 -1
  39. package/dist/core/logger.mjs +1 -1
  40. package/dist/core/path.mjs +1 -1
  41. package/dist/core/plugin.d.mts +1 -1
  42. package/dist/core/plugin.mjs +1 -1
  43. package/dist/core/reactivity.mjs +1 -1
  44. package/dist/core-CCwlN0Gn.mjs +12 -0
  45. package/dist/{core-y8QbzHM5.mjs.map → core-CCwlN0Gn.mjs.map} +1 -1
  46. package/dist/cron-BTGytNg-.d.mts +122 -0
  47. package/dist/cron-BTGytNg-.d.mts.map +1 -0
  48. package/dist/{csrf-RP5hgc0c.mjs → csrf-B8CGeOlP.mjs} +3 -3
  49. package/dist/csrf-B8CGeOlP.mjs.map +1 -0
  50. package/dist/{csrf-C4MwaMp4.d.mts → csrf-COFjRrUz.d.mts} +2 -2
  51. package/dist/{csrf-C4MwaMp4.d.mts.map → csrf-COFjRrUz.d.mts.map} +1 -1
  52. package/dist/{decorate-D85rEnU-.mjs → decorate-CahyjuWW.mjs} +1 -1
  53. package/dist/{decorators-mg0qJ6Qc.d.mts → decorators-DOcWsXci.d.mts} +2 -2
  54. package/dist/{decorators-mg0qJ6Qc.d.mts.map → decorators-DOcWsXci.d.mts.map} +1 -1
  55. package/dist/{define-adapter-C1Db6xfO.mjs → define-adapter-Ckc2P-wH.mjs} +2 -2
  56. package/dist/{define-adapter-C1Db6xfO.mjs.map → define-adapter-Ckc2P-wH.mjs.map} +1 -1
  57. package/dist/{disposables-CEAxve3A.mjs → disposables-DnvT8DXr.mjs} +2 -2
  58. package/dist/{disposables-CEAxve3A.mjs.map → disposables-DnvT8DXr.mjs.map} +1 -1
  59. package/dist/{env-BelmDj19.mjs → env-DMAdjj8Z.mjs} +4 -4
  60. package/dist/env-DMAdjj8Z.mjs.map +1 -0
  61. package/dist/{error-handler-C1uWVGVY.d.mts → error-handler-DiueQHes.d.mts} +2 -2
  62. package/dist/{error-handler-C1uWVGVY.d.mts.map → error-handler-DiueQHes.d.mts.map} +1 -1
  63. package/dist/{handler-DHlakr0v.mjs → handler-2CbWK63p.mjs} +3 -3
  64. package/dist/handler-2CbWK63p.mjs.map +1 -0
  65. package/dist/http/application.d.mts +2 -2
  66. package/dist/http/application.mjs +2 -2
  67. package/dist/http/bootstrap.d.mts +1 -1
  68. package/dist/http/bootstrap.mjs +2 -2
  69. package/dist/http/context.d.mts +2 -2
  70. package/dist/http/context.mjs +2 -2
  71. package/dist/http/middleware/cors.mjs +1 -1
  72. package/dist/http/middleware/csrf.d.mts +1 -1
  73. package/dist/http/middleware/csrf.mjs +2 -2
  74. package/dist/http/middleware/error-handler.d.mts +1 -1
  75. package/dist/http/middleware/error-handler.mjs +2 -2
  76. package/dist/http/middleware/error-handler.mjs.map +1 -1
  77. package/dist/http/middleware/helmet.mjs +1 -1
  78. package/dist/http/middleware/rate-limit.mjs +2 -2
  79. package/dist/http/middleware/request-id.mjs +1 -1
  80. package/dist/http/middleware/request-logger.mjs +2 -2
  81. package/dist/http/middleware/session.d.mts +1 -1
  82. package/dist/http/middleware/session.mjs +2 -2
  83. package/dist/http/middleware/session.mjs.map +1 -1
  84. package/dist/http/middleware/spa.d.mts +1 -1
  85. package/dist/http/middleware/spa.mjs +2 -2
  86. package/dist/http/middleware/upload.d.mts +1 -1
  87. package/dist/http/middleware/upload.mjs +3 -3
  88. package/dist/http/middleware/upload.mjs.map +1 -1
  89. package/dist/http/middleware/validate.mjs +1 -1
  90. package/dist/http/middleware/views.d.mts +1 -1
  91. package/dist/http/middleware/views.mjs +2 -2
  92. package/dist/http/query/index.mjs +2 -2
  93. package/dist/http/router-builder.d.mts +1 -1
  94. package/dist/http/router-builder.mjs +2 -2
  95. package/dist/http/runtimes/fastify.d.mts +1 -1
  96. package/dist/http/runtimes/fastify.d.mts.map +1 -1
  97. package/dist/http/runtimes/fastify.mjs +3 -3
  98. package/dist/http/runtimes/fastify.mjs.map +1 -1
  99. package/dist/http/runtimes/h3-web.d.mts +1 -1
  100. package/dist/http/runtimes/h3-web.d.mts.map +1 -1
  101. package/dist/http/runtimes/h3-web.mjs +2 -2
  102. package/dist/http/runtimes/h3-web.mjs.map +1 -1
  103. package/dist/http/runtimes/h3.d.mts +1 -6
  104. package/dist/http/runtimes/h3.d.mts.map +1 -1
  105. package/dist/http/runtimes/h3.mjs +2 -2
  106. package/dist/http/runtimes/h3.mjs.map +1 -1
  107. package/dist/{index-Btz1W0X5.d.mts → index-CDn-p3tq.d.mts} +27 -18
  108. package/dist/index-CDn-p3tq.d.mts.map +1 -0
  109. package/dist/index.d.mts +12 -12
  110. package/dist/index.mjs +2 -2
  111. package/dist/index.mjs.map +1 -1
  112. package/dist/jobs-C8_ESbx0.mjs +12 -0
  113. package/dist/jobs-C8_ESbx0.mjs.map +1 -0
  114. package/dist/{kv-stores-DUFcps01.mjs → kv-stores-BhUmirED.mjs} +3 -3
  115. package/dist/{kv-stores-DUFcps01.mjs.map → kv-stores-BhUmirED.mjs.map} +1 -1
  116. package/dist/{kv-stores-Dx5RvIaP.d.mts → kv-stores-CetFF9N_.d.mts} +135 -5
  117. package/dist/kv-stores-CetFF9N_.d.mts.map +1 -0
  118. package/dist/{metadata-B8_KXybT.mjs → metadata-BQG1MmqL.mjs} +2 -2
  119. package/dist/{metadata-B8_KXybT.mjs.map → metadata-BQG1MmqL.mjs.map} +1 -1
  120. package/dist/{module-registry-BFrJ1PQ4.mjs → module-registry-BXnvRtH9.mjs} +2 -2
  121. package/dist/{module-registry-BFrJ1PQ4.mjs.map → module-registry-BXnvRtH9.mjs.map} +1 -1
  122. package/dist/observers-BI8H_g45.mjs +12 -0
  123. package/dist/observers-BI8H_g45.mjs.map +1 -0
  124. package/dist/{query-CC7o6I5K.mjs → query-CRTeiKUv.mjs} +2 -2
  125. package/dist/{query-CC7o6I5K.mjs.map → query-CRTeiKUv.mjs.map} +1 -1
  126. package/dist/{respond-B-EDymxF.mjs → respond-BAxhPjRj.mjs} +2 -2
  127. package/dist/{respond-B-EDymxF.mjs.map → respond-BAxhPjRj.mjs.map} +1 -1
  128. package/dist/route-flag-B1lQht6v.d.mts.map +1 -1
  129. package/dist/{route-flag-B4sNP7zH.mjs → route-flag-GipNvQ4O.mjs} +3 -3
  130. package/dist/route-flag-GipNvQ4O.mjs.map +1 -0
  131. package/dist/{route-policy-CDlMbl1b.mjs → route-policy-DtGR4sar.mjs} +2 -2
  132. package/dist/route-policy-DtGR4sar.mjs.map +1 -0
  133. package/dist/{router-builder-C6gmK0nZ.d.mts → router-builder-BSBSYgYW.d.mts} +3 -3
  134. package/dist/{router-builder-C6gmK0nZ.d.mts.map → router-builder-BSBSYgYW.d.mts.map} +1 -1
  135. package/dist/{router-builder-cTsA2XtO.mjs → router-builder-C2nnS0VJ.mjs} +3 -3
  136. package/dist/{router-builder-cTsA2XtO.mjs.map → router-builder-C2nnS0VJ.mjs.map} +1 -1
  137. package/dist/{runtime-C-7Yhs7a.mjs → runtime-DGzigyO2.mjs} +3 -3
  138. package/dist/runtime-DGzigyO2.mjs.map +1 -0
  139. package/dist/{session-BHgRyfqZ.d.mts → session-4Tb6q0Ny.d.mts} +11 -1
  140. package/dist/session-4Tb6q0Ny.d.mts.map +1 -0
  141. package/dist/{upload-TW2ZuECF.d.mts → upload-DjhnyHHm.d.mts} +3 -15
  142. package/dist/{upload-TW2ZuECF.d.mts.map → upload-DjhnyHHm.d.mts.map} +1 -1
  143. package/dist/{upload-config-CoE6BzM4.mjs → upload-config-CcoZp7xA.mjs} +2 -2
  144. package/dist/{upload-config-CoE6BzM4.mjs.map → upload-config-CcoZp7xA.mjs.map} +1 -1
  145. package/dist/web.d.mts +39 -7
  146. package/dist/web.d.mts.map +1 -1
  147. package/dist/web.mjs +2 -2
  148. package/dist/web.mjs.map +1 -1
  149. package/package.json +15 -10
  150. package/dist/adapter-2bnoYEPX.d.mts.map +0 -1
  151. package/dist/application-DZiG1QCw.mjs +0 -12
  152. package/dist/application-DZiG1QCw.mjs.map +0 -1
  153. package/dist/application-_QOiAVx2.d.mts.map +0 -1
  154. package/dist/bootstrap-BEbka3UV.mjs +0 -12
  155. package/dist/bootstrap-BEbka3UV.mjs.map +0 -1
  156. package/dist/config-CIOXZmLS.mjs +0 -12
  157. package/dist/config-CIOXZmLS.mjs.map +0 -1
  158. package/dist/container-DF8FRoY8.mjs +0 -117
  159. package/dist/container-DF8FRoY8.mjs.map +0 -1
  160. package/dist/context-BTqeZH1A.mjs +0 -12
  161. package/dist/context-BTqeZH1A.mjs.map +0 -1
  162. package/dist/core-y8QbzHM5.mjs +0 -12
  163. package/dist/cron-DOOtTY4q.d.mts +0 -30
  164. package/dist/cron-DOOtTY4q.d.mts.map +0 -1
  165. package/dist/csrf-RP5hgc0c.mjs.map +0 -1
  166. package/dist/env-BelmDj19.mjs.map +0 -1
  167. package/dist/handler-DHlakr0v.mjs.map +0 -1
  168. package/dist/index-Btz1W0X5.d.mts.map +0 -1
  169. package/dist/kv-stores-Dx5RvIaP.d.mts.map +0 -1
  170. package/dist/route-flag-B4sNP7zH.mjs.map +0 -1
  171. package/dist/route-policy-CDlMbl1b.mjs.map +0 -1
  172. package/dist/runtime-C-7Yhs7a.mjs.map +0 -1
  173. package/dist/session-BHgRyfqZ.d.mts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"h3-web.mjs","names":[],"sources":["../../../src/http/runtimes/h3-web.ts"],"sourcesContent":["// The h3 v2 (web-standards) runtime — `@forinda/kickjs/h3-web`.\n//\n// ADDITIVE runtime: the h3 v1 runtime (`./h3.ts`, `@forinda/kickjs/h3`)\n// stays untouched so existing adopters keep working (locked decision,\n// web-standards-edge-design.md §3.1). This runtime targets h3 >= 2 — the\n// web-standard rebase where `event.req` is a WHATWG Request, handlers\n// return values/Responses, and `app.fetch(request)` is the universal entry.\n//\n// The request pipeline runs through the shared web driver pair\n// (`../web/driver`, `../web/handler`) — the same code path the\n// `@forinda/kickjs/web` edge entry uses, so node bootstrap and edge deploys\n// exercise identical request semantics.\n//\n// Known limitation vs the v1 runtime: no Vite dev-server fall-through —\n// unmatched requests are answered by the kick notFound handler (h3 v2 owns\n// the full request; there is no node `next()` bail-out mid-engine). Use the\n// v1 h3 runtime or Express for Vite-integrated dev setups.\n\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport { createRequire } from 'node:module'\n\nimport type {\n ConnectMiddleware,\n HttpRuntime,\n RouteTable,\n RuntimeAppOptions,\n UseConnectOptions,\n} from '../runtime'\nimport { compileWebRoute, type WebRouteHooks } from '../web/handler'\nimport { WebRequestShim, WebResponseDriver } from '../web/driver'\nimport { createLogger, describeError } from '../../core/logger'\n\nconst log = createLogger('H3WebRuntime')\n\nconst peerRequire = createRequire(import.meta.url)\n\nconst NOTFOUND_MW = Symbol('kickjs.h3web.notFoundMw')\nconst ERROR_MW = Symbol('kickjs.h3web.errorMw')\nconst ASSEMBLED = Symbol('kickjs.h3web.assembled')\nconst NOOP_NEXT = (): void => {}\n\n// Minimal structural surface of h3 v2 we depend on.\ninterface H3AppLike {\n on(method: string, path: string, handler: (event: H3EventLike) => unknown): unknown\n all(path: string, handler: (event: H3EventLike) => unknown): unknown\n use(...args: unknown[]): unknown\n fetch(request: Request): Promise<Response>\n}\ninterface H3EventLike {\n req: Request & { runtime?: { node?: { req: IncomingMessage; res: ServerResponse } } }\n url: URL\n context: { params?: Record<string, string> }\n}\n\ninterface H3v2Module {\n H3: new (config?: unknown) => H3AppLike\n toNodeHandler: (app: H3AppLike) => (req: IncomingMessage, res: ServerResponse) => void\n fromNodeHandler: (mw: unknown) => unknown\n}\n\nexport interface H3WebRuntimeOptions {\n /**\n * Pre-imported h3 v2 module. Two audiences:\n * - Edge/worker bundlers with no `createRequire` at runtime:\n * `h3WebRuntime({ h3: await import('h3') })`\n * - Tests running both h3 majors side by side via an npm alias.\n * Omitted → the peer is loaded via `createRequire` (node bootstrap path).\n */\n h3?: unknown\n}\n\n/** Resolve h3 (injected or peer-required) and fail fast unless it is v2. */\nfunction loadH3v2(injected?: unknown): H3v2Module {\n const mod = injected ?? peerRequire('h3')\n const m = mod as { __esModule?: boolean; default?: Record<string, unknown> } & Record<\n string,\n unknown\n >\n const resolved = (m && m.__esModule && m.default\n ? { ...m.default, ...m }\n : m) as unknown as H3v2Module\n if (typeof resolved.H3 !== 'function') {\n throw new Error(\n \"@forinda/kickjs: h3WebRuntime() requires h3 v2 (the web-standards line, npm dist-tag 'latest'), \" +\n 'but the installed h3 has no H3 class — that is the v1 line. ' +\n \"Either `pnpm add h3@latest` for this runtime, or keep h3 v1 and use h3Runtime() from '@forinda/kickjs/h3'.\",\n )\n }\n return resolved\n}\n\n/**\n * Bridge a connect-style terminal middleware (kick's notFound / error\n * handlers) onto the web driver pair, returning the produced Response.\n */\nasync function runConnectTerminal(\n mw: ConnectMiddleware | undefined,\n event: H3EventLike,\n err?: unknown,\n): Promise<Response> {\n const req = new WebRequestShim(event.req, event.url)\n const driver = new WebResponseDriver(event.req.signal)\n if (mw) {\n if (err !== undefined) {\n ;(mw as (e: unknown, rq: unknown, rs: unknown, n: () => void) => void)(\n err,\n req,\n driver,\n NOOP_NEXT,\n )\n } else {\n ;(mw as (rq: unknown, rs: unknown, n: () => void) => void)(req, driver, NOOP_NEXT)\n }\n }\n if (!driver.settled) {\n if (err !== undefined) {\n // The configured error handler ran but didn't settle the response\n // (or there wasn't one). Emitting a bare 500 with no log entry\n // makes this failure invisible on both sides — log it here, since\n // by definition nothing downstream will.\n log.error(err, `h3-web: error handler did not settle the response — ${describeError(err)}`)\n driver.status(500).json({\n error: 'Internal Server Error',\n ...(typeof process !== 'undefined' && process.env?.NODE_ENV === 'production'\n ? {}\n : { message: describeError(err) }),\n })\n } else {\n driver.status(404).json({ error: 'Not Found' })\n }\n }\n return driver.ready\n}\n\n// ── Connect middleware on the fetch path ─────────────────────────────────\n//\n// `app.fetch(request)` (edge, Bun, Deno, a serverless function) carries no\n// node req/res, and h3's `fromNodeHandler` throws without one. Connect\n// middleware there runs against the web driver pair instead: one request shim\n// per event (so `req.requestId` set by one middleware is seen by the next) and\n// one header bag per event that is merged into whatever Response comes back.\n// The merge is ours rather than h3's `event.res.headers` because h3 skips\n// prepared headers on non-2xx responses, and a 404/422/500 must still carry\n// helmet's headers and the request id, exactly as on node.\n\ninterface FetchConnectState {\n req: WebRequestShim\n headers: Headers\n}\n\nconst FETCH_CONNECT = new WeakMap<object, FetchConnectState>()\n\nfunction fetchConnectState(event: H3EventLike): FetchConnectState {\n let state = FETCH_CONNECT.get(event)\n if (!state) {\n state = { req: new WebRequestShim(event.req, event.url), headers: new Headers() }\n FETCH_CONNECT.set(event, state)\n }\n return state\n}\n\n/**\n * Add the headers connect middleware set to `response`. The response's own\n * headers win — a later `setHeader` overrides an earlier one on node too.\n * Consumed once, so every middleware layer can call it on the way out.\n */\nfunction withConnectHeaders(event: H3EventLike, response: Response): Response {\n const state = FETCH_CONNECT.get(event)\n if (!state) return response\n const missing = [...state.headers].filter(\n ([name]) => name === 'set-cookie' || !response.headers.has(name),\n )\n state.headers = new Headers()\n if (missing.length === 0) return response\n try {\n for (const [name, value] of missing) response.headers.append(name, value)\n return response\n } catch {\n // Immutable headers (a Response from fetch) — rebuild around the body.\n const headers = new Headers(response.headers)\n for (const [name, value] of missing) headers.append(name, value)\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n })\n }\n}\n\n/**\n * The node `res` surface connect middleware uses, over the web driver:\n * headers go to the per-event bag, `statusCode`, and `finish`/`close`\n * emitted once the response exists.\n */\nclass FetchConnectResponse extends WebResponseDriver {\n private code = 200\n private listeners: Array<[string, (...args: unknown[]) => void]> = []\n\n constructor(\n private readonly prepared: Headers,\n signal: AbortSignal,\n ) {\n super(signal)\n }\n\n get statusCode(): number {\n return this.code\n }\n\n set statusCode(code: number) {\n this.status(code)\n }\n\n override status(code: number): this {\n this.code = code\n return super.status(code)\n }\n\n override writeHead(code: number, headers?: Record<string, string | number | string[]>): this {\n this.code = code\n return super.writeHead(code, headers)\n }\n\n override setHeader(name: string, value: unknown): this {\n if (Array.isArray(value)) {\n this.prepared.delete(name)\n for (const v of value) this.prepared.append(name, String(v))\n } else {\n this.prepared.set(name, String(value))\n }\n return this\n }\n\n getHeader(name: string): string | undefined {\n return this.prepared.get(name) ?? undefined\n }\n\n hasHeader(name: string): boolean {\n return this.prepared.has(name)\n }\n\n removeHeader(name: string): void {\n this.prepared.delete(name)\n }\n\n override once(event: string, listener: (...args: unknown[]) => void): this {\n this.listeners.push([event, listener])\n return this\n }\n\n on(event: string, listener: (...args: unknown[]) => void): this {\n return this.once(event, listener)\n }\n\n removeListener(event: string, listener: (...args: unknown[]) => void): this {\n this.listeners = this.listeners.filter(([e, l]) => e !== event || l !== listener)\n return this\n }\n\n off(event: string, listener: (...args: unknown[]) => void): this {\n return this.removeListener(event, listener)\n }\n\n /** The response exists (or the request failed): fire `finish` then `close`. */\n done(): void {\n for (const event of ['finish', 'close']) {\n for (const [e, listener] of this.listeners) if (e === event) listener()\n this.listeners = this.listeners.filter(([e]) => e !== event)\n }\n }\n}\n\nfunction runConnectOnFetch(\n mw: ConnectMiddleware,\n event: H3EventLike,\n next: () => unknown,\n): Promise<unknown> {\n const state = fetchConnectState(event)\n const res = new FetchConnectResponse(state.headers, event.req.signal)\n\n return new Promise((resolve, reject) => {\n const respond = (response: Response): void => {\n res.done()\n resolve(withConnectHeaders(event, response))\n }\n const fail = (err: unknown): void => {\n res.done()\n reject(err)\n }\n\n // The middleware answered itself (`res.end`, `res.json`, `writeHead`).\n void res.ready.then(respond)\n\n const connectNext = (err?: unknown): void => {\n if (err) return fail(err)\n if (res.settled) return\n // The route builds its request store from the inbound header; hand it the\n // id requestScope/requestId settled on so body, logs and header agree.\n const id = state.req.requestId\n if (id && event.req.headers.get('x-request-id') !== id) {\n try {\n event.req.headers.set('x-request-id', id)\n } catch {\n // Immutable request headers on some runtimes — the route mints its own id.\n }\n }\n let downstream: unknown\n try {\n // Synchronous, so downstream work starts inside any AsyncLocalStorage\n // scope this middleware opened (requestScopeMiddleware).\n downstream = next()\n } catch (e) {\n return fail(e)\n }\n Promise.resolve(downstream).then((value) => {\n if (value instanceof Response) return respond(value)\n res.done()\n resolve(value)\n }, fail)\n }\n\n try {\n ;(mw as (rq: unknown, rs: unknown, n: (err?: unknown) => void) => void)(\n state.req,\n res,\n connectNext,\n )\n } catch (err) {\n fail(err)\n }\n })\n}\n\n/**\n * Terminal catch-all AFTER all mounted routes: kick's own notFound handler\n * answers unmatched paths (h3 v2's default 404 never fires). rou3 ranks `/**`\n * below every concrete route, so registration time does not matter.\n */\nfunction assembleCatchAll(app: H3AppLike): void {\n const state = app as unknown as Record<symbol, unknown>\n if (state[ASSEMBLED]) return\n state[ASSEMBLED] = true\n app.all('/**', (event: H3EventLike) => {\n const mw = state[NOTFOUND_MW] as ConnectMiddleware | undefined\n return runConnectTerminal(mw, event)\n })\n}\n\n/**\n * The h3 v2 HTTP runtime. Pass to `bootstrap({ runtime: h3WebRuntime() })`.\n * Requires the h3 v2 peer; fails fast with guidance when v1 is installed.\n */\nexport function h3WebRuntime(options: H3WebRuntimeOptions = {}): HttpRuntime<H3AppLike> {\n const { H3, toNodeHandler, fromNodeHandler } = loadH3v2(options.h3)\n\n return {\n name: 'h3-web',\n\n createApp(_options: RuntimeAppOptions = {}): H3AppLike {\n const holder: { app?: H3AppLike } = {}\n const app = new H3({\n // Engine-level errors (middleware throws outside the kick pipeline)\n // dispatch to the kick error handler once setErrorHandler stashes it.\n onError: (error: unknown, event: H3EventLike) => {\n const mw = (holder.app as unknown as Record<symbol, ConnectMiddleware | undefined>)?.[\n ERROR_MW\n ]\n return runConnectTerminal(mw, event, error).then((response) =>\n withConnectHeaders(event, response),\n )\n },\n })\n holder.app = app\n return app\n },\n\n nodeHandler(app) {\n assembleCatchAll(app)\n const listener = toNodeHandler(app)\n return (req: IncomingMessage, res: ServerResponse, next?: (err?: unknown) => void) => {\n try {\n const result = listener(req, res) as unknown\n if (result && typeof (result as Promise<unknown>).then === 'function') {\n void (result as Promise<unknown>).catch((err) => next?.(err))\n }\n } catch (err) {\n next?.(err)\n }\n }\n },\n\n mountRoutes(app, table: RouteTable) {\n for (const { mountPath, routes } of table) {\n for (const entry of routes) {\n const url = joinPath(mountPath, entry.path)\n const hooks: WebRouteHooks = {\n onError: async (err, req, driver) => {\n const mw = (app as unknown as Record<symbol, ConnectMiddleware | undefined>)[ERROR_MW]\n if (!mw) return\n ;(mw as (e: unknown, rq: unknown, rs: unknown, n: () => void) => void)(\n err,\n req,\n driver,\n NOOP_NEXT,\n )\n },\n }\n const run = compileWebRoute(entry, hooks)\n app.on(entry.method, url, (event: H3EventLike) =>\n run({\n request: event.req,\n url: event.url,\n params: event.context.params ?? {},\n }),\n )\n }\n }\n },\n\n useConnect(app, mw: ConnectMiddleware, opts?: UseConnectOptions) {\n // Behind a node server (toNodeHandler) the event carries node req/res and\n // h3's own bridge runs the middleware unchanged. Called through\n // `app.fetch(request)` there is none and fromNodeHandler would throw, so\n // the middleware runs against the web driver pair instead.\n const viaNode = fromNodeHandler(mw) as (event: H3EventLike) => unknown\n const handler = (event: H3EventLike, next: () => unknown) =>\n event.req.runtime?.node?.res ? viaNode(event) : runConnectOnFetch(mw, event, next)\n if (opts?.path !== undefined) {\n // v2 `use` is exact-match; `/**` covers the subtree like v1's prefix.\n app.use(joinPath(String(opts.path), '/**'), handler)\n } else {\n app.use(handler)\n }\n },\n\n serveStatic(app, prefix, dir) {\n // serve-static bridged like any other connect middleware (node only).\n const serveStatic = peerRequire('serve-static')\n this.useConnect(app, serveStatic(dir) as ConnectMiddleware, { path: prefix })\n },\n\n setNotFound(app, mw: ConnectMiddleware) {\n ;(app as unknown as Record<symbol, ConnectMiddleware>)[NOTFOUND_MW] = mw\n // Here as well as in nodeHandler: an app only ever called through\n // `app.fetch` never reaches nodeHandler, and would answer h3's own 404.\n assembleCatchAll(app)\n },\n\n setErrorHandler(app, mw: ConnectMiddleware) {\n ;(app as unknown as Record<symbol, ConnectMiddleware>)[ERROR_MW] = mw\n },\n\n capabilities: {\n render: false,\n uploads: true,\n connectMiddleware: true,\n nativeBodyParsing: true,\n },\n }\n}\n\n/**\n * h3-web runtime engine types for the `kick/runtime` typegen augmentation —\n * mirrors {@link import('./h3').H3RuntimeTypes} for the v1 runtime.\n */\nexport interface H3WebRuntimeTypes {\n request: Request\n response: Response\n app: unknown\n}\n\n/** Join a mount prefix and a route path into one URL, collapsing slashes. */\nfunction joinPath(mountPath: string, path: string): string {\n const a = mountPath.endsWith('/') ? mountPath.slice(0, -1) : mountPath\n if (path === '/' || path === '') return a === '' ? '/' : a\n const b = path.startsWith('/') ? path : `/${path}`\n return `${a}${b}`\n}\n"],"mappings":";;;;;;;;;;6MAgCA,MAAM,IAAM,aAAa,cAAc,EAEjC,YAAc,cAAc,YAAY,GAAG,EAE3C,YAAc,OAAO,yBAAyB,EAC9C,SAAW,OAAO,sBAAsB,EACxC,UAAY,OAAO,wBAAwB,EAC3C,cAAwB,CAAC,EAiC/B,SAAS,SAAS,SAAgC,CAEhD,IAAM,EADM,UAAY,YAAY,IAAI,EAKlC,SAAY,GAAK,EAAE,YAAc,EAAE,QACrC,CAAE,GAAG,EAAE,QAAS,GAAG,CAAE,EACrB,EACJ,GAAI,OAAO,SAAS,IAAO,WACzB,MAAU,MACR,wQAGF,EAEF,OAAO,QACT,CAMA,eAAe,mBACb,GACA,MACA,IACmB,CACnB,IAAM,IAAM,IAAI,eAAe,MAAM,IAAK,MAAM,GAAG,EAC7C,OAAS,IAAI,kBAAkB,MAAM,IAAI,MAAM,EA8BrD,OA7BI,KACE,MAAQ,IAAA,GAQT,GAA0D,IAAK,OAAQ,SA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,IAAM,QAAQ,KAAK,EAAI,kBAAkB,GAAI,MAAO,IAAI,EAC/E,MAAM,OAAS,IAAA,GAIjB,IAAI,IAAI,OAAO,EAFf,IAAI,IAAI,SAAS,OAAO,KAAK,IAAI,EAAG,KAAK,EAAG,OAAO,CAIvD,EAEA,YAAY,IAAK,OAAQ,IAAK,CAE5B,IAAM,YAAc,YAAY,cAAc,EAC9C,KAAK,WAAW,IAAK,YAAY,GAAG,EAAwB,CAAE,KAAM,MAAO,CAAC,CAC9E,EAEA,YAAY,IAAK,GAAuB,CACrC,IAAsD,aAAe,GAGtE,iBAAiB,GAAG,CACtB,EAEA,gBAAgB,IAAK,GAAuB,CACzC,IAAsD,UAAY,EACrE,EAEA,aAAc,CACZ,OAAQ,GACR,QAAS,GACT,kBAAmB,GACnB,kBAAmB,EACrB,CACF,CACF,CAaA,SAAS,SAAS,UAAmB,KAAsB,CACzD,IAAM,EAAI,UAAU,SAAS,GAAG,EAAI,UAAU,MAAM,EAAG,EAAE,EAAI,UAG7D,OAFI,OAAS,KAAO,OAAS,GAAW,IAAM,GAAK,IAAM,EAElD,GAAG,IADA,KAAK,WAAW,GAAG,EAAI,KAAO,IAAI,QAE9C"}
1
+ {"version":3,"file":"h3-web.mjs","names":[],"sources":["../../../src/http/runtimes/h3-web.ts"],"sourcesContent":["// The h3 v2 (web-standards) runtime — `@forinda/kickjs/h3-web`.\n//\n// ADDITIVE runtime: the h3 v1 runtime (`./h3.ts`, `@forinda/kickjs/h3`)\n// stays untouched so existing adopters keep working. This runtime targets h3 >= 2 — the\n// web-standard rebase where `event.req` is a WHATWG Request, handlers\n// return values/Responses, and `app.fetch(request)` is the universal entry.\n//\n// The request pipeline runs through the shared web driver pair\n// (`../web/driver`, `../web/handler`) — the same code path the\n// `@forinda/kickjs/web` edge entry uses, so node bootstrap and edge deploys\n// exercise identical request semantics.\n//\n// Known limitation vs the v1 runtime: no Vite dev-server fall-through —\n// unmatched requests are answered by the kick notFound handler (h3 v2 owns\n// the full request; there is no node `next()` bail-out mid-engine). Use the\n// v1 h3 runtime or Express for Vite-integrated dev setups.\n\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport { createRequire } from 'node:module'\n\nimport type {\n ConnectMiddleware,\n HttpRuntime,\n RouteTable,\n RuntimeAppOptions,\n UseConnectOptions,\n} from '../runtime'\nimport { compileWebRoute, type WebRouteHooks } from '../web/handler'\nimport { WebRequestShim, WebResponseDriver } from '../web/driver'\nimport { createLogger, describeError } from '../../core/logger'\n\nconst log = createLogger('H3WebRuntime')\n\nconst peerRequire = createRequire(import.meta.url)\n\nconst NOTFOUND_MW = Symbol('kickjs.h3web.notFoundMw')\nconst ERROR_MW = Symbol('kickjs.h3web.errorMw')\nconst ASSEMBLED = Symbol('kickjs.h3web.assembled')\nconst NOOP_NEXT = (): void => {}\n\n// Minimal structural surface of h3 v2 we depend on.\ninterface H3AppLike {\n on(method: string, path: string, handler: (event: H3EventLike) => unknown): unknown\n all(path: string, handler: (event: H3EventLike) => unknown): unknown\n use(...args: unknown[]): unknown\n fetch(request: Request): Promise<Response>\n}\ninterface H3EventLike {\n req: Request & { runtime?: { node?: { req: IncomingMessage; res: ServerResponse } } }\n url: URL\n context: { params?: Record<string, string> }\n}\n\ninterface H3v2Module {\n H3: new (config?: unknown) => H3AppLike\n toNodeHandler: (app: H3AppLike) => (req: IncomingMessage, res: ServerResponse) => void\n fromNodeHandler: (mw: unknown) => unknown\n}\n\nexport interface H3WebRuntimeOptions {\n /**\n * Pre-imported h3 v2 module. Two audiences:\n * - Edge/worker bundlers with no `createRequire` at runtime:\n * `h3WebRuntime({ h3: await import('h3') })`\n * - Tests running both h3 majors side by side via an npm alias.\n * Omitted → the peer is loaded via `createRequire` (node bootstrap path).\n */\n h3?: unknown\n}\n\n/** Resolve h3 (injected or peer-required) and fail fast unless it is v2. */\nfunction loadH3v2(injected?: unknown): H3v2Module {\n const mod = injected ?? peerRequire('h3')\n const m = mod as { __esModule?: boolean; default?: Record<string, unknown> } & Record<\n string,\n unknown\n >\n const resolved = (m && m.__esModule && m.default\n ? { ...m.default, ...m }\n : m) as unknown as H3v2Module\n if (typeof resolved.H3 !== 'function') {\n throw new Error(\n \"@forinda/kickjs: h3WebRuntime() requires h3 v2 (the web-standards line, npm dist-tag 'latest'), \" +\n 'but the installed h3 has no H3 class — that is the v1 line. ' +\n \"Either `pnpm add h3@latest` for this runtime, or keep h3 v1 and use h3Runtime() from '@forinda/kickjs/h3'.\",\n )\n }\n return resolved\n}\n\n/**\n * Bridge a connect-style terminal middleware (kick's notFound / error\n * handlers) onto the web driver pair, returning the produced Response.\n */\nasync function runConnectTerminal(\n mw: ConnectMiddleware | undefined,\n event: H3EventLike,\n err?: unknown,\n): Promise<Response> {\n const req = new WebRequestShim(event.req, event.url)\n const driver = new WebResponseDriver(event.req.signal)\n if (mw) {\n if (err !== undefined) {\n ;(mw as (e: unknown, rq: unknown, rs: unknown, n: () => void) => void)(\n err,\n req,\n driver,\n NOOP_NEXT,\n )\n } else {\n ;(mw as (rq: unknown, rs: unknown, n: () => void) => void)(req, driver, NOOP_NEXT)\n }\n }\n if (!driver.settled) {\n if (err !== undefined) {\n // The configured error handler ran but didn't settle the response\n // (or there wasn't one). Emitting a bare 500 with no log entry\n // makes this failure invisible on both sides — log it here, since\n // by definition nothing downstream will.\n log.error(err, `h3-web: error handler did not settle the response — ${describeError(err)}`)\n driver.status(500).json({\n error: 'Internal Server Error',\n ...(typeof process !== 'undefined' && process.env?.NODE_ENV === 'production'\n ? {}\n : { message: describeError(err) }),\n })\n } else {\n driver.status(404).json({ error: 'Not Found' })\n }\n }\n return driver.ready\n}\n\n// ── Connect middleware on the fetch path ─────────────────────────────────\n//\n// `app.fetch(request)` (edge, Bun, Deno, a serverless function) carries no\n// node req/res, and h3's `fromNodeHandler` throws without one. Connect\n// middleware there runs against the web driver pair instead: one request shim\n// per event (so `req.requestId` set by one middleware is seen by the next) and\n// one header bag per event that is merged into whatever Response comes back.\n// The merge is ours rather than h3's `event.res.headers` because h3 skips\n// prepared headers on non-2xx responses, and a 404/422/500 must still carry\n// helmet's headers and the request id, exactly as on node.\n\ninterface FetchConnectState {\n req: WebRequestShim\n headers: Headers\n}\n\nconst FETCH_CONNECT = new WeakMap<object, FetchConnectState>()\n\nfunction fetchConnectState(event: H3EventLike): FetchConnectState {\n let state = FETCH_CONNECT.get(event)\n if (!state) {\n state = { req: new WebRequestShim(event.req, event.url), headers: new Headers() }\n FETCH_CONNECT.set(event, state)\n }\n return state\n}\n\n/**\n * Add the headers connect middleware set to `response`. The response's own\n * headers win — a later `setHeader` overrides an earlier one on node too.\n * Consumed once, so every middleware layer can call it on the way out.\n */\nfunction withConnectHeaders(event: H3EventLike, response: Response): Response {\n const state = FETCH_CONNECT.get(event)\n if (!state) return response\n const missing = [...state.headers].filter(\n ([name]) => name === 'set-cookie' || !response.headers.has(name),\n )\n state.headers = new Headers()\n if (missing.length === 0) return response\n try {\n for (const [name, value] of missing) response.headers.append(name, value)\n return response\n } catch {\n // Immutable headers (a Response from fetch) — rebuild around the body.\n const headers = new Headers(response.headers)\n for (const [name, value] of missing) headers.append(name, value)\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n })\n }\n}\n\n/**\n * The node `res` surface connect middleware uses, over the web driver:\n * headers go to the per-event bag, `statusCode`, and `finish`/`close`\n * emitted once the response exists.\n */\nclass FetchConnectResponse extends WebResponseDriver {\n private code = 200\n private listeners: Array<[string, (...args: unknown[]) => void]> = []\n\n constructor(\n private readonly prepared: Headers,\n signal: AbortSignal,\n ) {\n super(signal)\n }\n\n get statusCode(): number {\n return this.code\n }\n\n set statusCode(code: number) {\n this.status(code)\n }\n\n override status(code: number): this {\n this.code = code\n return super.status(code)\n }\n\n override writeHead(code: number, headers?: Record<string, string | number | string[]>): this {\n this.code = code\n return super.writeHead(code, headers)\n }\n\n override setHeader(name: string, value: unknown): this {\n if (Array.isArray(value)) {\n this.prepared.delete(name)\n for (const v of value) this.prepared.append(name, String(v))\n } else {\n this.prepared.set(name, String(value))\n }\n return this\n }\n\n getHeader(name: string): string | undefined {\n return this.prepared.get(name) ?? undefined\n }\n\n hasHeader(name: string): boolean {\n return this.prepared.has(name)\n }\n\n removeHeader(name: string): void {\n this.prepared.delete(name)\n }\n\n override once(event: string, listener: (...args: unknown[]) => void): this {\n this.listeners.push([event, listener])\n return this\n }\n\n on(event: string, listener: (...args: unknown[]) => void): this {\n return this.once(event, listener)\n }\n\n removeListener(event: string, listener: (...args: unknown[]) => void): this {\n this.listeners = this.listeners.filter(([e, l]) => e !== event || l !== listener)\n return this\n }\n\n off(event: string, listener: (...args: unknown[]) => void): this {\n return this.removeListener(event, listener)\n }\n\n /** The response exists (or the request failed): fire `finish` then `close`. */\n done(): void {\n for (const event of ['finish', 'close']) {\n for (const [e, listener] of this.listeners) if (e === event) listener()\n this.listeners = this.listeners.filter(([e]) => e !== event)\n }\n }\n}\n\nfunction runConnectOnFetch(\n mw: ConnectMiddleware,\n event: H3EventLike,\n next: () => unknown,\n): Promise<unknown> {\n const state = fetchConnectState(event)\n const res = new FetchConnectResponse(state.headers, event.req.signal)\n\n return new Promise((resolve, reject) => {\n const respond = (response: Response): void => {\n res.done()\n resolve(withConnectHeaders(event, response))\n }\n const fail = (err: unknown): void => {\n res.done()\n reject(err)\n }\n\n // The middleware answered itself (`res.end`, `res.json`, `writeHead`).\n void res.ready.then(respond)\n\n const connectNext = (err?: unknown): void => {\n if (err) return fail(err)\n if (res.settled) return\n // The route builds its request store from the inbound header; hand it the\n // id requestScope/requestId settled on so body, logs and header agree.\n const id = state.req.requestId\n if (id && event.req.headers.get('x-request-id') !== id) {\n try {\n event.req.headers.set('x-request-id', id)\n } catch {\n // Immutable request headers on some runtimes — the route mints its own id.\n }\n }\n let downstream: unknown\n try {\n // Synchronous, so downstream work starts inside any AsyncLocalStorage\n // scope this middleware opened (requestScopeMiddleware).\n downstream = next()\n } catch (e) {\n return fail(e)\n }\n Promise.resolve(downstream).then((value) => {\n if (value instanceof Response) return respond(value)\n res.done()\n resolve(value)\n }, fail)\n }\n\n try {\n ;(mw as (rq: unknown, rs: unknown, n: (err?: unknown) => void) => void)(\n state.req,\n res,\n connectNext,\n )\n } catch (err) {\n fail(err)\n }\n })\n}\n\n/**\n * Terminal catch-all AFTER all mounted routes: kick's own notFound handler\n * answers unmatched paths (h3 v2's default 404 never fires). rou3 ranks `/**`\n * below every concrete route, so registration time does not matter.\n */\nfunction assembleCatchAll(app: H3AppLike): void {\n const state = app as unknown as Record<symbol, unknown>\n if (state[ASSEMBLED]) return\n state[ASSEMBLED] = true\n app.all('/**', (event: H3EventLike) => {\n const mw = state[NOTFOUND_MW] as ConnectMiddleware | undefined\n return runConnectTerminal(mw, event)\n })\n}\n\n/**\n * The h3 v2 HTTP runtime. Pass to `bootstrap({ runtime: h3WebRuntime() })`.\n * Requires the h3 v2 peer; fails fast with guidance when v1 is installed.\n */\nexport function h3WebRuntime(options: H3WebRuntimeOptions = {}): HttpRuntime<H3AppLike> {\n const { H3, toNodeHandler, fromNodeHandler } = loadH3v2(options.h3)\n\n return {\n name: 'h3-web',\n\n createApp(_options: RuntimeAppOptions = {}): H3AppLike {\n const holder: { app?: H3AppLike } = {}\n const app = new H3({\n // Engine-level errors (middleware throws outside the kick pipeline)\n // dispatch to the kick error handler once setErrorHandler stashes it.\n onError: (error: unknown, event: H3EventLike) => {\n const mw = (holder.app as unknown as Record<symbol, ConnectMiddleware | undefined>)?.[\n ERROR_MW\n ]\n return runConnectTerminal(mw, event, error).then((response) =>\n withConnectHeaders(event, response),\n )\n },\n })\n holder.app = app\n return app\n },\n\n nodeHandler(app) {\n assembleCatchAll(app)\n const listener = toNodeHandler(app)\n return (req: IncomingMessage, res: ServerResponse, next?: (err?: unknown) => void) => {\n try {\n const result = listener(req, res) as unknown\n if (result && typeof (result as Promise<unknown>).then === 'function') {\n void (result as Promise<unknown>).catch((err) => next?.(err))\n }\n } catch (err) {\n next?.(err)\n }\n }\n },\n\n mountRoutes(app, table: RouteTable) {\n for (const { mountPath, routes } of table) {\n for (const entry of routes) {\n const url = joinPath(mountPath, entry.path)\n const hooks: WebRouteHooks = {\n onError: async (err, req, driver) => {\n const mw = (app as unknown as Record<symbol, ConnectMiddleware | undefined>)[ERROR_MW]\n if (!mw) return\n ;(mw as (e: unknown, rq: unknown, rs: unknown, n: () => void) => void)(\n err,\n req,\n driver,\n NOOP_NEXT,\n )\n },\n }\n const run = compileWebRoute(entry, hooks)\n app.on(entry.method, url, (event: H3EventLike) =>\n run({\n request: event.req,\n url: event.url,\n params: event.context.params ?? {},\n }),\n )\n }\n }\n },\n\n useConnect(app, mw: ConnectMiddleware, opts?: UseConnectOptions) {\n // Behind a node server (toNodeHandler) the event carries node req/res and\n // h3's own bridge runs the middleware unchanged. Called through\n // `app.fetch(request)` there is none and fromNodeHandler would throw, so\n // the middleware runs against the web driver pair instead.\n const viaNode = fromNodeHandler(mw) as (event: H3EventLike) => unknown\n const handler = (event: H3EventLike, next: () => unknown) =>\n event.req.runtime?.node?.res ? viaNode(event) : runConnectOnFetch(mw, event, next)\n if (opts?.path !== undefined) {\n // v2 `use` is exact-match; `/**` covers the subtree like v1's prefix.\n app.use(joinPath(String(opts.path), '/**'), handler)\n } else {\n app.use(handler)\n }\n },\n\n serveStatic(app, prefix, dir) {\n // serve-static bridged like any other connect middleware (node only).\n const serveStatic = peerRequire('serve-static')\n this.useConnect(app, serveStatic(dir) as ConnectMiddleware, { path: prefix })\n },\n\n setNotFound(app, mw: ConnectMiddleware) {\n ;(app as unknown as Record<symbol, ConnectMiddleware>)[NOTFOUND_MW] = mw\n // Here as well as in nodeHandler: an app only ever called through\n // `app.fetch` never reaches nodeHandler, and would answer h3's own 404.\n assembleCatchAll(app)\n },\n\n setErrorHandler(app, mw: ConnectMiddleware) {\n ;(app as unknown as Record<symbol, ConnectMiddleware>)[ERROR_MW] = mw\n },\n\n capabilities: {\n render: false,\n uploads: true,\n connectMiddleware: true,\n nativeBodyParsing: true,\n },\n }\n}\n\n/**\n * h3-web runtime engine types for the `kick/runtime` typegen augmentation —\n * mirrors {@link import('./h3').H3RuntimeTypes} for the v1 runtime.\n */\nexport interface H3WebRuntimeTypes {\n request: Request\n response: Response\n app: unknown\n}\n\n/** Join a mount prefix and a route path into one URL, collapsing slashes. */\nfunction joinPath(mountPath: string, path: string): string {\n const a = mountPath.endsWith('/') ? mountPath.slice(0, -1) : mountPath\n if (path === '/' || path === '') return a === '' ? '/' : a\n const b = path.startsWith('/') ? path : `/${path}`\n return `${a}${b}`\n}\n"],"mappings":";;;;;;;;;;6MA+BA,MAAM,IAAM,aAAa,cAAc,EAEjC,YAAc,cAAc,YAAY,GAAG,EAE3C,YAAc,OAAO,yBAAyB,EAC9C,SAAW,OAAO,sBAAsB,EACxC,UAAY,OAAO,wBAAwB,EAC3C,cAAwB,CAAC,EAiC/B,SAAS,SAAS,SAAgC,CAEhD,IAAM,EADM,UAAY,YAAY,IAAI,EAKlC,SAAY,GAAK,EAAE,YAAc,EAAE,QACrC,CAAE,GAAG,EAAE,QAAS,GAAG,CAAE,EACrB,EACJ,GAAI,OAAO,SAAS,IAAO,WACzB,MAAU,MACR,wQAGF,EAEF,OAAO,QACT,CAMA,eAAe,mBACb,GACA,MACA,IACmB,CACnB,IAAM,IAAM,IAAI,eAAe,MAAM,IAAK,MAAM,GAAG,EAC7C,OAAS,IAAI,kBAAkB,MAAM,IAAI,MAAM,EA8BrD,OA7BI,KACE,MAAQ,IAAA,GAQT,GAA0D,IAAK,OAAQ,SAAS,EAPhF,GACC,IACA,IACA,OACA,SACF,GAKC,OAAO,UACN,MAAQ,IAAA,GAaV,OAAO,OAAO,GAAG,CAAC,CAAC,KAAK,CAAE,MAAO,WAAY,CAAC,GAR9C,IAAI,MAAM,IAAK,uDAAuD,cAAc,GAAG,GAAG,EAC1F,OAAO,OAAO,GAAG,CAAC,CAAC,KAAK,CACtB,MAAO,wBACP,GAAI,OAAO,QAAY,KAAe,QAAQ,KAAK,WAAa,aAC5D,CAAC,EACD,CAAE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C9E,EAEA,YAAY,IAAK,GAAuB,CACrC,IAAsD,aAAe,GAGtE,iBAAiB,GAAG,CACtB,EAEA,gBAAgB,IAAK,GAAuB,CACzC,IAAsD,UAAY,EACrE,EAEA,aAAc,CACZ,OAAQ,GACR,QAAS,GACT,kBAAmB,GACnB,kBAAmB,EACrB,CACF,CACF,CAaA,SAAS,SAAS,UAAmB,KAAsB,CACzD,IAAM,EAAI,UAAU,SAAS,GAAG,EAAI,UAAU,MAAM,EAAG,EAAE,EAAI,UAG7D,OAFI,OAAS,KAAO,OAAS,GAAW,IAAM,GAAK,IAAM,EAElD,GAAG,IADA,KAAK,WAAW,GAAG,EAAI,KAAO,IAAI,QAE9C"}
@@ -1,15 +1,10 @@
1
1
 
2
- import { f as HttpRuntime } from "../../adapter-2bnoYEPX.mjs";
2
+ import { p as HttpRuntime } from "../../adapter-DhjoIYVI.mjs";
3
3
  //#region src/http/runtimes/h3.d.ts
4
4
  interface H3AppLike {
5
5
  use(arg1: unknown, arg2?: unknown): unknown;
6
6
  handler: unknown;
7
7
  }
8
- /**
9
- * The h3 HTTP runtime. Pass to `bootstrap({ runtime: h3Runtime() })`.
10
- * h3 parses bodies itself (`readBody`), so the Application skips its default
11
- * `express.json()` (see `nativeBodyParsing`).
12
- */
13
8
  export declare function h3Runtime(): HttpRuntime<H3AppLike>;
14
9
  /**
15
10
  * The h3 runtime's engine-native types — what the runtime-typed escape hatches
@@ -1 +1 @@
1
- {"version":3,"file":"h3.d.mts","names":[],"sources":["../../../src/http/runtimes/h3.ts"],"mappings":";;;UA+CU;EACR,IAAI,eAAe;EACnB;;;;;;;wBA0Qc,aAAa,YAAY;;;;;;;;KAyIpC;EAA0C,WAAW;IAAM;KAC3D;EAA4C,iBAAiB,wBAAwB;IACtF;iBAGa;EACf,SAAS;EACT,UAAU;EACV,KAAK"}
1
+ {"version":3,"file":"h3.d.mts","names":[],"sources":["../../../src/http/runtimes/h3.ts"],"mappings":";;;UA+CU;EACR,IAAI,eAAe;EACnB;;wBAoSc,aAAa,YAAY;;;;;;;;KAiJpC;EAA0C,WAAW;IAAM;KAC3D;EAA4C,iBAAiB,wBAAwB;IACtF;iBAGa;EACf,SAAS;EACT,UAAU;EACV,KAAK"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v8.6.0
2
+ * @forinda/kickjs v9.0.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- 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-C-7Yhs7a.mjs";import{i as requestStore,t as RequestContext}from"../../context-BTqeZH1A.mjs";import{validate}from"../middleware/validate.mjs";import{t as applyUploadConfig}from"../../upload-config-CoE6BzM4.mjs";import"../middleware/upload.mjs";import{createRequire}from"node:module";const peerRequire=createRequire(import.meta.url),h3=()=>peerRequire(`h3`),NEXT=Symbol(`kickjs.h3.next`),ERROR_MW=Symbol(`kickjs.h3.errorMw`),ROUTER=Symbol(`kickjs.h3.router`),NOTFOUND_MW=Symbol(`kickjs.h3.notFoundMw`),ASSEMBLED=Symbol(`kickjs.h3.assembled`),NOOP_NEXT=()=>{},BODY_METHODS=new Set([`POST`,`PUT`,`PATCH`,`DELETE`]);var NodeResDriver=class{res;constructor(res){this.res=res}status(code){return this.res.statusCode=code,this}json(data){return!this.res.headersSent&&!this.res.getHeader(`content-type`)&&this.res.setHeader(`content-type`,`application/json; charset=utf-8`),this.res.end(JSON.stringify(data)),this}send(data){return this.res.end(data),this}type(contentType){return this.res.setHeader(`content-type`,contentType),this}setHeader(name,value){return this.res.setHeader(name,value),this}render(){throw Error(`ctx.render() is not supported on the h3 runtime (no view engine).`)}writeHead(statusCode,headers){return this.res.writeHead(statusCode,headers),this}flushHeaders(){return this.res.flushHeaders(),this}write(chunk){return this.res.write(chunk)}end(data){return this.res.end(data),this}once(event,listener){return this.res.once(event,listener),this}get headersSent(){return this.res.headersSent}};function resDriver(res){return new NodeResDriver(res)}const TRUST_PROXY=Symbol(`kickjs.h3.trustProxy`);function makeEventHandler(entry,trustProxy){let{getRouterParams,getQuery,readRawBody,readMultipartFormData}=h3(),upload=entry.meta.upload,validator=entry.meta.validation?validate(entry.meta.validation):void 0;return async event=>{let req=event.node.req,res=event.node.res;if(trustProxy&&!req.ip){let forwarded=req.headers[`x-forwarded-for`],first=(Array.isArray(forwarded)?forwarded[0]:forwarded)?.split(`,`)[0]?.trim();first&&(req.ip=first)}if(req.params=getRouterParams(event)??{},req.query=getQuery(event)??{},upload&&upload.mode!==`none`){let form=await readMultipartFormData(event).catch(()=>void 0),rawParts=[],fields={};for(let part of form??[])part.filename?rawParts.push({fieldname:part.name??``,filename:part.filename,mimetype:part.type??`application/octet-stream`,buffer:part.data}):part.name&&(fields[part.name]=part.data.toString(`utf-8`));let{file,files}=applyUploadConfig(rawParts,upload);req.file=file,req.files=files,req.body=fields}else if(BODY_METHODS.has(req.method??`GET`)){let{"content-length":length,"transfer-encoding":encoding}=req.headers;if(encoding!==void 0||length!==void 0&&length!==`0`){let kind=classifyMediaType(req.headers[`content-type`]);if(kind!==`multipart`){let raw=await readRawBody(event,`utf8`);if(raw){if(kind===`unsupported`)throw unsupportedMediaTypeError(req.headers[`content-type`]);if(kind===`json`)try{req.body=JSON.parse(raw)}catch(err){throw 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 headerId=req.headers[`x-request-id`],requestId=(Array.isArray(headerId)?headerId[0]:headerId)||req.requestId,store=createRequestStore(requestId);req.requestId=store.requestId,res.once(`close`,()=>disposeRequestStore(store)),await requestStore.run(store,async()=>{publishMatchedRoute(req,entry);let ctx=new RequestContext(req,res,NOOP_NEXT,resDriver(res));if(entry.earlyContributorRunner&&(await entry.earlyContributorRunner(ctx),res.writableEnded))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||res.writableEnded)return}if(entry.contributorRunner&&await entry.contributorRunner(ctx),res.writableEnded)return;let result=await entry.handler(ctx);!res.writableEnded&&!res.headersSent&&applyHandlerResult(ctx,result)})}}function unwrapH3Error(error){if(!(error instanceof Error))return error;let{cause}=error;return cause instanceof Error?cause:error}function h3Runtime(){return{name:`h3`,createApp(options={}){let{createApp}=h3(),app=createApp({onError:(error,event)=>{let res=event.node.res;if(res.writableEnded)return;let state=app;if(error?.statusCode===404){let next=event.node.req[NEXT];if(next){next();return}let nf=state[NOTFOUND_MW];if(nf){nf(event.node.req,resDriver(res),NOOP_NEXT);return}}let mw=state[ERROR_MW];mw&&mw(unwrapH3Error(error),event.node.req,resDriver(res),NOOP_NEXT)}});return app[TRUST_PROXY]=options.trustProxy,app},nodeHandler(app){let{toNodeListener}=h3(),state=app;state[ASSEMBLED]||(state[ASSEMBLED]=!0,state[ROUTER]&&app.use(state[ROUTER]));let listener=toNodeListener(app);return(req,res,next)=>{next&&(req[NEXT]=next),Promise.resolve(listener(req,res)).catch(err=>{next&&next(err)})}},mountRoutes(app,table){let{createRouter,eventHandler}=h3(),trustProxy=!!app[TRUST_PROXY],state=app;state[ROUTER]||(state[ROUTER]=createRouter());let router=state[ROUTER];for(let{mountPath,routes}of table)for(let entry of routes){let url=joinPath(mountPath,entry.path);router[entry.method.toLowerCase()](url,eventHandler(makeEventHandler(entry,trustProxy)))}},useConnect(app,mw,opts){let{fromNodeMiddleware}=h3(),handler=fromNodeMiddleware(mw);opts?.path===void 0?app.use(handler):app.use(opts.path,handler)},serveStatic(app,prefix,dir){let serveStatic=peerRequire(`serve-static`);this.useConnect(app,serveStatic(dir),{path:prefix})},setNotFound(app,mw){app[NOTFOUND_MW]=mw},setErrorHandler(app,mw){app[ERROR_MW]=mw},capabilities:{render:!1,uploads:!0,connectMiddleware:!0,nativeBodyParsing:!0}}}function joinPath(mountPath,path){let a=mountPath.endsWith(`/`)?mountPath.slice(0,-1):mountPath;return path===`/`||path===``?a===``?`/`:a:`${a}${path.startsWith(`/`)?path:`/${path}`}`}export{h3Runtime};
11
+ 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-DGzigyO2.mjs";import{l as requestStore,t as RequestContext}from"../../context-DlIdXA6I.mjs";import{validate}from"../middleware/validate.mjs";import{t as applyUploadConfig}from"../../upload-config-CcoZp7xA.mjs";import"../middleware/upload.mjs";import{createRequire}from"node:module";const peerRequire=createRequire(import.meta.url),h3=()=>peerRequire(`h3`),NEXT=Symbol(`kickjs.h3.next`),ERROR_MW=Symbol(`kickjs.h3.errorMw`),ROUTER=Symbol(`kickjs.h3.router`),NOTFOUND_MW=Symbol(`kickjs.h3.notFoundMw`),ASSEMBLED=Symbol(`kickjs.h3.assembled`),NOOP_NEXT=()=>{},BODY_METHODS=new Set([`POST`,`PUT`,`PATCH`,`DELETE`]);var NodeResDriver=class{res;constructor(res){this.res=res}status(code){return this.res.statusCode=code,this}json(data){return!this.res.headersSent&&!this.res.getHeader(`content-type`)&&this.res.setHeader(`content-type`,`application/json; charset=utf-8`),this.res.end(JSON.stringify(data)),this}send(data){return this.res.end(data),this}type(contentType){return this.res.setHeader(`content-type`,contentType),this}setHeader(name,value){return this.res.setHeader(name,value),this}render(){throw Error(`ctx.render() is not supported on the h3 runtime (no view engine).`)}writeHead(statusCode,headers){return this.res.writeHead(statusCode,headers),this}flushHeaders(){return this.res.flushHeaders(),this}write(chunk){return this.res.write(chunk)}end(data){return this.res.end(data),this}once(event,listener){return this.res.once(event,listener),this}get headersSent(){return this.res.headersSent}};function resDriver(res){return new NodeResDriver(res)}const TRUST_PROXY=Symbol(`kickjs.h3.trustProxy`);function makeEventHandler(entry,trustProxy){let{getRouterParams,getQuery,readRawBody,readMultipartFormData}=h3(),upload=entry.meta.upload,validator=entry.meta.validation?validate(entry.meta.validation):void 0;return async event=>{let req=event.node.req,res=event.node.res;if(trustProxy&&!req.ip){let forwarded=req.headers[`x-forwarded-for`],first=(Array.isArray(forwarded)?forwarded[0]:forwarded)?.split(`,`)[0]?.trim();first&&(req.ip=first)}if(req.params=getRouterParams(event)??{},req.query=getQuery(event)??{},req.httpVersionMajor===2&&req.headers[`content-length`]===void 0&&BODY_METHODS.has(req.method??`GET`)&&(req.rawBody=await readStreamBuffer(req)),upload&&upload.mode!==`none`){let form=await readMultipartFormData(event).catch(()=>void 0),rawParts=[],fields={};for(let part of form??[])part.filename?rawParts.push({fieldname:part.name??``,filename:part.filename,mimetype:part.type??`application/octet-stream`,buffer:part.data}):part.name&&(fields[part.name]=part.data.toString(`utf-8`));let{file,files}=applyUploadConfig(rawParts,upload);req.file=file,req.files=files,req.body=fields}else if(BODY_METHODS.has(req.method??`GET`)){let{"content-length":length,"transfer-encoding":encoding}=req.headers;if(encoding!==void 0||length!==void 0&&length!==`0`||req.httpVersionMajor===2&&length!==`0`){let kind=classifyMediaType(req.headers[`content-type`]);if(kind!==`multipart`){let raw=await readRawBody(event,`utf8`);if(raw){if(kind===`unsupported`)throw unsupportedMediaTypeError(req.headers[`content-type`]);if(kind===`json`)try{req.body=JSON.parse(raw)}catch(err){throw 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 headerId=req.headers[`x-request-id`],requestId=(Array.isArray(headerId)?headerId[0]:headerId)||req.requestId,store=createRequestStore(requestId);req.requestId=store.requestId,res.once(`close`,()=>disposeRequestStore(store)),await requestStore.run(store,async()=>{publishMatchedRoute(req,entry);let ctx=new RequestContext(req,res,NOOP_NEXT,resDriver(res));if(entry.earlyContributorRunner&&(await entry.earlyContributorRunner(ctx),res.writableEnded))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||res.writableEnded)return}if(entry.contributorRunner&&await entry.contributorRunner(ctx),res.writableEnded)return;let result=await entry.handler(ctx);!res.writableEnded&&!res.headersSent&&applyHandlerResult(ctx,result)})}}function unwrapH3Error(error){if(!(error instanceof Error))return error;let{cause}=error;return cause instanceof Error?cause:error}async function readStreamBuffer(req){let chunks=[];for await(let chunk of req)chunks.push(typeof chunk==`string`?Buffer.from(chunk):chunk);return Buffer.concat(chunks)}function h3Runtime(){return{name:`h3`,createApp(options={}){let{createApp}=h3(),app=createApp({onError:(error,event)=>{let res=event.node.res;if(res.writableEnded)return;let state=app,status=error?.statusCode,thrownByHandler=error?.cause instanceof Error;if(status===404&&!thrownByHandler){let next=event.node.req[NEXT];if(next){next();return}let nf=state[NOTFOUND_MW];if(nf){nf(event.node.req,resDriver(res),NOOP_NEXT);return}}let mw=state[ERROR_MW];mw&&mw(unwrapH3Error(error),event.node.req,resDriver(res),NOOP_NEXT)}});return app[TRUST_PROXY]=options.trustProxy,app},nodeHandler(app){let{toNodeListener}=h3(),state=app;state[ASSEMBLED]||(state[ASSEMBLED]=!0,state[ROUTER]&&app.use(state[ROUTER]));let listener=toNodeListener(app);return(req,res,next)=>{next&&(req[NEXT]=next),Promise.resolve(listener(req,res)).catch(err=>{next&&next(err)})}},mountRoutes(app,table){let{createRouter,eventHandler}=h3(),trustProxy=!!app[TRUST_PROXY],state=app;state[ROUTER]||(state[ROUTER]=createRouter());let router=state[ROUTER];for(let{mountPath,routes}of table)for(let entry of routes){let url=joinPath(mountPath,entry.path);router[entry.method.toLowerCase()](url,eventHandler(makeEventHandler(entry,trustProxy)))}},useConnect(app,mw,opts){let{fromNodeMiddleware}=h3(),handler=fromNodeMiddleware(mw);opts?.path===void 0?app.use(handler):app.use(opts.path,handler)},serveStatic(app,prefix,dir){let serveStatic=peerRequire(`serve-static`);this.useConnect(app,serveStatic(dir),{path:prefix})},setNotFound(app,mw){app[NOTFOUND_MW]=mw},setErrorHandler(app,mw){app[ERROR_MW]=mw},capabilities:{render:!1,uploads:!0,connectMiddleware:!0,nativeBodyParsing:!0,http2:!0}}}function joinPath(mountPath,path){let a=mountPath.endsWith(`/`)?mountPath.slice(0,-1):mountPath;return path===`/`||path===``?a===``?`/`:a:`${a}${path.startsWith(`/`)?path:`/${path}`}`}export{h3Runtime};
12
12
  //# sourceMappingURL=h3.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"h3.mjs","names":[],"sources":["../../../src/http/runtimes/h3.ts"],"sourcesContent":["// The h3 runtime — `@forinda/kickjs/h3`.\n//\n// h3 (unjs) is the HTTP layer behind Nitro / Nuxt. This binds it to the same\n// HttpRuntime contract as Express and Fastify: routes become native h3 router\n// routes, and the node `ServerResponse` (h3 exposes it as `event.node.res`) is\n// wrapped in a RuntimeResponse so `ctx.json` / `ctx.html` / `ctx.sse` work\n// unchanged.\n//\n// Targets h3 **v1** (stable, node-based: `createApp` / `createRouter` /\n// `toNodeListener`, with `event.node.req` / `event.node.res`). `h3` is an\n// optional peer pinned to `^1`.\n//\n// h3 v2 (https://h3.dev/migration) moves to a web-standard `Request`/`Response`\n// core. Adopting it is the spec's §8 \"web-standard driver\" — `RuntimeResponse`\n// was shaped so a future `webRuntime()` can implement it over WHATWG streams,\n// at which point h3 v2 (and edge/Bun/Deno) become a driver swap rather than a\n// rewrite. Until that lands, this binding uses the node-compatible v1 surface.\n\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport { createRequire } from 'node:module'\n\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 { HttpException } from '../../core/errors'\nimport { applyUploadConfig, type RawUploadPart } from '../middleware/upload'\nimport type {\n ConnectMiddleware,\n HttpRuntime,\n RouteEntry,\n RouteTable,\n RuntimeAppOptions,\n RuntimeResponse,\n UseConnectOptions,\n} from '../runtime'\n\nconst peerRequire = createRequire(import.meta.url)\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst h3 = (): any => peerRequire('h3')\n\ninterface H3EventLike {\n node: { req: IncomingMessage; res: ServerResponse }\n}\ninterface H3AppLike {\n use(arg1: unknown, arg2?: unknown): unknown\n handler: unknown\n}\n\nconst NEXT = Symbol('kickjs.h3.next')\nconst ERROR_MW = Symbol('kickjs.h3.errorMw')\n// h3's `createRouter` is terminal — on no match it THROWS a 404, it does not\n// fall through to the next `app.use` layer like an Express Router. So every\n// route source (controllers, /health, devtools /_debug, ad-hoc adapter routes)\n// must live on ONE shared router, registered AFTER all connect middleware.\nconst ROUTER = Symbol('kickjs.h3.router')\nconst NOTFOUND_MW = Symbol('kickjs.h3.notFoundMw')\nconst ASSEMBLED = Symbol('kickjs.h3.assembled')\nconst NOOP_NEXT = (): void => {}\nconst BODY_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])\n\n/**\n * Wrap a node ServerResponse (from `event.node.res`) as a RuntimeResponse.\n * A class so the ~12 driver methods live on a shared prototype — the previous\n * object-literal version re-allocated every method closure on each request.\n */\nclass NodeResDriver implements RuntimeResponse {\n constructor(private readonly res: ServerResponse) {}\n status(code: number): this {\n this.res.statusCode = code\n return this\n }\n json(data: unknown): this {\n // Do not clobber a content-type the caller already chose. This used to set\n // `application/json` unconditionally, so every `application/problem+json`\n // response — RFC 9457 problem details, which the error handler sets the\n // header for before serialising — went out as plain JSON on this runtime\n // alone. Express and Fastify both leave an existing value alone.\n if (!this.res.headersSent && !this.res.getHeader('content-type')) {\n this.res.setHeader('content-type', 'application/json; charset=utf-8')\n }\n this.res.end(JSON.stringify(data))\n return this\n }\n send(data: unknown): this {\n this.res.end(data as never)\n return this\n }\n type(contentType: string): this {\n this.res.setHeader('content-type', contentType)\n return this\n }\n setHeader(name: string, value: unknown): this {\n this.res.setHeader(name, value as never)\n return this\n }\n render(): never {\n throw new Error('ctx.render() is not supported on the h3 runtime (no view engine).')\n }\n writeHead(statusCode: number, headers?: Record<string, string | number | string[]>): this {\n this.res.writeHead(statusCode, headers)\n return this\n }\n flushHeaders(): this {\n this.res.flushHeaders()\n return this\n }\n write(chunk: unknown): boolean {\n return this.res.write(chunk as never)\n }\n end(data?: unknown): this {\n this.res.end(data as never)\n return this\n }\n once(event: string, listener: (...args: unknown[]) => void): this {\n this.res.once(event, listener)\n return this\n }\n get headersSent(): boolean {\n return this.res.headersSent\n }\n}\n\nfunction resDriver(res: ServerResponse): RuntimeResponse {\n return new NodeResDriver(res) as unknown as RuntimeResponse\n}\n\n/** Carries `trustProxy` from createApp() to the per-route handlers. */\nconst TRUST_PROXY = Symbol('kickjs.h3.trustProxy')\n\n/** Build the h3 event handler that runs the kickjs pipeline for one route. */\nfunction makeEventHandler(\n entry: RouteEntry,\n trustProxy: boolean,\n): (event: H3EventLike) => Promise<void> {\n const { getRouterParams, getQuery, readRawBody, readMultipartFormData } = h3()\n const upload = entry.meta.upload\n // Validation middleware built ONCE per route (parity with Express) — calling\n // validate() per request re-allocated the closure every time.\n const validator = entry.meta.validation ? validate(entry.meta.validation) : undefined\n return async (event: H3EventLike) => {\n const req = event.node.req as IncomingMessage & {\n requestId?: string\n body?: unknown\n params?: unknown\n query?: unknown\n file?: unknown\n files?: unknown\n }\n const res = event.node.res\n\n // h3 computes no client address of its own, so `resolveClientIp` fell\n // straight through to the socket — which behind a proxy is the proxy, and\n // put every caller in one rate-limit bucket with no way to configure out\n // of it (#614). Express and Fastify derive `req.ip` from their own\n // trust-proxy settings; this is h3's equivalent, and like theirs it is\n // OFF unless the app opts in, because an unverified `x-forwarded-for` is\n // client-controllable.\n if (trustProxy && !(req as { ip?: string }).ip) {\n const forwarded = req.headers['x-forwarded-for']\n const first = (Array.isArray(forwarded) ? forwarded[0] : forwarded)?.split(',')[0]?.trim()\n if (first) (req as { ip?: string }).ip = first\n }\n\n // Populate the express-shaped request fields h3 keeps elsewhere.\n req.params = getRouterParams(event) ?? {}\n req.query = getQuery(event) ?? {}\n if (upload && upload.mode !== 'none') {\n // @FileUpload: read the multipart body once (readBody would consume the\n // same stream, so the two are mutually exclusive). File parts → the\n // multer-shaped ctx.file/ctx.files; non-file fields → req.body.\n const form = (await readMultipartFormData(event).catch(() => undefined)) as\n | Array<{ name?: string; filename?: string; type?: string; data: Buffer }>\n | undefined\n const rawParts: RawUploadPart[] = []\n const fields: Record<string, unknown> = {}\n for (const part of form ?? []) {\n if (part.filename) {\n rawParts.push({\n fieldname: part.name ?? '',\n filename: part.filename,\n mimetype: part.type ?? 'application/octet-stream',\n buffer: part.data,\n })\n } else if (part.name) {\n fields[part.name] = part.data.toString('utf-8')\n }\n }\n const { file, files } = applyUploadConfig(rawParts, upload)\n req.file = file\n req.files = files\n req.body = fields\n } else if (BODY_METHODS.has(req.method ?? 'GET')) {\n // Swallow ONLY the absent-body case. `.catch(() => undefined)` also\n // swallowed a malformed one, so h3 answered 200 with the handler running\n // on `undefined` where Express and Fastify both answer 400 — a client\n // sending broken JSON got a success response, and the handler executed\n // against data that was never valid.\n const { 'content-length': length, 'transfer-encoding': encoding } = req.headers\n const sentBody = encoding !== undefined || (length !== undefined && length !== '0')\n if (sentBody) {\n // Read raw and apply the shared policy rather than calling `readBody`,\n // whose own content-type dispatch is the source of the divergence:\n // it matches `application/json` with `===` (so `; charset=utf-8` misses)\n // and routes everything unrecognised through `destr`, which returns the\n // RAW STRING for malformed input instead of throwing (#590).\n const kind = classifyMediaType(req.headers['content-type'])\n if (kind !== 'multipart') {\n const raw = await readRawBody(event, 'utf8')\n // Reject only once the body is known to be non-empty. `sentBody` is\n // true for an empty CHUNKED post — `transfer-encoding` is present\n // with no payload — and rejecting on that alone would 415 a request\n // that sent nothing, contradicting the rule the other runtimes apply.\n if (raw) {\n if (kind === 'unsupported') {\n // A body was sent in a format the framework does not parse. Say\n // so rather than handing the handler `undefined` and letting it\n // fail somewhere less obvious.\n throw unsupportedMediaTypeError(req.headers['content-type'])\n }\n if (kind === 'json') {\n try {\n req.body = JSON.parse(raw)\n } catch (err) {\n throw 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 }\n\n const headerId = req.headers['x-request-id']\n const requestId = (Array.isArray(headerId) ? headerId[0] : headerId) || req.requestId\n const store = createRequestStore(requestId)\n req.requestId = store.requestId\n\n // @PreDestroy teardown for REQUEST-scoped instances once the response\n // closes (finished or aborted) — parity with requestScopeMiddleware.\n res.once('close', () => disposeRequestStore(store))\n\n await requestStore.run(store, async () => {\n publishMatchedRoute(req, entry)\n const ctx = new RequestContext(req as never, res as never, NOOP_NEXT, resDriver(res))\n\n // `beforeValidation` contributors (#677) — ahead of validation and middleware.\n if (entry.earlyContributorRunner) {\n await entry.earlyContributorRunner(ctx)\n if (res.writableEnded) 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 || res.writableEnded) return\n }\n\n if (entry.contributorRunner) await entry.contributorRunner(ctx)\n if (res.writableEnded) return\n const result = await entry.handler(ctx)\n // Return-value handlers (reply.ts): auto-send when nothing was written.\n if (!res.writableEnded && !res.headersSent) applyHandlerResult(ctx, result)\n })\n }\n}\n\n/**\n * The original error h3 wrapped.\n *\n * h3 routes every thrown value through `createError()`, which returns its own\n * error with the original on `cause`. Handing that wrapper to the shared error\n * middleware means it sees something Express and Fastify never give it, and the\n * responses diverge: `instanceof HttpException` fails, so a thrown\n * `HttpException(418)` falls through to the generic branch and picks up a\n * `requestId` the other two omit, and `describeError` walks the cause chain to\n * report `kaboom ← caused by kaboom`.\n *\n * Only an `Error` cause is unwrapped. h3's own 404 carries no cause, so the\n * not-found path above is unaffected.\n */\nfunction unwrapH3Error(error: unknown): unknown {\n if (!(error instanceof Error)) return error\n const { cause } = error as { cause?: unknown }\n return cause instanceof Error ? cause : error\n}\n\n/**\n * The h3 HTTP runtime. Pass to `bootstrap({ runtime: h3Runtime() })`.\n * h3 parses bodies itself (`readBody`), so the Application skips its default\n * `express.json()` (see `nativeBodyParsing`).\n */\nexport function h3Runtime(): HttpRuntime<H3AppLike> {\n return {\n name: 'h3',\n\n createApp(options: RuntimeAppOptions = {}): H3AppLike {\n const { createApp } = h3()\n const app = createApp({\n onError: (error: unknown, event: H3EventLike) => {\n const res = event.node.res\n if (res.writableEnded) return\n const state = app as {\n [ERROR_MW]?: ConnectMiddleware\n [NOTFOUND_MW]?: ConnectMiddleware\n }\n // The shared router throws a 404 on no match (it's terminal). Treat\n // that as \"not found\", not a server error: hand back to the outer\n // chain (Vite dev fall-through) when present, else run the framework's\n // notFound handler so it returns a proper 404 — only genuine handler\n // errors reach the error middleware (and the ErrorHandler log).\n const status = (error as { statusCode?: number } | undefined)?.statusCode\n if (status === 404) {\n const next = (event.node.req as IncomingMessage & { [NEXT]?: () => void })[NEXT]\n if (next) {\n next()\n return\n }\n const nf = state[NOTFOUND_MW]\n if (nf) {\n ;(nf as (req: unknown, res: unknown, next: () => void) => void)(\n event.node.req,\n resDriver(res),\n NOOP_NEXT,\n )\n return\n }\n }\n const mw = state[ERROR_MW]\n if (mw) {\n ;(mw as (e: unknown, req: unknown, res: unknown, next: () => void) => void)(\n unwrapH3Error(error),\n event.node.req,\n resDriver(res),\n NOOP_NEXT,\n )\n }\n },\n })\n // Stash the setting for mountRoutes — h3 has no app-level config object\n // of its own to hang it on.\n ;(app as { [TRUST_PROXY]?: unknown })[TRUST_PROXY] = options.trustProxy\n return app as H3AppLike\n },\n\n nodeHandler(app) {\n const { toNodeListener } = h3()\n // Register the shared router exactly once, AFTER all connect middleware\n // (serveStatic / useConnect) the setup phase added via `app.use` — the\n // router is terminal, so anything that must run for non-route paths has to\n // sit before it in the stack.\n const state = app as { [ROUTER]?: unknown; [ASSEMBLED]?: boolean }\n if (!state[ASSEMBLED]) {\n state[ASSEMBLED] = true\n if (state[ROUTER]) app.use(state[ROUTER])\n }\n const listener = toNodeListener(app)\n return (req: IncomingMessage, res: ServerResponse, next?: (err?: unknown) => void) => {\n if (next) (req as IncomingMessage & { [NEXT]?: (err?: unknown) => void })[NEXT] = next\n Promise.resolve(listener(req, res)).catch((err) => {\n if (next) next(err)\n })\n }\n },\n\n mountRoutes(app, table: RouteTable) {\n const { createRouter, eventHandler } = h3()\n const trustProxy = Boolean((app as { [TRUST_PROXY]?: unknown })[TRUST_PROXY])\n // One shared router per app — every mountRoutes call (controllers, health,\n // devtools, ad-hoc adapter routes) adds to it. `app.use(router)` is\n // deferred to nodeHandler so the router lands after connect middleware.\n const state = app as { [ROUTER]?: ReturnType<typeof createRouter> }\n if (!state[ROUTER]) state[ROUTER] = createRouter()\n const router = state[ROUTER]\n for (const { mountPath, routes } of table) {\n for (const entry of routes) {\n const url = joinPath(mountPath, entry.path)\n const method = entry.method.toLowerCase() as 'get' | 'post' | 'put' | 'delete' | 'patch'\n router[method](url, eventHandler(makeEventHandler(entry, trustProxy)))\n }\n }\n },\n\n useConnect(app, mw: ConnectMiddleware, opts?: UseConnectOptions) {\n const { fromNodeMiddleware } = h3()\n const handler = fromNodeMiddleware(mw)\n if (opts?.path !== undefined) app.use(opts.path, handler)\n else app.use(handler)\n },\n\n serveStatic(app, prefix, dir) {\n // `serve-static` (the standalone connect middleware behind express.static)\n // so the h3 runtime carries no `express` dependency — bridged via\n // fromNodeMiddleware like any other connect middleware.\n const serveStatic = peerRequire('serve-static')\n this.useConnect(app, serveStatic(dir) as ConnectMiddleware, { path: prefix })\n },\n\n setNotFound(app, mw: ConnectMiddleware) {\n // Stash it — the shared router throws a 404 on no match, which `onError`\n // (createApp) dispatches to this handler (or to the Vite fall-through when\n // a `next` is present). A post-router `app.use` could never run, since the\n // terminal router throws before the stack advances.\n ;(app as { [NOTFOUND_MW]?: ConnectMiddleware })[NOTFOUND_MW] = mw\n },\n\n setErrorHandler(app, mw: ConnectMiddleware) {\n ;(app as { [ERROR_MW]?: ConnectMiddleware })[ERROR_MW] = mw\n },\n\n capabilities: {\n render: false,\n uploads: true,\n connectMiddleware: true,\n nativeBodyParsing: true,\n },\n }\n}\n\n/**\n * The h3 runtime's engine-native types — what the runtime-typed escape hatches\n * resolve to once the `kick/runtime` typegen emits a `KickRuntimeRegister`\n * augmentation pointing here (spec §4.3b). `AdapterContext.app` / `getRuntimeApp()`\n * become the h3 `App`; `ctx.req` / `ctx.res` the per-request `H3Event` (h3 v1\n * routes everything through the event). Mirrors `ExpressRuntimeTypes`.\n */\n// Resolved conditionally so this file typechecks against EITHER installed h3\n// major: v1 exports `App`; v2 (used by the sibling h3-web runtime) does not.\n// Runtime behavior is untouched — this block is type-only.\ntype H3AppType = typeof import('h3') extends { App: infer A } ? A : unknown\ntype H3EventType = typeof import('h3') extends { H3Event: new (...args: never[]) => infer E }\n ? E\n : unknown\n\nexport interface H3RuntimeTypes {\n request: H3EventType\n response: H3EventType\n app: H3AppType\n}\n\n/** Join a mount prefix and a route path; a root path maps to the prefix itself. */\nfunction joinPath(mountPath: string, path: string): string {\n const a = mountPath.endsWith('/') ? mountPath.slice(0, -1) : mountPath\n if (path === '/' || path === '') return a === '' ? '/' : a\n const b = path.startsWith('/') ? path : `/${path}`\n return `${a}${b}`\n}\n"],"mappings":";;;;;;;;;;6fAwCA,MAAM,YAAc,cAAc,YAAY,GAAG,EAE3C,OAAgB,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ent":["// The h3 runtime — `@forinda/kickjs/h3`.\n//\n// h3 (unjs) is the HTTP layer behind Nitro / Nuxt. This binds it to the same\n// HttpRuntime contract as Express and Fastify: routes become native h3 router\n// routes, and the node `ServerResponse` (h3 exposes it as `event.node.res`) is\n// wrapped in a RuntimeResponse so `ctx.json` / `ctx.html` / `ctx.sse` work\n// unchanged.\n//\n// Targets h3 **v1** (stable, node-based: `createApp` / `createRouter` /\n// `toNodeListener`, with `event.node.req` / `event.node.res`). `h3` is an\n// optional peer pinned to `^1`.\n//\n// h3 v2 (https://h3.dev/migration) moves to a web-standard `Request`/`Response`\n// core. Adopting it is the spec's §8 \"web-standard driver\" — `RuntimeResponse`\n// was shaped so a future `webRuntime()` can implement it over WHATWG streams,\n// at which point h3 v2 (and edge/Bun/Deno) become a driver swap rather than a\n// rewrite. Until that lands, this binding uses the node-compatible v1 surface.\n\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport { createRequire } from 'node:module'\n\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 { HttpException } from '../../core/errors'\nimport { applyUploadConfig, type RawUploadPart } from '../middleware/upload'\nimport type {\n ConnectMiddleware,\n HttpRuntime,\n RouteEntry,\n RouteTable,\n RuntimeAppOptions,\n RuntimeResponse,\n UseConnectOptions,\n} from '../runtime'\n\nconst peerRequire = createRequire(import.meta.url)\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst h3 = (): any => peerRequire('h3')\n\ninterface H3EventLike {\n node: { req: IncomingMessage; res: ServerResponse }\n}\ninterface H3AppLike {\n use(arg1: unknown, arg2?: unknown): unknown\n handler: unknown\n}\n\nconst NEXT = Symbol('kickjs.h3.next')\nconst ERROR_MW = Symbol('kickjs.h3.errorMw')\n// h3's `createRouter` is terminal — on no match it THROWS a 404, it does not\n// fall through to the next `app.use` layer like an Express Router. So every\n// route source (controllers, /health, devtools /_debug, ad-hoc adapter routes)\n// must live on ONE shared router, registered AFTER all connect middleware.\nconst ROUTER = Symbol('kickjs.h3.router')\nconst NOTFOUND_MW = Symbol('kickjs.h3.notFoundMw')\nconst ASSEMBLED = Symbol('kickjs.h3.assembled')\nconst NOOP_NEXT = (): void => {}\nconst BODY_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])\n\n/**\n * Wrap a node ServerResponse (from `event.node.res`) as a RuntimeResponse.\n * A class so the ~12 driver methods live on a shared prototype — the previous\n * object-literal version re-allocated every method closure on each request.\n */\nclass NodeResDriver implements RuntimeResponse {\n constructor(private readonly res: ServerResponse) {}\n status(code: number): this {\n this.res.statusCode = code\n return this\n }\n json(data: unknown): this {\n // Do not clobber a content-type the caller already chose. This used to set\n // `application/json` unconditionally, so every `application/problem+json`\n // response — RFC 9457 problem details, which the error handler sets the\n // header for before serialising — went out as plain JSON on this runtime\n // alone. Express and Fastify both leave an existing value alone.\n if (!this.res.headersSent && !this.res.getHeader('content-type')) {\n this.res.setHeader('content-type', 'application/json; charset=utf-8')\n }\n this.res.end(JSON.stringify(data))\n return this\n }\n send(data: unknown): this {\n this.res.end(data as never)\n return this\n }\n type(contentType: string): this {\n this.res.setHeader('content-type', contentType)\n return this\n }\n setHeader(name: string, value: unknown): this {\n this.res.setHeader(name, value as never)\n return this\n }\n render(): never {\n throw new Error('ctx.render() is not supported on the h3 runtime (no view engine).')\n }\n writeHead(statusCode: number, headers?: Record<string, string | number | string[]>): this {\n this.res.writeHead(statusCode, headers)\n return this\n }\n flushHeaders(): this {\n this.res.flushHeaders()\n return this\n }\n write(chunk: unknown): boolean {\n return this.res.write(chunk as never)\n }\n end(data?: unknown): this {\n this.res.end(data as never)\n return this\n }\n once(event: string, listener: (...args: unknown[]) => void): this {\n this.res.once(event, listener)\n return this\n }\n get headersSent(): boolean {\n return this.res.headersSent\n }\n}\n\nfunction resDriver(res: ServerResponse): RuntimeResponse {\n return new NodeResDriver(res) as unknown as RuntimeResponse\n}\n\n/** Carries `trustProxy` from createApp() to the per-route handlers. */\nconst TRUST_PROXY = Symbol('kickjs.h3.trustProxy')\n\n/** Build the h3 event handler that runs the kickjs pipeline for one route. */\nfunction makeEventHandler(\n entry: RouteEntry,\n trustProxy: boolean,\n): (event: H3EventLike) => Promise<void> {\n const { getRouterParams, getQuery, readRawBody, readMultipartFormData } = h3()\n const upload = entry.meta.upload\n // Validation middleware built ONCE per route (parity with Express) — calling\n // validate() per request re-allocated the closure every time.\n const validator = entry.meta.validation ? validate(entry.meta.validation) : undefined\n return async (event: H3EventLike) => {\n const req = event.node.req as IncomingMessage & {\n requestId?: string\n body?: unknown\n params?: unknown\n query?: unknown\n file?: unknown\n files?: unknown\n }\n const res = event.node.res\n\n // h3 computes no client address of its own, so `resolveClientIp` fell\n // straight through to the socket — which behind a proxy is the proxy, and\n // put every caller in one rate-limit bucket with no way to configure out\n // of it (#614). Express and Fastify derive `req.ip` from their own\n // trust-proxy settings; this is h3's equivalent, and like theirs it is\n // OFF unless the app opts in, because an unverified `x-forwarded-for` is\n // client-controllable.\n if (trustProxy && !(req as { ip?: string }).ip) {\n const forwarded = req.headers['x-forwarded-for']\n const first = (Array.isArray(forwarded) ? forwarded[0] : forwarded)?.split(',')[0]?.trim()\n if (first) (req as { ip?: string }).ip = first\n }\n\n // Populate the express-shaped request fields h3 keeps elsewhere.\n req.params = getRouterParams(event) ?? {}\n req.query = getQuery(event) ?? {}\n\n // HTTP/2 frames a body in DATA frames: no `transfer-encoding`, and\n // `content-length` is optional. h3's `readRawBody` — behind both the\n // JSON/text path and `readMultipartFormData` — returns `undefined` when\n // neither header is present, dropping the body. Read it once as bytes and\n // hand it over on `req.rawBody`, which `readRawBody` checks first.\n if (\n req.httpVersionMajor === 2 &&\n req.headers['content-length'] === undefined &&\n BODY_METHODS.has(req.method ?? 'GET')\n ) {\n ;(req as { rawBody?: Buffer }).rawBody = await readStreamBuffer(req)\n }\n if (upload && upload.mode !== 'none') {\n // @FileUpload: read the multipart body once (readBody would consume the\n // same stream, so the two are mutually exclusive). File parts → the\n // multer-shaped ctx.file/ctx.files; non-file fields → req.body.\n const form = (await readMultipartFormData(event).catch(() => undefined)) as\n | Array<{ name?: string; filename?: string; type?: string; data: Buffer }>\n | undefined\n const rawParts: RawUploadPart[] = []\n const fields: Record<string, unknown> = {}\n for (const part of form ?? []) {\n if (part.filename) {\n rawParts.push({\n fieldname: part.name ?? '',\n filename: part.filename,\n mimetype: part.type ?? 'application/octet-stream',\n buffer: part.data,\n })\n } else if (part.name) {\n fields[part.name] = part.data.toString('utf-8')\n }\n }\n const { file, files } = applyUploadConfig(rawParts, upload)\n req.file = file\n req.files = files\n req.body = fields\n } else if (BODY_METHODS.has(req.method ?? 'GET')) {\n // Swallow ONLY the absent-body case. `.catch(() => undefined)` also\n // swallowed a malformed one, so h3 answered 200 with the handler running\n // on `undefined` where Express and Fastify both answer 400 — a client\n // sending broken JSON got a success response, and the handler executed\n // against data that was never valid.\n // HTTP/2 frames the body in DATA frames: no `transfer-encoding`, and\n // `content-length` is optional, so there a body may be present with\n // neither header — only an explicit `content-length: 0` rules it out.\n const { 'content-length': length, 'transfer-encoding': encoding } = req.headers\n const sentBody =\n encoding !== undefined ||\n (length !== undefined && length !== '0') ||\n (req.httpVersionMajor === 2 && length !== '0')\n if (sentBody) {\n // Read raw and apply the shared policy rather than calling `readBody`,\n // whose own content-type dispatch is the source of the divergence:\n // it matches `application/json` with `===` (so `; charset=utf-8` misses)\n // and routes everything unrecognised through `destr`, which returns the\n // RAW STRING for malformed input instead of throwing (#590).\n const kind = classifyMediaType(req.headers['content-type'])\n if (kind !== 'multipart') {\n const raw = await readRawBody(event, 'utf8')\n // Reject only once the body is known to be non-empty. `sentBody` is\n // true for an empty CHUNKED post — `transfer-encoding` is present\n // with no payload — and rejecting on that alone would 415 a request\n // that sent nothing, contradicting the rule the other runtimes apply.\n if (raw) {\n if (kind === 'unsupported') {\n // A body was sent in a format the framework does not parse. Say\n // so rather than handing the handler `undefined` and letting it\n // fail somewhere less obvious.\n throw unsupportedMediaTypeError(req.headers['content-type'])\n }\n if (kind === 'json') {\n try {\n req.body = JSON.parse(raw)\n } catch (err) {\n throw 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 }\n\n const headerId = req.headers['x-request-id']\n const requestId = (Array.isArray(headerId) ? headerId[0] : headerId) || req.requestId\n const store = createRequestStore(requestId)\n req.requestId = store.requestId\n\n // @PreDestroy teardown for REQUEST-scoped instances once the response\n // closes (finished or aborted) — parity with requestScopeMiddleware.\n res.once('close', () => disposeRequestStore(store))\n\n await requestStore.run(store, async () => {\n publishMatchedRoute(req, entry)\n const ctx = new RequestContext(req as never, res as never, NOOP_NEXT, resDriver(res))\n\n // `beforeValidation` contributors (#677) — ahead of validation and middleware.\n if (entry.earlyContributorRunner) {\n await entry.earlyContributorRunner(ctx)\n if (res.writableEnded) 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 || res.writableEnded) return\n }\n\n if (entry.contributorRunner) await entry.contributorRunner(ctx)\n if (res.writableEnded) return\n const result = await entry.handler(ctx)\n // Return-value handlers (reply.ts): auto-send when nothing was written.\n if (!res.writableEnded && !res.headersSent) applyHandlerResult(ctx, result)\n })\n }\n}\n\n/**\n * The original error h3 wrapped.\n *\n * h3 routes every thrown value through `createError()`, which returns its own\n * error with the original on `cause`. Handing that wrapper to the shared error\n * middleware means it sees something Express and Fastify never give it, and the\n * responses diverge: `instanceof HttpException` fails, so a thrown\n * `HttpException(418)` falls through to the generic branch and picks up a\n * `requestId` the other two omit, and `describeError` walks the cause chain to\n * report `kaboom ← caused by kaboom`.\n *\n * Only an `Error` cause is unwrapped. h3's own 404 carries no cause, so the\n * not-found path above is unaffected.\n */\nfunction unwrapH3Error(error: unknown): unknown {\n if (!(error instanceof Error)) return error\n const { cause } = error as { cause?: unknown }\n return cause instanceof Error ? cause : error\n}\n\n/**\n * The h3 HTTP runtime. Pass to `bootstrap({ runtime: h3Runtime() })`.\n * h3 parses bodies itself (`readBody`), so the Application skips its default\n * `express.json()` (see `nativeBodyParsing`).\n */\n/** Collect a request stream as bytes — never decoded, so file parts stay intact. */\nasync function readStreamBuffer(req: AsyncIterable<Buffer | string>): Promise<Buffer> {\n const chunks: Buffer[] = []\n for await (const chunk of req) chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk)\n return Buffer.concat(chunks)\n}\n\nexport function h3Runtime(): HttpRuntime<H3AppLike> {\n return {\n name: 'h3',\n\n createApp(options: RuntimeAppOptions = {}): H3AppLike {\n const { createApp } = h3()\n const app = createApp({\n onError: (error: unknown, event: H3EventLike) => {\n const res = event.node.res\n if (res.writableEnded) return\n const state = app as {\n [ERROR_MW]?: ConnectMiddleware\n [NOTFOUND_MW]?: ConnectMiddleware\n }\n // The shared router throws a 404 on no match (it's terminal). Treat\n // that as \"not found\", not a server error: hand back to the outer\n // chain (Vite dev fall-through) when present, else run the framework's\n // notFound handler so it returns a proper 404 — only genuine handler\n // errors reach the error middleware (and the ErrorHandler log).\n //\n // Only the ROUTER's no-match counts: h3 builds it from a plain object,\n // so its `cause` is not an Error. A handler that throws\n // `HttpException(404, '…')` arrives wrapped with the exception as\n // `cause` — that is a handler error and belongs to the error\n // middleware, which keeps its detail (and reports it to observers).\n const status = (error as { statusCode?: number } | undefined)?.statusCode\n const thrownByHandler = (error as { cause?: unknown } | undefined)?.cause instanceof Error\n if (status === 404 && !thrownByHandler) {\n const next = (event.node.req as IncomingMessage & { [NEXT]?: () => void })[NEXT]\n if (next) {\n next()\n return\n }\n const nf = state[NOTFOUND_MW]\n if (nf) {\n ;(nf as (req: unknown, res: unknown, next: () => void) => void)(\n event.node.req,\n resDriver(res),\n NOOP_NEXT,\n )\n return\n }\n }\n const mw = state[ERROR_MW]\n if (mw) {\n ;(mw as (e: unknown, req: unknown, res: unknown, next: () => void) => void)(\n unwrapH3Error(error),\n event.node.req,\n resDriver(res),\n NOOP_NEXT,\n )\n }\n },\n })\n // Stash the setting for mountRoutes — h3 has no app-level config object\n // of its own to hang it on.\n ;(app as { [TRUST_PROXY]?: unknown })[TRUST_PROXY] = options.trustProxy\n return app as H3AppLike\n },\n\n nodeHandler(app) {\n const { toNodeListener } = h3()\n // Register the shared router exactly once, AFTER all connect middleware\n // (serveStatic / useConnect) the setup phase added via `app.use` — the\n // router is terminal, so anything that must run for non-route paths has to\n // sit before it in the stack.\n const state = app as { [ROUTER]?: unknown; [ASSEMBLED]?: boolean }\n if (!state[ASSEMBLED]) {\n state[ASSEMBLED] = true\n if (state[ROUTER]) app.use(state[ROUTER])\n }\n const listener = toNodeListener(app)\n return (req: IncomingMessage, res: ServerResponse, next?: (err?: unknown) => void) => {\n if (next) (req as IncomingMessage & { [NEXT]?: (err?: unknown) => void })[NEXT] = next\n Promise.resolve(listener(req, res)).catch((err) => {\n if (next) next(err)\n })\n }\n },\n\n mountRoutes(app, table: RouteTable) {\n const { createRouter, eventHandler } = h3()\n const trustProxy = Boolean((app as { [TRUST_PROXY]?: unknown })[TRUST_PROXY])\n // One shared router per app — every mountRoutes call (controllers, health,\n // devtools, ad-hoc adapter routes) adds to it. `app.use(router)` is\n // deferred to nodeHandler so the router lands after connect middleware.\n const state = app as { [ROUTER]?: ReturnType<typeof createRouter> }\n if (!state[ROUTER]) state[ROUTER] = createRouter()\n const router = state[ROUTER]\n for (const { mountPath, routes } of table) {\n for (const entry of routes) {\n const url = joinPath(mountPath, entry.path)\n const method = entry.method.toLowerCase() as 'get' | 'post' | 'put' | 'delete' | 'patch'\n router[method](url, eventHandler(makeEventHandler(entry, trustProxy)))\n }\n }\n },\n\n useConnect(app, mw: ConnectMiddleware, opts?: UseConnectOptions) {\n const { fromNodeMiddleware } = h3()\n const handler = fromNodeMiddleware(mw)\n if (opts?.path !== undefined) app.use(opts.path, handler)\n else app.use(handler)\n },\n\n serveStatic(app, prefix, dir) {\n // `serve-static` (the standalone connect middleware behind express.static)\n // so the h3 runtime carries no `express` dependency — bridged via\n // fromNodeMiddleware like any other connect middleware.\n const serveStatic = peerRequire('serve-static')\n this.useConnect(app, serveStatic(dir) as ConnectMiddleware, { path: prefix })\n },\n\n setNotFound(app, mw: ConnectMiddleware) {\n // Stash it — the shared router throws a 404 on no match, which `onError`\n // (createApp) dispatches to this handler (or to the Vite fall-through when\n // a `next` is present). A post-router `app.use` could never run, since the\n // terminal router throws before the stack advances.\n ;(app as { [NOTFOUND_MW]?: ConnectMiddleware })[NOTFOUND_MW] = mw\n },\n\n setErrorHandler(app, mw: ConnectMiddleware) {\n ;(app as { [ERROR_MW]?: ConnectMiddleware })[ERROR_MW] = mw\n },\n\n capabilities: {\n render: false,\n uploads: true,\n connectMiddleware: true,\n nativeBodyParsing: true,\n http2: true,\n },\n }\n}\n\n/**\n * The h3 runtime's engine-native types — what the runtime-typed escape hatches\n * resolve to once the `kick/runtime` typegen emits a `KickRuntimeRegister`\n * augmentation pointing here (spec §4.3b). `AdapterContext.app` / `getRuntimeApp()`\n * become the h3 `App`; `ctx.req` / `ctx.res` the per-request `H3Event` (h3 v1\n * routes everything through the event). Mirrors `ExpressRuntimeTypes`.\n */\n// Resolved conditionally so this file typechecks against EITHER installed h3\n// major: v1 exports `App`; v2 (used by the sibling h3-web runtime) does not.\n// Runtime behavior is untouched — this block is type-only.\ntype H3AppType = typeof import('h3') extends { App: infer A } ? A : unknown\ntype H3EventType = typeof import('h3') extends { H3Event: new (...args: never[]) => infer E }\n ? E\n : unknown\n\nexport interface H3RuntimeTypes {\n request: H3EventType\n response: H3EventType\n app: H3AppType\n}\n\n/** Join a mount prefix and a route path; a root path maps to the prefix itself. */\nfunction joinPath(mountPath: string, path: string): string {\n const a = mountPath.endsWith('/') ? mountPath.slice(0, -1) : mountPath\n if (path === '/' || path === '') return a === '' ? '/' : a\n const b = path.startsWith('/') ? path : `/${path}`\n return `${a}${b}`\n}\n"],"mappings":";;;;;;;;;;6fAwCA,MAAM,YAAc,cAAc,YAAY,GAAG,EAE3C,OAAgB,YAAY,IAAI,EAUhC,KAAO,OAAO,gBAAgB,EAC9B,SAAW,OAAO,mBAAmB,EAKrC,OAAS,OAAO,kBAAkB,EAClC,YAAc,OAAO,sBAAsB,EAC3C,UAAY,OAAO,qBAAqB,EACxC,cAAwB,CAAC,EACzB,aAAe,IAAI,IAAI,CAAC,OAAQ,MAAO,QAAS,QAAQ,CAAC,EAO/D,IAAM,cAAN,KAA+C,CAChB,IAA7B,YAAY,IAAsC,CAArB,KAAA,IAAA,GAAsB,CACnD,OAAO,KAAoB,CAEzB,MADA,MAAK,IAAI,WAAa,KACf,IACT,CACA,KAAK,KAAqB,CAUxB,MAJI,CAAC,KAAK,IAAI,aAAe,CAAC,KAAK,IAAI,UAAU,cAAc,GAC7D,KAAK,IAAI,UAAU,eAAgB,iCAAiC,EAEtE,KAAK,IAAI,IAAI,KAAK,UAAU,IAAI,CAAC,EAC1B,IACT,CACA,KAAK,KAAqB,CAExB,OADA,KAAK,IAAI,IAAI,IAAa,EACnB,IACT,CACA,KAAK,YAA2B,CAE9B,OADA,KAAK,IAAI,UAAU,eAAgB,WAAW,EACvC,IACT,CACA,UAAU,KAAc,MAAsB,CAE5C,OADA,KAAK,IAAI,UAAU,KAAM,KAAc,EAChC,IACT,CACA,QAAgB,CACd,MAAU,MAAM,mEAAmE,CACrF,CACA,UAAU,WAAoB,QAA4D,CAExF,OADA,KAAK,IAAI,UAAU,WAAY,OAAO,E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D,GAAM,CAAE,oBAAuB,GAAG,EAC5B,QAAU,mBAAmB,EAAE,EACjC,MAAM,OAAS,IAAA,GACd,IAAI,IAAI,OAAO,EADU,IAAI,IAAI,KAAK,KAAM,OAAO,CAE1D,EAEA,YAAY,IAAK,OAAQ,IAAK,CAI5B,IAAM,YAAc,YAAY,cAAc,EAC9C,KAAK,WAAW,IAAK,YAAY,GAAG,EAAwB,CAAE,KAAM,MAAO,CAAC,CAC9E,EAEA,YAAY,IAAK,GAAuB,CAKrC,IAA+C,aAAe,EACjE,EAEA,gBAAgB,IAAK,GAAuB,CACzC,IAA4C,UAAY,EAC3D,EAEA,aAAc,CACZ,OAAQ,GACR,QAAS,GACT,kBAAmB,GACnB,kBAAmB,GACnB,MAAO,EACT,CACF,CACF,CAwBA,SAAS,SAAS,UAAmB,KAAsB,CACzD,IAAM,EAAI,UAAU,SAAS,GAAG,EAAI,UAAU,MAAM,EAAG,EAAE,EAAI,UAG7D,OAFI,OAAS,KAAO,OAAS,GAAW,IAAM,GAAK,IAAM,EAElD,GAAG,IADA,KAAK,WAAW,GAAG,EAAI,KAAO,IAAI,QAE9C"}
@@ -1,5 +1,5 @@
1
1
 
2
- import { p as EnvKey } from "./decorators-mg0qJ6Qc.mjs";
2
+ import { p as EnvKey } from "./decorators-DOcWsXci.mjs";
3
3
  import { InferSchemaOutput } from "@forinda/kickjs-schema";
4
4
  import { z } from "zod";
5
5
  //#region src/config/env.d.ts
@@ -87,28 +87,34 @@ declare function defineEnv<T extends z.ZodRawShape>(extend: (base: typeof baseEn
87
87
  declare function loadEnv<T extends z.ZodObject<any>>(schema: T): z.infer<T>;
88
88
  declare function loadEnv(): [EnvKey] extends [never] ? Env : KickEnv;
89
89
  /**
90
- * Get a single typed environment variable value.
90
+ * Get a single typed environment variable value, read from the env schema
91
+ * the app registered — the one source of truth, set once with
92
+ * `loadEnv(envSchema)` in `src/env.ts`.
91
93
  *
92
- * Three forms:
93
- * - **No-arg, KickEnv populated** (`kick typegen` has run) → key is
94
- * constrained to known `KickEnv` keys; return type inferred from
95
- * the schema.
96
- * - **With explicit schema** → key constrained to that schema's keys;
97
- * return type is `z.infer<typeof schema>[K]`.
98
- * - **No-arg, KickEnv empty** → loose `string` key, `any` return.
94
+ * - **`getEnv(key)`** returns the parsed value: `getEnv('PORT')` is a number
95
+ * once `kick typegen` has run.
96
+ * - **`getEnv(key, fallback)`** returns `fallback` when the value is unset
97
+ * (`undefined` or `null`) — for keys the schema leaves optional.
99
98
  *
100
99
  * @example
101
100
  * ```ts
102
- * // After `kick typegen` (KickEnv populated):
103
- * const port = getEnv('PORT') // typed as number
104
- * const url = getEnv('DATABASE_URL') // typed as string
105
- *
106
- * // With an inline schema (legacy / one-off):
107
- * const dbUrl = getEnv('DATABASE_URL', envSchema)
101
+ * const port = getEnv('PORT') // number
102
+ * const region = getEnv('S3_REGION', 'eu-west-1') // string, never undefined
108
103
  * ```
104
+ *
105
+ * A default every caller shares belongs in the schema (`.default(...)`);
106
+ * the fallback is for a value one call site can live without.
109
107
  */
110
108
  declare function getEnv<K extends EnvKey>(key: K): KickEnv[K];
111
- declare function getEnv<T extends z.ZodObject<any>, K extends string & keyof z.infer<T>>(key: K, schema: T): z.infer<T>[K];
109
+ declare function getEnv<K extends EnvKey>(key: K, fallback: NonNullable<KickEnv[K]>): NonNullable<KickEnv[K]>;
110
+ /**
111
+ * Run `fn` with some env values replaced — for tests. The overrides are
112
+ * parsed values (`{ TRUST_PROXY: true }`), laid over the current env for the
113
+ * duration of the call and taken away afterwards, whatever `fn` does.
114
+ * `getEnv`, `ConfigService` and `@Value()` all see them. No `.env` file is
115
+ * read. Not for concurrent use: the env is process-wide.
116
+ */
117
+ declare function withEnv<T>(overrides: Record<string, unknown>, fn: () => T | Promise<T>): Promise<T>;
112
118
  /**
113
119
  * Reload env from `process.env`. Re-reads `.env` via dotenv (if
114
120
  * installed), then re-parses the result against the **same** schema
@@ -244,6 +250,8 @@ declare class ConfigService {
244
250
  * back-compat.
245
251
  */
246
252
  get<K extends string, T = any>(key: ConfigKey<K>): ConfigValue<K, T>;
253
+ /** With a fallback, returned when the value is unset (`undefined` or `null`). */
254
+ get<K extends string, T = any>(key: ConfigKey<K>, fallback: NonNullable<ConfigValue<K, T>>): NonNullable<ConfigValue<K, T>>;
247
255
  /**
248
256
  * Get all env config as a readonly object. When `KickEnv` is
249
257
  * populated by typegen, returns `Readonly<KickEnv>` so the caller
@@ -262,6 +270,7 @@ declare class ConfigService {
262
270
  */
263
271
  interface TypedConfigService<TEnv extends Record<string, any>> {
264
272
  get<K extends string & keyof TEnv>(key: K): TEnv[K];
273
+ get<K extends string & keyof TEnv>(key: K, fallback: NonNullable<TEnv[K]>): NonNullable<TEnv[K]>;
265
274
  getAll(): Readonly<TEnv>;
266
275
  reload(): void;
267
276
  isProduction(): boolean;
@@ -300,5 +309,5 @@ declare function createConfigService<T extends z.ZodObject<any>>(schema: T): {
300
309
  new (): TypedConfigService<z.infer<T>>;
301
310
  };
302
311
  //#endregion
303
- export { baseEnvSchema as a, loadEnv as c, resetEnvCache as d, Env as i, loadEnvFromSchema as l, TypedConfigService as n, defineEnv as o, createConfigService as r, getEnv as s, ConfigService as t, reloadEnv as u };
304
- //# sourceMappingURL=index-Btz1W0X5.d.mts.map
312
+ export { baseEnvSchema as a, loadEnv as c, resetEnvCache as d, withEnv as f, Env as i, loadEnvFromSchema as l, TypedConfigService as n, defineEnv as o, createConfigService as r, getEnv as s, ConfigService as t, reloadEnv as u };
313
+ //# sourceMappingURL=index-CDn-p3tq.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index-CDn-p3tq.d.mts","names":[],"sources":["../src/config/env.ts","../src/config/config-service.ts"],"mappings":";;;;;;;;;;iBAsOS,sBAAkB,EAAA;;;;;;;;GAQ1B,EAAA,KAAA;;KAGW,gBAAgB,kBAAkB;;;;;;;;;;;cAsBjC,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA6DZ,UAAU,UAAU,EAAE,aACp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UAAU,EAAE,gBAAgB,QAAQ;UAuC5D,mBAAkB,EAAA,MAAA"}
package/dist/index.d.mts CHANGED
@@ -1,29 +1,29 @@
1
1
 
2
2
  import { a as METADATA, c as Scope, i as Constructor, l as ServiceOptions, n as BuilderOf, o as MaybePromise, r as ClassKind, s as PostConstructStatus, t as Buildable } from "./interfaces-C1hCSoLD.mjs";
3
3
  import { a as tokenName, c as createToken, i as KickJsRegistry, l as isInjectionToken, n as ContainerChangeEvent, o as INJECTION_TOKEN, r as ContainerChangeListener, s as InjectionToken, t as Container } from "./container-Dpvd66Yt.mjs";
4
- import { A as Service, B as resolveAsset, C as Post, D as Put, F as ASSET_MANIFEST_VERSION, I as KickAssets, L as UnknownAssetError, M as normalizeApiQueryParamsConfig, N as withBuilder, O as Repository, P as ASSETS, R as assets, S as Patch, T as PreDestroy, V as useAssets, _ as Get, a as Autowired, b as Middleware, c as ColumnApiQueryParamsConfig, d as Delete, f as Env, g as FileUploadConfig, h as FileUpload, i as AssetKey, j as Value, k as RouteDefinition, l as Component, m as FileTypeFilter, n as ApiQueryParamsConfig, o as BaseUploadOptions, p as EnvKey, r as Asset, s as Builder, t as ApiQueryParams, u as Controller, v as Inject, w as PostConstruct, x as MiddlewareHandler, y as Injectable, z as clearAssetCache } from "./decorators-mg0qJ6Qc.mjs";
5
- import { a as baseEnvSchema, c as loadEnv, d as resetEnvCache, l as loadEnvFromSchema, n as TypedConfigService, o as defineEnv, r as createConfigService, s as getEnv, t as ConfigService, u as reloadEnv } from "./index-Btz1W0X5.mjs";
4
+ import { A as Service, B as resolveAsset, C as Post, D as Put, F as ASSET_MANIFEST_VERSION, I as KickAssets, L as UnknownAssetError, M as normalizeApiQueryParamsConfig, N as withBuilder, O as Repository, P as ASSETS, R as assets, S as Patch, T as PreDestroy, V as useAssets, _ as Get, a as Autowired, b as Middleware, c as ColumnApiQueryParamsConfig, d as Delete, f as Env, g as FileUploadConfig, h as FileUpload, i as AssetKey, j as Value, k as RouteDefinition, l as Component, m as FileTypeFilter, n as ApiQueryParamsConfig, o as BaseUploadOptions, p as EnvKey, r as Asset, s as Builder, t as ApiQueryParams, u as Controller, v as Inject, w as PostConstruct, x as MiddlewareHandler, y as Injectable, z as clearAssetCache } from "./decorators-DOcWsXci.mjs";
5
+ import { a as baseEnvSchema, c as loadEnv, d as resetEnvCache, f as withEnv, l as loadEnvFromSchema, n as TypedConfigService, o as defineEnv, r as createConfigService, s as getEnv, t as ConfigService, u as reloadEnv } from "./index-CDn-p3tq.mjs";
6
+ import { $ as setInMetaRecord, B as SourcedRegistration, C as RuntimeTypeMap, Ct as reportResponse, D as RequestContext, E as DeepReadonly, F as RunContributorsOptions, G as getMetaRecord, H as getClassMeta, I as runContributors, J as hasClassMeta, K as getMethodMeta, L as BuildPipelineOptions, M as AdapterFactory, N as DefineAdapterOptions, O as RouteShape, P as defineAdapter, Q as setInMetaMap, R as ContributorPipeline, S as RuntimeResponse, St as reportError, T as Ctx, U as getClassMetaOrUndefined, V as buildPipeline, W as getMetaMap, X as pushMethodMeta, Y as pushClassMeta, Z as setClassMeta, _ as RouteMeta, _t as IntrospectionKind, a as KickServer, at as defineModule, b as RuntimeAppOptions, bt as ErrorSource, c as ActiveRuntime, ct as PluginAsyncOptions, d as CtxHandler, dt as KickPlugin, et as setMethodMeta, f as ExpressRuntimeTypes, ft as ModuleRegistry, g as RouteEntry, gt as IntrospectFn, h as MatchedRoute, ht as KickJsPluginRegistry, i as AppAdapterClass, it as ModuleFactory, j as AdapterAsyncOptions, k as SseHandler, l as AdapterHttp, lt as PluginFactory, m as KickRuntimeRegister, mt as KickJsPluginName, n as AdapterMiddleware, nt as defineModules, o as MiddlewarePath, ot as BuildContext, p as HttpRuntime, pt as MutableModuleRegistry, q as getMethodMetaOrUndefined, r as AppAdapter, rt as DefineModuleOptions, s as MiddlewarePhase, st as DefinePluginOptions, t as AdapterContext, tt as ModuleList, u as ConnectMiddleware, ut as definePlugin, v as RouteMethod, vt as IntrospectionSnapshot, w as UseConnectOptions, x as RuntimeCapabilities, xt as ResponseInfo, y as RouteTable, yt as ErrorInfo, z as ContributorSource } from "./adapter-DhjoIYVI.mjs";
6
7
  import { _ as getRouteFlags, a as RouteFlagContext, c as RouteFlagName, d as RouteFlagTest, f as RouteFlagValue, g as defineRouteFlag, h as assertFlagTest, i as RouteFlag, l as RouteFlagPredicate, m as ValuedRouteFlag, n as KickRouteFlags, o as RouteFlagDeclaration, p as RouteFlags, r as NegatedRouteFlagName, s as RouteFlagDeclarations, t as BareRouteFlag, u as RouteFlagRecord, v as matchesFlagTest, y as resolveRouteFlags } from "./route-flag-B1lQht6v.mjs";
7
8
  import { C as MetaValue, S as ExecutionContext, _ as ResolvedDeps, a as ModuleRoutes, b as ContextMeta, c as ContextDecorator, d as ContextDecoratorTarget, f as ContextDecoratorWithDefaults, g as MissingParamKeys, h as DepValue, l as ContextDecoratorRequiringParams, m as ContributorRegistrations, n as AppModuleClass, o as AnyContributorRegistration, p as ContributorRegistration, r as AppModuleEntry, s as CallSiteParams, t as AppModule, u as ContextDecoratorSpec, v as defineContextDecorator, x as ContextMetaKey, y as ContextKeys } from "./app-module-DCA65GZZ.mjs";
8
- import { $ as ModuleList, A as AdapterFactory, B as getClassMeta, C as UseConnectOptions, D as RouteShape, E as RequestContext, F as BuildPipelineOptions, G as getMethodMetaOrUndefined, H as getMetaMap, I as ContributorPipeline, J as pushMethodMeta, K as hasClassMeta, L as ContributorSource, M as defineAdapter, N as RunContributorsOptions, O as SseHandler, P as runContributors, Q as setMethodMeta, R as SourcedRegistration, S as RuntimeTypeMap, T as DeepReadonly, U as getMetaRecord, V as getClassMetaOrUndefined, W as getMethodMeta, X as setInMetaMap, Y as setClassMeta, Z as setInMetaRecord, _ as RouteMethod, _t as IntrospectionKind, a as MiddlewarePath, at as DefinePluginOptions, b as RuntimeCapabilities, c as AdapterHttp, ct as definePlugin, d as ExpressRuntimeTypes, dt as MutableModuleRegistry, et as defineModules, f as HttpRuntime, ft as AugmentationMeta, g as RouteMeta, gt as IntrospectFn, h as RouteEntry, ht as defineAugmentation, i as AppAdapterClass, it as BuildContext, j as DefineAdapterOptions, k as AdapterAsyncOptions, l as ConnectMiddleware, lt as KickPlugin, m as MatchedRoute, mt as KickJsPluginRegistry, n as AdapterMiddleware, nt as ModuleFactory, o as MiddlewarePhase, ot as PluginAsyncOptions, p as KickRuntimeRegister, pt as KickJsPluginName, q as pushClassMeta, r as AppAdapter, rt as defineModule, s as ActiveRuntime, st as PluginFactory, t as AdapterContext, tt as DefineModuleOptions, u as CtxHandler, ut as ModuleRegistry, v as RouteTable, vt as IntrospectionSnapshot, w as Ctx, x as RuntimeResponse, y as RuntimeAppOptions, z as buildPipeline } from "./adapter-2bnoYEPX.mjs";
9
- import { i as getCronJobs, n as Cron, r as CronJobMeta, t as CRON_META } from "./cron-DOOtTY4q.mjs";
9
+ import { a as CronOptions, c as getCronJobs, d as runCronJob, f as runCronJobs, i as CronJobMeta, l as isCronJobEnabled, n as Cron, o as CronRun, r as CronJob, s as cronScheduleId, t as CRON_META, u as listCronJobs } from "./cron-BTGytNg-.mjs";
10
+ import { A as runJob, C as JobLike, D as listJobHandlers, E as ProcessDefinition, O as listJobQueues, S as JobHandler, T as Process, _ as JOB_DISPATCHER, a as KvSessionStoreOptions, b as JobContextCarrier, c as InferHandlerResponse, d as isReply, f as reply, g as JOB_CONTEXT_FIELD, h as waitUntil, i as KvSessionStore, j as stampJobContext, k as registerJobContext, l as Reply, m as settleBackgroundWork, n as KvRateLimitStore, o as RateLimitGuardOptions, p as PlatformContext, r as KvRateLimitStoreOptions, s as rateLimitGuard, t as KvLike, u as applyHandlerResult, v as JOB_META, w as NoJobHandlerError, x as JobDispatcher, y as Job } from "./kv-stores-CetFF9N_.mjs";
10
11
  import { a as Cacheable, c as setCacheProvider, i as CacheProvider, n as CacheEvict, o as MemoryCacheProvider, r as CacheOptions, s as getCacheProvider } from "./cache-C0qL0NSD.mjs";
11
12
  import { a as describeError, i as createLogger, n as Logger, r as LoggerProvider, t as ConsoleLoggerProvider } from "./logger-DA43DvNY.mjs";
12
- import { $ as MissingContributorError, A as ClusterOptions, B as GroupAssetKeysOptions, C as getRequestStore, D as expressRuntime, E as buildRoutes, F as RoutePolicyTable, G as MissingMountDepError, H as groupAssetKeys, I as bindRoutePolicy, J as MountSortItem, K as MountCycleError, L as offerRoutePolicy, M as KickHandler, N as createHandler, O as materializeRouter, P as bootstrap, Q as MissingContextValueError, R as AssetKeyPair, S as RequestStore, T as requestStore, U as stripExt, V as GroupAssetKeysResult, W as DuplicateMountNameError, X as ContributorCycleError, Y as mountSort, Z as DuplicateContributorError, _ as TraceContext, a as HEALTH_PROBE, at as FormatKickErrorOptions, b as traceContext, c as HealthModuleConfig, ct as formatKickError, d as SpaAdapter, dt as registerDisposable, et as CircuitBreaker, f as SpaAdapterOptions, g as TRACEPARENT_HEADER, h as ViewAdapterOptions, it as CircuitOpenError, j as isClusterPrimary, k as defineHttpContextDecorator, l as HealthProbe, lt as Disposable, m as ViewAdapter, n as ApplicationOptions, nt as CircuitBreakerState, o as HealthCheckResult, ot as KickError, q as MountKind, r as MiddlewareEntry, rt as CircuitBreakerStats, s as HealthController, st as KickErrorInit, t as Application, tt as CircuitBreakerOptions, u as healthModule, ut as disposeAll, v as TraceContextOptions, w as getRequestValue, x as requestScopeMiddleware, y as parseTraceparent, z as AssetKeyStrategy } from "./application-_QOiAVx2.mjs";
13
+ import { $ as MissingMountDepError, A as defineHttpContextDecorator, B as CRON_WORKER_ENV, C as RequestStore, D as buildRoutes, E as requestStore, F as bootstrap, G as offerRoutePolicy, H as KickCronAdapter, I as ERROR_CHANNEL, J as GroupAssetKeysOptions, K as AssetKeyPair, L as HANDLER_CHANNEL, M as isClusterPrimary, N as KickHandler, O as expressRuntime, P as createHandler, Q as DuplicateMountNameError, R as HandlerTraceContext, S as requestScopeMiddleware, T as getRequestValue, U as RoutePolicyTable, V as CronAdapterOptions, W as bindRoutePolicy, X as groupAssetKeys, Y as GroupAssetKeysResult, Z as stripExt, _ as TRACEPARENT_HEADER, _t as Disposable, at as DuplicateContributorError, b as parseTraceparent, c as HealthController, ct as CircuitBreaker, d as healthModule, dt as CircuitBreakerStats, et as MountCycleError, f as SpaAdapter, ft as CircuitOpenError, g as ViewAdapterOptions, gt as formatKickError, h as ViewAdapter, ht as KickErrorInit, i as ServerOptions, it as ContributorCycleError, j as ClusterOptions, k as materializeRouter, l as HealthModuleConfig, lt as CircuitBreakerOptions, mt as KickError, n as ApplicationOptions, nt as MountSortItem, o as HEALTH_PROBE, ot as MissingContextValueError, p as SpaAdapterOptions, pt as FormatKickErrorOptions, q as AssetKeyStrategy, r as MiddlewareEntry, rt as mountSort, s as HealthCheckResult, st as MissingContributorError, t as Application, tt as MountKind, u as HealthProbe, ut as CircuitBreakerState, v as TraceContext, vt as disposeAll, w as getRequestStore, x as traceContext, y as TraceContextOptions, yt as registerDisposable, z as RESPONSE_CHANNEL } from "./application-DqD58rhF.mjs";
13
14
  import { a as ProblemException, c as defaultProblemTitle, i as ProblemDetails, l as normalizeProblem, n as HttpStatus, o as Problems, r as HttpStatusCode, s as ValidationError, t as HttpException } from "./errors-By6UueCm.mjs";
14
15
  import { n as joinPaths, r as normalizePath, t as buildMountPath } from "./path-CMwIHsdv.mjs";
15
16
  import { a as isRef, c as toRefs, i as computed, l as unref, n as Ref, o as reactive, r as WatchOptions, s as ref, t as ComputedRef, u as watch } from "./reactivity-BkMNA0kp.mjs";
17
+ import { a as session, i as SessionStore, n as SessionData, r as SessionOptions, t as Session } from "./session-4Tb6q0Ny.mjs";
16
18
  import { C as SortItem, S as QueryFieldConfig, T as TypedParsedQuery, _ as FilterOperator, a as getQueryParsingDefaults, b as ParsedQuery, c as parseQuery, d as resetQueryParsingDefaults, f as setQueryParsingDefaults, g as FilterItem, h as FieldsOf, i as buildQueryParams, l as parseSearchQuery, m as FILTER_OPERATORS, n as QueryRejectReason, o as parseFilters, r as QueryRejection, s as parsePagination, t as ParseQueryOptions, u as parseSort, v as PaginatedResponse, x as QueryBuilderAdapter, y as PaginationParams } from "./index-BfT5KZ-M.mjs";
17
- import { a as KvSessionStoreOptions, c as InferHandlerResponse, d as isReply, f as reply, i as KvSessionStore, l as Reply, n as KvRateLimitStore, o as RateLimitGuardOptions, r as KvRateLimitStoreOptions, s as rateLimitGuard, t as KvLike, u as applyHandlerResult } from "./kv-stores-Dx5RvIaP.mjs";
18
- import { i as buildRouteTable, t as BuildRoutesOptions } from "./router-builder-C6gmK0nZ.mjs";
19
+ import { i as buildRouteTable, t as BuildRoutesOptions } from "./router-builder-BSBSYgYW.mjs";
19
20
  import { n as requestId, t as REQUEST_ID_HEADER } from "./request-id-CVzJ1uHD.mjs";
20
21
  import { n as validate } from "./validate-DMYpUnrf.mjs";
21
- import { n as errorHandler, r as notFoundHandler } from "./error-handler-C1uWVGVY.mjs";
22
- import { i as csrfGuard, n as CsrfOptions, r as csrf, t as CsrfGuardOptions } from "./csrf-C4MwaMp4.mjs";
22
+ import { n as errorHandler, r as notFoundHandler } from "./error-handler-DiueQHes.mjs";
23
+ import { i as csrfGuard, n as CsrfOptions, r as csrf, t as CsrfGuardOptions } from "./csrf-COFjRrUz.mjs";
23
24
  import { i as requestLogger, n as LoggedResponse, r as RequestLoggerOptions, t as LoggedRequest } from "./request-logger-TgcKRNDD.mjs";
24
25
  import { n as HelmetOptions, r as helmet } from "./helmet-C2QEU6S-.mjs";
25
26
  import { n as cors, t as CorsOptions } from "./cors-CsibNTQ6.mjs";
26
27
  import { n as RateLimitStore, r as rateLimit, t as RateLimitOptions } from "./rate-limit-Bwed3jOV.mjs";
27
- import { a as session, i as SessionStore, n as SessionData, r as SessionOptions, t as Session } from "./session-BHgRyfqZ.mjs";
28
- import { i as upload, l as resolveMimeTypes, n as buildUploadMiddleware, r as cleanupFiles, t as UploadOptions } from "./upload-TW2ZuECF.mjs";
29
- export { ASSETS, ASSET_MANIFEST_VERSION, type ActiveRuntime, type AdapterAsyncOptions, type AdapterContext, type AdapterFactory, type AdapterHttp, type AdapterMiddleware, type AnyContributorRegistration, ApiQueryParams, type ApiQueryParamsConfig, type ApiQueryParamsConfig as QueryParamsConfig, type AppAdapter, type AppAdapterClass, type AppModule, type AppModuleClass, type AppModuleEntry, Application, type ApplicationOptions, Asset, type AssetKey, type AssetKeyPair, type AssetKeyStrategy, type AugmentationMeta, Autowired, type BareRouteFlag, type BaseUploadOptions, type BuildContext, type BuildPipelineOptions, type BuildRoutesOptions, type Buildable, Builder, type BuilderOf, CRON_META, CacheEvict, type CacheOptions, type CacheProvider, Cacheable, type CallSiteParams, CircuitBreaker, type CircuitBreakerOptions, type CircuitBreakerState, type CircuitBreakerStats, CircuitOpenError, type ClassKind, type ClusterOptions, type ColumnApiQueryParamsConfig, Component, type ComputedRef, ConfigService, type ConnectMiddleware, ConsoleLoggerProvider, type Constructor, Container, type ContainerChangeEvent, type ContainerChangeListener, type ContextDecorator, type ContextDecoratorRequiringParams, type ContextDecoratorSpec, type ContextDecoratorTarget, type ContextDecoratorWithDefaults, type ContextKeys, type ContextMeta, type ContextMetaKey, ContributorCycleError, type ContributorPipeline, type ContributorRegistration, type ContributorRegistrations, type ContributorSource, Controller, type CorsOptions, Cron, type CronJobMeta, type CsrfGuardOptions, type CsrfOptions, type Ctx, type CtxHandler, type DeepReadonly, type DefineAdapterOptions, type DefineModuleOptions, type DefinePluginOptions, Delete, type DepValue, type Disposable, DuplicateContributorError, DuplicateMountNameError, type Env, type EnvKey, type ExecutionContext, type ExpressRuntimeTypes, FILTER_OPERATORS, type FieldsOf, type FileTypeFilter, FileUpload, type FileUploadConfig, type FilterItem, type FilterOperator, type FormatKickErrorOptions, Get, type GroupAssetKeysOptions, type GroupAssetKeysResult, HEALTH_PROBE, type HealthCheckResult, HealthController, type HealthModuleConfig, type HealthProbe, type HelmetOptions, HttpException, type HttpRuntime, HttpStatus, type HttpStatusCode, INJECTION_TOKEN, type InferHandlerResponse, Inject, Injectable, type InjectionToken, type IntrospectFn, type IntrospectionKind, type IntrospectionSnapshot, type KickAssets, KickError, type KickErrorInit, type KickHandler, type KickJsPluginName, type KickJsPluginRegistry, type KickJsRegistry, type KickPlugin, type KickRouteFlags, type KickRuntimeRegister, type KvLike, KvRateLimitStore, type KvRateLimitStoreOptions, KvSessionStore, type KvSessionStoreOptions, type LoggedRequest, type LoggedResponse, Logger, type LoggerProvider, METADATA, type MatchedRoute, type MaybePromise, MemoryCacheProvider, type MetaValue, Middleware, type MiddlewareEntry, type MiddlewareHandler, type MiddlewarePath, type MiddlewarePhase, MissingContextValueError, MissingContributorError, MissingMountDepError, type MissingParamKeys, type ModuleFactory, ModuleList, type ModuleRegistry, type ModuleRoutes, MountCycleError, type MountKind, type MountSortItem, MutableModuleRegistry, type NegatedRouteFlagName, type PaginatedResponse, type PaginationParams, type ParseQueryOptions, type ParsedQuery, Patch, type PluginAsyncOptions, type PluginFactory, Post, PostConstruct, type PostConstructStatus, PreDestroy, type ProblemDetails, ProblemException, Problems, Put, type QueryBuilderAdapter, type QueryFieldConfig, type QueryRejectReason, type QueryRejection, REQUEST_ID_HEADER, type RateLimitGuardOptions, type RateLimitOptions, type RateLimitStore, type Ref, type Reply, Repository, RequestContext, type RequestLoggerOptions, type RequestStore, type ResolvedDeps, type RouteDefinition, type RouteEntry, type RouteFlag, type RouteFlagContext, type RouteFlagDeclaration, type RouteFlagDeclarations, type RouteFlagName, type RouteFlagPredicate, type RouteFlagRecord, type RouteFlagTest, type RouteFlagValue, type RouteFlags, type RouteMeta, type RouteMethod, RoutePolicyTable, type RouteShape, type RouteTable, type RunContributorsOptions, type RuntimeAppOptions, type RuntimeCapabilities, type RuntimeResponse, type RuntimeTypeMap, Scope, Service, type ServiceOptions, type Session, type SessionData, type SessionOptions, type SessionStore, type SortItem, type SourcedRegistration, SpaAdapter, type SpaAdapterOptions, type SseHandler, TRACEPARENT_HEADER, type TraceContext, type TraceContextOptions, type TypedConfigService, type TypedParsedQuery, UnknownAssetError, type UploadOptions, type UseConnectOptions, type ValidationError, Value, type ValuedRouteFlag, ViewAdapter, type ViewAdapterOptions, type WatchOptions, applyHandlerResult, assertFlagTest, assets, baseEnvSchema, bindRoutePolicy, bootstrap, buildMountPath, buildPipeline, buildQueryParams, buildRouteTable, buildRoutes, buildUploadMiddleware, cleanupFiles, clearAssetCache, computed, cors, createConfigService, createHandler, createLogger, createToken, csrf, csrfGuard, defaultProblemTitle, defineAdapter, defineAugmentation, defineContextDecorator, defineEnv, defineHttpContextDecorator, defineModule, defineModules, definePlugin, defineRouteFlag, describeError, disposeAll, errorHandler, expressRuntime, formatKickError, getCacheProvider, getClassMeta, getClassMetaOrUndefined, getCronJobs, getEnv, getMetaMap, getMetaRecord, getMethodMeta, getMethodMetaOrUndefined, getQueryParsingDefaults, getRequestStore, getRequestValue, getRouteFlags, groupAssetKeys, hasClassMeta, healthModule, helmet, isClusterPrimary, isInjectionToken, isRef, isReply, joinPaths, loadEnv, loadEnvFromSchema, matchesFlagTest, materializeRouter, mountSort, normalizeApiQueryParamsConfig, normalizePath, normalizeProblem, notFoundHandler, offerRoutePolicy, parseFilters, parsePagination, parseQuery, parseSearchQuery, parseSort, parseTraceparent, pushClassMeta, pushMethodMeta, rateLimit, rateLimitGuard, reactive, ref, registerDisposable, reloadEnv, reply, requestId, requestLogger, requestScopeMiddleware, requestStore, resetEnvCache, resetQueryParsingDefaults, resolveAsset, resolveMimeTypes, resolveRouteFlags, runContributors, session, setCacheProvider, setClassMeta, setInMetaMap, setInMetaRecord, setMethodMeta, setQueryParsingDefaults, stripExt, toRefs, tokenName, traceContext, unref, upload, useAssets, validate, watch, withBuilder };
28
+ import { i as upload, l as resolveMimeTypes, n as buildUploadMiddleware, r as cleanupFiles, t as UploadOptions } from "./upload-DjhnyHHm.mjs";
29
+ export { ASSETS, ASSET_MANIFEST_VERSION, type ActiveRuntime, type AdapterAsyncOptions, type AdapterContext, type AdapterFactory, type AdapterHttp, type AdapterMiddleware, type AnyContributorRegistration, ApiQueryParams, type ApiQueryParamsConfig, type ApiQueryParamsConfig as QueryParamsConfig, type AppAdapter, type AppAdapterClass, type AppModule, type AppModuleClass, type AppModuleEntry, Application, type ApplicationOptions, Asset, type AssetKey, type AssetKeyPair, type AssetKeyStrategy, Autowired, type BareRouteFlag, type BaseUploadOptions, type BuildContext, type BuildPipelineOptions, type BuildRoutesOptions, type Buildable, Builder, type BuilderOf, CRON_META, CRON_WORKER_ENV, CacheEvict, type CacheOptions, type CacheProvider, Cacheable, type CallSiteParams, CircuitBreaker, type CircuitBreakerOptions, type CircuitBreakerState, type CircuitBreakerStats, CircuitOpenError, type ClassKind, type ClusterOptions, type ColumnApiQueryParamsConfig, Component, type ComputedRef, ConfigService, type ConnectMiddleware, ConsoleLoggerProvider, type Constructor, Container, type ContainerChangeEvent, type ContainerChangeListener, type ContextDecorator, type ContextDecoratorRequiringParams, type ContextDecoratorSpec, type ContextDecoratorTarget, type ContextDecoratorWithDefaults, type ContextKeys, type ContextMeta, type ContextMetaKey, ContributorCycleError, type ContributorPipeline, type ContributorRegistration, type ContributorRegistrations, type ContributorSource, Controller, type CorsOptions, Cron, type CronAdapterOptions, type CronJob, type CronJobMeta, type CronOptions, type CronRun, type CsrfGuardOptions, type CsrfOptions, type Ctx, type CtxHandler, type DeepReadonly, type DefineAdapterOptions, type DefineModuleOptions, type DefinePluginOptions, Delete, type DepValue, type Disposable, DuplicateContributorError, DuplicateMountNameError, ERROR_CHANNEL, type Env, type EnvKey, type ErrorInfo, type ErrorSource, type ExecutionContext, type ExpressRuntimeTypes, FILTER_OPERATORS, type FieldsOf, type FileTypeFilter, FileUpload, type FileUploadConfig, type FilterItem, type FilterOperator, type FormatKickErrorOptions, Get, type GroupAssetKeysOptions, type GroupAssetKeysResult, HANDLER_CHANNEL, HEALTH_PROBE, type HandlerTraceContext, type HealthCheckResult, HealthController, type HealthModuleConfig, type HealthProbe, type HelmetOptions, HttpException, type HttpRuntime, HttpStatus, type HttpStatusCode, INJECTION_TOKEN, type InferHandlerResponse, Inject, Injectable, type InjectionToken, type IntrospectFn, type IntrospectionKind, type IntrospectionSnapshot, JOB_CONTEXT_FIELD, JOB_DISPATCHER, JOB_META, Job, type JobContextCarrier, type JobDispatcher, type JobHandler, type JobLike, type KickAssets, KickCronAdapter, KickError, type KickErrorInit, type KickHandler, type KickJsPluginName, type KickJsPluginRegistry, type KickJsRegistry, type KickPlugin, type KickRouteFlags, type KickRuntimeRegister, type KickServer, type KvLike, KvRateLimitStore, type KvRateLimitStoreOptions, KvSessionStore, type KvSessionStoreOptions, type LoggedRequest, type LoggedResponse, Logger, type LoggerProvider, METADATA, type MatchedRoute, type MaybePromise, MemoryCacheProvider, type MetaValue, Middleware, type MiddlewareEntry, type MiddlewareHandler, type MiddlewarePath, type MiddlewarePhase, MissingContextValueError, MissingContributorError, MissingMountDepError, type MissingParamKeys, type ModuleFactory, ModuleList, type ModuleRegistry, type ModuleRoutes, MountCycleError, type MountKind, type MountSortItem, MutableModuleRegistry, type NegatedRouteFlagName, NoJobHandlerError, type PaginatedResponse, type PaginationParams, type ParseQueryOptions, type ParsedQuery, Patch, type PlatformContext, type PluginAsyncOptions, type PluginFactory, Post, PostConstruct, type PostConstructStatus, PreDestroy, type ProblemDetails, ProblemException, Problems, Process, type ProcessDefinition, Put, type QueryBuilderAdapter, type QueryFieldConfig, type QueryRejectReason, type QueryRejection, REQUEST_ID_HEADER, RESPONSE_CHANNEL, type RateLimitGuardOptions, type RateLimitOptions, type RateLimitStore, type Ref, type Reply, Repository, RequestContext, type RequestLoggerOptions, type RequestStore, type ResolvedDeps, type ResponseInfo, type RouteDefinition, type RouteEntry, type RouteFlag, type RouteFlagContext, type RouteFlagDeclaration, type RouteFlagDeclarations, type RouteFlagName, type RouteFlagPredicate, type RouteFlagRecord, type RouteFlagTest, type RouteFlagValue, type RouteFlags, type RouteMeta, type RouteMethod, RoutePolicyTable, type RouteShape, type RouteTable, type RunContributorsOptions, type RuntimeAppOptions, type RuntimeCapabilities, type RuntimeResponse, type RuntimeTypeMap, Scope, type ServerOptions, Service, type ServiceOptions, type Session, type SessionData, type SessionOptions, type SessionStore, type SortItem, type SourcedRegistration, SpaAdapter, type SpaAdapterOptions, type SseHandler, TRACEPARENT_HEADER, type TraceContext, type TraceContextOptions, type TypedConfigService, type TypedParsedQuery, UnknownAssetError, type UploadOptions, type UseConnectOptions, type ValidationError, Value, type ValuedRouteFlag, ViewAdapter, type ViewAdapterOptions, type WatchOptions, applyHandlerResult, assertFlagTest, assets, baseEnvSchema, bindRoutePolicy, bootstrap, buildMountPath, buildPipeline, buildQueryParams, buildRouteTable, buildRoutes, buildUploadMiddleware, cleanupFiles, clearAssetCache, computed, cors, createConfigService, createHandler, createLogger, createToken, cronScheduleId, csrf, csrfGuard, defaultProblemTitle, defineAdapter, defineContextDecorator, defineEnv, defineHttpContextDecorator, defineModule, defineModules, definePlugin, defineRouteFlag, describeError, disposeAll, errorHandler, expressRuntime, formatKickError, getCacheProvider, getClassMeta, getClassMetaOrUndefined, getCronJobs, getEnv, getMetaMap, getMetaRecord, getMethodMeta, getMethodMetaOrUndefined, getQueryParsingDefaults, getRequestStore, getRequestValue, getRouteFlags, groupAssetKeys, hasClassMeta, healthModule, helmet, isClusterPrimary, isCronJobEnabled, isInjectionToken, isRef, isReply, joinPaths, listCronJobs, listJobHandlers, listJobQueues, loadEnv, loadEnvFromSchema, matchesFlagTest, materializeRouter, mountSort, normalizeApiQueryParamsConfig, normalizePath, normalizeProblem, notFoundHandler, offerRoutePolicy, parseFilters, parsePagination, parseQuery, parseSearchQuery, parseSort, parseTraceparent, pushClassMeta, pushMethodMeta, rateLimit, rateLimitGuard, reactive, ref, registerDisposable, registerJobContext, reloadEnv, reply, reportError, reportResponse, requestId, requestLogger, requestScopeMiddleware, requestStore, resetEnvCache, resetQueryParsingDefaults, resolveAsset, resolveMimeTypes, resolveRouteFlags, runContributors, runCronJob, runCronJobs, runJob, session, setCacheProvider, setClassMeta, setInMetaMap, setInMetaRecord, setMethodMeta, setQueryParsingDefaults, settleBackgroundWork, stampJobContext, stripExt, toRefs, tokenName, traceContext, unref, upload, useAssets, validate, waitUntil, watch, withBuilder, withEnv };
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v8.6.0
2
+ * @forinda/kickjs v9.0.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{a as loadEnvFromSchema,i as loadEnv,n as defineEnv,o as reloadEnv,r as getEnv,s as resetEnvCache,t as baseEnvSchema}from"./env-BelmDj19.mjs";import{METADATA,Scope}from"./core/interfaces.mjs";import{a as isInjectionToken,c as KickError,i as createToken,l as formatKickError,n as tokenName,r as INJECTION_TOKEN,t as Container}from"./container-DF8FRoY8.mjs";import{ConsoleLoggerProvider,Logger,createLogger,describeError}from"./core/logger.mjs";import{a as getMethodMeta,c as pushClassMeta,d as setInMetaMap,f as setInMetaRecord,i as getMetaRecord,l as pushMethodMeta,n as getClassMetaOrUndefined,o as getMethodMetaOrUndefined,p as setMethodMeta,r as getMetaMap,s as hasClassMeta,t as getClassMeta,u as setClassMeta}from"./metadata-B8_KXybT.mjs";import{ApiQueryParams,Asset,Autowired,Builder,Component,Controller,Delete,FileUpload,Get,Inject,Injectable,Middleware,Patch,Post,PostConstruct,PreDestroy,Put,Repository,Service,Value,normalizeApiQueryParamsConfig,withBuilder}from"./core/decorators.mjs";import{a as HEALTH_PROBE,c as DuplicateMountNameError,d as mountSort,f as defineModule,i as materializeRouter,l as MissingMountDepError,n as buildRoutes,o as HealthController,r as expressRuntime,s as healthModule,t as Application,u as MountCycleError}from"./application-DZiG1QCw.mjs";import{t as MutableModuleRegistry}from"./module-registry-BFrJ1PQ4.mjs";import{CRON_META,Cron,getCronJobs}from"./core/cron.mjs";import{CacheEvict,Cacheable,MemoryCacheProvider,getCacheProvider,setCacheProvider}from"./core/cache.mjs";import{r as registerDisposable,t as disposeAll}from"./disposables-CEAxve3A.mjs";import{HttpException,HttpStatus,ProblemException,Problems,defaultProblemTitle,normalizeProblem}from"./core/errors.mjs";import{buildMountPath,joinPaths,normalizePath}from"./core/path.mjs";import{computed,isRef,reactive,ref,toRefs,unref,watch}from"./core/reactivity.mjs";import{l as resolveRouteFlags,n as assertFlagTest,o as getRouteFlags,r as defineRouteFlag,s as matchesFlagTest}from"./route-flag-B4sNP7zH.mjs";import{a as clearAssetCache,c as groupAssetKeys,i as assets,l as stripExt,n as ASSET_MANIFEST_VERSION,o as resolveAsset,r as UnknownAssetError,s as useAssets,t as ASSETS,u as defineContextDecorator}from"./core-y8QbzHM5.mjs";import{i as MissingContributorError,n as DuplicateContributorError,r as MissingContextValueError,t as ContributorCycleError}from"./context-errors-Ch0DuUQo.mjs";import{i as buildPipeline,r as buildRouteTable}from"./router-builder-cTsA2XtO.mjs";import{t as runContributors}from"./contributor-runner-DujKZy4N.mjs";import{t as defineAdapter}from"./define-adapter-C1Db6xfO.mjs";import{n as bindRoutePolicy,r as offerRoutePolicy,t as RoutePolicyTable}from"./route-policy-CDlMbl1b.mjs";import{c as requestScopeMiddleware,i as reply,n as applyHandlerResult,r as isReply}from"./runtime-C-7Yhs7a.mjs";import{REQUEST_ID_HEADER,requestId}from"./http/middleware/request-id.mjs";import{errorHandler,notFoundHandler}from"./http/middleware/error-handler.mjs";import{i as requestStore,n as getRequestStore,r as getRequestValue,t as RequestContext}from"./context-BTqeZH1A.mjs";import{a as parseQuery,c as resetQueryParsingDefaults,i as parsePagination,l as setQueryParsingDefaults,n as getQueryParsingDefaults,o as parseSearchQuery,r as parseFilters,s as parseSort,t as buildQueryParams,u as FILTER_OPERATORS}from"./query-CC7o6I5K.mjs";import{validate}from"./http/middleware/validate.mjs";import{r as resolveMimeTypes}from"./upload-config-CoE6BzM4.mjs";import{buildUploadMiddleware,cleanupFiles,upload}from"./http/middleware/upload.mjs";import{n as isClusterPrimary,t as bootstrap}from"./bootstrap-BEbka3UV.mjs";import{n as csrfGuard,r as randomHex,t as csrf}from"./csrf-RP5hgc0c.mjs";import{requestLogger}from"./http/middleware/request-logger.mjs";import{helmet}from"./http/middleware/helmet.mjs";import{cors}from"./http/middleware/cors.mjs";import{rateLimit}from"./http/middleware/rate-limit.mjs";import{n as KvSessionStore,r as rateLimitGuard,t as KvRateLimitStore}from"./kv-stores-DUFcps01.mjs";import{session}from"./http/middleware/session.mjs";import{ViewAdapter}from"./http/middleware/views.mjs";import{SpaAdapter}from"./http/middleware/spa.mjs";import{n as createConfigService,t as ConfigService}from"./config-CIOXZmLS.mjs";var ModuleList=class extends Array{mount(module){return this.push(module),this}};function defineModules(...initial){let list=new ModuleList;for(let entry of initial)list.push(entry);return list}var CircuitOpenError=class extends Error{breakerName;constructor(breakerName){super(`Circuit breaker "${breakerName}" is open — request rejected`),this.breakerName=breakerName,this.name=`CircuitOpenError`}},CircuitBreaker=class{name;state=`closed`;failures=0;successes=0;halfOpenAttempts=0;lastFailure;openedAt;failureThreshold;resetTimeout;halfOpenMax;constructor(name,options){this.name=name,this.failureThreshold=options.failureThreshold,this.resetTimeout=options.resetTimeout,this.halfOpenMax=options.halfOpenMax??1}async execute(fn){if(this.maybeTransitionToHalfOpen(),this.state===`open`||this.state===`half_open`&&this.halfOpenAttempts>=this.halfOpenMax)throw new CircuitOpenError(this.name);this.state===`half_open`&&this.halfOpenAttempts++;try{let result=await fn();return this.onSuccess(),result}catch(error){throw this.onFailure(),error}}getState(){return this.maybeTransitionToHalfOpen(),this.state}getStats(){return this.maybeTransitionToHalfOpen(),{failures:this.failures,successes:this.successes,state:this.state,...this.lastFailure?{lastFailure:this.lastFailure}:{}}}reset(){this.state=`closed`,this.failures=0,this.successes=0,this.halfOpenAttempts=0,this.lastFailure=void 0,this.openedAt=void 0}onSuccess(){this.state===`half_open`&&(this.state=`closed`,this.failures=0,this.halfOpenAttempts=0,this.openedAt=void 0),this.successes++}onFailure(){this.failures++,this.lastFailure=new Date,this.state===`half_open`?(this.state=`open`,this.openedAt=Date.now(),this.halfOpenAttempts=0):this.state===`closed`&&this.failures>=this.failureThreshold&&(this.state=`open`,this.openedAt=Date.now())}maybeTransitionToHalfOpen(){this.state===`open`&&this.openedAt!=null&&Date.now()-this.openedAt>=this.resetTimeout&&(this.state=`half_open`,this.halfOpenAttempts=0)}};const mergeConfig=(defaults={},overrides={})=>({...defaults,...overrides}),composeName=(base,scope)=>`${base}:${scope}`;function definePlugin(options){let buildSync=(instanceName,scoped,overrides)=>{let config=mergeConfig(options.defaults,overrides),built=options.build(config,{name:instanceName,scoped});return built.name=instanceName,built},buildAsync=(instanceName,opts)=>{let inner,ensureInner=async container=>{if(inner)return inner;let deps=(opts.inject??[]).map(tok=>container.resolve(tok)),config=await opts.useFactory(...deps);return inner=buildSync(instanceName,!1,config),inner};return{name:instanceName,async onReady(container){let built=await ensureInner(container);built.register?.(container),await built.onReady?.(container)},async shutdown(){await inner?.shutdown?.()}}},factory=(config=>buildSync(options.name,!1,config));return factory.scoped=(scopeName,config)=>buildSync(composeName(options.name,scopeName),!0,config),factory.async=opts=>buildAsync(options.name,opts),Object.defineProperty(factory,"definition",{value:Object.freeze({...options})}),factory}function defineAugmentation(name,meta){}function createHandler(options){let app,ready=()=>(app??=(async()=>{let instance=new Application(options);try{await instance.startWithoutServer()}catch(err){throw app=void 0,await instance.shutdown().catch(()=>{}),err}return instance})(),app);return{ready,async fetch(request){return(await ready()).fetch(request)},async node(req,res){(await ready()).handle(req,res)},async close(){let current=app;app=void 0,current&&await(await current).shutdown()}}}function defineHttpContextDecoratorImpl(spec){return defineContextDecorator(spec)}const defineHttpContextDecorator=Object.freeze(Object.assign(defineHttpContextDecoratorImpl,{withParams:()=>spec=>defineHttpContextDecoratorImpl(spec)})),TRACEPARENT_HEADER=`traceparent`,TRACEPARENT_RE=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;function generateTraceId(){return randomHex(16)}function generateSpanId(){return randomHex(8)}function parseTraceparent(header){let match=TRACEPARENT_RE.exec(header.trim().toLowerCase());if(!match)return null;let version=match[1],traceId=match[2],parentSpanId=match[3],flags=match[4];return version===`ff`||traceId===`00000000000000000000000000000000`||parentSpanId===`0000000000000000`?null:{version,traceId,parentSpanId,flags}}function traceContext(options={}){return(req,res,next)=>{let store=requestStore.getStore(),traceparentHeader=req.headers[TRACEPARENT_HEADER],raw=Array.isArray(traceparentHeader)?traceparentHeader[0]:traceparentHeader,parsed=raw?parseTraceparent(raw):null,traceId=parsed?.traceId??generateTraceId(),spanId=generateSpanId();store&&(store.values.set(`traceId`,traceId),store.values.set(`spanId`,spanId),parsed&&(store.values.set(`parentSpanId`,parsed.parentSpanId),store.values.set(`traceFlags`,parsed.flags),store.values.set(`traceVersion`,parsed.version))),req.traceId=traceId,req.spanId=spanId,options.propagateResponse&&res.setHeader(`traceresponse`,traceId),next()}}export{ASSETS,ASSET_MANIFEST_VERSION,ApiQueryParams,Application,Asset,Autowired,Builder,CRON_META,CacheEvict,Cacheable,CircuitBreaker,CircuitOpenError,Component,ConfigService,ConsoleLoggerProvider,Container,ContributorCycleError,Controller,Cron,Delete,DuplicateContributorError,DuplicateMountNameError,FILTER_OPERATORS,FileUpload,Get,HEALTH_PROBE,HealthController,HttpException,HttpStatus,INJECTION_TOKEN,Inject,Injectable,KickError,KvRateLimitStore,KvSessionStore,Logger,METADATA,MemoryCacheProvider,Middleware,MissingContextValueError,MissingContributorError,MissingMountDepError,ModuleList,MountCycleError,MutableModuleRegistry,Patch,Post,PostConstruct,PreDestroy,ProblemException,Problems,Put,REQUEST_ID_HEADER,Repository,RequestContext,RoutePolicyTable,Scope,Service,SpaAdapter,TRACEPARENT_HEADER,UnknownAssetError,Value,ViewAdapter,applyHandlerResult,assertFlagTest,assets,baseEnvSchema,bindRoutePolicy,bootstrap,buildMountPath,buildPipeline,buildQueryParams,buildRouteTable,buildRoutes,buildUploadMiddleware,cleanupFiles,clearAssetCache,computed,cors,createConfigService,createHandler,createLogger,createToken,csrf,csrfGuard,defaultProblemTitle,defineAdapter,defineAugmentation,defineContextDecorator,defineEnv,defineHttpContextDecorator,defineModule,defineModules,definePlugin,defineRouteFlag,describeError,disposeAll,errorHandler,expressRuntime,formatKickError,getCacheProvider,getClassMeta,getClassMetaOrUndefined,getCronJobs,getEnv,getMetaMap,getMetaRecord,getMethodMeta,getMethodMetaOrUndefined,getQueryParsingDefaults,getRequestStore,getRequestValue,getRouteFlags,groupAssetKeys,hasClassMeta,healthModule,helmet,isClusterPrimary,isInjectionToken,isRef,isReply,joinPaths,loadEnv,loadEnvFromSchema,matchesFlagTest,materializeRouter,mountSort,normalizeApiQueryParamsConfig,normalizePath,normalizeProblem,notFoundHandler,offerRoutePolicy,parseFilters,parsePagination,parseQuery,parseSearchQuery,parseSort,parseTraceparent,pushClassMeta,pushMethodMeta,rateLimit,rateLimitGuard,reactive,ref,registerDisposable,reloadEnv,reply,requestId,requestLogger,requestScopeMiddleware,requestStore,resetEnvCache,resetQueryParsingDefaults,resolveAsset,resolveMimeTypes,resolveRouteFlags,runContributors,session,setCacheProvider,setClassMeta,setInMetaMap,setInMetaRecord,setMethodMeta,setQueryParsingDefaults,stripExt,toRefs,tokenName,traceContext,unref,upload,useAssets,validate,watch,withBuilder};
11
+ import{a as loadEnvFromSchema,c as withEnv,i as loadEnv,n as defineEnv,o as reloadEnv,r as getEnv,s as resetEnvCache,t as baseEnvSchema}from"./env-DMAdjj8Z.mjs";import{METADATA,Scope}from"./core/interfaces.mjs";import{a as isInjectionToken,d as KickError,f as formatKickError,i as createToken,n as tokenName,r as INJECTION_TOKEN,t as Container}from"./container-Dw45sa0Y.mjs";import{ConsoleLoggerProvider,Logger,createLogger,describeError}from"./core/logger.mjs";import{a as getMethodMeta,c as pushClassMeta,d as setInMetaMap,f as setInMetaRecord,i as getMetaRecord,l as pushMethodMeta,n as getClassMetaOrUndefined,o as getMethodMetaOrUndefined,p as setMethodMeta,r as getMetaMap,s as hasClassMeta,t as getClassMeta,u as setClassMeta}from"./metadata-BQG1MmqL.mjs";import{ApiQueryParams,Asset,Autowired,Builder,Component,Controller,Delete,FileUpload,Get,Inject,Injectable,Middleware,Patch,Post,PostConstruct,PreDestroy,Put,Repository,Service,Value,normalizeApiQueryParamsConfig,withBuilder}from"./core/decorators.mjs";import{a as HEALTH_PROBE,c as ERROR_CHANNEL,d as DuplicateMountNameError,f as MissingMountDepError,h as defineModule,i as materializeRouter,l as HANDLER_CHANNEL,m as mountSort,n as buildRoutes,o as HealthController,p as MountCycleError,r as expressRuntime,s as healthModule,t as Application,u as RESPONSE_CHANNEL}from"./application-BnFA6J97.mjs";import{t as MutableModuleRegistry}from"./module-registry-BXnvRtH9.mjs";import{i as reportResponse,r as reportError}from"./observers-BI8H_g45.mjs";import{CRON_META,Cron,cronScheduleId,getCronJobs,isCronJobEnabled,listCronJobs,runCronJob,runCronJobs}from"./core/cron.mjs";import{a as NoJobHandlerError,c as listJobQueues,d as stampJobContext,i as Job,l as registerJobContext,n as JOB_DISPATCHER,o as Process,r as JOB_META,s as listJobHandlers,t as JOB_CONTEXT_FIELD,u as runJob}from"./jobs-C8_ESbx0.mjs";import{CacheEvict,Cacheable,MemoryCacheProvider,getCacheProvider,setCacheProvider}from"./core/cache.mjs";import{r as registerDisposable,t as disposeAll}from"./disposables-DnvT8DXr.mjs";import{HttpException,HttpStatus,ProblemException,Problems,defaultProblemTitle,normalizeProblem}from"./core/errors.mjs";import{buildMountPath,joinPaths,normalizePath}from"./core/path.mjs";import{computed,isRef,reactive,ref,toRefs,unref,watch}from"./core/reactivity.mjs";import{l as resolveRouteFlags,n as assertFlagTest,o as getRouteFlags,r as defineRouteFlag,s as matchesFlagTest}from"./route-flag-GipNvQ4O.mjs";import{a as clearAssetCache,c as groupAssetKeys,i as assets,l as stripExt,n as ASSET_MANIFEST_VERSION,o as resolveAsset,r as UnknownAssetError,s as useAssets,t as ASSETS,u as defineContextDecorator}from"./core-CCwlN0Gn.mjs";import{i as MissingContributorError,n as DuplicateContributorError,r as MissingContextValueError,t as ContributorCycleError}from"./context-errors-BqOFD7UE.mjs";import{i as buildPipeline,r as buildRouteTable}from"./router-builder-C2nnS0VJ.mjs";import{t as runContributors}from"./contributor-runner-DLvBA96K.mjs";import{t as defineAdapter}from"./define-adapter-Ckc2P-wH.mjs";import{n as bindRoutePolicy,r as offerRoutePolicy,t as RoutePolicyTable}from"./route-policy-DtGR4sar.mjs";import{c as requestScopeMiddleware,i as reply,n as applyHandlerResult,r as isReply}from"./runtime-DGzigyO2.mjs";import{REQUEST_ID_HEADER,requestId}from"./http/middleware/request-id.mjs";import{a as settleBackgroundWork,c as getRequestValue,l as requestStore,o as waitUntil,r as forwardBackgroundWork,s as getRequestStore,t as RequestContext}from"./context-DlIdXA6I.mjs";import{errorHandler,notFoundHandler}from"./http/middleware/error-handler.mjs";import{a as parseQuery,c as resetQueryParsingDefaults,i as parsePagination,l as setQueryParsingDefaults,n as getQueryParsingDefaults,o as parseSearchQuery,r as parseFilters,s as parseSort,t as buildQueryParams,u as FILTER_OPERATORS}from"./query-CRTeiKUv.mjs";import{validate}from"./http/middleware/validate.mjs";import{r as resolveMimeTypes}from"./upload-config-CcoZp7xA.mjs";import{buildUploadMiddleware,cleanupFiles,upload}from"./http/middleware/upload.mjs";import{i as KickCronAdapter,n as isClusterPrimary,r as CRON_WORKER_ENV,t as bootstrap}from"./bootstrap-K1PcxSTg.mjs";import{n as csrfGuard,r as randomHex,t as csrf}from"./csrf-B8CGeOlP.mjs";import{requestLogger}from"./http/middleware/request-logger.mjs";import{helmet}from"./http/middleware/helmet.mjs";import{cors}from"./http/middleware/cors.mjs";import{rateLimit}from"./http/middleware/rate-limit.mjs";import{n as KvSessionStore,r as rateLimitGuard,t as KvRateLimitStore}from"./kv-stores-BhUmirED.mjs";import{session}from"./http/middleware/session.mjs";import{ViewAdapter}from"./http/middleware/views.mjs";import{SpaAdapter}from"./http/middleware/spa.mjs";import{n as createConfigService,t as ConfigService}from"./config-16yw-Mxk.mjs";var ModuleList=class extends Array{mount(module){return this.push(module),this}};function defineModules(...initial){let list=new ModuleList;for(let entry of initial)list.push(entry);return list}var CircuitOpenError=class extends Error{breakerName;constructor(breakerName){super(`Circuit breaker "${breakerName}" is open — request rejected`),this.breakerName=breakerName,this.name=`CircuitOpenError`}},CircuitBreaker=class{name;state=`closed`;failures=0;successes=0;halfOpenAttempts=0;lastFailure;openedAt;failureThreshold;resetTimeout;halfOpenMax;constructor(name,options){this.name=name,this.failureThreshold=options.failureThreshold,this.resetTimeout=options.resetTimeout,this.halfOpenMax=options.halfOpenMax??1}async execute(fn){if(this.maybeTransitionToHalfOpen(),this.state===`open`||this.state===`half_open`&&this.halfOpenAttempts>=this.halfOpenMax)throw new CircuitOpenError(this.name);this.state===`half_open`&&this.halfOpenAttempts++;try{let result=await fn();return this.onSuccess(),result}catch(error){throw this.onFailure(),error}}getState(){return this.maybeTransitionToHalfOpen(),this.state}getStats(){return this.maybeTransitionToHalfOpen(),{failures:this.failures,successes:this.successes,state:this.state,...this.lastFailure?{lastFailure:this.lastFailure}:{}}}reset(){this.state=`closed`,this.failures=0,this.successes=0,this.halfOpenAttempts=0,this.lastFailure=void 0,this.openedAt=void 0}onSuccess(){this.state===`half_open`&&(this.state=`closed`,this.failures=0,this.halfOpenAttempts=0,this.openedAt=void 0),this.successes++}onFailure(){this.failures++,this.lastFailure=new Date,this.state===`half_open`?(this.state=`open`,this.openedAt=Date.now(),this.halfOpenAttempts=0):this.state===`closed`&&this.failures>=this.failureThreshold&&(this.state=`open`,this.openedAt=Date.now())}maybeTransitionToHalfOpen(){this.state===`open`&&this.openedAt!=null&&Date.now()-this.openedAt>=this.resetTimeout&&(this.state=`half_open`,this.halfOpenAttempts=0)}};const mergeConfig=(defaults={},overrides={})=>({...defaults,...overrides}),composeName=(base,scope)=>`${base}:${scope}`;function definePlugin(options){let buildSync=(instanceName,scoped,overrides)=>{let config=mergeConfig(options.defaults,overrides),built=options.build(config,{name:instanceName,scoped});return built.name=instanceName,built},buildAsync=(instanceName,opts)=>{let inner,ensureInner=async container=>{if(inner)return inner;let deps=(opts.inject??[]).map(tok=>container.resolve(tok)),config=await opts.useFactory(...deps);return inner=buildSync(instanceName,!1,config),inner};return{name:instanceName,async onReady(container){let built=await ensureInner(container);built.register?.(container),await built.onReady?.(container)},async shutdown(){await inner?.shutdown?.()}}},factory=(config=>buildSync(options.name,!1,config));return factory.scoped=(scopeName,config)=>buildSync(composeName(options.name,scopeName),!0,config),factory.async=opts=>buildAsync(options.name,opts),Object.defineProperty(factory,"definition",{value:Object.freeze({...options})}),factory}function createHandler(options){let app,ready=()=>(app??=(async()=>{let instance=new Application(options);try{await instance.startWithoutServer()}catch(err){throw app=void 0,await instance.shutdown().catch(()=>{}),err}return instance})(),app);return{ready,async fetch(request,platform){let response=await(await ready()).fetch(request);return forwardBackgroundWork(platform),response},async node(req,res,platform){if((await ready()).handle(req,res),platform?.waitUntil){let sent=new Promise(resolve=>res.once(`close`,()=>resolve()));platform.waitUntil(sent.then(settleBackgroundWork))}},async close(){let current=app;app=void 0,current&&await(await current).shutdown()}}}function defineHttpContextDecoratorImpl(spec){return defineContextDecorator(spec)}const defineHttpContextDecorator=Object.freeze(Object.assign(defineHttpContextDecoratorImpl,{withParams:()=>spec=>defineHttpContextDecoratorImpl(spec)})),TRACEPARENT_HEADER=`traceparent`,TRACEPARENT_RE=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;function generateTraceId(){return randomHex(16)}function generateSpanId(){return randomHex(8)}function parseTraceparent(header){let match=TRACEPARENT_RE.exec(header.trim().toLowerCase());if(!match)return null;let version=match[1],traceId=match[2],parentSpanId=match[3],flags=match[4];return version===`ff`||traceId===`00000000000000000000000000000000`||parentSpanId===`0000000000000000`?null:{version,traceId,parentSpanId,flags}}function traceContext(options={}){return(req,res,next)=>{let store=requestStore.getStore(),traceparentHeader=req.headers[TRACEPARENT_HEADER],raw=Array.isArray(traceparentHeader)?traceparentHeader[0]:traceparentHeader,parsed=raw?parseTraceparent(raw):null,traceId=parsed?.traceId??generateTraceId(),spanId=generateSpanId();store&&(store.values.set(`traceId`,traceId),store.values.set(`spanId`,spanId),parsed&&(store.values.set(`parentSpanId`,parsed.parentSpanId),store.values.set(`traceFlags`,parsed.flags),store.values.set(`traceVersion`,parsed.version))),req.traceId=traceId,req.spanId=spanId,options.propagateResponse&&res.setHeader(`traceresponse`,traceId),next()}}export{ASSETS,ASSET_MANIFEST_VERSION,ApiQueryParams,Application,Asset,Autowired,Builder,CRON_META,CRON_WORKER_ENV,CacheEvict,Cacheable,CircuitBreaker,CircuitOpenError,Component,ConfigService,ConsoleLoggerProvider,Container,ContributorCycleError,Controller,Cron,Delete,DuplicateContributorError,DuplicateMountNameError,ERROR_CHANNEL,FILTER_OPERATORS,FileUpload,Get,HANDLER_CHANNEL,HEALTH_PROBE,HealthController,HttpException,HttpStatus,INJECTION_TOKEN,Inject,Injectable,JOB_CONTEXT_FIELD,JOB_DISPATCHER,JOB_META,Job,KickCronAdapter,KickError,KvRateLimitStore,KvSessionStore,Logger,METADATA,MemoryCacheProvider,Middleware,MissingContextValueError,MissingContributorError,MissingMountDepError,ModuleList,MountCycleError,MutableModuleRegistry,NoJobHandlerError,Patch,Post,PostConstruct,PreDestroy,ProblemException,Problems,Process,Put,REQUEST_ID_HEADER,RESPONSE_CHANNEL,Repository,RequestContext,RoutePolicyTable,Scope,Service,SpaAdapter,TRACEPARENT_HEADER,UnknownAssetError,Value,ViewAdapter,applyHandlerResult,assertFlagTest,assets,baseEnvSchema,bindRoutePolicy,bootstrap,buildMountPath,buildPipeline,buildQueryParams,buildRouteTable,buildRoutes,buildUploadMiddleware,cleanupFiles,clearAssetCache,computed,cors,createConfigService,createHandler,createLogger,createToken,cronScheduleId,csrf,csrfGuard,defaultProblemTitle,defineAdapter,defineContextDecorator,defineEnv,defineHttpContextDecorator,defineModule,defineModules,definePlugin,defineRouteFlag,describeError,disposeAll,errorHandler,expressRuntime,formatKickError,getCacheProvider,getClassMeta,getClassMetaOrUndefined,getCronJobs,getEnv,getMetaMap,getMetaRecord,getMethodMeta,getMethodMetaOrUndefined,getQueryParsingDefaults,getRequestStore,getRequestValue,getRouteFlags,groupAssetKeys,hasClassMeta,healthModule,helmet,isClusterPrimary,isCronJobEnabled,isInjectionToken,isRef,isReply,joinPaths,listCronJobs,listJobHandlers,listJobQueues,loadEnv,loadEnvFromSchema,matchesFlagTest,materializeRouter,mountSort,normalizeApiQueryParamsConfig,normalizePath,normalizeProblem,notFoundHandler,offerRoutePolicy,parseFilters,parsePagination,parseQuery,parseSearchQuery,parseSort,parseTraceparent,pushClassMeta,pushMethodMeta,rateLimit,rateLimitGuard,reactive,ref,registerDisposable,registerJobContext,reloadEnv,reply,reportError,reportResponse,requestId,requestLogger,requestScopeMiddleware,requestStore,resetEnvCache,resetQueryParsingDefaults,resolveAsset,resolveMimeTypes,resolveRouteFlags,runContributors,runCronJob,runCronJobs,runJob,session,setCacheProvider,setClassMeta,setInMetaMap,setInMetaRecord,setMethodMeta,setQueryParsingDefaults,settleBackgroundWork,stampJobContext,stripExt,toRefs,tokenName,traceContext,unref,upload,useAssets,validate,waitUntil,watch,withBuilder,withEnv};
12
12
  //# sourceMappingURL=index.mjs.map