@forinda/kickjs 10.14.0 → 10.14.2
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.
- package/dist/{adapter-DL9JPcvC.d.mts → adapter-B64IOivZ.d.mts} +13 -53
- package/dist/adapter-B64IOivZ.d.mts.map +1 -0
- package/dist/{allowed-hosts-BpKwviq5.d.mts → allowed-hosts-U12_gESr.d.mts} +2 -4
- package/dist/allowed-hosts-U12_gESr.d.mts.map +1 -0
- package/dist/{app-module-Dk2Wenqx.d.mts → app-module-EmIojM4d.d.mts} +5 -11
- package/dist/app-module-EmIojM4d.d.mts.map +1 -0
- package/dist/application-BzimU62Q.mjs +14 -0
- package/dist/application-BzimU62Q.mjs.map +1 -0
- package/dist/{application-D921r4MW.d.mts → application-CGcY8SZZ.d.mts} +22 -74
- package/dist/application-CGcY8SZZ.d.mts.map +1 -0
- package/dist/{body-policy-CaerQ_lu.mjs → body-policy-Be3Y0hjq.mjs} +2 -2
- package/dist/{body-policy-CaerQ_lu.mjs.map → body-policy-Be3Y0hjq.mjs.map} +1 -1
- package/dist/{bootstrap-BXLsEeMW.mjs → bootstrap-Bvk3BWJX.mjs} +3 -3
- package/dist/{bootstrap-BXLsEeMW.mjs.map → bootstrap-Bvk3BWJX.mjs.map} +1 -1
- package/dist/{bounded-counters-DFef_B7d.mjs → bounded-counters-Bh5jeT9I.mjs} +2 -2
- package/dist/{bounded-counters-DFef_B7d.mjs.map → bounded-counters-Bh5jeT9I.mjs.map} +1 -1
- package/dist/{breach-padding-FBVGmcBb.d.mts → breach-padding-DfT9MXGb.d.mts} +2 -4
- package/dist/breach-padding-DfT9MXGb.d.mts.map +1 -0
- package/dist/{cache-CdRHSXow.d.mts → cache-DMIt3c6M.d.mts} +1 -3
- package/dist/cache-DMIt3c6M.d.mts.map +1 -0
- package/dist/{client-ip-DE5vkJWL.mjs → client-ip-CGH_IvnC.mjs} +2 -2
- package/dist/{client-ip-DE5vkJWL.mjs.map → client-ip-CGH_IvnC.mjs.map} +1 -1
- package/dist/config/index.d.mts +1 -1
- package/dist/config/index.mjs +2 -2
- package/dist/{config-De3xzaiZ.mjs → config-CjFxvh0v.mjs} +3 -3
- package/dist/{config-De3xzaiZ.mjs.map → config-CjFxvh0v.mjs.map} +1 -1
- package/dist/{connect-BlIamapT.d.mts → connect-DamOelO8.d.mts} +1 -3
- package/dist/connect-DamOelO8.d.mts.map +1 -0
- package/dist/{context-DBLyIErA.mjs → context-BvZLaTeE.mjs} +3 -3
- package/dist/{context-DBLyIErA.mjs.map → context-BvZLaTeE.mjs.map} +1 -1
- package/dist/{context-errors-By-pwipc.mjs → context-errors-BZVS0B1O.mjs} +2 -2
- package/dist/{context-errors-By-pwipc.mjs.map → context-errors-BZVS0B1O.mjs.map} +1 -1
- package/dist/{contributor-runner-BuMi_eLU.mjs → contributor-runner-fdKy6Tme.mjs} +3 -3
- package/dist/{contributor-runner-BuMi_eLU.mjs.map → contributor-runner-fdKy6Tme.mjs.map} +1 -1
- package/dist/core/adapter.d.mts +1 -1
- package/dist/core/adapter.mjs +1 -1
- package/dist/core/app-module.d.mts +1 -1
- package/dist/core/app-module.mjs +1 -1
- package/dist/core/cache.d.mts +1 -1
- package/dist/core/cache.mjs +1 -1
- package/dist/core/cache.mjs.map +1 -1
- package/dist/core/container.mjs +2 -2
- package/dist/core/cron.d.mts +1 -1
- package/dist/core/cron.mjs +2 -2
- package/dist/core/cron.mjs.map +1 -1
- package/dist/core/decorators.d.mts +1 -1
- package/dist/core/decorators.mjs +2 -2
- package/dist/core/decorators.mjs.map +1 -1
- package/dist/core/errors.d.mts +1 -1
- package/dist/core/errors.mjs +1 -1
- package/dist/core/errors.mjs.map +1 -1
- package/dist/core/interfaces.d.mts +1 -1
- package/dist/core/interfaces.mjs +1 -1
- package/dist/core/interfaces.mjs.map +1 -1
- package/dist/core/logger.d.mts +1 -1
- package/dist/core/logger.mjs +1 -1
- package/dist/core/logger.mjs.map +1 -1
- package/dist/core/path.d.mts +1 -1
- package/dist/core/path.mjs +1 -1
- package/dist/core/path.mjs.map +1 -1
- package/dist/core/plugin.d.mts +1 -1
- package/dist/core/plugin.mjs +1 -1
- package/dist/core/reactivity.d.mts +1 -1
- package/dist/core/reactivity.mjs +2 -2
- package/dist/core/reactivity.mjs.map +1 -1
- package/dist/{core-BziwPF77.mjs → core-CCIpjo6g.mjs} +3 -3
- package/dist/{core-BziwPF77.mjs.map → core-CCIpjo6g.mjs.map} +1 -1
- package/dist/{cors-BlR_b0Qb.d.mts → cors-J-q6PuSU.d.mts} +2 -4
- package/dist/cors-J-q6PuSU.d.mts.map +1 -0
- package/dist/{cron-BTGytNg-.d.mts → cron-DGV1AE0R.d.mts} +1 -3
- package/dist/cron-DGV1AE0R.d.mts.map +1 -0
- package/dist/{csrf-DOAaYozG.d.mts → csrf-DjtJPgA3.d.mts} +4 -6
- package/dist/csrf-DjtJPgA3.d.mts.map +1 -0
- package/dist/decorate-DRbXCNQz.mjs +13 -0
- package/dist/decorate-DRbXCNQz.mjs.map +1 -0
- package/dist/{decorators-DxNb5mWw.d.mts → decorators-BAD8qjuq.d.mts} +1 -5
- package/dist/decorators-BAD8qjuq.d.mts.map +1 -0
- package/dist/{define-adapter-CbVg-Fyh.mjs → define-adapter-DMo6og81.mjs} +2 -2
- package/dist/{define-adapter-CbVg-Fyh.mjs.map → define-adapter-DMo6og81.mjs.map} +1 -1
- package/dist/{di-hooks-DN_UC8Nc.mjs → di-hooks-DCqt2yJ9.mjs} +2 -2
- package/dist/{di-hooks-DN_UC8Nc.mjs.map → di-hooks-DCqt2yJ9.mjs.map} +1 -1
- package/dist/{disposables-C4BLa-Pc.mjs → disposables-BsdVu69-.mjs} +1 -1
- package/dist/{driver-DyWsGdcD.mjs → driver-oZBQDJZz.mjs} +3 -3
- package/dist/{driver-DyWsGdcD.mjs.map → driver-oZBQDJZz.mjs.map} +1 -1
- package/dist/{error-handler-D7DLWe1Q.d.mts → error-handler-Dl_gZRNK.d.mts} +2 -4
- package/dist/error-handler-Dl_gZRNK.d.mts.map +1 -0
- package/dist/{errors-By6UueCm.d.mts → errors-DZGuPLoZ.d.mts} +1 -3
- package/dist/errors-DZGuPLoZ.d.mts.map +1 -0
- package/dist/{express-FnNSFECr.mjs → express-f9CTA8qO.mjs} +3 -3
- package/dist/{express-FnNSFECr.mjs.map → express-f9CTA8qO.mjs.map} +1 -1
- package/dist/{express-lazy-B8AFaCA-.mjs → express-lazy-DMxcLBpT.mjs} +3 -3
- package/dist/{express-lazy-B8AFaCA-.mjs.map → express-lazy-DMxcLBpT.mjs.map} +1 -1
- package/dist/{handler--lTqJdpj.mjs → handler-B66laQY0.mjs} +3 -3
- package/dist/{handler--lTqJdpj.mjs.map → handler-B66laQY0.mjs.map} +1 -1
- package/dist/{helmet-BVuVBl-D.d.mts → helmet-Rwkbp9IS.d.mts} +2 -4
- package/dist/helmet-Rwkbp9IS.d.mts.map +1 -0
- package/dist/{host-Dn2rI7s7.mjs → host-DalMsn5Z.mjs} +2 -2
- package/dist/{host-Dn2rI7s7.mjs.map → host-DalMsn5Z.mjs.map} +1 -1
- package/dist/http/application.d.mts +1 -1
- package/dist/http/application.mjs +2 -2
- package/dist/http/bootstrap.d.mts +1 -1
- package/dist/http/bootstrap.mjs +2 -2
- package/dist/http/context.d.mts +2 -2
- package/dist/http/context.mjs +2 -2
- package/dist/http/middleware/allowed-hosts.d.mts +1 -1
- package/dist/http/middleware/allowed-hosts.mjs +2 -2
- package/dist/http/middleware/allowed-hosts.mjs.map +1 -1
- package/dist/http/middleware/breach-padding.d.mts +1 -1
- package/dist/http/middleware/breach-padding.mjs +1 -1
- package/dist/http/middleware/breach-padding.mjs.map +1 -1
- package/dist/http/middleware/cors.d.mts +1 -1
- package/dist/http/middleware/cors.mjs +1 -1
- package/dist/http/middleware/cors.mjs.map +1 -1
- package/dist/http/middleware/csrf.d.mts +1 -1
- package/dist/http/middleware/csrf.mjs +2 -2
- package/dist/http/middleware/csrf.mjs.map +1 -1
- package/dist/http/middleware/error-handler.d.mts +1 -1
- package/dist/http/middleware/error-handler.mjs +2 -2
- package/dist/http/middleware/error-handler.mjs.map +1 -1
- package/dist/http/middleware/helmet.d.mts +1 -1
- package/dist/http/middleware/helmet.mjs +1 -1
- package/dist/http/middleware/helmet.mjs.map +1 -1
- package/dist/http/middleware/rate-limit.d.mts +1 -1
- package/dist/http/middleware/rate-limit.mjs +2 -2
- package/dist/http/middleware/rate-limit.mjs.map +1 -1
- package/dist/http/middleware/request-id.d.mts +1 -1
- package/dist/http/middleware/request-id.mjs +1 -1
- package/dist/http/middleware/request-id.mjs.map +1 -1
- package/dist/http/middleware/request-logger.d.mts +1 -1
- package/dist/http/middleware/request-logger.mjs +2 -2
- package/dist/http/middleware/request-logger.mjs.map +1 -1
- package/dist/http/middleware/session.d.mts +1 -1
- package/dist/http/middleware/session.mjs +2 -2
- package/dist/http/middleware/session.mjs.map +1 -1
- package/dist/http/middleware/spa.d.mts +1 -1
- package/dist/http/middleware/spa.mjs +2 -2
- package/dist/http/middleware/spa.mjs.map +1 -1
- package/dist/http/middleware/upload.d.mts +2 -2
- package/dist/http/middleware/upload.mjs +2 -2
- package/dist/http/middleware/upload.mjs.map +1 -1
- package/dist/http/middleware/validate.d.mts +1 -1
- package/dist/http/middleware/validate.mjs +1 -1
- package/dist/http/middleware/validate.mjs.map +1 -1
- package/dist/http/middleware/views.d.mts +1 -1
- package/dist/http/middleware/views.mjs +2 -2
- package/dist/http/middleware/views.mjs.map +1 -1
- package/dist/http/query/index.d.mts +1 -1
- package/dist/http/query/index.mjs +2 -2
- package/dist/http/router-builder.d.mts +1 -1
- package/dist/http/router-builder.mjs +2 -2
- package/dist/http/runtimes/express.d.mts +3 -7
- package/dist/http/runtimes/express.d.mts.map +1 -1
- package/dist/http/runtimes/express.mjs +2 -2
- package/dist/http/runtimes/fastify.d.mts +1 -3
- package/dist/http/runtimes/fastify.d.mts.map +1 -1
- package/dist/http/runtimes/fastify.mjs +2 -2
- package/dist/http/runtimes/fastify.mjs.map +1 -1
- package/dist/http/runtimes/h3-web.mjs +1 -1
- package/dist/http/runtimes/h3.d.mts +1 -3
- package/dist/http/runtimes/h3.d.mts.map +1 -1
- package/dist/http/runtimes/h3.mjs +2 -2
- package/dist/http/runtimes/h3.mjs.map +1 -1
- package/dist/{index-DP_I4puv.d.mts → index-CFTwnev9.d.mts} +3 -7
- package/dist/index-CFTwnev9.d.mts.map +1 -0
- package/dist/{index-Blgka75E.d.mts → index-ZbCnCyQx.d.mts} +1 -5
- package/dist/index-ZbCnCyQx.d.mts.map +1 -0
- package/dist/index.d.mts +30 -30
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/dist/{interfaces-C6LHcYsg.d.mts → interfaces-BQhYh3lL.d.mts} +1 -3
- package/dist/interfaces-BQhYh3lL.d.mts.map +1 -0
- package/dist/{is-production-Cx4PGne9.mjs → is-production-9QzMIRuO.mjs} +2 -2
- package/dist/{is-production-Cx4PGne9.mjs.map → is-production-9QzMIRuO.mjs.map} +1 -1
- package/dist/{jobs-Bgtz3Hlq.mjs → jobs-CuZqVDDG.mjs} +3 -3
- package/dist/{jobs-Bgtz3Hlq.mjs.map → jobs-CuZqVDDG.mjs.map} +1 -1
- package/dist/{kv-stores-LBIBEueO.mjs → kv-stores-C9CJ3xCB.mjs} +3 -3
- package/dist/{kv-stores-LBIBEueO.mjs.map → kv-stores-C9CJ3xCB.mjs.map} +1 -1
- package/dist/{kv-stores-CwJdsMln.d.mts → kv-stores-wTD3VDPB.d.mts} +6 -18
- package/dist/kv-stores-wTD3VDPB.d.mts.map +1 -0
- package/dist/{lazy-serve-static-B9xQ0OE1.mjs → lazy-serve-static-DVWmKM7Z.mjs} +3 -3
- package/dist/{lazy-serve-static-B9xQ0OE1.mjs.map → lazy-serve-static-DVWmKM7Z.mjs.map} +1 -1
- package/dist/{logger-xE9qI_FS.d.mts → logger-BL8MiSrm.d.mts} +1 -3
- package/dist/logger-BL8MiSrm.d.mts.map +1 -0
- package/dist/{metadata-DS4TBMoC.mjs → metadata-BZRtQog3.mjs} +1 -1
- package/dist/{observers-Dokycjj0.mjs → observers-B4VnKAHK.mjs} +2 -2
- package/dist/{observers-Dokycjj0.mjs.map → observers-B4VnKAHK.mjs.map} +1 -1
- package/dist/{path-CMwIHsdv.d.mts → path-DsenzqJ7.d.mts} +1 -3
- package/dist/path-DsenzqJ7.d.mts.map +1 -0
- package/dist/{precompressed-BLYcqIAM.mjs → precompressed-AxF66Ls0.mjs} +2 -2
- package/dist/{precompressed-BLYcqIAM.mjs.map → precompressed-AxF66Ls0.mjs.map} +1 -1
- package/dist/{query-Cmtgo_-P.mjs → query-BwUR-ssX.mjs} +2 -2
- package/dist/{query-Cmtgo_-P.mjs.map → query-BwUR-ssX.mjs.map} +1 -1
- package/dist/{rate-limit-DQDk6bAH.d.mts → rate-limit-DMiV6bAq.d.mts} +3 -5
- package/dist/rate-limit-DMiV6bAq.d.mts.map +1 -0
- package/dist/{reactivity-DZrc3Yhu.d.mts → reactivity-Dski64km.d.mts} +1 -3
- package/dist/reactivity-Dski64km.d.mts.map +1 -0
- package/dist/{reply-Dcm0NAr0.mjs → reply-B5kZ6VGv.mjs} +3 -3
- package/dist/{reply-Dcm0NAr0.mjs.map → reply-B5kZ6VGv.mjs.map} +1 -1
- package/dist/{request-id-Dn64nEHK.d.mts → request-id-B_n-3A16.d.mts} +2 -4
- package/dist/request-id-B_n-3A16.d.mts.map +1 -0
- package/dist/{request-logger-TgcKRNDD.d.mts → request-logger-BV1C5r5q.d.mts} +1 -3
- package/dist/request-logger-BV1C5r5q.d.mts.map +1 -0
- package/dist/{request-scope-BmhPPGPk.mjs → request-scope-D2WQwatk.mjs} +3 -3
- package/dist/{request-scope-BmhPPGPk.mjs.map → request-scope-D2WQwatk.mjs.map} +1 -1
- package/dist/{respond-NCvYMEwC.mjs → respond-C6ohI69y.mjs} +2 -2
- package/dist/{respond-NCvYMEwC.mjs.map → respond-C6ohI69y.mjs.map} +1 -1
- package/dist/{rolldown-runtime-DKvcoND8.mjs → rolldown-runtime-DuhQYUab.mjs} +1 -1
- package/dist/{route-flag-DRM2yEZT.mjs → route-flag-CHiMvgar.mjs} +3 -3
- package/dist/{route-flag-DRM2yEZT.mjs.map → route-flag-CHiMvgar.mjs.map} +1 -1
- package/dist/{route-flag-B1lQht6v.d.mts → route-flag-CjXQl-oX.d.mts} +1 -3
- package/dist/route-flag-CjXQl-oX.d.mts.map +1 -0
- package/dist/{route-policy-T8RavXEx.mjs → route-policy-ckK7N1eN.mjs} +2 -2
- package/dist/{route-policy-T8RavXEx.mjs.map → route-policy-ckK7N1eN.mjs.map} +1 -1
- package/dist/{router-builder-iEHiFSZh.mjs → router-builder-D2cly8Wt.mjs} +3 -3
- package/dist/{router-builder-iEHiFSZh.mjs.map → router-builder-D2cly8Wt.mjs.map} +1 -1
- package/dist/{router-builder-C5EtcFSL.d.mts → router-builder-Dtyya4qP.d.mts} +3 -5
- package/dist/router-builder-Dtyya4qP.d.mts.map +1 -0
- package/dist/{runtime-D9KW2aLY.mjs → runtime-D9TN6CpL.mjs} +3 -3
- package/dist/{runtime-D9KW2aLY.mjs.map → runtime-D9TN6CpL.mjs.map} +1 -1
- package/dist/{session-DQG72vCf.d.mts → session-CXWu2rXW.d.mts} +2 -4
- package/dist/session-CXWu2rXW.d.mts.map +1 -0
- package/dist/{settings-DgZLgcNU.d.mts → settings-CB6lh6_s.d.mts} +1 -3
- package/dist/settings-CB6lh6_s.d.mts.map +1 -0
- package/dist/{settings-hG4DH8hQ.mjs → settings-v2N3V8Bl.mjs} +4 -4
- package/dist/settings-v2N3V8Bl.mjs.map +1 -0
- package/dist/{token-i5RynFrd.mjs → token-DtW16tw3.mjs} +1 -1
- package/dist/{upload-config-CTwzXhph.mjs → upload-config-BXjBiNjC.mjs} +2 -2
- package/dist/{upload-config-CTwzXhph.mjs.map → upload-config-BXjBiNjC.mjs.map} +1 -1
- package/dist/{upload-DnwvZQyi.d.mts → upload-eNNueUxR.d.mts} +4 -6
- package/dist/upload-eNNueUxR.d.mts.map +1 -0
- package/dist/{url-for-CQNJYjRH.mjs → url-for-C4Eomib7.mjs} +3 -3
- package/dist/{url-for-CQNJYjRH.mjs.map → url-for-C4Eomib7.mjs.map} +1 -1
- package/dist/{validate-D4Poe2EE.d.mts → validate-BbthfLBb.d.mts} +3 -5
- package/dist/validate-BbthfLBb.d.mts.map +1 -0
- package/dist/{view-renderer-BV2rwEUI.mjs → view-renderer-C4sMEruA.mjs} +3 -3
- package/dist/{view-renderer-BV2rwEUI.mjs.map → view-renderer-C4sMEruA.mjs.map} +1 -1
- package/dist/{web-crypto-hpIdycSO.mjs → web-crypto-SXVOPDxW.mjs} +2 -2
- package/dist/{web-crypto-hpIdycSO.mjs.map → web-crypto-SXVOPDxW.mjs.map} +1 -1
- package/dist/web.d.mts +7 -13
- package/dist/web.d.mts.map +1 -1
- package/dist/web.mjs +2 -2
- package/dist/web.mjs.map +1 -1
- package/package.json +4 -4
- package/dist/adapter-DL9JPcvC.d.mts.map +0 -1
- package/dist/allowed-hosts-BpKwviq5.d.mts.map +0 -1
- package/dist/app-module-Dk2Wenqx.d.mts.map +0 -1
- package/dist/application-CHBdxwF5.mjs +0 -14
- package/dist/application-CHBdxwF5.mjs.map +0 -1
- package/dist/application-D921r4MW.d.mts.map +0 -1
- package/dist/breach-padding-FBVGmcBb.d.mts.map +0 -1
- package/dist/cache-CdRHSXow.d.mts.map +0 -1
- package/dist/connect-BlIamapT.d.mts.map +0 -1
- package/dist/cors-BlR_b0Qb.d.mts.map +0 -1
- package/dist/cron-BTGytNg-.d.mts.map +0 -1
- package/dist/csrf-DOAaYozG.d.mts.map +0 -1
- package/dist/decorate-DgGmrJOP.mjs +0 -13
- package/dist/decorate-DgGmrJOP.mjs.map +0 -1
- package/dist/decorators-DxNb5mWw.d.mts.map +0 -1
- package/dist/error-handler-D7DLWe1Q.d.mts.map +0 -1
- package/dist/errors-By6UueCm.d.mts.map +0 -1
- package/dist/helmet-BVuVBl-D.d.mts.map +0 -1
- package/dist/index-Blgka75E.d.mts.map +0 -1
- package/dist/index-DP_I4puv.d.mts.map +0 -1
- package/dist/interfaces-C6LHcYsg.d.mts.map +0 -1
- package/dist/kv-stores-CwJdsMln.d.mts.map +0 -1
- package/dist/logger-xE9qI_FS.d.mts.map +0 -1
- package/dist/path-CMwIHsdv.d.mts.map +0 -1
- package/dist/rate-limit-DQDk6bAH.d.mts.map +0 -1
- package/dist/reactivity-DZrc3Yhu.d.mts.map +0 -1
- package/dist/request-id-Dn64nEHK.d.mts.map +0 -1
- package/dist/request-logger-TgcKRNDD.d.mts.map +0 -1
- package/dist/route-flag-B1lQht6v.d.mts.map +0 -1
- package/dist/router-builder-C5EtcFSL.d.mts.map +0 -1
- package/dist/session-DQG72vCf.d.mts.map +0 -1
- package/dist/settings-DgZLgcNU.d.mts.map +0 -1
- package/dist/settings-hG4DH8hQ.mjs.map +0 -1
- package/dist/upload-DnwvZQyi.d.mts.map +0 -1
- package/dist/validate-D4Poe2EE.d.mts.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"view-renderer-BV2rwEUI.mjs","names":[],"sources":["../src/http/request-store.ts","../src/http/background.ts","../src/http/view-renderer.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks'\nimport type { ContextMetaKey, MetaValue } from '../core/execution-context'\n\n/** Per-request storage for REQUEST-scoped DI and request context propagation */\nexport interface RequestStore {\n /** Unique request identifier */\n requestId: string\n /**\n * Per-request singleton cache for REQUEST-scoped services. Keys are\n * heterogeneous (class constructors, `InjectionToken` objects, raw\n * strings), so the map type stays `Map<any, any>`.\n */\n instances: Map<any, any>\n /**\n * Per-request key/value bag. Canonical backing store for\n * `RequestContext.set/get` and the Context Contributor pipeline (#107)\n * since Phase 3. Anything written here is visible to every concrete\n * execution context constructed for the same request, regardless of\n * which middleware/contributor wrote it.\n *\n * Keys are constrained to `string` per the locked decision in\n * `architecture.md` §20.12 (#4); the value type is `unknown` because\n * the concrete shape at each key is determined by the consumer's\n * `ContextMeta` augmentation, not by the store itself.\n *\n * Prefer the {@link getRequestValue} helper over reaching into this\n * map directly — it threads the augmented `ContextMeta` shape through\n * `MetaValue<K>` so consumers get typed reads without an `as` cast.\n * Writes should flow through `ctx.set(key, value)` or a Context\n * Contributor's return value — see the `setRequestValue` note below\n * for why this package intentionally does NOT ship a service-level\n * write helper.\n */\n values: Map<string, unknown>\n /** Set once {@link disposeRequestStore} has run — guards double-dispose. */\n disposed?: boolean\n}\n\n/** AsyncLocalStorage instance shared across the framework */\nexport const requestStore = new AsyncLocalStorage<RequestStore>()\n\n/**\n * Get the current request store. Throws if called outside a request context.\n * Used by the Container to resolve REQUEST-scoped dependencies.\n */\nexport function getRequestStore(): RequestStore {\n const store = requestStore.getStore()\n if (!store) {\n throw new Error(\n 'No active request context. REQUEST-scoped services can only be resolved during an HTTP request.',\n )\n }\n return store\n}\n\n/**\n * Read a per-request `ContextMeta`-keyed value from outside a controller\n * (services, repositories, anywhere with no `ctx` reference). Returns\n * the augmented type for the key — `MetaValue<K>` — so consumers get the\n * same static safety as `ctx.get(key)` without holding the context.\n *\n * Returns `undefined` outside an active request frame (background jobs,\n * startup code, tests without `requestScopeMiddleware()`) — the helper\n * is intentionally null-tolerant so calling it from a service that\n * runs in both request and non-request paths doesn't throw.\n *\n * @example\n * ```ts\n * declare module '@forinda/kickjs' {\n * interface ContextMeta { tenant: { id: string; name: string } }\n * }\n *\n * @Service()\n * class AuditService {\n * log(action: string) {\n * const tenant = getRequestValue('tenant') // typed: { id; name } | undefined\n * db.audit.insert({ action, tenantId: tenant?.id })\n * }\n * }\n * ```\n */\nexport function getRequestValue<K extends ContextMetaKey>(key: K): MetaValue<K> | undefined {\n return requestStore.getStore()?.values.get(key) as MetaValue<K> | undefined\n}\n\n// Intentionally NO `setRequestValue` export.\n//\n// Writes are deliberately context-scoped — only the controlled write\n// surfaces should mutate the per-request Map:\n//\n// 1. A Context Contributor's `resolve()` / `onError()` return value\n// (the runner does `ctx.set(reg.key, value)` on the contributor's\n// behalf). This is the canonical way to populate a key.\n// 2. A controller / middleware / contributor that holds a\n// `RequestContext` instance can call `ctx.set(key, value)`\n// directly. The write is auditable inline at the call site.\n//\n// Letting arbitrary services reach in and mutate the store from\n// anywhere produces \"spooky action at a distance\" — keys appear in\n// the request bag without an obvious source, and tracing which\n// service polluted what becomes a grep exercise. Services that need\n// to publish per-request state should return the value to the caller\n// (controller or contributor) and let *that* layer write it via\n// `ctx.set`. If a future need genuinely requires a service-level\n// write surface, expose a narrow function (`recordTrace`,\n// `markStartTime`) on a service that captures the side effect, not a\n// generic `setRequestValue`.\n","/**\n * Work that outlives the response — `waitUntil(promise)`.\n *\n * A handler that fires off an audit log, an email, or an analytics call and\n * answers without awaiting it leaves that promise unowned: on serverless the\n * platform freezes or kills the instance once the response is sent, and on a\n * Node server `SIGTERM` exits before it settles. `waitUntil` registers the\n * promise so something waits for it:\n *\n * - on the Node server, `shutdown()` awaits it (within `shutdownTimeout`);\n * - through `createHandler()` and the web entry, it is handed to the\n * platform's own `waitUntil` (Workers `ctx`, Netlify `context`, Vercel's\n * `waitUntil`) when you pass it in.\n *\n * Process-wide, like the DI container: one app per process.\n *\n * @module @forinda/kickjs/http/background\n */\nimport { createLogger } from '../core/logger'\nimport { reportError } from '../core/observers'\nimport { requestStore } from './request-store'\n\nconst log = createLogger('waitUntil')\nconst pending = new Set<Promise<void>>()\n\n/**\n * Keep `promise` alive past the response. A rejection is logged (with the\n * request id when called during a request), never left unhandled.\n *\n * @example\n * ```ts\n * @Post('/')\n * async create(ctx: RequestContext) {\n * const order = await this.orders.create(ctx.body)\n * ctx.waitUntil(this.mailer.sendReceipt(order)) // or waitUntil(...) outside a handler\n * return order\n * }\n * ```\n */\nexport function waitUntil(promise: Promise<unknown>): void {\n const requestId = requestStore.getStore()?.requestId\n const tracked: Promise<void> = Promise.resolve(promise).then(\n () => {},\n (err: unknown) => {\n log.error({ err, requestId }, 'Background work passed to waitUntil() failed')\n reportError(err, { source: 'background', requestId })\n },\n )\n pending.add(tracked)\n void tracked.finally(() => pending.delete(tracked))\n}\n\n/**\n * Resolve once every registered promise has settled — including work\n * registered while waiting. Never rejects.\n */\nexport async function settleBackgroundWork(): Promise<void> {\n while (pending.size > 0) await Promise.all(pending)\n}\n\n/** How many `waitUntil` promises have not settled yet. */\nexport function pendingBackgroundWork(): number {\n return pending.size\n}\n\n/**\n * The platform hook `createHandler()` and the web entry forward background\n * work to. Cloudflare Workers' `ctx`, Netlify's `context`, and `{ waitUntil }`\n * from `@vercel/functions` all have this shape.\n */\nexport interface PlatformContext {\n waitUntil?(promise: Promise<unknown>): void\n}\n\n/** Hand every pending (and later-registered) promise to the platform. */\nexport function forwardBackgroundWork(platform: PlatformContext | undefined): void {\n platform?.waitUntil?.(settleBackgroundWork())\n}\n","/**\n * The slot a view engine fills so `ctx.render()` works on every runtime.\n * An adapter binds a renderer onto each request; `ctx.render` asks it first\n * and falls back to the runtime's own engine (Express + ViewAdapter) when it\n * doesn't own the name. `Symbol.for`, so an engine binds it without\n * importing this module.\n */\nimport type { RequestContext } from './context'\n\nexport const VIEW_RENDERER = Symbol.for('kickjs.viewRenderer')\n\nexport interface ViewRenderOptions {\n status?: number\n headers?: Record<string, string>\n /** A layout for this render, or `false` for none — a partial response. */\n layout?: boolean | string\n locale?: string\n timeZone?: string\n}\n\n/** Resolves to the HTML, or to `undefined` when the name isn't this engine's. */\nexport type ViewRenderer = (\n name: string,\n data: Record<string, unknown>,\n opts: ViewRenderOptions,\n ctx: RequestContext,\n) => Promise<string | undefined>\n\nexport function bindViewRenderer(req: object, renderer: ViewRenderer): void {\n ;(req as Record<symbol, unknown>)[VIEW_RENDERER] = renderer\n}\n\nexport function viewRendererFor(req: unknown): ViewRenderer | undefined {\n return (req as Record<symbol, ViewRenderer | undefined> | null)?.[VIEW_RENDERER]\n}\n\nconst PENDING = Symbol('kickjs.pendingResponse')\n\n/** Remember a response still being produced, so the pipeline waits for it. */\nexport function setPendingResponse(ctx: object, p: Promise<void>): void {\n ;(ctx as Record<symbol, unknown>)[PENDING] = p\n}\n\n/** A response `ctx.render()` is still producing, when the handler didn't await it. */\nexport function pendingResponse(ctx: object): Promise<void> | undefined {\n return (ctx as Record<symbol, Promise<void> | undefined>)[PENDING]\n}\n"],"mappings":";;;;;;;;;;mJAuCA,MAAa,aAAe,IAAI,kBAMhC,SAAgB,iBAAgC,CAC9C,IAAM,MAAQ,aAAa,SAAS,EACpC,GAAI,CAAC,MACH,MAAU,MACR,iGACF,EAEF,OAAO,KACT,CA4BA,SAAgB,gBAA0C,IAAkC,CAC1F,OAAO,aAAa,SAAS,CAAC,EAAE,OAAO,IAAI,GAAG,CAChD,CC7DA,MAAM,IAAM,aAAa,WAAW,EAC9B,wBAAU,IAAI,IAgBpB,SAAgB,UAAU,QAAiC,CACzD,IAAM,UAAY,aAAa,SAAS,CAAC,EAAE,UACrC,QAAyB,QAAQ,QAAQ,OAAO,CAAC,CAAC,SAChD,CAAC,EACN,KAAiB,CAChB,IAAI,MAAM,CAAE,IAAK,SAAU,EAAG,8CAA8C,EAC5E,YAAY,IAAK,CAAE,OAAQ,aAAc,SAAU,CAAC,CACtD,CACF,EACA,QAAQ,IAAI,OAAO,EACnB,QAAa,YAAc,QAAQ,OAAO,OAAO,CAAC,CACpD,CAMA,eAAsB,sBAAsC,CAC1D,KAAO,QAAQ,KAAO,GAAG,MAAM,QAAQ,IAAI,OAAO,CACpD,CAGA,SAAgB,uBAAgC,CAC9C,OAAO,QAAQ,IACjB,CAYA,SAAgB,sBAAsB,SAA6C,CACjF,UAAU,YAAY,qBAAqB,CAAC,CAC9C,CCpEA,MAAa,cAAgB,OAAO,IAAI,qBAAqB,EAmB7D,SAAgB,iBAAiB,IAAa,SAA8B,CACzE,IAAiC,eAAiB,QACrD,CAEA,SAAgB,gBAAgB,IAAwC,CACtE,OAAQ,MAA0D,cACpE,CAEA,MAAM,QAAU,OAAO,wBAAwB,EAG/C,SAAgB,mBAAmB,IAAa,EAAwB,CACrE,IAAiC,SAAW,CAC/C,CAGA,SAAgB,gBAAgB,IAAwC,CACtE,OAAQ,IAAkD,QAC5D"}
|
|
1
|
+
{"version":3,"file":"view-renderer-C4sMEruA.mjs","names":[],"sources":["../src/http/request-store.ts","../src/http/background.ts","../src/http/view-renderer.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks'\nimport type { ContextMetaKey, MetaValue } from '../core/execution-context'\n\n/** Per-request storage for REQUEST-scoped DI and request context propagation */\nexport interface RequestStore {\n /** Unique request identifier */\n requestId: string\n /**\n * Per-request singleton cache for REQUEST-scoped services. Keys are\n * heterogeneous (class constructors, `InjectionToken` objects, raw\n * strings), so the map type stays `Map<any, any>`.\n */\n instances: Map<any, any>\n /**\n * Per-request key/value bag. Canonical backing store for\n * `RequestContext.set/get` and the Context Contributor pipeline (#107)\n * since Phase 3. Anything written here is visible to every concrete\n * execution context constructed for the same request, regardless of\n * which middleware/contributor wrote it.\n *\n * Keys are constrained to `string` per the locked decision in\n * `architecture.md` §20.12 (#4); the value type is `unknown` because\n * the concrete shape at each key is determined by the consumer's\n * `ContextMeta` augmentation, not by the store itself.\n *\n * Prefer the {@link getRequestValue} helper over reaching into this\n * map directly — it threads the augmented `ContextMeta` shape through\n * `MetaValue<K>` so consumers get typed reads without an `as` cast.\n * Writes should flow through `ctx.set(key, value)` or a Context\n * Contributor's return value — see the `setRequestValue` note below\n * for why this package intentionally does NOT ship a service-level\n * write helper.\n */\n values: Map<string, unknown>\n /** Set once {@link disposeRequestStore} has run — guards double-dispose. */\n disposed?: boolean\n}\n\n/** AsyncLocalStorage instance shared across the framework */\nexport const requestStore = new AsyncLocalStorage<RequestStore>()\n\n/**\n * Get the current request store. Throws if called outside a request context.\n * Used by the Container to resolve REQUEST-scoped dependencies.\n */\nexport function getRequestStore(): RequestStore {\n const store = requestStore.getStore()\n if (!store) {\n throw new Error(\n 'No active request context. REQUEST-scoped services can only be resolved during an HTTP request.',\n )\n }\n return store\n}\n\n/**\n * Read a per-request `ContextMeta`-keyed value from outside a controller\n * (services, repositories, anywhere with no `ctx` reference). Returns\n * the augmented type for the key — `MetaValue<K>` — so consumers get the\n * same static safety as `ctx.get(key)` without holding the context.\n *\n * Returns `undefined` outside an active request frame (background jobs,\n * startup code, tests without `requestScopeMiddleware()`) — the helper\n * is intentionally null-tolerant so calling it from a service that\n * runs in both request and non-request paths doesn't throw.\n *\n * @example\n * ```ts\n * declare module '@forinda/kickjs' {\n * interface ContextMeta { tenant: { id: string; name: string } }\n * }\n *\n * @Service()\n * class AuditService {\n * log(action: string) {\n * const tenant = getRequestValue('tenant') // typed: { id; name } | undefined\n * db.audit.insert({ action, tenantId: tenant?.id })\n * }\n * }\n * ```\n */\nexport function getRequestValue<K extends ContextMetaKey>(key: K): MetaValue<K> | undefined {\n return requestStore.getStore()?.values.get(key) as MetaValue<K> | undefined\n}\n\n// Intentionally NO `setRequestValue` export.\n//\n// Writes are deliberately context-scoped — only the controlled write\n// surfaces should mutate the per-request Map:\n//\n// 1. A Context Contributor's `resolve()` / `onError()` return value\n// (the runner does `ctx.set(reg.key, value)` on the contributor's\n// behalf). This is the canonical way to populate a key.\n// 2. A controller / middleware / contributor that holds a\n// `RequestContext` instance can call `ctx.set(key, value)`\n// directly. The write is auditable inline at the call site.\n//\n// Letting arbitrary services reach in and mutate the store from\n// anywhere produces \"spooky action at a distance\" — keys appear in\n// the request bag without an obvious source, and tracing which\n// service polluted what becomes a grep exercise. Services that need\n// to publish per-request state should return the value to the caller\n// (controller or contributor) and let *that* layer write it via\n// `ctx.set`. If a future need genuinely requires a service-level\n// write surface, expose a narrow function (`recordTrace`,\n// `markStartTime`) on a service that captures the side effect, not a\n// generic `setRequestValue`.\n","/**\n * Work that outlives the response — `waitUntil(promise)`.\n *\n * A handler that fires off an audit log, an email, or an analytics call and\n * answers without awaiting it leaves that promise unowned: on serverless the\n * platform freezes or kills the instance once the response is sent, and on a\n * Node server `SIGTERM` exits before it settles. `waitUntil` registers the\n * promise so something waits for it:\n *\n * - on the Node server, `shutdown()` awaits it (within `shutdownTimeout`);\n * - through `createHandler()` and the web entry, it is handed to the\n * platform's own `waitUntil` (Workers `ctx`, Netlify `context`, Vercel's\n * `waitUntil`) when you pass it in.\n *\n * Process-wide, like the DI container: one app per process.\n *\n * @module @forinda/kickjs/http/background\n */\nimport { createLogger } from '../core/logger'\nimport { reportError } from '../core/observers'\nimport { requestStore } from './request-store'\n\nconst log = createLogger('waitUntil')\nconst pending = new Set<Promise<void>>()\n\n/**\n * Keep `promise` alive past the response. A rejection is logged (with the\n * request id when called during a request), never left unhandled.\n *\n * @example\n * ```ts\n * @Post('/')\n * async create(ctx: RequestContext) {\n * const order = await this.orders.create(ctx.body)\n * ctx.waitUntil(this.mailer.sendReceipt(order)) // or waitUntil(...) outside a handler\n * return order\n * }\n * ```\n */\nexport function waitUntil(promise: Promise<unknown>): void {\n const requestId = requestStore.getStore()?.requestId\n const tracked: Promise<void> = Promise.resolve(promise).then(\n () => {},\n (err: unknown) => {\n log.error({ err, requestId }, 'Background work passed to waitUntil() failed')\n reportError(err, { source: 'background', requestId })\n },\n )\n pending.add(tracked)\n void tracked.finally(() => pending.delete(tracked))\n}\n\n/**\n * Resolve once every registered promise has settled — including work\n * registered while waiting. Never rejects.\n */\nexport async function settleBackgroundWork(): Promise<void> {\n while (pending.size > 0) await Promise.all(pending)\n}\n\n/** How many `waitUntil` promises have not settled yet. */\nexport function pendingBackgroundWork(): number {\n return pending.size\n}\n\n/**\n * The platform hook `createHandler()` and the web entry forward background\n * work to. Cloudflare Workers' `ctx`, Netlify's `context`, and `{ waitUntil }`\n * from `@vercel/functions` all have this shape.\n */\nexport interface PlatformContext {\n waitUntil?(promise: Promise<unknown>): void\n}\n\n/** Hand every pending (and later-registered) promise to the platform. */\nexport function forwardBackgroundWork(platform: PlatformContext | undefined): void {\n platform?.waitUntil?.(settleBackgroundWork())\n}\n","/**\n * The slot a view engine fills so `ctx.render()` works on every runtime.\n * An adapter binds a renderer onto each request; `ctx.render` asks it first\n * and falls back to the runtime's own engine (Express + ViewAdapter) when it\n * doesn't own the name. `Symbol.for`, so an engine binds it without\n * importing this module.\n */\nimport type { RequestContext } from './context'\n\nexport const VIEW_RENDERER = Symbol.for('kickjs.viewRenderer')\n\nexport interface ViewRenderOptions {\n status?: number\n headers?: Record<string, string>\n /** A layout for this render, or `false` for none — a partial response. */\n layout?: boolean | string\n locale?: string\n timeZone?: string\n}\n\n/** Resolves to the HTML, or to `undefined` when the name isn't this engine's. */\nexport type ViewRenderer = (\n name: string,\n data: Record<string, unknown>,\n opts: ViewRenderOptions,\n ctx: RequestContext,\n) => Promise<string | undefined>\n\nexport function bindViewRenderer(req: object, renderer: ViewRenderer): void {\n ;(req as Record<symbol, unknown>)[VIEW_RENDERER] = renderer\n}\n\nexport function viewRendererFor(req: unknown): ViewRenderer | undefined {\n return (req as Record<symbol, ViewRenderer | undefined> | null)?.[VIEW_RENDERER]\n}\n\nconst PENDING = Symbol('kickjs.pendingResponse')\n\n/** Remember a response still being produced, so the pipeline waits for it. */\nexport function setPendingResponse(ctx: object, p: Promise<void>): void {\n ;(ctx as Record<symbol, unknown>)[PENDING] = p\n}\n\n/** A response `ctx.render()` is still producing, when the handler didn't await it. */\nexport function pendingResponse(ctx: object): Promise<void> | undefined {\n return (ctx as Record<symbol, Promise<void> | undefined>)[PENDING]\n}\n"],"mappings":";;;;;;;;;;A,mJAuCA,MAAa,aAAe,IAAI,kBAMhC,SAAgB,iBAAgC,CAC9C,IAAM,MAAQ,aAAa,SAAS,EACpC,GAAI,CAAC,MACH,MAAU,MACR,iGACF,EAEF,OAAO,KACT,CA4BA,SAAgB,gBAA0C,IAAkC,CAC1F,OAAO,aAAa,SAAS,CAAC,EAAE,OAAO,IAAI,GAAG,CAChD,CC7DA,MAAM,IAAM,aAAa,WAAW,EAC9B,wBAAU,IAAI,IAgBpB,SAAgB,UAAU,QAAiC,CACzD,IAAM,UAAY,aAAa,SAAS,CAAC,EAAE,UACrC,QAAyB,QAAQ,QAAQ,OAAO,CAAC,CAAC,SAChD,CAAC,EACN,KAAiB,CAChB,IAAI,MAAM,CAAE,IAAK,SAAU,EAAG,8CAA8C,EAC5E,YAAY,IAAK,CAAE,OAAQ,aAAc,SAAU,CAAC,CACtD,CACF,EACA,QAAQ,IAAI,OAAO,EACnB,QAAa,YAAc,QAAQ,OAAO,OAAO,CAAC,CACpD,CAMA,eAAsB,sBAAsC,CAC1D,KAAO,QAAQ,KAAO,GAAG,MAAM,QAAQ,IAAI,OAAO,CACpD,CAGA,SAAgB,uBAAgC,CAC9C,OAAO,QAAQ,IACjB,CAYA,SAAgB,sBAAsB,SAA6C,CACjF,UAAU,YAAY,qBAAqB,CAAC,CAC9C,CCpEA,MAAa,cAAgB,OAAO,IAAI,qBAAqB,EAmB7D,SAAgB,iBAAiB,IAAa,SAA8B,CACzE,IAAiC,eAAiB,QACrD,CAEA,SAAgB,gBAAgB,IAAwC,CACtE,OAAQ,MAA0D,cACpE,CAEA,MAAM,QAAU,OAAO,wBAAwB,EAG/C,SAAgB,mBAAmB,IAAa,EAAwB,CACrE,IAAiC,SAAW,CAC/C,CAGA,SAAgB,gBAAgB,IAAwC,CACtE,OAAQ,IAAkD,QAC5D,C"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.14.
|
|
2
|
+
* @forinda/kickjs v10.14.2
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -9,4 +9,4 @@
|
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
11
|
function randomHex(bytes){let buf=crypto.getRandomValues(new Uint8Array(bytes));return Array.from(buf,b=>b.toString(16).padStart(2,`0`)).join(``)}function safeEqual(a,b){let length=Math.max(a.length,b.length),diff=a.length^b.length;for(let i=0;i<length;i++)diff|=a.charCodeAt(i)^b.charCodeAt(i);return diff===0}function matchesBearer(header,secret){return typeof header==`string`&&typeof secret==`string`&&secret.length>0&&safeEqual(header,`Bearer ${secret}`)}export{randomHex as n,safeEqual as r,matchesBearer as t};
|
|
12
|
-
//# sourceMappingURL=web-crypto-
|
|
12
|
+
//# sourceMappingURL=web-crypto-SXVOPDxW.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"web-crypto-
|
|
1
|
+
{"version":3,"file":"web-crypto-SXVOPDxW.mjs","names":[],"sources":["../src/core/web-crypto.ts"],"sourcesContent":["/**\n * Web Crypto helpers — portable across node/bun/deno/workers via\n * `globalThis.crypto`. The Web Crypto migration lives here so the request\n * path never imports `node:crypto` (edge-runtime portability).\n */\n\n/** Random hex string — replacement for `randomBytes(n).toString('hex')`. */\nexport function randomHex(bytes: number): string {\n const buf = crypto.getRandomValues(new Uint8Array(bytes))\n return Array.from(buf, (b) => b.toString(16).padStart(2, '0')).join('')\n}\n\n/**\n * Constant-time string comparison for secrets and tokens — the portable\n * counterpart of `timingSafeEqual`. Walks the longer input and folds the\n * length difference in, so it doesn't stop at the first wrong character and\n * a guess's contents don't show in the timing. The loop runs over the longer\n * input, so the time can still reveal the expected value's length.\n */\nexport function safeEqual(a: string, b: string): boolean {\n const length = Math.max(a.length, b.length)\n let diff = a.length ^ b.length\n // Past the end, charCodeAt is NaN, which `^` treats as 0.\n for (let i = 0; i < length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i)\n return diff === 0\n}\n\n/**\n * Constant-time check of an `Authorization: Bearer <secret>` header against a\n * shared secret — a cron trigger, a metrics scrape, a webhook. `false` for a\n * missing or non-string header, and for an empty secret (an unset env var\n * must not let `Authorization: Bearer ` through). Pass\n * `ctx.headers.authorization` as is.\n */\nexport function matchesBearer(header: unknown, secret: string): boolean {\n return (\n typeof header === 'string' &&\n typeof secret === 'string' &&\n secret.length > 0 &&\n safeEqual(header, `Bearer ${secret}`)\n )\n}\n"],"mappings":";;;;;;;;;;AAOA,SAAgB,UAAU,MAAuB,CAC/C,IAAM,IAAM,OAAO,gBAAgB,IAAI,WAAW,KAAK,CAAC,EACxD,OAAO,MAAM,KAAK,IAAM,GAAM,EAAE,SAAS,EAAE,CAAC,CAAC,SAAS,EAAG,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE,CACxE,CASA,SAAgB,UAAU,EAAW,EAAoB,CACvD,IAAM,OAAS,KAAK,IAAI,EAAE,OAAQ,EAAE,MAAM,EACtC,KAAO,EAAE,OAAS,EAAE,OAExB,IAAK,IAAI,EAAI,EAAG,EAAI,OAAQ,IAAK,MAAQ,EAAE,WAAW,CAAC,EAAI,EAAE,WAAW,CAAC,EACzE,OAAO,OAAS,CAClB,CASA,SAAgB,cAAc,OAAiB,OAAyB,CACtE,OACE,OAAO,QAAW,UAClB,OAAO,QAAW,UAClB,OAAO,OAAS,GAChB,UAAU,OAAQ,UAAU,QAAQ,CAExC,C"}
|
package/dist/web.d.mts
CHANGED
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
|
|
2
|
-
import {
|
|
3
|
-
import { x as MiddlewareHandler } from "./decorators-
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
//#region src/http/web/driver.d.ts
|
|
2
|
+
import { m as ContributorRegistrations, r as AppModuleEntry } from "./app-module-EmIojM4d.mjs";
|
|
3
|
+
import { x as MiddlewareHandler } from "./decorators-BAD8qjuq.mjs";
|
|
4
|
+
import { E as JobContextCarrier, F as registerJobContext, I as runJob, L as stampJobContext, S as JOB_CONTEXT_FIELD, a as KvSessionStoreOptions, c as matchesBearer, d as waitUntil, f as InferHandlerResponse, g as ReplyOptions, h as ReplyHeaders, i as KvSessionStore, k as JobLike, l as PlatformContext, m as Reply, n as KvRateLimitStore, o as RateLimitGuardOptions, r as KvRateLimitStoreOptions, s as rateLimitGuard, t as KvLike, x as reply, y as isReply } from "./kv-stores-wTD3VDPB.mjs";
|
|
5
|
+
import { a as SettingsDeclaration } from "./settings-CB6lh6_s.mjs";
|
|
6
|
+
import { t as ValidationErrorFactory } from "./validate-BbthfLBb.mjs";
|
|
7
|
+
import { O as SseHandler, h as RouteEntry, x as RuntimeResponse } from "./adapter-B64IOivZ.mjs";
|
|
8
|
+
import { f as runCronJobs, o as CronRun } from "./cron-DGV1AE0R.mjs";
|
|
10
9
|
/**
|
|
11
10
|
* Presents a web `Request` as the express-shaped `req` object that
|
|
12
11
|
* `RequestContext` (and route validation) reads: plain-object `headers`,
|
|
@@ -64,8 +63,6 @@ export declare class WebResponseDriver implements RuntimeResponse {
|
|
|
64
63
|
/** Switch to streaming mode and resolve `ready` with the streamed Response. */
|
|
65
64
|
private startStream;
|
|
66
65
|
}
|
|
67
|
-
//#endregion
|
|
68
|
-
//#region src/http/web/handler.d.ts
|
|
69
66
|
interface WebRouteInvocation {
|
|
70
67
|
request: Request;
|
|
71
68
|
url: URL;
|
|
@@ -91,8 +88,6 @@ interface WebRouteHooks {
|
|
|
91
88
|
export declare function compileWebRoute(entry: RouteEntry, hooks?: WebRouteHooks, options?: {
|
|
92
89
|
bodyLimit?: number;
|
|
93
90
|
}): (invocation: WebRouteInvocation) => Promise<Response>;
|
|
94
|
-
//#endregion
|
|
95
|
-
//#region src/web.d.ts
|
|
96
91
|
export interface CreateWebAppOptions {
|
|
97
92
|
/**
|
|
98
93
|
* The h3 v2 module, statically imported by the caller:
|
|
@@ -189,6 +184,5 @@ export interface QueueBatch {
|
|
|
189
184
|
retry(): void;
|
|
190
185
|
}>;
|
|
191
186
|
}
|
|
192
|
-
//#endregion
|
|
193
187
|
export { type CronRun, type InferHandlerResponse, JOB_CONTEXT_FIELD, type JobContextCarrier, type JobLike, type KvLike, KvRateLimitStore, type KvRateLimitStoreOptions, KvSessionStore, type KvSessionStoreOptions, type PlatformContext, type RateLimitGuardOptions, type Reply, type ReplyHeaders, type ReplyOptions, type SseHandler, isReply, matchesBearer, rateLimitGuard, registerJobContext, reply, runCronJobs, runJob, stampJobContext, waitUntil };
|
|
194
188
|
//# sourceMappingURL=web.d.mts.map
|
package/dist/web.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"web.d.mts","names":[],"sources":["../src/http/web/driver.ts","../src/http/web/handler.ts","../src/web.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"web.d.mts","names":[],"sources":["../src/http/web/driver.ts","../src/http/web/handler.ts","../src/web.ts"],"mappings":";;;;;;;;;;;;;;;qBAgBa;WACF;WACA;;WAEA,SAAS;EAClB;EACA,QAAQ;EACR,OAAO;EACP;EACA;EACA;GAGC;mBAEgB;EAEjB,YAAY,SAAS,SAAS,KAAK;;EAmBnC,KAAK,eAAe;;EAMpB,GAAG,eAAe;;qBA6BP,6BAA6B;mBAYX;;WAVpB,OAAO,QAAQ;;EAExB;UAEQ;mBACS;UACT;UACA;UACA;EAER,YAA6B,SAAS;EAMtC,OAAO;EAKP,KAAK;EAML,KAAK;EAYL,KAAK;;EAML,UAAU;EAQV,UAAU,cAAc;EAUxB;EAIA,UAAU,oBAAoB,UAAU;EASxC;EAKA,MAAM;EAQN,IAAI;EAUJ,KAAK,eAAe,cAAc;MAM9B;;UAKI;;UAuBA;;UCzLO;EACf,SAAS;EACT,KAAK;EACL,QAAQ;;;;;;;EAOR;;UAGe;;;;;;;;EAQf,WAAW,cAAc,KAAK,gBAAgB,KAAK,6BAA6B;;wBAwClE,gBACd,OAAO,YACP,QAAQ,eACR;EAAW;KACT,YAAY,uBAAuB,QAAQ;iBCT9B;;;;;;;EAOf;;EAEA,SAAS;;EAET;;;;;EAKA;;EAEA,eAAe;;;;;;EAMf,MAAM;;;;;;EAMN,cAAc;;;;;EAKd;;EAEA,WAAW;;EAEX,kBAAkB;;iBAGH;;;;;;EAMf,QAAQ,SAAS,SAAS,WAAW,oBAAoB,QAAQ;;EAEjE;;;;;;;;wBASc,aAAa,SAAS,sBAAsB;;;;;;;;;;;;;;;;;;;;;;wBAsK5C,mBACd,QAAQ,KAAK,uCAAuC;EAEpD,QACE,SAAS,SACT,MAAM,oCACN,MAAM,oBACH,QAAQ;EACb,YACE;IAAS;KACT,MAAM,oCACN,MAAM,oBACH;EACL,QACE,OAAO,YACP,MAAM,oCACN,MAAM,oBACH;;;iBAyCU;WACN;WACA,UAAU;aACR;aACA;IACT;IACA"}
|
package/dist/web.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.14.
|
|
2
|
+
* @forinda/kickjs v10.14.2
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,5 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{Container}from"./core/container.mjs";import{a as moduleName,n as RouteUrls,r as MutableModuleRegistry,t as ROUTE_URLS}from"./url-for-
|
|
11
|
+
import{Container}from"./core/container.mjs";import{a as moduleName,n as RouteUrls,r as MutableModuleRegistry,t as ROUTE_URLS}from"./url-for-C4Eomib7.mjs";import{n as assertRouteUnique,r as buildRouteTable,t as _setExternalContributorSources}from"./router-builder-D2cly8Wt.mjs";import{f as requestStore,l as waitUntil,o as forwardBackgroundWork}from"./view-renderer-C4sMEruA.mjs";import{runCronJobs}from"./core/cron.mjs";import{d as stampJobContext,l as registerJobContext,t as JOB_CONTEXT_FIELD,u as runJob}from"./jobs-CuZqVDDG.mjs";import{n as headFromGet,t as compileWebRoute}from"./handler-B66laQY0.mjs";import{o as loadSettings}from"./settings-v2N3V8Bl.mjs";import{o as parseByteSize}from"./body-policy-Be3Y0hjq.mjs";import{n as WebResponseDriver,t as WebRequestShim}from"./driver-oZBQDJZz.mjs";import{notFoundHandler}from"./http/middleware/error-handler.mjs";import{buildMountPath}from"./core/path.mjs";import{a as reply,r as isReply}from"./reply-B5kZ6VGv.mjs";import{t as matchesBearer}from"./web-crypto-SXVOPDxW.mjs";import{n as KvSessionStore,r as rateLimitGuard,t as KvRateLimitStore}from"./kv-stores-C9CJ3xCB.mjs";function createWebApp(options){let h3mod=options.h3;if(typeof h3mod?.H3!=`function`)throw Error(`@forinda/kickjs/web: pass the h3 v2 module — \`createWebApp({ h3: await import("h3"), ... })\`. The installed h3 must be v2 (npm dist-tag 'latest'); v1 has no H3 class.`);let container=Container.getInstance(),routeUrls=new RouteUrls;if(container.registerInstance(ROUTE_URLS,routeUrls),options.env){let env=options.env;Container.setEnvResolver(key=>env[key])}Container.setRequestStoreProvider(()=>requestStore.getStore()??null);let registry=new MutableModuleRegistry;for(let m of options.modules)registry.mount(m);let modules=registry.entries.map(entry=>typeof entry==`function`?new entry:entry),settingsEnv=options.env??(typeof process<`u`?process.env:{});for(let[section,value]of loadSettings([...options.settings??[],...modules.flatMap(mod=>mod.settings?.()??[])],settingsEnv))container.registerInstance(section,value);for(let mod of modules)mod.register?.(container);container.bootstrap();let app=new h3mod.H3,getUrls=[],apiPrefix=options.apiPrefix??`/api`,defaultVersion=options.defaultVersion??1,globalMiddleware=options.middlewares??[],bodyLimit=parseByteSize(options.jsonLimit??`1mb`),globalSources=(options.contributors??[]).map(registration=>({source:`global`,registration,label:`createWebApp`})),seenRoutes=/* @__PURE__ */ new Map,mounted=[];for(let mod of modules){let moduleLabel=moduleName(mod),moduleSources=(mod.contributors?.()??[]).map(registration=>({source:`module`,registration,label:moduleLabel}));_setExternalContributorSources([...moduleSources,...globalSources]);try{let result=mod.routes();if(!result)continue;let routeSets=Array.isArray(result)?result:[result];for(let route of routeSets){if(!route.controller)throw Error(`@forinda/kickjs/web: module route at '${route.path}' has no controller. Express-style \`router\` mounts are not supported on the web entry.`);let version=route.version??defaultVersion,mountPath=buildMountPath(route.prefix===!1?``:apiPrefix,version,route.path);for(let entry of buildRouteTable(route.controller,{mountFlags:route.flags})){let url=joinPath(mountPath,entry.path),owner=`${route.controller.name??`controller`}.${String(entry.meta.handlerName??`?`)}`;assertRouteUnique(seenRoutes,entry.method,url,owner),mounted.push({method:entry.method,path:url}),globalMiddleware.length>0&&(entry.middlewares=[...globalMiddleware,...entry.middlewares]),entry.validationError=options.validationError,entry.urls=routeUrls,routeUrls.add(owner,url);let run=compileWebRoute(entry,void 0,{bodyLimit}),handler=event=>run({request:event.req,url:event.url,params:event.context.params??{}});app.on(entry.method,url,handler),entry.method===`GET`&&getUrls.push({url,handler})}}}finally{_setExternalContributorSources([])}}for(let{url,handler}of getUrls)app.on(`HEAD`,url,event=>headFromGet(handler(event)));let notFound=notFoundHandler(mounted);return app.all(`/**`,event=>{let driver=new WebResponseDriver(event.req.signal);return notFound(new WebRequestShim(event.req,event.url),driver,()=>{}),driver.ready}),{fetch:async(request,platform)=>{let response=await app.fetch(request);return forwardBackgroundWork(platform),response},h3:app}}function createFetchHandler(build){let app;return{fetch:(request,env={},ctx)=>(app??=createWebApp(build(env)),app.fetch(request,ctx)),scheduled:async(event,env={},ctx)=>{app??=createWebApp(build(env));let run=runCronJobs(Container.getInstance(),{expression:event.cron},`workers`).then(()=>{});ctx?.waitUntil?.(run),await run},queue:async(batch,env={})=>{app??=createWebApp(build(env));let container=Container.getInstance();await Promise.all(batch.messages.map(async message=>{let body=message.body,named=typeof body==`object`&&!!body&&typeof body.name==`string`;try{await runJob(container,batch.queue,{name:named?body.name:``,data:named?body.data:message.body,id:message.id}),message.ack()}catch{message.retry()}}))}}}function joinPath(mountPath,path){let a=mountPath.endsWith(`/`)?mountPath.slice(0,-1):mountPath;return path===`/`||path===``?a===``?`/`:a:`${a}${path.startsWith(`/`)?path:`/${path}`}`}export{JOB_CONTEXT_FIELD,KvRateLimitStore,KvSessionStore,WebRequestShim,WebResponseDriver,compileWebRoute,createFetchHandler,createWebApp,isReply,matchesBearer,rateLimitGuard,registerJobContext,reply,runCronJobs,runJob,stampJobContext,waitUntil};
|
|
12
12
|
//# sourceMappingURL=web.mjs.map
|
package/dist/web.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"web.mjs","names":[],"sources":["../src/web.ts"],"sourcesContent":["// `@forinda/kickjs/web` — the web-standard fetch entry for edge runtimes\n// (Cloudflare Workers), Bun, and Deno.\n//\n// PURITY CONTRACT: this entry's import graph must stay free of node-only\n// runtime imports — no `node:http`, `node:cluster`, `node:fs`, `node:module`,\n// no `express`, no `Application`/`bootstrap`. The single sanctioned node API\n// is `node:async_hooks` (AsyncLocalStorage — available on Workers with\n// `nodejs_compat`, Deno, and Bun). Enforced by the bundle-graph purity test.\n//\n// ```ts\n// // Cloudflare Workers (wrangler.toml: compatibility_flags = [\"nodejs_compat\"])\n// import { createWebApp } from '@forinda/kickjs/web'\n// import * as h3 from 'h3'\n// import { modules } from './modules'\n//\n// const app = createWebApp({ h3, modules })\n// export default { fetch: (req: Request) => app.fetch(req) }\n//\n// // Bun\n// Bun.serve({ fetch: (req) => app.fetch(req) })\n// ```\n\nimport { Container } from './core/container'\nimport { MutableModuleRegistry } from './core/module-registry'\nimport type { AppModule, AppModuleClass, AppModuleEntry } from './core/app-module'\nimport type { ContributorRegistrations } from './core/context-decorator'\nimport type { MiddlewareHandler } from './core/decorators'\nimport type { SourcedRegistration } from './core/contributor-pipeline'\nimport {\n _setExternalContributorSources,\n assertRouteUnique,\n buildRouteTable,\n} from './http/router-builder'\nimport { requestStore } from './http/request-store'\nimport { forwardBackgroundWork, type PlatformContext } from './http/background'\nimport { runCronJobs } from './core/cron'\nimport { runJob } from './core/jobs'\nimport { compileWebRoute, headFromGet } from './http/web/handler'\nimport { ROUTE_URLS, RouteUrls } from './http/url-for'\nimport { loadSettings, type SettingsDeclaration } from './config/settings'\nimport { DEFAULT_BODY_LIMIT, parseByteSize } from './http/body-policy'\nimport { WebRequestShim, WebResponseDriver } from './http/web/driver'\nimport { notFoundHandler, type MountedRoute } from './http/middleware/error-handler'\nimport type { ValidationErrorFactory } from './http/middleware/validate'\nimport { buildMountPath } from './core/path'\nimport { moduleName } from './core/define-module'\n\nexport { WebRequestShim, WebResponseDriver } from './http/web/driver'\nexport { compileWebRoute } from './http/web/handler'\n// Return-value handler helpers — edge consumers can't import the main barrel.\nexport {\n reply,\n isReply,\n type Reply,\n type ReplyHeaders,\n type ReplyOptions,\n type InferHandlerResponse,\n} from './http/reply'\nexport type { SseHandler } from './http/context'\nexport { waitUntil, type PlatformContext } from './http/background'\nexport { runCronJobs, type CronRun } from './core/cron'\nexport { matchesBearer } from './core/web-crypto'\nexport {\n runJob,\n registerJobContext,\n stampJobContext,\n JOB_CONTEXT_FIELD,\n type JobLike,\n type JobContextCarrier,\n} from './core/jobs'\n// Edge-safe stores + ctx-style rate limiter (zero runtime imports).\nexport {\n KvRateLimitStore,\n KvSessionStore,\n type KvLike,\n type KvRateLimitStoreOptions,\n type KvSessionStoreOptions,\n} from './http/middleware/kv-stores'\nexport { rateLimitGuard, type RateLimitGuardOptions } from './http/middleware/rate-limit-guard'\n\n// Minimal structural surface of h3 v2 used here (kept local so this entry\n// never imports the node-coupled h3 runtime module).\ninterface H3AppLike {\n on(method: string, path: string, handler: (event: H3EventLike) => unknown): unknown\n all(path: string, handler: (event: H3EventLike) => unknown): unknown\n fetch(request: Request): Promise<Response>\n}\ninterface H3EventLike {\n req: Request\n url: URL\n context: { params?: Record<string, string> }\n}\n\nexport interface CreateWebAppOptions {\n /**\n * The h3 v2 module, statically imported by the caller:\n * `import * as h3 from 'h3'`. Passed in (rather than loaded here) because\n * edge bundlers have no `createRequire`, and a static `import 'h3'` inside\n * this entry would force the peer on every consumer of the subpath.\n */\n h3: unknown\n /** App modules — same shapes `bootstrap({ modules })` accepts. */\n modules: AppModuleEntry[]\n /** Route prefix (default '/api') — parity with bootstrap. */\n apiPrefix?: string\n /**\n * Default route version (default 1) — parity with bootstrap. `false` opts\n * out of URL versioning; a module's own `version` still overrides it.\n */\n defaultVersion?: number | false\n /** Global Context Contributors — parity with `bootstrap({ contributors })`. */\n contributors?: ContributorRegistrations\n /**\n * Env values for ConfigService/@Value resolution. On Workers, pass the\n * `env` binding from the fetch handler (see `createFetchHandler`); on\n * Bun/Deno, ambient `process.env` already works and this can be omitted.\n */\n env?: Record<string, string | undefined>\n /**\n * Global `(ctx, next)` middlewares, run before route middlewares on every\n * route — the web-entry counterpart of `bootstrap({ middlewares })`. Only\n * ctx-style handlers are accepted (no connect/express middleware here).\n */\n middlewares?: MiddlewareHandler[]\n /**\n * Largest request body parsed, as bytes or `'1mb'`-style (default `'1mb'`)\n * — parity with `bootstrap({ jsonLimit })`. A larger body answers 413.\n */\n jsonLimit?: string | number\n /** App-wide settings sections — parity with `bootstrap({ settings })`. */\n settings?: SettingsDeclaration[]\n /** What a failed route validation throws — parity with `bootstrap({ validationError })`. */\n validationError?: ValidationErrorFactory\n}\n\nexport interface WebApp {\n /**\n * Web-standard entry: `Request` in, `Response` out. Pass the platform\n * context (Workers `ctx`, Netlify `context`) so work handed to\n * `ctx.waitUntil()` finishes after the response.\n */\n fetch: (request: Request, platform?: PlatformContext) => Promise<Response>\n /** The underlying h3 v2 app, for advanced composition. */\n h3: unknown\n}\n\n/**\n * Build a KickJS app as a web-standard fetch handler — no node http server,\n * no Application/bootstrap. Module registration, DI, and the contributor\n * pipeline behave exactly like `bootstrap()`; routes are compiled once here\n * and served through h3 v2's router.\n */\nexport function createWebApp(options: CreateWebAppOptions): WebApp {\n const h3mod = options.h3 as { H3?: new () => H3AppLike }\n if (typeof h3mod?.H3 !== 'function') {\n throw new Error(\n '@forinda/kickjs/web: pass the h3 v2 module — `createWebApp({ h3: await import(\"h3\"), ... })`. ' +\n \"The installed h3 must be v2 (npm dist-tag 'latest'); v1 has no H3 class.\",\n )\n }\n\n const container = Container.getInstance()\n // Route names for ctx.urlFor() / the ROUTE_URLS token — bound before modules\n // register so their services can inject it.\n const routeUrls = new RouteUrls()\n container.registerInstance(ROUTE_URLS, routeUrls)\n // Wire ConfigService/@Value env resolution when the platform has no\n // ambient process.env (Workers). Latest-wins like loadEnv().\n if (options.env) {\n const env = options.env\n Container.setEnvResolver((key: string) => env[key])\n }\n\n // Request-scope provider — same wiring Application.setup() performs.\n Container.setRequestStoreProvider(() => requestStore.getStore() ?? null)\n\n // Module mounting — mirrors Application.setup() steps 1:1 for the module\n // path (plugins/adapters are out of scope for the edge entry at launch).\n const registry = new MutableModuleRegistry()\n for (const m of options.modules) registry.mount(m)\n const modules = registry.entries.map((entry) =>\n typeof entry === 'function' ? new (entry as AppModuleClass)() : (entry as AppModule),\n )\n // Declared settings sections — app-wide and mounted modules' — from the\n // platform env (Workers bindings) when given, bound before modules register.\n const settingsEnv = (options.env ??\n (typeof process !== 'undefined' ? process.env : {})) as NodeJS.ProcessEnv\n for (const [section, value] of loadSettings(\n [...(options.settings ?? []), ...modules.flatMap((mod) => mod.settings?.() ?? [])],\n settingsEnv,\n )) {\n container.registerInstance(section, value)\n }\n for (const mod of modules) mod.register?.(container)\n container.bootstrap()\n\n const app = new h3mod.H3()\n const getUrls: Array<{ url: string; handler: (event: H3EventLike) => unknown }> = []\n const apiPrefix = options.apiPrefix ?? '/api'\n const defaultVersion = options.defaultVersion ?? 1\n const globalMiddleware = options.middlewares ?? []\n const bodyLimit = parseByteSize(options.jsonLimit ?? DEFAULT_BODY_LIMIT)\n\n const globalSources: SourcedRegistration[] = (options.contributors ?? []).map(\n (registration): SourcedRegistration => ({\n source: 'global',\n registration: registration as SourcedRegistration['registration'],\n label: 'createWebApp',\n }),\n )\n\n // Duplicate-route guard (KICK006) — same boot-time check as the node path.\n const seenRoutes = new Map<string, string>()\n // For the catch-all: a known path with the wrong verb is a 405, not a 404.\n const mounted: MountedRoute[] = []\n\n for (const mod of modules) {\n const moduleLabel = moduleName(mod)\n const moduleSources: SourcedRegistration[] = (mod.contributors?.() ?? []).map(\n (registration): SourcedRegistration => ({\n source: 'module',\n registration,\n label: moduleLabel,\n }),\n )\n\n _setExternalContributorSources([...moduleSources, ...globalSources])\n try {\n const result = mod.routes()\n if (!result) continue\n const routeSets = Array.isArray(result) ? result : [result]\n for (const route of routeSets) {\n if (!route.controller) {\n throw new Error(\n `@forinda/kickjs/web: module route at '${route.path}' has no controller. ` +\n 'Express-style `router` mounts are not supported on the web entry.',\n )\n }\n const version = route.version ?? defaultVersion\n // `prefix: false` mounts at the root — parity with Application.\n const mountPath = buildMountPath(\n route.prefix === false ? '' : apiPrefix,\n version,\n route.path,\n )\n for (const entry of buildRouteTable(route.controller, { mountFlags: route.flags })) {\n const url = joinPath(mountPath, entry.path)\n // Per-handler owner so intra-controller duplicates name both methods.\n const owner = `${route.controller.name ?? 'controller'}.${String(entry.meta.handlerName ?? '?')}`\n assertRouteUnique(seenRoutes, entry.method, url, owner)\n mounted.push({ method: entry.method, path: url })\n if (globalMiddleware.length > 0) {\n entry.middlewares = [...globalMiddleware, ...entry.middlewares]\n }\n entry.validationError = options.validationError\n entry.urls = routeUrls\n routeUrls.add(owner, url)\n const run = compileWebRoute(entry, undefined, { bodyLimit })\n const handler = (event: H3EventLike) =>\n run({\n request: event.req,\n url: event.url,\n params: event.context.params ?? {},\n })\n app.on(entry.method, url, handler)\n if (entry.method === 'GET') getUrls.push({ url, handler })\n }\n }\n } finally {\n _setExternalContributorSources([])\n }\n }\n\n // HEAD answers every GET route, as on the node engines.\n for (const { url, handler } of getUrls) {\n app.on('HEAD', url, (event: H3EventLike) => headFromGet(handler(event) as Promise<Response>))\n }\n\n // Anything no route answered: the same 404 / 405 problem details as the\n // node engines, instead of h3's own 404 body.\n const notFound = notFoundHandler(mounted)\n app.all('/**', (event: H3EventLike) => {\n const driver = new WebResponseDriver(event.req.signal)\n notFound(new WebRequestShim(event.req, event.url), driver, () => {})\n return driver.ready\n })\n\n return {\n fetch: async (request: Request, platform?: PlatformContext) => {\n const response = await app.fetch(request)\n forwardBackgroundWork(platform)\n return response\n },\n h3: app,\n }\n}\n\n/**\n * Cloudflare Workers convenience: lazily build the app on the first request\n * so the Workers `env` binding can seed config before any module resolves.\n *\n * The Workers execution context (third argument) is forwarded, so work\n * handed to `ctx.waitUntil()` keeps running after the response.\n *\n * `scheduled` runs the `@Cron` jobs whose expression equals the trigger's\n * `event.cron` — list the same expressions under `[triggers] crons` in\n * wrangler.toml.\n *\n * `queue` consumes Cloudflare Queues: each message goes to the `@Job` class\n * for the batch's queue via `runJob`, and is acked when its handler\n * succeeds or retried when it throws. A message body of `{ name, data }`\n * picks the `@Process(name)` method; any other body goes to the queue's\n * catch-all `@Process()` as `data`.\n *\n * ```ts\n * export default createFetchHandler((env) => ({ h3, modules, env }))\n * ```\n */\nexport function createFetchHandler(\n build: (env: Record<string, string | undefined>) => CreateWebAppOptions,\n): {\n fetch: (\n request: Request,\n env?: Record<string, string | undefined>,\n ctx?: PlatformContext,\n ) => Promise<Response>\n scheduled: (\n event: { cron: string },\n env?: Record<string, string | undefined>,\n ctx?: PlatformContext,\n ) => Promise<void>\n queue: (\n batch: QueueBatch,\n env?: Record<string, string | undefined>,\n ctx?: PlatformContext,\n ) => Promise<void>\n} {\n let app: WebApp | undefined\n return {\n fetch: (request, env = {}, ctx) => {\n app ??= createWebApp(build(env))\n return app.fetch(request, ctx)\n },\n scheduled: async (event, env = {}, ctx) => {\n app ??= createWebApp(build(env))\n const run = runCronJobs(Container.getInstance(), { expression: event.cron }, 'workers').then(\n () => {},\n )\n ctx?.waitUntil?.(run)\n await run\n },\n queue: async (batch, env = {}) => {\n app ??= createWebApp(build(env))\n const container = Container.getInstance()\n await Promise.all(\n batch.messages.map(async (message) => {\n const body = message.body as { name?: unknown; data?: unknown } | null\n const named = body !== null && typeof body === 'object' && typeof body.name === 'string'\n try {\n await runJob(container, batch.queue, {\n name: named ? (body!.name as string) : '',\n data: named ? body!.data : message.body,\n id: message.id,\n })\n message.ack()\n } catch {\n // Reported by runJob; Cloudflare redelivers per the queue's retry settings.\n message.retry()\n }\n }),\n )\n },\n }\n}\n\n/** The part of a Cloudflare Queues `MessageBatch` the consumer uses. */\nexport interface QueueBatch {\n readonly queue: string\n readonly messages: ReadonlyArray<{\n readonly id: string\n readonly body: unknown\n ack(): void\n retry(): void\n }>\n}\n\n/** Join a mount prefix and a route path into one URL, collapsing slashes. */\nfunction joinPath(mountPath: string, path: string): string {\n const a = mountPath.endsWith('/') ? mountPath.slice(0, -1) : mountPath\n if (path === '/' || path === '') return a === '' ? '/' : a\n const b = path.startsWith('/') ? path : `/${path}`\n return `${a}${b}`\n}\n"],"mappings":";;;;;;;;;;omCAwJA,SAAgB,aAAa,QAAsC,CACjE,IAAM,MAAQ,QAAQ,GACtB,GAAI,OAAO,OAAO,IAAO,WACvB,MAAU,MACR,0KAEF,EAGF,IAAM,UAAY,UAAU,YAAY,EAGlC,UAAY,IAAI,UAItB,GAHA,UAAU,iBAAiB,WAAY,SAAS,EAG5C,QAAQ,IAAK,CACf,IAAM,IAAM,QAAQ,IACpB,UAAU,eAAgB,KAAgB,IAAI,IAAI,CACpD,CAGA,UAAU,4BAA8B,aAAa,SAAS,GAAK,IAAI,EAIvE,IAAM,SAAW,IAAI,sBACrB,IAAK,IAAM,KAAK,QAAQ,QAAS,SAAS,MAAM,CAAC,EACjD,IAAM,QAAU,SAAS,QAAQ,IAAK,OACpC,OAAO,OAAU,WAAa,IAAK,MAA8B,KACnE,EAGM,YAAe,QAAQ,MAC1B,OAAO,QAAY,IAAc,QAAQ,IAAM,CAAC,GACnD,IAAK,GAAM,CAAC,QAAS,SAAU,aAC7B,CAAC,GAAI,QAAQ,UAAY,CAAC,EAAI,GAAG,QAAQ,QAAS,KAAQ,IAAI,WAAW,GAAK,CAAC,CAAC,CAAC,EACjF,WACF,EACE,UAAU,iBAAiB,QAAS,KAAK,EAE3C,IAAK,IAAM,OAAO,QAAS,IAAI,WAAW,SAAS,EACnD,UAAU,UAAU,EAEpB,IAAM,IAAM,IAAI,MAAM,GAChB,QAA4E,CAAC,EAC7E,UAAY,QAAQ,WAAa,OACjC,eAAiB,QAAQ,gBAAkB,EAC3C,iBAAmB,QAAQ,aAAe,CAAC,EAC3C,UAAY,cAAc,QAAQ,WAAA,KAA+B,EAEjE,eAAwC,QAAQ,cAAgB,CAAC,EAAA,CAAG,IACvE,eAAuC,CACtC,OAAQ,SACM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AyB,OAAO,MAAS,YAAjC,MAA6C,OAAO,KAAK,MAAS,SAChF,GAAI,CACF,MAAM,OAAO,UAAW,MAAM,MAAO,CACnC,KAAM,MAAS,KAAM,KAAkB,GACvC,KAAM,MAAQ,KAAM,KAAO,QAAQ,KACnC,GAAI,QAAQ,EACd,CAAC,EACD,QAAQ,IAAI,CACd,MAAQ,CAEN,QAAQ,MAAM,CAChB,CACF,CAAC,CACH,CACF,CACF,CACF,CAcA,SAAS,SAAS,UAAmB,KAAsB,CACzD,IAAM,EAAI,UAAU,SAAS,GAAG,EAAI,UAAU,MAAM,EAAG,EAAE,EAAI,UAG7D,OAFI,OAAS,KAAO,OAAS,GAAW,IAAM,GAAK,IAAM,EAElD,GAAG,IADA,KAAK,WAAW,GAAG,EAAI,KAAO,IAAI,QAE9C"}
|
|
1
|
+
{"version":3,"file":"web.mjs","names":[],"sources":["../src/web.ts"],"sourcesContent":["// `@forinda/kickjs/web` — the web-standard fetch entry for edge runtimes\n// (Cloudflare Workers), Bun, and Deno.\n//\n// PURITY CONTRACT: this entry's import graph must stay free of node-only\n// runtime imports — no `node:http`, `node:cluster`, `node:fs`, `node:module`,\n// no `express`, no `Application`/`bootstrap`. The single sanctioned node API\n// is `node:async_hooks` (AsyncLocalStorage — available on Workers with\n// `nodejs_compat`, Deno, and Bun). Enforced by the bundle-graph purity test.\n//\n// ```ts\n// // Cloudflare Workers (wrangler.toml: compatibility_flags = [\"nodejs_compat\"])\n// import { createWebApp } from '@forinda/kickjs/web'\n// import * as h3 from 'h3'\n// import { modules } from './modules'\n//\n// const app = createWebApp({ h3, modules })\n// export default { fetch: (req: Request) => app.fetch(req) }\n//\n// // Bun\n// Bun.serve({ fetch: (req) => app.fetch(req) })\n// ```\n\nimport { Container } from './core/container'\nimport { MutableModuleRegistry } from './core/module-registry'\nimport type { AppModule, AppModuleClass, AppModuleEntry } from './core/app-module'\nimport type { ContributorRegistrations } from './core/context-decorator'\nimport type { MiddlewareHandler } from './core/decorators'\nimport type { SourcedRegistration } from './core/contributor-pipeline'\nimport {\n _setExternalContributorSources,\n assertRouteUnique,\n buildRouteTable,\n} from './http/router-builder'\nimport { requestStore } from './http/request-store'\nimport { forwardBackgroundWork, type PlatformContext } from './http/background'\nimport { runCronJobs } from './core/cron'\nimport { runJob } from './core/jobs'\nimport { compileWebRoute, headFromGet } from './http/web/handler'\nimport { ROUTE_URLS, RouteUrls } from './http/url-for'\nimport { loadSettings, type SettingsDeclaration } from './config/settings'\nimport { DEFAULT_BODY_LIMIT, parseByteSize } from './http/body-policy'\nimport { WebRequestShim, WebResponseDriver } from './http/web/driver'\nimport { notFoundHandler, type MountedRoute } from './http/middleware/error-handler'\nimport type { ValidationErrorFactory } from './http/middleware/validate'\nimport { buildMountPath } from './core/path'\nimport { moduleName } from './core/define-module'\n\nexport { WebRequestShim, WebResponseDriver } from './http/web/driver'\nexport { compileWebRoute } from './http/web/handler'\n// Return-value handler helpers — edge consumers can't import the main barrel.\nexport {\n reply,\n isReply,\n type Reply,\n type ReplyHeaders,\n type ReplyOptions,\n type InferHandlerResponse,\n} from './http/reply'\nexport type { SseHandler } from './http/context'\nexport { waitUntil, type PlatformContext } from './http/background'\nexport { runCronJobs, type CronRun } from './core/cron'\nexport { matchesBearer } from './core/web-crypto'\nexport {\n runJob,\n registerJobContext,\n stampJobContext,\n JOB_CONTEXT_FIELD,\n type JobLike,\n type JobContextCarrier,\n} from './core/jobs'\n// Edge-safe stores + ctx-style rate limiter (zero runtime imports).\nexport {\n KvRateLimitStore,\n KvSessionStore,\n type KvLike,\n type KvRateLimitStoreOptions,\n type KvSessionStoreOptions,\n} from './http/middleware/kv-stores'\nexport { rateLimitGuard, type RateLimitGuardOptions } from './http/middleware/rate-limit-guard'\n\n// Minimal structural surface of h3 v2 used here (kept local so this entry\n// never imports the node-coupled h3 runtime module).\ninterface H3AppLike {\n on(method: string, path: string, handler: (event: H3EventLike) => unknown): unknown\n all(path: string, handler: (event: H3EventLike) => unknown): unknown\n fetch(request: Request): Promise<Response>\n}\ninterface H3EventLike {\n req: Request\n url: URL\n context: { params?: Record<string, string> }\n}\n\nexport interface CreateWebAppOptions {\n /**\n * The h3 v2 module, statically imported by the caller:\n * `import * as h3 from 'h3'`. Passed in (rather than loaded here) because\n * edge bundlers have no `createRequire`, and a static `import 'h3'` inside\n * this entry would force the peer on every consumer of the subpath.\n */\n h3: unknown\n /** App modules — same shapes `bootstrap({ modules })` accepts. */\n modules: AppModuleEntry[]\n /** Route prefix (default '/api') — parity with bootstrap. */\n apiPrefix?: string\n /**\n * Default route version (default 1) — parity with bootstrap. `false` opts\n * out of URL versioning; a module's own `version` still overrides it.\n */\n defaultVersion?: number | false\n /** Global Context Contributors — parity with `bootstrap({ contributors })`. */\n contributors?: ContributorRegistrations\n /**\n * Env values for ConfigService/@Value resolution. On Workers, pass the\n * `env` binding from the fetch handler (see `createFetchHandler`); on\n * Bun/Deno, ambient `process.env` already works and this can be omitted.\n */\n env?: Record<string, string | undefined>\n /**\n * Global `(ctx, next)` middlewares, run before route middlewares on every\n * route — the web-entry counterpart of `bootstrap({ middlewares })`. Only\n * ctx-style handlers are accepted (no connect/express middleware here).\n */\n middlewares?: MiddlewareHandler[]\n /**\n * Largest request body parsed, as bytes or `'1mb'`-style (default `'1mb'`)\n * — parity with `bootstrap({ jsonLimit })`. A larger body answers 413.\n */\n jsonLimit?: string | number\n /** App-wide settings sections — parity with `bootstrap({ settings })`. */\n settings?: SettingsDeclaration[]\n /** What a failed route validation throws — parity with `bootstrap({ validationError })`. */\n validationError?: ValidationErrorFactory\n}\n\nexport interface WebApp {\n /**\n * Web-standard entry: `Request` in, `Response` out. Pass the platform\n * context (Workers `ctx`, Netlify `context`) so work handed to\n * `ctx.waitUntil()` finishes after the response.\n */\n fetch: (request: Request, platform?: PlatformContext) => Promise<Response>\n /** The underlying h3 v2 app, for advanced composition. */\n h3: unknown\n}\n\n/**\n * Build a KickJS app as a web-standard fetch handler — no node http server,\n * no Application/bootstrap. Module registration, DI, and the contributor\n * pipeline behave exactly like `bootstrap()`; routes are compiled once here\n * and served through h3 v2's router.\n */\nexport function createWebApp(options: CreateWebAppOptions): WebApp {\n const h3mod = options.h3 as { H3?: new () => H3AppLike }\n if (typeof h3mod?.H3 !== 'function') {\n throw new Error(\n '@forinda/kickjs/web: pass the h3 v2 module — `createWebApp({ h3: await import(\"h3\"), ... })`. ' +\n \"The installed h3 must be v2 (npm dist-tag 'latest'); v1 has no H3 class.\",\n )\n }\n\n const container = Container.getInstance()\n // Route names for ctx.urlFor() / the ROUTE_URLS token — bound before modules\n // register so their services can inject it.\n const routeUrls = new RouteUrls()\n container.registerInstance(ROUTE_URLS, routeUrls)\n // Wire ConfigService/@Value env resolution when the platform has no\n // ambient process.env (Workers). Latest-wins like loadEnv().\n if (options.env) {\n const env = options.env\n Container.setEnvResolver((key: string) => env[key])\n }\n\n // Request-scope provider — same wiring Application.setup() performs.\n Container.setRequestStoreProvider(() => requestStore.getStore() ?? null)\n\n // Module mounting — mirrors Application.setup() steps 1:1 for the module\n // path (plugins/adapters are out of scope for the edge entry at launch).\n const registry = new MutableModuleRegistry()\n for (const m of options.modules) registry.mount(m)\n const modules = registry.entries.map((entry) =>\n typeof entry === 'function' ? new (entry as AppModuleClass)() : (entry as AppModule),\n )\n // Declared settings sections — app-wide and mounted modules' — from the\n // platform env (Workers bindings) when given, bound before modules register.\n const settingsEnv = (options.env ??\n (typeof process !== 'undefined' ? process.env : {})) as NodeJS.ProcessEnv\n for (const [section, value] of loadSettings(\n [...(options.settings ?? []), ...modules.flatMap((mod) => mod.settings?.() ?? [])],\n settingsEnv,\n )) {\n container.registerInstance(section, value)\n }\n for (const mod of modules) mod.register?.(container)\n container.bootstrap()\n\n const app = new h3mod.H3()\n const getUrls: Array<{ url: string; handler: (event: H3EventLike) => unknown }> = []\n const apiPrefix = options.apiPrefix ?? '/api'\n const defaultVersion = options.defaultVersion ?? 1\n const globalMiddleware = options.middlewares ?? []\n const bodyLimit = parseByteSize(options.jsonLimit ?? DEFAULT_BODY_LIMIT)\n\n const globalSources: SourcedRegistration[] = (options.contributors ?? []).map(\n (registration): SourcedRegistration => ({\n source: 'global',\n registration: registration as SourcedRegistration['registration'],\n label: 'createWebApp',\n }),\n )\n\n // Duplicate-route guard (KICK006) — same boot-time check as the node path.\n const seenRoutes = new Map<string, string>()\n // For the catch-all: a known path with the wrong verb is a 405, not a 404.\n const mounted: MountedRoute[] = []\n\n for (const mod of modules) {\n const moduleLabel = moduleName(mod)\n const moduleSources: SourcedRegistration[] = (mod.contributors?.() ?? []).map(\n (registration): SourcedRegistration => ({\n source: 'module',\n registration,\n label: moduleLabel,\n }),\n )\n\n _setExternalContributorSources([...moduleSources, ...globalSources])\n try {\n const result = mod.routes()\n if (!result) continue\n const routeSets = Array.isArray(result) ? result : [result]\n for (const route of routeSets) {\n if (!route.controller) {\n throw new Error(\n `@forinda/kickjs/web: module route at '${route.path}' has no controller. ` +\n 'Express-style `router` mounts are not supported on the web entry.',\n )\n }\n const version = route.version ?? defaultVersion\n // `prefix: false` mounts at the root — parity with Application.\n const mountPath = buildMountPath(\n route.prefix === false ? '' : apiPrefix,\n version,\n route.path,\n )\n for (const entry of buildRouteTable(route.controller, { mountFlags: route.flags })) {\n const url = joinPath(mountPath, entry.path)\n // Per-handler owner so intra-controller duplicates name both methods.\n const owner = `${route.controller.name ?? 'controller'}.${String(entry.meta.handlerName ?? '?')}`\n assertRouteUnique(seenRoutes, entry.method, url, owner)\n mounted.push({ method: entry.method, path: url })\n if (globalMiddleware.length > 0) {\n entry.middlewares = [...globalMiddleware, ...entry.middlewares]\n }\n entry.validationError = options.validationError\n entry.urls = routeUrls\n routeUrls.add(owner, url)\n const run = compileWebRoute(entry, undefined, { bodyLimit })\n const handler = (event: H3EventLike) =>\n run({\n request: event.req,\n url: event.url,\n params: event.context.params ?? {},\n })\n app.on(entry.method, url, handler)\n if (entry.method === 'GET') getUrls.push({ url, handler })\n }\n }\n } finally {\n _setExternalContributorSources([])\n }\n }\n\n // HEAD answers every GET route, as on the node engines.\n for (const { url, handler } of getUrls) {\n app.on('HEAD', url, (event: H3EventLike) => headFromGet(handler(event) as Promise<Response>))\n }\n\n // Anything no route answered: the same 404 / 405 problem details as the\n // node engines, instead of h3's own 404 body.\n const notFound = notFoundHandler(mounted)\n app.all('/**', (event: H3EventLike) => {\n const driver = new WebResponseDriver(event.req.signal)\n notFound(new WebRequestShim(event.req, event.url), driver, () => {})\n return driver.ready\n })\n\n return {\n fetch: async (request: Request, platform?: PlatformContext) => {\n const response = await app.fetch(request)\n forwardBackgroundWork(platform)\n return response\n },\n h3: app,\n }\n}\n\n/**\n * Cloudflare Workers convenience: lazily build the app on the first request\n * so the Workers `env` binding can seed config before any module resolves.\n *\n * The Workers execution context (third argument) is forwarded, so work\n * handed to `ctx.waitUntil()` keeps running after the response.\n *\n * `scheduled` runs the `@Cron` jobs whose expression equals the trigger's\n * `event.cron` — list the same expressions under `[triggers] crons` in\n * wrangler.toml.\n *\n * `queue` consumes Cloudflare Queues: each message goes to the `@Job` class\n * for the batch's queue via `runJob`, and is acked when its handler\n * succeeds or retried when it throws. A message body of `{ name, data }`\n * picks the `@Process(name)` method; any other body goes to the queue's\n * catch-all `@Process()` as `data`.\n *\n * ```ts\n * export default createFetchHandler((env) => ({ h3, modules, env }))\n * ```\n */\nexport function createFetchHandler(\n build: (env: Record<string, string | undefined>) => CreateWebAppOptions,\n): {\n fetch: (\n request: Request,\n env?: Record<string, string | undefined>,\n ctx?: PlatformContext,\n ) => Promise<Response>\n scheduled: (\n event: { cron: string },\n env?: Record<string, string | undefined>,\n ctx?: PlatformContext,\n ) => Promise<void>\n queue: (\n batch: QueueBatch,\n env?: Record<string, string | undefined>,\n ctx?: PlatformContext,\n ) => Promise<void>\n} {\n let app: WebApp | undefined\n return {\n fetch: (request, env = {}, ctx) => {\n app ??= createWebApp(build(env))\n return app.fetch(request, ctx)\n },\n scheduled: async (event, env = {}, ctx) => {\n app ??= createWebApp(build(env))\n const run = runCronJobs(Container.getInstance(), { expression: event.cron }, 'workers').then(\n () => {},\n )\n ctx?.waitUntil?.(run)\n await run\n },\n queue: async (batch, env = {}) => {\n app ??= createWebApp(build(env))\n const container = Container.getInstance()\n await Promise.all(\n batch.messages.map(async (message) => {\n const body = message.body as { name?: unknown; data?: unknown } | null\n const named = body !== null && typeof body === 'object' && typeof body.name === 'string'\n try {\n await runJob(container, batch.queue, {\n name: named ? (body!.name as string) : '',\n data: named ? body!.data : message.body,\n id: message.id,\n })\n message.ack()\n } catch {\n // Reported by runJob; Cloudflare redelivers per the queue's retry settings.\n message.retry()\n }\n }),\n )\n },\n }\n}\n\n/** The part of a Cloudflare Queues `MessageBatch` the consumer uses. */\nexport interface QueueBatch {\n readonly queue: string\n readonly messages: ReadonlyArray<{\n readonly id: string\n readonly body: unknown\n ack(): void\n retry(): void\n }>\n}\n\n/** Join a mount prefix and a route path into one URL, collapsing slashes. */\nfunction joinPath(mountPath: string, path: string): string {\n const a = mountPath.endsWith('/') ? mountPath.slice(0, -1) : mountPath\n if (path === '/' || path === '') return a === '' ? '/' : a\n const b = path.startsWith('/') ? path : `/${path}`\n return `${a}${b}`\n}\n"],"mappings":";;;;;;;;;;A,omCAwJA,SAAgB,aAAa,QAAsC,CACjE,IAAM,MAAQ,QAAQ,GACtB,GAAI,OAAO,OAAO,IAAO,WACvB,MAAU,MACR,0KAEF,EAGF,IAAM,UAAY,UAAU,YAAY,EAGlC,UAAY,IAAI,UAItB,GAHA,UAAU,iBAAiB,WAAY,SAAS,EAG5C,QAAQ,IAAK,CACf,IAAM,IAAM,QAAQ,IACpB,UAAU,eAAgB,KAAgB,IAAI,IAAI,CACpD,CAGA,UAAU,4BAA8B,aAAa,SAAS,GAAK,IAAI,EAIvE,IAAM,SAAW,IAAI,sBACrB,IAAK,IAAM,KAAK,QAAQ,QAAS,SAAS,MAAM,CAAC,EACjD,IAAM,QAAU,SAAS,QAAQ,IAAK,OACpC,OAAO,OAAU,WAAa,IAAK,MAA8B,KACnE,EA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type-safe backend framework, powered by Vite. Built for developer experience, pluggable as you need — runs on Express, Fastify or h3.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"kickjs",
|
|
@@ -134,7 +134,7 @@
|
|
|
134
134
|
"peerDependencies": {
|
|
135
135
|
"@fastify/middie": "^9.0.0",
|
|
136
136
|
"@fastify/multipart": "^10.1.6",
|
|
137
|
-
"croner": "^
|
|
137
|
+
"croner": "^11.0.0",
|
|
138
138
|
"dotenv": "^17.0.0",
|
|
139
139
|
"express": "^5.1.0",
|
|
140
140
|
"fastify": "^5.0.0",
|
|
@@ -182,11 +182,11 @@
|
|
|
182
182
|
"@types/compression": "1.8.1",
|
|
183
183
|
"@types/express": "^5.0.6",
|
|
184
184
|
"@types/multer": "^2.3.0",
|
|
185
|
-
"@types/node": "^26.6.
|
|
185
|
+
"@types/node": "^26.6.6",
|
|
186
186
|
"@types/serve-static": "^2.2.0",
|
|
187
187
|
"@valibot/to-json-schema": "1.8.0",
|
|
188
188
|
"compression": "1.8.2",
|
|
189
|
-
"croner": "^
|
|
189
|
+
"croner": "^11.0.0",
|
|
190
190
|
"fastify": "^5.12.7",
|
|
191
191
|
"h3": "2.0.8",
|
|
192
192
|
"multer": "^2.5.0",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"adapter-DL9JPcvC.d.mts","names":["Container","Container","_0","NextFunction","Request","RequestHandler","ErrorRequestHandler","Container"],"sources":["../src/core/adapter-conditions.ts","../src/core/failure-analysis.ts","../src/core/observers.ts","../src/core/introspect.ts","../src/core/augmentation.ts","../src/core/module-registry.ts","../src/core/plugin.ts","../src/core/define-plugin.ts","../src/core/define-module.ts","../src/core/define-modules.ts","../src/core/contributor-pipeline.ts","../src/core/contributor-runner.ts","../src/core/define-adapter.ts","../src/http/view-renderer.ts","../src/http/url-for.ts","../src/http/conditional.ts","../src/http/middleware/upload-config.ts","../src/http/context.ts","../src/http/runtime.ts","../src/core/adapter.ts"],"mappings":";;;;;;;;;;;;;;;;;;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viq5.d.mts","names":["Request","Response","NextFunction"],"sources":["../src/http/middleware/allowed-hosts.ts"],"mappings":";;;UASiB;;;;;;;EAOf;;;;;;;;;;;EAWA;;;;;;;EAOA;;;;;;;;;;;;;;iBAsDc,aAAa,oBAAoB,uBAAmB,KASrDA,gBAAO,KAAOC,iBAAQ,MAAQC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"app-module-Dk2Wenqx.d.mts","names":[],"sources":["../src/core/execution-context.ts","../src/core/context-decorator.ts","../src/core/app-module.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UA8CiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAgCA;;;;;;;;;;;;;;;;;;;;;KAsBZ,wBAAwB,oBAAoB;KACrC,kBAAkB,4CAA4C;;KAG9D,UAAU,kBAAkB,sBAAsB,gBAAgB,cAC1E,YAAY,KACZ;;;;;;;;;UAUa,iBAAiB,cAAc,iBAAiB;;;;;;;;;EAS/D,IAAI,UAAU,gBAAgB,KAAK,IAAI,UAAU;;;;;;;;;;;;;;EAcjD,QAAQ,UAAU,OAAO,KAAK,IAAI,QAAQ,UAAU;;EAEpD,IAAI,UAAU,gBAAgB,KAAK,GAAG,OAAO,UAAU;;WAE9C;;;;;;;;;;;;KCtGC,WAAW,0BAA0B;;;;;;;;KASrC,aAAa,UAAU,eAAe,gBAC/C,WAAW,IAAI,EAAE,WAAW,qBAAqB,KAC9C,IACA,EAAE,WAAW,kBAAkB,KAC7B;;;;KAOH,kBAAkB,QAEpB,WAAW,iBAAiB,KAAK,GAAG,aAAa,WAC5C;;;;;;;;;;;KAYI,iBAAiB,GAAG,2BAA2B,YAEvD,QAAQ,kBAAkB,UAAU;;;;;;;;;KAU5B,eAAe,GAAG,OAAO,iBAAiB,GAAG,uBACrD,QAAQ,KACR,QAAQ,KAAK,KAAK,GAAG,iBAAiB,GAAG,YAAY;;;;;;;;;;;;;;UAexC,qB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AKjB,sBAAsB;;EAEtB,UAAU,eAAe;;;;;;;;;;;;;;;KAgBf,2BAA2B;;;;;;;;;;;;;;;;;;;;;;;UAwBtB;GACd,iBAAiB;WACT;aAAuB;aAAuB;;;;;;;;;;;;KAY7C,iBAAiB,iBAAiB,YAAY"}
|
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @forinda/kickjs v10.14.0
|
|
3
|
-
*
|
|
4
|
-
* Copyright (c) Felix Orinda
|
|
5
|
-
*
|
|
6
|
-
* This source code is licensed under the MIT license found in the
|
|
7
|
-
* LICENSE file in the root directory of this source tree.
|
|
8
|
-
*
|
|
9
|
-
* @license MIT
|
|
10
|
-
*/
|
|
11
|
-
import{a as tlsCredentialsError,i as moduleRouteMissingControllerError,n as http2RequiresTlsError,r as http2UnsupportedRuntimeError}from"./di-hooks-DN_UC8Nc.mjs";import{METADATA}from"./core/interfaces.mjs";import{Logger,createLogger}from"./core/logger.mjs";import{Container,tokenName}from"./core/container.mjs";import{n as createToken}from"./token-i5RynFrd.mjs";import{t as getClassMeta}from"./metadata-DS4TBMoC.mjs";import{Controller,Get}from"./core/decorators.mjs";import{a as moduleName,i as defineModule,n as RouteUrls,r as MutableModuleRegistry,t as ROUTE_URLS}from"./url-for-CQNJYjRH.mjs";import{a as setObserverPublisher,i as reportResponse,n as releaseObservers,o as setObservers,r as reportError,t as hasResponseObservers}from"./observers-Dokycjj0.mjs";import{runCronJobs}from"./core/cron.mjs";import{i as runDisposables,n as drainDisposables,r as registerDisposable,t as disposeAll}from"./disposables-C4BLa-Pc.mjs";import{HttpException}from"./core/errors.mjs";import{buildMountPath,joinPaths}from"./core/path.mjs";import{computed,ref}from"./core/reactivity.mjs";import{t as ROUTE_SLOT}from"./route-flag-DRM2yEZT.mjs";import"./core-BziwPF77.mjs";import{n as assertRouteUnique,r as buildRouteTable,t as _setExternalContributorSources}from"./router-builder-iEHiFSZh.mjs";import{t as isProduction}from"./is-production-Cx4PGne9.mjs";import{r as offerRoutePolicy,t as RoutePolicyTable}from"./route-policy-T8RavXEx.mjs";import{t as matchesBearer}from"./web-crypto-hpIdycSO.mjs";import{o as parseByteSize}from"./body-policy-CaerQ_lu.mjs";import{requestId}from"./http/middleware/request-id.mjs";import{c as settleBackgroundWork,f as requestStore,s as pendingBackgroundWork}from"./view-renderer-BV2rwEUI.mjs";import{errorHandler,notFoundHandler}from"./http/middleware/error-handler.mjs";import{allowedHosts}from"./http/middleware/allowed-hosts.mjs";import{i as requestScopeMiddleware,r as isRequestScopeMiddleware}from"./request-scope-BmhPPGPk.mjs";import{a as loadSettings,i as isOptionalSettings,o as originsOf}from"./settings-hG4DH8hQ.mjs";import{i as describeEnvSchema,t as __decorate}from"./decorate-DgGmrJOP.mjs";import{a as reply}from"./reply-Dcm0NAr0.mjs";import{i as expressRuntime,o as settleExpressLoad,r as expressBodyParsers}from"./express-lazy-B8AFaCA-.mjs";import{createRequire}from"node:module";import{join}from"node:path";import http from"node:http";import https from"node:https";import http2 from"node:http2";import tls from"node:tls";import diagnostics from"node:diagnostics_channel";import{randomBytes}from"node:crypto";var DuplicateMountNameError=class extends Error{kind;mountName;constructor(kind,mountName){super(`Duplicate ${kind} name '${mountName}' — every ${kind} must declare a unique name`),this.name=`DuplicateMountNameError`,this.kind=kind,this.mountName=mountName}},MissingMountDepError=class extends Error{kind;missing;dependent;constructor(kind,missing,dependent){super(`Missing ${kind} dependency '${missing}' required by '${dependent}' — is the ${kind} installed and named correctly?`),this.name=`MissingMountDepError`,this.kind=kind,this.missing=missing,this.dependent=dependent}},MountCycleError=class extends Error{kind;cycle;constructor(kind,cycle){super(`Cycle in ${kind} dependsOn declarations: ${cycle.join(` → `)}`),this.name=`MountCycleError`,this.kind=kind,this.cycle=Object.freeze([...cycle])}};function mountSort(items,kind){let byName=/* @__PURE__ */ new Map;for(let item of items){if(byName.has(item.name))throw new DuplicateMountNameError(kind,item.name);byName.set(item.name,item)}let indegree=/* @__PURE__ */ new Map,dependents=/* @__PURE__ */ new Map;for(let item of items)indegree.set(item.name,item.dependsOn?.length??0);for(let item of items)for(let dep of item.dependsOn??[]){if(!byName.has(dep))throw new MissingMountDepError(kind,dep,item.name);let list=dependents.get(dep)??[];list.push(item),dependents.set(dep,list)}let queue=[];for(let item of items)indegree.get(item.name)===0&&queue.push(item);let sorted=[];for(;queue.length>0;){let node=queue.shift();sorted.push(node);for(let dependent of dependents.get(node.name)??[]){let next=(indegree.get(dependent.name)??0)-1;indegree.set(dependent.name,next),next===0&&queue.push(dependent)}}if(sorted.length!==items.length)throw new MountCycleError(kind,reconstructCycle(items.filter(it=>(indegree.get(it.name)??0)>0),byName));return sorted}function reconstructCycle(residual,byName){let residualNames=new Set(residual.map(r=>r.name)),start=residual[0].name,path=[start],seen=/* @__PURE__ */ new Set([start]),cursor=start;for(;;){let nextDep=byName.get(cursor).dependsOn?.find(d=>residualNames.has(d));if(nextDep===void 0)break;if(seen.has(nextDep)){let cycleStart=path.indexOf(nextDep);return[...path.slice(cycleStart),nextDep]}path.push(nextDep),seen.add(nextDep),cursor=nextDep}return path}const HANDLER_CHANNEL=`kickjs:handler`,ERROR_CHANNEL=`kickjs:error`,RESPONSE_CHANNEL=`kickjs:response`,handlerChannel=diagnostics.tracingChannel(HANDLER_CHANNEL),errorChannel=diagnostics.channel(ERROR_CHANNEL),responseChannel=diagnostics.channel(RESPONSE_CHANNEL);function installChannelPublisher(){setObserverPublisher({name:`diagnostics_channel`,onError(error,info){errorChannel.hasSubscribers&&errorChannel.publish({error,...info})},onResponse(info){responseChannel.hasSubscribers&&responseChannel.publish(info)}},()=>responseChannel.hasSubscribers)}function traceHandler(handler,meta){return ctx=>handlerChannel.hasSubscribers?handlerChannel.tracePromise(async()=>handler(ctx),{...meta,requestId:ctx.requestId,ctx}):handler(ctx)}const round=ms=>Math.round(ms*10)/10;var StartupTimeline=class{began=performance.now();last=this.began;steps=[];completedAt;mark(name){let now=performance.now();this.steps.push({name,ms:round(now-this.last)}),this.last=now}async time(name,run){let started=performance.now(),before=this.last;try{return await run()}finally{let now=performance.now();this.steps.push({name,ms:round(now-started)}),this.last=now-(started-before)}}complete(){this.completedAt??=performance.now()}snapshot(){let end=this.completedAt??performance.now();return{totalMs:round(end-this.began),steps:[...this.steps]}}slowest(count){return this.steps.toSorted((a,b)=>b.ms-a.ms).slice(0,count)}};function onEnv(name,value){return()=>{let actual=process.env[name];return value===void 0?actual?!0:`${name} is not set`:actual===value?!0:actual===void 0?`${name} is not set`:`${name} is not '${value}'`}}function onPackage(name){return()=>{let bases=[process.argv[1],join(process.cwd(),`package.json`)].filter(base=>typeof base==`string`&&base.length>0);for(let base of bases)try{return createRequire(base).resolve(name),!0}catch{}return`package '${name}' is not installed`}}function allOf(...conditions){return()=>{for(let condition of conditions){let result=condition();if(result!==!0)return result}return!0}}function evaluateCondition(condition,onError){try{let result=condition();return result===!0?!0:typeof result==`string`&&result.length>0?result:`its condition returned false`}catch(err){return onError?.(err),`its condition threw (see the server log)`}}function findCode(err,codes,depth=0){if(!err||typeof err!=`object`||depth>5)return;let e=err;if(typeof e.code==`string`&&codes.includes(e.code))return e;for(let inner of[e.cause,...Array.isArray(e.errors)?e.errors:[]]){let found=findCode(inner,codes,depth+1);if(found)return found}}function findMessage(err,pattern,depth=0){if(!err||typeof err!=`object`||depth>5)return!1;let e=err;return typeof e.message==`string`&&pattern.test(e.message)?!0:[e.cause,...Array.isArray(e.errors)?e.errors:[]].some(inner=>findMessage(inner,pattern,depth+1))}const CREDENTIALS_REJECTED=/password authentication failed|access denied for user|authentication failed|NOAUTH|WRONGPASS/i,target=e=>typeof e.address==`string`?`${e.address}${typeof e.port==`number`?`:${e.port}`:``}`:typeof e.hostname==`string`?e.hostname:`the service`;function builtInAdvice(err,where){let refused=findCode(err,[`ECONNREFUSED`]);if(refused)return{summary:`${where} could not connect to ${target(refused)}: connection refused`,cause:`Nothing is listening at that address — the service is down, not started yet, or the URL points at the wrong host or port.`,fix:`Start the service, or check the connection URL in your env (localhost inside a container is the container itself).`};let dns=findCode(err,[`ENOTFOUND`,`EAI_AGAIN`]);if(dns)return{summary:`${where} could not resolve the host ${target(dns)}`,cause:`The host name in the connection URL does not resolve from here.`,fix:`Check the host name in your env — a typo, or a name that only resolves inside another network (a compose service name used from the host).`};let timeout=findCode(err,[`ETIMEDOUT`,`ECONNRESET`]);if(timeout)return{summary:`${where} lost the connection to ${target(timeout)} (${String(timeout.code)})`,cause:`The address answered slowly or not at all — a firewall, a security group, or the wrong network.`,fix:`Check that this machine is allowed to reach the service, and that TLS and port settings match it.`};if(findMessage(err,CREDENTIALS_REJECTED))return{summary:`${where} was refused: the credentials were not accepted`,cause:`The server rejected the user name or password.`,fix:`Check the user and password in your connection URL or env, and that the user exists on this server.`}}function formatAdvice(advice){return[advice.summary,...advice.cause?[``,` Cause: ${advice.cause}`]:[],``,` Fix: ${advice.fix}`].join(`
|
|
12
|
-
`)}const log$1=createLogger(`Checks`);function defineCheck(check){return check}var StartupCheckError=class extends Error{messages;constructor(messages){super(`Startup checks failed:\n${messages.map(m=>` ${m.id}: ${m.message}${m.fix?`\n fix: ${m.fix}`:``}`).join(`
|
|
13
|
-
`)}`),this.messages=messages,this.name=`StartupCheckError`}};const builtInChecks=[defineCheck({name:`allowed hosts`,deploy:!0,run:({options})=>{let configured=options.security?.allowedHosts,hosts=Array.isArray(configured)?configured:configured?.hosts;if(!(Array.isArray(hosts)&&hosts.length>0&&!hosts.includes(`*`)))return{id:`KICK-SEC-W001`,level:`warning`,message:"No allowed hosts in production (or `*`): any Host header is accepted, and absolute URLs built from it (reset links, redirects) can point anywhere.",fix:`bootstrap({ security: { allowedHosts: ['example.com'] } })`}}}),defineCheck({name:`trust proxy`,deploy:!0,run:({options})=>{if(options.trustProxy===!0)return{id:`KICK-SEC-W002`,level:`warning`,message:"`trustProxy: true` trusts every X-Forwarded-For hop, so a client that reaches the app directly can set its own IP (rate limits, logs, ctx.ip).",fix:"Trust the number of proxies in front of the app instead, e.g. `trustProxy: 1`."}}})];function runStartupChecks(checks,ctx,silenced=[]){let production=isProduction(),skip=new Set(silenced),found=[];for(let check of checks){if(check.deploy&&!production)continue;let result;try{result=check.run({...ctx,production})}catch(err){log$1.error(err,`Startup check '${check.name}' threw`);continue}for(let message of[result??[]].flat())skip.has(message.id)||found.push(message)}for(let message of found)message.level===`warning`&&log$1.warn(`${message.id}: ${message.message}${message.fix?` Fix: ${message.fix}`:``}`);let errors=found.filter(m=>m.level===`error`);if(errors.length>0)throw new StartupCheckError(errors);return found}function __decorateMetadata(k,v){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(k,v)}const HEALTH_PROBE=createToken(`kick/Health/probe`);function createHealthChecks(sources,options={}){let timeoutMs=options.timeoutMs??2e3,cached,runOne=async source=>{let name=source.name??`unknown`,started=Date.now(),timer,timedOut=new Promise(resolve=>{timer=setTimeout(()=>resolve({name,status:`down`,reason:`timeout`}),timeoutMs)});try{return await Promise.race([Promise.resolve().then(()=>source.onHealthCheck()).catch(()=>({name,status:`down`,reason:`error`})),timedOut])}finally{clearTimeout(timer);let ms=Date.now()-started;ms>=timeoutMs*.5&&options.onSlow?.(name,ms)}};return()=>{let now=Date.now();if(cached&&now-cached.at<1e3)return cached.result;let result=Promise.all(sources().filter(s=>s.onHealthCheck).map(runOne));return cached={at:now,result},result}}let HealthController=class{probe;constructor(probe){this.probe=probe}live(){return reply(200,{status:this.probe.isDraining()?`draining`:`ok`,uptime:process.uptime()})}async ready(){if(this.probe.isDraining())return reply(503,{status:`draining`,checks:[]});if(this.probe.isStarting?.())return reply(503,{status:`starting`,checks:[]});let checks=await this.probe.checks(),healthy=checks.every(c=>c.status===`up`);return reply(healthy?200:503,{status:healthy?`ready`:`degraded`,checks})}};__decorate([Get(`/live`),__decorateMetadata(`design:type`,Function),__decorateMetadata(`design:paramtypes`,[]),__decorateMetadata(`design:returntype`,void 0)],HealthController.prototype,`live`,null),__decorate([Get(`/ready`),__decorateMetadata(`design:type`,Function),__decorateMetadata(`design:paramtypes`,[]),__decorateMetadata(`design:returntype`,Promise)],HealthController.prototype,`ready`,null),HealthController=__decorate([Controller(),__decorateMetadata(`design:paramtypes`,[Object])],HealthController);const healthModule=defineModule({name:`HealthModule`,build:config=>({register(container){container.registerFactory(HealthController,()=>{let probe=container.resolve(HEALTH_PROBE);return new HealthController(probe)})},routes(){return{path:`/health`,controller:HealthController,version:!1,prefix:!1,flags:config.flags}}})}),HOP_BY_HOP_REQUEST=[`connection`,`keep-alive`,`proxy-connection`,`transfer-encoding`,`upgrade`,`te`,`trailer`,`host`,`content-length`],HOP_BY_HOP_RESPONSE=[`connection`,`keep-alive`,`proxy-connection`,`transfer-encoding`,`upgrade`,`trailer`,`content-encoding`,`content-length`],LOOPBACK_HOST=`x-kick-loopback-host`,LOOPBACK_SECRET=`x-kick-loopback-secret`;async function streamedBody(request){if(!request.body||request.method===`GET`||request.method===`HEAD`)return;let reader=request.body.getReader(),first=await reader.read();if(!first.done)return new ReadableStream({start(controller){controller.enqueue(first.value)},async pull(controller){let{done,value}=await reader.read();done?controller.close():controller.enqueue(value)},cancel(reason){return reader.cancel(reason)}})}function createLoopback(handle){let started,secret=randomBytes(24).toString(`hex`),server=()=>(started??=new Promise((resolve,reject)=>{let instance=http.createServer((req,res)=>{let host=req.headers[LOOPBACK_HOST];req.headers[LOOPBACK_SECRET]===secret&&typeof host==`string`&&(req.headers.host=host),delete req.headers[LOOPBACK_HOST],delete req.headers[LOOPBACK_SECRET],handle(req,res)});instance.once(`error`,reject),instance.listen(0,`127.0.0.1`,()=>{instance.unref(),resolve({origin:`http://127.0.0.1:${instance.address().port}`,server:instance})})}).catch(err=>{throw started=void 0,err}),started);return{async fetch(request){let{origin}=await server(),url=new URL(request.url),headers=new Headers(request.headers);for(let name of HOP_BY_HOP_REQUEST)headers.delete(name);headers.set(`x-forwarded-host`,url.host),headers.set(`x-forwarded-proto`,url.protocol.slice(0,-1)),headers.set(LOOPBACK_HOST,url.host),headers.set(LOOPBACK_SECRET,secret);let body=await streamedBody(request),upstream=await fetch(origin+url.pathname+url.search,{method:request.method,headers,body,...body?{duplex:`half`}:{},redirect:`manual`,signal:request.signal}),responseHeaders=new Headers(upstream.headers),named=responseHeaders.get(`connection`)?.split(`,`)??[];for(let name of[...HOP_BY_HOP_RESPONSE,...named])responseHeaders.delete(name.trim());return new Response(upstream.body,{status:upstream.status,statusText:upstream.statusText,headers:responseHeaders})},async close(){let running=await started?.catch(()=>void 0);if(started=void 0,!running)return;let closed=new Promise(resolve=>running.server.close(()=>resolve()));running.server.closeAllConnections(),await closed}}}const log=createLogger(`Application`);function assertUsableTls(options){let{key,cert,pfx,SNICallback,pskCallback}=options;if(!pfx&&!SNICallback&&!pskCallback){if(!key&&!cert)throw tlsCredentialsError(`no key/cert, pfx, SNICallback, or pskCallback`);if(!key)throw tlsCredentialsError(`cert is set but key is missing`);if(!cert)throw tlsCredentialsError(`key is set but cert is missing`)}try{tls.createSecureContext(options)}catch(err){throw tlsCredentialsError(err.message)}}function isModuleFactory(entry){return typeof entry==`function`&&`definition`in entry&&typeof entry.scoped==`function`}function isConfigurable(factory){return factory.definition?.defaults!=null}function toAppModule(entry){if(typeof entry!=`function`)return entry;if(isModuleFactory(entry)){if(isConfigurable(entry)){let name=entry.definition?.name||entry.name||`<anonymous>`;throw TypeError(`bootstrap: module \`${name}\` takes configuration, so it must be invoked.\n Write \`${name}()\` for its defaults, or \`${name}({ … })\` to configure it.\n Passing it bare would have silently selected the defaults.`)}return entry()}let name=entry.name||`<anonymous>`;if(!isConstructible(entry))throw TypeError(`bootstrap: module entry \`${name}\` is a function, but not a module class and not a defineModule() factory (no \`definition\`).\n A defineModule() module is passed as \`${name}\` or \`${name}()\`; a class must implement AppModule.`);let mod=new entry;if(typeof mod?.routes!=`function`)throw TypeError(`bootstrap: module entry \`${name}\` constructed, but the result does not implement AppModule — \`routes()\` is missing.\n A module class needs \`routes()\`; a defineModule() module is passed as \`${name}\` or \`${name}()\`.`);return mod}function isConstructible(fn){try{return Reflect.construct(String,[],fn),!0}catch{return!1}}const APPLICATION=createToken(`kick/Http/Application`);var Application=class{options;app;runtime;container;httpServer=null;managementApp=null;managementServer=null;wantsManagement=!1;handlerMode=!1;observers=[];http2Sessions=/* @__PURE__ */ new Set;loopback;timeline=new StartupTimeline;conditionReport=[];mountedRoutes=[];mountedRouteInfo=[];routeUrls=new RouteUrls;settingsPrefixes=/* @__PURE__ */ new Map;settingsProvided=/* @__PURE__ */ new Map;handlerFor;adapters;routePolicy=new RoutePolicyTable;plugins;_moduleContributors=[];_inFlightRequests=0;_status=ref(`idle`);status=computed(()=>this._status.value);_shutdown=null;_drainResolvers=[];constructor(options){this.options=options,this.runtime=options.runtime??expressRuntime(),this.container=Container.getInstance(),this.container.registerInstance(APPLICATION,this),this.plugins=mountSort(options.plugins??[],`plugin`);let allAdapters=[...this.plugins.flatMap(p=>p.adapters?.()??[]),...options.adapters??[]],anonAdapterCount=0,namedAdapters=allAdapters.map(adapter=>{if(!adapter.name){let ctorName=adapter.constructor?.name,fallback=ctorName&&ctorName!==`Object`?ctorName:`AnonymousAdapter#${anonAdapterCount++}`;return Object.assign(adapter,{name:fallback})}return adapter});this.adapters=mountSort(this.applyConditions(namedAdapters),`adapter`),this.observers=setObservers([...this.adapters,...this.plugins]),installChannelPublisher(),Container.setRequestStoreProvider(()=>requestStore.getStore()??null)}applyConditions(adapters){let seen=/* @__PURE__ */ new Set;for(let adapter of adapters){if(seen.has(adapter.name))throw new DuplicateMountNameError(`adapter`,adapter.name);seen.add(adapter.name)}let off=/* @__PURE__ */ new Map;for(let adapter of adapters){if(!adapter.when)continue;let result=evaluateCondition(adapter.when,err=>log.warn(`Adapter ${adapter.name}: its \`when\` condition threw — ${String(err)}`));result!==!0&&off.set(adapter.name,result)}let changed=off.size>0;for(;changed;){changed=!1;for(let adapter of adapters){if(off.has(adapter.name))continue;let missing=adapter.dependsOn?.find(dep=>off.has(dep));missing&&(off.set(adapter.name,`depends on ${missing}, which is off`),changed=!0)}}this.conditionReport=adapters.filter(a=>a.when||off.has(a.name)).map(a=>off.has(a.name)?{adapter:a.name,enabled:!1,reason:off.get(a.name)}:{adapter:a.name,enabled:!0});for(let outcome of this.conditionReport)outcome.enabled||log.debug(`Adapter ${outcome.adapter} is off: ${outcome.reason}`);return adapters.filter(a=>!off.has(a.name))}getConditionReport(){return this.conditionReport}get isDraining(){return this._status.value===`draining`||this._status.value===`stopped`}get inFlightRequests(){return this._inFlightRequests}getContainer(){return this.container}fetch(request){if(this.app===void 0)return Promise.reject(/* @__PURE__ */ Error(`kickjs: Application.fetch() before setup — await start() or startWithoutServer() first`));let runtimeApp=this.app;return typeof runtimeApp?.fetch==`function`?Promise.resolve(runtimeApp.fetch(request)):(this.loopback??=createLoopback((req,res)=>this.handle(req,res)),this.loopback.fetch(request))}createEngineApp(){return this.runtime.createApp({trustProxy:this.options.trustProxy,notFoundFallthrough:this.options.notFoundFallthrough,bodyLimit:parseByteSize(this.options.jsonLimit??`1mb`)})}handle(req,res,next){if(this.app===void 0)throw Error(`kickjs: Application.handle() before setup — await start() or startWithoutServer() first`);(!this.handlerFor||this.handlerFor.app!==this.app)&&(this.handlerFor={app:this.app,handler:this.runtime.nodeHandler(this.app)});let handler=this.handlerFor.handler;next?handler(req,res,next):handler(req,res)}adapterCtx(server,owner){let env=process.env.NODE_ENV??`production`,managementApp=this.managementApp;return{http:this.adapterHttp(void 0,owner),app:this.app,fetch:request=>this.fetch(request),container:this.container,server,...managementApp?{management:{http:this.adapterHttp(()=>managementApp,owner),server:this.managementServer??void 0}}:{},env,isProduction:isProduction()}}adapterHttp(target=()=>this.app,owner=`kick`){let record=(method,pattern,handler)=>{this.mountedRouteInfo.push({method,pattern,controller:owner,handler,contributors:[],source:`adapter`,port:target()===this.app?`app`:`management`})};return{route:(method,path,handler)=>{record(method,path,``);let entry={method,path,middlewares:[],contributorRunner:null,handler,meta:{}};this.runtime.mountRoutes(target(),[{mountPath:`/`,routes:[entry]}])},mount:(prefix,routes)=>{for(let entry of routes)record(entry.method,joinPaths(prefix,entry.path),String(entry.meta.handlerName??``));this.runtime.mountRoutes(target(),[{mountPath:prefix,routes}])},serveStatic:(prefix,dir)=>{record(`GET`,`${joinPaths(prefix,`/`).replace(/\/$/,``)}/*`,`static`),this.runtime.serveStatic(target(),prefix,dir)},use:(mw,opts)=>{this.runtime.useConnect(target(),mw,opts)}}}async callHook(hook,ctx,adapterName=`adapter`,hookName){if(!hook)return;let where=`${adapterName}.${hookName}`;try{await this.timeline.time(where,()=>hook(ctx))}catch(err){if(this.adviseOnFailure(err,where,adapterName),hookName!==`afterStart`)throw err;log.error(err,`${adapterName} afterStart hook failed`)}}adviseOnFailure(err,where,adapterName){let adapter=this.adapters.find(a=>a.name===adapterName),advice;try{advice=adapter?.analyzeFailure?.(err)}catch(analyzerErr){log.debug(`${adapterName}.analyzeFailure threw: ${String(analyzerErr)}`)}advice??=builtInAdvice(err,where),advice&&log.error(formatAdvice(advice))}getStartupTimeline(){return this.timeline.snapshot()}urlFor(name,...args){let[params,query]=args;return this.routeUrls.build(name,params,query)}collectModules(){let registry=new MutableModuleRegistry;for(let plugin of this.plugins){for(let m of plugin.modules?.()??[])registry.mount(m);plugin.setup?.(registry)}for(let m of this.options.modules)registry.mount(m);return this.options.setup?.(registry),registry}describeConfig(){let sections=[],seen=/* @__PURE__ */ new Map,add=(declaredBy,list)=>{for(let decl of list??[]){let section=`section`in decl?decl.section:decl,optional=isOptionalSettings(decl),listed=seen.get(section);if(listed){optional||delete listed.optional;continue}let entry={prefix:section.prefix,declaredBy,...section.description?{description:section.description}:{},...optional?{optional:!0}:{},vars:section.describe()};seen.set(section,entry),sections.push(entry)}};add(`app`,this.options.settings);for(let plugin of this.plugins)add(`plugin ${plugin.name}`,plugin.settings?.());for(let adapter of this.adapters)add(`adapter ${adapter.name}`,adapter.settings?.());for(let entry of this.collectModules().entries){let mod=toAppModule(entry);add(`module ${moduleName(mod)}`,mod.settings?.())}return{env:describeEnvSchema(),sections}}configOrigins(){return{env:originsOf(describeEnvSchema()),sections:Array.from(this.settingsPrefixes.values(),section=>({prefix:section.prefix,vars:this.settingsProvided.has(section)?section.envNames.map(name=>({name,origin:`provided`})):originsOf(section.describe())}))}}bindSettings(sections){for(let[section,value]of loadSettings(sections,process.env,this.settingsPrefixes,this.settingsProvided))this.container.registerInstance(section,value)}runChecks(){runStartupChecks([...builtInChecks,...this.options.checks??[]],{options:this.options,routes:this.mountedRoutes},this.options.silenceChecks),this.timeline.mark(`checks`)}reportStartup(){let{totalMs}=this.timeline.snapshot();if(totalMs<1e3)return;let slowest=this.timeline.slowest(3).map(step=>`${step.name} ${Math.round(step.ms)}ms`).join(`, `);log.info(`Startup took ${Math.round(totalMs)}ms — slowest: ${slowest}`)}async setup(){log.debug(`Bootstrapping application...`),await this.runtime.load?.(),await settleExpressLoad(),this.app??=this.createEngineApp(),this.wantsManagement&&(this.managementApp??=this.createEngineApp()),this.timeline=new StartupTimeline,this.mountedRouteInfo=[],this.routeUrls=new RouteUrls,this.container.registerInstance(ROUTE_URLS,this.routeUrls),this.container.registerInstance(APPLICATION,this),this.settingsPrefixes=/* @__PURE__ */ new Map,this.settingsProvided=/* @__PURE__ */ new Map,this.bindSettings([...this.options.settings??[],...this.plugins.flatMap(plugin=>plugin.settings?.()??[]),...this.adapters.flatMap(adapter=>adapter.settings?.()??[])]),this._moduleContributors=[];let adapterMw=this.collectAdapterMiddleware();this.app.__kickApp=this;let hostList=this.options.security?.allowedHosts;if(hostList){let hostOptions=Array.isArray(hostList)?{hosts:hostList}:hostList;this.runtime.useConnect(this.app,allowedHosts({...hostOptions,ignorePaths:[...hostOptions.ignorePaths??[],`/health/live`,`/health/ready`]}))}for(let adapter of this.adapters)await this.callHook(adapter.beforeMount?.bind(adapter),this.adapterCtx(void 0,adapter.name),adapter.name,`beforeMount`);this.handlerMode&&this.mountCronTrigger(),this.runtime.useConnect(this.app,this.requestTrackingMiddleware()),this.shouldAutoMountRequestScope()&&this.runtime.useConnect(this.app,requestScopeMiddleware()),this.managementApp&&this.options.contextStore!==`manual`&&this.runtime.useConnect(this.managementApp,requestScopeMiddleware()),this.mountMiddlewareList(adapterMw.beforeGlobal);for(let plugin of this.plugins)plugin.register?.(this.container);for(let plugin of this.plugins)try{let mw=plugin.middleware?.()??[];for(let handler of mw)this.runtime.useConnect(this.app,handler)}catch(err){log.error(err,`Plugin middleware failed: ${plugin.name??`unknown`}`)}let declaredHelmet=(this.options.middlewares??[]).some(entry=>typeof entry==`function`&&Symbol.for(`kick/http/helmet`)in entry);if(this.options.security?.helmet!==!1&&!declaredHelmet)try{let{helmet:helmetFn}=await import(`./http/middleware/helmet.mjs`);this.runtime.useConnect(this.app,helmetFn())}catch{}let userMiddlewares=this.options.middlewares;if(userMiddlewares)for(let entry of userMiddlewares)this.mountMiddlewareEntry(entry);else if(this.runtime.useConnect(this.app,requestId()),!this.runtime.capabilities.nativeBodyParsing){let limit=this.options.jsonLimit??`1mb`,parsers=this.runtime.bodyParsers?this.runtime.bodyParsers({limit}):await expressBodyParsers(limit);for(let parser of parsers)this.runtime.useConnect(this.app,parser)}this.mountMiddlewareList(adapterMw.afterGlobal),this.timeline.mark(`middleware`);let moduleRegistry=this.collectModules();this.options.health!==!1&&(this.container.registerInstance(HEALTH_PROBE,{isDraining:()=>this.isDraining,isStarting:()=>this._status.value===`starting`,checks:createHealthChecks(()=>this.adapters,{timeoutMs:typeof this.options.health==`object`?this.options.health.checkTimeout:void 0,onSlow:(name,ms)=>log.warn(`Health check '${name}' took ${ms}ms`)})}),moduleRegistry.mount(healthModule(this.options.health===!0?{}:this.options.health)));let modules=moduleRegistry.entries.map(toAppModule);this.bindSettings(modules.flatMap(mod=>mod.settings?.()??[]));for(let mod of modules)mod.register?.(this.container);this.container.bootstrap(),this.container.has(Logger)||this.container.registerInstance(Logger,new Logger),this.timeline.mark(`modules`),this.mountMiddlewareList(adapterMw.beforeRoutes);let apiPrefix=this.options.apiPrefix??`/api`,defaultVersion=this.options.defaultVersion??1,shouldLogRoutes=this.options.logRouteTable??this.options.logRoutesTable??!1,mountedRoutes=[],adapterSources=[];for(let adapter of this.adapters){let adapterContribs=adapter.contributors?.()??[],adapterLabel=adapter.name??adapter.constructor.name??`adapter`;for(let registration of adapterContribs)adapterSources.push({source:`adapter`,registration,label:adapterLabel})}for(let plugin of this.plugins){let pluginContribs=plugin.contributors?.()??[],pluginLabel=plugin.name??plugin.constructor?.name??`plugin`;for(let registration of pluginContribs)adapterSources.push({source:`adapter`,registration,label:pluginLabel})}let globalSources=(this.options.contributors??[]).map(registration=>({source:`global`,registration,label:`bootstrap`}));this._moduleContributors=[];let seenRoutes=/* @__PURE__ */ new Map,mountedPaths=[],managementPaths=[];this.mountedRoutes=mountedPaths;for(let mod of modules){let moduleLabel=moduleName(mod),moduleSources=(mod.contributors?.()??[]).map(registration=>({source:`module`,registration,label:moduleLabel}));for(let src of moduleSources)this._moduleContributors.push({registration:src.registration,label:moduleLabel});_setExternalContributorSources([...moduleSources,...adapterSources,...globalSources]);try{let result=mod.routes();if(!result)continue;let routeSets=Array.isArray(result)?result:[result];for(let route of routeSets){let version=route.version??defaultVersion,mountPath=buildMountPath(route.prefix===!1?``:apiPrefix,version,route.path);if(route.router)this.runtime.useConnect(this.app,route.router,{path:mountPath});else if(route.controller){let target=this.managementApp&&route.controller===HealthController?this.managementApp:this.app,routeTable=buildRouteTable(route.controller,{mountFlags:route.flags}),ctrl=route.controller.name??`controller`;for(let entry of routeTable){let owner=`${ctrl}.${String(entry.meta.handlerName??`?`)}`,fullPath=joinPaths(mountPath,entry.path);assertRouteUnique(seenRoutes,entry.method,fullPath,owner),(target===this.app?mountedPaths:managementPaths).push({method:entry.method,path:fullPath}),this.routeUrls.add(owner,fullPath),this.routePolicy.add(entry.method,fullPath,entry.meta.flags)}let traced=routeTable.map(entry=>{let pattern=joinPaths(mountPath,entry.path);return{...entry,handler:traceHandler(entry.handler,{method:entry.method,route:pattern,controller:route.controller?.name,handler:entry.meta.handlerName}),meta:{...entry.meta,pattern},validationError:this.options.validationError,urls:this.routeUrls}});this.runtime.mountRoutes(target,[{mountPath,routes:traced}]);for(let entry of traced)this.mountedRouteInfo.push({method:entry.method,pattern:entry.meta.pattern??entry.path,controller:route.controller.name,handler:String(entry.meta.handlerName??``),contributors:entry.meta.contributors??[],source:`module`,port:target===this.app?`app`:`management`})}else throw moduleRouteMissingControllerError(mountPath);let onManagement=!!this.managementApp&&route.controller===HealthController;if(route.controller&&!onManagement)for(let adapter of this.adapters)try{adapter.onRouteMount?.(route.controller,mountPath)}catch(err){log.error(err,`adapter.onRouteMount() failed for ${mountPath}`)}route.controller&&shouldLogRoutes&&mountedRoutes.push({controller:route.controller,mountPath,management:onManagement})}}finally{_setExternalContributorSources([])}}if(shouldLogRoutes&&mountedRoutes.length>0){let methodOrder=[`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`HEAD`,`OPTIONS`],methodRank=m=>{let i=methodOrder.indexOf(m);return i===-1?99:i},totalRoutes=0;log.info(`Routes:`);for(let{controller,mountPath,management}of mountedRoutes){let defs=getClassMeta(METADATA.ROUTES,controller,[]);if(defs.length===0)continue;let counts={};for(let def of defs){let m=def.method.toUpperCase();counts[m]=(counts[m]||0)+1}totalRoutes+=defs.length;let methods=Object.entries(counts).toSorted(([a],[b])=>methodRank(a)-methodRank(b)).map(([m,n])=>`${n} ${m}`).join(`, `),name=controller.name||`Controller`,port=management?` [management port]`:``;log.info(` ${name.padEnd(30)} ${mountPath.padEnd(25)} ${defs.length} routes (${methods})${port}`)}log.info(` Total: ${totalRoutes} routes`)}this.mountMiddlewareList(adapterMw.afterRoutes),this.timeline.mark(`routes`);for(let adapter of this.adapters)await this.callHook(adapter.beforeStart?.bind(adapter),this.adapterCtx(void 0,adapter.name),adapter.name,`beforeStart`);for(let entry of this.options.middlewares??[])offerRoutePolicy(typeof entry==`function`?entry:entry.handler,this.routePolicy);for(let adapter of this.adapters)for(let mw of adapter.middleware?.()??[])offerRoutePolicy(mw.handler,this.routePolicy);let builtInNotFound=notFoundHandler(mountedPaths),customNotFound=this.options.onNotFound;this.runtime.setNotFound(this.app,customNotFound?(req,res,next)=>customNotFound(req,res,err=>err===void 0?builtInNotFound(req,res,next):next(err)):builtInNotFound),this.runtime.setErrorHandler(this.app,observeErrors(this.options.onError??errorHandler())),this.managementApp&&(this.runtime.setNotFound(this.managementApp,notFoundHandler(managementPaths)),this.runtime.setErrorHandler(this.managementApp,observeErrors(errorHandler()))),this.timeline.mark(`error handlers`)}async registerOnly(){await this.setup()}async startWithoutServer(){await this.untilStartedOrStopped(()=>this.startWithoutServerSteps())}async untilStartedOrStopped(run){try{await run()}catch(err){throw this._status.value=`stopped`,err}}async startWithoutServerSteps(){this.handlerMode=!0,this._status.value=`starting`,await this.setup(),this.runChecks();let needServer=this.adapters.filter(adapter=>adapter.afterStart);needServer.length>0&&log.warn(`No HTTP server in handler mode, so afterStart does not run for: ${needServer.map(adapter=>adapter.name).join(`, `)}. Anything they attach to the server (WebSockets, upgrade handlers) is unavailable.`);for(let plugin of this.plugins)await plugin.onReady?.(this.container);this.timeline.mark(`ready`),this._status.value=`ready`,this.timeline.complete(),this.reportStartup()}async start(){await this.untilStartedOrStopped(()=>this.startSteps())}async startSteps(){let g=globalThis,serverOptions=this.options.server;if(this._status.value=`starting`,serverOptions&&g.__kickjs_httpServer)log.warn(`server options (tls / http2) are ignored in dev mode — Vite owns the server`);else if(serverOptions){if(serverOptions.http2===!0&&!serverOptions.tls)throw http2RequiresTlsError();if(serverOptions.http2===`h2c`&&serverOptions.tls)throw http2RequiresTlsError(!0);if(serverOptions.http2&&!this.runtime.capabilities.http2)throw http2UnsupportedRuntimeError(this.runtime.name);serverOptions.tls&&assertUsableTls(serverOptions.tls)}let management=this.options.management;if(management&&g.__kickjs_httpServer?log.info(`management port is ignored in dev mode — /health stays on the dev server`):management&&(this.wantsManagement=!0),await this.setup(),this.runChecks(),g.__kickjs_httpServer){this.httpServer=g.__kickjs_httpServer,log.debug(`Attached to Vite dev server`),g.__kickjs_app_shutdown=()=>this.shutdown();for(let adapter of this.adapters){let ctx=this.adapterCtx(this.httpServer,adapter.name);await this.callHook(adapter.afterStart?.bind(adapter),ctx,adapter.name,`afterStart`)}for(let plugin of this.plugins)await plugin.onReady?.(this.container);this.timeline.mark(`ready`),this._status.value=`ready`,this.timeline.complete(),this.reportStartup();return}let port=this.options.port??parseInt(process.env.PORT||`3000`,10);this.httpServer=this.createNodeServer(),this.httpServer.on(`error`,err=>{throw err.code===`EADDRINUSE`&&(log.error(`Port ${port} is already in use. Kill the existing process or use a different port:\n PORT=${port+1} kick dev\n lsof -i :${port} # find what's using it\n kill <PID> # stop it`),process.exit(1)),err}),this.managementApp&&management&&await this.listenManagement(management);try{await this.listenAndFinishStartup(port,serverOptions)}catch(err){throw await this.closeManagementServer(),err}}async listenAndFinishStartup(port,serverOptions){await new Promise((resolve,reject)=>{this.httpServer.listen(port,async()=>{try{let scheme=serverOptions?.tls?`https`:`http`,protocol=serverOptions?.http2===`h2c`?` (cleartext HTTP/2)`:serverOptions?.http2?` (HTTP/2)`:``;this.timeline.mark(`listen`),log.info(`Server running on ${scheme}://localhost:${port}${protocol}`);for(let adapter of this.adapters){let afterCtx=this.adapterCtx(this.httpServer,adapter.name);await this.callHook(adapter.afterStart?.bind(adapter),afterCtx,adapter.name,`afterStart`)}for(let plugin of this.plugins)await plugin.onReady?.(this.container);this.timeline.mark(`ready`),this._status.value=`ready`,this.timeline.complete(),this.reportStartup(),resolve()}catch(err){reject(err)}})})}async closeManagementServer(){let server=this.managementServer;server&&(this.managementServer=null,await new Promise(resolve=>{server.close(()=>resolve()),server.closeAllConnections()}))}async listenManagement(options){let handler=this.runtime.nodeHandler(this.managementApp);options.tls&&assertUsableTls(options.tls);let server=options.tls?https.createServer(options.tls,handler):http.createServer(handler);await new Promise((resolve,reject)=>{server.once(`error`,reject),server.listen(options.port,options.host,()=>{server.off(`error`,reject),resolve()})}),this.managementServer=server;let scheme=options.tls?`https`:`http`;log.info(`Management server on ${scheme}://${options.host??`localhost`}:${options.port}`);for(let line of describeRoutes(this.mountedRouteInfo.filter(r=>r.port===`management`)))log.info(` ${line}`)}createNodeServer(){let server=this.createBareServer(),options=this.options.server??{},keepAlive=options.keepAliveTimeout??65e3;return`keepAliveTimeout`in server&&(server.keepAliveTimeout=keepAlive,server.headersTimeout=options.headersTimeout??keepAlive+1e3,server.requestTimeout=options.requestTimeout??3e5),server}createBareServer(){let handler=this.runtime.nodeHandler(this.app),{tls,http2:useHttp2}=this.options.server??{};if(useHttp2){let server=useHttp2===`h2c`?http2.createServer(handler):http2.createSecureServer({...tls,allowHTTP1:!0},handler);return server.on(`session`,session=>{this.http2Sessions.add(session),session.once(`close`,()=>this.http2Sessions.delete(session))}),server}return tls?https.createServer(tls,handler):http.createServer(handler)}async rebuild(){let prevApp=this.app,prevContainer=this.container,prevRouteUrls=this.routeUrls,prevSettingsPrefixes=this.settingsPrefixes,prevSettingsProvided=this.settingsProvided,staleDisposables=drainDisposables();try{Container.reset(),this.container=Container.getInstance(),this.app=this.createEngineApp(),await this.setup()}catch(err){log.error(err,`HMR rebuild failed, keeping previous app`),await runDisposables(drainDisposables());for(let d of staleDisposables)registerDisposable(d);this.app=prevApp,this.container=prevContainer,this.routeUrls=prevRouteUrls,this.settingsPrefixes=prevSettingsPrefixes,this.settingsProvided=prevSettingsProvided;return}await runDisposables(staleDisposables),this.httpServer&&(this.httpServer.removeAllListeners(`request`),this.httpServer.on(`request`,this.runtime.nodeHandler(this.app)),log.debug(`HMR: app rebuilt and swapped`))}shutdown(options={}){return this._shutdown?(log.debug(`Shutdown already in progress, waiting on it`),this._shutdown):(this._shutdown=this.runShutdown(options),this._shutdown)}async runShutdown(options){let closeServer=options.closeServer??!0;this._status.value=`draining`;let preStopDelay=this.options.preStopDelay??0;closeServer&&preStopDelay>0&&(log.debug(`Waiting ${preStopDelay}ms for load balancers to stop routing here...`),await new Promise(resolve=>setTimeout(resolve,preStopDelay))),log.debug(`Shutting down — draining in-flight requests...`);let timeoutMs=this.options.shutdownTimeout??3e4,timer,forceExitPromise=timeoutMs>0?new Promise(resolve=>{timer=setTimeout(()=>resolve(`timeout`),timeoutMs),timer.unref()}):new Promise(()=>{});try{if(closeServer&&this.httpServer){this.httpServer.close(()=>{});for(let session of this.http2Sessions)session.close()}if(closeServer&&this._inFlightRequests>0){log.debug(`Waiting for ${this._inFlightRequests} in-flight request(s) to complete...`);let drainPromise=new Promise(resolve=>{this._drainResolvers.push(()=>resolve(`drained`))});if(await Promise.race([drainPromise,forceExitPromise])===`timeout`){log.warn(`Shutdown timeout (${timeoutMs}ms) reached with ${this._inFlightRequests} request(s) still in-flight, forcing shutdown`);for(let session of this.http2Sessions)session.destroy()}else log.debug(`All in-flight requests completed`)}closeServer&&pendingBackgroundWork()>0&&(log.debug(`Waiting for ${pendingBackgroundWork()} waitUntil() task(s) to settle...`),await Promise.race([settleBackgroundWork().then(()=>`settled`),forceExitPromise])===`timeout`&&log.warn(`Shutdown timeout (${timeoutMs}ms) reached with ${pendingBackgroundWork()} waitUntil() task(s) still running`));let hookTimeoutMs=closeServer?timeoutMs:Math.min(timeoutMs,5e3),timeBoxed=(label,run)=>{let hook=(async()=>run())();return hookTimeoutMs<=0?hook:new Promise((resolve,reject)=>{let t=setTimeout(()=>{log.warn(`${label} did not finish shutting down within ${hookTimeoutMs}ms — continuing without it. Its resources may still be held.`),resolve(void 0)},hookTimeoutMs);t.unref(),hook.then(value=>{clearTimeout(t),resolve(value)},err=>{clearTimeout(t),reject(err)})})},wasListening=this.httpServer?.listening===!0,results=await Promise.allSettled([...this.plugins.map(plugin=>timeBoxed(`Plugin '${plugin.name}'`,()=>plugin.shutdown?.())),...this.adapters.map(adapter=>timeBoxed(`Adapter '${adapter.name}'`,()=>adapter.shutdown?.())),timeBoxed(`Runtime '${this.runtime.name}'`,()=>this.runtime.close?.(this.app)),...this.managementApp&&closeServer?[timeBoxed(`Runtime '${this.runtime.name}' (management)`,()=>this.runtime.close?.(this.managementApp))]:[]]);!closeServer&&wasListening&&this.httpServer?.listening===!1&&log.error("An adapter or plugin closed the shared HTTP server during an HMR reload. The dev server is now unreachable and will not rebind until you restart it. Close only what you own: socket.io's `io.close()` closes the HTTP server passed to its constructor — on a reload, disconnect the sockets instead.");for(let result of results)result.status===`rejected`&&log.error({err:result.reason},`Adapter shutdown failed`);await disposeAll(),this.container.flushChanges(),await this.loopback?.close(),this.loopback=void 0,closeServer&&await this.closeManagementServer(),closeServer&&releaseObservers(this.observers)}finally{timer&&clearTimeout(timer),this._status.value=`stopped`}}getRuntimeApp(){return this.app}getActiveRuntime(){return{name:this.runtime.name,capabilities:this.runtime.capabilities}}getExpressApp(){return this.app}getAdapters(){return this.adapters}getPlugins(){return this.plugins}getRoutes(){return this.mountedRouteInfo}getContributors(){let out=[],ingest=(list,source,label)=>{if(list)for(let reg of list){let r=reg;if(r.key===void 0||r.key===null)continue;let key=typeof r.key==`string`?r.key:tokenName(r.key);out.push({key,source,label,dependsOn:Array.isArray(r.dependsOn)?r.dependsOn:[]})}};for(let adapter of this.adapters)ingest(adapter.contributors?.(),`adapter`,adapter.name??`adapter`);for(let plugin of this.plugins)ingest(plugin.contributors?.(),`plugin`,plugin.name??`plugin`);for(let{registration,label}of this._moduleContributors)ingest([registration],`module`,label);ingest(this.options.contributors,`global`,`bootstrap`);let sites=/* @__PURE__ */ new Set;for(let route of this.mountedRouteInfo)for(let c of route.contributors){if(c.source!==`class`&&c.source!==`method`)continue;let site=`${c.source}:${c.label??`${route.controller}.${route.handler}`}`;sites.has(site)||(sites.add(site),out.push({key:c.key,source:c.source,label:c.label??`${route.controller}.${route.handler}`,dependsOn:c.dependsOn}))}return out}getHttpServer(){return this.httpServer}getManagementServer(){return this.managementServer}shouldAutoMountRequestScope(){if(this.options.contextStore===`manual`)return!1;let userEntries=this.options.middlewares??[];for(let entry of userEntries){let handler=typeof entry==`function`?entry:entry.handler;if(isRequestScopeMiddleware(handler))return!1}return!0}collectAdapterMiddleware(){let result={beforeGlobal:[],afterGlobal:[],beforeRoutes:[],afterRoutes:[]};for(let adapter of this.adapters){let entries=adapter.middleware?.()??[];for(let entry of entries)result[entry.phase??`afterGlobal`].push(entry)}return result}mountMiddlewareList(entries){for(let entry of entries)entry.path===void 0?this.runtime.useConnect(this.app,entry.handler):this.runtime.useConnect(this.app,entry.handler,{path:entry.path})}mountMiddlewareEntry(entry){typeof entry==`function`?this.runtime.useConnect(this.app,entry):this.runtime.useConnect(this.app,entry.handler,{path:entry.path})}mountCronTrigger(){let secret=process.env.CRON_SECRET;secret&&this.adapterHttp().route(`GET`,`/_kick/cron/:scheduleId`,async ctx=>{if(!matchesBearer(ctx.headers.authorization,secret))throw new HttpException(401,`Missing or invalid CRON_SECRET bearer token`);let result=await runCronJobs(this.container,{scheduleId:ctx.params.scheduleId},`http`);ctx.json(result,result.failed>0?500:200)})}requestTrackingMiddleware(){return(req,res,next)=>{this._inFlightRequests++;let started=hasResponseObservers()?performance.now():void 0,onFinish=()=>settle(!0),onClose=()=>settle(!1),settle=finished=>{if(res.removeListener(`finish`,onFinish),res.removeListener(`close`,onClose),finished&&started!==void 0){let matched=req[ROUTE_SLOT];reportResponse({method:req.method,path:requestPath(req),route:matched?.pattern,status:res.statusCode,durationMs:performance.now()-started,requestId:requestIdOf(req)})}if(this._inFlightRequests--,this.isDraining&&this._inFlightRequests===0){for(let resolve of this._drainResolvers)resolve();this._drainResolvers=[]}};res.on(`finish`,onFinish),res.on(`close`,onClose),next()}}};function describeRoutes(routes){let byOwner=/* @__PURE__ */ new Map;for(let route of routes)byOwner.set(route.controller,[...byOwner.get(route.controller)??[],route]);let width=Math.max(0,...[...byOwner.keys()].map(owner=>owner.length));return[...byOwner].map(([owner,list])=>{if(list.length<=4)return`${owner.padEnd(width)} ${list.map(r=>`${r.method} ${r.pattern}`).join(`, `)}`;let segments=list.map(r=>r.pattern.split(`/`)),common=[];for(let i=0;segments.every(s=>s[i]!==void 0&&s[i]===segments[0][i]);i++)common.push(segments[0][i]);return`${owner.padEnd(width)} ${list.length} routes under ${common.join(`/`)||`/`}`})}function requestPath(req){return(req.originalUrl??req.url??``).split(`?`)[0]}function requestIdOf(req){let header=req.headers?.[`x-request-id`];return req.requestId??(typeof header==`string`?header:void 0)}function errorStatus(err){return typeof err?.problem?.status==`number`?err.problem.status:typeof err?.status==`number`?err.status:typeof err?.statusCode==`number`?err.statusCode:err?.name===`ZodError`?422:500}function observeErrors(handler){return((err,req,res,next)=>{let matched=req?.[ROUTE_SLOT];return reportError(err,{source:`request`,requestId:requestIdOf(req??{}),method:req?.method,path:requestPath(req??{}),route:matched?.pattern,status:errorStatus(err)}),handler(err,req,res,next)})}export{MountCycleError as _,HealthController as a,defineCheck as c,onPackage as d,ERROR_CHANNEL as f,MissingMountDepError as g,DuplicateMountNameError as h,HEALTH_PROBE as i,allOf as l,RESPONSE_CHANNEL as m,Application as n,healthModule as o,HANDLER_CHANNEL as p,describeRoutes as r,StartupCheckError as s,APPLICATION as t,onEnv as u,mountSort as v};
|
|
14
|
-
//# sourceMappingURL=application-CHBdxwF5.mjs.map
|