@forinda/kickjs 10.14.2 → 10.15.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 (270) hide show
  1. package/dist/{adapter-B64IOivZ.d.mts → adapter-D_nUmKEQ.d.mts} +172 -34
  2. package/dist/adapter-D_nUmKEQ.d.mts.map +1 -0
  3. package/dist/{allowed-hosts-U12_gESr.d.mts → allowed-hosts-BQlQFt-1.d.mts} +6 -1
  4. package/dist/allowed-hosts-BQlQFt-1.d.mts.map +1 -0
  5. package/dist/{app-module-EmIojM4d.d.mts → app-module-BmViGLgj.d.mts} +5 -5
  6. package/dist/{app-module-EmIojM4d.d.mts.map → app-module-BmViGLgj.d.mts.map} +1 -1
  7. package/dist/application-B16ltRnC.mjs +14 -0
  8. package/dist/application-B16ltRnC.mjs.map +1 -0
  9. package/dist/{application-CGcY8SZZ.d.mts → application-ClCq0AgY.d.mts} +190 -53
  10. package/dist/application-ClCq0AgY.d.mts.map +1 -0
  11. package/dist/{body-policy-Be3Y0hjq.mjs → body-policy-D8LveWmO.mjs} +2 -2
  12. package/dist/{body-policy-Be3Y0hjq.mjs.map → body-policy-D8LveWmO.mjs.map} +1 -1
  13. package/dist/{bootstrap-Bvk3BWJX.mjs → bootstrap-C5NvsxHQ.mjs} +3 -3
  14. package/dist/bootstrap-C5NvsxHQ.mjs.map +1 -0
  15. package/dist/{bounded-counters-Bh5jeT9I.mjs → bounded-counters-BtvB2daV.mjs} +2 -2
  16. package/dist/{bounded-counters-Bh5jeT9I.mjs.map → bounded-counters-BtvB2daV.mjs.map} +1 -1
  17. package/dist/{breach-padding-DfT9MXGb.d.mts → breach-padding-BUuc21Eu.d.mts} +6 -1
  18. package/dist/breach-padding-BUuc21Eu.d.mts.map +1 -0
  19. package/dist/{cache-DMIt3c6M.d.mts → cache-ByX5O2Hp.d.mts} +26 -1
  20. package/dist/{cache-DMIt3c6M.d.mts.map → cache-ByX5O2Hp.d.mts.map} +1 -1
  21. package/dist/{client-ip-CGH_IvnC.mjs → client-ip-CWvyHmqt.mjs} +2 -2
  22. package/dist/{client-ip-CGH_IvnC.mjs.map → client-ip-CWvyHmqt.mjs.map} +1 -1
  23. package/dist/config/index.d.mts +6 -1
  24. package/dist/config/index.mjs +2 -2
  25. package/dist/{config-CjFxvh0v.mjs → config-BIQoDNil.mjs} +3 -3
  26. package/dist/{config-CjFxvh0v.mjs.map → config-BIQoDNil.mjs.map} +1 -1
  27. package/dist/container-DtdUiRwr.d.mts +3 -0
  28. package/dist/{context-BvZLaTeE.mjs → context-BzFNflxV.mjs} +3 -3
  29. package/dist/context-BzFNflxV.mjs.map +1 -0
  30. package/dist/{context-errors-BZVS0B1O.mjs → context-errors-BmaG4vwd.mjs} +2 -2
  31. package/dist/context-errors-BmaG4vwd.mjs.map +1 -0
  32. package/dist/{contributor-runner-fdKy6Tme.mjs → contributor-runner-BnJzu2GI.mjs} +3 -3
  33. package/dist/contributor-runner-BnJzu2GI.mjs.map +1 -0
  34. package/dist/core/adapter.d.mts +1 -1
  35. package/dist/core/adapter.mjs +1 -1
  36. package/dist/core/app-module.d.mts +1 -1
  37. package/dist/core/app-module.mjs +1 -1
  38. package/dist/core/cache.d.mts +1 -1
  39. package/dist/core/cache.mjs +1 -1
  40. package/dist/core/cache.mjs.map +1 -1
  41. package/dist/core/container.d.mts +1 -1
  42. package/dist/core/container.mjs +2 -2
  43. package/dist/core/cron.d.mts +1 -1
  44. package/dist/core/cron.mjs +2 -2
  45. package/dist/core/cron.mjs.map +1 -1
  46. package/dist/core/decorators.d.mts +1 -1
  47. package/dist/core/decorators.mjs +2 -2
  48. package/dist/core/decorators.mjs.map +1 -1
  49. package/dist/core/errors.d.mts +1 -1
  50. package/dist/core/errors.mjs +1 -1
  51. package/dist/core/errors.mjs.map +1 -1
  52. package/dist/core/interfaces.d.mts +1 -1
  53. package/dist/core/interfaces.mjs +1 -1
  54. package/dist/core/logger.d.mts +1 -1
  55. package/dist/core/logger.mjs +1 -1
  56. package/dist/core/logger.mjs.map +1 -1
  57. package/dist/core/path.mjs +1 -1
  58. package/dist/core/plugin.d.mts +1 -1
  59. package/dist/core/plugin.mjs +1 -1
  60. package/dist/core/reactivity.d.mts +1 -1
  61. package/dist/core/reactivity.mjs +2 -2
  62. package/dist/core/reactivity.mjs.map +1 -1
  63. package/dist/core-Dqzah_BX.mjs +12 -0
  64. package/dist/core-Dqzah_BX.mjs.map +1 -0
  65. package/dist/{cors-J-q6PuSU.d.mts → cors-u1OwTxQ8.d.mts} +6 -1
  66. package/dist/cors-u1OwTxQ8.d.mts.map +1 -0
  67. package/dist/{cron-DGV1AE0R.d.mts → cron-Bxm2MY8u.d.mts} +10 -1
  68. package/dist/cron-Bxm2MY8u.d.mts.map +1 -0
  69. package/dist/{csrf-DjtJPgA3.d.mts → csrf-8-Jknvmc.d.mts} +12 -2
  70. package/dist/csrf-8-Jknvmc.d.mts.map +1 -0
  71. package/dist/{decorate-DRbXCNQz.mjs → decorate-C3to8dG-.mjs} +3 -3
  72. package/dist/{decorate-DRbXCNQz.mjs.map → decorate-C3to8dG-.mjs.map} +1 -1
  73. package/dist/{decorators-BAD8qjuq.d.mts → decorators-Bflncyz6.d.mts} +122 -6
  74. package/dist/decorators-Bflncyz6.d.mts.map +1 -0
  75. package/dist/{define-adapter-DMo6og81.mjs → define-adapter-DCjNTP6m.mjs} +2 -2
  76. package/dist/define-adapter-DCjNTP6m.mjs.map +1 -0
  77. package/dist/{di-hooks-DCqt2yJ9.mjs → di-hooks-DTDy7ABs.mjs} +2 -2
  78. package/dist/di-hooks-DTDy7ABs.mjs.map +1 -0
  79. package/dist/{disposables-BsdVu69-.mjs → disposables-BC291ukb.mjs} +1 -1
  80. package/dist/{driver-oZBQDJZz.mjs → driver-D59oWDec.mjs} +3 -3
  81. package/dist/{driver-oZBQDJZz.mjs.map → driver-D59oWDec.mjs.map} +1 -1
  82. package/dist/{error-handler-Dl_gZRNK.d.mts → error-handler-gZLQFHeE.d.mts} +2 -2
  83. package/dist/{error-handler-Dl_gZRNK.d.mts.map → error-handler-gZLQFHeE.d.mts.map} +1 -1
  84. package/dist/{errors-DZGuPLoZ.d.mts → errors-CppqPy0A.d.mts} +2 -1
  85. package/dist/errors-CppqPy0A.d.mts.map +1 -0
  86. package/dist/{express-f9CTA8qO.mjs → express-JAXx9MK0.mjs} +3 -3
  87. package/dist/{express-f9CTA8qO.mjs.map → express-JAXx9MK0.mjs.map} +1 -1
  88. package/dist/{express-lazy-DMxcLBpT.mjs → express-lazy-jIFBeDpY.mjs} +3 -3
  89. package/dist/{express-lazy-DMxcLBpT.mjs.map → express-lazy-jIFBeDpY.mjs.map} +1 -1
  90. package/dist/{handler-B66laQY0.mjs → handler-C8iAD_xz.mjs} +3 -3
  91. package/dist/{handler-B66laQY0.mjs.map → handler-C8iAD_xz.mjs.map} +1 -1
  92. package/dist/{helmet-Rwkbp9IS.d.mts → helmet-1H0LKr6y.d.mts} +6 -1
  93. package/dist/helmet-1H0LKr6y.d.mts.map +1 -0
  94. package/dist/{host-DalMsn5Z.mjs → host-Crxmi91N.mjs} +2 -2
  95. package/dist/{host-DalMsn5Z.mjs.map → host-Crxmi91N.mjs.map} +1 -1
  96. package/dist/http/application.d.mts +1 -1
  97. package/dist/http/application.mjs +2 -2
  98. package/dist/http/bootstrap.d.mts +1 -1
  99. package/dist/http/bootstrap.mjs +2 -2
  100. package/dist/http/context.d.mts +2 -2
  101. package/dist/http/context.mjs +2 -2
  102. package/dist/http/middleware/allowed-hosts.d.mts +1 -1
  103. package/dist/http/middleware/allowed-hosts.mjs +2 -2
  104. package/dist/http/middleware/allowed-hosts.mjs.map +1 -1
  105. package/dist/http/middleware/breach-padding.d.mts +1 -1
  106. package/dist/http/middleware/breach-padding.mjs +1 -1
  107. package/dist/http/middleware/breach-padding.mjs.map +1 -1
  108. package/dist/http/middleware/cors.d.mts +1 -1
  109. package/dist/http/middleware/cors.mjs +1 -1
  110. package/dist/http/middleware/cors.mjs.map +1 -1
  111. package/dist/http/middleware/csrf.d.mts +1 -1
  112. package/dist/http/middleware/csrf.mjs +2 -2
  113. package/dist/http/middleware/csrf.mjs.map +1 -1
  114. package/dist/http/middleware/error-handler.d.mts +1 -1
  115. package/dist/http/middleware/error-handler.mjs +2 -2
  116. package/dist/http/middleware/helmet.d.mts +1 -1
  117. package/dist/http/middleware/helmet.mjs +1 -1
  118. package/dist/http/middleware/helmet.mjs.map +1 -1
  119. package/dist/http/middleware/rate-limit.d.mts +1 -1
  120. package/dist/http/middleware/rate-limit.mjs +2 -2
  121. package/dist/http/middleware/rate-limit.mjs.map +1 -1
  122. package/dist/http/middleware/request-id.d.mts +1 -1
  123. package/dist/http/middleware/request-id.mjs +1 -1
  124. package/dist/http/middleware/request-id.mjs.map +1 -1
  125. package/dist/http/middleware/request-logger.d.mts +1 -1
  126. package/dist/http/middleware/request-logger.mjs +2 -2
  127. package/dist/http/middleware/request-logger.mjs.map +1 -1
  128. package/dist/http/middleware/session.d.mts +1 -1
  129. package/dist/http/middleware/session.mjs +2 -2
  130. package/dist/http/middleware/session.mjs.map +1 -1
  131. package/dist/http/middleware/spa.d.mts +1 -1
  132. package/dist/http/middleware/spa.mjs +2 -2
  133. package/dist/http/middleware/spa.mjs.map +1 -1
  134. package/dist/http/middleware/upload.d.mts +2 -2
  135. package/dist/http/middleware/upload.mjs +2 -2
  136. package/dist/http/middleware/upload.mjs.map +1 -1
  137. package/dist/http/middleware/validate.d.mts +1 -1
  138. package/dist/http/middleware/validate.mjs +1 -1
  139. package/dist/http/middleware/views.d.mts +1 -1
  140. package/dist/http/middleware/views.mjs +2 -2
  141. package/dist/http/middleware/views.mjs.map +1 -1
  142. package/dist/http/query/index.d.mts +1 -1
  143. package/dist/http/query/index.mjs +2 -2
  144. package/dist/http/router-builder.d.mts +1 -1
  145. package/dist/http/router-builder.mjs +2 -2
  146. package/dist/http/runtimes/express.d.mts +3 -2
  147. package/dist/http/runtimes/express.d.mts.map +1 -1
  148. package/dist/http/runtimes/express.mjs +2 -2
  149. package/dist/http/runtimes/fastify.d.mts +3 -3
  150. package/dist/http/runtimes/fastify.mjs +2 -2
  151. package/dist/http/runtimes/fastify.mjs.map +1 -1
  152. package/dist/http/runtimes/h3-web.mjs +1 -1
  153. package/dist/http/runtimes/h3.d.mts +1 -1
  154. package/dist/http/runtimes/h3.mjs +2 -2
  155. package/dist/http/runtimes/h3.mjs.map +1 -1
  156. package/dist/{index-ZbCnCyQx.d.mts → index-CtjmSXFy.d.mts} +11 -1
  157. package/dist/index-CtjmSXFy.d.mts.map +1 -0
  158. package/dist/{index-CFTwnev9.d.mts → index-DoukvKwh.d.mts} +2 -2
  159. package/dist/{index-CFTwnev9.d.mts.map → index-DoukvKwh.d.mts.map} +1 -1
  160. package/dist/index.d.mts +34 -28
  161. package/dist/index.mjs +2 -2
  162. package/dist/index.mjs.map +1 -1
  163. package/dist/{interfaces-BQhYh3lL.d.mts → interfaces-CvO9sAea.d.mts} +3 -3
  164. package/dist/{interfaces-BQhYh3lL.d.mts.map → interfaces-CvO9sAea.d.mts.map} +1 -1
  165. package/dist/{is-production-9QzMIRuO.mjs → is-production-LziEMGrc.mjs} +2 -2
  166. package/dist/{is-production-9QzMIRuO.mjs.map → is-production-LziEMGrc.mjs.map} +1 -1
  167. package/dist/{jobs-CuZqVDDG.mjs → jobs-D7ToA0yF.mjs} +3 -3
  168. package/dist/jobs-D7ToA0yF.mjs.map +1 -0
  169. package/dist/{kv-stores-wTD3VDPB.d.mts → kv-stores-DdGPLXQG.d.mts} +32 -7
  170. package/dist/kv-stores-DdGPLXQG.d.mts.map +1 -0
  171. package/dist/{kv-stores-C9CJ3xCB.mjs → kv-stores-DpM57Xr5.mjs} +3 -3
  172. package/dist/kv-stores-DpM57Xr5.mjs.map +1 -0
  173. package/dist/{lazy-serve-static-DVWmKM7Z.mjs → lazy-serve-static-DxI2K-zs.mjs} +3 -3
  174. package/dist/{lazy-serve-static-DVWmKM7Z.mjs.map → lazy-serve-static-DxI2K-zs.mjs.map} +1 -1
  175. package/dist/{logger-BL8MiSrm.d.mts → logger-ByJsVwqY.d.mts} +3 -3
  176. package/dist/{logger-BL8MiSrm.d.mts.map → logger-ByJsVwqY.d.mts.map} +1 -1
  177. package/dist/{metadata-BZRtQog3.mjs → metadata-nTTSnVTO.mjs} +1 -1
  178. package/dist/{observers-B4VnKAHK.mjs → observers-fQtCIKLq.mjs} +2 -2
  179. package/dist/observers-fQtCIKLq.mjs.map +1 -0
  180. package/dist/{precompressed-AxF66Ls0.mjs → precompressed-BtwmgzyS.mjs} +2 -2
  181. package/dist/{precompressed-AxF66Ls0.mjs.map → precompressed-BtwmgzyS.mjs.map} +1 -1
  182. package/dist/{query-BwUR-ssX.mjs → query-Dr28oT30.mjs} +2 -2
  183. package/dist/query-Dr28oT30.mjs.map +1 -0
  184. package/dist/{rate-limit-DMiV6bAq.d.mts → rate-limit-BQx_P6gG.d.mts} +11 -1
  185. package/dist/rate-limit-BQx_P6gG.d.mts.map +1 -0
  186. package/dist/{reactivity-Dski64km.d.mts → reactivity-KZOrwVeK.d.mts} +32 -1
  187. package/dist/reactivity-KZOrwVeK.d.mts.map +1 -0
  188. package/dist/{reply-B5kZ6VGv.mjs → reply-ChoI5SvM.mjs} +3 -3
  189. package/dist/{reply-B5kZ6VGv.mjs.map → reply-ChoI5SvM.mjs.map} +1 -1
  190. package/dist/{request-id-B_n-3A16.d.mts → request-id-B9Myiv75.d.mts} +2 -1
  191. package/dist/request-id-B9Myiv75.d.mts.map +1 -0
  192. package/dist/{request-logger-BV1C5r5q.d.mts → request-logger-CYyAuPmo.d.mts} +6 -1
  193. package/dist/request-logger-CYyAuPmo.d.mts.map +1 -0
  194. package/dist/{request-scope-D2WQwatk.mjs → request-scope-BfSNdmz9.mjs} +3 -3
  195. package/dist/{request-scope-D2WQwatk.mjs.map → request-scope-BfSNdmz9.mjs.map} +1 -1
  196. package/dist/{respond-C6ohI69y.mjs → respond-1BjaDME9.mjs} +2 -2
  197. package/dist/{respond-C6ohI69y.mjs.map → respond-1BjaDME9.mjs.map} +1 -1
  198. package/dist/rolldown-runtime-B5KeNctS.mjs +11 -0
  199. package/dist/{route-flag-CHiMvgar.mjs → route-flag-B6ZmhkfI.mjs} +3 -3
  200. package/dist/{route-flag-CHiMvgar.mjs.map → route-flag-B6ZmhkfI.mjs.map} +1 -1
  201. package/dist/{route-policy-ckK7N1eN.mjs → route-policy-BG--gAcF.mjs} +2 -2
  202. package/dist/route-policy-BG--gAcF.mjs.map +1 -0
  203. package/dist/{router-builder-Dtyya4qP.d.mts → router-builder-BkIW_qjz.d.mts} +3 -2
  204. package/dist/router-builder-BkIW_qjz.d.mts.map +1 -0
  205. package/dist/{router-builder-D2cly8Wt.mjs → router-builder-DHKtp4I8.mjs} +3 -3
  206. package/dist/router-builder-DHKtp4I8.mjs.map +1 -0
  207. package/dist/{runtime-D9TN6CpL.mjs → runtime-CUfFIHiC.mjs} +3 -3
  208. package/dist/runtime-CUfFIHiC.mjs.map +1 -0
  209. package/dist/{session-CXWu2rXW.d.mts → session-DPTbfwKO.d.mts} +40 -1
  210. package/dist/session-DPTbfwKO.d.mts.map +1 -0
  211. package/dist/{settings-v2N3V8Bl.mjs → settings-I7GUX5ps.mjs} +3 -3
  212. package/dist/{settings-v2N3V8Bl.mjs.map → settings-I7GUX5ps.mjs.map} +1 -1
  213. package/dist/{token-DtW16tw3.mjs → token-uWfhVlfe.mjs} +1 -1
  214. package/dist/{upload-eNNueUxR.d.mts → upload-O3VTcODy.d.mts} +3 -3
  215. package/dist/{upload-eNNueUxR.d.mts.map → upload-O3VTcODy.d.mts.map} +1 -1
  216. package/dist/{upload-config-BXjBiNjC.mjs → upload-config-BXqBuyza.mjs} +2 -2
  217. package/dist/{upload-config-BXjBiNjC.mjs.map → upload-config-BXqBuyza.mjs.map} +1 -1
  218. package/dist/url-for-CuMaQ2wS.mjs +12 -0
  219. package/dist/url-for-CuMaQ2wS.mjs.map +1 -0
  220. package/dist/{validate-BbthfLBb.d.mts → validate-CTgfm7oE.d.mts} +2 -2
  221. package/dist/{validate-BbthfLBb.d.mts.map → validate-CTgfm7oE.d.mts.map} +1 -1
  222. package/dist/{view-renderer-C4sMEruA.mjs → view-renderer-Bf1Wy-DQ.mjs} +3 -3
  223. package/dist/view-renderer-Bf1Wy-DQ.mjs.map +1 -0
  224. package/dist/{web-crypto-SXVOPDxW.mjs → web-crypto-JzoGmiG0.mjs} +2 -2
  225. package/dist/{web-crypto-SXVOPDxW.mjs.map → web-crypto-JzoGmiG0.mjs.map} +1 -1
  226. package/dist/web.d.mts +6 -6
  227. package/dist/web.d.mts.map +1 -1
  228. package/dist/web.mjs +2 -2
  229. package/dist/web.mjs.map +1 -1
  230. package/package.json +10 -10
  231. package/dist/adapter-B64IOivZ.d.mts.map +0 -1
  232. package/dist/allowed-hosts-U12_gESr.d.mts.map +0 -1
  233. package/dist/application-BzimU62Q.mjs +0 -14
  234. package/dist/application-BzimU62Q.mjs.map +0 -1
  235. package/dist/application-CGcY8SZZ.d.mts.map +0 -1
  236. package/dist/bootstrap-Bvk3BWJX.mjs.map +0 -1
  237. package/dist/breach-padding-DfT9MXGb.d.mts.map +0 -1
  238. package/dist/container-4iJdDkRH.d.mts +0 -3
  239. package/dist/context-BvZLaTeE.mjs.map +0 -1
  240. package/dist/context-errors-BZVS0B1O.mjs.map +0 -1
  241. package/dist/contributor-runner-fdKy6Tme.mjs.map +0 -1
  242. package/dist/core-CCIpjo6g.mjs +0 -12
  243. package/dist/core-CCIpjo6g.mjs.map +0 -1
  244. package/dist/cors-J-q6PuSU.d.mts.map +0 -1
  245. package/dist/cron-DGV1AE0R.d.mts.map +0 -1
  246. package/dist/csrf-DjtJPgA3.d.mts.map +0 -1
  247. package/dist/decorators-BAD8qjuq.d.mts.map +0 -1
  248. package/dist/define-adapter-DMo6og81.mjs.map +0 -1
  249. package/dist/di-hooks-DCqt2yJ9.mjs.map +0 -1
  250. package/dist/errors-DZGuPLoZ.d.mts.map +0 -1
  251. package/dist/helmet-Rwkbp9IS.d.mts.map +0 -1
  252. package/dist/index-ZbCnCyQx.d.mts.map +0 -1
  253. package/dist/jobs-CuZqVDDG.mjs.map +0 -1
  254. package/dist/kv-stores-C9CJ3xCB.mjs.map +0 -1
  255. package/dist/kv-stores-wTD3VDPB.d.mts.map +0 -1
  256. package/dist/observers-B4VnKAHK.mjs.map +0 -1
  257. package/dist/query-BwUR-ssX.mjs.map +0 -1
  258. package/dist/rate-limit-DMiV6bAq.d.mts.map +0 -1
  259. package/dist/reactivity-Dski64km.d.mts.map +0 -1
  260. package/dist/request-id-B_n-3A16.d.mts.map +0 -1
  261. package/dist/request-logger-BV1C5r5q.d.mts.map +0 -1
  262. package/dist/rolldown-runtime-DuhQYUab.mjs +0 -11
  263. package/dist/route-policy-ckK7N1eN.mjs.map +0 -1
  264. package/dist/router-builder-D2cly8Wt.mjs.map +0 -1
  265. package/dist/router-builder-Dtyya4qP.d.mts.map +0 -1
  266. package/dist/runtime-D9TN6CpL.mjs.map +0 -1
  267. package/dist/session-CXWu2rXW.d.mts.map +0 -1
  268. package/dist/url-for-C4Eomib7.mjs +0 -12
  269. package/dist/url-for-C4Eomib7.mjs.map +0 -1
  270. package/dist/view-renderer-C4sMEruA.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"helmet.mjs","names":[],"sources":["../../../src/http/middleware/helmet.ts"],"sourcesContent":["import type {\n ConnectRequest as Request,\n ConnectResponse as Response,\n ConnectNext as NextFunction,\n} from '../connect'\n\n/** Brand identifying a `helmet()` handler, so auto-injection can stand down. */\nexport const HELMET_MIDDLEWARE = Symbol.for('kick/http/helmet')\n\nexport interface HelmetOptions {\n /** Set Content-Security-Policy header (default: self-only policy) */\n contentSecurityPolicy?: boolean | Record<string, string[]>\n /** Set X-Content-Type-Options: nosniff (default: true) */\n noSniff?: boolean\n /** Set X-Frame-Options (default: 'DENY') */\n frameguard?: false | 'DENY' | 'SAMEORIGIN'\n /** Set Strict-Transport-Security (default: max-age=31536000; includeSubDomains) */\n hsts?: false | { maxAge?: number; includeSubDomains?: boolean; preload?: boolean }\n /** Set X-DNS-Prefetch-Control (default: off) */\n dnsPrefetch?: boolean\n /** Remove X-Powered-By header (default: true) */\n hidePoweredBy?: boolean\n /** Set Referrer-Policy (default: 'no-referrer') */\n referrerPolicy?: false | string\n /** Set X-XSS-Protection: 0 (default: true — disables legacy XSS auditor) */\n xssFilter?: boolean\n}\n\n/**\n * Security headers middleware. Lightweight alternative to the `helmet` npm package\n * with sensible defaults for API servers.\n *\n * @example\n * ```ts\n * bootstrap({\n * middlewares: [helmet(), requestId(), express.json()],\n * })\n * ```\n *\n * Options are read once, when the middleware is created: changing the options\n * object afterwards does not change the headers. Create a new middleware instead.\n */\nexport function helmet(options: HelmetOptions = {}) {\n const {\n noSniff = true,\n frameguard = 'DENY',\n hsts = { maxAge: 31536000, includeSubDomains: true },\n dnsPrefetch = false,\n hidePoweredBy = true,\n referrerPolicy = 'no-referrer',\n xssFilter = true,\n contentSecurityPolicy = false,\n } = options\n\n // Header values depend only on the options — built once, not per request.\n const hstsValue = hsts\n ? `max-age=${hsts.maxAge ?? 31536000}${hsts.includeSubDomains ? '; includeSubDomains' : ''}${\n hsts.preload ? '; preload' : ''\n }`\n : undefined\n const cspValue = !contentSecurityPolicy\n ? undefined\n : typeof contentSecurityPolicy === 'object'\n ? Object.entries(contentSecurityPolicy)\n .map(([key, values]) => `${key} ${values.join(' ')}`)\n .join('; ')\n : \"default-src 'self'\"\n\n const handler = (req: Request, res: Response, next: NextFunction) => {\n if (hidePoweredBy) res.removeHeader('X-Powered-By')\n if (noSniff) res.setHeader('X-Content-Type-Options', 'nosniff')\n if (frameguard) res.setHeader('X-Frame-Options', frameguard)\n if (xssFilter) res.setHeader('X-XSS-Protection', '0')\n if (referrerPolicy) res.setHeader('Referrer-Policy', referrerPolicy)\n if (!dnsPrefetch) res.setHeader('X-DNS-Prefetch-Control', 'off')\n\n if (hstsValue) res.setHeader('Strict-Transport-Security', hstsValue)\n if (cspValue) res.setHeader('Content-Security-Policy', cspValue)\n\n next()\n }\n\n // Brand the handler so the Application skips its own auto-injection. Without\n // that, auto-helmet runs first with defaults and a user helmet can only ADD\n // headers — an explicit `frameguard: false` would leave the auto-injected\n // `X-Frame-Options: DENY` standing.\n return Object.defineProperty(handler, HELMET_MIDDLEWARE, { value: true })\n}\n"],"mappings":";;;;;;;;;;AAOA,MAAa,kBAAoB,OAAO,IAAI,kBAAkB,EAmC9D,SAAgB,OAAO,QAAyB,CAAC,EAAG,CAClD,GAAM,CACJ,QAAU,GACV,WAAa,OACb,KAAO,CAAE,OAAQ,QAAU,kBAAmB,EAAK,EACnD,YAAc,GACd,cAAgB,GAChB,eAAiB,cACjB,UAAY,GACZ,sBAAwB,IACtB,QAGE,UAAY,KACd,WAAW,KAAK,QAAU,UAAW,KAAK,kBAAoB,sBAAwB,KACpF,KAAK,QAAU,YAAc,KAE/B,IAAA,GACE,SAAY,sBAEd,OAAO,uBAA0B,SAC/B,OAAO,QAAQ,qBAAqB,CAAC,CAClC,KAAK,CAAC,IAAK,UAAY,GAAG,IAAI,GAAG,OAAO,KAAK,GAAG,GAAG,CAAC,CACpD,KAAK,IAAI,EACZ,qBALF,IAAA,GAyBJ,OAAO,OAAO,gBAlBG,IAAc,IAAe,OAAuB,CAC/D,eAAe,IAAI,aAAa,cAAc,EAC9C,SAAS,IAAI,UAAU,yBAA0B,SAAS,EAC1D,YAAY,IAAI,UAAU,kBAAmB,UAAU,EACvD,WAAW,IAAI,UAAU,mBAAoB,GAAG,EAChD,gBAAgB,IAAI,UAAU,kBAAmB,cAAc,EAC9D,aAAa,IAAI,UAAU,yBAA0B,KAAK,EAE3D,WAAW,IAAI,UAAU,4BAA6B,SAAS,EAC/D,UAAU,IAAI,UAAU,0BAA2B,QAAQ,EAE/D,KAAK,CACP,EAMsC,kBAAmB,CAAE,MAAO,EAAK,CAAC,CAC1E,C"}
1
+ {"version":3,"file":"helmet.mjs","names":[],"sources":["../../../src/http/middleware/helmet.ts"],"sourcesContent":["import type {\n ConnectRequest as Request,\n ConnectResponse as Response,\n ConnectNext as NextFunction,\n} from '../connect'\n\n/** Brand identifying a `helmet()` handler, so auto-injection can stand down. */\nexport const HELMET_MIDDLEWARE = Symbol.for('kick/http/helmet')\n\n/**\n * Options for {@link helmet}: which security headers to set, and their values.\n *\n * @see https://kickjs.app/guide/security-headers\n */\nexport interface HelmetOptions {\n /** Set Content-Security-Policy header (default: self-only policy) */\n contentSecurityPolicy?: boolean | Record<string, string[]>\n /** Set X-Content-Type-Options: nosniff (default: true) */\n noSniff?: boolean\n /** Set X-Frame-Options (default: 'DENY') */\n frameguard?: false | 'DENY' | 'SAMEORIGIN'\n /** Set Strict-Transport-Security (default: max-age=31536000; includeSubDomains) */\n hsts?: false | { maxAge?: number; includeSubDomains?: boolean; preload?: boolean }\n /** Set X-DNS-Prefetch-Control (default: off) */\n dnsPrefetch?: boolean\n /** Remove X-Powered-By header (default: true) */\n hidePoweredBy?: boolean\n /** Set Referrer-Policy (default: 'no-referrer') */\n referrerPolicy?: false | string\n /** Set X-XSS-Protection: 0 (default: true — disables legacy XSS auditor) */\n xssFilter?: boolean\n}\n\n/**\n * Security headers middleware. Lightweight alternative to the `helmet` npm package\n * with sensible defaults for API servers.\n *\n * @example\n * ```ts\n * bootstrap({\n * middlewares: [helmet(), requestId(), express.json()],\n * })\n * ```\n *\n * Options are read once, when the middleware is created: changing the options\n * object afterwards does not change the headers. Create a new middleware instead.\n */\nexport function helmet(options: HelmetOptions = {}) {\n const {\n noSniff = true,\n frameguard = 'DENY',\n hsts = { maxAge: 31536000, includeSubDomains: true },\n dnsPrefetch = false,\n hidePoweredBy = true,\n referrerPolicy = 'no-referrer',\n xssFilter = true,\n contentSecurityPolicy = false,\n } = options\n\n // Header values depend only on the options — built once, not per request.\n const hstsValue = hsts\n ? `max-age=${hsts.maxAge ?? 31536000}${hsts.includeSubDomains ? '; includeSubDomains' : ''}${\n hsts.preload ? '; preload' : ''\n }`\n : undefined\n const cspValue = !contentSecurityPolicy\n ? undefined\n : typeof contentSecurityPolicy === 'object'\n ? Object.entries(contentSecurityPolicy)\n .map(([key, values]) => `${key} ${values.join(' ')}`)\n .join('; ')\n : \"default-src 'self'\"\n\n const handler = (req: Request, res: Response, next: NextFunction) => {\n if (hidePoweredBy) res.removeHeader('X-Powered-By')\n if (noSniff) res.setHeader('X-Content-Type-Options', 'nosniff')\n if (frameguard) res.setHeader('X-Frame-Options', frameguard)\n if (xssFilter) res.setHeader('X-XSS-Protection', '0')\n if (referrerPolicy) res.setHeader('Referrer-Policy', referrerPolicy)\n if (!dnsPrefetch) res.setHeader('X-DNS-Prefetch-Control', 'off')\n\n if (hstsValue) res.setHeader('Strict-Transport-Security', hstsValue)\n if (cspValue) res.setHeader('Content-Security-Policy', cspValue)\n\n next()\n }\n\n // Brand the handler so the Application skips its own auto-injection. Without\n // that, auto-helmet runs first with defaults and a user helmet can only ADD\n // headers — an explicit `frameguard: false` would leave the auto-injected\n // `X-Frame-Options: DENY` standing.\n return Object.defineProperty(handler, HELMET_MIDDLEWARE, { value: true })\n}\n"],"mappings":";;;;;;;;;;AAOA,MAAa,kBAAoB,OAAO,IAAI,kBAAkB,EAwC9D,SAAgB,OAAO,QAAyB,CAAC,EAAG,CAClD,GAAM,CACJ,QAAU,GACV,WAAa,OACb,KAAO,CAAE,OAAQ,QAAU,kBAAmB,EAAK,EACnD,YAAc,GACd,cAAgB,GAChB,eAAiB,cACjB,UAAY,GACZ,sBAAwB,IACtB,QAGE,UAAY,KACd,WAAW,KAAK,QAAU,UAAW,KAAK,kBAAoB,sBAAwB,KACpF,KAAK,QAAU,YAAc,KAE/B,IAAA,GACE,SAAY,sBAEd,OAAO,uBAA0B,SAC/B,OAAO,QAAQ,qBAAqB,CAAC,CAClC,KAAK,CAAC,IAAK,UAAY,GAAG,IAAI,GAAG,OAAO,KAAK,GAAG,GAAG,CAAC,CACpD,KAAK,IAAI,EACZ,qBALF,IAAA,GAyBJ,OAAO,OAAO,gBAlBG,IAAc,IAAe,OAAuB,CAC/D,eAAe,IAAI,aAAa,cAAc,EAC9C,SAAS,IAAI,UAAU,yBAA0B,SAAS,EAC1D,YAAY,IAAI,UAAU,kBAAmB,UAAU,EACvD,WAAW,IAAI,UAAU,mBAAoB,GAAG,EAChD,gBAAgB,IAAI,UAAU,kBAAmB,cAAc,EAC9D,aAAa,IAAI,UAAU,yBAA0B,KAAK,EAE3D,WAAW,IAAI,UAAU,4BAA6B,SAAS,EAC/D,UAAU,IAAI,UAAU,0BAA2B,QAAQ,EAE/D,KAAK,CACP,EAMsC,kBAAmB,CAAE,MAAO,EAAK,CAAC,CAC1E,C"}
@@ -1,3 +1,3 @@
1
1
 
2
- import { i as rateLimit, n as RateLimitOptions, r as RateLimitStore, t as MemoryStore } from "../../rate-limit-DMiV6bAq.mjs";
2
+ import { i as rateLimit, n as RateLimitOptions, r as RateLimitStore, t as MemoryStore } from "../../rate-limit-BQx_P6gG.mjs";
3
3
  export { MemoryStore, RateLimitOptions, RateLimitStore, rateLimit };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.14.2
2
+ * @forinda/kickjs v10.15.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{n as assertFlagTest,s as matchesFlagTest}from"../../route-flag-CHiMvgar.mjs";import{n as bindRoutePolicy}from"../../route-policy-ckK7N1eN.mjs";import{i as sendJson}from"../../respond-C6ohI69y.mjs";import{n as resolvePathname,t as resolveClientIp}from"../../client-ip-CGH_IvnC.mjs";import{r as registerDisposable}from"../../disposables-BsdVu69-.mjs";import{t as BoundedCounters}from"../../bounded-counters-Bh5jeT9I.mjs";var MemoryStore=class{counters;cleanupTimer;constructor(windowMs,limit){this.counters=new BoundedCounters(windowMs,limit),this.cleanupTimer=setInterval(()=>this.counters.sweep(),windowMs),this.cleanupTimer.unref&&this.cleanupTimer.unref(),registerDisposable(()=>this.dispose())}dispose(){clearInterval(this.cleanupTimer),this.counters.clear()}async increment(key){return this.counters.increment(key)}async decrement(key){this.counters.decrement(key)}async reset(key){this.counters.reset(key)}};function rateLimit(options={}){let max=options.max??100,windowMs=options.windowMs??6e4,message=options.message??`Too Many Requests`,statusCode=options.statusCode??429,keyGenerator=options.keyGenerator??(req=>resolveClientIp(req)??`global`),sendHeaders=options.headers??!0,store=options.store??new MemoryStore(windowMs,max),skip=options.skip,skipPaths=new Set(options.skipPaths??[]),exemptWhen=options.exemptWhen;exemptWhen!==void 0&&assertFlagTest(exemptWhen,`rateLimit({ exemptWhen })`);let policy;return bindRoutePolicy(async(req,res,next)=>{let pathname=resolvePathname(req);if(skipPaths.has(pathname))return next();if(exemptWhen!==void 0&&policy){let{originalUrl}=req,routePath=originalUrl?resolvePathname({url:originalUrl}):pathname,flags=policy.lookup(String(req.method??`GET`),routePath);if(matchesFlagTest(exemptWhen,flags))return next()}if(skip&&skip(req))return next();let key=keyGenerator(req),{totalHits,resetTime}=await store.increment(key),remaining=Math.max(0,max-totalHits);if(sendHeaders&&(res.setHeader(`RateLimit-Limit`,max),res.setHeader(`RateLimit-Remaining`,remaining),res.setHeader(`RateLimit-Reset`,Math.ceil(resetTime.getTime()/1e3))),totalHits>max)return sendJson(res,statusCode,{message});next()},table=>{policy=table})}export{MemoryStore,rateLimit};
11
+ import{n as assertFlagTest,s as matchesFlagTest}from"../../route-flag-B6ZmhkfI.mjs";import{n as bindRoutePolicy}from"../../route-policy-BG--gAcF.mjs";import{i as sendJson}from"../../respond-1BjaDME9.mjs";import{n as resolvePathname,t as resolveClientIp}from"../../client-ip-CWvyHmqt.mjs";import{r as registerDisposable}from"../../disposables-BC291ukb.mjs";import{t as BoundedCounters}from"../../bounded-counters-BtvB2daV.mjs";var MemoryStore=class{counters;cleanupTimer;constructor(windowMs,limit){this.counters=new BoundedCounters(windowMs,limit),this.cleanupTimer=setInterval(()=>this.counters.sweep(),windowMs),this.cleanupTimer.unref&&this.cleanupTimer.unref(),registerDisposable(()=>this.dispose())}dispose(){clearInterval(this.cleanupTimer),this.counters.clear()}async increment(key){return this.counters.increment(key)}async decrement(key){this.counters.decrement(key)}async reset(key){this.counters.reset(key)}};function rateLimit(options={}){let max=options.max??100,windowMs=options.windowMs??6e4,message=options.message??`Too Many Requests`,statusCode=options.statusCode??429,keyGenerator=options.keyGenerator??(req=>resolveClientIp(req)??`global`),sendHeaders=options.headers??!0,store=options.store??new MemoryStore(windowMs,max),skip=options.skip,skipPaths=new Set(options.skipPaths??[]),exemptWhen=options.exemptWhen;exemptWhen!==void 0&&assertFlagTest(exemptWhen,`rateLimit({ exemptWhen })`);let policy;return bindRoutePolicy(async(req,res,next)=>{let pathname=resolvePathname(req);if(skipPaths.has(pathname))return next();if(exemptWhen!==void 0&&policy){let{originalUrl}=req,routePath=originalUrl?resolvePathname({url:originalUrl}):pathname,flags=policy.lookup(String(req.method??`GET`),routePath);if(matchesFlagTest(exemptWhen,flags))return next()}if(skip&&skip(req))return next();let key=keyGenerator(req),{totalHits,resetTime}=await store.increment(key),remaining=Math.max(0,max-totalHits);if(sendHeaders&&(res.setHeader(`RateLimit-Limit`,max),res.setHeader(`RateLimit-Remaining`,remaining),res.setHeader(`RateLimit-Reset`,Math.ceil(resetTime.getTime()/1e3))),totalHits>max)return sendJson(res,statusCode,{message});next()},table=>{policy=table})}export{MemoryStore,rateLimit};
12
12
  //# sourceMappingURL=rate-limit.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"rate-limit.mjs","names":[],"sources":["../../../src/http/middleware/rate-limit.ts"],"sourcesContent":["import { assertFlagTest, matchesFlagTest, type RouteFlagTest } from '../../core/route-flag'\nimport { bindRoutePolicy, type RoutePolicyTable } from '../../core/route-policy'\nimport { sendJson } from './respond'\nimport type {\n ConnectRequest as Request,\n ConnectResponse as Response,\n ConnectNext as NextFunction,\n} from '../connect'\nimport { resolveClientIp, resolvePathname, type ClientRequestLike } from '../client-ip'\n\nimport { registerDisposable } from '../../core/disposables'\nimport { BoundedCounters } from './bounded-counters'\n\nexport interface RateLimitStore {\n increment(key: string): Promise<{ totalHits: number; resetTime: Date }>\n decrement(key: string): Promise<void>\n reset(key: string): Promise<void>\n}\n\nexport interface RateLimitOptions {\n /** Maximum number of requests per window (default: 100) */\n max?: number\n /** Time window in milliseconds (default: 60_000) */\n windowMs?: number\n /** Response message when rate limit is exceeded (default: 'Too Many Requests') */\n message?: string\n /** HTTP status code when rate limit is exceeded (default: 429) */\n statusCode?: number\n /** Function to generate the key for rate limiting (default: req.ip) */\n keyGenerator?: (req: Request) => string\n /** Whether to send rate limit headers (default: true) */\n headers?: boolean\n /** Custom store implementation (default: in-memory Map) */\n store?: RateLimitStore\n /** Function to skip rate limiting for certain requests */\n skip?: (req: Request) => boolean\n /** Paths to exclude from rate limiting */\n skipPaths?: string[]\n /**\n * Skip limiting on routes carrying a route flag — a name, a list of names\n * (any-of), or a predicate.\n *\n * This middleware runs before route matching, so it has no `ctx.route` to\n * read. Instead the Application hands it a table of every mounted route's\n * flags at boot, and the incoming method + pathname is looked up against it.\n * Requests matching no route match no flags — which is the point of limiting\n * here rather than in a route-scoped guard.\n *\n * ```ts\n * const Public = defineRouteFlag('auth.public')\n * bootstrap({ middlewares: [rateLimit({ max: 60, exemptWhen: 'auth.public' })] })\n * ```\n *\n * Prefer `skipPaths` only for paths that are not routes at all (a static\n * mount, a proxied prefix); a flag cannot describe those.\n */\n exemptWhen?: RouteFlagTest\n}\n\n/** @internal Exported for tests. Bounded: see {@link BoundedCounters}. */\nexport class MemoryStore implements RateLimitStore {\n private readonly counters: BoundedCounters\n private cleanupTimer: ReturnType<typeof setInterval>\n\n /** @param limit The `max` it enforces, so it never evicts a counter at the limit. */\n constructor(windowMs: number, limit?: number) {\n this.counters = new BoundedCounters(windowMs, limit)\n this.cleanupTimer = setInterval(() => this.counters.sweep(), windowMs)\n // Allow the process to exit without waiting for the timer\n if (this.cleanupTimer.unref) {\n this.cleanupTimer.unref()\n }\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 hits Map.\n registerDisposable(() => this.dispose())\n }\n\n /** Clear the cleanup interval and drop all hit counters. */\n dispose(): void {\n clearInterval(this.cleanupTimer)\n this.counters.clear()\n }\n\n async increment(key: string): Promise<{ totalHits: number; resetTime: Date }> {\n return this.counters.increment(key)\n }\n\n async decrement(key: string): Promise<void> {\n this.counters.decrement(key)\n }\n\n async reset(key: string): Promise<void> {\n this.counters.reset(key)\n }\n}\n\n/**\n * Rate limiting middleware.\n *\n * Limits the number of requests a client can make within a time window.\n * Uses an in-memory store by default, but accepts a custom store for\n * distributed deployments (e.g. Redis).\n *\n * @example\n * ```ts\n * import { rateLimit } from '@forinda/kickjs'\n *\n * bootstrap({\n * modules,\n * middlewares: [\n * rateLimit({ max: 100, windowMs: 60_000 }),\n * // ... other middleware\n * ],\n * })\n * ```\n */\nexport function rateLimit(options: RateLimitOptions = {}) {\n const max = options.max ?? 100\n const windowMs = options.windowMs ?? 60_000\n const message = options.message ?? 'Too Many Requests'\n const statusCode = options.statusCode ?? 429\n // `req.ip` is Express-only. Under Fastify and h3 it is undefined, so EVERY\n // caller fell back to the same `'127.0.0.1'` literal — one shared bucket,\n // letting a single client exhaust the limit for everyone.\n const keyGenerator =\n options.keyGenerator ??\n ((req: Request) => resolveClientIp(req as ClientRequestLike) ?? 'global')\n const sendHeaders = options.headers ?? true\n const store = options.store ?? new MemoryStore(windowMs, max)\n const skip = options.skip\n const skipPaths = new Set(options.skipPaths ?? [])\n const exemptWhen = options.exemptWhen\n if (exemptWhen !== undefined) assertFlagTest(exemptWhen, 'rateLimit({ exemptWhen })')\n\n // Filled in by the Application once routes are mounted, via the slot\n // declared below. Absent when this middleware runs outside an Application\n // (a bare connect stack, a unit test) — `exemptWhen` then matches nothing,\n // which fails closed: everything stays limited.\n let policy: RoutePolicyTable | undefined\n\n const handler = async (req: Request, res: Response, next: NextFunction) => {\n // Skip if path is in the skip list\n // `req.path` is Express-only; `has(undefined)` never matched, so\n // configured skips were silently dead on the other runtimes.\n const pathname = resolvePathname(req as ClientRequestLike)\n if (skipPaths.has(pathname)) {\n return next()\n }\n\n // Flag exemption: ask the table what flags the matched route WOULD carry.\n // A request matching no route matches no flags and stays limited.\n // Routes are registered by their full path; mounted at a path, `req.url`\n // is relative to the mount, so look the route up by `originalUrl`.\n if (exemptWhen !== undefined && policy) {\n const { originalUrl } = req as ClientRequestLike\n const routePath = originalUrl ? resolvePathname({ url: originalUrl }) : pathname\n const flags = policy.lookup(String(req.method ?? 'GET'), routePath)\n if (matchesFlagTest(exemptWhen, flags)) {\n return next()\n }\n }\n\n // Skip if the skip function returns true\n if (skip && skip(req)) {\n return next()\n }\n\n const key = keyGenerator(req)\n const { totalHits, resetTime } = await store.increment(key)\n const remaining = Math.max(0, max - totalHits)\n\n if (sendHeaders) {\n res.setHeader('RateLimit-Limit', max)\n res.setHeader('RateLimit-Remaining', remaining)\n res.setHeader('RateLimit-Reset', Math.ceil(resetTime.getTime() / 1000))\n }\n\n if (totalHits > max) {\n return sendJson(res, statusCode, { message })\n }\n\n next()\n }\n\n return bindRoutePolicy(handler, (table) => {\n policy = table\n })\n}\n"],"mappings":";;;;;;;;;;A,0aA4DA,IAAa,YAAb,KAAmD,CACjD,SACA,aAGA,YAAY,SAAkB,MAAgB,CAC5C,KAAK,SAAW,IAAI,gBAAgB,SAAU,KAAK,EACnD,KAAK,aAAe,gBAAkB,KAAK,SAAS,MAAM,EAAG,QAAQ,EAEjE,KAAK,aAAa,OACpB,KAAK,aAAa,MAAM,EAK1B,uBAAyB,KAAK,QAAQ,CAAC,CACzC,CAGA,SAAgB,CACd,cAAc,KAAK,YAAY,EAC/B,KAAK,SAAS,MAAM,CACtB,CAEA,MAAM,UAAU,IAA8D,CAC5E,OAAO,KAAK,SAAS,UAAU,GAAG,CACpC,CAEA,MAAM,UAAU,IAA4B,CAC1C,KAAK,SAAS,UAAU,GAAG,CAC7B,CAEA,MAAM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EAG9C,KAAK,CACP,EAEiC,OAAU,CACzC,OAAS,KACX,CAAC,CACH,C"}
1
+ {"version":3,"file":"rate-limit.mjs","names":[],"sources":["../../../src/http/middleware/rate-limit.ts"],"sourcesContent":["import { assertFlagTest, matchesFlagTest, type RouteFlagTest } from '../../core/route-flag'\nimport { bindRoutePolicy, type RoutePolicyTable } from '../../core/route-policy'\nimport { sendJson } from './respond'\nimport type {\n ConnectRequest as Request,\n ConnectResponse as Response,\n ConnectNext as NextFunction,\n} from '../connect'\nimport { resolveClientIp, resolvePathname, type ClientRequestLike } from '../client-ip'\n\nimport { registerDisposable } from '../../core/disposables'\nimport { BoundedCounters } from './bounded-counters'\n\n/**\n * Where rate-limit counters live. Implement it to share counts across instances (Redis, KV).\n *\n * @see https://kickjs.app/guide/rate-limiting\n */\nexport interface RateLimitStore {\n increment(key: string): Promise<{ totalHits: number; resetTime: Date }>\n decrement(key: string): Promise<void>\n reset(key: string): Promise<void>\n}\n\n/**\n * Options for {@link rateLimit}.\n *\n * @see https://kickjs.app/guide/rate-limiting\n */\nexport interface RateLimitOptions {\n /** Maximum number of requests per window (default: 100) */\n max?: number\n /** Time window in milliseconds (default: 60_000) */\n windowMs?: number\n /** Response message when rate limit is exceeded (default: 'Too Many Requests') */\n message?: string\n /** HTTP status code when rate limit is exceeded (default: 429) */\n statusCode?: number\n /** Function to generate the key for rate limiting (default: req.ip) */\n keyGenerator?: (req: Request) => string\n /** Whether to send rate limit headers (default: true) */\n headers?: boolean\n /** Custom store implementation (default: in-memory Map) */\n store?: RateLimitStore\n /** Function to skip rate limiting for certain requests */\n skip?: (req: Request) => boolean\n /** Paths to exclude from rate limiting */\n skipPaths?: string[]\n /**\n * Skip limiting on routes carrying a route flag — a name, a list of names\n * (any-of), or a predicate.\n *\n * This middleware runs before route matching, so it has no `ctx.route` to\n * read. Instead the Application hands it a table of every mounted route's\n * flags at boot, and the incoming method + pathname is looked up against it.\n * Requests matching no route match no flags — which is the point of limiting\n * here rather than in a route-scoped guard.\n *\n * ```ts\n * const Public = defineRouteFlag('auth.public')\n * bootstrap({ middlewares: [rateLimit({ max: 60, exemptWhen: 'auth.public' })] })\n * ```\n *\n * Prefer `skipPaths` only for paths that are not routes at all (a static\n * mount, a proxied prefix); a flag cannot describe those.\n */\n exemptWhen?: RouteFlagTest\n}\n\n/** @internal Exported for tests. Bounded: see {@link BoundedCounters}. */\nexport class MemoryStore implements RateLimitStore {\n private readonly counters: BoundedCounters\n private cleanupTimer: ReturnType<typeof setInterval>\n\n /** @param limit The `max` it enforces, so it never evicts a counter at the limit. */\n constructor(windowMs: number, limit?: number) {\n this.counters = new BoundedCounters(windowMs, limit)\n this.cleanupTimer = setInterval(() => this.counters.sweep(), windowMs)\n // Allow the process to exit without waiting for the timer\n if (this.cleanupTimer.unref) {\n this.cleanupTimer.unref()\n }\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 hits Map.\n registerDisposable(() => this.dispose())\n }\n\n /** Clear the cleanup interval and drop all hit counters. */\n dispose(): void {\n clearInterval(this.cleanupTimer)\n this.counters.clear()\n }\n\n async increment(key: string): Promise<{ totalHits: number; resetTime: Date }> {\n return this.counters.increment(key)\n }\n\n async decrement(key: string): Promise<void> {\n this.counters.decrement(key)\n }\n\n async reset(key: string): Promise<void> {\n this.counters.reset(key)\n }\n}\n\n/**\n * Rate limiting middleware.\n *\n * Limits the number of requests a client can make within a time window.\n * Uses an in-memory store by default, but accepts a custom store for\n * distributed deployments (e.g. Redis).\n *\n * @example\n * ```ts\n * import { rateLimit } from '@forinda/kickjs'\n *\n * bootstrap({\n * modules,\n * middlewares: [\n * rateLimit({ max: 100, windowMs: 60_000 }),\n * // ... other middleware\n * ],\n * })\n * ```\n */\nexport function rateLimit(options: RateLimitOptions = {}) {\n const max = options.max ?? 100\n const windowMs = options.windowMs ?? 60_000\n const message = options.message ?? 'Too Many Requests'\n const statusCode = options.statusCode ?? 429\n // `req.ip` is Express-only. Under Fastify and h3 it is undefined, so EVERY\n // caller fell back to the same `'127.0.0.1'` literal — one shared bucket,\n // letting a single client exhaust the limit for everyone.\n const keyGenerator =\n options.keyGenerator ??\n ((req: Request) => resolveClientIp(req as ClientRequestLike) ?? 'global')\n const sendHeaders = options.headers ?? true\n const store = options.store ?? new MemoryStore(windowMs, max)\n const skip = options.skip\n const skipPaths = new Set(options.skipPaths ?? [])\n const exemptWhen = options.exemptWhen\n if (exemptWhen !== undefined) assertFlagTest(exemptWhen, 'rateLimit({ exemptWhen })')\n\n // Filled in by the Application once routes are mounted, via the slot\n // declared below. Absent when this middleware runs outside an Application\n // (a bare connect stack, a unit test) — `exemptWhen` then matches nothing,\n // which fails closed: everything stays limited.\n let policy: RoutePolicyTable | undefined\n\n const handler = async (req: Request, res: Response, next: NextFunction) => {\n // Skip if path is in the skip list\n // `req.path` is Express-only; `has(undefined)` never matched, so\n // configured skips were silently dead on the other runtimes.\n const pathname = resolvePathname(req as ClientRequestLike)\n if (skipPaths.has(pathname)) {\n return next()\n }\n\n // Flag exemption: ask the table what flags the matched route WOULD carry.\n // A request matching no route matches no flags and stays limited.\n // Routes are registered by their full path; mounted at a path, `req.url`\n // is relative to the mount, so look the route up by `originalUrl`.\n if (exemptWhen !== undefined && policy) {\n const { originalUrl } = req as ClientRequestLike\n const routePath = originalUrl ? resolvePathname({ url: originalUrl }) : pathname\n const flags = policy.lookup(String(req.method ?? 'GET'), routePath)\n if (matchesFlagTest(exemptWhen, flags)) {\n return next()\n }\n }\n\n // Skip if the skip function returns true\n if (skip && skip(req)) {\n return next()\n }\n\n const key = keyGenerator(req)\n const { totalHits, resetTime } = await store.increment(key)\n const remaining = Math.max(0, max - totalHits)\n\n if (sendHeaders) {\n res.setHeader('RateLimit-Limit', max)\n res.setHeader('RateLimit-Remaining', remaining)\n res.setHeader('RateLimit-Reset', Math.ceil(resetTime.getTime() / 1000))\n }\n\n if (totalHits > max) {\n return sendJson(res, statusCode, { message })\n }\n\n next()\n }\n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CAAE,IAAK,WAAY,CAAC,EAAI,SAClE,MAAQ,OAAO,OAAO,OAAO,IAAI,QAAU,KAAK,EAAG,SAAS,EAClE,GAAI,gBAAgB,WAAY,KAAK,EACnC,OAAO,KAAK,CAEhB,CAGA,GAAI,MAAQ,KAAK,GAAG,EAClB,OAAO,KAAK,EAGd,IAAM,IAAM,aAAa,GAAG,EACtB,CAAE,UAAW,WAAc,MAAM,MAAM,UAAU,GAAG,EACpD,UAAY,KAAK,IAAI,EAAG,IAAM,SAAS,EAQ7C,GANI,cACF,IAAI,UAAU,kBAAmB,GAAG,EACpC,IAAI,UAAU,sBAAuB,SAAS,EAC9C,IAAI,UAAU,kBAAmB,KAAK,KAAK,UAAU,QAAQ,EAAI,GAAI,CAAC,GAGpE,UAAY,IACd,OAAO,SAAS,IAAK,WAAY,CAAE,OAAQ,CAAC,EAG9C,KAAK,CACP,EAEiC,OAAU,CACzC,OAAS,KACX,CAAC,CACH,C"}
@@ -1,3 +1,3 @@
1
1
 
2
- import { n as requestId, t as REQUEST_ID_HEADER } from "../../request-id-B_n-3A16.mjs";
2
+ import { n as requestId, t as REQUEST_ID_HEADER } from "../../request-id-B9Myiv75.mjs";
3
3
  export { REQUEST_ID_HEADER, requestId };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.14.2
2
+ * @forinda/kickjs v10.15.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -1 +1 @@
1
- {"version":3,"file":"request-id.mjs","names":[],"sources":["../../../src/http/middleware/request-id.ts"],"sourcesContent":["import type {\n ConnectRequest as Request,\n ConnectResponse as Response,\n ConnectNext as NextFunction,\n} from '../connect'\n\nexport const REQUEST_ID_HEADER = 'x-request-id'\n\n/**\n * Middleware that generates or propagates a unique request ID.\n *\n * Idempotent: if `req.requestId` is already set (e.g. by\n * `requestScopeMiddleware` earlier in the pipeline), this middleware reuses\n * it instead of generating a divergent second value. Keeps the\n * X-Request-Id response header, the ALS store's `requestId`, and\n * `RequestContext.requestId` in agreement for every request, regardless of\n * mounting order.\n */\nexport function requestId() {\n return (req: Request, res: Response, next: NextFunction) => {\n const existing = (req as Request & { requestId?: string }).requestId\n // globalThis.crypto (Web Crypto) — portable across node/bun/deno/workers,\n // unlike node:crypto. Node ≥ 19 exposes it globally; engines pin ≥ 20.\n const header = req.headers[REQUEST_ID_HEADER]\n const id = existing || (Array.isArray(header) ? header[0] : header) || crypto.randomUUID()\n ;(req as any).requestId = id\n res.setHeader(REQUEST_ID_HEADER, id)\n next()\n }\n}\n"],"mappings":";;;;;;;;;;AAMA,MAAa,kBAAoB,eAYjC,SAAgB,WAAY,CAC1B,OAAQ,IAAc,IAAe,OAAuB,CAC1D,IAAM,SAAY,IAAyC,UAGrD,OAAS,IAAI,QAAQ,mBACrB,GAAK,WAAa,MAAM,QAAQ,MAAM,EAAI,OAAO,GAAK,SAAW,OAAO,WAAW,EACxF,IAAa,UAAY,GAC1B,IAAI,UAAU,kBAAmB,EAAE,EACnC,KAAK,CACP,CACF,C"}
1
+ {"version":3,"file":"request-id.mjs","names":[],"sources":["../../../src/http/middleware/request-id.ts"],"sourcesContent":["import type {\n ConnectRequest as Request,\n ConnectResponse as Response,\n ConnectNext as NextFunction,\n} from '../connect'\n\n/** Header the request ID is read from and echoed in: `x-request-id`. */\nexport const REQUEST_ID_HEADER = 'x-request-id'\n\n/**\n * Middleware that generates or propagates a unique request ID.\n *\n * Idempotent: if `req.requestId` is already set (e.g. by\n * `requestScopeMiddleware` earlier in the pipeline), this middleware reuses\n * it instead of generating a divergent second value. Keeps the\n * X-Request-Id response header, the ALS store's `requestId`, and\n * `RequestContext.requestId` in agreement for every request, regardless of\n * mounting order.\n */\nexport function requestId() {\n return (req: Request, res: Response, next: NextFunction) => {\n const existing = (req as Request & { requestId?: string }).requestId\n // globalThis.crypto (Web Crypto) — portable across node/bun/deno/workers,\n // unlike node:crypto. Node ≥ 19 exposes it globally; engines pin ≥ 20.\n const header = req.headers[REQUEST_ID_HEADER]\n const id = existing || (Array.isArray(header) ? header[0] : header) || crypto.randomUUID()\n ;(req as any).requestId = id\n res.setHeader(REQUEST_ID_HEADER, id)\n next()\n }\n}\n"],"mappings":";;;;;;;;;;AAOA,MAAa,kBAAoB,eAYjC,SAAgB,WAAY,CAC1B,OAAQ,IAAc,IAAe,OAAuB,CAC1D,IAAM,SAAY,IAAyC,UAGrD,OAAS,IAAI,QAAQ,mBACrB,GAAK,WAAa,MAAM,QAAQ,MAAM,EAAI,OAAO,GAAK,SAAW,OAAO,WAAW,EACvF,IAAY,UAAY,GAC1B,IAAI,UAAU,kBAAmB,EAAE,EACnC,KAAK,CACP,CACF,C"}
@@ -1,3 +1,3 @@
1
1
 
2
- import { i as requestLogger, n as LoggedResponse, r as RequestLoggerOptions, t as LoggedRequest } from "../../request-logger-BV1C5r5q.mjs";
2
+ import { i as requestLogger, n as LoggedResponse, r as RequestLoggerOptions, t as LoggedRequest } from "../../request-logger-CYyAuPmo.mjs";
3
3
  export { LoggedRequest, LoggedResponse, RequestLoggerOptions, requestLogger };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.14.2
2
+ * @forinda/kickjs v10.15.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{createLogger}from"../../core/logger.mjs";import"../../core-CCIpjo6g.mjs";function pathnameOf(url){if(!url)return`/`;let q=url.indexOf(`?`);return(q===-1?url:url.slice(0,q))||`/`}function requestLogger(options={}){let log=createLogger(options.name??`HTTP`),level=options.level??`info`,skip=options.skip??[];return(req,res,next)=>{let pathname=req.path??pathnameOf(req.url);if(skip.some(prefix=>pathname.startsWith(prefix)))return next();let start=Date.now();res.on(`finish`,()=>{let duration=Date.now()-start,requestId=req.requestId||req.headers[`x-request-id`]||`-`,status=res.statusCode,path=req.originalUrl??req.url??`/`;log.child({method:req.method,path,status,ms:duration,requestId})[level](`${req.method} ${path} ${status} ${duration}ms ${requestId}`)}),next()}}export{requestLogger};
11
+ import{createLogger}from"../../core/logger.mjs";import"../../core-Dqzah_BX.mjs";function pathnameOf(url){if(!url)return`/`;let q=url.indexOf(`?`);return(q===-1?url:url.slice(0,q))||`/`}function requestLogger(options={}){let log=createLogger(options.name??`HTTP`),level=options.level??`info`,skip=options.skip??[];return(req,res,next)=>{let pathname=req.path??pathnameOf(req.url);if(skip.some(prefix=>pathname.startsWith(prefix)))return next();let start=Date.now();res.on(`finish`,()=>{let duration=Date.now()-start,requestId=req.requestId||req.headers[`x-request-id`]||`-`,status=res.statusCode,path=req.originalUrl??req.url??`/`;log.child({method:req.method,path,status,ms:duration,requestId})[level](`${req.method} ${path} ${status} ${duration}ms ${requestId}`)}),next()}}export{requestLogger};
12
12
  //# sourceMappingURL=request-logger.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"request-logger.mjs","names":[],"sources":["../../../src/http/middleware/request-logger.ts"],"sourcesContent":["/**\n * The slice of the request/response this logger touches, from node's shapes\n * rather than Express's. This runs under EVERY runtime — Fastify and h3 hand\n * connect middleware the raw node objects — so anything Express-only is\n * `undefined` there.\n */\n/**\n * The request shape this middleware reads.\n *\n * Exported because it appears in the returned handler's signature: a consumer\n * following the documented `src/middleware/index.ts` layout exports the\n * middleware array with an inferred type, and a type the entry does not\n * re-export cannot be named there — `TS4023: Exported variable 'middleware'\n * has or is using name 'LoggedRequest' … but cannot be named`.\n *\n * Deliberately structural rather than Express's `Request`: the Fastify and h3\n * runtimes pass a raw Node request, which has `url` but no `path`.\n */\nexport interface LoggedRequest {\n method?: string\n url?: string\n /** Express-only convenience; the raw node request has only `url`. */\n path?: string\n /** Express-only; absent on the raw node request the other runtimes pass. */\n originalUrl?: string\n headers: Record<string, string | string[] | undefined>\n}\n\n/** The response shape this middleware reads. Exported for the same reason as {@link LoggedRequest}. */\nexport interface LoggedResponse {\n statusCode: number\n on(event: 'finish', listener: () => void): unknown\n}\n\n/** Pathname only — `req.url` carries the query string. */\nfunction pathnameOf(url: string | undefined): string {\n if (!url) return '/'\n const q = url.indexOf('?')\n return (q === -1 ? url : url.slice(0, q)) || '/'\n}\nimport { createLogger } from '../../core'\n\nexport interface RequestLoggerOptions {\n /** Logger name (default: 'HTTP') */\n name?: string\n /** Log level for successful requests (default: 'info') */\n level?: 'info' | 'debug' | 'trace'\n /** Skip logging for paths matching these prefixes (e.g. ['/health', '/_debug']) */\n skip?: string[]\n}\n\n/**\n * Middleware that logs every request with method, URL, status, duration, and request ID.\n *\n * @example\n * ```ts\n * bootstrap({\n * middlewares: [requestId(), requestLogger(), express.json()],\n * })\n * ```\n *\n * Output:\n * ```\n * [HTTP] GET /api/v1/users 200 12ms req-abc123\n * [HTTP] POST /api/v1/users 201 45ms req-def456\n * ```\n */\nexport function requestLogger(options: RequestLoggerOptions = {}) {\n const log = createLogger(options.name ?? 'HTTP')\n const level = options.level ?? 'info'\n const skip = options.skip ?? []\n\n return (req: LoggedRequest, res: LoggedResponse, next: () => void) => {\n // `req.path` is Express-only. Under Fastify and h3 it is `undefined`, so\n // this threw `Cannot read properties of undefined (reading 'startsWith')`\n // on EVERY request as soon as a `skip` prefix was configured — the\n // middleware crashed the request rather than declining to log it.\n const pathname = req.path ?? pathnameOf(req.url)\n if (skip.some((prefix) => pathname.startsWith(prefix))) {\n return next()\n }\n\n const start = Date.now()\n\n res.on('finish', () => {\n const duration = Date.now() - start\n const requestId = (req as any).requestId || req.headers['x-request-id'] || '-'\n const status = res.statusCode\n\n // `originalUrl` is Express-only — on Fastify and h3 this logged\n // `GET undefined 200 12ms`, dropping the path from every access-log\n // line under those runtimes.\n // Both are optional, so the pair still needs a floor — otherwise the\n // line reads `GET undefined` again, just via a different route.\n const path = req.originalUrl ?? req.url ?? '/'\n // The same line as always, with the parts as fields too — a provider\n // writing JSON (`LOG_FORMAT=json`, pino) gets queryable columns.\n const fields = log.child({ method: req.method, path, status, ms: duration, requestId })\n fields[level](`${req.method} ${path} ${status} ${duration}ms ${requestId}`)\n })\n\n next()\n }\n}\n"],"mappings":";;;;;;;;;;A,gFAmCA,SAAS,WAAW,IAAiC,CACnD,GAAI,CAAC,IAAK,MAAO,IACjB,IAAM,EAAI,IAAI,QAAQ,GAAG,EACzB,OAAQ,IAAM,GAAK,IAAM,IAAI,MAAM,EAAG,CAAC,IAAM,GAC/C,CA4BA,SAAgB,cAAc,QAAgC,CAAC,EAAG,CAChE,IAAM,IAAM,aAAa,QAAQ,MAAQ,MAAM,EACzC,MAAQ,QAAQ,OAAS,OACzB,KAAO,QAAQ,MAAQ,CAAC,EAE9B,OAAQ,IAAoB,IAAqB,OAAqB,CAKpE,IAAM,SAAW,IAAI,MAAQ,WAAW,IAAI,GAAG,EAC/C,GAAI,KAAK,KAAM,QAAW,SAAS,WAAW,MAAM,CAAC,EACnD,OAAO,KAAK,EAGd,IAAM,MAAQ,KAAK,IAAI,EAEvB,IAAI,GAAG,aAAgB,CACrB,IAAM,SAAW,KAAK,IAAI,EAAI,MACxB,UAAa,IAAY,WAAa,IAAI,QAAQ,iBAAmB,IACrE,OAAS,IAAI,WAOb,KAAO,IAAI,aAAe,IAAI,KAAO,IAI3C,IADmB,MAAM,CAAE,OAAQ,IAAI,OAAQ,KAAM,OAAQ,GAAI,SAAU,SAAU,CAChF,CAAC,CAAC,MAAM,CAAC,GAAG,IAAI,OAAO,GAAG,KAAK,GAAG,OAAO,GAAG,SAAS,KAAK,WAAW,CAC5E,CAAC,EAED,KAAK,CACP,CACF,C"}
1
+ {"version":3,"file":"request-logger.mjs","names":[],"sources":["../../../src/http/middleware/request-logger.ts"],"sourcesContent":["/**\n * The slice of the request/response this logger touches, from node's shapes\n * rather than Express's. This runs under EVERY runtime — Fastify and h3 hand\n * connect middleware the raw node objects — so anything Express-only is\n * `undefined` there.\n */\n/**\n * The request shape this middleware reads.\n *\n * Exported because it appears in the returned handler's signature: a consumer\n * following the documented `src/middleware/index.ts` layout exports the\n * middleware array with an inferred type, and a type the entry does not\n * re-export cannot be named there — `TS4023: Exported variable 'middleware'\n * has or is using name 'LoggedRequest' … but cannot be named`.\n *\n * Deliberately structural rather than Express's `Request`: the Fastify and h3\n * runtimes pass a raw Node request, which has `url` but no `path`.\n */\nexport interface LoggedRequest {\n method?: string\n url?: string\n /** Express-only convenience; the raw node request has only `url`. */\n path?: string\n /** Express-only; absent on the raw node request the other runtimes pass. */\n originalUrl?: string\n headers: Record<string, string | string[] | undefined>\n}\n\n/** The response shape this middleware reads. Exported for the same reason as {@link LoggedRequest}. */\nexport interface LoggedResponse {\n statusCode: number\n on(event: 'finish', listener: () => void): unknown\n}\n\n/** Pathname only — `req.url` carries the query string. */\nfunction pathnameOf(url: string | undefined): string {\n if (!url) return '/'\n const q = url.indexOf('?')\n return (q === -1 ? url : url.slice(0, q)) || '/'\n}\nimport { createLogger } from '../../core'\n\n/**\n * Options for {@link requestLogger}.\n *\n * @see https://kickjs.app/guide/logging\n */\nexport interface RequestLoggerOptions {\n /** Logger name (default: 'HTTP') */\n name?: string\n /** Log level for successful requests (default: 'info') */\n level?: 'info' | 'debug' | 'trace'\n /** Skip logging for paths matching these prefixes (e.g. ['/health', '/_debug']) */\n skip?: string[]\n}\n\n/**\n * Middleware that logs every request with method, URL, status, duration, and request ID.\n *\n * @example\n * ```ts\n * bootstrap({\n * middlewares: [requestId(), requestLogger(), express.json()],\n * })\n * ```\n *\n * Output:\n * ```\n * [HTTP] GET /api/v1/users 200 12ms req-abc123\n * [HTTP] POST /api/v1/users 201 45ms req-def456\n * ```\n */\nexport function requestLogger(options: RequestLoggerOptions = {}) {\n const log = createLogger(options.name ?? 'HTTP')\n const level = options.level ?? 'info'\n const skip = options.skip ?? []\n\n return (req: LoggedRequest, res: LoggedResponse, next: () => void) => {\n // `req.path` is Express-only. Under Fastify and h3 it is `undefined`, so\n // this threw `Cannot read properties of undefined (reading 'startsWith')`\n // on EVERY request as soon as a `skip` prefix was configured — the\n // middleware crashed the request rather than declining to log it.\n const pathname = req.path ?? pathnameOf(req.url)\n if (skip.some((prefix) => pathname.startsWith(prefix))) {\n return next()\n }\n\n const start = Date.now()\n\n res.on('finish', () => {\n const duration = Date.now() - start\n const requestId = (req as any).requestId || req.headers['x-request-id'] || '-'\n const status = res.statusCode\n\n // `originalUrl` is Express-only — on Fastify and h3 this logged\n // `GET undefined 200 12ms`, dropping the path from every access-log\n // line under those runtimes.\n // Both are optional, so the pair still needs a floor — otherwise the\n // line reads `GET undefined` again, just via a different route.\n const path = req.originalUrl ?? req.url ?? '/'\n // The same line as always, with the parts as fields too — a provider\n // writing JSON (`LOG_FORMAT=json`, pino) gets queryable columns.\n const fields = log.child({ method: req.method, path, status, ms: duration, requestId })\n fields[level](`${req.method} ${path} ${status} ${duration}ms ${requestId}`)\n })\n\n next()\n }\n}\n"],"mappings":";;;;;;;;;;A,gFAmCA,SAAS,WAAW,IAAiC,CACnD,GAAI,CAAC,IAAK,MAAO,IACjB,IAAM,EAAI,IAAI,QAAQ,GAAG,EACzB,OAAQ,IAAM,GAAK,IAAM,IAAI,MAAM,EAAG,CAAC,IAAM,GAC/C,CAiCA,SAAgB,cAAc,QAAgC,CAAC,EAAG,CAChE,IAAM,IAAM,aAAa,QAAQ,MAAQ,MAAM,EACzC,MAAQ,QAAQ,OAAS,OACzB,KAAO,QAAQ,MAAQ,CAAC,EAE9B,OAAQ,IAAoB,IAAqB,OAAqB,CAKpE,IAAM,SAAW,IAAI,MAAQ,WAAW,IAAI,GAAG,EAC/C,GAAI,KAAK,KAAM,QAAW,SAAS,WAAW,MAAM,CAAC,EACnD,OAAO,KAAK,EAGd,IAAM,MAAQ,KAAK,IAAI,EAEvB,IAAI,GAAG,aAAgB,CACrB,IAAM,SAAW,KAAK,IAAI,EAAI,MACxB,UAAa,IAAY,WAAa,IAAI,QAAQ,iBAAmB,IACrE,OAAS,IAAI,WAOb,KAAO,IAAI,aAAe,IAAI,KAAO,IAG5B,IAAI,MAAM,CAAE,OAAQ,IAAI,OAAQ,KAAM,OAAQ,GAAI,SAAU,SAAU,CAChF,CAAC,CAAC,MAAM,CAAC,GAAG,IAAI,OAAO,GAAG,KAAK,GAAG,OAAO,GAAG,SAAS,KAAK,WAAW,CAC5E,CAAC,EAED,KAAK,CACP,CACF,C"}
@@ -1,3 +1,3 @@
1
1
 
2
- import { a as SessionStore, i as SessionOptions, n as Session, o as session, r as SessionData, t as MemoryStore } from "../../session-CXWu2rXW.mjs";
2
+ import { a as SessionStore, i as SessionOptions, n as Session, o as session, r as SessionData, t as MemoryStore } from "../../session-DPTbfwKO.mjs";
3
3
  export { MemoryStore, Session, SessionData, SessionOptions, SessionStore, session };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.14.2
2
+ * @forinda/kickjs v10.15.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{a as setCookie,r as replaceCookie,t as parseCookieHeader}from"../../respond-C6ohI69y.mjs";import{createLogger}from"../../core/logger.mjs";import{n as WebResponseDriver}from"../../driver-oZBQDJZz.mjs";import{r as registerDisposable}from"../../disposables-BsdVu69-.mjs";import{t as isProduction}from"../../is-production-9QzMIRuO.mjs";import{createCipheriv,createDecipheriv,createHmac,hkdfSync,randomBytes,randomUUID,timingSafeEqual}from"node:crypto";var MemoryStore=class{sessions=/* @__PURE__ */ new Map;empty=/* @__PURE__ */ new Set;cleanupInterval;constructor(){this.cleanupInterval=setInterval(()=>this.purge(),6e4),this.cleanupInterval.unref(),registerDisposable(()=>this.dispose())}dispose(){clearInterval(this.cleanupInterval),this.sessions.clear(),this.empty.clear()}async get(sid){let entry=this.sessions.get(sid);return entry?Date.now()>entry.expires?(this.sessions.delete(sid),this.empty.delete(sid),null):entry.data:null}async set(sid,data,maxAge){for(this.sessions.delete(sid),this.sessions.set(sid,{data,expires:Date.now()+maxAge}),this.empty.delete(sid),Object.keys(data).length===0&&this.empty.add(sid);this.sessions.size>1e4;){let victim=this.empty.values().next().value??this.sessions.keys().next().value;this.sessions.delete(victim),this.empty.delete(victim)}}async destroy(sid){this.sessions.delete(sid),this.empty.delete(sid)}async touch(sid,maxAge){let entry=this.sessions.get(sid);entry&&(entry.expires=Date.now()+maxAge,this.sessions.delete(sid),this.sessions.set(sid,entry))}purge(){let now=Date.now();for(let[sid,entry]of this.sessions)now>entry.expires&&(this.sessions.delete(sid),this.empty.delete(sid))}};function secretList(secret){let list=Array.isArray(secret)?secret:[secret];if(list.length===0||list.some(s=>typeof s!=`string`||s.length===0))throw Error("session(): `secret` must be a non-empty string or list of strings");return list}function sign(value,secret){return`s:${value}.${createHmac(`sha256`,secret).update(value).digest(`base64url`)}`}function unsign(signed,secrets){if(!signed.startsWith(`s:`))return!1;let raw=signed.slice(2),dotIndex=raw.lastIndexOf(`.`);if(dotIndex===-1)return!1;let value=raw.slice(0,dotIndex),provided=Buffer.from(raw.slice(dotIndex+1));for(let[index,secret]of secrets.entries()){let expected=Buffer.from(createHmac(`sha256`,secret).update(value).digest(`base64url`));if(provided.length===expected.length&&timingSafeEqual(provided,expected))return{value,stale:index>0}}return!1}const storeLog=createLogger(`Session`);function session(options){if(options.store===`cookie`)return cookieSession(options);let{cookieName=`kick.sid`,maxAge=864e5,rolling=!1,saveUninitialized=!0,saveTimeout=5e3,cookie:cookieOpts={}}=options,secrets=secretList(options.secret),secret=secrets[0],store=options.store??new MemoryStore,cookieDefaults={httpOnly:cookieOpts.httpOnly??!0,secure:cookieOpts.secure??isProduction(),sameSite:cookieOpts.sameSite??`lax`,path:cookieOpts.path??`/`,...cookieOpts.domain?{domain:cookieOpts.domain}:{},maxAge};return async(req,res,next)=>{let cookies=req.cookies;if(!cookies){let header=req.headers.cookie;cookies=header?parseCookieHeader(header):{}}let signedCookie=cookies[cookieName],sid=!1,sessionData=null,isNew=!1,staleSignature=!1;if(signedCookie){let unsigned=unsign(signedCookie,secrets);unsigned&&(sid=unsigned.value,staleSignature=unsigned.stale,sessionData=await store.get(sid))}sid&&sessionData||(sid=randomUUID(),sessionData={},isNew=!0);let currentSid=sid,currentData={...sessionData},destroyed=!1,sessionObj={get id(){return currentSid},data:currentData,async regenerate(){await store.destroy(currentSid),currentSid=randomUUID(),currentData={},sessionObj.data=currentData,await store.set(currentSid,currentData,maxAge),setCookie(res,cookieName,sign(currentSid,secret),cookieDefaults)},async destroy(){await store.destroy(currentSid),destroyed=!0,currentData={},sessionObj.data=currentData,setCookie(res,cookieName,``,{...cookieDefaults,maxAge:0,expires:/* @__PURE__ */ new Date(0)})},async save(){destroyed||await store.set(currentSid,currentData,maxAge)}};req.session=sessionObj,isNew&&setCookie(res,cookieName,sign(currentSid,secret),cookieDefaults);let persisted,persist=()=>persisted??=(async()=>{destroyed||(!isNew||saveUninitialized||Object.keys(currentData).length!==0)&&(await store.set(currentSid,currentData,maxAge),rolling&&!isNew&&store.touch&&await store.touch(currentSid,maxAge))})(),saved=()=>new Promise(done=>{let timer=setTimeout(()=>{storeLog.error(`Session save took over ${saveTimeout}ms; sending the response anyway`),done()},saveTimeout);persist().then(()=>{clearTimeout(timer),done()},err=>{clearTimeout(timer),storeLog.error(err,`Session save failed; sending the response anyway`),done()})});if(res instanceof WebResponseDriver)res.on(`finish`,()=>saved());else{let end=res.end;res.end=function(...args){return saved().then(()=>end.apply(this,args)),this}}!isNew&&(rolling||staleSignature)&&setCookie(res,cookieName,sign(currentSid,secret),cookieDefaults),next()}}const cookieLog=createLogger(`Session`);function sealer(secrets,cookieName){let keys=secrets.map(secret=>Buffer.from(hkdfSync(`sha256`,secret,`kick.session`,`cookie-store-v1`,32))),key=keys[0],aad=Buffer.from(cookieName);return{seal(payload){let iv=randomBytes(12),cipher=createCipheriv(`aes-256-gcm`,key,iv).setAAD(aad),body=Buffer.concat([cipher.update(JSON.stringify(payload),`utf8`),cipher.final()]);return`v1.${Buffer.concat([iv,cipher.getAuthTag(),body]).toString(`base64url`)}`},open(value){if(!value.startsWith(`v1.`))return null;let raw;try{raw=Buffer.from(value.slice(3),`base64url`)}catch{return null}if(raw.length<29)return null;for(let[index,k]of keys.entries())try{let decipher=createDecipheriv(`aes-256-gcm`,k,raw.subarray(0,12)).setAAD(aad).setAuthTag(raw.subarray(12,28)),json=Buffer.concat([decipher.update(raw.subarray(28)),decipher.final()]),payload=JSON.parse(json.toString(`utf8`));return typeof payload?.i!=`string`||typeof payload.e!=`number`||!payload.d||typeof payload.d!=`object`?null:payload.e>Date.now()?{payload,stale:index>0}:null}catch{}return null}}}function cookieSession(options){let{cookieName=`kick.sid`,maxAge=864e5,rolling=!1,saveUninitialized=!0,cookie:cookieOpts={}}=options,{seal,open}=sealer(secretList(options.secret),cookieName),cookieDefaults={httpOnly:cookieOpts.httpOnly??!0,secure:cookieOpts.secure??isProduction(),sameSite:cookieOpts.sameSite??`lax`,path:cookieOpts.path??`/`,...cookieOpts.domain?{domain:cookieOpts.domain}:{}},warnedSize=!1;return(req,res,next)=>{let cookies=req.cookies;if(!cookies){let header=req.headers.cookie;cookies=header?parseCookieHeader(header):{}}let opened=cookies[cookieName]?open(cookies[cookieName]):null,existing=opened?.payload??null,isNew=!existing,id=existing?.i??randomUUID(),destroyed=!1,written=existing&&!opened?.stale?JSON.stringify(existing.d):void 0,write=(force=!1)=>{if(res.headersSent)return;if(destroyed){replaceCookie(res,cookieName,``,{...cookieDefaults,maxAge:0,expires:/* @__PURE__ */ new Date(0)});return}let json=JSON.stringify(sessionObj.data);if(json===written&&!force&&(!rolling||isNew)||written===void 0&&json===`{}`&&!saveUninitialized&&!force)return;let value=seal({i:id,d:sessionObj.data,e:Date.now()+maxAge});value.length+cookieName.length>4e3&&!warnedSize&&(warnedSize=!0,cookieLog.warn(`session cookie is ${value.length} bytes; browsers drop cookies over 4 KB, so this session will not be kept. Store less in it, or use a shared store.`)),replaceCookie(res,cookieName,value,{...cookieDefaults,maxAge}),written=json};for(let method of[`writeHead`,`flushHeaders`,`write`,`end`]){let original=res[method];typeof original==`function`&&(res[method]=function(...args){return write(),original.apply(this,args)})}res.on?.(`finish`,()=>write());let sessionObj={get id(){return id},data:existing?{...existing.d}:{},async regenerate(){id=randomUUID(),sessionObj.data={},written=void 0,write(!0)},async destroy(){destroyed=!0,sessionObj.data={},write()},async save(){write()}};req.session=sessionObj,next()}}export{MemoryStore,session};
11
+ import{a as setCookie,r as replaceCookie,t as parseCookieHeader}from"../../respond-1BjaDME9.mjs";import{createLogger}from"../../core/logger.mjs";import{n as WebResponseDriver}from"../../driver-D59oWDec.mjs";import{r as registerDisposable}from"../../disposables-BC291ukb.mjs";import{t as isProduction}from"../../is-production-LziEMGrc.mjs";import{createCipheriv,createDecipheriv,createHmac,hkdfSync,randomBytes,randomUUID,timingSafeEqual}from"node:crypto";var MemoryStore=class{sessions=/* @__PURE__ */ new Map;empty=/* @__PURE__ */ new Set;cleanupInterval;constructor(){this.cleanupInterval=setInterval(()=>this.purge(),6e4),this.cleanupInterval.unref(),registerDisposable(()=>this.dispose())}dispose(){clearInterval(this.cleanupInterval),this.sessions.clear(),this.empty.clear()}async get(sid){let entry=this.sessions.get(sid);return entry?Date.now()>entry.expires?(this.sessions.delete(sid),this.empty.delete(sid),null):entry.data:null}async set(sid,data,maxAge){for(this.sessions.delete(sid),this.sessions.set(sid,{data,expires:Date.now()+maxAge}),this.empty.delete(sid),Object.keys(data).length===0&&this.empty.add(sid);this.sessions.size>1e4;){let victim=this.empty.values().next().value??this.sessions.keys().next().value;this.sessions.delete(victim),this.empty.delete(victim)}}async destroy(sid){this.sessions.delete(sid),this.empty.delete(sid)}async touch(sid,maxAge){let entry=this.sessions.get(sid);entry&&(entry.expires=Date.now()+maxAge,this.sessions.delete(sid),this.sessions.set(sid,entry))}purge(){let now=Date.now();for(let[sid,entry]of this.sessions)now>entry.expires&&(this.sessions.delete(sid),this.empty.delete(sid))}};function secretList(secret){let list=Array.isArray(secret)?secret:[secret];if(list.length===0||list.some(s=>typeof s!=`string`||s.length===0))throw Error("session(): `secret` must be a non-empty string or list of strings");return list}function sign(value,secret){return`s:${value}.${createHmac(`sha256`,secret).update(value).digest(`base64url`)}`}function unsign(signed,secrets){if(!signed.startsWith(`s:`))return!1;let raw=signed.slice(2),dotIndex=raw.lastIndexOf(`.`);if(dotIndex===-1)return!1;let value=raw.slice(0,dotIndex),provided=Buffer.from(raw.slice(dotIndex+1));for(let[index,secret]of secrets.entries()){let expected=Buffer.from(createHmac(`sha256`,secret).update(value).digest(`base64url`));if(provided.length===expected.length&&timingSafeEqual(provided,expected))return{value,stale:index>0}}return!1}const storeLog=createLogger(`Session`);function session(options){if(options.store===`cookie`)return cookieSession(options);let{cookieName=`kick.sid`,maxAge=864e5,rolling=!1,saveUninitialized=!0,saveTimeout=5e3,cookie:cookieOpts={}}=options,secrets=secretList(options.secret),secret=secrets[0],store=options.store??new MemoryStore,cookieDefaults={httpOnly:cookieOpts.httpOnly??!0,secure:cookieOpts.secure??isProduction(),sameSite:cookieOpts.sameSite??`lax`,path:cookieOpts.path??`/`,...cookieOpts.domain?{domain:cookieOpts.domain}:{},maxAge};return async(req,res,next)=>{let cookies=req.cookies;if(!cookies){let header=req.headers.cookie;cookies=header?parseCookieHeader(header):{}}let signedCookie=cookies[cookieName],sid=!1,sessionData=null,isNew=!1,staleSignature=!1;if(signedCookie){let unsigned=unsign(signedCookie,secrets);unsigned&&(sid=unsigned.value,staleSignature=unsigned.stale,sessionData=await store.get(sid))}sid&&sessionData||(sid=randomUUID(),sessionData={},isNew=!0);let currentSid=sid,currentData={...sessionData},destroyed=!1,sessionObj={get id(){return currentSid},data:currentData,async regenerate(){await store.destroy(currentSid),currentSid=randomUUID(),currentData={},sessionObj.data=currentData,await store.set(currentSid,currentData,maxAge),setCookie(res,cookieName,sign(currentSid,secret),cookieDefaults)},async destroy(){await store.destroy(currentSid),destroyed=!0,currentData={},sessionObj.data=currentData,setCookie(res,cookieName,``,{...cookieDefaults,maxAge:0,expires:/* @__PURE__ */ new Date(0)})},async save(){destroyed||await store.set(currentSid,currentData,maxAge)}};req.session=sessionObj,isNew&&setCookie(res,cookieName,sign(currentSid,secret),cookieDefaults);let persisted,persist=()=>persisted??=(async()=>{destroyed||(!isNew||saveUninitialized||Object.keys(currentData).length!==0)&&(await store.set(currentSid,currentData,maxAge),rolling&&!isNew&&store.touch&&await store.touch(currentSid,maxAge))})(),saved=()=>new Promise(done=>{let timer=setTimeout(()=>{storeLog.error(`Session save took over ${saveTimeout}ms; sending the response anyway`),done()},saveTimeout);persist().then(()=>{clearTimeout(timer),done()},err=>{clearTimeout(timer),storeLog.error(err,`Session save failed; sending the response anyway`),done()})});if(res instanceof WebResponseDriver)res.on(`finish`,()=>saved());else{let end=res.end;res.end=function(...args){return saved().then(()=>end.apply(this,args)),this}}!isNew&&(rolling||staleSignature)&&setCookie(res,cookieName,sign(currentSid,secret),cookieDefaults),next()}}const cookieLog=createLogger(`Session`);function sealer(secrets,cookieName){let keys=secrets.map(secret=>Buffer.from(hkdfSync(`sha256`,secret,`kick.session`,`cookie-store-v1`,32))),key=keys[0],aad=Buffer.from(cookieName);return{seal(payload){let iv=randomBytes(12),cipher=createCipheriv(`aes-256-gcm`,key,iv).setAAD(aad),body=Buffer.concat([cipher.update(JSON.stringify(payload),`utf8`),cipher.final()]);return`v1.${Buffer.concat([iv,cipher.getAuthTag(),body]).toString(`base64url`)}`},open(value){if(!value.startsWith(`v1.`))return null;let raw;try{raw=Buffer.from(value.slice(3),`base64url`)}catch{return null}if(raw.length<29)return null;for(let[index,k]of keys.entries())try{let decipher=createDecipheriv(`aes-256-gcm`,k,raw.subarray(0,12)).setAAD(aad).setAuthTag(raw.subarray(12,28)),json=Buffer.concat([decipher.update(raw.subarray(28)),decipher.final()]),payload=JSON.parse(json.toString(`utf8`));return typeof payload?.i!=`string`||typeof payload.e!=`number`||!payload.d||typeof payload.d!=`object`?null:payload.e>Date.now()?{payload,stale:index>0}:null}catch{}return null}}}function cookieSession(options){let{cookieName=`kick.sid`,maxAge=864e5,rolling=!1,saveUninitialized=!0,cookie:cookieOpts={}}=options,{seal,open}=sealer(secretList(options.secret),cookieName),cookieDefaults={httpOnly:cookieOpts.httpOnly??!0,secure:cookieOpts.secure??isProduction(),sameSite:cookieOpts.sameSite??`lax`,path:cookieOpts.path??`/`,...cookieOpts.domain?{domain:cookieOpts.domain}:{}},warnedSize=!1;return(req,res,next)=>{let cookies=req.cookies;if(!cookies){let header=req.headers.cookie;cookies=header?parseCookieHeader(header):{}}let opened=cookies[cookieName]?open(cookies[cookieName]):null,existing=opened?.payload??null,isNew=!existing,id=existing?.i??randomUUID(),destroyed=!1,written=existing&&!opened?.stale?JSON.stringify(existing.d):void 0,write=(force=!1)=>{if(res.headersSent)return;if(destroyed){replaceCookie(res,cookieName,``,{...cookieDefaults,maxAge:0,expires:/* @__PURE__ */ new Date(0)});return}let json=JSON.stringify(sessionObj.data);if(json===written&&!force&&(!rolling||isNew)||written===void 0&&json===`{}`&&!saveUninitialized&&!force)return;let value=seal({i:id,d:sessionObj.data,e:Date.now()+maxAge});value.length+cookieName.length>4e3&&!warnedSize&&(warnedSize=!0,cookieLog.warn(`session cookie is ${value.length} bytes; browsers drop cookies over 4 KB, so this session will not be kept. Store less in it, or use a shared store.`)),replaceCookie(res,cookieName,value,{...cookieDefaults,maxAge}),written=json};for(let method of[`writeHead`,`flushHeaders`,`write`,`end`]){let original=res[method];typeof original==`function`&&(res[method]=function(...args){return write(),original.apply(this,args)})}res.on?.(`finish`,()=>write());let sessionObj={get id(){return id},data:existing?{...existing.d}:{},async regenerate(){id=randomUUID(),sessionObj.data={},written=void 0,write(!0)},async destroy(){destroyed=!0,sessionObj.data={},write()},async save(){write()}};req.session=sessionObj,next()}}export{MemoryStore,session};
12
12
  //# sourceMappingURL=session.mjs.map
@@ -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 { 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 /**\n * The save, waited for at most `saveTimeout` ms: a stalled store mustn't hold\n * the response forever. Never rejects — a failure is logged.\n */\n const saved = (): Promise<void> =>\n new Promise((done) => {\n const timer = setTimeout(() => {\n storeLog.error(`Session save took over ${saveTimeout}ms; sending the response anyway`)\n done()\n }, saveTimeout)\n persist().then(\n () => {\n clearTimeout(timer)\n done()\n },\n (err: unknown) => {\n clearTimeout(timer)\n storeLog.error(err, 'Session save failed; sending the response anyway')\n done()\n },\n )\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(); h3 through fetch waits\n // for the promise the `finish` listener below returns instead.\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 void saved().then(() => end.apply(this, args))\n return this\n }\n }\n // The fetch drivers: h3 through fetch waits for this promise before handing\n // back the response. (A Node response saved in end(), above.)\n else res.on('finish', () => saved())\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":";;;;;;;;;;A,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,OA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,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,C"}
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\n/**\n * Where server-side session data lives. Implement it to keep sessions in a shared store; `touch` is optional.\n *\n * @see https://kickjs.app/guide/sessions\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\n/**\n * The session on a request, set by {@link session}: its ID, data, and methods to regenerate, destroy or save it.\n *\n * @see https://kickjs.app/guide/sessions\n */\nexport interface Session {\n id: string\n data: SessionData\n regenerate(): Promise<void>\n destroy(): Promise<void>\n save(): Promise<void>\n}\n\n/**\n * Options for {@link session}.\n *\n * @see https://kickjs.app/guide/sessions\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\nconst storeLog = createLogger('Session')\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 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 /**\n * The save, waited for at most `saveTimeout` ms: a stalled store mustn't hold\n * the response forever. Never rejects — a failure is logged.\n */\n const saved = (): Promise<void> =>\n new Promise((done) => {\n const timer = setTimeout(() => {\n storeLog.error(`Session save took over ${saveTimeout}ms; sending the response anyway`)\n done()\n }, saveTimeout)\n persist().then(\n () => {\n clearTimeout(timer)\n done()\n },\n (err: unknown) => {\n clearTimeout(timer)\n storeLog.error(err, 'Session save failed; sending the response anyway')\n done()\n },\n )\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(); h3 through fetch waits\n // for the promise the `finish` listener below returns instead.\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 void saved().then(() => end.apply(this, args))\n return this\n }\n }\n // The fetch drivers: h3 through fetch waits for this promise before handing\n // back the response. (A Node response saved in end(), above.)\n else res.on('finish', () => saved())\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":";;;;;;;;;;A,ucA0HA,IAAa,YAAb,KAAiD,CAC9B,yBAAW,IAAI,IAEf,sBAAQ,IAAI,IACZ,gBAEjB,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,CAAC,CAAC,KAAK,CAAC,CAAC,MAC/E,KAAK,SAAS,OAAO,MAAM,EAC3B,KAAK,MAAM,OAAO,MAAM,CAC1B,CACF,CAEA,MAAM,QAAQ,IAA4B,CACxC,KAAK,SAAS,OAAO,GAAG,EACxB,KAAK,MAAM,O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AM,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,aACtB,IAAgD,QAAU,SAE1D,GAAG,KACH,CAEA,OADA,MAAM,EACC,SAAS,MAAM,KAAM,IAAI,CAClC,EACF,CAKE,IAAuE,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,EACE,IAAY,QAAU,WACxB,KAAK,CACP,CACF,C"}
@@ -1,3 +1,3 @@
1
1
 
2
- import { b as SpaAdapterOptions, x as resolveClientDir, y as SpaAdapter } from "../../application-CGcY8SZZ.mjs";
2
+ import { b as SpaAdapterOptions, x as resolveClientDir, y as SpaAdapter } from "../../application-ClCq0AgY.mjs";
3
3
  export { SpaAdapter, SpaAdapterOptions, resolveClientDir };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.14.2
2
+ * @forinda/kickjs v10.15.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-CCIpjo6g.mjs";import{t as defineAdapter}from"../../define-adapter-DMo6og81.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-Dqzah_BX.mjs";import{t as defineAdapter}from"../../define-adapter-DCjNTP6m.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 +1 @@
1
- {"version":3,"file":"spa.mjs","names":["\"accept\""],"sources":["../../../src/http/middleware/spa.ts"],"sourcesContent":["import { existsSync, readdirSync, readFileSync } from 'node:fs'\nimport { resolve, join, dirname, isAbsolute } from 'node:path'\nimport { Logger, defineAdapter } from '../../core'\nimport type { ConnectMiddleware } from '../runtime'\n\nconst log = Logger.for('SpaAdapter')\n\nexport interface SpaAdapterOptions {\n /**\n * Directory containing the built SPA files (index.html, assets, etc.)\n * Default: 'dist/client'\n *\n * @example\n * ```ts\n * // Vue: 'dist'\n * // React (Vite): 'dist'\n * // React (CRA): 'build'\n * // Svelte: 'build'\n * // Angular: 'dist/my-app/browser'\n * ```\n */\n clientDir?: string\n\n /**\n * URL prefix for API routes. SPA fallback only applies to\n * non-API routes (routes NOT starting with this prefix).\n * Default: '/api'\n *\n * Matching is segment-aware: `/api` excludes `/api` and `/api/users`, but\n * NOT `/apidocs` — a plain `startsWith` swallowed any path that merely\n * began with the same letters.\n *\n * Set to an array for multiple prefixes:\n * ```ts\n * apiPrefix: ['/api', '/graphql', '/_debug']\n * ```\n */\n apiPrefix?: string | string[]\n\n /**\n * Additional paths to exclude from SPA fallback.\n * These paths will NOT serve index.html. Segment-aware, like `apiPrefix`.\n *\n * @example\n * ```ts\n * exclude: ['/health', '/metrics', '/ws']\n * ```\n */\n exclude?: string[]\n\n /**\n * Cache-Control header for static assets (default: 'public, max-age=31536000, immutable')\n * Set to false to disable caching headers.\n */\n cacheControl?: string | false\n\n /**\n * Cache-Control for index.html (default: 'no-cache')\n * index.html should not be cached to ensure clients get fresh builds.\n */\n indexCacheControl?: string\n\n /**\n * Serve index.html even when the client did not ask for HTML.\n * Default: false.\n *\n * By default the fallback only fires for requests whose `Accept` header\n * includes `text/html` — the rule `connect-history-api-fallback` uses. That\n * keeps a missing `/assets/app.js` a 404 instead of handing back an HTML\n * document that the browser then fails to parse as JavaScript, which is a\n * confusing way to discover a broken build.\n *\n * Turn this on if you have non-browser clients that deep-link into SPA\n * routes without an `Accept` header.\n */\n alwaysFallback?: boolean\n}\n\n/**\n * Nearest directory at or above `from` that holds a `package.json`.\n * `null` when the walk reaches the filesystem root without finding one.\n */\nfunction nearestPackageRoot(from: string): string | null {\n let dir = from\n for (;;) {\n if (existsSync(join(dir, 'package.json'))) return dir\n const parent = dirname(dir)\n if (parent === dir) return null\n dir = parent\n }\n}\n\n/**\n * Where to look for the built SPA.\n *\n * `process.cwd()` is the framework's convention (assets and env files resolve\n * the same way) and stays the primary base. But a relative `clientDir` then\n * only works when the process happens to be started from the app directory —\n * `node server/dist/index.js` run from a monorepo root resolved `../web/dist`\n * against the root and found nothing, serving no SPA with only a warning.\n *\n * So: try cwd first, and only if that misses, retry against the package root\n * of the entry script. Both are checked for existence before being chosen, so\n * this can never silently pick a directory that is not there — a genuinely\n * missing build still lands on the cwd path, which is what the warning names.\n *\n * Deliberately not entry-relative FIRST: under `kick dev` the entry is the CLI\n * binary, whose package root is the CLI itself.\n *\n * Exported for tests only — not re-exported from the package index.\n */\nexport function resolveClientDir(\n clientDir: string,\n // Injected rather than read from the process so tests can exercise the\n // monorepo-root case without `process.chdir` / `process.argv` mutation —\n // neither is supported under vitest's `threads` pool, and the root config\n // uses exactly that.\n cwd: string = process.cwd(),\n entry: string | undefined = process.argv[1],\n): string {\n // `resolve` even for an already-absolute path: `resolvesToFile` compares its\n // (always normalized) target against this string, so a trailing slash or a\n // `.`/`..` segment here would make the containment check never match and\n // silently drop the Cache-Control header on every request. Fails closed, so\n // it never weakened the traversal guard — it just stopped doing its job.\n if (isAbsolute(clientDir)) return resolve(clientDir)\n const fromCwd = resolve(cwd, clientDir)\n if (existsSync(fromCwd)) return fromCwd\n\n if (entry) {\n const root = nearestPackageRoot(dirname(resolve(entry)))\n if (root) {\n const fromEntry = resolve(root, clientDir)\n if (existsSync(fromEntry)) return fromEntry\n }\n }\n return fromCwd\n}\n\n/**\n * The slice of the request/response this adapter touches, spelled from the\n * node `http` shapes rather than Express's. `ConnectMiddleware` is typed as\n * Express's `RequestHandler`, but under Fastify and h3 these handlers receive\n * the raw node objects (or a driver), so relying on `req.path` / `res.send`\n * is what made the previous version Express-only.\n */\ninterface SpaRequest {\n url?: string\n method?: string\n headers?: Record<string, string | string[] | undefined>\n}\n\ninterface SpaResponse {\n setHeader(name: string, value: string): void\n statusCode: number\n end(chunk?: string): void\n}\n\ntype SpaHandler = (req: SpaRequest, res: SpaResponse, next: () => void) => void\n\n/** Pathname only — `req.url` carries the query string, and `req.path` is Express-only. */\nfunction pathnameOf(url: string | undefined): string {\n if (!url) return '/'\n const q = url.indexOf('?')\n const h = url.indexOf('#')\n const end = Math.min(q === -1 ? url.length : q, h === -1 ? url.length : h)\n return url.slice(0, end) || '/'\n}\n\n/**\n * Segment-aware prefix test: `/api` covers `/api` and `/api/users`, not\n * `/apidocs`. `startsWith` alone made any same-prefixed route disappear from\n * the SPA fallback and 404 instead.\n */\nfunction isUnder(pathname: string, prefix: string): boolean {\n if (!prefix || prefix === '/') return true\n const p = prefix.endsWith('/') ? prefix.slice(0, -1) : prefix\n return pathname === p || pathname.startsWith(`${p}/`)\n}\n\n/** Media ranges that count as \"the client wants a document\". */\nconst HTML_TYPES = ['text/html', 'application/xhtml+xml']\n\n/** `q` for a media range, defaulting to 1 when absent or unparseable. */\nfunction qualityOf(params: string[]): number {\n const q = params.find((param) => param.startsWith('q='))\n if (!q) return 1\n const value = Number.parseFloat(q.slice(2))\n return Number.isNaN(value) ? 1 : value\n}\n\n/**\n * Does the client want an HTML document back?\n *\n * Parses media ranges with q-values rather than substring-matching:\n * `Accept: text/html;q=0` explicitly says HTML is NOT acceptable (RFC 9110\n * §12.5.1 — \"a value of 0 means not acceptable\"), and a substring check read\n * that as a yes and returned the document anyway.\n *\n * Wildcards are matched by specificity, as RFC 9110 §12.5.1 requires: an exact\n * `text/html` beats `text/*`, so `Accept: text/*, text/html;q=0` correctly\n * rejects HTML even though the wildcard would have accepted it.\n *\n * A bare `*` / `*` deliberately does NOT count, at any q. Assets are fetched\n * with `Accept: * / *`, and treating that as a document request is what makes\n * a missing script come back as HTML — the very thing the fallback rules\n * exist to prevent.\n */\nfunction acceptsHtml(accept: string | string[] | undefined): boolean {\n const raw = Array.isArray(accept) ? accept.join(',') : (accept ?? '')\n if (!raw) return false\n\n const ranges = raw\n .split(',')\n .map((part) => part.split(';').map((t) => t.trim().toLowerCase()))\n .filter(([type]) => Boolean(type))\n\n return HTML_TYPES.some((htmlType) => {\n const [group] = htmlType.split('/')\n // Most specific match wins: exact type, else `type/*`. `*/*` is skipped.\n const exact = ranges.find(([type]) => type === htmlType)\n const wildcard = ranges.find(([type]) => type === `${group}/*`)\n const match = exact ?? wildcard\n return match ? qualityOf(match.slice(1)) > 0 : false\n })\n}\n\n/**\n * SPA adapter — serve a Vue, React, Svelte, or Angular build alongside\n * your KickJS API. API routes are handled by controllers; everything else\n * falls back to index.html for client-side routing.\n *\n * Written against the engine-agnostic `http` surface (`serveStatic` / `use`),\n * so it runs under Express, Fastify, and h3 alike. The previous version\n * reached for `express.static`, `req.path`, and `res.send`, all of which are\n * Express-only — it silently served nothing on the other runtimes.\n *\n * Migrated to the `defineAdapter()` factory — call without `new`, as\n * `ViewAdapter` has since v4.\n *\n * @example\n * ```ts\n * import { SpaAdapter } from '@forinda/kickjs/spa'\n *\n * bootstrap({\n * modules,\n * adapters: [\n * SpaAdapter({\n * clientDir: 'dist/client', // or 'build', 'dist', etc.\n * apiPrefix: '/api',\n * }),\n * ],\n * })\n * ```\n *\n * File structure:\n * ```\n * dist/\n * client/ ← SPA build output\n * index.html\n * assets/\n * app.js\n * style.css\n * server/ ← KickJS server\n * ```\n */\nexport const SpaAdapter = defineAdapter<SpaAdapterOptions>({\n name: 'SpaAdapter',\n defaults: {\n clientDir: 'dist/client',\n apiPrefix: '/api',\n exclude: [],\n cacheControl: 'public, max-age=31536000, immutable',\n indexCacheControl: 'no-cache',\n alwaysFallback: false,\n },\n build: (config) => {\n const clientDir = resolveClientDir(config.clientDir ?? 'dist/client')\n const rawPrefix = config.apiPrefix ?? '/api'\n const apiPrefixes = Array.isArray(rawPrefix) ? rawPrefix : [rawPrefix]\n const excludePaths = config.exclude ?? []\n const cacheControl = config.cacheControl ?? 'public, max-age=31536000, immutable'\n const indexCacheControl = config.indexCacheControl ?? 'no-cache'\n const alwaysFallback = config.alwaysFallback ?? false\n\n let indexHtml: string | null = null\n\n /**\n * Every file in the build, as request paths (`/assets/app.js`), captured\n * once at mount.\n *\n * This used to be a `statSync` per request. That is a synchronous\n * filesystem call on the hot path of every non-reserved request, and a\n * slow or contended disk blocks the event loop for unrelated requests.\n * The directory is a static build — its contents are already snapshotted\n * at boot, since `index.html` is read into memory there — so the lookup\n * belongs in memory too. No filesystem access remains in the request path.\n *\n * A build added to after boot is not picked up, which is the same\n * contract `index.html` already had.\n */\n let assetPaths: ReadonlySet<string> = new Set()\n\n function snapshotClientDir(): ReadonlySet<string> {\n const paths = new Set<string>()\n // A hand-rolled walk rather than `readdirSync(dir, { recursive: true })`\n // with `Dirent.parentPath`. Both are newer than the package's declared\n // `node >=20.0`: the `recursive` option landed in 20.1, `parentPath` in\n // 20.12, and the older `Dirent.path` alias it replaced is already gone\n // on Node 24 — so no single spelling covers the supported range. The\n // failure would have been silent, too: the surrounding `catch` turns a\n // `TypeError` from `join(undefined, name)` into an empty snapshot, which\n // reads as \"no files\" and drops every Cache-Control header.\n //\n // `readdirSync(dir, { withFileTypes: true })` is ancient and stable, and\n // tracking the parent ourselves needs no new API.\n const walk = (absDir: string, prefix: string): void => {\n for (const entry of readdirSync(absDir, { withFileTypes: true })) {\n const child = `${prefix}/${entry.name}`\n // Symlinks report as neither file nor directory here (readdir does\n // not follow them), so a symlinked tree is skipped rather than\n // risking a cycle. A symlinked asset simply goes unlabelled — the\n // static layer still serves it, it just misses the cache header.\n if (entry.isDirectory()) walk(join(absDir, entry.name), child)\n else if (entry.isFile()) paths.add(child)\n }\n }\n try {\n walk(clientDir, '')\n } catch {\n // Unreadable build directory — fall back to labelling nothing rather\n // than failing the boot. Serving still works; caching just opts out.\n return new Set()\n }\n return paths\n }\n\n /**\n * How the static layer will answer this path: as the index document, as a\n * long-lived asset, or not at all.\n *\n * Membership of the snapshot IS the containment guard — a traversal like\n * `/../../etc/passwd` simply is not a key — so no prefix comparison is\n * needed and the whole check is one `Set.has`.\n */\n const classifyPath = (pathname: string): 'file' | 'index' | null => {\n let decoded: string\n try {\n decoded = decodeURIComponent(pathname)\n } catch {\n return null\n }\n if (decoded.includes('\\0')) return null\n\n // A directory is served from its `index.html`, so `/` — the single most\n // common request — is an index request, not an asset. Reporting it as\n // neither left the root document without the configured policy.\n const asIndex = decoded.endsWith('/') ? `${decoded}index.html` : null\n if (asIndex && assetPaths.has(asIndex)) return 'index'\n if (!assetPaths.has(decoded)) return null\n return decoded.endsWith('.html') ? 'index' : 'file'\n }\n\n /** Skipped by the fallback: API routes, opted-out paths. */\n const isReserved = (pathname: string): boolean =>\n apiPrefixes.some((p) => isUnder(pathname, p)) ||\n excludePaths.some((p) => isUnder(pathname, p))\n\n return {\n beforeMount({ http }) {\n if (!existsSync(clientDir)) {\n log.warn(`SPA client directory not found: ${clientDir}`)\n log.warn(\n `Build your frontend first, or set clientDir to the correct path ` +\n `(relative paths resolve from ${process.cwd()}).`,\n )\n return\n }\n\n const indexPath = join(clientDir, 'index.html')\n if (!existsSync(indexPath)) {\n log.warn(`index.html not found in ${clientDir}`)\n return\n }\n indexHtml = readFileSync(indexPath, 'utf-8')\n assetPaths = snapshotClientDir()\n\n // Cache-Control runs as its own middleware ahead of the static\n // handler: the engine-agnostic `serveStatic` takes no header hook,\n // and headers set before the static layer writes still land on the\n // response. Keyed off the request path rather than the resolved file,\n // which is the same decision `express.static`'s `setHeaders` made.\n if (cacheControl !== false) {\n http.use(((req, res, next) => {\n const pathname = pathnameOf(req.url)\n // Only label a response the static layer will actually serve.\n // `express.static`'s `setHeaders` fired on hits only; running as\n // a separate middleware loses that, and an unconditional header\n // put `immutable, max-age=31536000` on the 404 for a missing\n // asset — telling every cache to keep that miss for a year.\n const kind = isReserved(pathname) ? null : classifyPath(pathname)\n if (kind) {\n res.setHeader('Cache-Control', kind === 'index' ? indexCacheControl : cacheControl)\n }\n next()\n }) satisfies SpaHandler as unknown as ConnectMiddleware)\n }\n\n http.serveStatic('/', clientDir)\n log.debug(`Serving SPA from ${clientDir}`)\n },\n\n beforeStart({ http }) {\n if (!indexHtml) return\n\n http.use(((req, res, next) => {\n // GET and HEAD both navigate. HEAD used to fall through to a 404,\n // which broke proxies and link checkers probing SPA routes.\n const method = (req.method ?? 'GET').toUpperCase()\n if (method !== 'GET' && method !== 'HEAD') return next()\n\n const pathname = pathnameOf(req.url)\n if (isReserved(pathname)) return next()\n\n // Content negotiation instead of a \"does the path contain a dot\"\n // guess. The old heuristic 404'd every legitimate route carrying a\n // dot (`/users/john.doe`, `/v1.2/spec`) while still handing HTML to\n // genuinely missing assets whose path had no extension.\n const accept = req.headers?.['accept'] as string | string[] | undefined\n if (!alwaysFallback && !acceptsHtml(accept)) return next()\n\n const body = indexHtml as string\n res.setHeader('Content-Type', 'text/html; charset=utf-8')\n res.setHeader('Cache-Control', indexCacheControl)\n res.setHeader('Content-Length', String(Buffer.byteLength(body)))\n res.statusCode = 200\n // HEAD must carry identical headers and no body.\n res.end(method === 'HEAD' ? undefined : body)\n }) satisfies SpaHandler as unknown as ConnectMiddleware)\n },\n }\n },\n})\n"],"mappings":";;;;;;;;;;A,4PAKA,MAAM,IAAM,OAAO,IAAI,YAAY,EA6EnC,SAAS,mBAAmB,KAA6B,CACvD,IAAI,IAAM,KACV,OAAS,CACP,GAAI,WAAW,KAAK,IAAK,cAAc,CAAC,EAAG,OAAO,IAClD,IAAM,OAAS,QAAQ,GAAG,EAC1B,GAAI,SAAW,IAAK,OAAO,KAC3B,IAAM,MACR,CACF,CAqBA,SAAgB,iBACd,UAKA,IAAc,QAAQ,IAAI,EAC1B,MAA4B,QAAQ,KAAK,GACjC,CAMR,GAAI,WAAW,SAAS,EAAG,OAAO,QAAQ,SAAS,EACnD,IAAM,QAAU,QAAQ,IAAK,SAAS,EACtC,GAAI,WAAW,OAAO,EAAG,OAAO,QAEhC,GAAI,MAAO,CACT,IAAM,KAAO,mBAAmB,QAAQ,QAAQ,KAAK,CAAC,CAAC,EACvD,GAAI,KAAM,CACR,IAAM,UAAY,QAAQ,KAAM,SAAS,EACzC,GAAI,WAAW,SAAS,EAAG,OAAO,SACpC,CACF,CACA,OAAO,OACT,CAwBA,SAAS,WAAW,IAAiC,CACnD,GAAI,CAAC,IAAK,MAAO,IACjB,IAAM,EAAI,IAAI,QAAQ,GAAG,EACnB,EAAI,IAAI,QAAQ,GAAG,EACnB,IAAM,KAAK,IAAI,IAAM,GAAK,IAAI,OAAS,EAAG,IAAM,GAAK,IAAI,OAAS,CAAC,EACzE,OAAO,IAAI,MAAM,EAAG,GAAG,GAAK,GAC9B,CAOA,SAAS,QAAQ,SAAkB,OAAyB,CAC1D,GAAI,CAAC,QAAU,SAAW,IAAK,MAAO,GACtC,IAAM,EAAI,OAAO,SAAS,GAAG,EAAI,OAAO,MAAM,EAAG,EAAE,EAAI,OACvD,O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iB,IACnB,KAAK,MAAM,IAAK,IAAK,OAAS,CAC5B,IAAM,SAAW,WAAW,IAAI,GAAG,EAM7B,KAAO,WAAW,QAAQ,EAAI,KAAO,aAAa,QAAQ,EAC5D,MACF,IAAI,UAAU,gBAAiB,OAAS,QAAU,kBAAoB,YAAY,EAEpF,KAAK,CACP,EAAuD,EAGzD,KAAK,YAAY,IAAK,SAAS,EAC/B,IAAI,MAAM,oBAAoB,WAAW,GA5BvC,IAAI,KAAK,2BAA2B,WAAW,CA6BnD,EAEA,YAAY,CAAE,MAAQ,CACf,WAEL,KAAK,MAAM,IAAK,IAAK,OAAS,CAG5B,IAAM,QAAU,IAAI,QAAU,MAAA,CAAO,YAAY,EACjD,GAAI,SAAW,OAAS,SAAW,OAAQ,OAAO,KAAK,EAEvD,IAAM,SAAW,WAAW,IAAI,GAAG,EACnC,GAAI,WAAW,QAAQ,EAAG,OAAO,KAAK,EAMtC,IAAM,OAAS,IAAI,SAAUA,OAC7B,GAAI,CAAC,gBAAkB,CAAC,YAAY,MAAM,EAAG,OAAO,KAAK,EAEzD,IAAM,KAAO,UACb,IAAI,UAAU,eAAgB,0BAA0B,EACxD,IAAI,UAAU,gBAAiB,iBAAiB,EAChD,IAAI,UAAU,iBAAkB,OAAO,OAAO,WAAW,IAAI,CAAC,CAAC,EAC/D,IAAI,WAAa,IAEjB,IAAI,IAAI,SAAW,OAAS,IAAA,GAAY,IAAI,CAC9C,EAAuD,CACzD,CACF,CACF,CACF,CAAC,E"}
1
+ {"version":3,"file":"spa.mjs","names":["\"accept\""],"sources":["../../../src/http/middleware/spa.ts"],"sourcesContent":["import { existsSync, readdirSync, readFileSync } from 'node:fs'\nimport { resolve, join, dirname, isAbsolute } from 'node:path'\nimport { Logger, defineAdapter } from '../../core'\nimport type { ConnectMiddleware } from '../runtime'\n\nconst log = Logger.for('SpaAdapter')\n\n/**\n * Options for {@link SpaAdapter}.\n *\n * @see https://kickjs.app/guide/spa\n */\nexport interface SpaAdapterOptions {\n /**\n * Directory containing the built SPA files (index.html, assets, etc.)\n * Default: 'dist/client'\n *\n * @example\n * ```ts\n * // Vue: 'dist'\n * // React (Vite): 'dist'\n * // React (CRA): 'build'\n * // Svelte: 'build'\n * // Angular: 'dist/my-app/browser'\n * ```\n */\n clientDir?: string\n\n /**\n * URL prefix for API routes. SPA fallback only applies to\n * non-API routes (routes NOT starting with this prefix).\n * Default: '/api'\n *\n * Matching is segment-aware: `/api` excludes `/api` and `/api/users`, but\n * NOT `/apidocs` — a plain `startsWith` swallowed any path that merely\n * began with the same letters.\n *\n * Set to an array for multiple prefixes:\n * ```ts\n * apiPrefix: ['/api', '/graphql', '/_debug']\n * ```\n */\n apiPrefix?: string | string[]\n\n /**\n * Additional paths to exclude from SPA fallback.\n * These paths will NOT serve index.html. Segment-aware, like `apiPrefix`.\n *\n * @example\n * ```ts\n * exclude: ['/health', '/metrics', '/ws']\n * ```\n */\n exclude?: string[]\n\n /**\n * Cache-Control header for static assets (default: 'public, max-age=31536000, immutable')\n * Set to false to disable caching headers.\n */\n cacheControl?: string | false\n\n /**\n * Cache-Control for index.html (default: 'no-cache')\n * index.html should not be cached to ensure clients get fresh builds.\n */\n indexCacheControl?: string\n\n /**\n * Serve index.html even when the client did not ask for HTML.\n * Default: false.\n *\n * By default the fallback only fires for requests whose `Accept` header\n * includes `text/html` — the rule `connect-history-api-fallback` uses. That\n * keeps a missing `/assets/app.js` a 404 instead of handing back an HTML\n * document that the browser then fails to parse as JavaScript, which is a\n * confusing way to discover a broken build.\n *\n * Turn this on if you have non-browser clients that deep-link into SPA\n * routes without an `Accept` header.\n */\n alwaysFallback?: boolean\n}\n\n/**\n * Nearest directory at or above `from` that holds a `package.json`.\n * `null` when the walk reaches the filesystem root without finding one.\n */\nfunction nearestPackageRoot(from: string): string | null {\n let dir = from\n for (;;) {\n if (existsSync(join(dir, 'package.json'))) return dir\n const parent = dirname(dir)\n if (parent === dir) return null\n dir = parent\n }\n}\n\n/**\n * Where to look for the built SPA.\n *\n * `process.cwd()` is the framework's convention (assets and env files resolve\n * the same way) and stays the primary base. But a relative `clientDir` then\n * only works when the process happens to be started from the app directory —\n * `node server/dist/index.js` run from a monorepo root resolved `../web/dist`\n * against the root and found nothing, serving no SPA with only a warning.\n *\n * So: try cwd first, and only if that misses, retry against the package root\n * of the entry script. Both are checked for existence before being chosen, so\n * this can never silently pick a directory that is not there — a genuinely\n * missing build still lands on the cwd path, which is what the warning names.\n *\n * Deliberately not entry-relative FIRST: under `kick dev` the entry is the CLI\n * binary, whose package root is the CLI itself.\n *\n * Exported for tests only — not re-exported from the package index.\n */\nexport function resolveClientDir(\n clientDir: string,\n // Injected rather than read from the process so tests can exercise the\n // monorepo-root case without `process.chdir` / `process.argv` mutation —\n // neither is supported under vitest's `threads` pool, and the root config\n // uses exactly that.\n cwd: string = process.cwd(),\n entry: string | undefined = process.argv[1],\n): string {\n // `resolve` even for an already-absolute path: `resolvesToFile` compares its\n // (always normalized) target against this string, so a trailing slash or a\n // `.`/`..` segment here would make the containment check never match and\n // silently drop the Cache-Control header on every request. Fails closed, so\n // it never weakened the traversal guard — it just stopped doing its job.\n if (isAbsolute(clientDir)) return resolve(clientDir)\n const fromCwd = resolve(cwd, clientDir)\n if (existsSync(fromCwd)) return fromCwd\n\n if (entry) {\n const root = nearestPackageRoot(dirname(resolve(entry)))\n if (root) {\n const fromEntry = resolve(root, clientDir)\n if (existsSync(fromEntry)) return fromEntry\n }\n }\n return fromCwd\n}\n\n/**\n * The slice of the request/response this adapter touches, spelled from the\n * node `http` shapes rather than Express's. `ConnectMiddleware` is typed as\n * Express's `RequestHandler`, but under Fastify and h3 these handlers receive\n * the raw node objects (or a driver), so relying on `req.path` / `res.send`\n * is what made the previous version Express-only.\n */\ninterface SpaRequest {\n url?: string\n method?: string\n headers?: Record<string, string | string[] | undefined>\n}\n\ninterface SpaResponse {\n setHeader(name: string, value: string): void\n statusCode: number\n end(chunk?: string): void\n}\n\ntype SpaHandler = (req: SpaRequest, res: SpaResponse, next: () => void) => void\n\n/** Pathname only — `req.url` carries the query string, and `req.path` is Express-only. */\nfunction pathnameOf(url: string | undefined): string {\n if (!url) return '/'\n const q = url.indexOf('?')\n const h = url.indexOf('#')\n const end = Math.min(q === -1 ? url.length : q, h === -1 ? url.length : h)\n return url.slice(0, end) || '/'\n}\n\n/**\n * Segment-aware prefix test: `/api` covers `/api` and `/api/users`, not\n * `/apidocs`. `startsWith` alone made any same-prefixed route disappear from\n * the SPA fallback and 404 instead.\n */\nfunction isUnder(pathname: string, prefix: string): boolean {\n if (!prefix || prefix === '/') return true\n const p = prefix.endsWith('/') ? prefix.slice(0, -1) : prefix\n return pathname === p || pathname.startsWith(`${p}/`)\n}\n\n/** Media ranges that count as \"the client wants a document\". */\nconst HTML_TYPES = ['text/html', 'application/xhtml+xml']\n\n/** `q` for a media range, defaulting to 1 when absent or unparseable. */\nfunction qualityOf(params: string[]): number {\n const q = params.find((param) => param.startsWith('q='))\n if (!q) return 1\n const value = Number.parseFloat(q.slice(2))\n return Number.isNaN(value) ? 1 : value\n}\n\n/**\n * Does the client want an HTML document back?\n *\n * Parses media ranges with q-values rather than substring-matching:\n * `Accept: text/html;q=0` explicitly says HTML is NOT acceptable (RFC 9110\n * §12.5.1 — \"a value of 0 means not acceptable\"), and a substring check read\n * that as a yes and returned the document anyway.\n *\n * Wildcards are matched by specificity, as RFC 9110 §12.5.1 requires: an exact\n * `text/html` beats `text/*`, so `Accept: text/*, text/html;q=0` correctly\n * rejects HTML even though the wildcard would have accepted it.\n *\n * A bare `*` / `*` deliberately does NOT count, at any q. Assets are fetched\n * with `Accept: * / *`, and treating that as a document request is what makes\n * a missing script come back as HTML — the very thing the fallback rules\n * exist to prevent.\n */\nfunction acceptsHtml(accept: string | string[] | undefined): boolean {\n const raw = Array.isArray(accept) ? accept.join(',') : (accept ?? '')\n if (!raw) return false\n\n const ranges = raw\n .split(',')\n .map((part) => part.split(';').map((t) => t.trim().toLowerCase()))\n .filter(([type]) => Boolean(type))\n\n return HTML_TYPES.some((htmlType) => {\n const [group] = htmlType.split('/')\n // Most specific match wins: exact type, else `type/*`. `*/*` is skipped.\n const exact = ranges.find(([type]) => type === htmlType)\n const wildcard = ranges.find(([type]) => type === `${group}/*`)\n const match = exact ?? wildcard\n return match ? qualityOf(match.slice(1)) > 0 : false\n })\n}\n\n/**\n * SPA adapter — serve a Vue, React, Svelte, or Angular build alongside\n * your KickJS API. API routes are handled by controllers; everything else\n * falls back to index.html for client-side routing.\n *\n * Written against the engine-agnostic `http` surface (`serveStatic` / `use`),\n * so it runs under Express, Fastify, and h3 alike. The previous version\n * reached for `express.static`, `req.path`, and `res.send`, all of which are\n * Express-only — it silently served nothing on the other runtimes.\n *\n * Migrated to the `defineAdapter()` factory — call without `new`, as\n * `ViewAdapter` has since v4.\n *\n * @example\n * ```ts\n * import { SpaAdapter } from '@forinda/kickjs/spa'\n *\n * bootstrap({\n * modules,\n * adapters: [\n * SpaAdapter({\n * clientDir: 'dist/client', // or 'build', 'dist', etc.\n * apiPrefix: '/api',\n * }),\n * ],\n * })\n * ```\n *\n * File structure:\n * ```\n * dist/\n * client/ ← SPA build output\n * index.html\n * assets/\n * app.js\n * style.css\n * server/ ← KickJS server\n * ```\n *\n * @see https://kickjs.app/guide/spa\n */\nexport const SpaAdapter = defineAdapter<SpaAdapterOptions>({\n name: 'SpaAdapter',\n defaults: {\n clientDir: 'dist/client',\n apiPrefix: '/api',\n exclude: [],\n cacheControl: 'public, max-age=31536000, immutable',\n indexCacheControl: 'no-cache',\n alwaysFallback: false,\n },\n build: (config) => {\n const clientDir = resolveClientDir(config.clientDir ?? 'dist/client')\n const rawPrefix = config.apiPrefix ?? '/api'\n const apiPrefixes = Array.isArray(rawPrefix) ? rawPrefix : [rawPrefix]\n const excludePaths = config.exclude ?? []\n const cacheControl = config.cacheControl ?? 'public, max-age=31536000, immutable'\n const indexCacheControl = config.indexCacheControl ?? 'no-cache'\n const alwaysFallback = config.alwaysFallback ?? false\n\n let indexHtml: string | null = null\n\n /**\n * Every file in the build, as request paths (`/assets/app.js`), captured\n * once at mount.\n *\n * This used to be a `statSync` per request. That is a synchronous\n * filesystem call on the hot path of every non-reserved request, and a\n * slow or contended disk blocks the event loop for unrelated requests.\n * The directory is a static build — its contents are already snapshotted\n * at boot, since `index.html` is read into memory there — so the lookup\n * belongs in memory too. No filesystem access remains in the request path.\n *\n * A build added to after boot is not picked up, which is the same\n * contract `index.html` already had.\n */\n let assetPaths: ReadonlySet<string> = new Set()\n\n function snapshotClientDir(): ReadonlySet<string> {\n const paths = new Set<string>()\n // A hand-rolled walk rather than `readdirSync(dir, { recursive: true })`\n // with `Dirent.parentPath`. Both are newer than the package's declared\n // `node >=20.0`: the `recursive` option landed in 20.1, `parentPath` in\n // 20.12, and the older `Dirent.path` alias it replaced is already gone\n // on Node 24 — so no single spelling covers the supported range. The\n // failure would have been silent, too: the surrounding `catch` turns a\n // `TypeError` from `join(undefined, name)` into an empty snapshot, which\n // reads as \"no files\" and drops every Cache-Control header.\n //\n // `readdirSync(dir, { withFileTypes: true })` is ancient and stable, and\n // tracking the parent ourselves needs no new API.\n const walk = (absDir: string, prefix: string): void => {\n for (const entry of readdirSync(absDir, { withFileTypes: true })) {\n const child = `${prefix}/${entry.name}`\n // Symlinks report as neither file nor directory here (readdir does\n // not follow them), so a symlinked tree is skipped rather than\n // risking a cycle. A symlinked asset simply goes unlabelled — the\n // static layer still serves it, it just misses the cache header.\n if (entry.isDirectory()) walk(join(absDir, entry.name), child)\n else if (entry.isFile()) paths.add(child)\n }\n }\n try {\n walk(clientDir, '')\n } catch {\n // Unreadable build directory — fall back to labelling nothing rather\n // than failing the boot. Serving still works; caching just opts out.\n return new Set()\n }\n return paths\n }\n\n /**\n * How the static layer will answer this path: as the index document, as a\n * long-lived asset, or not at all.\n *\n * Membership of the snapshot IS the containment guard — a traversal like\n * `/../../etc/passwd` simply is not a key — so no prefix comparison is\n * needed and the whole check is one `Set.has`.\n */\n const classifyPath = (pathname: string): 'file' | 'index' | null => {\n let decoded: string\n try {\n decoded = decodeURIComponent(pathname)\n } catch {\n return null\n }\n if (decoded.includes('\\0')) return null\n\n // A directory is served from its `index.html`, so `/` — the single most\n // common request — is an index request, not an asset. Reporting it as\n // neither left the root document without the configured policy.\n const asIndex = decoded.endsWith('/') ? `${decoded}index.html` : null\n if (asIndex && assetPaths.has(asIndex)) return 'index'\n if (!assetPaths.has(decoded)) return null\n return decoded.endsWith('.html') ? 'index' : 'file'\n }\n\n /** Skipped by the fallback: API routes, opted-out paths. */\n const isReserved = (pathname: string): boolean =>\n apiPrefixes.some((p) => isUnder(pathname, p)) ||\n excludePaths.some((p) => isUnder(pathname, p))\n\n return {\n beforeMount({ http }) {\n if (!existsSync(clientDir)) {\n log.warn(`SPA client directory not found: ${clientDir}`)\n log.warn(\n `Build your frontend first, or set clientDir to the correct path ` +\n `(relative paths resolve from ${process.cwd()}).`,\n )\n return\n }\n\n const indexPath = join(clientDir, 'index.html')\n if (!existsSync(indexPath)) {\n log.warn(`index.html not found in ${clientDir}`)\n return\n }\n indexHtml = readFileSync(indexPath, 'utf-8')\n assetPaths = snapshotClientDir()\n\n // Cache-Control runs as its own middleware ahead of the static\n // handler: the engine-agnostic `serveStatic` takes no header hook,\n // and headers set before the static layer writes still land on the\n // response. Keyed off the request path rather than the resolved file,\n // which is the same decision `express.static`'s `setHeaders` made.\n if (cacheControl !== false) {\n http.use(((req, res, next) => {\n const pathname = pathnameOf(req.url)\n // Only label a response the static layer will actually serve.\n // `express.static`'s `setHeaders` fired on hits only; running as\n // a separate middleware loses that, and an unconditional header\n // put `immutable, max-age=31536000` on the 404 for a missing\n // asset — telling every cache to keep that miss for a year.\n const kind = isReserved(pathname) ? null : classifyPath(pathname)\n if (kind) {\n res.setHeader('Cache-Control', kind === 'index' ? indexCacheControl : cacheControl)\n }\n next()\n }) satisfies SpaHandler as unknown as ConnectMiddleware)\n }\n\n http.serveStatic('/', clientDir)\n log.debug(`Serving SPA from ${clientDir}`)\n },\n\n beforeStart({ http }) {\n if (!indexHtml) return\n\n http.use(((req, res, next) => {\n // GET and HEAD both navigate. HEAD used to fall through to a 404,\n // which broke proxies and link checkers probing SPA routes.\n const method = (req.method ?? 'GET').toUpperCase()\n if (method !== 'GET' && method !== 'HEAD') return next()\n\n const pathname = pathnameOf(req.url)\n if (isReserved(pathname)) return next()\n\n // Content negotiation instead of a \"does the path contain a dot\"\n // guess. The old heuristic 404'd every legitimate route carrying a\n // dot (`/users/john.doe`, `/v1.2/spec`) while still handing HTML to\n // genuinely missing assets whose path had no extension.\n const accept = req.headers?.['accept'] as string | string[] | undefined\n if (!alwaysFallback && !acceptsHtml(accept)) return next()\n\n const body = indexHtml as string\n res.setHeader('Content-Type', 'text/html; charset=utf-8')\n res.setHeader('Cache-Control', indexCacheControl)\n res.setHeader('Content-Length', String(Buffer.byteLength(body)))\n res.statusCode = 200\n // HEAD must carry identical headers and no body.\n res.end(method === 'HEAD' ? undefined : body)\n }) satisfies SpaHandler as unknown as ConnectMiddleware)\n },\n }\n },\n})\n"],"mappings":";;;;;;;;;;A,4PAKA,MAAM,IAAM,OAAO,IAAI,YAAY,EAkFnC,SAAS,mBAAmB,KAA6B,CACvD,IAAI,IAAM,KACV,OAAS,CACP,GAAI,WAAW,KAAK,IAAK,cAAc,CAAC,EAAG,OAAO,IAClD,IAAM,OAAS,QAAQ,GAAG,EAC1B,GAAI,SAAW,IAAK,OAAO,KAC3B,IAAM,MACR,CACF,CAqBA,SAAgB,iBACd,UAKA,IAAc,QAAQ,IAAI,EAC1B,MAA4B,QAAQ,KAAK,GACjC,CAMR,GAAI,WAAW,SAAS,EAAG,OAAO,QAAQ,SAAS,EACnD,IAAM,QAAU,QAAQ,IAAK,SAAS,EACtC,GAAI,WAAW,OAAO,EAAG,OAAO,QAEhC,GAAI,MAAO,CACT,IAAM,KAAO,mBAAmB,QAAQ,QAAQ,KAAK,CAAC,CAAC,EACvD,GAAI,KAAM,CACR,IAAM,UAAY,QAAQ,KAAM,SAAS,EAC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AAI,UAAU,iBAAkB,OAAO,OAAO,WAAW,IAAI,CAAC,CAAC,EAC/D,IAAI,WAAa,IAEjB,IAAI,IAAI,SAAW,OAAS,IAAA,GAAY,IAAI,CAC9C,EAAuD,CACzD,CACF,CACF,CACF,CAAC,E"}
@@ -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-B64IOivZ.mjs";
3
- import { i as upload, n as buildUploadMiddleware, r as cleanupFiles, t as UploadOptions } from "../../upload-eNNueUxR.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-D_nUmKEQ.mjs";
3
+ import { i as upload, n as buildUploadMiddleware, r as cleanupFiles, t as UploadOptions } from "../../upload-O3VTcODy.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.14.2
2
+ * @forinda/kickjs v10.15.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{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-BXjBiNjC.mjs";import{f as tooLarge}from"../../body-policy-Be3Y0hjq.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{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-BXqBuyza.mjs";import{f as tooLarge}from"../../body-policy-D8LveWmO.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