@forinda/kickjs 10.12.0 → 10.13.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 (164) hide show
  1. package/dist/{adapter-DiJfCKXU.d.mts → adapter-g_vQffKr.d.mts} +7 -5
  2. package/dist/adapter-g_vQffKr.d.mts.map +1 -0
  3. package/dist/{application-W8fhRn97.mjs → application-dhmb3PMx.mjs} +3 -3
  4. package/dist/{application-W8fhRn97.mjs.map → application-dhmb3PMx.mjs.map} +1 -1
  5. package/dist/{application-Rb6jeTAp.d.mts → application-r0VMb-A5.d.mts} +7 -7
  6. package/dist/{application-Rb6jeTAp.d.mts.map → application-r0VMb-A5.d.mts.map} +1 -1
  7. package/dist/{body-policy-cWfUReGC.mjs → body-policy-BK8PLFhR.mjs} +2 -2
  8. package/dist/{body-policy-cWfUReGC.mjs.map → body-policy-BK8PLFhR.mjs.map} +1 -1
  9. package/dist/{bootstrap-Cg3-PXxu.mjs → bootstrap-Cm4Tv-uh.mjs} +3 -3
  10. package/dist/{bootstrap-Cg3-PXxu.mjs.map → bootstrap-Cm4Tv-uh.mjs.map} +1 -1
  11. package/dist/{bounded-counters-BIrM6PXT.mjs → bounded-counters-DhDwQV9i.mjs} +2 -2
  12. package/dist/{bounded-counters-BIrM6PXT.mjs.map → bounded-counters-DhDwQV9i.mjs.map} +1 -1
  13. package/dist/{client-ip-BAtoGmC3.mjs → client-ip-gBC8rx8G.mjs} +2 -2
  14. package/dist/{client-ip-BAtoGmC3.mjs.map → client-ip-gBC8rx8G.mjs.map} +1 -1
  15. package/dist/config/index.mjs +2 -2
  16. package/dist/{config-DCjeCuL2.mjs → config-CufiDd1o.mjs} +3 -3
  17. package/dist/{config-DCjeCuL2.mjs.map → config-CufiDd1o.mjs.map} +1 -1
  18. package/dist/context-Vy_DYHAM.mjs +12 -0
  19. package/dist/context-Vy_DYHAM.mjs.map +1 -0
  20. package/dist/{context-errors-BULDLnr1.mjs → context-errors-BNm2NUfA.mjs} +2 -2
  21. package/dist/{context-errors-BULDLnr1.mjs.map → context-errors-BNm2NUfA.mjs.map} +1 -1
  22. package/dist/{contributor-runner-CKv5LriN.mjs → contributor-runner-BwBRcB65.mjs} +3 -3
  23. package/dist/{contributor-runner-CKv5LriN.mjs.map → contributor-runner-BwBRcB65.mjs.map} +1 -1
  24. package/dist/core/adapter.d.mts +1 -1
  25. package/dist/core/adapter.mjs +1 -1
  26. package/dist/core/app-module.mjs +1 -1
  27. package/dist/core/cache.mjs +1 -1
  28. package/dist/core/container.mjs +2 -2
  29. package/dist/core/cron.mjs +2 -2
  30. package/dist/core/decorators.mjs +2 -2
  31. package/dist/core/errors.mjs +1 -1
  32. package/dist/core/interfaces.mjs +1 -1
  33. package/dist/core/logger.mjs +1 -1
  34. package/dist/core/path.mjs +1 -1
  35. package/dist/core/plugin.d.mts +1 -1
  36. package/dist/core/plugin.mjs +1 -1
  37. package/dist/core/reactivity.mjs +2 -2
  38. package/dist/{core-Kqw_11xA.mjs → core-uD7kn0hF.mjs} +3 -3
  39. package/dist/{core-Kqw_11xA.mjs.map → core-uD7kn0hF.mjs.map} +1 -1
  40. package/dist/{csrf-w5bc-PGs.d.mts → csrf-DOAaYozG.d.mts} +17 -2
  41. package/dist/csrf-DOAaYozG.d.mts.map +1 -0
  42. package/dist/{decorate-Dji9dYab.mjs → decorate-7rlBW7PY.mjs} +3 -3
  43. package/dist/{decorate-Dji9dYab.mjs.map → decorate-7rlBW7PY.mjs.map} +1 -1
  44. package/dist/{define-adapter-DqTV48jK.mjs → define-adapter-rcNang-q.mjs} +2 -2
  45. package/dist/{define-adapter-DqTV48jK.mjs.map → define-adapter-rcNang-q.mjs.map} +1 -1
  46. package/dist/{di-hooks-CUWf3HlQ.mjs → di-hooks-CdmCtJWu.mjs} +2 -2
  47. package/dist/{di-hooks-CUWf3HlQ.mjs.map → di-hooks-CdmCtJWu.mjs.map} +1 -1
  48. package/dist/{disposables-D7NlxYjq.mjs → disposables-tpEyEZ9s.mjs} +1 -1
  49. package/dist/driver-C8ZOdZck.mjs +12 -0
  50. package/dist/driver-C8ZOdZck.mjs.map +1 -0
  51. package/dist/{error-handler-OfxVJX3s.d.mts → error-handler-vox7HLaR.d.mts} +2 -2
  52. package/dist/{error-handler-OfxVJX3s.d.mts.map → error-handler-vox7HLaR.d.mts.map} +1 -1
  53. package/dist/express-DjX6B-HB.mjs +12 -0
  54. package/dist/{express-B6jvEdCZ.mjs.map → express-DjX6B-HB.mjs.map} +1 -1
  55. package/dist/{express-lazy-BE10FhlA.mjs → express-lazy-DBLuSOgw.mjs} +3 -3
  56. package/dist/{express-lazy-BE10FhlA.mjs.map → express-lazy-DBLuSOgw.mjs.map} +1 -1
  57. package/dist/handler-CHJs4HZ3.mjs +12 -0
  58. package/dist/handler-CHJs4HZ3.mjs.map +1 -0
  59. package/dist/{host-B5w-Sz-2.mjs → host-BxUGat0u.mjs} +2 -2
  60. package/dist/{host-B5w-Sz-2.mjs.map → host-BxUGat0u.mjs.map} +1 -1
  61. package/dist/http/application.d.mts +1 -1
  62. package/dist/http/application.mjs +2 -2
  63. package/dist/http/bootstrap.d.mts +1 -1
  64. package/dist/http/bootstrap.mjs +2 -2
  65. package/dist/http/context.d.mts +1 -1
  66. package/dist/http/context.mjs +2 -2
  67. package/dist/http/middleware/allowed-hosts.mjs +2 -2
  68. package/dist/http/middleware/breach-padding.mjs +1 -1
  69. package/dist/http/middleware/cors.mjs +1 -1
  70. package/dist/http/middleware/csrf.d.mts +2 -2
  71. package/dist/http/middleware/csrf.mjs +2 -2
  72. package/dist/http/middleware/csrf.mjs.map +1 -1
  73. package/dist/http/middleware/error-handler.d.mts +1 -1
  74. package/dist/http/middleware/error-handler.mjs +2 -2
  75. package/dist/http/middleware/helmet.mjs +1 -1
  76. package/dist/http/middleware/rate-limit.mjs +2 -2
  77. package/dist/http/middleware/request-id.mjs +1 -1
  78. package/dist/http/middleware/request-logger.mjs +2 -2
  79. package/dist/http/middleware/session.d.mts +1 -1
  80. package/dist/http/middleware/session.mjs +2 -2
  81. package/dist/http/middleware/session.mjs.map +1 -1
  82. package/dist/http/middleware/spa.d.mts +1 -1
  83. package/dist/http/middleware/spa.mjs +2 -2
  84. package/dist/http/middleware/upload.d.mts +2 -2
  85. package/dist/http/middleware/upload.mjs +2 -2
  86. package/dist/http/middleware/validate.mjs +1 -1
  87. package/dist/http/middleware/views.d.mts +1 -1
  88. package/dist/http/middleware/views.mjs +2 -2
  89. package/dist/http/query/index.mjs +2 -2
  90. package/dist/http/router-builder.d.mts +1 -1
  91. package/dist/http/router-builder.mjs +2 -2
  92. package/dist/http/runtimes/express.d.mts +2 -2
  93. package/dist/http/runtimes/express.mjs +2 -2
  94. package/dist/http/runtimes/fastify.d.mts +1 -1
  95. package/dist/http/runtimes/fastify.mjs +2 -2
  96. package/dist/http/runtimes/fastify.mjs.map +1 -1
  97. package/dist/http/runtimes/h3-web.mjs +1 -1
  98. package/dist/http/runtimes/h3.d.mts +1 -1
  99. package/dist/http/runtimes/h3.mjs +2 -2
  100. package/dist/http/runtimes/h3.mjs.map +1 -1
  101. package/dist/index.d.mts +9 -9
  102. package/dist/index.mjs +3 -3
  103. package/dist/index.mjs.map +1 -1
  104. package/dist/{is-production-D0kfhCW4.mjs → is-production-WunZdVDZ.mjs} +2 -2
  105. package/dist/{is-production-D0kfhCW4.mjs.map → is-production-WunZdVDZ.mjs.map} +1 -1
  106. package/dist/{jobs-F8vpXQt7.mjs → jobs-DxkFQkZG.mjs} +3 -3
  107. package/dist/{jobs-F8vpXQt7.mjs.map → jobs-DxkFQkZG.mjs.map} +1 -1
  108. package/dist/{kv-stores-BN7c9bt9.d.mts → kv-stores-B6KIUgPS.d.mts} +3 -3
  109. package/dist/{kv-stores-BN7c9bt9.d.mts.map → kv-stores-B6KIUgPS.d.mts.map} +1 -1
  110. package/dist/{kv-stores-DxVO4y2v.mjs → kv-stores-C4YUttef.mjs} +3 -3
  111. package/dist/{kv-stores-DxVO4y2v.mjs.map → kv-stores-C4YUttef.mjs.map} +1 -1
  112. package/dist/{lazy-serve-static-BeucQAk2.mjs → lazy-serve-static-BBO3lkBi.mjs} +3 -3
  113. package/dist/{lazy-serve-static-BeucQAk2.mjs.map → lazy-serve-static-BBO3lkBi.mjs.map} +1 -1
  114. package/dist/{metadata-DeXrp8uO.mjs → metadata-s6adg8tp.mjs} +1 -1
  115. package/dist/{observers-DL7RRlLR.mjs → observers-Dn36QtbG.mjs} +2 -2
  116. package/dist/{observers-DL7RRlLR.mjs.map → observers-Dn36QtbG.mjs.map} +1 -1
  117. package/dist/{precompressed-CYkmmoRU.mjs → precompressed-Dn3S9e-q.mjs} +2 -2
  118. package/dist/{precompressed-CYkmmoRU.mjs.map → precompressed-Dn3S9e-q.mjs.map} +1 -1
  119. package/dist/{query-Coc1hIiS.mjs → query-BukuyQDW.mjs} +2 -2
  120. package/dist/{query-Coc1hIiS.mjs.map → query-BukuyQDW.mjs.map} +1 -1
  121. package/dist/{reply-Bg1gyBtE.mjs → reply-DDoHPeGF.mjs} +3 -3
  122. package/dist/{reply-Bg1gyBtE.mjs.map → reply-DDoHPeGF.mjs.map} +1 -1
  123. package/dist/{request-scope-R9FuLLnB.mjs → request-scope-BmUpBk1z.mjs} +3 -3
  124. package/dist/{request-scope-R9FuLLnB.mjs.map → request-scope-BmUpBk1z.mjs.map} +1 -1
  125. package/dist/{respond-BDd0h6bG.mjs → respond-Bo3vSCwu.mjs} +2 -2
  126. package/dist/{respond-BDd0h6bG.mjs.map → respond-Bo3vSCwu.mjs.map} +1 -1
  127. package/dist/{rolldown-runtime-OjcH9Gd_.mjs → rolldown-runtime-DHJmXo5e.mjs} +1 -1
  128. package/dist/{route-flag-ECQsPj4x.mjs → route-flag-Cwckim1c.mjs} +3 -3
  129. package/dist/{route-flag-ECQsPj4x.mjs.map → route-flag-Cwckim1c.mjs.map} +1 -1
  130. package/dist/{route-policy-0ZBRrh9x.mjs → route-policy-CycYu5mR.mjs} +2 -2
  131. package/dist/{route-policy-0ZBRrh9x.mjs.map → route-policy-CycYu5mR.mjs.map} +1 -1
  132. package/dist/{router-builder-abKMvAmP.mjs → router-builder--PLE0eDf.mjs} +3 -3
  133. package/dist/{router-builder-abKMvAmP.mjs.map → router-builder--PLE0eDf.mjs.map} +1 -1
  134. package/dist/{router-builder-DtGrng_X.d.mts → router-builder-DdfPBl09.d.mts} +2 -2
  135. package/dist/{router-builder-DtGrng_X.d.mts.map → router-builder-DdfPBl09.d.mts.map} +1 -1
  136. package/dist/runtime-OgMPp4md.mjs +12 -0
  137. package/dist/runtime-OgMPp4md.mjs.map +1 -0
  138. package/dist/{session-8uNRCplB.d.mts → session-DQG72vCf.d.mts} +7 -25
  139. package/dist/session-DQG72vCf.d.mts.map +1 -0
  140. package/dist/{settings-vuB5TedF.mjs → settings-Dn9iQ-BU.mjs} +3 -3
  141. package/dist/{settings-vuB5TedF.mjs.map → settings-Dn9iQ-BU.mjs.map} +1 -1
  142. package/dist/{token-BJJiF3_2.mjs → token-B3xWBu0S.mjs} +1 -1
  143. package/dist/{upload-C9IfY1aQ.d.mts → upload-DodgN_Ef.d.mts} +2 -2
  144. package/dist/{upload-C9IfY1aQ.d.mts.map → upload-DodgN_Ef.d.mts.map} +1 -1
  145. package/dist/{upload-config-TFTYQPaH.mjs → upload-config-BrbOOmcm.mjs} +2 -2
  146. package/dist/{upload-config-TFTYQPaH.mjs.map → upload-config-BrbOOmcm.mjs.map} +1 -1
  147. package/dist/{url-for-kZidAFyr.mjs → url-for-1SdTJZzK.mjs} +3 -3
  148. package/dist/{url-for-kZidAFyr.mjs.map → url-for-1SdTJZzK.mjs.map} +1 -1
  149. package/dist/{view-renderer-CSPD7F-f.mjs → view-renderer-Caqy9XY5.mjs} +3 -3
  150. package/dist/{view-renderer-CSPD7F-f.mjs.map → view-renderer-Caqy9XY5.mjs.map} +1 -1
  151. package/dist/{web-crypto-Q0WFs8ua.mjs → web-crypto-DnhQ8LCv.mjs} +2 -2
  152. package/dist/{web-crypto-Q0WFs8ua.mjs.map → web-crypto-DnhQ8LCv.mjs.map} +1 -1
  153. package/dist/web.d.mts +2 -2
  154. package/dist/web.mjs +2 -2
  155. package/dist/web.mjs.map +1 -1
  156. package/package.json +1 -1
  157. package/dist/adapter-DiJfCKXU.d.mts.map +0 -1
  158. package/dist/context-Cc6k0gsM.mjs +0 -12
  159. package/dist/context-Cc6k0gsM.mjs.map +0 -1
  160. package/dist/csrf-w5bc-PGs.d.mts.map +0 -1
  161. package/dist/express-B6jvEdCZ.mjs +0 -12
  162. package/dist/handler-BpMOjmfq.mjs +0 -12
  163. package/dist/handler-BpMOjmfq.mjs.map +0 -1
  164. package/dist/session-8uNRCplB.d.mts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"session.mjs","names":[],"sources":["../../../src/http/middleware/session.ts"],"sourcesContent":["import { parseCookieHeader, replaceCookie, setCookie } from './respond'\nimport {\n createCipheriv,\n createDecipheriv,\n createHmac,\n hkdfSync,\n randomBytes,\n randomUUID,\n timingSafeEqual,\n} from 'node:crypto'\nimport { createLogger } from '../../core/logger'\nimport type {\n ConnectRequest as Request,\n ConnectResponse as Response,\n ConnectNext as NextFunction,\n} from '../connect'\n\nimport { registerDisposable } from '../../core/disposables'\nimport { isProduction } from '../../core/is-production'\n\n/**\n * What a session holds. Augment it to type your keys — undeclared keys stay\n * readable as `unknown`:\n *\n * ```ts\n * declare module '@forinda/kickjs' {\n * interface SessionData { userId?: string; cart?: string[] }\n * }\n * ```\n */\nexport interface SessionData {\n [key: string]: unknown\n}\n\nexport interface SessionStore {\n get(sid: string): Promise<SessionData | null>\n set(sid: string, data: SessionData, maxAge: number): Promise<void>\n destroy(sid: string): Promise<void>\n touch?(sid: string, maxAge: number): Promise<void>\n}\n\nexport interface Session {\n id: string\n data: SessionData\n regenerate(): Promise<void>\n destroy(): Promise<void>\n save(): Promise<void>\n}\n\nexport interface SessionOptions {\n /**\n * Secret that signs the session cookie — or, with `store: 'cookie'`,\n * encrypts it (required).\n *\n * Pass a list to rotate without logging everyone out: the first secret signs\n * new cookies, every secret is accepted, and a cookie made with an older one\n * is re-issued with the first. Drop the old secret once sessions have moved\n * over (after `maxAge`).\n *\n * ```ts\n * session({ secret: [process.env.SESSION_SECRET!, process.env.SESSION_SECRET_OLD!] })\n * ```\n */\n secret: string | string[]\n /** Cookie name (default: 'kick.sid') */\n cookieName?: string\n /** Session max age in milliseconds (default: 86400000 = 24h) */\n maxAge?: number\n /** Reset maxAge on every response (default: false) */\n rolling?: boolean\n /** Save new sessions that have not been modified (default: true) */\n saveUninitialized?: boolean\n /** Cookie options */\n cookie?: {\n httpOnly?: boolean\n secure?: boolean\n sameSite?: 'strict' | 'lax' | 'none'\n path?: string\n domain?: string\n }\n /**\n * Where session data lives. Default: in memory, in this process.\n *\n * `'cookie'` keeps it in the session cookie itself, encrypted with\n * AES-256-GCM under a key derived from `secret`: every instance reads the\n * same session with nothing shared between them — serverless functions,\n * several containers. The data has to fit a cookie (about 4 KB).\n *\n * Or pass a store shared between instances (`KvSessionStore`, Redis).\n */\n store?: SessionStore | 'cookie'\n}\n\n// ── In-Memory Store ───────────────────────────────────────────────────\n\n// ponytail: fixed cap for the single-instance default; a shared store\n// (KvSessionStore, Redis) is the answer for more.\nconst MAX_SESSIONS = 10_000\n\n/** @internal Exported for tests. */\nexport class MemoryStore implements SessionStore {\n private readonly sessions = new Map<string, { data: SessionData; expires: number }>()\n /** Sessions with no data, oldest first: evicted before any that hold some. */\n private readonly empty = new Set<string>()\n private readonly cleanupInterval: ReturnType<typeof setInterval>\n\n constructor() {\n // Purge expired sessions every 60 seconds\n this.cleanupInterval = setInterval(() => this.purge(), 60_000)\n this.cleanupInterval.unref()\n // Symmetric teardown: Application.shutdown() drains the disposables\n // registry — without this, every in-process app re-create (tests, HMR)\n // leaked one live interval + its session Map.\n registerDisposable(() => this.dispose())\n }\n\n /** Clear the cleanup interval and drop all sessions. */\n dispose(): void {\n clearInterval(this.cleanupInterval)\n this.sessions.clear()\n this.empty.clear()\n }\n\n async get(sid: string): Promise<SessionData | null> {\n const entry = this.sessions.get(sid)\n if (!entry) return null\n if (Date.now() > entry.expires) {\n this.sessions.delete(sid)\n this.empty.delete(sid)\n return null\n }\n return entry.data\n }\n\n async set(sid: string, data: SessionData, maxAge: number): Promise<void> {\n // Deleted first so the map stays in last-written order, oldest at the front.\n this.sessions.delete(sid)\n this.sessions.set(sid, { data, expires: Date.now() + maxAge })\n this.empty.delete(sid)\n if (Object.keys(data).length === 0) this.empty.add(sid)\n // A session is created for every visitor without a cookie, so a client\n // can make as many as it sends requests. Past the cap, an empty session\n // goes first — a flood of cookieless requests makes only empty ones, so\n // it can't push out sessions that hold a login; only when none is empty\n // does the least recently written go.\n while (this.sessions.size > MAX_SESSIONS) {\n const victim = this.empty.values().next().value ?? this.sessions.keys().next().value!\n this.sessions.delete(victim)\n this.empty.delete(victim)\n }\n }\n\n async destroy(sid: string): Promise<void> {\n this.sessions.delete(sid)\n this.empty.delete(sid)\n }\n\n async touch(sid: string, maxAge: number): Promise<void> {\n const entry = this.sessions.get(sid)\n if (entry) {\n entry.expires = Date.now() + maxAge\n this.sessions.delete(sid)\n this.sessions.set(sid, entry)\n }\n }\n\n private purge() {\n const now = Date.now()\n for (const [sid, entry] of this.sessions) {\n if (now > entry.expires) {\n this.sessions.delete(sid)\n this.empty.delete(sid)\n }\n }\n }\n}\n\n// ── Cookie Signing ────────────────────────────────────────────────────\n\n/** `secret` as a non-empty list, newest first. */\nfunction secretList(secret: string | string[]): string[] {\n const list = Array.isArray(secret) ? secret : [secret]\n if (list.length === 0 || list.some((s) => typeof s !== 'string' || s.length === 0)) {\n throw new Error('session(): `secret` must be a non-empty string or list of strings')\n }\n return list\n}\n\nfunction sign(value: string, secret: string): string {\n const signature = createHmac('sha256', secret).update(value).digest('base64url')\n return `s:${value}.${signature}`\n}\n\n/**\n * The signed value, and whether it was signed with an older secret than the\n * first (so the caller re-issues it); false when no secret verifies it.\n */\nfunction unsign(signed: string, secrets: string[]): { value: string; stale: boolean } | false {\n if (!signed.startsWith('s:')) return false\n const raw = signed.slice(2)\n const dotIndex = raw.lastIndexOf('.')\n if (dotIndex === -1) return false\n\n const value = raw.slice(0, dotIndex)\n const provided = Buffer.from(raw.slice(dotIndex + 1))\n\n for (const [index, secret] of secrets.entries()) {\n const expected = Buffer.from(createHmac('sha256', secret).update(value).digest('base64url'))\n if (provided.length === expected.length && timingSafeEqual(provided, expected)) {\n return { value, stale: index > 0 }\n }\n }\n return false\n}\n\n// ── Middleware Factory ────────────────────────────────────────────────\n\n/**\n * Session management middleware.\n *\n * Attaches a `req.session` object with `id`, `data`, `regenerate()`,\n * `destroy()`, and `save()` methods. Session IDs are signed with\n * HMAC-SHA256 to prevent cookie tampering.\n *\n * Reads the session cookie from `req.cookies` when an upstream cookie\n * parser is present; otherwise parses `req.headers.cookie` directly, so\n * no cookie parser is required upstream.\n *\n * @example\n * ```ts\n * import { session } from '@forinda/kickjs'\n *\n * bootstrap({\n * modules,\n * middlewares: [\n * session({ secret: process.env.SESSION_SECRET! }),\n * // ... other middleware\n * ],\n * })\n * ```\n */\nexport function session(options: SessionOptions) {\n if (options.store === 'cookie') return cookieSession(options)\n const {\n cookieName = 'kick.sid',\n maxAge = 86_400_000,\n rolling = false,\n saveUninitialized = true,\n cookie: cookieOpts = {},\n } = options\n const secrets = secretList(options.secret)\n const secret = secrets[0]\n const store = (options.store as SessionStore | undefined) ?? new MemoryStore()\n\n const cookieDefaults = {\n httpOnly: cookieOpts.httpOnly ?? true,\n secure: cookieOpts.secure ?? isProduction(),\n sameSite: cookieOpts.sameSite ?? ('lax' as const),\n path: cookieOpts.path ?? '/',\n ...(cookieOpts.domain ? { domain: cookieOpts.domain } : {}),\n maxAge,\n }\n\n return async (req: Request, res: Response, next: NextFunction) => {\n let cookies = (req as any).cookies as Record<string, string> | undefined\n if (!cookies) {\n const header = req.headers.cookie\n cookies = header ? parseCookieHeader(header) : {}\n }\n const signedCookie = cookies[cookieName]\n let sid: string | false = false\n let sessionData: SessionData | null = null\n let isNew = false\n let staleSignature = false\n\n // Attempt to recover existing session\n if (signedCookie) {\n const unsigned = unsign(signedCookie, secrets)\n if (unsigned) {\n sid = unsigned.value\n staleSignature = unsigned.stale\n sessionData = await store.get(sid)\n }\n }\n\n // Create new session if none found\n if (!sid || !sessionData) {\n sid = randomUUID()\n sessionData = {}\n isNew = true\n }\n\n let currentSid = sid\n let currentData = { ...sessionData }\n let destroyed = false\n\n const sessionObj: Session = {\n get id() {\n return currentSid\n },\n data: currentData,\n\n async regenerate() {\n await store.destroy(currentSid)\n currentSid = randomUUID()\n currentData = {}\n sessionObj.data = currentData\n await store.set(currentSid, currentData, maxAge)\n setCookie(res, cookieName, sign(currentSid, secret), cookieDefaults)\n },\n\n async destroy() {\n await store.destroy(currentSid)\n destroyed = true\n currentData = {}\n sessionObj.data = currentData\n // Expire the cookie the same way it was set — `res.clearCookie` is\n // Express-only and threw under Fastify and h3.\n setCookie(res, cookieName, '', { ...cookieDefaults, maxAge: 0, expires: new Date(0) })\n },\n\n async save() {\n if (!destroyed) {\n await store.set(currentSid, currentData, maxAge)\n }\n },\n }\n\n ;(req as any).session = sessionObj\n\n // Set cookie for new sessions\n if (isNew) {\n setCookie(res, cookieName, sign(currentSid, secret), cookieDefaults)\n }\n\n // Auto-save on response finish\n res.on('finish', async () => {\n if (destroyed) return\n if (isNew && !saveUninitialized && Object.keys(currentData).length === 0) return\n\n await store.set(currentSid, currentData, maxAge)\n\n if (rolling && !isNew) {\n if (store.touch) {\n await store.touch(currentSid, maxAge)\n }\n }\n })\n\n // Rolling refreshes the cookie on every response; a cookie signed with an\n // older secret is re-signed with the current one.\n if (!isNew && (rolling || staleSignature)) {\n setCookie(res, cookieName, sign(currentSid, secret), cookieDefaults)\n }\n\n next()\n }\n}\n\n// ── Cookie store ──────────────────────────────────────────────────────\n\nconst cookieLog = createLogger('Session')\n\n/** Browsers drop a cookie larger than 4096 bytes, name and attributes included. */\nconst COOKIE_LIMIT = 4000\n\ninterface CookiePayload {\n /** Session id. */\n i: string\n d: SessionData\n /** Expiry, ms since epoch. */\n e: number\n}\n\n/**\n * AES-256-GCM, with the cookie name as associated data: `v1.<iv|tag|ciphertext>`.\n * Seals with the first secret's key; opens with any of them.\n */\nfunction sealer(secrets: string[], cookieName: string) {\n const keys = secrets.map((secret) =>\n Buffer.from(hkdfSync('sha256', secret, 'kick.session', 'cookie-store-v1', 32)),\n )\n const key = keys[0]\n const aad = Buffer.from(cookieName)\n return {\n seal(payload: CookiePayload): string {\n const iv = randomBytes(12)\n const cipher = createCipheriv('aes-256-gcm', key, iv).setAAD(aad)\n const body = Buffer.concat([cipher.update(JSON.stringify(payload), 'utf8'), cipher.final()])\n return `v1.${Buffer.concat([iv, cipher.getAuthTag(), body]).toString('base64url')}`\n },\n /**\n * The payload and whether an older secret's key opened it, or null for\n * anything forged, altered, expired or malformed.\n */\n open(value: string): { payload: CookiePayload; stale: boolean } | null {\n if (!value.startsWith('v1.')) return null\n let raw: Buffer\n try {\n raw = Buffer.from(value.slice(3), 'base64url')\n } catch {\n return null\n }\n if (raw.length < 29) return null\n for (const [index, k] of keys.entries()) {\n try {\n const decipher = createDecipheriv('aes-256-gcm', k, raw.subarray(0, 12))\n .setAAD(aad)\n .setAuthTag(raw.subarray(12, 28))\n const json = Buffer.concat([decipher.update(raw.subarray(28)), decipher.final()])\n const payload = JSON.parse(json.toString('utf8')) as CookiePayload\n if (typeof payload?.i !== 'string' || typeof payload.e !== 'number') return null\n if (!payload.d || typeof payload.d !== 'object') return null\n return payload.e > Date.now() ? { payload, stale: index > 0 } : null\n } catch {\n // Not this key (the auth tag fails) — try the next.\n }\n }\n return null\n },\n }\n}\n\ntype HeaderWriter = (...args: unknown[]) => unknown\n\n/**\n * `session({ store: 'cookie' })`. The cookie is written as late as possible —\n * just before the response's headers go out — so every change made while\n * handling the request is in it, nested ones included. `save()` writes it\n * straight away, for code that redirects right after.\n */\nfunction cookieSession(options: SessionOptions) {\n const {\n cookieName = 'kick.sid',\n maxAge = 86_400_000,\n rolling = false,\n saveUninitialized = true,\n cookie: cookieOpts = {},\n } = options\n const { seal, open } = sealer(secretList(options.secret), cookieName)\n const cookieDefaults = {\n httpOnly: cookieOpts.httpOnly ?? true,\n secure: cookieOpts.secure ?? isProduction(),\n sameSite: cookieOpts.sameSite ?? ('lax' as const),\n path: cookieOpts.path ?? '/',\n ...(cookieOpts.domain ? { domain: cookieOpts.domain } : {}),\n }\n let warnedSize = false\n\n return (req: Request, res: Response, next: NextFunction) => {\n let cookies = (req as any).cookies as Record<string, string> | undefined\n if (!cookies) {\n const header = req.headers.cookie\n cookies = header ? parseCookieHeader(header) : {}\n }\n const opened = cookies[cookieName] ? open(cookies[cookieName]) : null\n const existing = opened?.payload ?? null\n const isNew = !existing\n\n let id = existing?.i ?? randomUUID()\n let destroyed = false\n // What the browser already holds, to skip rewriting an unchanged cookie.\n // A cookie sealed with an older secret counts as nothing held, so it is\n // rewritten with the current one.\n let written = existing && !opened?.stale ? JSON.stringify(existing.d) : undefined\n\n const write = (force = false) => {\n if (res.headersSent) return\n if (destroyed) {\n replaceCookie(res, cookieName, '', { ...cookieDefaults, maxAge: 0, expires: new Date(0) })\n return\n }\n const json = JSON.stringify(sessionObj.data)\n // Unchanged: leave the browser's copy, unless `rolling` renews it.\n if (json === written && !force && !(rolling && !isNew)) return\n // A new, empty session gets a cookie only with saveUninitialized.\n if (written === undefined && json === '{}' && !saveUninitialized && !force) return\n const value = seal({ i: id, d: sessionObj.data, e: Date.now() + maxAge })\n if (value.length + cookieName.length > COOKIE_LIMIT && !warnedSize) {\n warnedSize = true\n cookieLog.warn(\n `session cookie is ${value.length} bytes; browsers drop cookies over 4 KB, ` +\n 'so this session will not be kept. Store less in it, or use a shared store.',\n )\n }\n replaceCookie(res, cookieName, value, { ...cookieDefaults, maxAge })\n written = json\n }\n\n // Just before the headers go out, on whichever call sends them first —\n // Node responses go through writeHead; the web driver's buffered end()\n // does not.\n for (const method of ['writeHead', 'flushHeaders', 'write', 'end'] as const) {\n const original = (res as unknown as Record<string, HeaderWriter | undefined>)[method]\n if (typeof original !== 'function') continue\n ;(res as unknown as Record<string, HeaderWriter>)[method] = function (\n this: unknown,\n ...args: unknown[]\n ) {\n write()\n return original.apply(this, args)\n }\n }\n\n // h3 called through fetch hands middleware a stand-in response whose\n // headers join the route's response after `finish` — the last chance there.\n // On a Node response `finish` comes after the headers, so this is a no-op.\n ;(res as unknown as { on?: (event: string, fn: () => void) => unknown }).on?.('finish', () =>\n write(),\n )\n\n const sessionObj: Session = {\n get id() {\n return id\n },\n data: existing ? { ...existing.d } : {},\n async regenerate() {\n id = randomUUID()\n sessionObj.data = {}\n written = undefined\n write(true)\n },\n async destroy() {\n destroyed = true\n sessionObj.data = {}\n write()\n },\n async save() {\n write()\n },\n }\n ;(req as any).session = sessionObj\n next()\n }\n}\n"],"mappings":";;;;;;;;;;yYAoGA,IAAa,YAAb,KAAiD,CAC/C,yBAA4B,IAAI,IAEhC,sBAAyB,IAAI,IAC7B,gBAEA,aAAc,CAEZ,KAAK,gBAAkB,gBAAkB,KAAK,MAAM,EAAG,GAAM,EAC7D,KAAK,gBAAgB,MAAM,EAI3B,uBAAyB,KAAK,QAAQ,CAAC,CACzC,CAGA,SAAgB,CACd,cAAc,KAAK,eAAe,EAClC,KAAK,SAAS,MAAM,EACpB,KAAK,MAAM,MAAM,CACnB,CAEA,MAAM,IAAI,IAA0C,CAClD,IAAM,MAAQ,KAAK,SAAS,IAAI,GAAG,EAOnC,OANK,MACD,KAAK,IAAI,EAAI,MAAM,SACrB,KAAK,SAAS,OAAO,GAAG,EACxB,KAAK,MAAM,OAAO,GAAG,EACd,MAEF,MAAM,KANM,IAOrB,CAEA,MAAM,IAAI,IAAa,KAAmB,OAA+B,CAWvE,IATA,KAAK,SAAS,OAAO,GAAG,EACxB,KAAK,SAAS,IAAI,IAAK,CAAE,KAAM,QAAS,KAAK,IAAI,EAAI,MAAO,CAAC,EAC7D,KAAK,MAAM,OAAO,GAA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ACR,qBAAqB,MAAM,OAAO,oHAEpC,GAEF,cAAc,IAAK,WAAY,MAAO,CAAE,GAAG,eAAgB,MAAO,CAAC,EACnE,QAAU,IACZ,EAKA,IAAK,IAAM,SAAU,CAAC,YAAa,eAAgB,QAAS,KAAK,EAAY,CAC3E,IAAM,SAAY,IAA4D,QAC1E,OAAO,UAAa,aACvB,IAAiD,QAAU,SAE1D,GAAG,KACH,CAEA,OADA,MAAM,EACC,SAAS,MAAM,KAAM,IAAI,CAClC,EACF,CAKC,IAAwE,KAAK,aAC5E,MAAM,CACR,EAEA,IAAM,WAAsB,CAC1B,IAAI,IAAK,CACP,OAAO,EACT,EACA,KAAM,SAAW,CAAE,GAAG,SAAS,CAAE,EAAI,CAAC,EACtC,MAAM,YAAa,CACjB,GAAK,WAAW,EAChB,WAAW,KAAO,CAAC,EACnB,QAAU,IAAA,GACV,MAAM,EAAI,CACZ,EACA,MAAM,SAAU,CACd,UAAY,GACZ,WAAW,KAAO,CAAC,EACnB,MAAM,CACR,EACA,MAAM,MAAO,CACX,MAAM,CACR,CACF,EACC,IAAa,QAAU,WACxB,KAAK,CACP,CACF"}
1
+ {"version":3,"file":"session.mjs","names":[],"sources":["../../../src/http/middleware/session.ts"],"sourcesContent":["import { parseCookieHeader, replaceCookie, setCookie } from './respond'\nimport {\n createCipheriv,\n createDecipheriv,\n createHmac,\n hkdfSync,\n randomBytes,\n randomUUID,\n timingSafeEqual,\n} from 'node:crypto'\nimport { createLogger } from '../../core/logger'\nimport { WebResponseDriver } from '../web/driver'\nimport type {\n ConnectRequest as Request,\n ConnectResponse as Response,\n ConnectNext as NextFunction,\n} from '../connect'\n\nimport { registerDisposable } from '../../core/disposables'\nimport { isProduction } from '../../core/is-production'\n\n/**\n * What a session holds. Augment it to type your keys — undeclared keys stay\n * readable as `unknown`:\n *\n * ```ts\n * declare module '@forinda/kickjs' {\n * interface SessionData { userId?: string; cart?: string[] }\n * }\n * ```\n */\nexport interface SessionData {\n [key: string]: unknown\n}\n\nexport interface SessionStore {\n get(sid: string): Promise<SessionData | null>\n set(sid: string, data: SessionData, maxAge: number): Promise<void>\n destroy(sid: string): Promise<void>\n touch?(sid: string, maxAge: number): Promise<void>\n}\n\nexport interface Session {\n id: string\n data: SessionData\n regenerate(): Promise<void>\n destroy(): Promise<void>\n save(): Promise<void>\n}\n\nexport interface SessionOptions {\n /**\n * Secret that signs the session cookie — or, with `store: 'cookie'`,\n * encrypts it (required).\n *\n * Pass a list to rotate without logging everyone out: the first secret signs\n * new cookies, every secret is accepted, and a cookie made with an older one\n * is re-issued with the first. Drop the old secret once sessions have moved\n * over (after `maxAge`).\n *\n * ```ts\n * session({ secret: [process.env.SESSION_SECRET!, process.env.SESSION_SECRET_OLD!] })\n * ```\n */\n secret: string | string[]\n /** Cookie name (default: 'kick.sid') */\n cookieName?: string\n /** Session max age in milliseconds (default: 86400000 = 24h) */\n maxAge?: number\n /** Reset maxAge on every response (default: false) */\n rolling?: boolean\n /** Save new sessions that have not been modified (default: true) */\n saveUninitialized?: boolean\n /**\n * How long a response waits for the store to save the session before it\n * goes out anyway, in ms (default 5000). A stalled store would otherwise\n * hold every response; past this, the request after it may not see the save.\n */\n saveTimeout?: number\n /** Cookie options */\n cookie?: {\n httpOnly?: boolean\n secure?: boolean\n sameSite?: 'strict' | 'lax' | 'none'\n path?: string\n domain?: string\n }\n /**\n * Where session data lives. Default: in memory, in this process.\n *\n * `'cookie'` keeps it in the session cookie itself, encrypted with\n * AES-256-GCM under a key derived from `secret`: every instance reads the\n * same session with nothing shared between them — serverless functions,\n * several containers. The data has to fit a cookie (about 4 KB).\n *\n * Or pass a store shared between instances (`KvSessionStore`, Redis).\n */\n store?: SessionStore | 'cookie'\n}\n\n// ── In-Memory Store ───────────────────────────────────────────────────\n\n// ponytail: fixed cap for the single-instance default; a shared store\n// (KvSessionStore, Redis) is the answer for more.\nconst MAX_SESSIONS = 10_000\n\n/** @internal Exported for tests. */\nexport class MemoryStore implements SessionStore {\n private readonly sessions = new Map<string, { data: SessionData; expires: number }>()\n /** Sessions with no data, oldest first: evicted before any that hold some. */\n private readonly empty = new Set<string>()\n private readonly cleanupInterval: ReturnType<typeof setInterval>\n\n constructor() {\n // Purge expired sessions every 60 seconds\n this.cleanupInterval = setInterval(() => this.purge(), 60_000)\n this.cleanupInterval.unref()\n // Symmetric teardown: Application.shutdown() drains the disposables\n // registry — without this, every in-process app re-create (tests, HMR)\n // leaked one live interval + its session Map.\n registerDisposable(() => this.dispose())\n }\n\n /** Clear the cleanup interval and drop all sessions. */\n dispose(): void {\n clearInterval(this.cleanupInterval)\n this.sessions.clear()\n this.empty.clear()\n }\n\n async get(sid: string): Promise<SessionData | null> {\n const entry = this.sessions.get(sid)\n if (!entry) return null\n if (Date.now() > entry.expires) {\n this.sessions.delete(sid)\n this.empty.delete(sid)\n return null\n }\n return entry.data\n }\n\n async set(sid: string, data: SessionData, maxAge: number): Promise<void> {\n // Deleted first so the map stays in last-written order, oldest at the front.\n this.sessions.delete(sid)\n this.sessions.set(sid, { data, expires: Date.now() + maxAge })\n this.empty.delete(sid)\n if (Object.keys(data).length === 0) this.empty.add(sid)\n // A session is created for every visitor without a cookie, so a client\n // can make as many as it sends requests. Past the cap, an empty session\n // goes first — a flood of cookieless requests makes only empty ones, so\n // it can't push out sessions that hold a login; only when none is empty\n // does the least recently written go.\n while (this.sessions.size > MAX_SESSIONS) {\n const victim = this.empty.values().next().value ?? this.sessions.keys().next().value!\n this.sessions.delete(victim)\n this.empty.delete(victim)\n }\n }\n\n async destroy(sid: string): Promise<void> {\n this.sessions.delete(sid)\n this.empty.delete(sid)\n }\n\n async touch(sid: string, maxAge: number): Promise<void> {\n const entry = this.sessions.get(sid)\n if (entry) {\n entry.expires = Date.now() + maxAge\n this.sessions.delete(sid)\n this.sessions.set(sid, entry)\n }\n }\n\n private purge() {\n const now = Date.now()\n for (const [sid, entry] of this.sessions) {\n if (now > entry.expires) {\n this.sessions.delete(sid)\n this.empty.delete(sid)\n }\n }\n }\n}\n\n// ── Cookie Signing ────────────────────────────────────────────────────\n\n/** `secret` as a non-empty list, newest first. */\nfunction secretList(secret: string | string[]): string[] {\n const list = Array.isArray(secret) ? secret : [secret]\n if (list.length === 0 || list.some((s) => typeof s !== 'string' || s.length === 0)) {\n throw new Error('session(): `secret` must be a non-empty string or list of strings')\n }\n return list\n}\n\nfunction sign(value: string, secret: string): string {\n const signature = createHmac('sha256', secret).update(value).digest('base64url')\n return `s:${value}.${signature}`\n}\n\n/**\n * The signed value, and whether it was signed with an older secret than the\n * first (so the caller re-issues it); false when no secret verifies it.\n */\nfunction unsign(signed: string, secrets: string[]): { value: string; stale: boolean } | false {\n if (!signed.startsWith('s:')) return false\n const raw = signed.slice(2)\n const dotIndex = raw.lastIndexOf('.')\n if (dotIndex === -1) return false\n\n const value = raw.slice(0, dotIndex)\n const provided = Buffer.from(raw.slice(dotIndex + 1))\n\n for (const [index, secret] of secrets.entries()) {\n const expected = Buffer.from(createHmac('sha256', secret).update(value).digest('base64url'))\n if (provided.length === expected.length && timingSafeEqual(provided, expected)) {\n return { value, stale: index > 0 }\n }\n }\n return false\n}\n\n// ── Middleware Factory ────────────────────────────────────────────────\n\n/**\n * Session management middleware.\n *\n * Attaches a `req.session` object with `id`, `data`, `regenerate()`,\n * `destroy()`, and `save()` methods. Session IDs are signed with\n * HMAC-SHA256 to prevent cookie tampering.\n *\n * Reads the session cookie from `req.cookies` when an upstream cookie\n * parser is present; otherwise parses `req.headers.cookie` directly, so\n * no cookie parser is required upstream.\n *\n * @example\n * ```ts\n * import { session } from '@forinda/kickjs'\n *\n * bootstrap({\n * modules,\n * middlewares: [\n * session({ secret: process.env.SESSION_SECRET! }),\n * // ... other middleware\n * ],\n * })\n * ```\n */\nconst storeLog = createLogger('Session')\n\nexport function session(options: SessionOptions) {\n if (options.store === 'cookie') return cookieSession(options)\n const {\n cookieName = 'kick.sid',\n maxAge = 86_400_000,\n rolling = false,\n saveUninitialized = true,\n saveTimeout = 5000,\n cookie: cookieOpts = {},\n } = options\n const secrets = secretList(options.secret)\n const secret = secrets[0]\n const store = (options.store as SessionStore | undefined) ?? new MemoryStore()\n\n const cookieDefaults = {\n httpOnly: cookieOpts.httpOnly ?? true,\n secure: cookieOpts.secure ?? isProduction(),\n sameSite: cookieOpts.sameSite ?? ('lax' as const),\n path: cookieOpts.path ?? '/',\n ...(cookieOpts.domain ? { domain: cookieOpts.domain } : {}),\n maxAge,\n }\n\n return async (req: Request, res: Response, next: NextFunction) => {\n let cookies = (req as any).cookies as Record<string, string> | undefined\n if (!cookies) {\n const header = req.headers.cookie\n cookies = header ? parseCookieHeader(header) : {}\n }\n const signedCookie = cookies[cookieName]\n let sid: string | false = false\n let sessionData: SessionData | null = null\n let isNew = false\n let staleSignature = false\n\n // Attempt to recover existing session\n if (signedCookie) {\n const unsigned = unsign(signedCookie, secrets)\n if (unsigned) {\n sid = unsigned.value\n staleSignature = unsigned.stale\n sessionData = await store.get(sid)\n }\n }\n\n // Create new session if none found\n if (!sid || !sessionData) {\n sid = randomUUID()\n sessionData = {}\n isNew = true\n }\n\n let currentSid = sid\n let currentData = { ...sessionData }\n let destroyed = false\n\n const sessionObj: Session = {\n get id() {\n return currentSid\n },\n data: currentData,\n\n async regenerate() {\n await store.destroy(currentSid)\n currentSid = randomUUID()\n currentData = {}\n sessionObj.data = currentData\n await store.set(currentSid, currentData, maxAge)\n setCookie(res, cookieName, sign(currentSid, secret), cookieDefaults)\n },\n\n async destroy() {\n await store.destroy(currentSid)\n destroyed = true\n currentData = {}\n sessionObj.data = currentData\n // Expire the cookie the same way it was set — `res.clearCookie` is\n // Express-only and threw under Fastify and h3.\n setCookie(res, cookieName, '', { ...cookieDefaults, maxAge: 0, expires: new Date(0) })\n },\n\n async save() {\n if (!destroyed) {\n await store.set(currentSid, currentData, maxAge)\n }\n },\n }\n\n ;(req as any).session = sessionObj\n\n // Set cookie for new sessions\n if (isNew) {\n setCookie(res, cookieName, sign(currentSid, secret), cookieDefaults)\n }\n\n // Saved once, at the end of the request.\n let persisted: Promise<void> | undefined\n const persist = () =>\n (persisted ??= (async () => {\n if (destroyed) return\n if (isNew && !saveUninitialized && Object.keys(currentData).length === 0) return\n await store.set(currentSid, currentData, maxAge)\n if (rolling && !isNew && store.touch) await store.touch(currentSid, maxAge)\n })())\n\n // Before the response goes out, not after: the redirect after a form post\n // comes straight back and must see what this request wrote. The response\n // ends once the store has it (a Redis write, say), as express-session does.\n // The fetch drivers build their Response in end(), so they keep the\n // `finish` save below.\n if (!(res instanceof WebResponseDriver)) {\n const end = res.end as (...args: unknown[]) => unknown\n ;(res as unknown as { end: (...args: unknown[]) => unknown }).end = function (\n this: unknown,\n ...args: unknown[]\n ) {\n let sent = false\n const send = () => {\n if (sent) return\n sent = true\n clearTimeout(timer)\n end.apply(this, args)\n }\n const timer = setTimeout(() => {\n storeLog.error(`Session save took over ${saveTimeout}ms; sending the response anyway`)\n send()\n }, saveTimeout)\n persist().then(send, (err: unknown) => {\n storeLog.error(err, 'Session save failed; sending the response anyway')\n send()\n })\n return this\n }\n }\n res.on('finish', () => {\n // Already logged by end() on a Node response; the fetch drivers only save here.\n persist().catch((err: unknown) => {\n if (res instanceof WebResponseDriver)\n storeLog.error(err, 'Session save failed after the response was sent')\n })\n })\n\n // Rolling refreshes the cookie on every response; a cookie signed with an\n // older secret is re-signed with the current one.\n if (!isNew && (rolling || staleSignature)) {\n setCookie(res, cookieName, sign(currentSid, secret), cookieDefaults)\n }\n\n next()\n }\n}\n\n// ── Cookie store ──────────────────────────────────────────────────────\n\nconst cookieLog = createLogger('Session')\n\n/** Browsers drop a cookie larger than 4096 bytes, name and attributes included. */\nconst COOKIE_LIMIT = 4000\n\ninterface CookiePayload {\n /** Session id. */\n i: string\n d: SessionData\n /** Expiry, ms since epoch. */\n e: number\n}\n\n/**\n * AES-256-GCM, with the cookie name as associated data: `v1.<iv|tag|ciphertext>`.\n * Seals with the first secret's key; opens with any of them.\n */\nfunction sealer(secrets: string[], cookieName: string) {\n const keys = secrets.map((secret) =>\n Buffer.from(hkdfSync('sha256', secret, 'kick.session', 'cookie-store-v1', 32)),\n )\n const key = keys[0]\n const aad = Buffer.from(cookieName)\n return {\n seal(payload: CookiePayload): string {\n const iv = randomBytes(12)\n const cipher = createCipheriv('aes-256-gcm', key, iv).setAAD(aad)\n const body = Buffer.concat([cipher.update(JSON.stringify(payload), 'utf8'), cipher.final()])\n return `v1.${Buffer.concat([iv, cipher.getAuthTag(), body]).toString('base64url')}`\n },\n /**\n * The payload and whether an older secret's key opened it, or null for\n * anything forged, altered, expired or malformed.\n */\n open(value: string): { payload: CookiePayload; stale: boolean } | null {\n if (!value.startsWith('v1.')) return null\n let raw: Buffer\n try {\n raw = Buffer.from(value.slice(3), 'base64url')\n } catch {\n return null\n }\n if (raw.length < 29) return null\n for (const [index, k] of keys.entries()) {\n try {\n const decipher = createDecipheriv('aes-256-gcm', k, raw.subarray(0, 12))\n .setAAD(aad)\n .setAuthTag(raw.subarray(12, 28))\n const json = Buffer.concat([decipher.update(raw.subarray(28)), decipher.final()])\n const payload = JSON.parse(json.toString('utf8')) as CookiePayload\n if (typeof payload?.i !== 'string' || typeof payload.e !== 'number') return null\n if (!payload.d || typeof payload.d !== 'object') return null\n return payload.e > Date.now() ? { payload, stale: index > 0 } : null\n } catch {\n // Not this key (the auth tag fails) — try the next.\n }\n }\n return null\n },\n }\n}\n\ntype HeaderWriter = (...args: unknown[]) => unknown\n\n/**\n * `session({ store: 'cookie' })`. The cookie is written as late as possible —\n * just before the response's headers go out — so every change made while\n * handling the request is in it, nested ones included. `save()` writes it\n * straight away, for code that redirects right after.\n */\nfunction cookieSession(options: SessionOptions) {\n const {\n cookieName = 'kick.sid',\n maxAge = 86_400_000,\n rolling = false,\n saveUninitialized = true,\n cookie: cookieOpts = {},\n } = options\n const { seal, open } = sealer(secretList(options.secret), cookieName)\n const cookieDefaults = {\n httpOnly: cookieOpts.httpOnly ?? true,\n secure: cookieOpts.secure ?? isProduction(),\n sameSite: cookieOpts.sameSite ?? ('lax' as const),\n path: cookieOpts.path ?? '/',\n ...(cookieOpts.domain ? { domain: cookieOpts.domain } : {}),\n }\n let warnedSize = false\n\n return (req: Request, res: Response, next: NextFunction) => {\n let cookies = (req as any).cookies as Record<string, string> | undefined\n if (!cookies) {\n const header = req.headers.cookie\n cookies = header ? parseCookieHeader(header) : {}\n }\n const opened = cookies[cookieName] ? open(cookies[cookieName]) : null\n const existing = opened?.payload ?? null\n const isNew = !existing\n\n let id = existing?.i ?? randomUUID()\n let destroyed = false\n // What the browser already holds, to skip rewriting an unchanged cookie.\n // A cookie sealed with an older secret counts as nothing held, so it is\n // rewritten with the current one.\n let written = existing && !opened?.stale ? JSON.stringify(existing.d) : undefined\n\n const write = (force = false) => {\n if (res.headersSent) return\n if (destroyed) {\n replaceCookie(res, cookieName, '', { ...cookieDefaults, maxAge: 0, expires: new Date(0) })\n return\n }\n const json = JSON.stringify(sessionObj.data)\n // Unchanged: leave the browser's copy, unless `rolling` renews it.\n if (json === written && !force && !(rolling && !isNew)) return\n // A new, empty session gets a cookie only with saveUninitialized.\n if (written === undefined && json === '{}' && !saveUninitialized && !force) return\n const value = seal({ i: id, d: sessionObj.data, e: Date.now() + maxAge })\n if (value.length + cookieName.length > COOKIE_LIMIT && !warnedSize) {\n warnedSize = true\n cookieLog.warn(\n `session cookie is ${value.length} bytes; browsers drop cookies over 4 KB, ` +\n 'so this session will not be kept. Store less in it, or use a shared store.',\n )\n }\n replaceCookie(res, cookieName, value, { ...cookieDefaults, maxAge })\n written = json\n }\n\n // Just before the headers go out, on whichever call sends them first —\n // Node responses go through writeHead; the web driver's buffered end()\n // does not.\n for (const method of ['writeHead', 'flushHeaders', 'write', 'end'] as const) {\n const original = (res as unknown as Record<string, HeaderWriter | undefined>)[method]\n if (typeof original !== 'function') continue\n ;(res as unknown as Record<string, HeaderWriter>)[method] = function (\n this: unknown,\n ...args: unknown[]\n ) {\n write()\n return original.apply(this, args)\n }\n }\n\n // h3 called through fetch hands middleware a stand-in response whose\n // headers join the route's response after `finish` — the last chance there.\n // On a Node response `finish` comes after the headers, so this is a no-op.\n ;(res as unknown as { on?: (event: string, fn: () => void) => unknown }).on?.('finish', () =>\n write(),\n )\n\n const sessionObj: Session = {\n get id() {\n return id\n },\n data: existing ? { ...existing.d } : {},\n async regenerate() {\n id = randomUUID()\n sessionObj.data = {}\n written = undefined\n write(true)\n },\n async destroy() {\n destroyed = true\n sessionObj.data = {}\n write()\n },\n async save() {\n write()\n },\n }\n ;(req as any).session = sessionObj\n next()\n }\n}\n"],"mappings":";;;;;;;;;;ucA2GA,IAAa,YAAb,KAAiD,CAC/C,yBAA4B,IAAI,IAEhC,sBAAyB,IAAI,IAC7B,gBAEA,aAAc,CAEZ,KAAK,gBAAkB,gBAAkB,KAAK,MAAM,EAAG,GAAM,EAC7D,KAAK,gBAAgB,MAAM,EAI3B,uBAAyB,KAAK,QAAQ,CAAC,CACzC,CAGA,SAAgB,CACd,cAAc,KAAK,eAAe,EAClC,KAAK,SAAS,MAAM,EACpB,KAAK,MAAM,MAAM,CACnB,CAEA,MAAM,IAAI,IAA0C,CAClD,IAAM,MAAQ,KAAK,SAAS,IAAI,GAAG,EAOnC,OANK,MACD,KAAK,IAAI,EAAI,MAAM,SACrB,KAAK,SAAS,OAAO,GAAG,EACxB,KAAK,MAAM,OAAO,GAAG,EACd,MAEF,MAAM,KANM,IAOrB,CAEA,MAAM,IAAI,IAAa,KAAmB,OAA+B,CAWvE,IATA,KAAK,SAAS,OAAO,GAAG,EACxB,KAAK,SAAS,IAAI,IAAK,CAAE,KAAM,QAAS,KAAK,IAAI,EAAI,MAAO,CAAC,EAC7D,KAAK,MAAM,OAAO,GAAG,EACjB,OAAO,KAAK,IAAI,CAAC,CAAC,SAAW,GAAG,KAAK,MAAM,IAAI,GAAG,EAM/C,KAAK,SAAS,KAAO,KAAc,CACxC,IAAM,OAAS,KAAK,MAAM,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,OAAS,KAAK,SAAS,KAAK,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AAG,eAAgB,OAAQ,EAAG,wBAAS,IAAI,KAAK,CAAC,CAAE,CAAC,EACzF,MACF,CACA,IAAM,KAAO,KAAK,UAAU,WAAW,IAAI,EAI3C,GAFI,OAAS,SAAW,CAAC,QAAW,UAAY,QAE5C,UAAY,IAAA,IAAa,OAAS,MAAQ,CAAC,mBAAqB,CAAC,MAAO,OAC5E,IAAM,MAAQ,KAAK,CAAE,EAAG,GAAI,EAAG,WAAW,KAAM,EAAG,KAAK,IAAI,EAAI,MAAO,CAAC,EACpE,MAAM,OAAS,WAAW,OAAS,KAAgB,CAAC,aACtD,WAAa,GACb,UAAU,KACR,qBAAqB,MAAM,OAAO,oHAEpC,GAEF,cAAc,IAAK,WAAY,MAAO,CAAE,GAAG,eAAgB,MAAO,CAAC,EACnE,QAAU,IACZ,EAKA,IAAK,IAAM,SAAU,CAAC,YAAa,eAAgB,QAAS,KAAK,EAAY,CAC3E,IAAM,SAAY,IAA4D,QAC1E,OAAO,UAAa,aACvB,IAAiD,QAAU,SAE1D,GAAG,KACH,CAEA,OADA,MAAM,EACC,SAAS,MAAM,KAAM,IAAI,CAClC,EACF,CAKC,IAAwE,KAAK,aAC5E,MAAM,CACR,EAEA,IAAM,WAAsB,CAC1B,IAAI,IAAK,CACP,OAAO,EACT,EACA,KAAM,SAAW,CAAE,GAAG,SAAS,CAAE,EAAI,CAAC,EACtC,MAAM,YAAa,CACjB,GAAK,WAAW,EAChB,WAAW,KAAO,CAAC,EACnB,QAAU,IAAA,GACV,MAAM,EAAI,CACZ,EACA,MAAM,SAAU,CACd,UAAY,GACZ,WAAW,KAAO,CAAC,EACnB,MAAM,CACR,EACA,MAAM,MAAO,CACX,MAAM,CACR,CACF,EACC,IAAa,QAAU,WACxB,KAAK,CACP,CACF"}
@@ -1,3 +1,3 @@
1
1
 
2
- import { b as SpaAdapterOptions, x as resolveClientDir, y as SpaAdapter } from "../../application-Rb6jeTAp.mjs";
2
+ import { b as SpaAdapterOptions, x as resolveClientDir, y as SpaAdapter } from "../../application-r0VMb-A5.mjs";
3
3
  export { SpaAdapter, SpaAdapterOptions, resolveClientDir };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.12.0
2
+ * @forinda/kickjs v10.13.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{Logger}from"../../core/logger.mjs";import"../../core-Kqw_11xA.mjs";import{t as defineAdapter}from"../../define-adapter-DqTV48jK.mjs";import{existsSync,readFileSync,readdirSync}from"node:fs";import{dirname,isAbsolute,join,resolve}from"node:path";const log=Logger.for(`SpaAdapter`);function nearestPackageRoot(from){let dir=from;for(;;){if(existsSync(join(dir,`package.json`)))return dir;let parent=dirname(dir);if(parent===dir)return null;dir=parent}}function resolveClientDir(clientDir,cwd=process.cwd(),entry=process.argv[1]){if(isAbsolute(clientDir))return resolve(clientDir);let fromCwd=resolve(cwd,clientDir);if(existsSync(fromCwd))return fromCwd;if(entry){let root=nearestPackageRoot(dirname(resolve(entry)));if(root){let fromEntry=resolve(root,clientDir);if(existsSync(fromEntry))return fromEntry}}return fromCwd}function pathnameOf(url){if(!url)return`/`;let q=url.indexOf(`?`),h=url.indexOf(`#`),end=Math.min(q===-1?url.length:q,h===-1?url.length:h);return url.slice(0,end)||`/`}function isUnder(pathname,prefix){if(!prefix||prefix===`/`)return!0;let p=prefix.endsWith(`/`)?prefix.slice(0,-1):prefix;return pathname===p||pathname.startsWith(`${p}/`)}const HTML_TYPES=[`text/html`,`application/xhtml+xml`];function qualityOf(params){let q=params.find(param=>param.startsWith(`q=`));if(!q)return 1;let value=Number.parseFloat(q.slice(2));return Number.isNaN(value)?1:value}function acceptsHtml(accept){let raw=Array.isArray(accept)?accept.join(`,`):accept??``;if(!raw)return!1;let ranges=raw.split(`,`).map(part=>part.split(`;`).map(t=>t.trim().toLowerCase())).filter(([type])=>!!type);return HTML_TYPES.some(htmlType=>{let[group]=htmlType.split(`/`),exact=ranges.find(([type])=>type===htmlType),wildcard=ranges.find(([type])=>type===`${group}/*`),match=exact??wildcard;return match?qualityOf(match.slice(1))>0:!1})}const SpaAdapter=defineAdapter({name:`SpaAdapter`,defaults:{clientDir:`dist/client`,apiPrefix:`/api`,exclude:[],cacheControl:`public, max-age=31536000, immutable`,indexCacheControl:`no-cache`,alwaysFallback:!1},build:config=>{let clientDir=resolveClientDir(config.clientDir??`dist/client`),rawPrefix=config.apiPrefix??`/api`,apiPrefixes=Array.isArray(rawPrefix)?rawPrefix:[rawPrefix],excludePaths=config.exclude??[],cacheControl=config.cacheControl??`public, max-age=31536000, immutable`,indexCacheControl=config.indexCacheControl??`no-cache`,alwaysFallback=config.alwaysFallback??!1,indexHtml=null,assetPaths=/* @__PURE__ */ new Set;function snapshotClientDir(){let paths=/* @__PURE__ */ new Set,walk=(absDir,prefix)=>{for(let entry of readdirSync(absDir,{withFileTypes:!0})){let child=`${prefix}/${entry.name}`;entry.isDirectory()?walk(join(absDir,entry.name),child):entry.isFile()&&paths.add(child)}};try{walk(clientDir,``)}catch{return/* @__PURE__ */ new Set}return paths}let classifyPath=pathname=>{let decoded;try{decoded=decodeURIComponent(pathname)}catch{return null}if(decoded.includes(`\0`))return null;let asIndex=decoded.endsWith(`/`)?`${decoded}index.html`:null;return asIndex&&assetPaths.has(asIndex)?`index`:assetPaths.has(decoded)?decoded.endsWith(`.html`)?`index`:`file`:null},isReserved=pathname=>apiPrefixes.some(p=>isUnder(pathname,p))||excludePaths.some(p=>isUnder(pathname,p));return{beforeMount({http}){if(!existsSync(clientDir)){log.warn(`SPA client directory not found: ${clientDir}`),log.warn(`Build your frontend first, or set clientDir to the correct path (relative paths resolve from ${process.cwd()}).`);return}let indexPath=join(clientDir,`index.html`);existsSync(indexPath)?(indexHtml=readFileSync(indexPath,`utf-8`),assetPaths=snapshotClientDir(),cacheControl!==!1&&http.use(((req,res,next)=>{let pathname=pathnameOf(req.url),kind=isReserved(pathname)?null:classifyPath(pathname);kind&&res.setHeader(`Cache-Control`,kind===`index`?indexCacheControl:cacheControl),next()})),http.serveStatic(`/`,clientDir),log.debug(`Serving SPA from ${clientDir}`)):log.warn(`index.html not found in ${clientDir}`)},beforeStart({http}){indexHtml&&http.use(((req,res,next)=>{let method=(req.method??`GET`).toUpperCase();if(method!==`GET`&&method!==`HEAD`)return next();let pathname=pathnameOf(req.url);if(isReserved(pathname))return next();let accept=req.headers?.accept;if(!alwaysFallback&&!acceptsHtml(accept))return next();let body=indexHtml;res.setHeader(`Content-Type`,`text/html; charset=utf-8`),res.setHeader(`Cache-Control`,indexCacheControl),res.setHeader(`Content-Length`,String(Buffer.byteLength(body))),res.statusCode=200,res.end(method===`HEAD`?void 0:body)}))}}}});export{SpaAdapter,resolveClientDir};
11
+ import{Logger}from"../../core/logger.mjs";import"../../core-uD7kn0hF.mjs";import{t as defineAdapter}from"../../define-adapter-rcNang-q.mjs";import{existsSync,readFileSync,readdirSync}from"node:fs";import{dirname,isAbsolute,join,resolve}from"node:path";const log=Logger.for(`SpaAdapter`);function nearestPackageRoot(from){let dir=from;for(;;){if(existsSync(join(dir,`package.json`)))return dir;let parent=dirname(dir);if(parent===dir)return null;dir=parent}}function resolveClientDir(clientDir,cwd=process.cwd(),entry=process.argv[1]){if(isAbsolute(clientDir))return resolve(clientDir);let fromCwd=resolve(cwd,clientDir);if(existsSync(fromCwd))return fromCwd;if(entry){let root=nearestPackageRoot(dirname(resolve(entry)));if(root){let fromEntry=resolve(root,clientDir);if(existsSync(fromEntry))return fromEntry}}return fromCwd}function pathnameOf(url){if(!url)return`/`;let q=url.indexOf(`?`),h=url.indexOf(`#`),end=Math.min(q===-1?url.length:q,h===-1?url.length:h);return url.slice(0,end)||`/`}function isUnder(pathname,prefix){if(!prefix||prefix===`/`)return!0;let p=prefix.endsWith(`/`)?prefix.slice(0,-1):prefix;return pathname===p||pathname.startsWith(`${p}/`)}const HTML_TYPES=[`text/html`,`application/xhtml+xml`];function qualityOf(params){let q=params.find(param=>param.startsWith(`q=`));if(!q)return 1;let value=Number.parseFloat(q.slice(2));return Number.isNaN(value)?1:value}function acceptsHtml(accept){let raw=Array.isArray(accept)?accept.join(`,`):accept??``;if(!raw)return!1;let ranges=raw.split(`,`).map(part=>part.split(`;`).map(t=>t.trim().toLowerCase())).filter(([type])=>!!type);return HTML_TYPES.some(htmlType=>{let[group]=htmlType.split(`/`),exact=ranges.find(([type])=>type===htmlType),wildcard=ranges.find(([type])=>type===`${group}/*`),match=exact??wildcard;return match?qualityOf(match.slice(1))>0:!1})}const SpaAdapter=defineAdapter({name:`SpaAdapter`,defaults:{clientDir:`dist/client`,apiPrefix:`/api`,exclude:[],cacheControl:`public, max-age=31536000, immutable`,indexCacheControl:`no-cache`,alwaysFallback:!1},build:config=>{let clientDir=resolveClientDir(config.clientDir??`dist/client`),rawPrefix=config.apiPrefix??`/api`,apiPrefixes=Array.isArray(rawPrefix)?rawPrefix:[rawPrefix],excludePaths=config.exclude??[],cacheControl=config.cacheControl??`public, max-age=31536000, immutable`,indexCacheControl=config.indexCacheControl??`no-cache`,alwaysFallback=config.alwaysFallback??!1,indexHtml=null,assetPaths=/* @__PURE__ */ new Set;function snapshotClientDir(){let paths=/* @__PURE__ */ new Set,walk=(absDir,prefix)=>{for(let entry of readdirSync(absDir,{withFileTypes:!0})){let child=`${prefix}/${entry.name}`;entry.isDirectory()?walk(join(absDir,entry.name),child):entry.isFile()&&paths.add(child)}};try{walk(clientDir,``)}catch{return/* @__PURE__ */ new Set}return paths}let classifyPath=pathname=>{let decoded;try{decoded=decodeURIComponent(pathname)}catch{return null}if(decoded.includes(`\0`))return null;let asIndex=decoded.endsWith(`/`)?`${decoded}index.html`:null;return asIndex&&assetPaths.has(asIndex)?`index`:assetPaths.has(decoded)?decoded.endsWith(`.html`)?`index`:`file`:null},isReserved=pathname=>apiPrefixes.some(p=>isUnder(pathname,p))||excludePaths.some(p=>isUnder(pathname,p));return{beforeMount({http}){if(!existsSync(clientDir)){log.warn(`SPA client directory not found: ${clientDir}`),log.warn(`Build your frontend first, or set clientDir to the correct path (relative paths resolve from ${process.cwd()}).`);return}let indexPath=join(clientDir,`index.html`);existsSync(indexPath)?(indexHtml=readFileSync(indexPath,`utf-8`),assetPaths=snapshotClientDir(),cacheControl!==!1&&http.use(((req,res,next)=>{let pathname=pathnameOf(req.url),kind=isReserved(pathname)?null:classifyPath(pathname);kind&&res.setHeader(`Cache-Control`,kind===`index`?indexCacheControl:cacheControl),next()})),http.serveStatic(`/`,clientDir),log.debug(`Serving SPA from ${clientDir}`)):log.warn(`index.html not found in ${clientDir}`)},beforeStart({http}){indexHtml&&http.use(((req,res,next)=>{let method=(req.method??`GET`).toUpperCase();if(method!==`GET`&&method!==`HEAD`)return next();let pathname=pathnameOf(req.url);if(isReserved(pathname))return next();let accept=req.headers?.accept;if(!alwaysFallback&&!acceptsHtml(accept))return next();let body=indexHtml;res.setHeader(`Content-Type`,`text/html; charset=utf-8`),res.setHeader(`Cache-Control`,indexCacheControl),res.setHeader(`Content-Length`,String(Buffer.byteLength(body))),res.statusCode=200,res.end(method===`HEAD`?void 0:body)}))}}}});export{SpaAdapter,resolveClientDir};
12
12
  //# sourceMappingURL=spa.mjs.map
@@ -1,4 +1,4 @@
1
1
 
2
- import { A as RawUploadPart, F as buildFileTypeFilter, I as resolveMimeTypes, M as UploadedFile, N as UploadedFileLike, P as applyUploadConfig, j as UploadStorageEngine } from "../../adapter-DiJfCKXU.mjs";
3
- import { i as upload, n as buildUploadMiddleware, r as cleanupFiles, t as UploadOptions } from "../../upload-C9IfY1aQ.mjs";
2
+ import { A as RawUploadPart, F as buildFileTypeFilter, I as resolveMimeTypes, M as UploadedFile, N as UploadedFileLike, P as applyUploadConfig, j as UploadStorageEngine } from "../../adapter-g_vQffKr.mjs";
3
+ import { i as upload, n as buildUploadMiddleware, r as cleanupFiles, t as UploadOptions } from "../../upload-DodgN_Ef.mjs";
4
4
  export { type RawUploadPart, UploadOptions, type UploadStorageEngine, type UploadedFile, type UploadedFileLike, applyUploadConfig, buildFileTypeFilter, buildUploadMiddleware, cleanupFiles, resolveMimeTypes, upload };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.12.0
2
+ * @forinda/kickjs v10.13.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,HttpStatus}from"../../core/errors.mjs";import{f as tooLarge}from"../../body-policy-cWfUReGC.mjs";import{a as normalizeOriginalName,c as tooManyFiles,i as buildFileTypeFilter,l as uploadLimits,n as UPLOAD_FIELDS_ALLOWANCE,o as resolveMimeTypes,r as applyUploadConfig,s as serverFileName,t as MAX_UPLOAD_FIELDS}from"../../upload-config-TFTYQPaH.mjs";import{unlink}from"node:fs/promises";import{Transform}from"node:stream";let _multer;function loadMulter(){return _multer??=import(`multer`).then(mod=>mod.default??mod,()=>{throw Error(`@forinda/kickjs: file uploads require the 'multer' package, which is not installed. Add it to your dependencies.`)})}function translateMulterErrors(mw,options,files){let maxSize=options.maxSize??5242880;return(req,res,next)=>{mw(req,res,err=>{if(files&&err?.code===`LIMIT_UNEXPECTED_FILE`&&err.field===files.field)return next(tooManyFiles(files.max));if(err&&err.code===`LIMIT_FILE_SIZE`){let name=err.field??`file`;return next(new HttpException(HttpStatus.PAYLOAD_TOO_LARGE,`File ${name} exceeds the ${maxSize}-byte limit`))}if(!err)try{nameUploads(req,options)}catch(error){return next(error)}next(err)})}}function nameUploads(req,options){let files=[req.file,...Array.isArray(req.files)?req.files:[]];for(let file of files)file&&(file.originalname=normalizeOriginalName(file.originalname),file.filename??=serverFileName(file,options))}function createMulter(options){let limits={fileSize:options.maxSize??5242880,fields:MAX_UPLOAD_FIELDS,fieldSize:UPLOAD_FIELDS_ALLOWANCE},fileFilter;if(options.allowedTypes){let typeAllowed=buildFileTypeFilter(options.allowedTypes,options.customMimeMap);fileFilter=(_req,file,cb)=>{typeAllowed(file.mimetype,file.originalname)?cb(null,!0):cb(new HttpException(HttpStatus.UNSUPPORTED_MEDIA_TYPE,`File type ${file.mimetype} is not allowed`))}}let multerOptions={limits,defParamCharset:`utf8`,...fileFilter?{fileFilter}:{},...options.storage?{storage:options.storage}:{},...options.dest?{dest:options.dest}:{}},built,lazy=pick=>{let handler;return(req,res,next)=>{handler??=(built??=loadMulter().then(multer=>multer(multerOptions))).then(pick),handler.then(run=>run(req,res,next),err=>{handler=built=_multer=void 0,next(err)})}};return{single:field=>lazy(m=>m.single(field)),array:(field,maxCount)=>lazy(m=>m.array(field,maxCount)),none:()=>lazy(m=>m.none())}}function bothConventions(handler){return((first,second,third)=>third===void 0&&typeof second==`function`&&typeof first==`object`&&first&&`req`in first&&`res`in first?new Promise((resolve,reject)=>{handler(first.req,first.res,err=>{if(err)return reject(err);resolve(),second()})}):handler(first,second,third))}function capBody(mw,limit){return(req,res,next)=>{if(Number(req.headers[`content-length`])>limit)return next(tooLarge(limit));if(typeof req.pipe!=`function`)return mw(req,res,next);let pipe=req.pipe.bind(req);req.pipe=(destination=>{let received=0,counter=new Transform({transform(chunk,_encoding,done){if(received+=chunk.length,received<=limit)return done(null,chunk);received-chunk.length<=limit&&destination.destroy(tooLarge(limit)),done()}});return pipe(counter),counter.pipe(destination)}),mw(req,res,next)}}function single(fieldName,options={}){let m=createMulter(options),{total}=uploadLimits({mode:`single`,maxSize:options.maxSize});return bothConventions(capBody(translateMulterErrors(m.single(fieldName),options,{field:fieldName,max:1}),total))}function array(fieldName,maxCount=10,options={}){let m=createMulter(options),{total}=uploadLimits({mode:`array`,maxSize:options.maxSize,maxCount});return bothConventions(capBody(translateMulterErrors(m.array(fieldName,maxCount),options,{field:fieldName,max:maxCount}),total))}function none(options={}){let m=createMulter(options),{total}=uploadLimits({mode:`none`});return bothConventions(capBody(translateMulterErrors(m.none(),options),total))}function cleanupFiles(){return(req,res,next)=>{res.on(`finish`,async()=>{let files=[];if(req.file?.path&&files.push(req.file),Array.isArray(req.files))for(let f of req.files)f?.path&&files.push(f);for(let file of files)try{await unlink(file.path)}catch{}}),next()}}function buildUploadMiddleware(config){let options={};config.maxSize&&(options.maxSize=config.maxSize),config.allowedTypes&&(options.allowedTypes=config.allowedTypes),config.customMimeMap&&(options.customMimeMap=config.customMimeMap),config.rename&&(options.rename=config.rename);let fieldName=config.fieldName??`file`;switch(config.mode){case`single`:return single(fieldName,options);case`array`:return array(fieldName,config.maxCount??10,options);case`none`:return none(options)}}const upload={single,array,none};export{applyUploadConfig,buildFileTypeFilter,buildUploadMiddleware,cleanupFiles,resolveMimeTypes,upload};
11
+ import{HttpException,HttpStatus}from"../../core/errors.mjs";import{f as tooLarge}from"../../body-policy-BK8PLFhR.mjs";import{a as normalizeOriginalName,c as tooManyFiles,i as buildFileTypeFilter,l as uploadLimits,n as UPLOAD_FIELDS_ALLOWANCE,o as resolveMimeTypes,r as applyUploadConfig,s as serverFileName,t as MAX_UPLOAD_FIELDS}from"../../upload-config-BrbOOmcm.mjs";import{unlink}from"node:fs/promises";import{Transform}from"node:stream";let _multer;function loadMulter(){return _multer??=import(`multer`).then(mod=>mod.default??mod,()=>{throw Error(`@forinda/kickjs: file uploads require the 'multer' package, which is not installed. Add it to your dependencies.`)})}function translateMulterErrors(mw,options,files){let maxSize=options.maxSize??5242880;return(req,res,next)=>{mw(req,res,err=>{if(files&&err?.code===`LIMIT_UNEXPECTED_FILE`&&err.field===files.field)return next(tooManyFiles(files.max));if(err&&err.code===`LIMIT_FILE_SIZE`){let name=err.field??`file`;return next(new HttpException(HttpStatus.PAYLOAD_TOO_LARGE,`File ${name} exceeds the ${maxSize}-byte limit`))}if(!err)try{nameUploads(req,options)}catch(error){return next(error)}next(err)})}}function nameUploads(req,options){let files=[req.file,...Array.isArray(req.files)?req.files:[]];for(let file of files)file&&(file.originalname=normalizeOriginalName(file.originalname),file.filename??=serverFileName(file,options))}function createMulter(options){let limits={fileSize:options.maxSize??5242880,fields:MAX_UPLOAD_FIELDS,fieldSize:UPLOAD_FIELDS_ALLOWANCE},fileFilter;if(options.allowedTypes){let typeAllowed=buildFileTypeFilter(options.allowedTypes,options.customMimeMap);fileFilter=(_req,file,cb)=>{typeAllowed(file.mimetype,file.originalname)?cb(null,!0):cb(new HttpException(HttpStatus.UNSUPPORTED_MEDIA_TYPE,`File type ${file.mimetype} is not allowed`))}}let multerOptions={limits,defParamCharset:`utf8`,...fileFilter?{fileFilter}:{},...options.storage?{storage:options.storage}:{},...options.dest?{dest:options.dest}:{}},built,lazy=pick=>{let handler;return(req,res,next)=>{handler??=(built??=loadMulter().then(multer=>multer(multerOptions))).then(pick),handler.then(run=>run(req,res,next),err=>{handler=built=_multer=void 0,next(err)})}};return{single:field=>lazy(m=>m.single(field)),array:(field,maxCount)=>lazy(m=>m.array(field,maxCount)),none:()=>lazy(m=>m.none())}}function bothConventions(handler){return((first,second,third)=>third===void 0&&typeof second==`function`&&typeof first==`object`&&first&&`req`in first&&`res`in first?new Promise((resolve,reject)=>{handler(first.req,first.res,err=>{if(err)return reject(err);resolve(),second()})}):handler(first,second,third))}function capBody(mw,limit){return(req,res,next)=>{if(Number(req.headers[`content-length`])>limit)return next(tooLarge(limit));if(typeof req.pipe!=`function`)return mw(req,res,next);let pipe=req.pipe.bind(req);req.pipe=(destination=>{let received=0,counter=new Transform({transform(chunk,_encoding,done){if(received+=chunk.length,received<=limit)return done(null,chunk);received-chunk.length<=limit&&destination.destroy(tooLarge(limit)),done()}});return pipe(counter),counter.pipe(destination)}),mw(req,res,next)}}function single(fieldName,options={}){let m=createMulter(options),{total}=uploadLimits({mode:`single`,maxSize:options.maxSize});return bothConventions(capBody(translateMulterErrors(m.single(fieldName),options,{field:fieldName,max:1}),total))}function array(fieldName,maxCount=10,options={}){let m=createMulter(options),{total}=uploadLimits({mode:`array`,maxSize:options.maxSize,maxCount});return bothConventions(capBody(translateMulterErrors(m.array(fieldName,maxCount),options,{field:fieldName,max:maxCount}),total))}function none(options={}){let m=createMulter(options),{total}=uploadLimits({mode:`none`});return bothConventions(capBody(translateMulterErrors(m.none(),options),total))}function cleanupFiles(){return(req,res,next)=>{res.on(`finish`,async()=>{let files=[];if(req.file?.path&&files.push(req.file),Array.isArray(req.files))for(let f of req.files)f?.path&&files.push(f);for(let file of files)try{await unlink(file.path)}catch{}}),next()}}function buildUploadMiddleware(config){let options={};config.maxSize&&(options.maxSize=config.maxSize),config.allowedTypes&&(options.allowedTypes=config.allowedTypes),config.customMimeMap&&(options.customMimeMap=config.customMimeMap),config.rename&&(options.rename=config.rename);let fieldName=config.fieldName??`file`;switch(config.mode){case`single`:return single(fieldName,options);case`array`:return array(fieldName,config.maxCount??10,options);case`none`:return none(options)}}const upload={single,array,none};export{applyUploadConfig,buildFileTypeFilter,buildUploadMiddleware,cleanupFiles,resolveMimeTypes,upload};
12
12
  //# sourceMappingURL=upload.mjs.map
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.12.0
2
+ * @forinda/kickjs v10.13.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -1,3 +1,3 @@
1
1
 
2
- import { C as ViewAdapterOptions, S as ViewAdapter, w as viewDirs } from "../../application-Rb6jeTAp.mjs";
2
+ import { C as ViewAdapterOptions, S as ViewAdapter, w as viewDirs } from "../../application-r0VMb-A5.mjs";
3
3
  export { ViewAdapter, ViewAdapterOptions, viewDirs };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.12.0
2
+ * @forinda/kickjs v10.13.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{Logger}from"../../core/logger.mjs";import"../../core-Kqw_11xA.mjs";import{t as defineAdapter}from"../../define-adapter-DqTV48jK.mjs";import{dirname,resolve}from"node:path";const log=Logger.for(`ViewEngine`),ViewAdapter=defineAdapter({name:`ViewAdapter`,build:options=>({beforeMount({app:engineApp}){let app=engineApp,{engine,ext,viewsDir=`src/views`}=options;engine.__express?app.engine(ext,engine.__express):typeof engine.renderFile==`function`?app.engine(ext,(path,opts,callback)=>{engine.renderFile(path,opts,callback)}):(typeof engine==`function`||log.warn(`Engine for .${ext} does not have __express or renderFile. Trying as-is.`),app.engine(ext,engine)),app.set(`view engine`,ext),app.set(`views`,viewDirs(viewsDir)),log.debug(`View engine: ${ext} (${viewDirs(viewsDir).join(`, `)})`)}})});function viewDirs(viewsDir){let root=resolve(process.env.KICK_APP_ROOT??process.cwd(),viewsDir),entry=process.argv[1]?resolve(dirname(resolve(process.argv[1])),viewsDir):root;return[.../* @__PURE__ */ new Set([root,entry])]}export{ViewAdapter,viewDirs};
11
+ import{Logger}from"../../core/logger.mjs";import"../../core-uD7kn0hF.mjs";import{t as defineAdapter}from"../../define-adapter-rcNang-q.mjs";import{dirname,resolve}from"node:path";const log=Logger.for(`ViewEngine`),ViewAdapter=defineAdapter({name:`ViewAdapter`,build:options=>({beforeMount({app:engineApp}){let app=engineApp,{engine,ext,viewsDir=`src/views`}=options;engine.__express?app.engine(ext,engine.__express):typeof engine.renderFile==`function`?app.engine(ext,(path,opts,callback)=>{engine.renderFile(path,opts,callback)}):(typeof engine==`function`||log.warn(`Engine for .${ext} does not have __express or renderFile. Trying as-is.`),app.engine(ext,engine)),app.set(`view engine`,ext),app.set(`views`,viewDirs(viewsDir)),log.debug(`View engine: ${ext} (${viewDirs(viewsDir).join(`, `)})`)}})});function viewDirs(viewsDir){let root=resolve(process.env.KICK_APP_ROOT??process.cwd(),viewsDir),entry=process.argv[1]?resolve(dirname(resolve(process.argv[1])),viewsDir):root;return[.../* @__PURE__ */ new Set([root,entry])]}export{ViewAdapter,viewDirs};
12
12
  //# sourceMappingURL=views.mjs.map
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.12.0
2
+ * @forinda/kickjs v10.13.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,4 +8,4 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- export{u as FILTER_OPERATORS,t as buildQueryParams,n as getQueryParsingDefaults,r as parseFilters,i as parsePagination,a as parseQuery,o as parseSearchQuery,s as parseSort,c as resetQueryParsingDefaults,l as setQueryParsingDefaults}from"../../query-Coc1hIiS.mjs";
11
+ export{u as FILTER_OPERATORS,t as buildQueryParams,n as getQueryParsingDefaults,r as parseFilters,i as parsePagination,a as parseQuery,o as parseSearchQuery,s as parseSort,c as resetQueryParsingDefaults,l as setQueryParsingDefaults}from"../../query-BukuyQDW.mjs";
@@ -1,3 +1,3 @@
1
1
 
2
- import { i as buildRouteTable, n as _setExternalContributorSources, r as assertRouteUnique, t as BuildRoutesOptions } from "../router-builder-DtGrng_X.mjs";
2
+ import { i as buildRouteTable, n as _setExternalContributorSources, r as assertRouteUnique, t as BuildRoutesOptions } from "../router-builder-DdfPBl09.mjs";
3
3
  export { BuildRoutesOptions, _setExternalContributorSources, assertRouteUnique, buildRouteTable };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.12.0
2
+ * @forinda/kickjs v10.13.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,4 +8,4 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- export{t as _setExternalContributorSources,n as assertRouteUnique,r as buildRouteTable}from"../router-builder-abKMvAmP.mjs";
11
+ export{t as _setExternalContributorSources,n as assertRouteUnique,r as buildRouteTable}from"../router-builder--PLE0eDf.mjs";
@@ -1,7 +1,7 @@
1
1
 
2
- import { d as HttpRuntime, h as RouteEntry } from "../../adapter-DiJfCKXU.mjs";
2
+ import { d as HttpRuntime, h as RouteEntry } from "../../adapter-g_vQffKr.mjs";
3
3
  import { n as ConnectHandler } from "../../connect-BlIamapT.mjs";
4
- import { t as BuildRoutesOptions } from "../../router-builder-DtGrng_X.mjs";
4
+ import { t as BuildRoutesOptions } from "../../router-builder-DdfPBl09.mjs";
5
5
  import { Express, Request, Response } from "express";
6
6
  //#region src/http/runtimes/express.d.ts
7
7
  /**
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.12.0
2
+ * @forinda/kickjs v10.13.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,4 +8,4 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- export{t as buildRoutes,n as expressRuntime,i as materializeRouter}from"../../express-B6jvEdCZ.mjs";
11
+ export{t as buildRoutes,n as expressRuntime,i as materializeRouter}from"../../express-DjX6B-HB.mjs";
@@ -1,5 +1,5 @@
1
1
 
2
- import { d as HttpRuntime } from "../../adapter-DiJfCKXU.mjs";
2
+ import { d as HttpRuntime } from "../../adapter-g_vQffKr.mjs";
3
3
  import { IncomingMessage, ServerResponse } from "node:http";
4
4
  //#region src/http/runtimes/fastify.d.ts
5
5
  interface FastifyReplyLike {
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.12.0
2
+ * @forinda/kickjs v10.13.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,6 +8,6 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{createLogger}from"../../core/logger.mjs";import{HttpException}from"../../core/errors.mjs";import{a as hasPrototypeKey,c as prototypeKeyError,f as tooLarge,i as formFields,p as unsupportedMediaTypeError,s as parseForm}from"../../body-policy-cWfUReGC.mjs";import{f as requestStore}from"../../view-renderer-CSPD7F-f.mjs";import{n as disposeRequestStore,t as createRequestStore}from"../../request-scope-R9FuLLnB.mjs";import{n as applyHandlerResult}from"../../reply-Bg1gyBtE.mjs";import{i as stringifyJson,r as publishMatchedRoute,t as RequestContext}from"../../context-Cc6k0gsM.mjs";import{validate}from"../middleware/validate.mjs";import{c as tooManyFiles,l as uploadLimits,n as UPLOAD_FIELDS_ALLOWANCE,r as applyUploadConfig,t as MAX_UPLOAD_FIELDS}from"../../upload-config-TFTYQPaH.mjs";import"../middleware/upload.mjs";import{t as lazyServeStatic}from"../../lazy-serve-static-BeucQAk2.mjs";import Fastify from"fastify";const pluginOf=mod=>mod.default??mod,createFastify=Fastify,log=createLogger(`FastifyRuntime`),QUEUE=Symbol(`kickjs.fastify.connectQueue`),READY=Symbol(`kickjs.fastify.ready`),NEXT=Symbol(`kickjs.fastify.next`),STORE=Symbol(`kickjs.fastify.store`),NEEDS_MULTIPART=Symbol(`kickjs.fastify.needsMultipart`),NOOP_NEXT=()=>{};function settleOrFail(reply,returned){typeof returned?.then==`function`&&Promise.resolve(returned).then(void 0,()=>{!reply.sent&&!reply.raw.headersSent&&reply.code(500).send({message:`Internal Server Error`})})}function inRouteStore(raw,res,fn){let own=raw[STORE];if(own)return void requestStore.run(own,fn);if(requestStore.getStore())return fn();let header=raw.headers[`x-request-id`],store=createRequestStore(raw.requestId||(Array.isArray(header)?header[0]:header));res.once(`close`,()=>disposeRequestStore(store)),requestStore.run(store,fn)}const NO_FALLTHROUGH=Symbol(`kickjs.fastify.noFallthrough`);function multipartError(err,limits,file){switch(err?.code){case`FST_REQ_FILE_TOO_LARGE`:return new HttpException(413,`File ${file} exceeds the ${limits.fileSize}-byte limit`);case`FST_FILES_LIMIT`:return tooManyFiles(limits.files);case`FST_FIELDS_LIMIT`:case`FST_PARTS_LIMIT`:return new HttpException(413,`Too many form fields`);case`FST_PROTO_VIOLATION`:return prototypeKeyError();default:return err}}var FastifyReplyDriver=class{reply;constructor(reply){this.reply=reply}status(code){return this.reply.code(code),this}json(data){return this.reply.getHeader(`content-type`)||this.reply.type(`application/json; charset=utf-8`),this.reply.serializer(stringifyJson).send(data),this}send(data){return this.reply.send(data),this}type(contentType){return this.reply.type(contentType),this}getHeader(name){return this.reply.getHeader(name)}setHeader(name,value){return this.reply.removeHeader(name),this.reply.header(name,value),this}render(){throw Error(`ctx.render() is not supported on the Fastify runtime (no view engine).`)}writeHead(statusCode,headers){return this.reply.hijack(),this.reply.raw.writeHead(statusCode,headers),this}flushHeaders(){return this.reply.raw.flushHeaders?.(),this}write(chunk){return this.reply.raw.write(chunk)}end(data){return this.reply.raw.headersSent?this.reply.raw.end(data):this.reply.send(data??``),this}once(event,listener){return this.reply.raw.once(event,listener),this}get headersSent(){return this.reply.sent||this.reply.raw.headersSent}};function replyDriver(reply){return new FastifyReplyDriver(reply)}function routeHandler(entry){let validator=entry.meta.validation?validate(entry.meta.validation,{validationError:entry.validationError}):void 0;return async(request,reply)=>{let raw=request.raw;if(raw.body=request.body,raw.params=request.params,raw.query=request.query,entry.meta.upload&&entry.meta.upload.mode!==`none`){if(typeof request.parts!=`function`)throw Error(`@forinda/kickjs: @FileUpload on the Fastify runtime requires '@fastify/multipart'.
11
+ import{createLogger}from"../../core/logger.mjs";import{HttpException}from"../../core/errors.mjs";import{a as hasPrototypeKey,c as prototypeKeyError,f as tooLarge,i as formFields,p as unsupportedMediaTypeError,s as parseForm}from"../../body-policy-BK8PLFhR.mjs";import{f as requestStore}from"../../view-renderer-Caqy9XY5.mjs";import{n as disposeRequestStore,t as createRequestStore}from"../../request-scope-BmUpBk1z.mjs";import{n as applyHandlerResult}from"../../reply-DDoHPeGF.mjs";import{t as RequestContext}from"../../context-Vy_DYHAM.mjs";import{n as publishMatchedRoute,r as stringifyJson}from"../../runtime-OgMPp4md.mjs";import{validate}from"../middleware/validate.mjs";import{c as tooManyFiles,l as uploadLimits,n as UPLOAD_FIELDS_ALLOWANCE,r as applyUploadConfig,t as MAX_UPLOAD_FIELDS}from"../../upload-config-BrbOOmcm.mjs";import"../middleware/upload.mjs";import{t as lazyServeStatic}from"../../lazy-serve-static-BBO3lkBi.mjs";import Fastify from"fastify";const pluginOf=mod=>mod.default??mod,createFastify=Fastify,log=createLogger(`FastifyRuntime`),QUEUE=Symbol(`kickjs.fastify.connectQueue`),READY=Symbol(`kickjs.fastify.ready`),NEXT=Symbol(`kickjs.fastify.next`),STORE=Symbol(`kickjs.fastify.store`),NEEDS_MULTIPART=Symbol(`kickjs.fastify.needsMultipart`),NOOP_NEXT=()=>{};function settleOrFail(reply,returned){typeof returned?.then==`function`&&Promise.resolve(returned).then(void 0,()=>{!reply.sent&&!reply.raw.headersSent&&reply.code(500).send({message:`Internal Server Error`})})}function inRouteStore(raw,res,fn){let own=raw[STORE];if(own)return void requestStore.run(own,fn);if(requestStore.getStore())return fn();let header=raw.headers[`x-request-id`],store=createRequestStore(raw.requestId||(Array.isArray(header)?header[0]:header));res.once(`close`,()=>disposeRequestStore(store)),requestStore.run(store,fn)}const NO_FALLTHROUGH=Symbol(`kickjs.fastify.noFallthrough`);function multipartError(err,limits,file){switch(err?.code){case`FST_REQ_FILE_TOO_LARGE`:return new HttpException(413,`File ${file} exceeds the ${limits.fileSize}-byte limit`);case`FST_FILES_LIMIT`:return tooManyFiles(limits.files);case`FST_FIELDS_LIMIT`:case`FST_PARTS_LIMIT`:return new HttpException(413,`Too many form fields`);case`FST_PROTO_VIOLATION`:return prototypeKeyError();default:return err}}var FastifyReplyDriver=class{reply;constructor(reply){this.reply=reply}status(code){return this.reply.code(code),this}json(data){return this.reply.getHeader(`content-type`)||this.reply.type(`application/json; charset=utf-8`),this.reply.serializer(stringifyJson).send(data),this}send(data){return this.reply.send(data),this}type(contentType){return this.reply.type(contentType),this}getHeader(name){return this.reply.getHeader(name)}setHeader(name,value){return this.reply.removeHeader(name),this.reply.header(name,value),this}render(){throw Error(`ctx.render() is not supported on the Fastify runtime (no view engine).`)}writeHead(statusCode,headers){return this.reply.hijack(),this.reply.raw.writeHead(statusCode,headers),this}flushHeaders(){return this.reply.raw.flushHeaders?.(),this}write(chunk){return this.reply.raw.write(chunk)}end(data){return this.reply.raw.headersSent?this.reply.raw.end(data):this.reply.send(data??``),this}once(event,listener){return this.reply.raw.once(event,listener),this}get headersSent(){return this.reply.sent||this.reply.raw.headersSent}};function replyDriver(reply){return new FastifyReplyDriver(reply)}function routeHandler(entry){let validator=entry.meta.validation?validate(entry.meta.validation,{validationError:entry.validationError}):void 0;return async(request,reply)=>{let raw=request.raw;if(raw.body=request.body,raw.params=request.params,raw.query=request.query,entry.meta.upload&&entry.meta.upload.mode!==`none`){if(typeof request.parts!=`function`)throw Error(`@forinda/kickjs: @FileUpload on the Fastify runtime requires '@fastify/multipart'.
12
12
  Install it as a peer dependency: pnpm add @fastify/multipart.`);let limits=uploadLimits(entry.meta.upload),rawParts=[],fields=[],current=`file`,received=0,count=bytes=>{if(received+=bytes,received>limits.total)throw tooLarge(limits.total)};try{for await(let part of request.parts({limits:{fileSize:limits.fileSize,files:limits.files,fields:MAX_UPLOAD_FIELDS,fieldSize:UPLOAD_FIELDS_ALLOWANCE}}))if(part.type===`file`&&part.toBuffer){current=part.filename??part.fieldname;let buffer=await part.toBuffer();count(buffer.length),rawParts.push({fieldname:part.fieldname,filename:part.filename??``,mimetype:part.mimetype??`application/octet-stream`,buffer})}else{let value=String(part.value);count(Buffer.byteLength(part.fieldname)+Buffer.byteLength(value)),fields.push([part.fieldname,value])}}catch(err){throw multipartError(err,limits,current)}let{file,files}=applyUploadConfig(rawParts,entry.meta.upload);raw.file=file,raw.files=files,raw.body={...raw.body,...formFields(fields)}}if(hasPrototypeKey(raw.body))throw prototypeKeyError();let headerId=raw.headers[`x-request-id`],requestId=raw.requestId||(Array.isArray(headerId)?headerId[0]:headerId),store=createRequestStore(requestId);raw.requestId=store.requestId,raw[STORE]=store,reply.getHeader(`x-request-id`)||reply.header(`x-request-id`,store.requestId),reply.raw.once(`close`,()=>disposeRequestStore(store)),await requestStore.run(store,async()=>{publishMatchedRoute(raw,entry);let ctx=new RequestContext(raw,reply,NOOP_NEXT,replyDriver(reply));if(entry.earlyContributorRunner&&(await entry.earlyContributorRunner(ctx),reply.sent))return;validator&&await new Promise((resolve,reject)=>{validator(raw,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||reply.sent)return}if(entry.contributorRunner&&await entry.contributorRunner(ctx),reply.sent)return;let result=await entry.handler(ctx);!reply.sent&&!await applyHandlerResult(ctx,result)&&reply.callNotFound()})}}function hopTrust(hops){return(_ip,hopIndex)=>hopIndex<hops}function fastifyRuntime(){return{name:`fastify`,createApp(options={}){let app=createFastify({logger:!1,routerOptions:{ignoreTrailingSlash:!0},...options.bodyLimit===void 0?{}:{bodyLimit:options.bodyLimit},trustProxy:typeof options.trustProxy==`number`?hopTrust(options.trustProxy):options.trustProxy});app[QUEUE]=[];let addParser=app.addContentTypeParser?.bind(app);return addParser&&(addParser(/^application\/[\w.+-]+\+json$/,{parseAs:`string`},(_req,body,done)=>{if(body===``)return done(null,void 0);try{done(null,JSON.parse(body))}catch(err){done(HttpException.badRequest(err instanceof Error?err.message:`Request body could not be parsed`),void 0)}}),addParser(`application/x-www-form-urlencoded`,{parseAs:`string`},(_req,body,done)=>{done(null,parseForm(body))}),addParser(/^text\//,{parseAs:`string`},(_req,body,done)=>{done(null,body)}),addParser(`*`,{parseAs:`string`},(req,body,done)=>{if(!body)return done(null,void 0);done(unsupportedMediaTypeError(req.headers?.[`content-type`]),void 0)})),options.notFoundFallthrough===!1&&(app[NO_FALLTHROUGH]=!0),app},nodeHandler(app){let state=app;state[READY]||(state[READY]=(async()=>{if(state[NEEDS_MULTIPART]){let multipart=pluginOf(await import(`@fastify/multipart`));await app.register(multipart,{limits:{fileSize:2**53-1}})}let middie=pluginOf(await import(`@fastify/middie`));await app.register(middie);for(let{mw,opts}of state[QUEUE]??[])opts?.path===void 0?app.use(mw):app.use(opts.path,mw);await app.ready()})());let readyP=state[READY],ready=!1;return readyP.then(()=>ready=!0,()=>{}),(req,res,next)=>{next&&(req[NEXT]=next),ready?app.routing(req,res):readyP.then(()=>app.routing(req,res)).catch(err=>{if(next)return next(err);log.error(err,`Fastify failed to start`),res.statusCode=500,res.end(`Internal Server Error`)})}},mountRoutes(app,table){for(let{mountPath,routes}of table)for(let entry of routes){entry.meta.upload&&(app[NEEDS_MULTIPART]=!0);let url=joinPath(mountPath,entry.path);app.route({method:entry.method,url,handler:routeHandler(entry)})}},useConnect(app,mw,opts){app[QUEUE]?.push({mw,opts})},serveStatic(app,prefix,dir){this.useConnect(app,lazyServeStatic(dir),{path:prefix})},setNotFound(app,mw){app.setNotFoundHandler((request,reply)=>{let next=request.raw[NEXT];next&&!app[NO_FALLTHROUGH]?(reply.hijack(),next()):inRouteStore(request.raw,reply.raw,()=>settleOrFail(reply,mw(request.raw,replyDriver(reply),NOOP_NEXT)))})},setErrorHandler(app,mw){app.setErrorHandler((err,request,reply)=>{inRouteStore(request.raw,reply.raw,()=>settleOrFail(reply,mw(err,request.raw,replyDriver(reply),NOOP_NEXT)))})},close(app){return app.close()},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{fastifyRuntime};
13
13
  //# sourceMappingURL=fastify.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"fastify.mjs","names":[],"sources":["../../../src/http/runtimes/fastify.ts"],"sourcesContent":["// The Fastify runtime — `@forinda/kickjs/fastify`.\n//\n// Implements the same HttpRuntime contract as expressRuntime, over Fastify 5.\n// KickJS still owns decorators → RouteTable, the contributor pipeline, and the\n// RequestContext surface; this runtime materializes routes as NATIVE Fastify\n// routes and wraps `reply` in a RuntimeResponse so `ctx.json` / `ctx.html` /\n// `ctx.sse` work unchanged.\n//\n// `fastify`, `@fastify/middie` are optional peers — install them alongside\n// `@forinda/kickjs` to use this subpath.\n//\n// Lifecycle note: Fastify registration (`register` / `use` / `route`) is\n// deferred until `ready()`. Connect middleware needs `@fastify/middie`\n// registered first, so `useConnect` only QUEUES middleware; `nodeHandler`\n// registers middie, then the queued middleware, then awaits `ready()`.\n\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport Fastify from 'fastify'\n\nimport { HttpException } from '../../core/errors'\nimport {\n formFields,\n hasPrototypeKey,\n parseForm,\n prototypeKeyError,\n tooLarge,\n unsupportedMediaTypeError,\n} from '../body-policy'\nimport { RequestContext } from '../context'\nimport { publishMatchedRoute, stringifyJson } from '../runtime'\nimport { applyHandlerResult } from '../reply'\nimport { requestStore } from '../request-store'\nimport { createRequestStore, disposeRequestStore } from '../middleware/request-scope'\nimport type { RequestStore } from '../request-store'\nimport { validate } from '../middleware/validate'\nimport { applyUploadConfig, type RawUploadPart } from '../middleware/upload'\nimport {\n MAX_UPLOAD_FIELDS,\n UPLOAD_FIELDS_ALLOWANCE,\n tooManyFiles,\n uploadLimits,\n} from '../middleware/upload-config'\nimport { lazyServeStatic } from './lazy-serve-static'\nimport { createLogger } from '../../core/logger'\nimport type {\n ConnectMiddleware,\n HttpRuntime,\n RouteEntry,\n RouteTable,\n RuntimeAppOptions,\n RuntimeResponse,\n UseConnectOptions,\n} from '../runtime'\n\n// The peers load through `import`, never `createRequire`: a bundler follows an\n// import, so `kick build:netlify|vercel` inlines them into the function. A\n// computed require is left for the platform to resolve, and the function has\n// no node_modules. `fastify` is static (this entry is the Fastify runtime);\n// the plugins are imported when first needed.\nconst pluginOf = (mod: { default?: unknown }): any => mod.default ?? mod\n// Typed structurally below (FastifyAppLike), as when this was required untyped.\nconst createFastify = Fastify as unknown as (options: object) => unknown\nconst log = createLogger('FastifyRuntime')\n\n// Minimal structural surface we use from Fastify — avoids a hard type dep so\n// the root package never needs `fastify` installed to typecheck.\ninterface FastifyReplyLike {\n code(statusCode: number): FastifyReplyLike\n send(payload?: unknown): FastifyReplyLike\n header(name: string, value: unknown): FastifyReplyLike\n removeHeader(name: string): FastifyReplyLike\n type(contentType: string): FastifyReplyLike\n serializer(fn: (payload: unknown) => string): FastifyReplyLike\n getHeader(name: string): unknown\n hijack(): void\n /** Hand the request to the not-found handler (Fastify 5). */\n callNotFound(): void\n readonly sent: boolean\n readonly raw: ServerResponse\n}\ninterface FastifyRequestLike {\n raw: IncomingMessage\n body?: unknown\n params?: unknown\n query?: unknown\n /** Request headers, as Fastify normalises them (lowercased keys). */\n headers?: Record<string, string | string[] | undefined>\n /** Present once @fastify/multipart is registered — async iterator of parts. */\n parts?: (options?: { limits?: Record<string, number> }) => AsyncIterableIterator<MultipartPart>\n isMultipart?: () => boolean\n}\ntype FastifyHandler = (request: FastifyRequestLike, reply: FastifyReplyLike) => void | Promise<void>\ninterface FastifyAppLike {\n close(): Promise<void>\n register(plugin: unknown, opts?: unknown): Promise<void> | FastifyAppLike\n use(path: unknown, mw?: unknown): unknown\n route(opts: { method: string; url: string; handler: FastifyHandler }): unknown\n setNotFoundHandler(handler: FastifyHandler): unknown\n setErrorHandler(\n handler: (err: unknown, req: FastifyRequestLike, reply: FastifyReplyLike) => void,\n ): unknown\n ready(): Promise<void>\n routing(req: IncomingMessage, res: ServerResponse): void\n /**\n * Fastify's content-type parser registry. Typed here rather than reached for\n * with a cast so the callback shape is checked at the call site — these\n * parsers decide what `ctx.body` is on this runtime.\n */\n addContentTypeParser?(\n matcher: string | RegExp | string[],\n opts: { parseAs: 'string' | 'buffer' },\n parser: FastifyBodyParser,\n ): unknown\n}\n\n/** The `done` callback a Fastify content-type parser calls. */\ntype FastifyParserDone = (err: Error | null, body?: unknown) => void\n\n/** `done`-style callback Fastify hands a content-type parser. */\ntype FastifyBodyParser = (\n req: FastifyRequestLike,\n body: string | Buffer,\n done: (err: Error | null, body?: unknown) => void,\n) => void\n\nconst QUEUE = Symbol('kickjs.fastify.connectQueue')\nconst READY = Symbol('kickjs.fastify.ready')\nconst NEXT = Symbol('kickjs.fastify.next')\n/** The route's request store, re-entered by the error and not-found handlers. */\nconst STORE = Symbol('kickjs.fastify.store')\n// Set during mountRoutes when any route carries @FileUpload metadata, so\n// nodeHandler knows to register @fastify/multipart before ready().\nconst NEEDS_MULTIPART = Symbol('kickjs.fastify.needsMultipart')\nconst NOOP_NEXT = (): void => {}\n\n/**\n * An async error / not-found handler that rejects never answers; answer 500\n * so the request ends instead of hanging until the client gives up.\n */\nfunction settleOrFail(reply: FastifyReplyLike, returned: unknown): void {\n if (typeof (returned as PromiseLike<void> | undefined)?.then !== 'function') return\n Promise.resolve(returned).then(undefined, () => {\n if (!reply.sent && !reply.raw.headersSent) {\n // The 500 body every engine's built-in error handler starts from.\n reply.code(500).send({ message: 'Internal Server Error' })\n }\n })\n}\n/**\n * Run `fn` in the store the matched route opened. An error before any route\n * ran (a body Fastify couldn't parse) uses the store already active, or one\n * of its own, disposed when the response closes.\n */\nfunction inRouteStore(raw: IncomingMessage, res: ServerResponse, fn: () => void): void {\n const own = (raw as { [STORE]?: RequestStore })[STORE]\n if (own) return void requestStore.run(own, fn)\n if (requestStore.getStore()) return fn()\n const header = raw.headers['x-request-id']\n const store = createRequestStore(\n (raw as { requestId?: string }).requestId || (Array.isArray(header) ? header[0] : header),\n )\n res.once('close', () => disposeRequestStore(store))\n requestStore.run(store, fn)\n}\n\n/** `notFoundFallthrough: false` — answer unmatched requests instead of handing them back. */\nconst NO_FALLTHROUGH = Symbol('kickjs.fastify.noFallthrough')\n\n/**\n * @fastify/multipart's limit errors as the exceptions every engine raises —\n * the same status and message as `applyUploadConfig` and the web runtime.\n */\nfunction multipartError(\n err: unknown,\n limits: { fileSize: number; files: number },\n file: string,\n): unknown {\n switch ((err as { code?: string } | null)?.code) {\n case 'FST_REQ_FILE_TOO_LARGE':\n return new HttpException(413, `File ${file} exceeds the ${limits.fileSize}-byte limit`)\n case 'FST_FILES_LIMIT':\n return tooManyFiles(limits.files)\n case 'FST_FIELDS_LIMIT':\n case 'FST_PARTS_LIMIT':\n return new HttpException(413, 'Too many form fields')\n case 'FST_PROTO_VIOLATION':\n return prototypeKeyError()\n default:\n return err\n }\n}\n\n// A @fastify/multipart part as we consume it from `request.parts()`.\ninterface MultipartPart {\n type: 'file' | 'field'\n fieldname: string\n filename?: string\n mimetype?: string\n value?: unknown\n toBuffer?: () => Promise<Buffer>\n}\n\n/**\n * Wrap a Fastify reply so the RequestContext response helpers drive it.\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 FastifyReplyDriver implements RuntimeResponse {\n constructor(private readonly reply: FastifyReplyLike) {}\n status(code: number): this {\n this.reply.code(code)\n return this\n }\n json(data: unknown): this {\n // A custom serializer drops Fastify's default content-type; keep one the\n // caller chose (`application/problem+json`).\n if (!this.reply.getHeader('content-type')) this.reply.type('application/json; charset=utf-8')\n this.reply.serializer(stringifyJson).send(data)\n return this\n }\n send(data: unknown): this {\n this.reply.send(data)\n return this\n }\n type(contentType: string): this {\n this.reply.type(contentType)\n return this\n }\n getHeader(name: string): unknown {\n return this.reply.getHeader(name)\n }\n setHeader(name: string, value: unknown): this {\n // Replace, as node's `res.setHeader` and the web driver do. Fastify's\n // `header()` appends for `set-cookie`, so `setCookie()` — which passes the\n // whole list each time — sent the first cookie twice.\n this.reply.removeHeader(name)\n this.reply.header(name, value)\n return this\n }\n render(): never {\n throw new Error('ctx.render() is not supported on the Fastify runtime (no view engine).')\n }\n writeHead(statusCode: number, headers?: Record<string, string | number | string[]>): this {\n // Streaming / SSE: take over the raw socket so Fastify doesn't try to\n // serialize a reply we're writing by hand.\n this.reply.hijack()\n this.reply.raw.writeHead(statusCode, headers)\n return this\n }\n flushHeaders(): this {\n ;(this.reply.raw as ServerResponse & { flushHeaders?: () => void }).flushHeaders?.()\n return this\n }\n write(chunk: unknown): boolean {\n return this.reply.raw.write(chunk as never)\n }\n end(data?: unknown): this {\n // After writeHead (streaming, SSE) the reply is hijacked and the raw\n // socket is ours to finish. Otherwise finish through the reply, so the\n // status and headers set on it are sent — `ctx.redirect()` writes its\n // Location with setHeader() and then calls end().\n if (this.reply.raw.headersSent) this.reply.raw.end(data as never)\n else this.reply.send(data ?? '')\n return this\n }\n once(event: string, listener: (...args: unknown[]) => void): this {\n this.reply.raw.once(event, listener)\n return this\n }\n get headersSent(): boolean {\n return this.reply.sent || this.reply.raw.headersSent\n }\n}\n\nfunction replyDriver(reply: FastifyReplyLike): RuntimeResponse {\n return new FastifyReplyDriver(reply) as unknown as RuntimeResponse\n}\n\n/** Build the Fastify per-route handler that runs the kickjs pipeline. */\nfunction routeHandler(entry: RouteEntry): FastifyHandler {\n // Validation middleware is built ONCE per route (parity with the Express\n // materializer) — `validate()` constructs a fresh closure, so calling it\n // per request was pure allocation waste.\n const validator = entry.meta.validation\n ? validate(entry.meta.validation, { validationError: entry.validationError })\n : undefined\n return async (request, reply) => {\n // Fastify runs the route handler OUTSIDE the connect-middleware chain, so\n // (unlike Express) the requestScopeMiddleware ALS frame isn't active here.\n // Establish it around the pipeline so REQUEST-scoped DI, contributors, and\n // ctx.set/get work. Reuse the inbound x-request-id, or the id a connect\n // middleware (requestId / requestScope, run earlier via middie) already\n // stamped on the raw request, before generating a fresh one.\n // Use the raw node request as `ctx.req`: it natively provides the stream\n // events (`on('close')` / `once`) that SSE and `ctx.signal` need — Fastify's\n // request object doesn't. Copy Fastify's parsed body/params/query onto it so\n // `ctx.body` / `ctx.params` / `ctx.query` keep working.\n const raw = request.raw as IncomingMessage & {\n requestId?: string\n body?: unknown\n params?: unknown\n query?: unknown\n file?: unknown\n files?: unknown\n }\n raw.body = request.body\n raw.params = request.params\n raw.query = request.query\n\n // @FileUpload: buffer multipart parts into the multer-shaped file(s) that\n // `ctx.file` / `ctx.files` expose. Fastify doesn't parse multipart natively\n // — @fastify/multipart (registered in nodeHandler when any route needs it)\n // provides `request.parts()`. Non-file fields are merged onto `raw.body` so\n // validation / `ctx.body` see them, matching multer's req.body behavior.\n if (entry.meta.upload && entry.meta.upload.mode !== 'none') {\n if (typeof request.parts !== 'function') {\n throw new Error(\n \"@forinda/kickjs: @FileUpload on the Fastify runtime requires '@fastify/multipart'.\\n\" +\n 'Install it as a peer dependency: pnpm add @fastify/multipart.',\n )\n }\n // The parser stops at the route's limits instead of buffering whatever\n // arrives: a file past maxSize, or more files than the route takes, is a 413.\n const limits = uploadLimits(entry.meta.upload)\n const rawParts: RawUploadPart[] = []\n const fields: Array<[string, string]> = []\n let current = 'file'\n // Per-part limits alone allow many parts; the whole body is held to the\n // route's budget too, the same total h3 and the web entry read at most.\n let received = 0\n const count = (bytes: number) => {\n received += bytes\n if (received > limits.total) {\n throw tooLarge(limits.total)\n }\n }\n try {\n for await (const part of request.parts({\n limits: {\n fileSize: limits.fileSize,\n files: limits.files,\n fields: MAX_UPLOAD_FIELDS,\n fieldSize: UPLOAD_FIELDS_ALLOWANCE,\n },\n })) {\n if (part.type === 'file' && part.toBuffer) {\n current = part.filename ?? part.fieldname\n const buffer = await part.toBuffer()\n count(buffer.length)\n rawParts.push({\n fieldname: part.fieldname,\n filename: part.filename ?? '',\n mimetype: part.mimetype ?? 'application/octet-stream',\n buffer,\n })\n } else {\n const value = String(part.value)\n count(Buffer.byteLength(part.fieldname) + Buffer.byteLength(value))\n fields.push([part.fieldname, value])\n }\n }\n } catch (err) {\n throw multipartError(err, limits, current)\n }\n const { file, files } = applyUploadConfig(rawParts, entry.meta.upload)\n raw.file = file\n raw.files = files\n raw.body = { ...(raw.body as Record<string, unknown> | undefined), ...formFields(fields) }\n }\n\n // A key that could rewrite a prototype — refused before any of the app's code sees it.\n if (hasPrototypeKey(raw.body)) throw prototypeKeyError()\n\n const headerId = raw.headers['x-request-id']\n // An id already assigned (requestId() middleware) wins over the header,\n // as on Express and h3.\n const requestId = raw.requestId || (Array.isArray(headerId) ? headerId[0] : headerId)\n const store = createRequestStore(requestId)\n // Propagate the resolved id back onto the raw request so anything reading\n // `req.requestId` inside the frame (e.g. request-logger) matches the store\n // and the X-Request-Id response header — parity with Express.\n raw.requestId = store.requestId\n ;(raw as { [STORE]?: RequestStore })[STORE] = store\n if (!reply.getHeader('x-request-id')) reply.header('x-request-id', store.requestId)\n\n // @PreDestroy teardown for REQUEST-scoped instances once the response\n // closes (finished or aborted) — parity with requestScopeMiddleware.\n reply.raw.once('close', () => disposeRequestStore(store))\n\n await requestStore.run(store, async () => {\n publishMatchedRoute(raw, entry)\n const ctx = new RequestContext(raw as never, reply as never, NOOP_NEXT, replyDriver(reply))\n\n // `beforeValidation` contributors (#677) — ahead of validation and middleware.\n if (entry.earlyContributorRunner) {\n await entry.earlyContributorRunner(ctx)\n if (reply.sent) return\n }\n\n // Validation (from @Get(path, schema) / route.validation). `validator` is a\n // connect-style middleware built once at route registration; it mutates\n // req.body/query/params to the parsed value and calls next(err) on failure\n // — it never touches `res`, so it runs cleanly here. A rejection\n // propagates to the error handler (422).\n if (validator) {\n await new Promise<void>((resolve, reject) => {\n validator(raw as never, undefined as never, (err?: unknown) =>\n err ? reject(err) : resolve(),\n )\n })\n }\n\n // Class + method middleware — `(ctx, next)`; await each, stop if it ended\n // the response or called next(err).\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 || reply.sent) return\n }\n\n if (entry.contributorRunner) await entry.contributorRunner(ctx)\n if (reply.sent) return\n const result = await entry.handler(ctx)\n // Return-value handlers (reply.ts): auto-send when nothing was written.\n // Nothing written and nothing returned falls through to the 404 handler,\n // as on Express and h3 — not Fastify's own empty 200.\n if (!reply.sent && !(await applyHandlerResult(ctx, result))) reply.callNotFound()\n })\n }\n}\n\n/** Express's `trust proxy` number: trust the first `hops` addresses from the socket. */\nfunction hopTrust(hops: number): (ip: string, hopIndex: number) => boolean {\n return (_ip, hopIndex) => hopIndex < hops\n}\n\n/**\n * The Fastify HTTP runtime. Pass to `bootstrap({ runtime: fastifyRuntime() })`.\n * Per spec §10: Fastify's built-in pino logger is disabled (`logger: false`) so\n * the kickjs `requestLogger` middleware stays the single log format.\n */\nexport function fastifyRuntime(): HttpRuntime<FastifyAppLike> {\n return {\n name: 'fastify',\n\n createApp(options: RuntimeAppOptions = {}): FastifyAppLike {\n const app = createFastify({\n logger: false,\n // Match Express / h3 routing leniency: `/api/v1/hello` and\n // `/api/v1/hello/` resolve to the same route. Without this, Fastify's\n // strict router 404s a trailing-slash request — e.g. a controller's\n // root `@Get('/')` (mounted at the prefix) misses `${prefix}/`. Set under\n // `routerOptions` (Fastify 5+; top-level `ignoreTrailingSlash` is\n // deprecated, removed in Fastify 6).\n routerOptions: { ignoreTrailingSlash: true },\n // `jsonLimit`, which Fastify otherwise ignores in favour of its own 1 MiB.\n ...(options.bodyLimit !== undefined ? { bodyLimit: options.bodyLimit } : {}),\n // Express semantics for every form. Fastify takes a predicate as-is,\n // but reads a hop count as \"trust nothing\", where Express trusts that\n // many hops from the socket.\n trustProxy:\n typeof options.trustProxy === 'number'\n ? hopTrust(options.trustProxy)\n : options.trustProxy,\n }) as FastifyAppLike & {\n [QUEUE]?: Array<{ mw: ConnectMiddleware; opts?: UseConnectOptions }>\n }\n app[QUEUE] = []\n\n // Fastify ships parsers for `application/json` and `text/plain` only, and\n // answers 415 for everything else. That made a form post work on Express\n // and h3 but fail on Fastify alone (#590). Register the rest of the\n // framework's supported set so all engines agree.\n //\n // Deliberately NOT a `'*'` catch-all: that would swallow multipart, and\n // `@fastify/multipart` is itself the multipart content-type parser,\n // registered conditionally in `nodeHandler` when a route needs it.\n const addParser = app.addContentTypeParser?.bind(app)\n if (addParser) {\n // `application/*+json` — RFC 6838 §4.2.8 guarantees the bytes are JSON.\n addParser(\n /^application\\/[\\w.+-]+\\+json$/,\n { parseAs: 'string' },\n (_req: FastifyRequestLike, body: string | Buffer, done: FastifyParserDone) => {\n if (body === '') return done(null, undefined)\n try {\n done(null, JSON.parse(body as string))\n } catch (err) {\n // A bare SyntaxError carries no status, so the shared error handler\n // would call it a 500 — Fastify's own JSON parser answers 400\n // (FST_ERR_CTP_INVALID_JSON_BODY), and so must this one.\n done(\n HttpException.badRequest(\n err instanceof Error ? err.message : 'Request body could not be parsed',\n ),\n undefined,\n )\n }\n },\n )\n addParser(\n 'application/x-www-form-urlencoded',\n { parseAs: 'string' },\n (_req: FastifyRequestLike, body: string | Buffer, done: FastifyParserDone) => {\n done(null, parseForm(body as string))\n },\n )\n // `text/*` beyond Fastify's built-in `text/plain`. Raw string, never\n // JSON: `text/plain` is CORS-safelisted, so parsing it as JSON would\n // re-open no-preflight CSRF against a JSON API.\n addParser(\n /^text\\//,\n { parseAs: 'string' },\n (_req: FastifyRequestLike, body: string | Buffer, done: FastifyParserDone) => {\n done(null, body)\n },\n )\n // Fastify already answers 415 for a type it has no parser for, but with\n // its own message and no `Accept`. `'*'` is Fastify's documented\n // fallback — consulted only when nothing more specific matches — so it\n // does not shadow the parsers above, nor `@fastify/multipart`, which\n // registers `multipart/form-data` when an upload route needs it.\n addParser(\n '*',\n { parseAs: 'string' },\n (req: FastifyRequestLike, body: string | Buffer, done: FastifyParserDone) => {\n // No body is not an unsupported body. Fastify calls the parser even\n // for an empty payload, so without this a bodyless POST carrying an\n // unrelated content type would be rejected.\n if (!body) return done(null, undefined)\n done(unsupportedMediaTypeError(req.headers?.['content-type']), undefined)\n },\n )\n }\n\n if (options.notFoundFallthrough === false) {\n ;(app as { [NO_FALLTHROUGH]?: boolean })[NO_FALLTHROUGH] = true\n }\n return app\n },\n\n nodeHandler(app) {\n // Register middie + queued connect middleware + finalize `ready()` exactly\n // ONCE per app, even though Application may call nodeHandler per request.\n const state = app as {\n [QUEUE]?: Array<{ mw: ConnectMiddleware; opts?: UseConnectOptions }>\n [READY]?: Promise<void>\n [NEEDS_MULTIPART]?: boolean\n }\n if (!state[READY]) {\n state[READY] = (async () => {\n // Register @fastify/multipart first when any route uses @FileUpload so\n // `request.parts()` is available. Our applyUploadConfig enforces the\n // real per-file maxSize, so give the plugin a generous fileSize ceiling\n // (its 1MB default would silently truncate larger uploads first).\n if (state[NEEDS_MULTIPART]) {\n const multipart = pluginOf(await import('@fastify/multipart'))\n await app.register(multipart, { limits: { fileSize: Number.MAX_SAFE_INTEGER } })\n }\n const middie = pluginOf(await import('@fastify/middie'))\n await app.register(middie)\n for (const { mw, opts } of state[QUEUE] ?? []) {\n if (opts?.path !== undefined)\n (app.use as (p: unknown, m: unknown) => void)(opts.path, mw)\n else (app.use as (m: unknown) => void)(mw)\n }\n await app.ready()\n })()\n }\n const readyP = state[READY]\n // Once ready, route synchronously — no promise hop per request.\n let ready = false\n readyP.then(\n () => (ready = true),\n () => {},\n )\n\n return (req: IncomingMessage, res: ServerResponse, next?: (err?: unknown) => void) => {\n if (next) (req as IncomingMessage & { [NEXT]?: (err?: unknown) => void })[NEXT] = next\n if (ready) {\n app.routing(req, res)\n return\n }\n readyP\n .then(() => app.routing(req, res))\n .catch((err) => {\n if (next) return next(err)\n // No host to hand the error to: answer rather than leave the request open.\n log.error(err, 'Fastify failed to start')\n res.statusCode = 500\n res.end('Internal Server Error')\n })\n }\n },\n\n mountRoutes(app, table: RouteTable) {\n for (const { mountPath, routes } of table) {\n for (const entry of routes) {\n if (entry.meta.upload) (app as { [NEEDS_MULTIPART]?: boolean })[NEEDS_MULTIPART] = true\n const url = joinPath(mountPath, entry.path)\n app.route({ method: entry.method, url, handler: routeHandler(entry) })\n }\n }\n },\n\n useConnect(app, mw: ConnectMiddleware, opts?: UseConnectOptions) {\n const queue = (\n app as { [QUEUE]?: Array<{ mw: ConnectMiddleware; opts?: UseConnectOptions }> }\n )[QUEUE]\n queue?.push({ mw, opts })\n },\n\n serveStatic(app, prefix, dir) {\n // Serve via `serve-static` (the standalone connect middleware behind\n // express.static) so the Fastify runtime carries no `express` dependency —\n // queued like any other connect middleware, bridged through middie.\n this.useConnect(app, lazyServeStatic(dir), { path: prefix })\n },\n\n setNotFound(app, mw: ConnectMiddleware) {\n app.setNotFoundHandler((request, reply) => {\n const next = (request.raw as IncomingMessage & { [NEXT]?: (err?: unknown) => void })[NEXT]\n if (next && !(app as { [NO_FALLTHROUGH]?: boolean })[NO_FALLTHROUGH]) {\n // Vite dev fall-through: hand the request back to the outer chain.\n reply.hijack()\n next()\n return\n }\n // Pass the reply DRIVER (not raw res) so the connect-style\n // notFoundHandler's `res.status().json()` lands on the Fastify reply.\n // In the route's store when a route handed over (`callNotFound()`).\n inRouteStore(request.raw, reply.raw, () =>\n settleOrFail(\n reply,\n (mw as (req: unknown, res: unknown, next: () => void) => unknown)(\n request.raw,\n replyDriver(reply),\n NOOP_NEXT,\n ),\n ),\n )\n })\n },\n\n setErrorHandler(app, mw: ConnectMiddleware) {\n app.setErrorHandler((err, request, reply) => {\n // Reply driver (not raw res) so the connect-style errorHandler's\n // `res.status().json()` / `setHeader` land on the Fastify reply.\n // In the route's store: Fastify calls this outside it, and an error\n // page should see the handler's ctx values and REQUEST-scoped instances.\n inRouteStore(request.raw, reply.raw, () =>\n settleOrFail(\n reply,\n (mw as (e: unknown, req: unknown, res: unknown, next: () => void) => unknown)(\n err,\n request.raw,\n replyDriver(reply),\n NOOP_NEXT,\n ),\n ),\n )\n })\n },\n\n close(app) {\n // Runs the instance's onClose hooks (plugins registered on it).\n return app.close()\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 Fastify runtime's engine-native types — what the runtime-typed escape\n * hatches resolve to once the `kick/runtime` typegen emits a `KickRuntimeRegister`\n * augmentation pointing here (spec §4.3b). `AdapterContext.app` / `getRuntimeApp()`\n * become `FastifyInstance`; `ctx.req` / `ctx.res` the Fastify request / reply.\n * Mirrors {@link import('../runtime').ExpressRuntimeTypes} for the default engine.\n */\nexport interface FastifyRuntimeTypes {\n request: import('fastify').FastifyRequest\n response: import('fastify').FastifyReply\n app: import('fastify').FastifyInstance\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 // A root route path ('/' or '') maps to the mount prefix itself — otherwise a\n // controller `@Post('/')` would register at `${prefix}/`, and a request to\n // `${prefix}` (no trailing slash) wouldn't match under Fastify's strict router.\n if (path === '/' || path === '') return a === '' ? '/' : a\n const b = path.startsWith('/') ? path : `/${path}`\n return `${a}${b}`\n}\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AAQ,IAAK,CAI5B,KAAK,WAAW,IAAK,gBAAgB,GAAG,EAAG,CAAE,KAAM,MAAO,CAAC,CAC7D,EAEA,YAAY,IAAK,GAAuB,CACtC,IAAI,oBAAoB,QAAS,QAAU,CACzC,IAAM,KAAQ,QAAQ,IAA+D,MACjF,MAAQ,CAAE,IAAuC,iBAEnD,MAAM,OAAO,EACb,KAAK,GAMP,aAAa,QAAQ,IAAK,MAAM,QAC9B,aACE,MACC,GACC,QAAQ,IACR,YAAY,KAAK,EACjB,SACF,CACF,CACF,CACF,CAAC,CACH,EAEA,gBAAgB,IAAK,GAAuB,CAC1C,IAAI,iBAAiB,IAAK,QAAS,QAAU,CAK3C,aAAa,QAAQ,IAAK,MAAM,QAC9B,aACE,MACC,GACC,IACA,QAAQ,IACR,YAAY,KAAK,EACjB,SACF,CACF,CACF,CACF,CAAC,CACH,EAEA,MAAM,IAAK,CAET,OAAO,IAAI,MAAM,CACnB,EAEA,aAAc,CACZ,OAAQ,GACR,QAAS,GACT,kBAAmB,GACnB,kBAAmB,GACnB,MAAO,EACT,CACF,CACF,CAgBA,SAAS,SAAS,UAAmB,KAAsB,CACzD,IAAM,EAAI,UAAU,SAAS,GAAG,EAAI,UAAU,MAAM,EAAG,EAAE,EAAI,UAM7D,OAFI,OAAS,KAAO,OAAS,GAAW,IAAM,GAAK,IAAM,EAElD,GAAG,IADA,KAAK,WAAW,GAAG,EAAI,KAAO,IAAI,QAE9C"}
1
+ {"version":3,"file":"fastify.mjs","names":[],"sources":["../../../src/http/runtimes/fastify.ts"],"sourcesContent":["// The Fastify runtime — `@forinda/kickjs/fastify`.\n//\n// Implements the same HttpRuntime contract as expressRuntime, over Fastify 5.\n// KickJS still owns decorators → RouteTable, the contributor pipeline, and the\n// RequestContext surface; this runtime materializes routes as NATIVE Fastify\n// routes and wraps `reply` in a RuntimeResponse so `ctx.json` / `ctx.html` /\n// `ctx.sse` work unchanged.\n//\n// `fastify`, `@fastify/middie` are optional peers — install them alongside\n// `@forinda/kickjs` to use this subpath.\n//\n// Lifecycle note: Fastify registration (`register` / `use` / `route`) is\n// deferred until `ready()`. Connect middleware needs `@fastify/middie`\n// registered first, so `useConnect` only QUEUES middleware; `nodeHandler`\n// registers middie, then the queued middleware, then awaits `ready()`.\n\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport Fastify from 'fastify'\n\nimport { HttpException } from '../../core/errors'\nimport {\n formFields,\n hasPrototypeKey,\n parseForm,\n prototypeKeyError,\n tooLarge,\n unsupportedMediaTypeError,\n} from '../body-policy'\nimport { RequestContext } from '../context'\nimport { publishMatchedRoute, stringifyJson } from '../runtime'\nimport { applyHandlerResult } from '../reply'\nimport { requestStore } from '../request-store'\nimport { createRequestStore, disposeRequestStore } from '../middleware/request-scope'\nimport type { RequestStore } from '../request-store'\nimport { validate } from '../middleware/validate'\nimport { applyUploadConfig, type RawUploadPart } from '../middleware/upload'\nimport {\n MAX_UPLOAD_FIELDS,\n UPLOAD_FIELDS_ALLOWANCE,\n tooManyFiles,\n uploadLimits,\n} from '../middleware/upload-config'\nimport { lazyServeStatic } from './lazy-serve-static'\nimport { createLogger } from '../../core/logger'\nimport type {\n ConnectMiddleware,\n HttpRuntime,\n RouteEntry,\n RouteTable,\n RuntimeAppOptions,\n RuntimeResponse,\n UseConnectOptions,\n} from '../runtime'\n\n// The peers load through `import`, never `createRequire`: a bundler follows an\n// import, so `kick build:netlify|vercel` inlines them into the function. A\n// computed require is left for the platform to resolve, and the function has\n// no node_modules. `fastify` is static (this entry is the Fastify runtime);\n// the plugins are imported when first needed.\nconst pluginOf = (mod: { default?: unknown }): any => mod.default ?? mod\n// Typed structurally below (FastifyAppLike), as when this was required untyped.\nconst createFastify = Fastify as unknown as (options: object) => unknown\nconst log = createLogger('FastifyRuntime')\n\n// Minimal structural surface we use from Fastify — avoids a hard type dep so\n// the root package never needs `fastify` installed to typecheck.\ninterface FastifyReplyLike {\n code(statusCode: number): FastifyReplyLike\n send(payload?: unknown): FastifyReplyLike\n header(name: string, value: unknown): FastifyReplyLike\n removeHeader(name: string): FastifyReplyLike\n type(contentType: string): FastifyReplyLike\n serializer(fn: (payload: unknown) => string): FastifyReplyLike\n getHeader(name: string): unknown\n hijack(): void\n /** Hand the request to the not-found handler (Fastify 5). */\n callNotFound(): void\n readonly sent: boolean\n readonly raw: ServerResponse\n}\ninterface FastifyRequestLike {\n raw: IncomingMessage\n body?: unknown\n params?: unknown\n query?: unknown\n /** Request headers, as Fastify normalises them (lowercased keys). */\n headers?: Record<string, string | string[] | undefined>\n /** Present once @fastify/multipart is registered — async iterator of parts. */\n parts?: (options?: { limits?: Record<string, number> }) => AsyncIterableIterator<MultipartPart>\n isMultipart?: () => boolean\n}\ntype FastifyHandler = (request: FastifyRequestLike, reply: FastifyReplyLike) => void | Promise<void>\ninterface FastifyAppLike {\n close(): Promise<void>\n register(plugin: unknown, opts?: unknown): Promise<void> | FastifyAppLike\n use(path: unknown, mw?: unknown): unknown\n route(opts: { method: string; url: string; handler: FastifyHandler }): unknown\n setNotFoundHandler(handler: FastifyHandler): unknown\n setErrorHandler(\n handler: (err: unknown, req: FastifyRequestLike, reply: FastifyReplyLike) => void,\n ): unknown\n ready(): Promise<void>\n routing(req: IncomingMessage, res: ServerResponse): void\n /**\n * Fastify's content-type parser registry. Typed here rather than reached for\n * with a cast so the callback shape is checked at the call site — these\n * parsers decide what `ctx.body` is on this runtime.\n */\n addContentTypeParser?(\n matcher: string | RegExp | string[],\n opts: { parseAs: 'string' | 'buffer' },\n parser: FastifyBodyParser,\n ): unknown\n}\n\n/** The `done` callback a Fastify content-type parser calls. */\ntype FastifyParserDone = (err: Error | null, body?: unknown) => void\n\n/** `done`-style callback Fastify hands a content-type parser. */\ntype FastifyBodyParser = (\n req: FastifyRequestLike,\n body: string | Buffer,\n done: (err: Error | null, body?: unknown) => void,\n) => void\n\nconst QUEUE = Symbol('kickjs.fastify.connectQueue')\nconst READY = Symbol('kickjs.fastify.ready')\nconst NEXT = Symbol('kickjs.fastify.next')\n/** The route's request store, re-entered by the error and not-found handlers. */\nconst STORE = Symbol('kickjs.fastify.store')\n// Set during mountRoutes when any route carries @FileUpload metadata, so\n// nodeHandler knows to register @fastify/multipart before ready().\nconst NEEDS_MULTIPART = Symbol('kickjs.fastify.needsMultipart')\nconst NOOP_NEXT = (): void => {}\n\n/**\n * An async error / not-found handler that rejects never answers; answer 500\n * so the request ends instead of hanging until the client gives up.\n */\nfunction settleOrFail(reply: FastifyReplyLike, returned: unknown): void {\n if (typeof (returned as PromiseLike<void> | undefined)?.then !== 'function') return\n Promise.resolve(returned).then(undefined, () => {\n if (!reply.sent && !reply.raw.headersSent) {\n // The 500 body every engine's built-in error handler starts from.\n reply.code(500).send({ message: 'Internal Server Error' })\n }\n })\n}\n/**\n * Run `fn` in the store the matched route opened. An error before any route\n * ran (a body Fastify couldn't parse) uses the store already active, or one\n * of its own, disposed when the response closes.\n */\nfunction inRouteStore(raw: IncomingMessage, res: ServerResponse, fn: () => void): void {\n const own = (raw as { [STORE]?: RequestStore })[STORE]\n if (own) return void requestStore.run(own, fn)\n if (requestStore.getStore()) return fn()\n const header = raw.headers['x-request-id']\n const store = createRequestStore(\n (raw as { requestId?: string }).requestId || (Array.isArray(header) ? header[0] : header),\n )\n res.once('close', () => disposeRequestStore(store))\n requestStore.run(store, fn)\n}\n\n/** `notFoundFallthrough: false` — answer unmatched requests instead of handing them back. */\nconst NO_FALLTHROUGH = Symbol('kickjs.fastify.noFallthrough')\n\n/**\n * @fastify/multipart's limit errors as the exceptions every engine raises —\n * the same status and message as `applyUploadConfig` and the web runtime.\n */\nfunction multipartError(\n err: unknown,\n limits: { fileSize: number; files: number },\n file: string,\n): unknown {\n switch ((err as { code?: string } | null)?.code) {\n case 'FST_REQ_FILE_TOO_LARGE':\n return new HttpException(413, `File ${file} exceeds the ${limits.fileSize}-byte limit`)\n case 'FST_FILES_LIMIT':\n return tooManyFiles(limits.files)\n case 'FST_FIELDS_LIMIT':\n case 'FST_PARTS_LIMIT':\n return new HttpException(413, 'Too many form fields')\n case 'FST_PROTO_VIOLATION':\n return prototypeKeyError()\n default:\n return err\n }\n}\n\n// A @fastify/multipart part as we consume it from `request.parts()`.\ninterface MultipartPart {\n type: 'file' | 'field'\n fieldname: string\n filename?: string\n mimetype?: string\n value?: unknown\n toBuffer?: () => Promise<Buffer>\n}\n\n/**\n * Wrap a Fastify reply so the RequestContext response helpers drive it.\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 FastifyReplyDriver implements RuntimeResponse {\n constructor(private readonly reply: FastifyReplyLike) {}\n status(code: number): this {\n this.reply.code(code)\n return this\n }\n json(data: unknown): this {\n // A custom serializer drops Fastify's default content-type; keep one the\n // caller chose (`application/problem+json`).\n if (!this.reply.getHeader('content-type')) this.reply.type('application/json; charset=utf-8')\n this.reply.serializer(stringifyJson).send(data)\n return this\n }\n send(data: unknown): this {\n this.reply.send(data)\n return this\n }\n type(contentType: string): this {\n this.reply.type(contentType)\n return this\n }\n getHeader(name: string): unknown {\n return this.reply.getHeader(name)\n }\n setHeader(name: string, value: unknown): this {\n // Replace, as node's `res.setHeader` and the web driver do. Fastify's\n // `header()` appends for `set-cookie`, so `setCookie()` — which passes the\n // whole list each time — sent the first cookie twice.\n this.reply.removeHeader(name)\n this.reply.header(name, value)\n return this\n }\n render(): never {\n throw new Error('ctx.render() is not supported on the Fastify runtime (no view engine).')\n }\n writeHead(statusCode: number, headers?: Record<string, string | number | string[]>): this {\n // Streaming / SSE: take over the raw socket so Fastify doesn't try to\n // serialize a reply we're writing by hand.\n this.reply.hijack()\n this.reply.raw.writeHead(statusCode, headers)\n return this\n }\n flushHeaders(): this {\n ;(this.reply.raw as ServerResponse & { flushHeaders?: () => void }).flushHeaders?.()\n return this\n }\n write(chunk: unknown): boolean {\n return this.reply.raw.write(chunk as never)\n }\n end(data?: unknown): this {\n // After writeHead (streaming, SSE) the reply is hijacked and the raw\n // socket is ours to finish. Otherwise finish through the reply, so the\n // status and headers set on it are sent — `ctx.redirect()` writes its\n // Location with setHeader() and then calls end().\n if (this.reply.raw.headersSent) this.reply.raw.end(data as never)\n else this.reply.send(data ?? '')\n return this\n }\n once(event: string, listener: (...args: unknown[]) => void): this {\n this.reply.raw.once(event, listener)\n return this\n }\n get headersSent(): boolean {\n return this.reply.sent || this.reply.raw.headersSent\n }\n}\n\nfunction replyDriver(reply: FastifyReplyLike): RuntimeResponse {\n return new FastifyReplyDriver(reply) as unknown as RuntimeResponse\n}\n\n/** Build the Fastify per-route handler that runs the kickjs pipeline. */\nfunction routeHandler(entry: RouteEntry): FastifyHandler {\n // Validation middleware is built ONCE per route (parity with the Express\n // materializer) — `validate()` constructs a fresh closure, so calling it\n // per request was pure allocation waste.\n const validator = entry.meta.validation\n ? validate(entry.meta.validation, { validationError: entry.validationError })\n : undefined\n return async (request, reply) => {\n // Fastify runs the route handler OUTSIDE the connect-middleware chain, so\n // (unlike Express) the requestScopeMiddleware ALS frame isn't active here.\n // Establish it around the pipeline so REQUEST-scoped DI, contributors, and\n // ctx.set/get work. Reuse the inbound x-request-id, or the id a connect\n // middleware (requestId / requestScope, run earlier via middie) already\n // stamped on the raw request, before generating a fresh one.\n // Use the raw node request as `ctx.req`: it natively provides the stream\n // events (`on('close')` / `once`) that SSE and `ctx.signal` need — Fastify's\n // request object doesn't. Copy Fastify's parsed body/params/query onto it so\n // `ctx.body` / `ctx.params` / `ctx.query` keep working.\n const raw = request.raw as IncomingMessage & {\n requestId?: string\n body?: unknown\n params?: unknown\n query?: unknown\n file?: unknown\n files?: unknown\n }\n raw.body = request.body\n raw.params = request.params\n raw.query = request.query\n\n // @FileUpload: buffer multipart parts into the multer-shaped file(s) that\n // `ctx.file` / `ctx.files` expose. Fastify doesn't parse multipart natively\n // — @fastify/multipart (registered in nodeHandler when any route needs it)\n // provides `request.parts()`. Non-file fields are merged onto `raw.body` so\n // validation / `ctx.body` see them, matching multer's req.body behavior.\n if (entry.meta.upload && entry.meta.upload.mode !== 'none') {\n if (typeof request.parts !== 'function') {\n throw new Error(\n \"@forinda/kickjs: @FileUpload on the Fastify runtime requires '@fastify/multipart'.\\n\" +\n 'Install it as a peer dependency: pnpm add @fastify/multipart.',\n )\n }\n // The parser stops at the route's limits instead of buffering whatever\n // arrives: a file past maxSize, or more files than the route takes, is a 413.\n const limits = uploadLimits(entry.meta.upload)\n const rawParts: RawUploadPart[] = []\n const fields: Array<[string, string]> = []\n let current = 'file'\n // Per-part limits alone allow many parts; the whole body is held to the\n // route's budget too, the same total h3 and the web entry read at most.\n let received = 0\n const count = (bytes: number) => {\n received += bytes\n if (received > limits.total) {\n throw tooLarge(limits.total)\n }\n }\n try {\n for await (const part of request.parts({\n limits: {\n fileSize: limits.fileSize,\n files: limits.files,\n fields: MAX_UPLOAD_FIELDS,\n fieldSize: UPLOAD_FIELDS_ALLOWANCE,\n },\n })) {\n if (part.type === 'file' && part.toBuffer) {\n current = part.filename ?? part.fieldname\n const buffer = await part.toBuffer()\n count(buffer.length)\n rawParts.push({\n fieldname: part.fieldname,\n filename: part.filename ?? '',\n mimetype: part.mimetype ?? 'application/octet-stream',\n buffer,\n })\n } else {\n const value = String(part.value)\n count(Buffer.byteLength(part.fieldname) + Buffer.byteLength(value))\n fields.push([part.fieldname, value])\n }\n }\n } catch (err) {\n throw multipartError(err, limits, current)\n }\n const { file, files } = applyUploadConfig(rawParts, entry.meta.upload)\n raw.file = file\n raw.files = files\n raw.body = { ...(raw.body as Record<string, unknown> | undefined), ...formFields(fields) }\n }\n\n // A key that could rewrite a prototype — refused before any of the app's code sees it.\n if (hasPrototypeKey(raw.body)) throw prototypeKeyError()\n\n const headerId = raw.headers['x-request-id']\n // An id already assigned (requestId() middleware) wins over the header,\n // as on Express and h3.\n const requestId = raw.requestId || (Array.isArray(headerId) ? headerId[0] : headerId)\n const store = createRequestStore(requestId)\n // Propagate the resolved id back onto the raw request so anything reading\n // `req.requestId` inside the frame (e.g. request-logger) matches the store\n // and the X-Request-Id response header — parity with Express.\n raw.requestId = store.requestId\n ;(raw as { [STORE]?: RequestStore })[STORE] = store\n if (!reply.getHeader('x-request-id')) reply.header('x-request-id', store.requestId)\n\n // @PreDestroy teardown for REQUEST-scoped instances once the response\n // closes (finished or aborted) — parity with requestScopeMiddleware.\n reply.raw.once('close', () => disposeRequestStore(store))\n\n await requestStore.run(store, async () => {\n publishMatchedRoute(raw, entry)\n const ctx = new RequestContext(raw as never, reply as never, NOOP_NEXT, replyDriver(reply))\n\n // `beforeValidation` contributors (#677) — ahead of validation and middleware.\n if (entry.earlyContributorRunner) {\n await entry.earlyContributorRunner(ctx)\n if (reply.sent) return\n }\n\n // Validation (from @Get(path, schema) / route.validation). `validator` is a\n // connect-style middleware built once at route registration; it mutates\n // req.body/query/params to the parsed value and calls next(err) on failure\n // — it never touches `res`, so it runs cleanly here. A rejection\n // propagates to the error handler (422).\n if (validator) {\n await new Promise<void>((resolve, reject) => {\n validator(raw as never, undefined as never, (err?: unknown) =>\n err ? reject(err) : resolve(),\n )\n })\n }\n\n // Class + method middleware — `(ctx, next)`; await each, stop if it ended\n // the response or called next(err).\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 || reply.sent) return\n }\n\n if (entry.contributorRunner) await entry.contributorRunner(ctx)\n if (reply.sent) return\n const result = await entry.handler(ctx)\n // Return-value handlers (reply.ts): auto-send when nothing was written.\n // Nothing written and nothing returned falls through to the 404 handler,\n // as on Express and h3 — not Fastify's own empty 200.\n if (!reply.sent && !(await applyHandlerResult(ctx, result))) reply.callNotFound()\n })\n }\n}\n\n/** Express's `trust proxy` number: trust the first `hops` addresses from the socket. */\nfunction hopTrust(hops: number): (ip: string, hopIndex: number) => boolean {\n return (_ip, hopIndex) => hopIndex < hops\n}\n\n/**\n * The Fastify HTTP runtime. Pass to `bootstrap({ runtime: fastifyRuntime() })`.\n * Per spec §10: Fastify's built-in pino logger is disabled (`logger: false`) so\n * the kickjs `requestLogger` middleware stays the single log format.\n */\nexport function fastifyRuntime(): HttpRuntime<FastifyAppLike> {\n return {\n name: 'fastify',\n\n createApp(options: RuntimeAppOptions = {}): FastifyAppLike {\n const app = createFastify({\n logger: false,\n // Match Express / h3 routing leniency: `/api/v1/hello` and\n // `/api/v1/hello/` resolve to the same route. Without this, Fastify's\n // strict router 404s a trailing-slash request — e.g. a controller's\n // root `@Get('/')` (mounted at the prefix) misses `${prefix}/`. Set under\n // `routerOptions` (Fastify 5+; top-level `ignoreTrailingSlash` is\n // deprecated, removed in Fastify 6).\n routerOptions: { ignoreTrailingSlash: true },\n // `jsonLimit`, which Fastify otherwise ignores in favour of its own 1 MiB.\n ...(options.bodyLimit !== undefined ? { bodyLimit: options.bodyLimit } : {}),\n // Express semantics for every form. Fastify takes a predicate as-is,\n // but reads a hop count as \"trust nothing\", where Express trusts that\n // many hops from the socket.\n trustProxy:\n typeof options.trustProxy === 'number'\n ? hopTrust(options.trustProxy)\n : options.trustProxy,\n }) as FastifyAppLike & {\n [QUEUE]?: Array<{ mw: ConnectMiddleware; opts?: UseConnectOptions }>\n }\n app[QUEUE] = []\n\n // Fastify ships parsers for `application/json` and `text/plain` only, and\n // answers 415 for everything else. That made a form post work on Express\n // and h3 but fail on Fastify alone (#590). Register the rest of the\n // framework's supported set so all engines agree.\n //\n // Deliberately NOT a `'*'` catch-all: that would swallow multipart, and\n // `@fastify/multipart` is itself the multipart content-type parser,\n // registered conditionally in `nodeHandler` when a route needs it.\n const addParser = app.addContentTypeParser?.bind(app)\n if (addParser) {\n // `application/*+json` — RFC 6838 §4.2.8 guarantees the bytes are JSON.\n addParser(\n /^application\\/[\\w.+-]+\\+json$/,\n { parseAs: 'string' },\n (_req: FastifyRequestLike, body: string | Buffer, done: FastifyParserDone) => {\n if (body === '') return done(null, undefined)\n try {\n done(null, JSON.parse(body as string))\n } catch (err) {\n // A bare SyntaxError carries no status, so the shared error handler\n // would call it a 500 — Fastify's own JSON parser answers 400\n // (FST_ERR_CTP_INVALID_JSON_BODY), and so must this one.\n done(\n HttpException.badRequest(\n err instanceof Error ? err.message : 'Request body could not be parsed',\n ),\n undefined,\n )\n }\n },\n )\n addParser(\n 'application/x-www-form-urlencoded',\n { parseAs: 'string' },\n (_req: FastifyRequestLike, body: string | Buffer, done: FastifyParserDone) => {\n done(null, parseForm(body as string))\n },\n )\n // `text/*` beyond Fastify's built-in `text/plain`. Raw string, never\n // JSON: `text/plain` is CORS-safelisted, so parsing it as JSON would\n // re-open no-preflight CSRF against a JSON API.\n addParser(\n /^text\\//,\n { parseAs: 'string' },\n (_req: FastifyRequestLike, body: string | Buffer, done: FastifyParserDone) => {\n done(null, body)\n },\n )\n // Fastify already answers 415 for a type it has no parser for, but with\n // its own message and no `Accept`. `'*'` is Fastify's documented\n // fallback — consulted only when nothing more specific matches — so it\n // does not shadow the parsers above, nor `@fastify/multipart`, which\n // registers `multipart/form-data` when an upload route needs it.\n addParser(\n '*',\n { parseAs: 'string' },\n (req: FastifyRequestLike, body: string | Buffer, done: FastifyParserDone) => {\n // No body is not an unsupported body. Fastify calls the parser even\n // for an empty payload, so without this a bodyless POST carrying an\n // unrelated content type would be rejected.\n if (!body) return done(null, undefined)\n done(unsupportedMediaTypeError(req.headers?.['content-type']), undefined)\n },\n )\n }\n\n if (options.notFoundFallthrough === false) {\n ;(app as { [NO_FALLTHROUGH]?: boolean })[NO_FALLTHROUGH] = true\n }\n return app\n },\n\n nodeHandler(app) {\n // Register middie + queued connect middleware + finalize `ready()` exactly\n // ONCE per app, even though Application may call nodeHandler per request.\n const state = app as {\n [QUEUE]?: Array<{ mw: ConnectMiddleware; opts?: UseConnectOptions }>\n [READY]?: Promise<void>\n [NEEDS_MULTIPART]?: boolean\n }\n if (!state[READY]) {\n state[READY] = (async () => {\n // Register @fastify/multipart first when any route uses @FileUpload so\n // `request.parts()` is available. Our applyUploadConfig enforces the\n // real per-file maxSize, so give the plugin a generous fileSize ceiling\n // (its 1MB default would silently truncate larger uploads first).\n if (state[NEEDS_MULTIPART]) {\n const multipart = pluginOf(await import('@fastify/multipart'))\n await app.register(multipart, { limits: { fileSize: Number.MAX_SAFE_INTEGER } })\n }\n const middie = pluginOf(await import('@fastify/middie'))\n await app.register(middie)\n for (const { mw, opts } of state[QUEUE] ?? []) {\n if (opts?.path !== undefined)\n (app.use as (p: unknown, m: unknown) => void)(opts.path, mw)\n else (app.use as (m: unknown) => void)(mw)\n }\n await app.ready()\n })()\n }\n const readyP = state[READY]\n // Once ready, route synchronously — no promise hop per request.\n let ready = false\n readyP.then(\n () => (ready = true),\n () => {},\n )\n\n return (req: IncomingMessage, res: ServerResponse, next?: (err?: unknown) => void) => {\n if (next) (req as IncomingMessage & { [NEXT]?: (err?: unknown) => void })[NEXT] = next\n if (ready) {\n app.routing(req, res)\n return\n }\n readyP\n .then(() => app.routing(req, res))\n .catch((err) => {\n if (next) return next(err)\n // No host to hand the error to: answer rather than leave the request open.\n log.error(err, 'Fastify failed to start')\n res.statusCode = 500\n res.end('Internal Server Error')\n })\n }\n },\n\n mountRoutes(app, table: RouteTable) {\n for (const { mountPath, routes } of table) {\n for (const entry of routes) {\n if (entry.meta.upload) (app as { [NEEDS_MULTIPART]?: boolean })[NEEDS_MULTIPART] = true\n const url = joinPath(mountPath, entry.path)\n app.route({ method: entry.method, url, handler: routeHandler(entry) })\n }\n }\n },\n\n useConnect(app, mw: ConnectMiddleware, opts?: UseConnectOptions) {\n const queue = (\n app as { [QUEUE]?: Array<{ mw: ConnectMiddleware; opts?: UseConnectOptions }> }\n )[QUEUE]\n queue?.push({ mw, opts })\n },\n\n serveStatic(app, prefix, dir) {\n // Serve via `serve-static` (the standalone connect middleware behind\n // express.static) so the Fastify runtime carries no `express` dependency —\n // queued like any other connect middleware, bridged through middie.\n this.useConnect(app, lazyServeStatic(dir), { path: prefix })\n },\n\n setNotFound(app, mw: ConnectMiddleware) {\n app.setNotFoundHandler((request, reply) => {\n const next = (request.raw as IncomingMessage & { [NEXT]?: (err?: unknown) => void })[NEXT]\n if (next && !(app as { [NO_FALLTHROUGH]?: boolean })[NO_FALLTHROUGH]) {\n // Vite dev fall-through: hand the request back to the outer chain.\n reply.hijack()\n next()\n return\n }\n // Pass the reply DRIVER (not raw res) so the connect-style\n // notFoundHandler's `res.status().json()` lands on the Fastify reply.\n // In the route's store when a route handed over (`callNotFound()`).\n inRouteStore(request.raw, reply.raw, () =>\n settleOrFail(\n reply,\n (mw as (req: unknown, res: unknown, next: () => void) => unknown)(\n request.raw,\n replyDriver(reply),\n NOOP_NEXT,\n ),\n ),\n )\n })\n },\n\n setErrorHandler(app, mw: ConnectMiddleware) {\n app.setErrorHandler((err, request, reply) => {\n // Reply driver (not raw res) so the connect-style errorHandler's\n // `res.status().json()` / `setHeader` land on the Fastify reply.\n // In the route's store: Fastify calls this outside it, and an error\n // page should see the handler's ctx values and REQUEST-scoped instances.\n inRouteStore(request.raw, reply.raw, () =>\n settleOrFail(\n reply,\n (mw as (e: unknown, req: unknown, res: unknown, next: () => void) => unknown)(\n err,\n request.raw,\n replyDriver(reply),\n NOOP_NEXT,\n ),\n ),\n )\n })\n },\n\n close(app) {\n // Runs the instance's onClose hooks (plugins registered on it).\n return app.close()\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 Fastify runtime's engine-native types — what the runtime-typed escape\n * hatches resolve to once the `kick/runtime` typegen emits a `KickRuntimeRegister`\n * augmentation pointing here (spec §4.3b). `AdapterContext.app` / `getRuntimeApp()`\n * become `FastifyInstance`; `ctx.req` / `ctx.res` the Fastify request / reply.\n * Mirrors {@link import('../runtime').ExpressRuntimeTypes} for the default engine.\n */\nexport interface FastifyRuntimeTypes {\n request: import('fastify').FastifyRequest\n response: import('fastify').FastifyReply\n app: import('fastify').FastifyInstance\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 // A root route path ('/' or '') maps to the mount prefix itself — otherwise a\n // controller `@Post('/')` would register at `${prefix}/`, and a request to\n // `${prefix}` (no trailing slash) wouldn't match under Fastify's strict router.\n if (path === '/' || path === '') return a === '' ? '/' : a\n const b = path.startsWith('/') ? path : `/${path}`\n return `${a}${b}`\n}\n"],"mappings":";;;;;;;;;;q8BA2DA,MAAM,SAAY,KAAoC,IAAI,SAAW,IAE/D,cAAgB,QAChB,IAAM,aAAa,gBAAgB,EA+DnC,MAAQ,OAAO,6BAA6B,EAC5C,MAAQ,OAAO,sBAAsB,EACrC,KAAO,OAAO,qBAAqB,EAEnC,MAAQ,OAAO,sBAAsB,EAGrC,gBAAkB,OAAO,+BAA+B,EACxD,cAAwB,CAAC,EAM/B,SAAS,aAAa,MAAyB,SAAyB,CAClE,OAAQ,UAA4C,MAAS,YACjE,QAAQ,QAAQ,QAAQ,CAAC,CAAC,KAAK,IAAA,OAAiB,CAC1C,CAAC,MAAM,MAAQ,CAAC,MAAM,IAAI,aAE5B,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK,CAAE,QAAS,uBAAwB,CAAC,CAE7D,CAAC,CACH,CAMA,SAAS,aAAa,IAAsB,IAAqB,GAAsB,CACrF,IAAM,IAAO,IAAmC,OAChD,GAAI,IAAK,OAAO,KAAK,aAAa,IAAI,IAAK,EAAE,EAC7C,GAAI,aAAa,SAAS,EAAG,OAAO,GAAG,EACvC,IAAM,OAAS,IAAI,QAAQ,gBACrB,MAAQ,mBACX,IAA+B,YAAc,MAAM,QAAQ,MAAM,EAAI,OAAO,GAAK,OACpF,EACA,IAAI,KAAK,YAAe,oBAAoB,KAAK,CAAC,EAClD,aAAa,IAAI,MAAO,EAAE,CAC5B,CAGA,MAAM,eAAiB,OAAO,8BAA8B,EAM5D,SAAS,eACP,IACA,OACA,KACS,CACT,OAAS,KAAkC,KAA3C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forinda/kickjs v10.13.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -1,5 +1,5 @@
1
1
 
2
- import { d as HttpRuntime } from "../../adapter-DiJfCKXU.mjs";
2
+ import { d as HttpRuntime } from "../../adapter-g_vQffKr.mjs";
3
3
  import { IncomingMessage, ServerResponse } from "node:http";
4
4
  //#region src/http/runtimes/h3.d.ts
5
5
  interface H3AppLike {