@forinda/kickjs 10.14.1 → 10.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{adapter-DL9JPcvC.d.mts → adapter-D_nUmKEQ.d.mts} +175 -77
- package/dist/adapter-D_nUmKEQ.d.mts.map +1 -0
- package/dist/{allowed-hosts-BpKwviq5.d.mts → allowed-hosts-BQlQFt-1.d.mts} +7 -4
- package/dist/allowed-hosts-BQlQFt-1.d.mts.map +1 -0
- package/dist/{app-module-Dk2Wenqx.d.mts → app-module-BmViGLgj.d.mts} +7 -13
- package/dist/app-module-BmViGLgj.d.mts.map +1 -0
- package/dist/application-B16ltRnC.mjs +14 -0
- package/dist/application-B16ltRnC.mjs.map +1 -0
- package/dist/{application-D921r4MW.d.mts → application-ClCq0AgY.d.mts} +200 -115
- package/dist/application-ClCq0AgY.d.mts.map +1 -0
- package/dist/{body-policy-CwgUYBw7.mjs → body-policy-D8LveWmO.mjs} +2 -2
- package/dist/{body-policy-CwgUYBw7.mjs.map → body-policy-D8LveWmO.mjs.map} +1 -1
- package/dist/{bootstrap-CY0v5VVF.mjs → bootstrap-C5NvsxHQ.mjs} +3 -3
- package/dist/bootstrap-C5NvsxHQ.mjs.map +1 -0
- package/dist/{bounded-counters-CF8EnVUm.mjs → bounded-counters-BtvB2daV.mjs} +2 -2
- package/dist/{bounded-counters-CF8EnVUm.mjs.map → bounded-counters-BtvB2daV.mjs.map} +1 -1
- package/dist/{breach-padding-FBVGmcBb.d.mts → breach-padding-BUuc21Eu.d.mts} +7 -4
- package/dist/breach-padding-BUuc21Eu.d.mts.map +1 -0
- package/dist/{cache-CdRHSXow.d.mts → cache-ByX5O2Hp.d.mts} +26 -3
- package/dist/cache-ByX5O2Hp.d.mts.map +1 -0
- package/dist/{client-ip-CpEuptqr.mjs → client-ip-CWvyHmqt.mjs} +2 -2
- package/dist/{client-ip-CpEuptqr.mjs.map → client-ip-CWvyHmqt.mjs.map} +1 -1
- package/dist/config/index.d.mts +6 -1
- package/dist/config/index.mjs +2 -2
- package/dist/{config-Djisd0f5.mjs → config-BIQoDNil.mjs} +3 -3
- package/dist/{config-Djisd0f5.mjs.map → config-BIQoDNil.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/container-DtdUiRwr.d.mts +3 -0
- package/dist/{context-Cgr5dtIZ.mjs → context-BzFNflxV.mjs} +3 -3
- package/dist/context-BzFNflxV.mjs.map +1 -0
- package/dist/{context-errors-6x0bjldv.mjs → context-errors-BmaG4vwd.mjs} +2 -2
- package/dist/context-errors-BmaG4vwd.mjs.map +1 -0
- package/dist/{contributor-runner-DQ2fXJ29.mjs → contributor-runner-BnJzu2GI.mjs} +3 -3
- package/dist/contributor-runner-BnJzu2GI.mjs.map +1 -0
- 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.d.mts +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-Dqzah_BX.mjs +12 -0
- package/dist/core-Dqzah_BX.mjs.map +1 -0
- package/dist/{cors-BlR_b0Qb.d.mts → cors-u1OwTxQ8.d.mts} +7 -4
- package/dist/cors-u1OwTxQ8.d.mts.map +1 -0
- package/dist/{cron-BTGytNg-.d.mts → cron-Bxm2MY8u.d.mts} +10 -3
- package/dist/cron-Bxm2MY8u.d.mts.map +1 -0
- package/dist/{csrf-DOAaYozG.d.mts → csrf-8-Jknvmc.d.mts} +14 -6
- package/dist/csrf-8-Jknvmc.d.mts.map +1 -0
- package/dist/decorate-C3to8dG-.mjs +13 -0
- package/dist/decorate-C3to8dG-.mjs.map +1 -0
- package/dist/{decorators-DxNb5mWw.d.mts → decorators-Bflncyz6.d.mts} +122 -10
- package/dist/decorators-Bflncyz6.d.mts.map +1 -0
- package/dist/{define-adapter-CZCFyDp5.mjs → define-adapter-DCjNTP6m.mjs} +2 -2
- package/dist/define-adapter-DCjNTP6m.mjs.map +1 -0
- package/dist/{di-hooks-ZfnBZMDp.mjs → di-hooks-DTDy7ABs.mjs} +2 -2
- package/dist/di-hooks-DTDy7ABs.mjs.map +1 -0
- package/dist/{disposables-DFZXQuVg.mjs → disposables-BC291ukb.mjs} +1 -1
- package/dist/{driver-D_bUSW7N.mjs → driver-D59oWDec.mjs} +3 -3
- package/dist/{driver-D_bUSW7N.mjs.map → driver-D59oWDec.mjs.map} +1 -1
- package/dist/{error-handler-D7DLWe1Q.d.mts → error-handler-gZLQFHeE.d.mts} +2 -4
- package/dist/error-handler-gZLQFHeE.d.mts.map +1 -0
- package/dist/{errors-By6UueCm.d.mts → errors-CppqPy0A.d.mts} +2 -3
- package/dist/{errors-By6UueCm.d.mts.map → errors-CppqPy0A.d.mts.map} +1 -1
- package/dist/{express-31o4SoCz.mjs → express-JAXx9MK0.mjs} +3 -3
- package/dist/{express-31o4SoCz.mjs.map → express-JAXx9MK0.mjs.map} +1 -1
- package/dist/{express-lazy-GCgYyykt.mjs → express-lazy-jIFBeDpY.mjs} +3 -3
- package/dist/{express-lazy-GCgYyykt.mjs.map → express-lazy-jIFBeDpY.mjs.map} +1 -1
- package/dist/{handler-Bvs0gx1o.mjs → handler-C8iAD_xz.mjs} +3 -3
- package/dist/{handler-Bvs0gx1o.mjs.map → handler-C8iAD_xz.mjs.map} +1 -1
- package/dist/{helmet-BVuVBl-D.d.mts → helmet-1H0LKr6y.d.mts} +7 -4
- package/dist/helmet-1H0LKr6y.d.mts.map +1 -0
- package/dist/{host-CKz7eCtO.mjs → host-Crxmi91N.mjs} +2 -2
- package/dist/{host-CKz7eCtO.mjs.map → host-Crxmi91N.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 +4 -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 +3 -5
- 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-Blgka75E.d.mts → index-CtjmSXFy.d.mts} +11 -5
- package/dist/index-CtjmSXFy.d.mts.map +1 -0
- package/dist/{index-DP_I4puv.d.mts → index-DoukvKwh.d.mts} +3 -7
- package/dist/index-DoukvKwh.d.mts.map +1 -0
- package/dist/index.d.mts +38 -32
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/dist/{interfaces-C6LHcYsg.d.mts → interfaces-CvO9sAea.d.mts} +3 -5
- package/dist/interfaces-CvO9sAea.d.mts.map +1 -0
- package/dist/{is-production-6wpWSGvS.mjs → is-production-LziEMGrc.mjs} +2 -2
- package/dist/{is-production-6wpWSGvS.mjs.map → is-production-LziEMGrc.mjs.map} +1 -1
- package/dist/{jobs-BTnyyRY1.mjs → jobs-D7ToA0yF.mjs} +3 -3
- package/dist/jobs-D7ToA0yF.mjs.map +1 -0
- package/dist/{kv-stores-CwJdsMln.d.mts → kv-stores-DdGPLXQG.d.mts} +33 -20
- package/dist/kv-stores-DdGPLXQG.d.mts.map +1 -0
- package/dist/{kv-stores-HUdUibOx.mjs → kv-stores-DpM57Xr5.mjs} +3 -3
- package/dist/kv-stores-DpM57Xr5.mjs.map +1 -0
- package/dist/{lazy-serve-static-CZBn-40v.mjs → lazy-serve-static-DxI2K-zs.mjs} +3 -3
- package/dist/{lazy-serve-static-CZBn-40v.mjs.map → lazy-serve-static-DxI2K-zs.mjs.map} +1 -1
- package/dist/{logger-xE9qI_FS.d.mts → logger-ByJsVwqY.d.mts} +3 -5
- package/dist/logger-ByJsVwqY.d.mts.map +1 -0
- package/dist/{metadata-UjLEzS06.mjs → metadata-nTTSnVTO.mjs} +1 -1
- package/dist/{observers-C4bWQTop.mjs → observers-fQtCIKLq.mjs} +2 -2
- package/dist/observers-fQtCIKLq.mjs.map +1 -0
- package/dist/{path-CMwIHsdv.d.mts → path-DsenzqJ7.d.mts} +1 -3
- package/dist/path-DsenzqJ7.d.mts.map +1 -0
- package/dist/{precompressed-BNkw1Vrz.mjs → precompressed-BtwmgzyS.mjs} +2 -2
- package/dist/{precompressed-BNkw1Vrz.mjs.map → precompressed-BtwmgzyS.mjs.map} +1 -1
- package/dist/{query-DXIo1mII.mjs → query-Dr28oT30.mjs} +2 -2
- package/dist/query-Dr28oT30.mjs.map +1 -0
- package/dist/{rate-limit-DQDk6bAH.d.mts → rate-limit-BQx_P6gG.d.mts} +13 -5
- package/dist/rate-limit-BQx_P6gG.d.mts.map +1 -0
- package/dist/{reactivity-DZrc3Yhu.d.mts → reactivity-KZOrwVeK.d.mts} +32 -3
- package/dist/reactivity-KZOrwVeK.d.mts.map +1 -0
- package/dist/{reply-CpMbB8uH.mjs → reply-ChoI5SvM.mjs} +3 -3
- package/dist/{reply-CpMbB8uH.mjs.map → reply-ChoI5SvM.mjs.map} +1 -1
- package/dist/{request-id-Dn64nEHK.d.mts → request-id-B9Myiv75.d.mts} +3 -4
- package/dist/request-id-B9Myiv75.d.mts.map +1 -0
- package/dist/{request-logger-TgcKRNDD.d.mts → request-logger-CYyAuPmo.d.mts} +6 -3
- package/dist/request-logger-CYyAuPmo.d.mts.map +1 -0
- package/dist/{request-scope-DZQceiLY.mjs → request-scope-BfSNdmz9.mjs} +3 -3
- package/dist/{request-scope-DZQceiLY.mjs.map → request-scope-BfSNdmz9.mjs.map} +1 -1
- package/dist/{respond-Bc71p7sN.mjs → respond-1BjaDME9.mjs} +2 -2
- package/dist/{respond-Bc71p7sN.mjs.map → respond-1BjaDME9.mjs.map} +1 -1
- package/dist/rolldown-runtime-B5KeNctS.mjs +11 -0
- package/dist/{route-flag-DWNbpMIE.mjs → route-flag-B6ZmhkfI.mjs} +3 -3
- package/dist/{route-flag-DWNbpMIE.mjs.map → route-flag-B6ZmhkfI.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-DsdJx3bk.mjs → route-policy-BG--gAcF.mjs} +2 -2
- package/dist/route-policy-BG--gAcF.mjs.map +1 -0
- package/dist/{router-builder-C5EtcFSL.d.mts → router-builder-BkIW_qjz.d.mts} +4 -5
- package/dist/router-builder-BkIW_qjz.d.mts.map +1 -0
- package/dist/{router-builder-CiwYhiUM.mjs → router-builder-DHKtp4I8.mjs} +3 -3
- package/dist/router-builder-DHKtp4I8.mjs.map +1 -0
- package/dist/{runtime-Bus9RVyU.mjs → runtime-CUfFIHiC.mjs} +3 -3
- package/dist/runtime-CUfFIHiC.mjs.map +1 -0
- package/dist/{session-DQG72vCf.d.mts → session-DPTbfwKO.d.mts} +41 -4
- package/dist/session-DPTbfwKO.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-CNZ7iRli.mjs → settings-I7GUX5ps.mjs} +4 -4
- package/dist/settings-I7GUX5ps.mjs.map +1 -0
- package/dist/{token-CroYM4Lm.mjs → token-uWfhVlfe.mjs} +1 -1
- package/dist/{upload-DnwvZQyi.d.mts → upload-O3VTcODy.d.mts} +4 -6
- package/dist/upload-O3VTcODy.d.mts.map +1 -0
- package/dist/{upload-config-Bq3qcDel.mjs → upload-config-BXqBuyza.mjs} +2 -2
- package/dist/{upload-config-Bq3qcDel.mjs.map → upload-config-BXqBuyza.mjs.map} +1 -1
- package/dist/url-for-CuMaQ2wS.mjs +12 -0
- package/dist/url-for-CuMaQ2wS.mjs.map +1 -0
- package/dist/{validate-D4Poe2EE.d.mts → validate-CTgfm7oE.d.mts} +3 -5
- package/dist/validate-CTgfm7oE.d.mts.map +1 -0
- package/dist/{view-renderer-Dbha_94K.mjs → view-renderer-Bf1Wy-DQ.mjs} +3 -3
- package/dist/view-renderer-Bf1Wy-DQ.mjs.map +1 -0
- package/dist/{web-crypto-CJiyfQrv.mjs → web-crypto-JzoGmiG0.mjs} +2 -2
- package/dist/{web-crypto-CJiyfQrv.mjs.map → web-crypto-JzoGmiG0.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 +13 -13
- 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-BosHcuBZ.mjs +0 -14
- package/dist/application-BosHcuBZ.mjs.map +0 -1
- package/dist/application-D921r4MW.d.mts.map +0 -1
- package/dist/bootstrap-CY0v5VVF.mjs.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/container-4iJdDkRH.d.mts +0 -3
- package/dist/context-Cgr5dtIZ.mjs.map +0 -1
- package/dist/context-errors-6x0bjldv.mjs.map +0 -1
- package/dist/contributor-runner-DQ2fXJ29.mjs.map +0 -1
- package/dist/core-g3y9VDwr.mjs +0 -12
- package/dist/core-g3y9VDwr.mjs.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-LMK39Sn6.mjs +0 -13
- package/dist/decorate-LMK39Sn6.mjs.map +0 -1
- package/dist/decorators-DxNb5mWw.d.mts.map +0 -1
- package/dist/define-adapter-CZCFyDp5.mjs.map +0 -1
- package/dist/di-hooks-ZfnBZMDp.mjs.map +0 -1
- package/dist/error-handler-D7DLWe1Q.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/jobs-BTnyyRY1.mjs.map +0 -1
- package/dist/kv-stores-CwJdsMln.d.mts.map +0 -1
- package/dist/kv-stores-HUdUibOx.mjs.map +0 -1
- package/dist/logger-xE9qI_FS.d.mts.map +0 -1
- package/dist/observers-C4bWQTop.mjs.map +0 -1
- package/dist/path-CMwIHsdv.d.mts.map +0 -1
- package/dist/query-DXIo1mII.mjs.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/rolldown-runtime-Z3gdyCfQ.mjs +0 -11
- package/dist/route-flag-B1lQht6v.d.mts.map +0 -1
- package/dist/route-policy-DsdJx3bk.mjs.map +0 -1
- package/dist/router-builder-C5EtcFSL.d.mts.map +0 -1
- package/dist/router-builder-CiwYhiUM.mjs.map +0 -1
- package/dist/runtime-Bus9RVyU.mjs.map +0 -1
- package/dist/session-DQG72vCf.d.mts.map +0 -1
- package/dist/settings-CNZ7iRli.mjs.map +0 -1
- package/dist/settings-DgZLgcNU.d.mts.map +0 -1
- package/dist/upload-DnwvZQyi.d.mts.map +0 -1
- package/dist/url-for-BCQLTEJj.mjs +0 -12
- package/dist/url-for-BCQLTEJj.mjs.map +0 -1
- package/dist/validate-D4Poe2EE.d.mts.map +0 -1
- package/dist/view-renderer-Dbha_94K.mjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"decorate-LMK39Sn6.mjs","names":["\"NODE_ENV\"","\"VITEST\"","\"KICKJS_ENV_FILE\""],"sources":["../src/config/env.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\nimport type { z } from 'zod'\nimport { detectSchema, type InferSchemaOutput } from '@forinda/kickjs-schema'\nimport { _useSecretFileReader, describeSchemaVars, type ConfigVar } from './settings'\nimport { Container } from '../core/container'\nimport type { EnvKey } from '../core/decorators'\n\n/**\n * Lazy `zod` accessor. `zod` is an **optional** peer of\n * `@forinda/kickjs` — only the Zod-based env helpers (`baseEnvSchema`,\n * `defineEnv`, `loadEnv`) need it. Apps that validate env via Valibot /\n * Yup / Standard Schema go through `loadEnvFromSchema` (which only\n * touches the validator-agnostic `detectSchema`) and never load zod.\n *\n * Importing `zod` at module top-level made it a *hard* dependency of\n * the whole framework: `import { anything } from '@forinda/kickjs'`\n * eagerly evaluated this module, so a non-Zod app with no `zod`\n * installed crashed at module load / build time (\"Cannot find module\n * 'zod'\"). Deferring the require to first use keeps the import out of\n * the eager graph.\n */\nlet _zod: typeof import('zod') | undefined\nfunction getZod(): typeof import('zod') {\n if (_zod) return _zod\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n _zod = require('zod') as typeof import('zod')\n } catch {\n throw new Error(\n \"@forinda/kickjs: the 'zod' peer dependency is required for \" +\n 'baseEnvSchema / defineEnv / loadEnv but is not installed. ' +\n 'Install it (`pnpm add zod`), or define your env with a non-Zod ' +\n 'schema and call loadEnvFromSchema() instead — @forinda/kickjs-schema ' +\n 'supports Valibot, Yup, and any Standard Schema validator without zod.',\n )\n }\n return _zod\n}\n\n/**\n * Lazily load `.env` via dotenv if it is installed in the consumer app.\n * `dotenv` is an **optional peer dependency** of `@forinda/kickjs` —\n * apps that want `.env` file support install it themselves (the CLI\n * generators add it to every scaffolded `package.json`). Apps that\n * inject env via the shell, Docker, or a secret manager can skip it\n * entirely and `process.env` is read as-is.\n *\n * We call `dotenv.config()` directly rather than `require('dotenv/config')`\n * so that a re-evaluation of this module (e.g. Vite SSR full-reload after\n * editing `.env`) can re-read the file. `dotenv/config` is a side-effect\n * shim that CJS caches aggressively, so the second `require` is a no-op\n * and new keys never reach `process.env` — the root cause of the\n * \"DATABASE_URL undefined until restart\" bug on Windows dev.\n *\n * Which file(s) get read is decided by {@link resolveEnvFiles}.\n */\nfunction isTestRun(): boolean {\n return process.env['NODE_ENV'] === 'test' || !!process.env['VITEST']\n}\n\n/**\n * The mode whose env files apply. A test run is always mode `test`;\n * otherwise `NODE_ENV`, defaulting to the same `development` value\n * `baseEnvSchema` uses.\n *\n * The {@link isTestRun} check has to come FIRST, and the two predicates\n * have to agree. They did not: this read `NODE_ENV ?? (VITEST ? 'test'\n * : 'development')`, so an explicitly-set `NODE_ENV=development` won\n * file selection while `isTestRun()` — which counts `VITEST` on its own\n * — still gated the backfill warning. A vitest run with\n * `NODE_ENV=development` exported (common in a shell profile or a CI\n * image) therefore skipped the `.env.test` sitting right there, loaded\n * the developer's `.env`, and printed a warning telling the user to\n * create the very file it had just ignored. Worst of both: the alarm\n * without the protection.\n *\n * So `VITEST` outranks a non-test `NODE_ENV` for file selection. To run\n * a suite deliberately against another mode's files, name them with\n * `KICKJS_ENV_FILE`, which still bypasses all of this.\n */\nfunction envMode(): string {\n if (isTestRun()) return 'test'\n return process.env['NODE_ENV'] ?? 'development'\n}\n\nconst GENERIC_ENV_FILES = ['.env.local', '.env'] as const\n\n/**\n * Which env files dotenv should read, relative to `process.cwd()`, in\n * **highest-precedence-first** order. `null` means \"read nothing\".\n *\n * The cascade follows the convention Vite popularised, where a\n * mode-specific file outranks every generic one:\n *\n * ```\n * .env.[mode].local > .env.[mode] > .env.local > .env\n * ```\n *\n * Vars already present in `process.env` still outrank all of them —\n * that is what `override: false` at the call site buys, and it matches\n * Vite (\"environment variables that already exist … have the highest\n * priority and will not be overwritten by `.env` files\").\n *\n * **Test mode is the one exception, and deliberately so.** When the mode\n * is `test` and a `.env.test` / `.env.test.local` exists, that file is\n * treated as an explicit opt-in to an isolated environment and the\n * generic files are dropped rather than layered under it. Layering is\n * exactly the hole this closes: with `override: false`, every key a test\n * runner forgets to pin is silently backfilled from the developer's\n * `.env`, so a suite can pin its database URL and still reach live\n * development services through the keys it forgot. For `development` and\n * `production` the layering is what people expect and want (shared base\n * plus overrides), and there is no dev-resource-in-a-test failure mode\n * to guard against, so those cascade normally.\n *\n * `KICKJS_ENV_FILE` overrides the decision entirely — a comma-separated\n * list of files (highest precedence first), or `off` to skip dotenv\n * altogether (for apps that inject env via the shell, Docker, or a\n * secret manager).\n */\nfunction resolveEnvFiles(): string[] | null {\n const explicit = process.env['KICKJS_ENV_FILE']\n if (explicit === 'off' || explicit === 'none') return null\n if (explicit) {\n return explicit\n .split(',')\n .map((f) => f.trim())\n .filter(Boolean)\n }\n\n const exists = (f: string): boolean => existsSync(resolve(process.cwd(), f))\n const mode = envMode()\n const modeFiles = [`.env.${mode}.local`, `.env.${mode}`]\n\n // A test-scoped file present = isolate. Without one we still read the\n // generic files (so an existing project is unchanged) and warn.\n const isolate = mode === 'test' && modeFiles.some(exists)\n const chain = isolate ? modeFiles : [...modeFiles, ...GENERIC_ENV_FILES]\n\n const found = chain.filter(exists)\n return found.length > 0 ? found : null\n}\n\n/** One-shot guard so the test-backfill warning cannot spam a suite. */\nlet warnedTestBackfill = false\n\n/**\n * Of the keys dotenv parsed out of the files, the ones whose value in\n * `process.env` actually differs from `before` — i.e. the ones dotenv\n * really applied.\n *\n * This distinction is the whole point of the warning. `result.parsed`\n * is everything READ from the files, not everything APPLIED: under\n * `override: false` a key already set by the test runner keeps the\n * runner's value and the file's copy is discarded. Warning about those\n * would name vars the user correctly pinned, which is exactly backwards\n * — the message exists to say which vars leaked IN, and listing pinned\n * ones alongside them makes it untrustworthy noise.\n *\n * Exported for tests only; not re-exported from the package index, so\n * it is not public API.\n */\nexport function appliedKeys(before: NodeJS.ProcessEnv, parsed: Record<string, string>): string[] {\n return Object.keys(parsed).filter((k) => process.env[k] !== before[k])\n}\n\nfunction tryLoadDotenv(override = false): void {\n const files = resolveEnvFiles()\n if (!files) return\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const dotenv = require('dotenv')\n // `quiet: true` suppresses dotenv 17's tip banner that goes to stdout.\n // Required for CLI tools whose stdout is parsed by callers (`kick explain\n // --json`, etc) — the banner would otherwise corrupt the JSON output.\n //\n // dotenv resolves array precedence positionally, and the DIRECTION\n // depends on `override`: with `override: false` the first file to set a\n // key wins; with `override: true` each file overwrites the last, so the\n // final one wins. `files` is ordered highest-precedence-first, so the\n // override path has to reverse it — otherwise a `reloadEnv()` would\n // silently invert the cascade and let `.env` beat `.env.production`.\n const path = override ? files.toReversed() : files\n\n // Isolation is opt-in, and nobody discovers an opt-in. A test run that\n // read the generic files says so once, on stderr — but only about the\n // vars it actually pulled in, so snapshot process.env first. Skipped\n // entirely when no warning could fire, to keep the copy off the boot\n // path of a normal run.\n const usedGeneric = files.some((f) => (GENERIC_ENV_FILES as readonly string[]).includes(f))\n const mayWarn = !warnedTestBackfill && isTestRun() && usedGeneric\n const before = mayWarn ? { ...process.env } : undefined\n\n const result = dotenv.config({ path, override, quiet: true })\n\n if (mayWarn && result.parsed) {\n const applied = appliedKeys(before!, result.parsed)\n // Only latch the one-shot guard once something is actually reported;\n // latching on a run that had nothing to say would swallow the real\n // warning from a later reload.\n if (applied.length > 0) {\n warnedTestBackfill = true\n console.warn(\n `[kickjs] test run took ${applied.length} env var(s) from ` +\n `${files.join(', ')} (${applied.slice(0, 5).join(', ')}` +\n `${applied.length > 5 ? ', …' : ''}). Create a .env.test to isolate the ` +\n 'suite, or set KICKJS_ENV_FILE=off.',\n )\n }\n }\n } catch {\n // dotenv not installed — fall through, env vars must come from\n // the environment directly. This is a valid deployment style.\n }\n}\ntryLoadDotenv()\n\n/**\n * Build the base env schema. Memoized so repeated calls reuse one\n * schema instance (matters for the `cachedSchema === s` identity check\n * in {@link loadEnv}). Loads zod lazily via {@link getZod}.\n */\n// Build the concrete base schema. This function is the single source of\n// the *type* of `baseEnvSchema` (via `ReturnType<typeof buildBaseEnvSchema>`)\n// AND its runtime value (via `getBaseEnvSchema`). It is NEVER called at\n// module load — only lazily through `getBaseEnvSchema()` — so referencing\n// its return type stays compile-time-only and pulls no eager zod import.\n// Spelling the type this way (rather than `z.ZodObject<any>`) preserves the\n// precise PORT/NODE_ENV/LOG_LEVEL shape, which `defineEnv` composition and\n// the `kick typegen` `KickEnv` inference depend on.\nfunction buildBaseEnvSchema() {\n const z = getZod()\n return z.object({\n // Server\n PORT: z.coerce.number().default(3000),\n NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),\n LOG_LEVEL: z.string().default('info'),\n })\n}\n\n/** Precise type of the base env schema — no runtime value, no eager zod. */\nexport type BaseEnvSchema = ReturnType<typeof buildBaseEnvSchema>\n\n/**\n * Memoized base schema. Reuses one instance so the `cachedSchema === s`\n * identity check in {@link loadEnv} holds. Loads zod lazily.\n */\nlet _baseEnvSchema: BaseEnvSchema | undefined\nexport function getBaseEnvSchema(): BaseEnvSchema {\n if (!_baseEnvSchema) _baseEnvSchema = buildBaseEnvSchema()\n return _baseEnvSchema\n}\n\n/**\n * Base environment schema with common server variables.\n * Users extend this with their own application-specific vars.\n *\n * Back-compat lazy view over {@link getBaseEnvSchema}: constructing the\n * Proxy does NOT load zod — zod is only required the moment a property\n * (`.extend`, `.parse`, `.shape`, …) is actually accessed. This keeps\n * `import { baseEnvSchema } from '@forinda/kickjs'` zero-cost for apps\n * that don't use the Zod env path, while keeping the precise schema type.\n */\nexport const baseEnvSchema: BaseEnvSchema = new Proxy({} as BaseEnvSchema, {\n get(_t, prop) {\n const real = getBaseEnvSchema() as unknown as Record<string | symbol, unknown>\n const value = real[prop]\n // Bind methods to the real schema so zod's internal `this` works.\n return typeof value === 'function' ? (value as (...a: unknown[]) => unknown).bind(real) : value\n },\n has(_t, prop) {\n return prop in (getBaseEnvSchema() as object)\n },\n}) as BaseEnvSchema\n\n/** Cached env config to avoid re-parsing — keyed by schema reference */\nlet cachedEnv: any = null\n/**\n * Values {@link withEnv} lays over the parsed env while its callback runs.\n * Kept apart from the cache so a re-parse during the callback (a different\n * schema, a reload) can't drop them.\n */\nlet envOverlay: Record<string, unknown> | null = null\n\nfunction overlaid<T>(env: T): T {\n return envOverlay ? ({ ...(env as object), ...envOverlay } as T) : env\n}\n\n/** What `@Value()` reads: an overlay value first, then the parsed env. */\nfunction resolveEnvKey(key: string): unknown {\n return envOverlay && key in envOverlay ? envOverlay[key] : cachedEnv?.[key]\n}\nlet cachedSchema: any = null\n\n/**\n * Define a custom env schema. The base schema (`PORT`, `NODE_ENV`,\n * `LOG_LEVEL`) is always merged in, so users never need to remember to\n * extend it themselves — both styles below produce the same result and\n * both surface the base keys in `KickEnv`.\n *\n * Returns a Zod schema that validates `process.env`.\n *\n * @example\n * ```ts\n * // Style A — return a fresh object; base fields are merged automatically\n * export default defineEnv(() =>\n * z.object({\n * DATABASE_URL: z.string().url(),\n * JWT_SECRET: z.string().min(32),\n * })\n * )\n *\n * // Style B — explicitly extend `base` (still works, identical result)\n * export default defineEnv((base) =>\n * base.extend({\n * DATABASE_URL: z.string().url(),\n * })\n * )\n * ```\n *\n * User-defined keys override base keys when they collide, so a project\n * can re-type `PORT` or tighten `NODE_ENV` without losing the rest of\n * the base shape.\n */\nexport function defineEnv<T extends z.ZodRawShape>(\n extend: (base: typeof baseEnvSchema) => z.ZodObject<T>,\n): z.ZodObject<typeof baseEnvSchema.shape & T> {\n const base = getBaseEnvSchema()\n const userSchema = extend(base as typeof baseEnvSchema)\n // Always merge the base in. `extend` lets the user's shape override\n // any colliding base keys, which preserves the escape hatch for\n // projects that want to re-type `PORT` etc.\n return base.extend(userSchema.shape) as z.ZodObject<typeof baseEnvSchema.shape & T>\n}\n\n/**\n * Parse and validate `process.env` against a Zod schema. Caches result per schema.\n *\n * **No-arg behaviour is sticky.** The first time `loadEnv(schema)` is called\n * with an extended schema, the cache holds that schema. Subsequent\n * `loadEnv()` calls (no arg) will reuse the cached extended schema rather\n * than falling back to `baseEnvSchema`.\n *\n * Stickiness matters because `ConfigService` and the `@Value()` decorator\n * both read through the no-arg form internally. Without it, resolving\n * either of them after a `loadEnv(extendedSchema)` call would silently\n * downgrade the env to the base shape and drop every user-defined key.\n *\n * To force a re-parse with a different schema, pass the new schema explicitly.\n * To start fresh, call `resetEnvCache()` (full reset) or `reloadEnv()`\n * (re-parse against the same schema after a `.env` file change).\n *\n * **Typing:**\n * - With an explicit schema → returns `z.infer<typeof schema>`.\n * - With no schema and `KickEnv` populated by typegen → returns\n * `KickEnv` (the project-wide typed env shape).\n * - With no schema and `KickEnv` empty → returns the base `Env`.\n */\nexport function loadEnv<T extends z.ZodObject<any>>(schema: T): z.infer<T>\nexport function loadEnv(): [EnvKey] extends [never] ? Env : KickEnv\nexport function loadEnv<T extends z.ZodObject<any>>(schema?: T): any {\n // Sticky: when called with no arg, prefer the most recently cached\n // schema over re-parsing with the base schema.\n const s = schema ?? cachedSchema ?? getBaseEnvSchema()\n // Re-parse if schema changed or no cache yet\n if (cachedEnv && cachedSchema === s) return overlaid(cachedEnv)\n cachedSchema = s\n if (describingConfig()) return describedEnv(s)\n cachedEnv = s.parse(withSecretFiles(process.env, Object.keys(s.shape ?? {})))\n\n // Register env resolver so @Value() reads validated values\n Container.setEnvResolver(resolveEnvKey)\n\n return overlaid(cachedEnv)\n}\n\n/**\n * Get a single typed environment variable value, read from the env schema\n * the app registered — the one source of truth, set once with\n * `loadEnv(envSchema)` in `src/env.ts`.\n *\n * - **`getEnv(key)`** returns the parsed value: `getEnv('PORT')` is a number\n * once `kick typegen` has run.\n * - **`getEnv(key, fallback)`** returns `fallback` when the value is unset\n * (`undefined` or `null`) — for keys the schema leaves optional.\n *\n * @example\n * ```ts\n * const port = getEnv('PORT') // number\n * const region = getEnv('S3_REGION', 'eu-west-1') // string, never undefined\n * ```\n *\n * A default every caller shares belongs in the schema (`.default(...)`);\n * the fallback is for a value one call site can live without.\n */\nexport function getEnv<K extends EnvKey>(key: K): KickEnv[K]\nexport function getEnv<K extends EnvKey>(\n key: K,\n fallback: NonNullable<KickEnv[K]>,\n): NonNullable<KickEnv[K]>\nexport function getEnv(key: string, fallback?: unknown): any {\n // The old second argument was a schema. Still honoured, so existing calls\n // keep working, but the schema belongs in one place: loadEnv(envSchema).\n if (isZodObject(fallback)) {\n if (!warnedSchemaArg) {\n warnedSchemaArg = true\n process.emitWarning(\n 'getEnv(key, schema) is deprecated: register the schema once with loadEnv(envSchema); ' +\n 'the second argument is now a fallback value.',\n 'DeprecationWarning',\n )\n }\n return (loadEnv(fallback) as Record<string, unknown>)[key]\n }\n const value = (loadEnv() as Record<string, unknown>)[key]\n return value ?? fallback\n}\n\nlet warnedSchemaArg = false\n\nfunction isZodObject(value: unknown): value is z.ZodObject<any> {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { safeParse?: unknown }).safeParse === 'function' &&\n 'shape' in value\n )\n}\n\n/**\n * Run `fn` with some env values replaced — for tests. The overrides are\n * parsed values (`{ TRUST_PROXY: true }`), laid over the current env for the\n * duration of the call and taken away afterwards, whatever `fn` does.\n * `getEnv`, `ConfigService` and `@Value()` all see them. No `.env` file is\n * read. Not for concurrent use: the env is process-wide.\n */\nexport async function withEnv<T>(\n overrides: Record<string, unknown>,\n fn: () => T | Promise<T>,\n): Promise<T> {\n loadEnv() // registers the resolver @Value() reads through\n const previous = envOverlay\n // Nested calls layer: the inner overrides win, the outer ones come back after.\n envOverlay = { ...previous, ...overrides }\n try {\n return await fn()\n } finally {\n envOverlay = previous\n }\n}\n\n/**\n * Reload env from `process.env`. Re-reads `.env` via dotenv (if\n * installed), then re-parses the result against the **same** schema\n * the project registered at startup. Called during HMR rebuild and by\n * `envWatchPlugin` to pick up `.env` file changes mid-session.\n *\n * Crucially, this preserves the registered schema. Wiping it would\n * silently downgrade `ConfigService` and `@Value()` back to the base\n * schema on the next read, so every user-defined key would start\n * resolving as `undefined` after the first `.env` save — which was the\n * original \"config disappears in dev\" bug.\n *\n * If you need to fully forget the schema (e.g. tests that swap schemas\n * between cases), call {@link resetEnvCache} instead.\n */\nexport function reloadEnv(): void {\n // Re-read the env file(s) into process.env if dotenv is installed.\n // Routed through the same resolver as boot so a reload can never\n // disagree with startup about which file is authoritative — the\n // inline `dotenv.config()` this replaced always read `.env`, so\n // under a test run it could clobber pinned `.env.test` values with\n // the developer's own.\n tryLoadDotenv(true)\n\n // Drop the parsed snapshot but keep the schema. Re-parse eagerly so\n // existing consumers (including ConfigService getters and @Value\n // resolvers that may already hold references to the env state) see\n // the new values on their very next read instead of having to\n // re-trigger any cache-population step.\n cachedEnv = null\n if (cachedSchema) {\n if (typeof cachedSchema.parse === 'function') {\n loadEnv(cachedSchema)\n } else {\n loadEnvFromSchema(cachedSchema)\n }\n }\n}\n\n/**\n * Fully reset the env cache, including the registered schema. Use this\n * in tests that need to swap schemas between cases — `reloadEnv()`\n * deliberately preserves the schema to avoid the \"user keys vanish on\n * `.env` reload\" footgun.\n */\nexport function resetEnvCache(): void {\n cachedEnv = null\n cachedSchema = null\n // Also re-arm the one-shot backfill warning. This is the \"start fresh\"\n // hook, and a suite that swaps env between cases should get told each\n // time it picks up the generic files, not only the first.\n warnedTestBackfill = false\n // Drop the resolver too. It closes over `cachedEnv`, so leaving it\n // installed left `@Value()` reading through a live closure over a\n // null cache — indistinguishable from \"key not set\" but with no\n // schema to re-parse against.\n Container.setEnvResolver(null)\n}\n\n/**\n * Schema-agnostic env loader. Accepts any schema supported by\n * `@forinda/kickjs-schema` (Zod, Valibot, Yup, any Standard Schema, a\n * KickSchema or one from a registered adapter, or a plain validator function).\n *\n * Unlike `loadEnv()` which uses Zod's `.parse()` and throws a\n * `ZodError`, this function uses `detectSchema().safeParse()` and\n * throws a plain `Error` with structured issue messages on failure.\n *\n * @example\n * ```ts\n * import * as v from 'valibot'\n * import { fromValibot } from '@forinda/kickjs-schema/valibot'\n *\n * const envSchema = fromValibot(v.object({\n * PORT: v.pipe(v.string(), v.transform(Number)),\n * NODE_ENV: v.picklist(['development', 'production', 'test']),\n * }))\n *\n * loadEnvFromSchema(envSchema) // registers the schema; read values with getEnv('PORT')\n * ```\n */\n/**\n * Single inferring signature. `TSchema` is inferred from the call site;\n * the conditional return type maps the unknown-input case (TSchema\n * resolves to `unknown` only when the argument is `unknown`-typed\n * because nothing on the value side carried a richer brand) to\n * `Record<string, unknown>` rather than letting `InferSchemaOutput`\n * fall through to `unknown`. The previous two-overload form had the\n * generic overload win for `unknown`-typed inputs (`unknown` is\n * assignable to any `TSchema`), so the documented \"Record\" fallback\n * never actually applied.\n */\nexport function loadEnvFromSchema<TSchema>(\n schema: TSchema,\n): unknown extends TSchema ? Record<string, unknown> : InferSchemaOutput<TSchema>\nexport function loadEnvFromSchema(schema: unknown): unknown {\n if (describingConfig()) {\n cachedSchema = schema\n return describedEnv(schema)\n }\n const wrapped = detectSchema(schema)\n const declared = Object.keys(\n ((wrapped.toJsonSchema?.() as { properties?: Record<string, unknown> } | undefined)\n ?.properties ?? {}) as Record<string, unknown>,\n )\n const result = wrapped.safeParse(withSecretFiles(process.env, declared))\n if (!result.success) {\n const details = result.issues\n .map((i) => ` ${i.path.join('.') || '(root)'}: ${i.message}`)\n .join('\\n')\n throw new Error(`Environment validation failed:\\n${details}`)\n }\n cachedEnv = result.data\n cachedSchema = schema\n Container.setEnvResolver(resolveEnvKey)\n return overlaid(result.data)\n}\n\n/**\n * The env with `<KEY>_FILE` secrets read in — the Docker / Kubernetes\n * convention: `DB_PASSWORD_FILE=/run/secrets/db` supplies `DB_PASSWORD`.\n *\n * Only for keys the schema declares (`LOG_FILE` meaning \"where to log\" must\n * not be read as the secret `LOG`), and into the copy that is parsed — not\n * into `process.env`, which child processes inherit. A key set both ways is\n * an error, as in the official Postgres image; so is a file that can't be\n * read. One trailing newline (as `echo` leaves) is dropped.\n */\nexport function withSecretFiles(\n env: NodeJS.ProcessEnv,\n keys: readonly string[],\n): Record<string, string | undefined> {\n let out: Record<string, string | undefined> | undefined\n for (const key of keys) {\n const path = env[`${key}_FILE`]\n if (!path) continue\n if (env[key] !== undefined && env[key] !== '') {\n throw new Error(`Environment: set either ${key} or ${key}_FILE, not both`)\n }\n let value: string\n try {\n value = readFileSync(path, 'utf8')\n } catch (err) {\n throw new Error(\n `Environment: ${key}_FILE points at ${path}, which could not be read ` +\n `(${(err as NodeJS.ErrnoException).code ?? 'error'})`,\n // The fs error names the path, never the contents.\n { cause: err },\n )\n }\n out ??= { ...env }\n out[key] = value.replace(/\\r?\\n$/, '')\n }\n return out ?? env\n}\n\n/**\n * Output type of {@link baseEnvSchema}. Hand-written (rather than\n * `z.infer<typeof baseEnvSchema>`) so the type is available without the\n * eager `zod` value import — `baseEnvSchema` is now a lazy Proxy typed\n * as `z.ZodObject<any>`, from which `z.infer` could not recover the\n * precise shape anyway.\n */\nexport type Env = {\n PORT: number\n NODE_ENV: 'development' | 'production' | 'test'\n LOG_LEVEL: string\n}\n\n// `defineSettings` sections read `<NAME>_FILE` secrets through this too.\n_useSecretFileReader(withSecretFiles)\n\n/**\n * Set by `kick env example` while it loads the app: env loaders record the\n * schema and skip validation — the environment it describes may not exist\n * yet. @internal\n */\nexport const DESCRIBE_CONFIG = Symbol.for('kickjs.config.describe')\n\nfunction describingConfig(): boolean {\n return (globalThis as Record<symbol, unknown>)[DESCRIBE_CONFIG] === true\n}\n\n/**\n * What env reads return while describing, unvalidated: the value that's set,\n * or the schema's default. Entry files pass these on as they load, as in\n * `session({ secret: getEnv('SESSION_SECRET') })`, so a required variable with\n * neither gets a placeholder rather than `undefined`. Nothing serves requests\n * in this mode, so the placeholder is never used for real.\n *\n * Empty counts as unset, as in `originsOf`: `kick env example` writes required\n * variables as `NAME=`, so a copied `.env` has empty values, and passing those on\n * would fail the very load this mode exists to get through.\n */\nfunction describedEnv(schema: unknown): Record<string, unknown> {\n const env: Record<string, unknown> = {}\n for (const v of describeSchemaVars(schema)) {\n const value = process.env[v.name] || v.default\n if (value !== undefined) env[v.name] = value\n else if (v.required) env[v.name] = 'kick-env-example-placeholder'\n }\n return env\n}\n\n/**\n * The variables the app's env schema reads — the schema registered with\n * `loadEnv` / `loadEnvFromSchema`, or the base schema — without parsing the\n * environment. For `kick env example`.\n */\nexport function describeEnvSchema(): ConfigVar[] {\n return describeSchemaVars(cachedSchema ?? getBaseEnvSchema())\n}\n"],"mappings":";;;;;;;;;;4TAsBA,I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B;;;;;;;;;;;;;;;;;;;;KA4BS,kBAAkB,eAAe,KAAK,MAAM;;iBAGxC,cAAc,UAAU,sBAAsB,iBAAiB;;;;;KAqBnE,8BAA8B,kBAAkB;;;;;UAM3C;;EAEf;;;;;;EAMA,eAAe;;EAEf,gBAAgB;;;;;;;;EAQhB,UAAU;IACR;IACA;IACA;IACA;;;UAIa,yBAAyB;EACxC;;EAEA;;EAEA;;;iBAIc,WAAW,QAAQ,mBAAmB"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"define-adapter-CZCFyDp5.mjs","names":[],"sources":["../src/core/define-adapter.ts"],"sourcesContent":["import type { AppAdapter, AdapterContext } from './adapter'\nimport type { BuildContext } from './define-plugin'\n\n/**\n * Options passed to {@link defineAdapter}. Mirrors {@link DefinePluginOptions}\n * exactly — see `architecture.md` §21.3.4 for the definePlugin/defineAdapter\n * symmetry rationale.\n *\n * The optional `TExtra` generic lets an adapter ship public methods\n * beyond the standard {@link AppAdapter} contract — they're preserved\n * on the returned adapter instance so external callers (tests, peer\n * adapters) can invoke them directly. See `OtelAdapter.applyRedaction`\n * for the canonical use case.\n */\nexport interface DefineAdapterOptions<TConfig, TExtra = unknown> {\n /**\n * Stable identity used for logging, `dependsOn` lookups, and `.scoped()`\n * namespacing. Required for adapters that participate in `dependsOn`\n * sort — error messages reference adapters by name.\n */\n name: string\n version?: string\n requires?: { kickjs?: string }\n defaults?: Partial<TConfig>\n build(config: TConfig, ctx: BuildContext): Omit<AppAdapter, 'name'> & TExtra\n}\n\n/**\n * Async-config form of an adapter. Identical shape to `PluginAsyncOptions`\n * but resolved during `beforeStart` (the earliest async hook in\n * `AppAdapter`) — meaning `middleware()` and `contributors()` from the inner\n * adapter are **not** picked up. Use the bare/`.scoped()` form when you need\n * those.\n */\nexport interface AdapterAsyncOptions<TConfig> {\n inject?: ReadonlyArray<unknown>\n useFactory(...deps: any[]): TConfig | Promise<TConfig>\n}\n\n/**\n * Factory returned by {@link defineAdapter}. Same surface as\n * {@link PluginFactory} (call / `.scoped()` / `.async()`) so adopters learn\n * one mental model for both primitives. Returned instances carry both\n * the standard {@link AppAdapter} contract and any `TExtra` extension\n * methods the `build` function exposed.\n */\nexport interface AdapterFactory<TConfig, TExtra = unknown> {\n (config?: Partial<TConfig>): AppAdapter & TExtra\n scoped(scopeName: string, config?: Partial<TConfig>): AppAdapter & TExtra\n async(opts: AdapterAsyncOptions<TConfig>): AppAdapter\n readonly definition: Readonly<DefineAdapterOptions<TConfig, TExtra>>\n}\n\nconst mergeConfig = <TConfig>(\n defaults: Partial<TConfig> = {},\n overrides: Partial<TConfig> = {},\n): TConfig => ({ ...defaults, ...overrides }) as TConfig\n\nconst composeName = (base: string, scope: string): string => `${base}:${scope}`\n\n/**\n * Build an {@link AppAdapter} factory from a typed definition. See\n * `architecture.md` §21.3.4 for migration guidance — most first-party\n * adapter packages collapse to a single `defineAdapter()` call after this\n * lands.\n *\n * @example\n * ```ts\n * const TenantAdapter = defineAdapter<TenantConfig>({\n * name: 'TenantAdapter',\n * defaults: { strategy: 'header', required: true },\n * build: (config) => ({\n * middleware: () => [tenantResolverMiddleware(config)],\n * beforeStart: ({ container }) => registerTenantFactory(container, config),\n * }),\n * })\n *\n * bootstrap({\n * adapters: [\n * TenantAdapter({ strategy: 'subdomain' }),\n * TenantAdapter.scoped('shard-eu', { headerName: 'x-eu-tenant' }),\n * ],\n * })\n * ```\n */\nexport function defineAdapter<TConfig = Record<string, unknown>, TExtra = unknown>(\n options: DefineAdapterOptions<TConfig, TExtra>,\n): AdapterFactory<TConfig, TExtra> {\n const buildSync = (\n instanceName: string,\n scoped: boolean,\n overrides?: Partial<TConfig>,\n ): AppAdapter & TExtra => {\n const config = mergeConfig(options.defaults, overrides)\n // Mutate `name` on the build result instead of spreading — spread\n // strips prototype methods when `build()` returns a class instance.\n // Extension methods declared by the build function (`TExtra`) survive\n // the mutation since they're own properties on the build result.\n const built = options.build(config, { name: instanceName, scoped }) as AppAdapter & TExtra\n ;(built as AppAdapter).name = instanceName\n return built\n }\n\n const buildAsync = (instanceName: string, opts: AdapterAsyncOptions<TConfig>): AppAdapter => {\n let inner: AppAdapter | undefined\n\n return {\n name: instanceName,\n async beforeStart(ctx: AdapterContext) {\n const deps = (opts.inject ?? []).map((tok) => ctx.container.resolve(tok as never))\n const config = await opts.useFactory(...deps)\n inner = buildSync(instanceName, false, config as Partial<TConfig>)\n await inner.beforeStart?.(ctx)\n },\n async afterStart(ctx: AdapterContext) {\n await inner?.afterStart?.(ctx)\n },\n async shutdown() {\n await inner?.shutdown?.()\n },\n async onHealthCheck() {\n return (await inner?.onHealthCheck?.()) ?? { name: instanceName, status: 'up' }\n },\n }\n }\n\n const factory = ((config?: Partial<TConfig>) =>\n buildSync(options.name, false, config)) as AdapterFactory<TConfig, TExtra>\n\n factory.scoped = (scopeName: string, config?: Partial<TConfig>) =>\n buildSync(composeName(options.name, scopeName), true, config)\n\n factory.async = (opts: AdapterAsyncOptions<TConfig>) => buildAsync(options.name, opts)\n\n Object.defineProperty(factory, 'definition', { value: Object.freeze({ ...options }) })\n\n return factory\n}\n"],"mappings":";;;;;;;;;;AAqDA,MAAM,aACJ,SAA6B,CAAC,EAC9B,UAA8B,CAAC,KAClB,CAAE,GAAG,SAAU,GAAG,SAAU,GAErC,aAAe,KAAc,QAA0B,GAAG,KAAK,GAAG,QA2BxE,SAAgB,cACd,QACiC,CACjC,IAAM,WACJ,aACA,OACA,YACwB,CACxB,IAAM,OAAS,YAAY,QAAQ,SAAU,SAAS,EAKhD,MAAQ,QAAQ,MAAM,OAAQ,CAAE,KAAM,aAAc,MAAO,CAAC,EAElE,MADC,OAAsB,KAAO,aACvB,KACT,EAEM,YAAc,aAAsB,OAAmD,CAC3F,IAAI,MAEJ,MAAO,CACL,KAAM,aACN,MAAM,YAAY,IAAqB,CACrC,IAAM,MAAQ,KAAK,QAAU,CAAC,EAAA,CAAG,IAAK,KAAQ,IAAI,UAAU,QAAQ,GAAY,CAAC,EAC3E,OAAS,MAAM,KAAK,WAAW,GAAG,IAAI,EAC5C,MAAQ,UAAU,aAAc,GAAO,MAA0B,EACjE,MAAM,MAAM,cAAc,GAAG,CAC/B,EACA,MAAM,WAAW,IAAqB,CACpC,MAAM,OAAO,aAAa,GAAG,CAC/B,EACA,MAAM,UAAW,CACf,MAAM,OAAO,WAAW,CAC1B,EACA,MAAM,eAAgB,CACpB,OAAQ,MAAM,OAAO,gBAAgB,GAAM,CAAE,KAAM,aAAc,OAAQ,IAAK,CAChF,CACF,CACF,EAEM,SAAY,QAChB,UAAU,QAAQ,KAAM,GAAO,MAAM,GASvC,MAPA,SAAQ,QAAU,UAAmB,SACnC,UAAU,YAAY,QAAQ,KAAM,SAAS,EAAG,GAAM,MAAM,EAE9D,QAAQ,MAAS,MAAuC,WAAW,QAAQ,KAAM,IAAI,EAErF,OAAO,eAAe,QAAS,aAAc,CAAE,MAAO,OAAO,OAAO,CAAE,GAAG,OAAQ,CAAC,CAAE,CAAC,EAE9E,OACT"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"di-hooks-ZfnBZMDp.mjs","names":[],"sources":["../src/core/asset-resolver-slot.ts","../src/core/kick-error.ts","../src/core/kick-errors.ts","../src/core/di-hooks.ts"],"sourcesContent":["/**\n * Indirection slot between the DI container's `@Asset` property injection\n * and the asset manager. The container must NOT import `./assets` directly —\n * its eager `node:fs`/`node:path` imports would poison the edge-safe\n * `@forinda/kickjs/web` entry graph (every graph includes the container).\n *\n * `./assets` registers the real resolver at module scope, so any node app\n * that imports the asset manager (the core barrel does) gets full `@Asset`\n * behavior; an edge bundle that never imports it gets a clear error on\n * first `@Asset` property access instead of a broken bundle.\n */\n\ntype AssetResolver = (namespace: string, key: string) => unknown\n\nlet impl: AssetResolver | null = null\n\n/** Called by `./assets` at module scope to install the real resolver. */\nexport function _setAssetResolver(fn: AssetResolver): void {\n impl = fn\n}\n\n/** Resolve an asset through the slot — throws when no asset manager is loaded. */\nexport function resolveAssetViaSlot(namespace: string, key: string): unknown {\n if (!impl) {\n throw new Error(\n `@Asset('${namespace}/${key}'): the asset manager is not loaded. ` +\n \"Import it (any import from '@forinda/kickjs' loads it) — note @Asset \" +\n 'reads from the filesystem and is not supported on edge runtimes.',\n )\n }\n return impl(namespace, key)\n}\n","/**\n * Structured framework error with code, cause, and actionable fix hint.\n *\n * The goal is \"the developer who hits this knows what to do next.\" A\n * cryptic `Error('No binding found for: UserService')` becomes a\n * multi-line explanation pointing at the likely cause, the exact code\n * change to apply, and a docs link.\n *\n * `.message` carries the full multi-line plain-text body so Node's\n * default `Error.toString()` and unhandled-exception printing still\n * surface the helpful version. Call {@link formatKickError} to render a\n * colorized version for terminals.\n *\n * Per-error factories live in `kick-errors.ts` — those are the public\n * entry points framework code uses. `KickError` is exported so adopters\n * can build their own structured errors using the same shape.\n */\nexport interface KickErrorInit {\n /** Short stable identifier (e.g. `KICK001`, `NO_PROVIDER`). */\n code: string\n /** One-line headline. */\n summary: string\n /** Multi-line explanation of why this happened. */\n cause?: string\n /** Multi-line actionable fix — show exact code if possible. */\n fix?: string\n /** Absolute URL to the docs page that covers this error. */\n docsUrl?: string\n /** Arbitrary structured fields for log consumers / debug tooling. */\n context?: Record<string, unknown>\n}\n\nexport class KickError extends Error {\n public readonly code: string\n public readonly summary: string\n public readonly cause?: string\n public readonly fix?: string\n public readonly docsUrl?: string\n public readonly context?: Record<string, unknown>\n\n constructor(init: KickErrorInit) {\n super(formatKickError(init, { color: false }))\n this.name = 'KickError'\n this.code = init.code\n this.summary = init.summary\n if (init.cause !== undefined) this.cause = init.cause\n if (init.fix !== undefined) this.fix = init.fix\n if (init.docsUrl !== undefined) this.docsUrl = init.docsUrl\n if (init.context !== undefined) this.context = init.context\n }\n}\n\n// ── ANSI colour helpers ────────────────────────────────────────────────\n\n/**\n * `true` when the runtime can render ANSI escape codes on stderr.\n * Honors `NO_COLOR` (https://no-color.org) and `FORCE_COLOR`.\n */\nfunction ansiEnabled(): boolean {\n if (process.env.NO_COLOR) return false\n if (process.env.FORCE_COLOR) return true\n // Node sets `isTTY` on the writable streams when stdout/stderr is a\n // terminal. KickError output goes to stderr conceptually (it's an\n // error), so we follow that stream's affordances.\n return process.stderr?.isTTY === true\n}\n\n// Use the Unicode-escape form (`\u001b`) rather than the hex-escape (`\\x1b`)\n// for the ANSI ESC byte — both produce the same character, but oxlint's\n// `no-control-character` rule flags the hex form as \"unexpected control\n// character in string literal\". Functionally identical, lint-clean.\nconst ESC = '\u001b['\nconst RESET = `${ESC}0m`\n\nfunction paint(text: string, code: string, enabled: boolean): string {\n return enabled ? `${ESC}${code}m${text}${RESET}` : text\n}\n\nconst c = {\n red: (s: string, enabled: boolean) => paint(s, '31', enabled),\n bold: (s: string, enabled: boolean) => paint(s, '1', enabled),\n dim: (s: string, enabled: boolean) => paint(s, '2', enabled),\n cyan: (s: string, enabled: boolean) => paint(s, '36', enabled),\n blue: (s: string, enabled: boolean) => paint(s, '34', enabled),\n underline: (s: string, enabled: boolean) => paint(s, '4', enabled),\n}\n\n// ── Formatter ─────────────────────────────────────────────────────────\n\nexport interface FormatKickErrorOptions {\n /**\n * Render ANSI colour codes. Defaults to TTY detection (`NO_COLOR` /\n * `FORCE_COLOR` env vars honoured). Pass `false` for log files,\n * structured loggers, or HTTP response bodies.\n */\n color?: boolean\n}\n\n/**\n * Render a {@link KickErrorInit} (or {@link KickError} instance) into a\n * multi-line human-readable string. Identical layout regardless of\n * colour — the colour flag only toggles ANSI codes.\n */\nexport function formatKickError(\n err: KickErrorInit | KickError,\n options: FormatKickErrorOptions = {},\n): string {\n const color = options.color ?? ansiEnabled()\n const lines: string[] = []\n\n // Headline: `KICK001: No provider for UserService`\n const code = c.bold(c.red(err.code, color), color)\n lines.push(`${code}: ${err.summary}`)\n\n if (err.cause) {\n lines.push('', ` ${c.bold(c.dim('Cause:', color), color)}`)\n for (const line of err.cause.split('\\n')) {\n lines.push(` ${highlightInline(line, color)}`)\n }\n }\n\n if (err.fix) {\n lines.push('', ` ${c.bold(c.dim('Fix:', color), color)}`)\n for (const line of err.fix.split('\\n')) {\n lines.push(` ${highlightInline(line, color)}`)\n }\n }\n\n if (err.docsUrl) {\n lines.push('', ` ${c.bold(c.dim('Docs:', color), color)}`)\n lines.push(` ${c.underline(c.blue(err.docsUrl, color), color)}`)\n }\n\n return lines.join('\\n')\n}\n\n/**\n * Highlight inline `code spans` in a line of cause/fix text. Anything\n * between backticks gets cyan when colour is enabled; backticks stay\n * in the output so the plain-text rendering still distinguishes\n * literals.\n */\nfunction highlightInline(line: string, color: boolean): string {\n if (!color) return line\n return line.replace(/`([^`]+)`/g, (_, inner: string) => `\\`${c.cyan(inner, true)}\\``)\n}\n","/**\n * Catalog of framework errors with structured cause + fix hints.\n *\n * Each factory function returns a {@link KickError} with a stable\n * `code` (KICK001, KICK002, …), a human-readable summary, an\n * explanation of the likely cause, an actionable fix, and a docs URL.\n *\n * Adding a new error: pick the next free code, add the factory below,\n * call it from the framework site that used to throw a bare `Error`.\n * Keep the public function name descriptive — `noProviderError`,\n * `envValueMissingError` — so call sites grep cleanly.\n *\n * Codes are stable. Reordering or renumbering breaks adopters whose\n * tools key on `err.code`.\n */\nimport { KickError } from './kick-error'\n\nconst DOCS_BASE = 'https://kickjs.app'\n\n// ── DI container ──────────────────────────────────────────────────────\n\n/**\n * KICK001 — No provider registered for a token.\n *\n * Thrown by `Container.resolve()` when no binding can be found for the\n * requested token. The most common cause is forgetting to add the\n * enclosing module to `bootstrap({ modules })`.\n */\nexport function noProviderError(tokenName: string): KickError {\n return new KickError({\n code: 'KICK001',\n summary: `No provider for ${tokenName}`,\n cause: `\\`${tokenName}\\` was requested from the DI container but no binding is registered.\nThis usually means one of:\n • The class is decorated with @Service() / @Repository() / @Controller(),\n but its enclosing module isn't passed to bootstrap({ modules: [...] }).\n • The class isn't decorated at all (decorators register the binding).\n • You're injecting a token (created with createToken()) that nothing\n provides — add a Container.register(TOKEN, ...) call or a module that\n binds it.`,\n fix: `If \\`${tokenName}\\` lives in a module, add the module to bootstrap:\n\n bootstrap({\n modules: [\n UsersModule, // add this\n OtherModule,\n ],\n })\n\nIf it's a custom token, register it explicitly:\n\n const TENANT_REPO = createToken<TenantRepo>('TENANT_REPO')\n Container.getInstance().register(TENANT_REPO, { useClass: PrismaTenantRepo })`,\n docsUrl: `${DOCS_BASE}/guide/dependency-injection#registering-services`,\n context: { token: tokenName },\n })\n}\n\n/**\n * KICK002 — REQUEST-scoped binding resolved without a request store\n * provider configured.\n */\nexport function requestScopeMiddlewareMissingError(tokenName: string): KickError {\n return new KickError({\n code: 'KICK002',\n summary: `Cannot resolve REQUEST-scoped \"${tokenName}\" — request scope middleware not mounted`,\n cause: `\\`${tokenName}\\` has \\`scope: Scope.REQUEST\\` but no AsyncLocalStorage frame is wired.\nThe framework's request-scope middleware sets up that frame; without it,\nREQUEST-scoped resolutions have nowhere to cache the per-request instance.`,\n fix: `Add \\`requestScopeMiddleware()\\` to your global middleware pipeline,\nor let the framework auto-mount it by using \\`contextStore: 'auto'\\`\n(the default — only check this if you set it to 'manual' explicitly):\n\n bootstrap({\n modules,\n // contextStore: 'auto', // default; no need to set\n })\n\nIf you set \\`contextStore: 'manual'\\` deliberately (rare), you own the\nALS wrapping — call \\`requestStore.run({...}, () => ...)\\` around the\ncode that resolves the binding.`,\n docsUrl: `${DOCS_BASE}/guide/dependency-injection#scopes`,\n context: { token: tokenName },\n })\n}\n\n/**\n * KICK003 — REQUEST-scoped binding resolved outside any HTTP request\n * context (no ALS store active).\n */\nexport function requestScopeOutsideRequestError(tokenName: string): KickError {\n return new KickError({\n code: 'KICK003',\n summary: `Cannot resolve REQUEST-scoped \"${tokenName}\" outside an HTTP request`,\n cause: `\\`${tokenName}\\` has \\`scope: Scope.REQUEST\\` and was resolved outside\nany HTTP request context. The request-scope middleware is wired, but\nthe call happened before a request started (e.g. in a top-level\nimport, a constructor, a cron job, a test without setup).`,\n fix: `If the caller is request-scoped (controller, request-scoped service),\nmake sure the call happens inside the request lifecycle, not at module\nload time.\n\nIn tests, wrap setup in an ALS frame manually:\n\n import { requestStore } from '@forinda/kickjs'\n\n requestStore.run(\n { requestId: 'test', instances: new Map(), values: new Map() },\n () => {\n const svc = container.resolve(MyRequestScopedService)\n // ...\n },\n )\n\nIf the caller is a SINGLETON, change \\`${tokenName}\\` to TRANSIENT or\nSINGLETON scope, or inject a factory instead of the instance directly.`,\n docsUrl: `${DOCS_BASE}/guide/dependency-injection#scopes`,\n context: { token: tokenName },\n })\n}\n\n/**\n * KICK010 — A token was bound normally after its `registerFallback()`\n * singleton had already been resolved.\n *\n * Whatever resolved the fallback still holds that instance; letting the new\n * binding take over would leave two instances that disagree.\n */\nexport function fallbackAlreadyResolvedError(tokenName: string): KickError {\n return new KickError({\n code: 'KICK010',\n summary: `Cannot bind ${tokenName}: its fallback was already resolved`,\n cause: `\\`${tokenName}\\` has a default from \\`container.registerFallback()\\`, and something\nresolved that default before the app bound its own. Code that resolved it holds\nthe fallback instance; the new binding would hand everyone else a different one.`,\n fix: `Bind \\`${tokenName}\\` before anything resolves it — in a module's\n\\`register(container)\\` or a plugin's \\`register()\\`, not later in a request or\nan \\`afterStart\\` hook. If an adapter resolves the token while booting (in\n\\`beforeMount\\`), resolve it lazily instead (in \\`beforeStart\\` or on first use).`,\n docsUrl: `${DOCS_BASE}/guide/dependency-injection#fallback-bindings`,\n context: { token: tokenName },\n })\n}\n\n// ── Config / env wiring ───────────────────────────────────────────────\n\n/**\n * KICK004 — `@Value('X')` resolved but the env var isn't set and no\n * default was provided.\n *\n * This is the canonical \"you forgot to wire env\" symptom — surfaces\n * when ConfigService can't find the key. The fix usually involves\n * either setting the env var or wiring `loadEnv(envSchema)` at startup.\n */\nexport function envValueMissingError(envKey: string): KickError {\n return new KickError({\n code: 'KICK004',\n summary: `@Value('${envKey}'): environment variable not set and no default provided`,\n cause: `\\`@Value('${envKey}')\\` resolved but the env var isn't present and the\ndecorator didn't declare a default. Possible reasons:\n • The variable is genuinely missing from your environment / .env file.\n • Your \\`src/env.ts\\` calls \\`loadEnv(envSchema)\\` but \\`src/index.ts\\`\n doesn't import \\`./env\\` before \\`bootstrap()\\`. Without that import\n the schema never runs and ConfigService stays empty — \\`@Value\\`\n only finds the var via the \\`process.env\\` fallback.`,\n fix: `Either set the variable in your shell / .env file:\n\n ${envKey}=...\n\nOr add a default at the decorator:\n\n @Value('${envKey}', { default: 'fallback' })\n private value!: string\n\nIf you're using a schema, make sure \\`src/env.ts\\` is imported from\n\\`src/index.ts\\` BEFORE bootstrap runs:\n\n // src/index.ts\n import 'reflect-metadata'\n import './env' // ← this line is required\n import { bootstrap } from '@forinda/kickjs'\n // ...`,\n docsUrl: `${DOCS_BASE}/guide/configuration#wiring-the-schema-at-startup`,\n context: { envKey },\n })\n}\n\n// ── Module setup ──────────────────────────────────────────────────────\n\n/**\n * KICK005 — A module's `routes()` return value declares a mount path\n * but provides neither a `controller` class nor a pre-built `router`.\n */\nexport function moduleRouteMissingControllerError(mountPath: string): KickError {\n return new KickError({\n code: 'KICK005',\n summary: `Module route at ${mountPath} requires either 'controller' or 'router'`,\n cause: `A module's \\`routes()\\` returned an entry for \\`${mountPath}\\` but didn't\nspecify how to build the router. The framework needs either a decorated\ncontroller class (it calls \\`buildRoutes()\\` internally) or a hand-built\nExpress Router.`,\n fix: `Pass \\`controller:\\` for the common case:\n\n routes() {\n return {\n path: '${mountPath}',\n controller: UsersController,\n }\n }\n\nOr pass \\`router:\\` for full control:\n\n routes() {\n return {\n path: '${mountPath}',\n router: myExpressRouter,\n }\n }`,\n docsUrl: `${DOCS_BASE}/guide/modules`,\n context: { mountPath },\n })\n}\n\n/**\n * KICK006 — Two handlers claim the same HTTP verb + mounted path. The\n * engine would silently dispatch one of them (Express/h3: first wins,\n * Fastify: its own throw), while typegen and the typed client may\n * describe the other — so this fails at boot instead.\n */\nexport function duplicateRouteError(\n method: string,\n path: string,\n owner: string,\n prior: string,\n): KickError {\n return new KickError({\n code: 'KICK006',\n summary: `Duplicate route: ${method} ${path} is registered twice`,\n cause: `\\`${owner}\\` registers \\`${method} ${path}\\`, but that verb + path is\nalready claimed by \\`${prior}\\`. Only one handler can win at dispatch\ntime, and which one depends on the engine — while \\`kick typegen\\` and\nthe typed client may describe the other. Param names are ignored when\ncomparing (\\`/:id\\` and \\`/:taskId\\` are the same route).`,\n fix: `Change one of the two paths, remove the duplicate handler, or mount\nthe second controller under a different module path / version:\n\n routes() {\n return { path: '/tasks', controller: TasksController, version: 2 }\n }`,\n docsUrl: `${DOCS_BASE}/guide/modules`,\n context: { method, path, owner, prior },\n })\n}\n\n// ── Server ────────────────────────────────────────────────────────────\n\n/**\n * KICK007 — `server.http2` on a runtime that cannot serve HTTP/2. Express 5\n * does not run on Node's HTTP/2 compatibility layer (requests hang and it\n * throws internally), so this fails at boot rather than on the first request.\n */\nexport function http2UnsupportedRuntimeError(runtime: string): KickError {\n return new KickError({\n code: 'KICK007',\n summary: `The ${runtime} runtime cannot serve HTTP/2`,\n cause: `\\`bootstrap({ server: { http2: true } })\\` asks for an HTTP/2 server, but the\n\\`${runtime}\\` runtime does not support Node's HTTP/2 compatibility layer —\nrequests would hang instead of being answered.`,\n fix: `Pick one:\n • Switch to a runtime that serves HTTP/2:\n bootstrap({ runtime: fastifyRuntime(), server: { tls, http2: true } })\n (or h3Runtime()).\n • Drop \\`http2\\` and keep HTTPS over HTTP/1.1: server: { tls }.\n • Terminate HTTP/2 at your proxy / load balancer and serve HTTP/1.1 to it.`,\n docsUrl: `${DOCS_BASE}/guide/http-runtimes#https-and-http-2`,\n context: { runtime },\n })\n}\n\n/**\n * KICK008 — `server.http2: true` without `server.tls`, or `http2: 'h2c'` with\n * it. Browsers only speak HTTP/2 over TLS, so cleartext HTTP/2 is its own,\n * explicit setting.\n */\nexport function http2RequiresTlsError(h2cWithTls = false): KickError {\n if (h2cWithTls) {\n return new KickError({\n code: 'KICK008',\n summary: \"server.http2: 'h2c' does not take server.tls\",\n cause: `\\`http2: 'h2c'\\` serves cleartext HTTP/2, but \\`tls\\` was set too.`,\n fix: `Use \\`http2: true\\` to serve HTTP/2 over TLS, or drop \\`tls\\` for cleartext HTTP/2.`,\n docsUrl: `${DOCS_BASE}/guide/http-runtimes#https-and-http-2`,\n })\n }\n return new KickError({\n code: 'KICK008',\n summary: 'server.http2 requires server.tls',\n cause: `\\`bootstrap({ server: { http2: true } })\\` was set without \\`tls\\`. Browsers only\nnegotiate HTTP/2 over TLS.`,\n fix: `Pass the certificate and key alongside http2:\n\n server: {\n tls: { key: readFileSync('key.pem'), cert: readFileSync('cert.pem') },\n http2: true,\n }\n\nBehind a proxy or service mesh that speaks cleartext HTTP/2 to the app (gRPC\nthrough Envoy or Linkerd), use \\`http2: 'h2c'\\` instead. Or remove \\`http2\\` if\nthe proxy sends HTTP/1.1.`,\n docsUrl: `${DOCS_BASE}/guide/http-runtimes#https-and-http-2`,\n })\n}\n\n/**\n * KICK009 — `server.tls` cannot identify the server. Node starts an HTTPS /\n * HTTP/2 server without a certificate (or with a key that does not match it)\n * and then fails every TLS handshake, so this is checked at boot instead.\n */\nexport function tlsCredentialsError(problem: string): KickError {\n return new KickError({\n code: 'KICK009',\n summary: `server.tls is not usable: ${problem}`,\n cause: `\\`bootstrap({ server: { tls } })\\` was given TLS options the server cannot use:\n${problem}. Node would start anyway and fail every TLS handshake.`,\n fix: `Give the server an identity:\n • \\`key\\` and \\`cert\\` together (PEM, matching each other), or\n • \\`pfx\\` (with \\`passphrase\\` if it is encrypted), or\n • \\`SNICallback\\` / \\`pskCallback\\` for per-host or PSK setups.\n\n server: { tls: { key: readFileSync('key.pem'), cert: readFileSync('cert.pem') } }`,\n docsUrl: `${DOCS_BASE}/guide/http-runtimes#https-and-http-2`,\n context: { problem },\n })\n}\n","/**\n * Connects the DI core (`@forinda/kickjs-di`) to\n * the framework: catalogued errors, the logger, and `@Asset` injection.\n * Imported by `./container` and `./decorators`, so every kickjs entry that\n * reaches the container installs them.\n */\nimport { Container, type DiErrorCode } from '@forinda/kickjs-di'\n// Slot indirection, NOT `./assets` — that module's eager node:fs import\n// would poison the edge-safe web entry graph (see asset-resolver-slot.ts).\nimport { resolveAssetViaSlot } from './asset-resolver-slot'\nimport { METADATA } from './interfaces'\nimport {\n envValueMissingError,\n fallbackAlreadyResolvedError,\n noProviderError,\n requestScopeMiddlewareMissingError,\n requestScopeOutsideRequestError,\n} from './kick-errors'\nimport { createLogger } from './logger'\n\nconst CATALOGUE: Record<DiErrorCode, (subject: string) => Error> = {\n KICK001: noProviderError,\n KICK002: requestScopeMiddlewareMissingError,\n KICK003: requestScopeOutsideRequestError,\n KICK004: envValueMissingError,\n KICK010: fallbackAlreadyResolvedError,\n}\n\nContainer.setErrorFactory((code, subject) => CATALOGUE[code](subject))\nContainer.setLogger(createLogger('Container'))\nContainer.definePropertyInjector(METADATA.ASSET, ({ assetKey }: { assetKey: string }) => {\n const slash = assetKey.indexOf('/')\n if (slash === -1) {\n throw new Error(\n `@Asset('${assetKey}'): asset key must include a '/' separator (e.g. 'mails/welcome').`,\n )\n }\n const namespace = assetKey.slice(0, slash)\n const key = assetKey.slice(slash + 1)\n return () => resolveAssetViaSlot(namespace, key)\n})\n"],"mappings":";;;;;;;;;;kIAcA,IAAI,KAA6B,KAGjC,SAAgB,kBAAkB,GAAyB,CACzD,KAAO,EACT,CAGA,SAAgB,oBAAoB,UAAmB,IAAsB,CAC3E,GAAI,CAAC,KACH,MAAU,MACR,WAAW,UAAU,GAAG,IAAI,2KAG9B,EAEF,OAAO,KAAK,UAAW,GAAG,CAC5B,CCCA,IAAa,UAAb,cAA+B,KAAM,CACnC,KACA,QACA,MACA,IACA,QACA,QAEA,YAAY,KAAqB,CAC/B,MAAM,gBAAgB,KAAM,CAAE,MAAO,EAAM,CAAC,CAAC,EAC7C,KAAK,KAAO,YACZ,KAAK,KAAO,KAAK,KACjB,KAAK,QAAU,KAAK,QAChB,KAAK,QAAU,IAAA,KAAW,KAAK,MAAQ,KAAK,OAC5C,KAAK,MAAQ,IAAA,KAAW,KAAK,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AEI,IAAI,UAAU,CACnB,KAAM,UACN,QAAS,mCACT,MAAO,4GAEP,IAAK;;;;;;;;;2BAUL,QAAS,GAAG,UAAU,sCACxB,CAAC,CACH,CAOA,SAAgB,oBAAoB,QAA4B,CAC9D,OAAO,IAAI,UAAU,CACnB,KAAM,UACN,QAAS,6BAA6B,UACtC,MAAO;EACT,QAAQ,yDACN,IAAK,6SAML,QAAS,GAAG,UAAU,uCACtB,QAAS,CAAE,OAAQ,CACrB,CAAC,CACH,CCzTA,MAAM,UAA6D,CACjE,QAAS,gBACT,QAAS,mCACT,QAAS,gCACT,QAAS,qBACT,QAAS,4BACX,EAEA,UAAU,iBAAiB,KAAM,UAAY,UAAU,KAAK,CAAC,OAAO,CAAC,EACrE,UAAU,UAAU,aAAa,WAAW,CAAC,EAC7C,UAAU,uBAAuB,SAAS,OAAQ,CAAE,YAAqC,CACvF,IAAM,MAAQ,SAAS,QAAQ,GAAG,EAClC,GAAI,QAAU,GACZ,MAAU,MACR,WAAW,SAAS,mEACtB,EAEF,IAAM,UAAY,SAAS,MAAM,EAAG,KAAK,EACnC,IAAM,SAAS,MAAM,MAAQ,CAAC,EACpC,UAAa,oBAAoB,UAAW,GAAG,CACjD,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"error-handler-D7DLWe1Q.d.mts","names":[],"sources":["../src/http/middleware/error-handler.ts"],"mappings":";;;;;;;;;;;UAUU;EACR;EACA;;EAEA;EACA,SAAS;;;UAWM;EACf;;EAEA;;;;;;;;;;;;;;;;iBAiCc,gBAAgB,kBAAiB,kBAAmB,KAMrD,cAAY,KAAO,iBAAe,sBAAmB;;;;;;;;;;;;;;;;;;;;;iBAuDpD,iBAAY,UACV,KAAO,cAAY,KAAO,iBAAe,sBAAmB"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"helmet-BVuVBl-D.d.mts","names":["Request","Response","NextFunction"],"sources":["../src/http/middleware/helmet.ts"],"mappings":";;;;cAOa;UAEI;;EAEf,kCAAkC;;EAElC;;EAEA;;EAEA;IAAiB;IAAiB;IAA6B;;;EAE/D;;EAEA;;EAEA;;EAEA;;;;;;;;;;;;;;;;iBAiBc,OAAO,UAAS,iBAAkB,KA0B1BA,gBAAO,KAAOC,iBAAQ,MAAQC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index-Blgka75E.d.mts","names":[],"sources":["../src/http/query/types.ts","../src/http/query/parse-query.ts"],"mappings":";;;KACY;cAaC,kBAAgB;UAcZ;EACf;EACA,UAAU;EACV;;UAGe;EACf;EACA;;UAGe;EACf;EACA;EACA;;;;;;;UAQe;EACf,SAAS;EACT,MAAM;EACN,YAAY;EACZ;;;;;;;;;;KAWU,SACV,gBAAgB,8BAChB,sDACE,4BAA4B,KAAK,oBAAoB,UACrD,mBACE,aAEF;EAAkB,eAAe;IAC/B,+BACQ;;;;;;;;;;;;;;;;;;UAqBG,iBACf,gBAAgB,sCACR;EACR,SAAS,MAAM;IAAe,OAAO,SAAS;;EAC9C,MAAM,MAAM;IAAa,OAAO,SAAS;;;;;;;;;;;;;KAa/B,mBAAmB,yBAAyB;UAEvC;EACf;EACA;EACA;;;;;;UAOe;EACf,SAAS;EACT,WAAW;EACX;GACC;;;UAIc,kBAAkB;EACjC,MAAM;EACN;IACE;IACA;IACA;IACA;IACA;IACA;;;;;;EAMF;IAAS;IAAc;IAAqB;;;;KAIlC;;;;;;;;;;;KAYA,iBAAiB,SAAS,eAAe;;UAGpC,YAAY,gBAAgB,kDAAkD,KAC7F,iBAAiB;;EAIjB,QAAQ;;EAER;;;UAIe,sBAAsB;;EAErC;;;;;;EAMA,aAAa,KAAK,MAAM,eAAe;;;UAIxB,wBAAwB;EACvC,MAAM;EACN;IACE;IACA;;IAEA;;;EAGF;IAAS;IAAc;;;;;;;;;;;;;;;;;;;;;;;;;;UA0BR,oBAAoB,eAAe;;WAEzC;;;;;;EAOT,MAAM,QAAQ,aAAa,QAAQ,UAAU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;;;;;;;;;;;;;iBA2BK;;;;;;;iBA8BA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA+CA,kBAAkB,SAChC,QAAQ,0BACS,UAAU,0BAA0B,kBAAkB;;;;;;;;KAqE7D;EACV;EACA;EACA;;;;;;;;;;;KC9lBG,UAAU,qBAAqB,0BAA0B,IAAI,IAAI;;;;;;;KAQjE,YAAY,kBAAkB,KAAK,UAAU,SAAS,QAAQ,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;cA2B3D;;;;;;;;;;;;;;cAcC;;;;;;;;;;EAaZ,IAAI,kBAAkB,SAAS,KAAK,UAAU,KAAK,YAAY,GAAG;;EAElE,IAAI,kBAAkB,SACpB,KAAK,UAAU,IACf,UAAU,YAAY,YAAY,GAAG,MACpC,YAAY,YAAY,GAAG;;;;;;EAU9B,WAAW,0BAA0B,SAAS,uBAAuB,SAAS;;EAK9E;EAMA;EAIA;EAIA;;;;;;UASe,mBAAmB,aAAa;EAC/C,IAAI,yBAAyB,MAAM,KAAK,IAAI,KAAK;EACjD,IAAI,yBAAyB,MAAM,KAAK,GAAG,UAAU,YAAY,KAAK,MAAM,YAAY,KAAK;EAC7F,UAAU,SAAS;EACnB;EACA;EACA;EACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA+Bc,oBAAoB,UAAU,EAAE,gBAAgB,QAAQ;UAuC5D,mBAAkB,EAAA,MAAA"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"interfaces-C6LHcYsg.d.mts","names":[],"sources":["../src/core/interfaces.ts"],"mappings":";;;;;KAeY,aAAa,YAAY,IAAI,QAAQ;;cAGpC;;;;;;;;;;;;;WAEG;WACN;WACW;WACC;WACA;WACC;WACR;WACC;WACD;WACN"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"jobs-BTnyyRY1.mjs","names":[],"sources":["../src/core/jobs.ts"],"sourcesContent":["/**\n * Background jobs, with whatever runs them.\n *\n * `@Job(queue)` / `@Process(name)` only record which method handles which\n * job — the same way `@Cron` only records a schedule. Any job tool turns that\n * into running code in a few lines: subscribe to each queue from\n * {@link listJobQueues}, and hand every job it receives to {@link runJob}.\n *\n * @Job('email')\n * export class EmailJobs {\n * @Process('welcome')\n * async welcome(job: JobLike<{ to: string }>) { await sendWelcome(job.data.to) }\n * }\n *\n * Enqueueing goes through {@link JOB_DISPATCHER}, which the active adapter\n * provides — code that dispatches never names the tool.\n *\n * `@forinda/kickjs-queue` ships a BullMQ adapter (plus RabbitMQ / Kafka /\n * Redis pub-sub providers); the web entry's `queue()` runs Cloudflare Queues.\n */\nimport { Service } from './decorators'\nimport { getClassMeta, getClassMetaOrUndefined, pushClassMeta, setClassMeta } from './metadata'\nimport { reportError } from './observers'\nimport { createLogger } from './logger'\nimport { createToken } from './token'\n\nconst log = createLogger('KickJobs')\n\n/** Metadata keys — the same ones `@forinda/kickjs-queue` used, so existing readers keep working. */\nexport const JOB_META = {\n JOB: 'kick/queue/job',\n PROCESS: 'kick/queue/process',\n} as const\n\n/** What a `@Process` method records. */\nexport interface ProcessDefinition {\n /** Method name on the class. */\n handlerName: string\n /** Job name it handles; `undefined` handles every job in the queue. */\n jobName?: string\n}\n\n/**\n * The least a job tool hands over. Runners pass their own job object through\n * unchanged — BullMQ's `Job`, a Cloudflare message — so a handler can still\n * reach tool-specific fields (`job.attemptsMade`, `job.updateProgress()`).\n */\nexport interface JobLike<Data = unknown> {\n name: string\n data: Data\n id?: string\n}\n\n/**\n * Every `@Job` class, keyed by class name like the DI registry: an HMR\n * re-evaluation replaces the old class instead of leaving both subscribed.\n */\nconst jobClasses = new Map<string, Function>()\n\n/** Mark a class as handling jobs on `queue`. The class is a DI singleton. */\nexport function Job(queue: string): ClassDecorator {\n return (target) => {\n Service()(target)\n setClassMeta(JOB_META.JOB, queue, target)\n jobClasses.set(target.name, target)\n }\n}\n\n/** Mark a method as handling `jobName` — or, without a name, every job its queue gets. */\nexport function Process(jobName?: string): MethodDecorator {\n return (target, propertyKey) => {\n pushClassMeta<ProcessDefinition>(JOB_META.PROCESS, target.constructor, {\n handlerName: propertyKey as string,\n jobName,\n })\n }\n}\n\n/** One handler: its queue, job name (absent for a catch-all), class and method. */\nexport interface JobHandler extends ProcessDefinition {\n queue: string\n target: Function\n}\n\n/**\n * Every `@Process` method of a `@Job` class the container can resolve.\n * Classes it doesn't know (not in a module, or from before an HMR reload)\n * are skipped.\n */\nexport function listJobHandlers(container: { has(token: unknown): boolean }): JobHandler[] {\n const handlers: JobHandler[] = []\n for (const target of jobClasses.values()) {\n if (!container.has(target)) continue\n const queue = getClassMetaOrUndefined<string>(JOB_META.JOB, target)\n if (queue === undefined) continue\n const processes = getClassMeta<ProcessDefinition[]>(JOB_META.PROCESS, target, [])\n if (processes.length === 0) {\n log.warn(`@Job('${queue}') class ${target.name} has no @Process methods`)\n }\n for (const process of processes) handlers.push({ ...process, queue, target })\n }\n return handlers\n}\n\n/** The queues something handles — what a runner subscribes to. */\nexport function listJobQueues(container: { has(token: unknown): boolean }): string[] {\n return [...new Set(listJobHandlers(container).map((h) => h.queue))]\n}\n\n/** Thrown when a queue receives a job no `@Process` method handles. */\nexport class NoJobHandlerError extends Error {\n constructor(\n readonly queue: string,\n readonly jobName: string,\n ) {\n super(`No @Process handler for job \"${jobName}\" on queue \"${queue}\"`)\n this.name = 'NoJobHandlerError'\n }\n}\n\n/**\n * Run one job: pick the `@Process` method for `job.name` (or the queue's\n * catch-all), resolve its class from the container and call it with `job`\n * as given. A failure is reported to the error observers (`source: 'job'`)\n * and rethrown, so the tool's own retry and dead-letter handling still\n * applies. A job nothing handles throws {@link NoJobHandlerError} rather\n * than being acknowledged and lost.\n */\nexport async function runJob(\n container: { has(token: unknown): boolean; resolve(token: unknown): unknown },\n queue: string,\n job: JobLike,\n /** Extra fields for the error report — e.g. the tool's attempt count. */\n report: Record<string, unknown> = {},\n): Promise<unknown> {\n const handlers = listJobHandlers(container).filter((h) => h.queue === queue)\n const handler =\n handlers.find((h) => h.jobName === job.name) ?? handlers.find((h) => h.jobName === undefined)\n try {\n if (!handler) throw new NoJobHandlerError(queue, job.name)\n const instance = container.resolve(handler.target) as Record<string, (j: JobLike) => unknown>\n return await withJobContext(job, () => instance[handler.handlerName]!(job))()\n } catch (err) {\n log.error({ err }, `Job ${queue}/${job.name} failed`)\n reportError(err, { source: 'job', context: { queue, job: job.name, id: job.id, ...report } })\n throw err\n }\n}\n\n/**\n * Something about where a job was dispatched from that its handler should\n * run with — the tenant, a trace id, the acting user. Captured when the job\n * is dispatched, carried in its data, and restored around the handler.\n */\nexport interface JobContextCarrier<T = unknown> {\n /** Unique: the field it travels under. */\n key: string\n /** The value to carry, or `undefined` for nothing. */\n capture(): T | undefined\n /** Run the handler with the value back in place. */\n restore<R>(value: T, run: () => R): R\n}\n\n/** The field a job's data carries its context in. Removed before the handler sees the data. */\nexport const JOB_CONTEXT_FIELD = '__kickContext'\n\nconst jobContextCarriers = new Map<string, JobContextCarrier>()\n\n/** Carry a value from dispatch to handler for every job. Registering a key again replaces it. */\nexport function registerJobContext<T>(carrier: JobContextCarrier<T>): void {\n jobContextCarriers.set(carrier.key, carrier as JobContextCarrier)\n}\n\nconst isPlainObject = (v: unknown): v is Record<string, unknown> =>\n !!v && typeof v === 'object' && Object.getPrototypeOf(v) === Object.prototype\n\n/**\n * `data` with the current job context added — for a {@link JobDispatcher}\n * implementation to call before enqueueing. Any `__kickContext` already in\n * `data` is removed first: only this call may set it, so a dispatcher that\n * enqueues caller-supplied data without it lets that data choose the context. Only plain-object data can carry\n * it; anything else, or nothing to carry, is returned as is.\n */\nexport function stampJobContext<Data>(data: Data): Data {\n if (!isPlainObject(data)) return data\n // Only the dispatcher's own context travels. A caller's data (a request\n // body, say) carrying the field would otherwise pick the job's tenant.\n const { [JOB_CONTEXT_FIELD]: _untrusted, ...rest } = data\n const context: Record<string, unknown> = {}\n for (const [key, carrier] of jobContextCarriers) {\n const value = carrier.capture()\n if (value !== undefined) context[key] = value\n }\n const stamped = Object.keys(context).length > 0 ? { ...rest, [JOB_CONTEXT_FIELD]: context } : rest\n return stamped as Data\n}\n\n/** Take the carried context off the job's data, and wrap `run` in every restore. */\nfunction withJobContext<R>(job: JobLike, run: () => R): () => R {\n const data = job.data\n if (!isPlainObject(data) || !(JOB_CONTEXT_FIELD in data)) return run\n const context = data[JOB_CONTEXT_FIELD]\n delete data[JOB_CONTEXT_FIELD]\n // Only an object of carrier keys is context; anything else is dropped.\n if (!isPlainObject(context)) return run\n let wrapped = run\n for (const [key, value] of Object.entries(context)) {\n const carrier = jobContextCarriers.get(key)\n if (!carrier) continue\n const inner = wrapped\n wrapped = () => carrier.restore(value, inner)\n }\n return wrapped\n}\n\n/** Enqueue a job — implemented by whichever adapter runs the jobs. */\nexport interface JobDispatcher {\n dispatch<Data = unknown>(\n queue: string,\n name: string,\n data: Data,\n options?: Record<string, unknown>,\n ): Promise<unknown>\n}\n\n/**\n * The active job dispatcher. Inject it to enqueue without naming the tool:\n * `@Inject(JOB_DISPATCHER) private jobs!: JobDispatcher`.\n */\nexport const JOB_DISPATCHER = createToken<JobDispatcher>('kick/jobs/Dispatcher')\n"],"mappings":";;;;;;;;;;0TA0BA,MAAM,IAAM,aAAa,UAAU,EAGtB,SAAW,CACtB,IAAK,iBACL,QAAS,oBACX,EAyBM,2BAAa,IAAI,IAGvB,SAAgB,IAAI,MAA+B,CACjD,MAAQ,SAAW,CACjB,QAAQ,CAAC,CAAC,MAAM,EAChB,aAAa,SAAS,IAAK,MAAO,MAAM,EACxC,WAAW,IAAI,OAAO,KAAM,MAAM,CACpC,CACF,CAGA,SAAgB,QAAQ,QAAmC,CACzD,OAAQ,OAAQ,cAAgB,CAC9B,cAAiC,SAAS,QAAS,OAAO,YAAa,CACrE,YAAa,YACb,OACF,CAAC,CACH,CACF,CAaA,SAAgB,gBAAgB,UAA2D,CACzF,IAAM,SAAyB,CAAC,EAChC,IAAK,IAAM,UAAU,WAAW,OAAO,EAAG,CACxC,GAAI,CA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,IACA,UAAU,4BAWR;iBAEQ,QAAQ,iBAAiB,SAAS;;;;;;;;cAerC;;UAGI;GACd,SAAS,KAAK,wBAAwB;;iBAGzB,cAAc,iBAAiB,SAAS;;;;;;;;;;;;;;iBAqBxC,mBACd,KAAK,gBACL,4BACW;;;;;;;;;;;;;;;;;iBCnIG,UAAU,SAAS;;;;;iBAiBb,wBAAwB;;;;;;UAc7B;EACf,WAAW,SAAS;;;;;;;;;;;iBCrCN,cAAc,iBAAiB;;;UCvB9B;;EAEf;;EAEA;;EAEA;;EAEA;;;;;;;;;;;;;;;;;;;;;;;EAuBA,gBAAgB,KAAK;;EAErB;;;;;;EAMA,QAAQ;;EAER,QAAQ,KAAK;;;;;;;;;;;;;;;;EAgBb,aAAa;;;;;;;;;;;;;;;;;iBAoDC,eAAe,UAAS,wBAA6B;;;;;;;;;;;;;;;;;;;UCnGpD;EACf,IAAI,cAAc;EAClB,IAAI,aAAa,eAAe;IAAY;MAA2B;EACvE,OAAO,cAAc;;UAQN;;EAEf;;EAEA;;;;;;;;;;;;cAaW,4BAA4B;mBAKpB;mBAJF;mBACA;EAEjB,YACmB,IAAI,QACrB,SAAS;EAML,UAAU,cAAc;IAAU;IAAmB,WAAW;;EAahE,UAAU,cAAc;EAQxB,MAAM,cAAc;UAIZ;UAUA;;UAOC;;EAEf;;;;;;;;;;;;cAaW,0BAA0B;mBAIlB;mBAHF;EAEjB,YACmB,IAAI,QACrB,UAAS;EAKL,IAAI,cAAc,QAAQ;EAU1B,IAAI,aAAa,MAAM,aAAa,iBAAiB;EAMrD,QAAQ,cAAc;EAItB,MAAM,aAAa,iBAAiB"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"kv-stores-HUdUibOx.mjs","names":[],"sources":["../src/http/middleware/rate-limit-guard.ts","../src/http/middleware/kv-stores.ts"],"sourcesContent":["// Ctx-style rate limiter — runs on BOTH pipelines: the node runtimes (via\n// `@Middleware()` / class middleware) and the `@forinda/kickjs/web` fetch\n// entry (via `@Middleware()` or `createWebApp({ middleware })`), unlike the\n// connect-style `rateLimit()` which is node-only. Zero runtime imports —\n// part of the edge purity graph.\nimport { assertFlagTest, matchesFlagTest, type RouteFlagTest } from '../../core/route-flag'\nimport type { MiddlewareHandler } from '../../core/decorators'\nimport type { RequestContext } from '../context'\nimport type { RateLimitStore } from './rate-limit'\nimport { BoundedCounters } from './bounded-counters'\n\nexport interface RateLimitGuardOptions {\n /** Maximum number of requests per window (default: 100). */\n max?: number\n /** Time window in milliseconds (default: 60_000). */\n windowMs?: number\n /** Response message when the limit is exceeded (default: 'Too Many Requests'). */\n message?: string\n /** HTTP status code when the limit is exceeded (default: 429). */\n statusCode?: number\n /**\n * Rate-limit key per request. Defaults to `ctx.ip`, falling back to\n * `'global'`. Return a user/tenant id here for authenticated quotas.\n *\n * ::: warning Behind a proxy, configure `trustProxy` or every client shares\n * one bucket\n * On a node runtime `ctx.ip` is the runtime's vetted client address —\n * Express derives it from `trust proxy`, Fastify from `trustProxy`. Without\n * that setting it is the SOCKET address, which behind a load balancer or\n * Cloudflare is the proxy's, so every caller lands in the same bucket and one\n * noisy client exhausts the allowance for everyone.\n *\n * `bootstrap({ trustProxy: true })` is the fix. Forwarded headers are\n * deliberately not consulted here: `x-forwarded-for` is client-controllable\n * unless a proxy overwrites it, so trusting it unconditionally would let a\n * direct caller mint a fresh allowance per request by varying the header —\n * evading the limit rather than enforcing it. The header chain\n * (`cf-connecting-ip` → `x-forwarded-for` → `x-real-ip`) applies only on the\n * `@forinda/kickjs/web` edge entry, where there is no socket and the platform\n * has already terminated the connection.\n * :::\n */\n keyGenerator?: (ctx: RequestContext) => string\n /** Send `X-RateLimit-*` / `Retry-After` headers (default: true). */\n headers?: boolean\n /**\n * Counter backend. Defaults to a per-isolate in-memory map — fine for a\n * single node process, useless on edge where isolates recycle: pass a\n * `KvRateLimitStore` (or Redis-backed store) there.\n */\n store?: RateLimitStore\n /** Skip limiting for a request (health checks, allowlists). */\n skip?: (ctx: RequestContext) => boolean\n /**\n * Skip limiting on routes carrying a route flag — a name, a list of names\n * (any-of), or a predicate. Declared on the route rather than restated as a\n * path here, so it cannot drift when `apiPrefix` or a module's `version`\n * changes:\n *\n * ```ts\n * const Public = defineRouteFlag('auth.public')\n * rateLimitGuard({ max: 60, exemptWhen: 'auth.public' })\n * ```\n *\n * Only meaningful where a route has been matched — as `@Middleware()` on a\n * class or method, or in `createWebApp({ middleware })`. Mounted app-wide\n * ahead of routing there is no route to read, and nothing is exempted.\n */\n exemptWhen?: RouteFlagTest\n}\n\n/**\n * Timer-free in-memory store: expired windows are swept on insert, from the\n * front. Bounded: see {@link BoundedCounters}.\n *\n * @internal Exported for tests.\n */\nexport class LazyMemoryStore implements RateLimitStore {\n private readonly counters: BoundedCounters\n\n /** @param limit The `max` it enforces, so it never evicts a counter at the limit. */\n constructor(windowMs: number, limit?: number) {\n this.counters = new BoundedCounters(windowMs, limit)\n }\n\n async increment(key: string): Promise<{ totalHits: number; resetTime: Date }> {\n return this.counters.increment(key)\n }\n\n async decrement(key: string): Promise<void> {\n this.counters.decrement(key)\n }\n\n async reset(key: string): Promise<void> {\n this.counters.reset(key)\n }\n}\n\nfunction defaultKey(ctx: RequestContext): string {\n // `ctx.ip` carries the resolution that used to live here: prefer the\n // runtime-computed address (Express derives it from `trust proxy`), fall\n // back to forwarded headers only for runtimes that compute none.\n return ctx.ip ?? 'global'\n}\n\n/**\n * Rate limiting as a `(ctx, next)` middleware.\n *\n * ```ts\n * // Edge (Cloudflare Workers) — app-wide:\n * const app = createWebApp({\n * h3, modules,\n * middlewares: [rateLimitGuard({ max: 60, windowMs: 60_000, store: new KvRateLimitStore(env.KV, { windowMs: 60_000 }) })],\n * })\n *\n * // Any runtime — per controller/route:\n * @Middleware(rateLimitGuard({ max: 10 }))\n * @Post('/login')\n * ```\n */\nexport function rateLimitGuard(options: RateLimitGuardOptions = {}): MiddlewareHandler {\n const max = options.max ?? 100\n const windowMs = options.windowMs ?? 60_000\n const message = options.message ?? 'Too Many Requests'\n const statusCode = options.statusCode ?? 429\n const keyGenerator = options.keyGenerator ?? defaultKey\n const sendHeaders = options.headers ?? true\n const store = options.store ?? new LazyMemoryStore(windowMs, max)\n\n const exemptWhen = options.exemptWhen\n if (exemptWhen !== undefined) assertFlagTest(exemptWhen, 'rateLimitGuard({ exemptWhen })')\n\n return async (ctx: RequestContext, next: () => void): Promise<void> => {\n if (options.skip?.(ctx)) return next()\n if (exemptWhen !== undefined && matchesFlagTest(exemptWhen, ctx.route?.flags, ctx.route)) {\n return next()\n }\n\n const { totalHits, resetTime } = await store.increment(keyGenerator(ctx))\n const remaining = Math.max(0, max - totalHits)\n\n if (sendHeaders) {\n ctx.setHeader('X-RateLimit-Limit', String(max))\n ctx.setHeader('X-RateLimit-Remaining', String(remaining))\n ctx.setHeader('X-RateLimit-Reset', String(Math.ceil(resetTime.getTime() / 1000)))\n }\n\n if (totalHits > max) {\n const retryAfter = Math.max(1, Math.ceil((resetTime.getTime() - Date.now()) / 1000))\n if (sendHeaders) ctx.setHeader('Retry-After', String(retryAfter))\n ctx.json({ message }, statusCode)\n return\n }\n\n next()\n }\n}\n","// Edge-safe store adapters over a minimal KV surface. Zero runtime imports —\n// this file must stay importable from the `@forinda/kickjs/web` purity graph.\nimport type { RateLimitStore } from './rate-limit'\nimport type { SessionData, SessionStore } from './session'\n\n/**\n * The minimal async KV surface both stores need. Structurally compatible\n * with a Cloudflare Workers `KVNamespace` binding — pass it straight in:\n *\n * ```ts\n * export default {\n * fetch(req: Request, env: Env) {\n * const store = new KvRateLimitStore(env.MY_KV, { windowMs: 60_000 })\n * // ...\n * },\n * }\n * ```\n *\n * Anything with the same shape works too (Deno KV wrapper, Upstash Redis\n * REST client adapter, a Map-backed fake in tests).\n */\nexport interface KvLike {\n get(key: string): Promise<string | null>\n put(key: string, value: string, options?: { expirationTtl?: number }): Promise<void>\n delete(key: string): Promise<void>\n}\n\n/** Cloudflare KV rejects TTLs under 60 seconds — clamp up, never down. */\nfunction kvTtlSeconds(ms: number): number {\n return Math.max(60, Math.ceil(ms / 1000))\n}\n\nexport interface KvRateLimitStoreOptions {\n /** Window length in ms — must match the `windowMs` given to the limiter. */\n windowMs: number\n /** Key prefix in the KV namespace (default `'rl:'`). */\n prefix?: string\n}\n\n/**\n * {@link RateLimitStore} over a {@link KvLike} namespace, for edge deployments\n * where in-memory counters reset on every isolate.\n *\n * KV is eventually consistent and this is a read-modify-write counter, so\n * limiting is **approximate** under concurrency — bursts racing across\n * isolates can each read the same count. That is the accepted trade-off for\n * abuse throttling; use a Durable Object / Redis store when you need an\n * exact ceiling (billing quotas, strict per-key locks).\n */\nexport class KvRateLimitStore implements RateLimitStore {\n private readonly prefix: string\n private readonly windowMs: number\n\n constructor(\n private readonly kv: KvLike,\n options: KvRateLimitStoreOptions,\n ) {\n this.windowMs = options.windowMs\n this.prefix = options.prefix ?? 'rl:'\n }\n\n async increment(key: string): Promise<{ totalHits: number; resetTime: Date }> {\n const now = Date.now()\n const entry = await this.read(key)\n if (entry && entry.reset > now) {\n entry.hits++\n await this.write(key, entry)\n return { totalHits: entry.hits, resetTime: new Date(entry.reset) }\n }\n const fresh = { hits: 1, reset: now + this.windowMs }\n await this.write(key, fresh)\n return { totalHits: 1, resetTime: new Date(fresh.reset) }\n }\n\n async decrement(key: string): Promise<void> {\n const entry = await this.read(key)\n if (entry && entry.hits > 0) {\n entry.hits--\n await this.write(key, entry)\n }\n }\n\n async reset(key: string): Promise<void> {\n await this.kv.delete(this.prefix + key)\n }\n\n private async read(key: string): Promise<{ hits: number; reset: number } | null> {\n const raw = await this.kv.get(this.prefix + key)\n if (raw === null) return null\n try {\n return JSON.parse(raw) as { hits: number; reset: number }\n } catch {\n return null\n }\n }\n\n private async write(key: string, entry: { hits: number; reset: number }): Promise<void> {\n await this.kv.put(this.prefix + key, JSON.stringify(entry), {\n expirationTtl: kvTtlSeconds(Math.max(entry.reset - Date.now(), 1000)),\n })\n }\n}\n\nexport interface KvSessionStoreOptions {\n /** Key prefix in the KV namespace (default `'sess:'`). */\n prefix?: string\n}\n\n/**\n * {@link SessionStore} over a {@link KvLike} namespace. Plug into the node\n * `session()` middleware today (e.g. backed by Upstash/Cloudflare KV via\n * REST) so sessions survive restarts and horizontal scaling; TTL expiry is\n * delegated to the KV layer via `expirationTtl`.\n *\n * Cost note: `touch()` is a get + put round-trip (KvLike has no TTL-only\n * refresh), so `session({ rolling: true })` doubles KV operations per\n * request — per-operation-billed platforms may prefer `rolling: false`.\n */\nexport class KvSessionStore implements SessionStore {\n private readonly prefix: string\n\n constructor(\n private readonly kv: KvLike,\n options: KvSessionStoreOptions = {},\n ) {\n this.prefix = options.prefix ?? 'sess:'\n }\n\n async get(sid: string): Promise<SessionData | null> {\n const raw = await this.kv.get(this.prefix + sid)\n if (raw === null) return null\n try {\n return JSON.parse(raw) as SessionData\n } catch {\n return null\n }\n }\n\n async set(sid: string, data: SessionData, maxAge: number): Promise<void> {\n await this.kv.put(this.prefix + sid, JSON.stringify(data), {\n expirationTtl: kvTtlSeconds(maxAge),\n })\n }\n\n async destroy(sid: string): Promise<void> {\n await this.kv.delete(this.prefix + sid)\n }\n\n async touch(sid: string, maxAge: number): Promise<void> {\n const data = await this.get(sid)\n if (data !== null) await this.set(sid, data, maxAge)\n }\n}\n"],"mappings":";;;;;;;;;;kJA6EA,IAAa,gBAAb,KAAuD,CACrD,SAGA,YAAY,SAAkB,MAAgB,CAC5C,KAAK,SAAW,IAAI,gBAAgB,SAAU,KAAK,CACrD,CAEA,MAAM,UAAU,IAA8D,CAC5E,OAAO,KAAK,SAAS,UAAU,GAAG,CACpC,CAEA,MAAM,UAAU,IAA4B,CAC1C,KAAK,SAAS,UAAU,GAAG,CAC7B,CAEA,MAAM,MAAM,IAA4B,CACtC,KAAK,SAAS,MAAM,GAAG,CACzB,CACF,EAEA,SAAS,WAAW,IAA6B,CAI/C,OAAO,IAAI,IAAM,QACnB,CAiBA,SAAgB,eAAe,QAAiC,CAAC,EAAsB,CACrF,IA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AS;;UAQ5B;;cAMI;;;;;;;;;;;SAkBL,YAAY,UAAU;;SAOtB,eAAe;;;;;SAQf;;SAOA,IAAI,eAAe;;EAU1B,MAAM,eAAe;;;;;;EAMrB,MAAM,QAAQ,0BAA0B;EAMxC,KAAK,gBAAgB;EAIrB,KAAK,gBAAgB;;EAKrB,MAAM,cAAc,gBAAgB;;EAEpC,MAAM,gBAAgB;;EAEtB,MAAM;EA8BN,MAAM,gBAAgB;EAItB,MAAM,gBAAgB;EAKtB,MAAM,gBAAgB;;;;;;;;;;;iBAeR,cAAc,cAAc;;iBA+B5B,aAAa,eAAe"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"observers-C4bWQTop.mjs","names":[],"sources":["../src/core/observers.ts"],"sourcesContent":["/**\n * One place every error and every response is reported to — so an error\n * tracker, a metrics exporter, or an APM integration hooks in once instead of\n * replacing the error handler and patching each source.\n *\n * Observers are adapters and plugins with `onError` / `onResponse`, plus\n * whatever the Node server's tracing channels publish (see `http/tracing.ts`).\n * Observe-only: they cannot change the response, and one that throws is\n * logged and skipped — it never breaks a request or another observer.\n *\n * Free of `node:` imports: `waitUntil` (shared with the web entry) reports\n * through here.\n *\n * @module @forinda/kickjs/core/observers\n */\nimport { createLogger } from './logger'\n\nconst log = createLogger('Observers')\n\n/** Where an error came from. Integrations may report their own sources. */\nexport type ErrorSource =\n | 'request'\n | 'uncaught'\n | 'unhandled-rejection'\n | 'background'\n | 'job'\n | (string & {})\n\nexport interface ErrorInfo {\n source: ErrorSource\n requestId?: string\n method?: string\n /** The request URL path, as received. */\n path?: string\n /** The matched route pattern, e.g. `/api/v1/users/:id`, when one matched. */\n route?: string\n /** The status the error was answered with, for request errors. */\n status?: number\n /** Anything else the reporter knows — a queue and job name, a cron schedule. */\n context?: Record<string, unknown>\n}\n\nexport interface ResponseInfo {\n method: string\n path: string\n /** The matched route pattern, or undefined when no route matched (404s). */\n route?: string\n status: number\n durationMs: number\n requestId?: string\n}\n\nexport interface Observer {\n name?: string\n onError?(error: unknown, info: ErrorInfo): void | Promise<void>\n onResponse?(info: ResponseInfo): void | Promise<void>\n}\n\nlet observers: readonly Observer[] = []\nlet publisher: Observer | undefined\nlet publisherWantsResponses: () => boolean = () => false\n\n/**\n * Replace the observer set — called by the Application from its adapters and\n * plugins. Returns the installed set, so its owner can later release exactly\n * that set (see {@link releaseObservers}).\n */\nexport function setObservers(list: readonly Observer[]): readonly Observer[] {\n observers = list.filter((o) => o.onError || o.onResponse)\n return observers\n}\n\n/**\n * Clear the observer set — but only if it is still the one `installed`. The\n * set is process-wide: a newer Application may have replaced it, and an older\n * one shutting down must not clear the newer one's observers.\n */\nexport function releaseObservers(installed: readonly Observer[]): void {\n if (observers === installed) observers = []\n}\n\n/**\n * The Node server's tracing channels, fed from the same reports. `wantsResponses`\n * is checked per request: a channel can gain a subscriber at any time.\n */\nexport function setObserverPublisher(\n next: Observer | undefined,\n wantsResponses: () => boolean = () => false,\n): void {\n publisher = next\n publisherWantsResponses = wantsResponses\n}\n\n/** Whether anything is listening for responses — lets the server skip timing work. */\nexport function hasResponseObservers(): boolean {\n return observers.some((o) => o.onResponse) || publisherWantsResponses()\n}\n\nfunction notify(pick: (o: Observer) => void | Promise<void> | undefined, what: string): void {\n for (const observer of publisher ? [...observers, publisher] : observers) {\n try {\n const result = pick(observer)\n if (result && typeof (result as Promise<void>).catch === 'function') {\n ;(result as Promise<void>).catch((err: unknown) => failed(observer, what, err))\n }\n } catch (err) {\n failed(observer, what, err)\n }\n }\n}\n\nfunction failed(observer: Observer, what: string, err: unknown): void {\n // Logged directly, never re-reported: an observer failing inside onError\n // must not loop back into onError. Guarded too: a custom LoggerProvider that\n // throws would otherwise escape reportError() — or, from an async\n // observer, become an unhandled rejection that bootstrap reports right back\n // here.\n try {\n log.error({ err }, `${observer.name ?? 'observer'}.${what} threw — skipped`)\n } catch {\n // Nothing left to tell; reportError's \"never throws\" contract wins.\n }\n}\n\n/**\n * Report an error to every observer. The framework calls this for request\n * errors, uncaught exceptions, unhandled rejections, `waitUntil` failures and\n * queue job failures; call it from your own integrations too (a cron runner,\n * a message consumer). Never throws.\n */\nexport function reportError(error: unknown, info: ErrorInfo): void {\n notify((o) => o.onError?.(error, info), 'onError')\n}\n\n/** Report a finished response to every observer. Never throws. */\nexport function reportResponse(info: ResponseInfo): void {\n notify((o) => o.onResponse?.(info), 'onResponse')\n}\n"],"mappings":";;;;;;;;;;4CAiBA,MAAM,IAAM,aAAa,WAAW,EAyCpC,IAAI,UAAiC,CAAC,EAClC,UACA,4BAA+C,GAOnD,SAAgB,aAAa,KAAgD,CAE3E,MADA,WAAY,KAAK,OAAQ,GAAM,EAAE,SAAW,EAAE,UAAU,EACjD,SACT,CAOA,SAAgB,iBAAiB,UAAsC,CACjE,YAAc,YAAW,UAAY,CAAC,EAC5C,CAMA,SAAgB,qBACd,KACA,mBAAsC,GAChC,CACN,UAAY,KACZ,wBAA0B,cAC5B,CAGA,SAAgB,sBAAgC,CAC9C,OAAO,UAAU,KAAM,GAAM,EAAE,UAAU,GAAK,wBAAwB,CACxE,CAEA,SAAS,OAAO,KAAyD,KAAoB,CAC3F,IAAK,IAAM,YAAY,UAAY,CAAC,GAAG,UAAW,SAAS,EAAI,UAC7D,GAAI,CACF,IAAM,OAAS,KAAK,QAAQ,EACxB,QAAU,OAAQ,OAAyB,OAAU,YACtD,OAA0B,MAAO,KAAiB,OAAO,SAAU,KAAM,GAAG,CAAC,CAElF,OAAS,IAAK,CACZ,OAAO,SAAU,KAAM,GAAG,CAC5B,CAEJ,CAEA,SAAS,OAAO,SAAoB,KAAc,IAAoB,CAMpE,GAAI,CACF,IAAI,MAAM,CAAE,GAAI,EAAG,GAAG,SAAS,MAAQ,WAAW,GAAG,KAAK,iBAAiB,CAC7E,MAAQ,CAER,CACF,CAQA,SAAgB,YAAY,MAAgB,KAAuB,CACjE,OAAQ,GAAM,EAAE,UAAU,MAAO,IAAI,EAAG,SAAS,CACnD,CAGA,SAAgB,eAAe,KAA0B,CACvD,OAAQ,GAAM,EAAE,aAAa,IAAI,EAAG,YAAY,CAClD"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"path-CMwIHsdv.d.mts","names":[],"sources":["../src/core/path.ts"],"mappings":";;;;;;;;;iBAOgB,cAAc;;;;;;;;;;;;iBAsBd,aAAa;;;;;;;;;iBAmBb,eAAe,mBAAmB,yBAAyB"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"query-DXIo1mII.mjs","names":[],"sources":["../src/http/query/types.ts","../src/http/query/parse-query.ts"],"sourcesContent":["/** Supported filter operators for query string parsing */\nexport type FilterOperator =\n | 'eq'\n | 'neq'\n | 'gt'\n | 'gte'\n | 'lt'\n | 'lte'\n | 'between'\n | 'in'\n | 'contains'\n | 'starts'\n | 'ends'\n\nexport const FILTER_OPERATORS = new Set<string>([\n 'eq',\n 'neq',\n 'gt',\n 'gte',\n 'lt',\n 'lte',\n 'between',\n 'in',\n 'contains',\n 'starts',\n 'ends',\n])\n\nexport interface FilterItem {\n field: string\n operator: FilterOperator\n value: string\n}\n\nexport interface SortItem {\n field: string\n direction: 'asc' | 'desc'\n}\n\nexport interface PaginationParams {\n page: number\n limit: number\n offset: number\n}\n\n/**\n * The result of parsing a query string. ORM-agnostic — pass this to\n * a query builder adapter (Drizzle, Prisma, Sequelize, etc.) to produce\n * database-specific query objects.\n */\nexport interface ParsedQuery {\n filters: FilterItem[]\n sort: SortItem[]\n pagination: PaginationParams\n search: string\n}\n\n/**\n * Helper that extracts the literal field union from a `QueryFieldConfig`\n * key. When the user passes `{ filterable: ['status', 'category'] } as const`,\n * `FieldsOf<typeof config, 'filterable'>` resolves to `'status' | 'category'`.\n *\n * Without `as const`, the arrays widen to `string[]` and the union falls\n * back to `string`. This is the documented escape hatch.\n */\nexport type FieldsOf<\n TConfig extends QueryFieldConfig | undefined,\n K extends 'filterable' | 'sortable' | 'searchable',\n> = TConfig extends { readonly [P in K]: readonly (infer F)[] }\n ? F extends string\n ? F\n : string\n : TConfig extends { columns: infer C }\n ? K extends 'filterable'\n ? keyof C & string\n : string\n : string\n\n/**\n * Narrowed `ParsedQuery` whose `filters[].field` and `sort[].field`\n * unions are constrained to the literal whitelist passed to\n * `ctx.qs()` / `parseQuery()`. Extends `ParsedQuery`, so any function\n * accepting `ParsedQuery` accepts a `TypedParsedQuery<X>` automatically\n * (subtype assignment, no codegen, backward compatible).\n *\n * @example\n * ```ts\n * const parsed = ctx.qs({\n * filterable: ['status', 'priority'],\n * sortable: ['createdAt'],\n * } as const)\n * parsed.filters[0]?.field // 'status' | 'priority'\n * parsed.sort[0]?.field // 'createdAt'\n * ```\n */\nexport interface TypedParsedQuery<\n TConfig extends QueryFieldConfig | undefined,\n> extends ParsedQuery {\n filters: Array<FilterItem & { field: FieldsOf<TConfig, 'filterable'> }>\n sort: Array<SortItem & { field: FieldsOf<TConfig, 'sortable'> }>\n}\n\n/**\n * Restrict which fields can be filtered, sorted, or searched.\n * Fields not in the allow-list are silently ignored.\n *\n * Accepts two forms:\n * 1. **String arrays** (standard): `{ filterable: ['name', 'status'], sortable: ['createdAt'] }`\n * 2. **Column-object maps** (Drizzle-style): `{ columns: { name: col, status: col }, sortable: { createdAt: col } }`\n *\n * When column-object maps are provided, `Object.keys()` is used to derive the field names.\n */\nexport type QueryFieldConfig = StringQueryFieldConfig | ColumnQueryFieldConfig\n\nexport interface StringQueryFieldConfig {\n filterable?: string[]\n sortable?: string[]\n searchable?: string[]\n}\n\n/**\n * Column-object-based field config (e.g., from DrizzleQueryParamsConfig).\n * Keys are the field names used in query strings; values are ORM column references.\n */\nexport interface ColumnQueryFieldConfig {\n columns: Record<string, any>\n sortable?: Record<string, any>\n searchColumns?: any[]\n [key: string]: any\n}\n\n/** Standardized paginated response shape */\nexport interface PaginatedResponse<T = any> {\n data: T[]\n meta: {\n page: number\n limit: number\n total: number\n totalPages: number\n hasNext: boolean\n hasPrev: boolean\n }\n /**\n * Relative links (path + query, never a host) to this page and its\n * neighbours. `next` / `prev` are `null` at the ends.\n */\n links: { self: string; next: string | null; prev: string | null }\n}\n\n/** A JSON primitive stored in a cursor. Dates arrive as ISO strings. */\nexport type CursorValue = string | number | boolean | null\n\n/**\n * Where the previous page ended: the last row's values for the active sort\n * fields plus the id tie-breaker, keyed by field name — e.g.\n * `{ createdAt: '2026-01-01T00:00:00.000Z', id: 'u7' }`.\n *\n * Decoded from a client-supplied cursor and NOT signed: treat it as untrusted\n * input. Bind the values as query parameters and keep filters / authorization\n * scoping in the fetcher, so a forged cursor can only move the position,\n * never widen what the caller may see.\n */\nexport type CursorPosition = Readonly<Record<string, CursorValue>>\n\n/** What `ctx.paginateCursor()` hands its fetcher. */\nexport interface CursorQuery<TConfig extends QueryFieldConfig | undefined = undefined> extends Omit<\n TypedParsedQuery<TConfig>,\n 'pagination'\n> {\n /** `null` on the first page. */\n cursor: CursorPosition | null\n /** Page size. Fetch `limit + 1` rows — the extra one tells whether a next page exists. */\n limit: number\n}\n\n/** Options for `ctx.paginateCursor()`. */\nexport interface CursorPaginateOptions<T = any> {\n /** Unique, stable tie-breaker field read off each row. Default `'id'`. */\n idField?: string\n /**\n * Build the cursor values from a row yourself, instead of reading the sort\n * fields + `idField` off it (e.g. when the row shape differs from the\n * sortable field names). Values must be JSON primitives.\n */\n cursorKey?: (row: T) => Record<string, CursorValue>\n}\n\n/** Standardized cursor (keyset) paginated response shape */\nexport interface CursorPaginatedResponse<T = any> {\n data: T[]\n meta: {\n limit: number\n hasNext: boolean\n /** Opaque; pass back as `?cursor=` for the next page. `null` on the last page. */\n nextCursor: string | null\n }\n /** Relative links (path + query, never a host); `next` is `null` on the last page. */\n links: { self: string; next: string | null }\n}\n\n/**\n * Interface for ORM-specific query builder adapters.\n * Implement this to translate a `ParsedQuery` into your ORM's query format.\n *\n * @example\n * ```ts\n * // Drizzle adapter\n * class DrizzleQueryAdapter implements QueryBuilderAdapter<DrizzleQueryResult> {\n * build(parsed: ParsedQuery, config: DrizzleConfig): DrizzleQueryResult {\n * // Convert filters → Drizzle SQL conditions\n * // Convert sort → Drizzle orderBy\n * return { where, orderBy, limit, offset }\n * }\n * }\n *\n * // Prisma adapter\n * class PrismaQueryAdapter implements QueryBuilderAdapter<PrismaQueryResult> {\n * build(parsed: ParsedQuery, config: PrismaConfig): PrismaQueryResult {\n * return { where, orderBy, skip, take }\n * }\n * }\n * ```\n */\nexport interface QueryBuilderAdapter<TResult = any, TConfig = any> {\n /** Human-readable name for debugging */\n readonly name: string\n\n /**\n * Convert a ParsedQuery into an ORM-specific query object.\n * @param parsed - The ORM-agnostic parsed query\n * @param config - ORM-specific configuration (column maps, search columns, etc.)\n */\n build(parsed: ParsedQuery, config: TConfig): TResult\n}\n","import {\n FILTER_OPERATORS,\n type FilterItem,\n type FilterOperator,\n type SortItem,\n type PaginationParams,\n type ParsedQuery,\n type QueryFieldConfig,\n type StringQueryFieldConfig,\n type TypedParsedQuery,\n} from './types'\n\n// ── Configurable defaults ───────────────────────────────────────────────\n\n/**\n * Why a rejected field/value was dropped. Surfaced through\n * {@link ParseQueryOptions.onReject} so a caller can warn, count, or\n * return a 400 instead of the historical silent drop.\n */\nexport type QueryRejectReason = 'field-not-allowed' | 'unknown-operator' | 'truncated'\n\nexport interface QueryRejection {\n kind: 'filter' | 'sort' | 'search'\n field: string\n reason: QueryRejectReason\n}\n\nexport interface ParseQueryOptions {\n /** Hard cap on `limit`. Default: global (100, override via {@link setQueryParsingDefaults}). */\n maxLimit?: number\n /** `limit` when the query omits one. Default: global (20). */\n defaultLimit?: number\n /** Max `q` length before truncation. Default: global (200). */\n maxSearchLength?: number\n /**\n * Called once per dropped filter/sort field or truncated search.\n * The historical behaviour is a silent drop; wire this to a logger or\n * a 400 to make over-broad / typo'd queries visible.\n */\n onReject?: (rejection: QueryRejection) => void\n}\n\ninterface QueryParsingDefaults {\n maxLimit: number\n defaultLimit: number\n maxSearchLength: number\n defaultPage: number\n}\n\nconst BUILTIN_DEFAULTS: QueryParsingDefaults = {\n maxLimit: 100,\n defaultLimit: 20,\n maxSearchLength: 200,\n defaultPage: 1,\n}\n\nconst defaults: QueryParsingDefaults = { ...BUILTIN_DEFAULTS }\n\n/**\n * Globally override the query-parsing limits — call once at bootstrap.\n * Per-call {@link ParseQueryOptions} still take precedence over these.\n */\nexport function setQueryParsingDefaults(\n partial: Partial<Omit<QueryParsingDefaults, 'defaultPage'>>,\n): void {\n if (partial.maxLimit !== undefined) defaults.maxLimit = partial.maxLimit\n if (partial.defaultLimit !== undefined) defaults.defaultLimit = partial.defaultLimit\n if (partial.maxSearchLength !== undefined) defaults.maxSearchLength = partial.maxSearchLength\n}\n\n/** Read the current global query-parsing defaults (a copy). */\nexport function getQueryParsingDefaults(): Readonly<QueryParsingDefaults> {\n return { ...defaults }\n}\n\n/**\n * Restore the built-in query-parsing defaults (maxLimit 100, defaultLimit\n * 20, maxSearchLength 200). Useful in test teardown after a\n * {@link setQueryParsingDefaults} override so global state can't leak\n * between tests.\n */\nexport function resetQueryParsingDefaults(): void {\n Object.assign(defaults, BUILTIN_DEFAULTS)\n}\n\n// ── Individual parsers ──────────────────────────────────────────────────\n\n/** Parse filter strings like \"status:eq:active\" into structured objects */\nexport function parseFilters(\n filterParam: string | string[] | undefined,\n allowedFields?: string[],\n options?: Pick<ParseQueryOptions, 'onReject'>,\n): FilterItem[] {\n if (!filterParam) return []\n\n const items = Array.isArray(filterParam) ? filterParam : [filterParam]\n const results: FilterItem[] = []\n const allowed = allowedFields ? new Set(allowedFields) : null\n const onReject = options?.onReject\n\n for (const item of items) {\n // Split on first two colons only — value may contain colons (e.g. timestamps)\n const firstColon = item.indexOf(':')\n if (firstColon === -1) continue\n\n const secondColon = item.indexOf(':', firstColon + 1)\n if (secondColon === -1) continue\n\n const field = item.slice(0, firstColon)\n const operator = item.slice(firstColon + 1, secondColon)\n const value = item.slice(secondColon + 1)\n\n if (!field || !value) continue\n if (!FILTER_OPERATORS.has(operator)) {\n onReject?.({ kind: 'filter', field, reason: 'unknown-operator' })\n continue\n }\n if (allowed && !allowed.has(field)) {\n onReject?.({ kind: 'filter', field, reason: 'field-not-allowed' })\n continue\n }\n\n results.push({ field, operator: operator as FilterOperator, value })\n }\n\n return results\n}\n\n/**\n * Parse sort into structured items. Accepts `field:asc|desc`, `-field`\n * (descending), and `field` / `+field` (ascending), repeated or\n * comma-separated: `?sort=-featured,price` = `?sort=featured:desc&sort=price:asc`.\n */\nexport function parseSort(\n sortParam: string | string[] | undefined,\n allowedFields?: string[],\n options?: Pick<ParseQueryOptions, 'onReject'>,\n): SortItem[] {\n if (!sortParam) return []\n\n const items = (Array.isArray(sortParam) ? sortParam : [sortParam]).flatMap((s) => s.split(','))\n const results: SortItem[] = []\n const allowed = allowedFields ? new Set(allowedFields) : null\n const onReject = options?.onReject\n\n for (const raw of items) {\n // `+` in a query string arrives as a space; trim covers `+field` too.\n const item = raw.trim()\n if (!item) continue\n let field: string\n let dir: string\n const lastColon = item.lastIndexOf(':')\n if (lastColon !== -1) {\n // Split on the last colon so field names with colons work.\n field = item.slice(0, lastColon)\n dir = item.slice(lastColon + 1).toLowerCase()\n } else if (item.startsWith('-')) {\n field = item.slice(1)\n dir = 'desc'\n } else {\n field = item.startsWith('+') ? item.slice(1) : item\n dir = 'asc'\n }\n\n if (!field) continue\n if (dir !== 'asc' && dir !== 'desc') continue\n if (allowed && !allowed.has(field)) {\n onReject?.({ kind: 'sort', field, reason: 'field-not-allowed' })\n continue\n }\n\n results.push({ field, direction: dir })\n }\n\n return results\n}\n\n/** Parse page/limit into pagination with computed offset */\nexport function parsePagination(\n params: {\n page?: string | number\n limit?: string | number\n },\n options?: Pick<ParseQueryOptions, 'maxLimit' | 'defaultLimit'>,\n): PaginationParams {\n const defaultLimit = options?.defaultLimit ?? defaults.defaultLimit\n const maxLimit = options?.maxLimit ?? defaults.maxLimit\n\n let page =\n typeof params.page === 'string'\n ? Number.parseInt(params.page, 10)\n : (params.page ?? defaults.defaultPage)\n let limit =\n typeof params.limit === 'string'\n ? Number.parseInt(params.limit, 10)\n : (params.limit ?? defaultLimit)\n\n if (Number.isNaN(page) || page < 1) page = defaults.defaultPage\n if (Number.isNaN(limit) || limit < 1) limit = defaultLimit\n if (limit > maxLimit) limit = maxLimit\n\n return { page, limit, offset: (page - 1) * limit }\n}\n\n/** Sanitize and truncate search query */\nexport function parseSearchQuery(\n q: string | undefined,\n options?: Pick<ParseQueryOptions, 'maxSearchLength' | 'onReject'>,\n): string {\n if (!q) return ''\n const maxLen = options?.maxSearchLength ?? defaults.maxSearchLength\n const trimmed = q.trim()\n if (trimmed.length > maxLen) {\n options?.onReject?.({ kind: 'search', field: 'q', reason: 'truncated' })\n return trimmed.slice(0, maxLen)\n }\n return trimmed\n}\n\n// ── Config normalizer ───────────────────────────────────────────────────\n\n/**\n * Normalize a QueryFieldConfig into the string-based form.\n * Detects column-object-based configs (DrizzleQueryParamsConfig) by checking\n * for a `columns` property and extracts `Object.keys()`.\n */\nfunction normalizeFieldConfig(config?: QueryFieldConfig): StringQueryFieldConfig | undefined {\n if (!config) return undefined\n\n // Column-object-based config (e.g., DrizzleQueryParamsConfig)\n if ('columns' in config && config.columns && typeof config.columns === 'object') {\n return {\n filterable: Object.keys(config.columns),\n sortable: config.sortable ? Object.keys(config.sortable) : undefined,\n searchable: undefined, // searchColumns are Column objects, not used for string filtering\n }\n }\n\n // Already string-based\n return config as StringQueryFieldConfig\n}\n\n// ── Combined parser ─────────────────────────────────────────────────────\n\n/**\n * Parse a raw Express query object into a structured, ORM-agnostic ParsedQuery.\n *\n * @param query - Raw query string object from `req.query` or Zod-validated object\n * @param fieldConfig - Optional field restrictions (whitelist filterable/sortable/searchable).\n * Accepts both string-based configs (`{ filterable, sortable, searchable }`) and\n * column-object configs (`{ columns, sortable, searchColumns }`).\n * @param options - Limits + an `onReject` hook for dropped/truncated input.\n *\n * @example\n * ```ts\n * // String-based config\n * const parsed = parseQuery(ctx.query, {\n * filterable: ['status', 'priority'],\n * sortable: ['createdAt', 'title'],\n * })\n *\n * // Column-object config (DrizzleQueryParamsConfig)\n * const parsed = parseQuery(ctx.query, TASK_QUERY_CONFIG)\n * ```\n *\n * Query string format:\n * - Filters: `?filter=field:operator:value` (repeatable)\n * - Sort: `?sort=field:asc|desc`, `-field` / `field`, repeatable or comma-separated\n * - Pagination: `?page=1&limit=20`\n * - Search: `?q=search+term`\n *\n * Filter operators: eq, neq, gt, gte, lt, lte, between, in, contains, starts, ends\n */\nexport function parseQuery<TConfig extends QueryFieldConfig | undefined = undefined>(\n query: Record<string, any>,\n fieldConfig?: TConfig,\n options?: ParseQueryOptions,\n): TypedParsedQuery<TConfig> {\n const normalized = normalizeFieldConfig(fieldConfig)\n const rejectOpts = options?.onReject ? { onReject: options.onReject } : undefined\n return {\n filters: parseFilters(query.filter, normalized?.filterable, rejectOpts),\n sort: parseSort(query.sort, normalized?.sortable, rejectOpts),\n pagination: parsePagination({ page: query.page, limit: query.limit }, options),\n search: parseSearchQuery(query.q, options),\n } as TypedParsedQuery<TConfig>\n}\n\n// ── Query URL builder (for client-side or testing) ──────────────────────\n\n/** Convert ParsedQuery back into query string parameters */\nexport function buildQueryParams(\n parsed: Partial<ParsedQuery>,\n): Record<string, string | string[] | number> {\n const params: Record<string, string | string[] | number> = {}\n\n if (parsed.filters?.length) {\n params.filter = parsed.filters.map((f) => `${f.field}:${f.operator}:${f.value}`)\n }\n\n if (parsed.sort?.length) {\n params.sort = parsed.sort.map((s) => `${s.field}:${s.direction}`)\n }\n\n if (parsed.pagination) {\n params.page = parsed.pagination.page\n params.limit = parsed.pagination.limit\n }\n\n if (parsed.search) {\n params.q = parsed.search\n }\n\n return params\n}\n"],"mappings":";;;;;;;;;;AAcA,MAAa,iCAAmB,IAAI,IAAY,CAC9C,KACA,MACA,KACA,MACA,KACA,MACA,UACA,KACA,WACA,SACA,MACF,CAAC,ECuBK,iBAAyC,CAC7C,SAAU,IACV,aAAc,GACd,gBAAiB,IACjB,YAAa,CACf,EAEM,SAAiC,CAAE,GAAG,g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{"version":3,"file":"rate-limit-DQDk6bAH.d.mts","names":["Request","Response","NextFunction"],"sources":["../src/http/middleware/rate-limit.ts"],"mappings":";;;;UAaiB;EACf,UAAU,cAAc;IAAU;IAAmB,WAAW;;EAChE,UAAU,cAAc;EACxB,MAAM,cAAc;;UAGL;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA,gBAAgB,KAAKA;;EAErB;;EAEA,QAAQ;;EAER,QAAQ,KAAKA;;EAEb;;;;;;;;;;;;;;;;;;;EAmBA,aAAa;;;cAIF,uBAAuB;mBACjB;UACT;;EAGR,YAAY,kBAAkB;;EAc9B;EAKM,UAAU,cAAc;IAAU;IAAmB,WAAW;;EAIhE,UAAU,cAAc;EAIxB,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;iBAyBZ,UAAU,UAAS,oBAAqB,KAwB1BA,gBAAO,KAAOC,iBAAQ,MAAQC,gBAAY"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"reactivity-DZrc3Yhu.d.mts","names":[],"sources":["../src/core/reactivity.ts"],"mappings":";;;;;;;;;;;;;;;;;;iBAyKgB,MAAM,GAAG,UAAU,IAAI;UAoBtB,IAAI;EACnB,OAAO;;;;;EAKP,UAAU,KAAK,UAAU,GAAG,UAAU;;;;;;;EAOtC,UAAU;;UAGK;;;;;;EAMf;;;;;;;;;;;;;;;iBAgBc,IAAI,GAAG,cAAc,GAAG,UAAS,aAAkB,IAAI;UA0DtD,YAAY;WAClB,OAAO;;;;;;EAMhB,UAAU;;;;;;;;;EASV;;;;;;;;;;;;;iBAcc,SAAS,GAAG,cAAc,IAAI,YAAY;UAqDzC;;EAEf;;KAGG,YAAY,KAAK,IAAI,KAAK,YAAY,YAAY;;;;;;;;;;;;;;;;;;;;iBAqBvC,MAAM,GACpB,QAAQ,YAAY,IACpB,WAAW,UAAU,GAAG,UAAU,YAClC,UAAU;iBAkFI,SAAS,kBAAkB,QAAQ,IAAI;;iBAoEvC,MAAM,SAAS,iBAAiB,SAAS,IAAI,KAAK,YAAY;;iBAK9D,MAAM,GAAG,OAAO,IAAI,KAAK,YAAY,KAAK,IAAI;;;;;iBAQ9C,MAAM,kBAAkB,gBAAgB,GAAG,KAAK,GAAG,KAAK,IAAI,IAAI,EAAE;;iBAmBlE,OAAO,kBAAkB,KAAK,OAAO,WAAW,IAAI,IAAI,EAAE"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"request-id-Dn64nEHK.d.mts","names":["Request","Response","NextFunction"],"sources":["../src/http/middleware/request-id.ts"],"mappings":";;;cAMa;;;;;;;;;;;iBAYG,cAAS,KACVA,gBAAO,KAAOC,iBAAQ,MAAQC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"request-logger-TgcKRNDD.d.mts","names":[],"sources":["../src/http/middleware/request-logger.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;UAkBiB;EACf;EACA;;EAEA;;EAEA;EACA,SAAS;;;UAIM;EACf;EACA,GAAG,iBAAiB;;UAWL;;EAEf;;EAEA;;EAEA;;;;;;;;;;;;;;;;;;iBAmBc,cAAc,UAAS,wBAAyB,KAKjD,eAAa,KAAO,gBAAc"}
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @forinda/kickjs v10.14.1
|
|
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{createRequire}from"node:module";var __defProp=Object.defineProperty,__exportAll=(all,no_symbols)=>{let target={};for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0});return no_symbols||__defProp(target,Symbol.toStringTag,{value:`Module`}),target},__require=/* @__PURE__ */ createRequire(import.meta.url);export{__require as n,__exportAll as t};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"route-flag-B1lQht6v.d.mts","names":[],"sources":["../src/core/route-flag.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAiDiB;;;;;;;KAQL,uBAAuB,iDAEzB;;;;;KAME,eAAe,kBAAkB,sBAAsB,gBAAgB,iBAC/E,eAAe,KACf;;UAmBa;WACN;;WAEA;;;;;;;;;;;;;;UAeM;;;;;;;GAOd,QAAQ;;;;;GAKR,gBAAgB,8BAA8B,aAAa;;;UAI7C,gBAAgB;GAC9B,OAAO,KAAK,gBAAgB;;;;;;;;;WASpB,KAAK;WACL;;;;;;;;;;;KAYC,UAAU,yBAAyB,IAC3C,gBAAgB,gBAAgB,KAChC,gBAAgB;;;;;;;;;;;;;;;;;;;;;;iBA2CJ,sBAAsB,UAAU,eAC9C,MAAM,IACL,UAAU,eAAe;iBACZ,gBAAgB,GAAG,MAAM,gBAAgB,UAAU;;;;;;;;;;;iBAkEnD,kBACd,4BAA4B,wBAC5B,6BAA6B,wBAC7B,6BAA4B,yBAC3B;;;;;;;;;UAgCc,mBAAmB;EAClC,IAAI,MAAM;EACV,IAAI,UAAU,eAAe,MAAM,IAAI,eAAe;;;;;;;;UASvC;WACN,OAAO;WACP;aACE;aACA;aACA;aACA;;;;;;;;;;;;;;;;KAiBD,sBAAsB,KAAK;;;;;;;;;;;;;;;;;;;;;KAsB3B,2BAA2B;;;;;;;;;;;;;;;KAgB3B,gBACR,gBACA,gCACS,2BACA,yBACT;;;;;;;;iBASY,gBACd,MAAM,eACN,OAAO,wBACP,QAAQ;;;;;;;;;;;;iBA2CM,eAAe,MAAM,eAAe;;;;;;;;;;;;;;;;;;;iBAiDpC,cAAc,yBAAyB,sBAAsB;;;;;;;;KAiCjE,qBAAqB,KAAK,iBAAiB,eAAe;;;;;;;;KAS1D,iCAAiC,kBAAkB"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"route-policy-DsdJx3bk.mjs","names":[],"sources":["../src/core/route-policy.ts"],"sourcesContent":["/**\n * The route policy table — route flags for pre-match middleware.\n *\n * Middleware mounted app-wide (the connect-style `rateLimit()`, `csrf()`) runs\n * *before* a route is matched, so it cannot read `ctx.route.flags`: there is no\n * route yet. That is also the reason to keep it there — an abuse control has to\n * see traffic that matches nothing, which a route-scoped guard never does.\n *\n * So the flags come to it instead. Every mounted route registers its method,\n * full path and resolved flags here at boot; a global middleware asks the table\n * what flags *would* apply to an incoming method + pathname.\n *\n * The table is per-Application, handed to middleware that opts in via\n * {@link bindRoutePolicy}. Nothing global: two apps in one process (a test file,\n * an embedded admin app) each get their own.\n */\n\nimport type { RouteFlags } from './route-flag'\n\n/** Flags for one mounted route, keyed for lookup by an incoming request. */\ninterface PolicyEntry {\n /** Compiled from the mounted path — `/users/:id` → `^/users/([^/]+)$`. */\n readonly pattern: RegExp\n readonly flags: RouteFlags\n}\n\nconst EMPTY: RouteFlags = new Map() as RouteFlags\n\n/**\n * Turn a mounted path into a matcher.\n *\n * Deliberately small: `:param` matches one segment, `*` matches the rest, and\n * everything else is literal. This is a *lookup* over paths the engine already\n * chose to mount, not a second router — if it ever disagrees with the engine,\n * the answer is fewer features here, not more.\n */\nfunction compile(path: string): RegExp {\n const source = path\n .replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&')\n .replace(/\\/:[^/]+/g, '/([^/]+)')\n .replace(/\\*/g, '.*')\n return new RegExp(`^${source}/?$`)\n}\n\nexport class RoutePolicyTable {\n /** Bucketed by method: an incoming request only scans its own verb. */\n private readonly byMethod = new Map<string, PolicyEntry[]>()\n\n add(method: string, path: string, flags: RouteFlags | undefined): void {\n if (!flags || flags.size === 0) return // nothing to say about this route\n const verb = method.toUpperCase()\n const bucket = this.byMethod.get(verb) ?? []\n bucket.push({ pattern: compile(path), flags })\n this.byMethod.set(verb, bucket)\n }\n\n /**\n * Flags that apply to `method pathname`, or an empty map when the path\n * matches no flagged route — including when it matches no route at all,\n * which is exactly the traffic this exists to keep visible.\n */\n lookup(method: string, pathname: string): RouteFlags {\n const bucket = this.byMethod.get(method.toUpperCase())\n if (!bucket) return EMPTY\n for (const entry of bucket) {\n if (entry.pattern.test(pathname)) return entry.flags\n }\n return EMPTY\n }\n\n /** Drop everything — the Application rebuilds on every HMR reload. */\n clear(): void {\n this.byMethod.clear()\n }\n\n get size(): number {\n let total = 0\n for (const bucket of this.byMethod.values()) total += bucket.length\n return total\n }\n}\n\n/**\n * Slot a middleware exposes to say \"hand me the policy table once routes are\n * mounted\". The Application calls it during setup; middleware that never\n * declares it is untouched.\n */\nexport const ROUTE_POLICY_SLOT: unique symbol = Symbol.for('kick.routePolicy') as never\n\n/** A middleware that accepts the policy table. */\nexport interface RoutePolicyAware {\n [ROUTE_POLICY_SLOT]?: (table: RoutePolicyTable) => void\n}\n\n/**\n * Declare that `handler` wants the policy table.\n *\n * Explicit hand-off rather than a module-level singleton, so the table a\n * middleware reads is always the one belonging to the app that mounted it.\n */\nexport function bindRoutePolicy<T extends object>(\n handler: T,\n receive: (table: RoutePolicyTable) => void,\n): T {\n Object.defineProperty(handler, ROUTE_POLICY_SLOT, { value: receive, enumerable: false })\n return handler\n}\n\n/** Hand the table to a middleware if it declared the slot. */\nexport function offerRoutePolicy(handler: unknown, table: RoutePolicyTable): void {\n const receive = (handler as RoutePolicyAware | null)?.[ROUTE_POLICY_SLOT]\n if (typeof receive === 'function') receive(table)\n}\n"],"mappings":";;;;;;;;;;AA0BA,MAAM,sBAAoB,IAAI,IAU9B,SAAS,QAAQ,KAAsB,CACrC,IAAM,OAAS,KACZ,QAAQ,qBAAsB,MAAM,CAAC,CACrC,QAAQ,YAAa,UAAU,CAAC,CAChC,QAAQ,MAAO,IAAI,EACtB,OAAW,OAAO,IAAI,OAAO,IAAI,CACnC,CAEA,IAAa,iBAAb,KAA8B,CAE5B,yBAA4B,IAAI,IAEhC,IAAI,OAAgB,KAAc,MAAqC,CACrE,GAAI,CAAC,OAAS,MAAM,OAAS,EAAG,OAChC,IAAM,KAAO,OAAO,YAAY,EAC1B,OAAS,KAAK,SAAS,IAAI,IAAI,GAAK,CAAC,EAC3C,OAAO,KAAK,CAAE,QAAS,QAAQ,IAAI,EAAG,KAAM,CAAC,EAC7C,KAAK,SAAS,IAAI,KAAM,MAAM,CAChC,CAOA,OAAO,OAAgB,SAA8B,CACnD,IAAM,OAAS,KAAK,SAAS,IAAI,OAAO,YAAY,CAAC,EACrD,GAAI,CAAC,OAAQ,OAAO,MACpB,IAAK,IAAM,SAAS,OAClB,GAAI,MAAM,QAAQ,KAAK,QAAQ,EAAG,OAAO,MAAM,MAEjD,OAAO,KACT,CAGA,OAAc,CACZ,KAAK,SAAS,MAAM,CACtB,CAEA,IAAI,MAAe,CACjB,IAAI,MAAQ,EACZ,IAAK,IAAM,UAAU,KAAK,SAAS,OAAO,EAAG,OAAS,OAAO,OAC7D,OAAO,KACT,CACF,EAOA,MAAa,kBAAmC,OAAO,IAAI,kBAAkB,EAa7E,SAAgB,gBACd,QACA,QACG,CAEH,OADA,OAAO,eAAe,QAAS,kBAAmB,CAAE,MAAO,QAAS,WAAY,EAAM,CAAC,EAChF,OACT,CAGA,SAAgB,iBAAiB,QAAkB,MAA+B,CAChF,IAAM,QAAW,UAAsC,mBACnD,OAAO,SAAY,YAAY,QAAQ,KAAK,CAClD"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"router-builder-C5EtcFSL.d.mts","names":[],"sources":["../src/http/router-builder.ts"],"mappings":";;;;;iBA2CgB,+BAA+B,kBAAkB;;;;;;;;;;;iBAcjD,kBACd,UAAU,qBACV,gBACA,kBACA;UAUe;;;;;;;EAOf,2BAA2B;;;;;;EAM3B,aAAa;;;;;;;;;;;;;;;;;;;;;;iBAuBC,gBACd,sBACA,UAAS,qBACR"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"router-builder-CiwYhiUM.mjs","names":[],"sources":["../src/core/contributor-pipeline.ts","../src/http/router-builder.ts"],"sourcesContent":["import type { AnyContributorRegistration } from './context-decorator'\nimport {\n ContributorCycleError,\n DuplicateContributorError,\n MissingContributorError,\n} from './context-errors'\n\n/**\n * Where a contributor was registered, ordered by precedence\n * (lower index wins). Mirrors `architecture.md` §20.4.\n *\n * Levels (highest → lowest precedence):\n * - `'method'` — `@LoadX` on a controller method.\n * - `'class'` — `@LoadX` on a controller class.\n * - `'module'` — returned by `AppModule.contributors?()`. Per-module scope.\n * - `'adapter'` — returned by `AppAdapter.contributors?()`. Cross-cutting, applies\n * to every module's routes.\n * - `'global'` — `ApplicationOptions.contributors`. App-wide default.\n */\nexport type ContributorSource = 'method' | 'class' | 'module' | 'adapter' | 'global'\n\n/** Precedence-ranked source list. Index = precedence; method (0) wins ties. */\nconst PRECEDENCE_ORDER: readonly ContributorSource[] = [\n 'method',\n 'class',\n 'module',\n 'adapter',\n 'global',\n]\n\n/**\n * Input row to {@link buildPipeline}. Pairs a registration with its origin\n * so dedup can apply the precedence rule and diagnostic errors can name\n * the offending site.\n *\n * `registration` is the type-erased {@link AnyContributorRegistration}\n * — the runner doesn't care about each registration's narrow `D` /\n * `Ctx` shape, and adopters frequently mix HTTP / transport-agnostic\n * contributors in the same `externalSources` / `contributors()`\n * array. The narrow generics from `defineContextDecorator` survive\n * at the *definition* site (where `resolve` is typed); they're erased\n * here so collections compose without `as any` casts.\n */\nexport interface SourcedRegistration {\n registration: AnyContributorRegistration\n source: ContributorSource\n /** Human label surfaced in DuplicateContributorError messages. */\n label?: string\n}\n\n/**\n * Resolved, validated, topo-sorted pipeline ready for execution.\n *\n * `contributors` is in execution order — every entry's `dependsOn`\n * keys appear earlier. `keys` is the set of all keys this pipeline\n * produces; the runner uses it for fast existence checks and the\n * builder uses it for missing-dep validation.\n */\nexport interface ContributorPipeline {\n readonly contributors: readonly AnyContributorRegistration[]\n readonly keys: ReadonlySet<string>\n}\n\nexport interface BuildPipelineOptions {\n /** Optional route identifier surfaced in diagnostic errors (e.g., 'GET /projects/:id'). */\n route?: string\n}\n\n/**\n * Build, validate, and topo-sort a contributor pipeline.\n *\n * Pipeline:\n *\n * 1. Group sources by precedence (method > class > module > adapter > global).\n * 2. Within each precedence level, two contributors with the same `key`\n * raise {@link DuplicateContributorError}.\n * 3. Across levels, the highest-precedence contributor wins each key\n * (lower-precedence duplicates are silently dropped — that is the\n * documented override mechanism, not an error).\n * 4. Every key referenced by `dependsOn` must be produced by the\n * surviving set, otherwise {@link MissingContributorError}.\n * 5. Kahn's algorithm topo-sorts the survivors. Any nodes left after\n * the queue drains form a cycle → {@link ContributorCycleError}\n * with a reconstructed path.\n *\n * Pure function — no DI, no I/O. Safe to call once at startup per\n * route and cache the result.\n */\nexport function buildPipeline(\n sources: readonly SourcedRegistration[],\n options: BuildPipelineOptions = {},\n): ContributorPipeline {\n const route = options.route\n\n // Step 1: group by source.\n const bySource = new Map<ContributorSource, SourcedRegistration[]>()\n for (const src of PRECEDENCE_ORDER) bySource.set(src, [])\n for (const entry of sources) bySource.get(entry.source)!.push(entry)\n\n // Step 2 + 3: dedup with precedence. We walk highest precedence first,\n // claim its keys, and drop lower-precedence rows that conflict.\n const winners = new Map<string, SourcedRegistration>()\n for (const src of PRECEDENCE_ORDER) {\n const rows = bySource.get(src)!\n const keysAtThisLevel = new Map<string, SourcedRegistration[]>()\n for (const row of rows) {\n const key = row.registration.key\n const existing = keysAtThisLevel.get(key) ?? []\n existing.push(row)\n keysAtThisLevel.set(key, existing)\n }\n for (const [key, rowsForKey] of keysAtThisLevel) {\n if (rowsForKey.length > 1) {\n const labels = rowsForKey.map((r, i) => r.label ?? `${src}#${i}`)\n throw new DuplicateContributorError(key, labels)\n }\n if (!winners.has(key)) winners.set(key, rowsForKey[0])\n }\n }\n\n const survivors = [...winners.values()].map((r) => r.registration)\n const allKeys = new Set(survivors.map((r) => r.key))\n\n // Step 4: dependsOn validation.\n for (const reg of survivors) {\n for (const dep of reg.dependsOn) {\n if (!allKeys.has(dep)) {\n throw new MissingContributorError(dep, reg.key, route, reg.definedAt)\n }\n }\n }\n\n // Step 5: Kahn topo-sort.\n const sorted = topoSort(survivors, route)\n\n return Object.freeze({\n contributors: Object.freeze(sorted),\n keys: allKeys,\n })\n}\n\n/**\n * Split a built pipeline into the contributors that run before request\n * validation (`beforeValidation: true`) and the rest, which keep their place\n * after `@Middleware()`. Both halves stay in topo order.\n *\n * An early contributor can only depend on other early ones — its dependency\n * would not have run yet otherwise — so that fails here, at boot.\n */\nexport function splitBeforeValidation(\n pipeline: ContributorPipeline,\n route?: string,\n): { early: ContributorPipeline | null; late: ContributorPipeline | null } {\n const early = pipeline.contributors.filter((reg) => reg.beforeValidation)\n if (early.length === 0) return { early: null, late: pipeline }\n\n const earlyKeys = new Set(early.map((reg) => reg.key))\n for (const reg of early) {\n const lateDep = reg.dependsOn.find((dep) => !earlyKeys.has(dep))\n if (lateDep !== undefined) {\n throw new Error(\n `Contributor '${reg.key}'${route ? ` on ${route}` : ''} sets beforeValidation but ` +\n `depends on '${lateDep}', which runs after validation. Set beforeValidation on ` +\n `'${lateDep}' too, or remove it from '${reg.key}'.`,\n )\n }\n }\n\n const late = pipeline.contributors.filter((reg) => !reg.beforeValidation)\n return {\n early: Object.freeze({ contributors: Object.freeze(early), keys: earlyKeys }),\n late:\n late.length === 0\n ? null\n : Object.freeze({\n contributors: Object.freeze(late),\n keys: new Set(late.map((reg) => reg.key)),\n }),\n }\n}\n\n/**\n * Kahn's algorithm with deterministic ordering on ties.\n *\n * Nodes with no remaining incoming edges enter the queue in input\n * order. Cycles surface as nodes still present after the queue\n * drains; we reconstruct one cycle path for diagnostics.\n */\nfunction topoSort(\n registrations: readonly AnyContributorRegistration[],\n route: string | undefined,\n): AnyContributorRegistration[] {\n // indegree[key] = number of unresolved dependsOn entries for key\n const indegree = new Map<string, number>()\n // dependents[depKey] = list of registrations that depend on depKey\n const dependents = new Map<string, AnyContributorRegistration[]>()\n const byKey = new Map<string, AnyContributorRegistration>()\n\n for (const reg of registrations) {\n indegree.set(reg.key, reg.dependsOn.length)\n byKey.set(reg.key, reg)\n }\n for (const reg of registrations) {\n for (const dep of reg.dependsOn) {\n const list = dependents.get(dep) ?? []\n list.push(reg)\n dependents.set(dep, list)\n }\n }\n\n // Initial queue: registrations with zero indegree, preserving input order.\n const queue: AnyContributorRegistration[] = []\n for (const reg of registrations) {\n if (indegree.get(reg.key) === 0) queue.push(reg)\n }\n\n const sorted: AnyContributorRegistration[] = []\n while (queue.length > 0) {\n const node = queue.shift()!\n sorted.push(node)\n for (const dependent of dependents.get(node.key) ?? []) {\n const next = (indegree.get(dependent.key) ?? 0) - 1\n indegree.set(dependent.key, next)\n if (next === 0) queue.push(dependent)\n }\n }\n\n if (sorted.length !== registrations.length) {\n const remaining = registrations.filter((r) => (indegree.get(r.key) ?? 0) > 0)\n throw new ContributorCycleError(reconstructCycle(remaining, byKey), route)\n }\n\n return sorted\n}\n\n/**\n * Reconstruct one cycle path from the residual graph.\n *\n * Walks from any remaining node, following its first dependency that's\n * still in the residual set, until we revisit a node. The path returned\n * starts and ends with the same key so the message reads naturally:\n * `tenant → project → tenant`.\n */\nfunction reconstructCycle(\n residual: readonly AnyContributorRegistration[],\n byKey: ReadonlyMap<string, AnyContributorRegistration>,\n): string[] {\n const residualKeys = new Set(residual.map((r) => r.key))\n const start = residual[0].key\n const path: string[] = [start]\n const seen = new Set<string>([start])\n let cursor: string = start\n\n while (true) {\n const reg = byKey.get(cursor)!\n const nextDep = reg.dependsOn.find((d) => residualKeys.has(d))\n if (nextDep === undefined) break\n if (seen.has(nextDep)) {\n // Trim the prefix that isn't part of the cycle.\n const cycleStart = path.indexOf(nextDep)\n return [...path.slice(cycleStart), nextDep]\n }\n path.push(nextDep)\n seen.add(nextDep)\n cursor = nextDep\n }\n\n // Fallback — couldn't reconstruct a strict cycle, return what we walked.\n return path\n}\n","// Concrete-module imports (NOT the `../core` barrel): the barrel re-exports\n// the asset manager, whose eager `node:fs` import would poison the edge-safe\n// `@forinda/kickjs/web` entry graph that flows through this file.\nimport {\n buildPipeline,\n splitBeforeValidation,\n type SourcedRegistration,\n} from '../core/contributor-pipeline'\nimport { runContributors } from '../core/contributor-runner'\nimport { Container } from '../core/container'\nimport { METADATA } from '../core/interfaces'\nimport type { ContributorRegistration } from '../core/context-decorator'\nimport type { FileUploadConfig, MiddlewareHandler, RouteDefinition } from '../core/decorators'\nimport { getClassMeta, getMethodMeta, getMethodMetaOrUndefined } from '../core/metadata'\nimport {\n getClassFlagDeclarations,\n getMethodFlagDeclarations,\n registerMountFlags,\n resolveRouteFlags,\n toFlagDeclarations,\n type RouteFlagDeclarations,\n} from '../core/route-flag'\nimport { duplicateRouteError } from '../core/kick-errors'\nimport type { CtxHandler, RouteContributor, RouteEntry, RouteMethod } from './runtime'\n\n/**\n * Per-module SourcedRegistration[] threaded through the route-mount loop by\n * Application.setup(). Carries module + adapter + global contributors so\n * buildRouteTable() can merge them with class + method ones into a single pipeline.\n *\n * Module setup is sequential, so this slot is race-free. Cleared in a finally\n * block after each module mounts. Outside of Application setup the slot is\n * empty — direct buildRouteTable()/buildRoutes() callers (mostly tests) see only\n * class + method contributors unless they pass `externalSources` explicitly.\n *\n * Same idiom as `Container.requestStoreProvider`: an internal escape hatch for\n * cross-module wiring without inversion-of-control gymnastics.\n *\n * @internal\n */\nlet _externalContributorSources: readonly SourcedRegistration[] = []\n\n/** @internal — set by Application.setup() before each `mod.routes()` call. */\nexport function _setExternalContributorSources(sources: readonly SourcedRegistration[]): void {\n _externalContributorSources = sources\n}\n\n/**\n * Boot-time duplicate-route guard shared by the node and web mount loops.\n *\n * Registers `METHOD /mounted/path` into `registry` and throws\n * {@link duplicateRouteError} (KICK006) if another handler already claimed\n * it. Param *names* are ignored — `/tasks/:id` and `/tasks/:taskId` are the\n * same route at dispatch time, so they collide here too.\n *\n * @internal\n */\nexport function assertRouteUnique(\n registry: Map<string, string>,\n method: string,\n fullPath: string,\n owner: string,\n): void {\n const key = `${method.toUpperCase()} ${fullPath.replace(/:[^/]+/g, ':*')}`\n const prior = registry.get(key)\n if (prior !== undefined) {\n throw duplicateRouteError(method.toUpperCase(), fullPath, owner, prior)\n }\n registry.set(key, owner)\n}\n\nexport interface BuildRoutesOptions {\n /**\n * Extra contributors to merge into the per-route pipeline at their declared\n * precedence levels. Pass explicitly when calling buildRouteTable/buildRoutes\n * outside the Application route-mount loop (typically in tests). When omitted,\n * falls back to the slot set by Application.setup().\n */\n externalSources?: readonly SourcedRegistration[]\n /**\n * Flags the mounting module declares for every route on this controller\n * (`ModuleRoutes.flags`). Lowest precedence — a class or method declaration\n * of the same name wins, and `@Flag.off` on a method removes it.\n */\n mountFlags?: RouteFlagDeclarations\n}\n\n/**\n * Turn a controller class decorated with @Get, @Post, etc. into a plain-data\n * {@link RouteEntry}[] — the engine-neutral route table an {@link HttpRuntime}\n * materializes.\n *\n * What used to be per-handler Express `(req, res, next)` closures is now\n * captured as data: `middlewares` keep their `(ctx, next)` shape, the contributor\n * pipeline is pre-built into a `contributorRunner` closure, validation / upload\n * stay as metadata, and the terminal `handler` resolves the controller per-request\n * (to respect DI scoping) and invokes it. The runtime owns how these get wrapped\n * onto its engine.\n *\n * Routes use only the method-level decorator paths (e.g. @Get('/me') → '/me').\n * The @Controller path is NOT baked in — it is metadata for Swagger/introspection.\n * The module's routes().path is the single source of truth for the mount prefix,\n * which avoids path doubling when both the module and controller specify the path.\n *\n * The contributor pipeline is built here, so a cycle or missing `dependsOn`\n * throws at table-build time (boot) rather than on first request.\n */\nexport function buildRouteTable(\n controllerClass: any,\n options: BuildRoutesOptions = {},\n): RouteEntry[] {\n const container = Container.getInstance()\n const externalSources = options.externalSources ?? _externalContributorSources\n const routes: RouteDefinition[] = getClassMeta<RouteDefinition[]>(\n METADATA.ROUTES,\n controllerClass,\n [],\n )\n\n // Class-level middleware\n const classMiddlewares: MiddlewareHandler[] = getClassMeta<MiddlewareHandler[]>(\n METADATA.CLASS_MIDDLEWARES,\n controllerClass,\n [],\n )\n\n // Class-level Context Contributors (#107) — applied to every method on the\n // controller. Method-level contributors are added per-route below.\n const classContributors: ContributorRegistration[] = getClassMeta<ContributorRegistration[]>(\n METADATA.CLASS_CONTRIBUTORS,\n controllerClass,\n [],\n )\n\n // Route flags declared on the controller — inherited by every method below\n // unless a method declares the same flag `false` (see core/route-flag.ts).\n const classFlagDeclarations = getClassFlagDeclarations(controllerClass)\n\n // Flags the module declared for this whole mount. Recorded against the class\n // so `getRouteFlags()` — the resolver Swagger and DevTools use, which sees no\n // mount — reports what the runtime actually resolved.\n const mountFlagDeclarations = toFlagDeclarations(\n options.mountFlags,\n `${controllerClass?.name ?? 'controller'} mount flags`,\n )\n registerMountFlags(controllerClass, mountFlagDeclarations)\n\n const entries: RouteEntry[] = []\n\n for (const route of routes) {\n const method = route.method.toUpperCase() as RouteMethod\n const fullPath = route.path || '/'\n\n // Method-level middleware\n const methodMiddlewares: MiddlewareHandler[] = getMethodMeta<MiddlewareHandler[]>(\n METADATA.METHOD_MIDDLEWARES,\n controllerClass,\n route.handlerName,\n [],\n )\n\n // @FileUpload decorator — runtime supplies the upload backend.\n const fileUploadConfig = getMethodMetaOrUndefined<FileUploadConfig>(\n METADATA.FILE_UPLOAD,\n controllerClass,\n route.handlerName,\n )\n\n // Context Contributor pipeline (#107) — class + method contributors,\n // built once at mount time so cycle/missing-dep failures abort boot.\n const methodContributors: ContributorRegistration[] = getMethodMeta<ContributorRegistration[]>(\n METADATA.METHOD_CONTRIBUTORS,\n controllerClass,\n route.handlerName,\n [],\n )\n\n // Flags in force for THIS route: class declarations overridden by method\n // ones. Resolved at build time so the per-request cost is a map lookup.\n const flags = resolveRouteFlags(\n classFlagDeclarations,\n getMethodFlagDeclarations(controllerClass, route.handlerName),\n mountFlagDeclarations,\n )\n\n let contributorRunner: CtxHandler | null = null\n let earlyContributorRunner: CtxHandler | null = null\n let contributors: RouteContributor[] | undefined\n if (\n classContributors.length > 0 ||\n methodContributors.length > 0 ||\n externalSources.length > 0\n ) {\n // Labels are surfaced in DuplicateContributorError messages — include\n // the registration's key + the original index so a same-key collision\n // at one precedence level points at the conflicting decorator slot,\n // not just the host method/class.\n const sources: SourcedRegistration[] = [\n ...methodContributors.map((registration, i): SourcedRegistration => ({\n source: 'method',\n registration,\n label: `${controllerClass.name}.${String(route.handlerName)}#${i}(${registration.key})`,\n })),\n ...classContributors.map((registration, i): SourcedRegistration => ({\n source: 'class',\n registration,\n label: `${controllerClass.name}.@class#${i}(${registration.key})`,\n })),\n ...externalSources,\n ]\n const routeLabel = `${method} ${fullPath}`\n const pipeline = buildPipeline(sources, { route: routeLabel })\n contributors = describePipeline(pipeline.contributors, sources)\n const { early, late } = splitBeforeValidation(pipeline, routeLabel)\n if (early) {\n earlyContributorRunner = (ctx) =>\n runContributors({ pipeline: early, ctx, container, flags })\n }\n if (late) {\n contributorRunner = (ctx) => runContributors({ pipeline: late, ctx, container, flags })\n }\n }\n\n // Terminal handler — resolve controller per-request to respect DI scoping.\n const handler: CtxHandler = (ctx) => container.resolve(controllerClass)[route.handlerName](ctx)\n\n entries.push({\n method,\n path: fullPath,\n middlewares: [...classMiddlewares, ...methodMiddlewares],\n contributorRunner,\n earlyContributorRunner,\n handler,\n meta: {\n controller: controllerClass,\n handlerName: route.handlerName,\n validation: route.validation,\n upload: fileUploadConfig,\n flags,\n ...(contributors ? { contributors } : {}),\n },\n })\n }\n\n return entries\n}\n\n/**\n * The pipeline as introspection shows it. The built pipeline keeps only the\n * registrations; their sources and labels are recovered from the inputs by\n * identity, along with the lower-precedence registrations each one replaced.\n */\nfunction describePipeline(\n ordered: readonly SourcedRegistration['registration'][],\n sources: readonly SourcedRegistration[],\n): RouteContributor[] {\n const bySource = new Map(sources.map((s) => [s.registration, s]))\n // Execution order: the pipeline is split at run time — `beforeValidation`\n // ones run first, ahead of middleware and validation, then the rest. Each\n // half keeps its dependency order.\n const runOrder = [\n ...ordered.filter((r) => r.beforeValidation === true),\n ...ordered.filter((r) => r.beforeValidation !== true),\n ]\n return runOrder.map((registration) => {\n const winner = bySource.get(registration)\n const described: RouteContributor = {\n key: registration.key,\n source: winner?.source ?? 'global',\n dependsOn: registration.dependsOn,\n beforeValidation: registration.beforeValidation === true,\n overrides: sources\n .filter((s) => s.registration !== registration && s.registration.key === registration.key)\n .map((s) => (s.label ? { source: s.source, label: s.label } : { source: s.source })),\n }\n if (winner?.label) described.label = winner.label\n return described\n })\n}\n"],"mappings":";;;;;;;;;;+mBAsBA,MAAM,iBAAiD,CACrD,SACA,QACA,SACA,UACA,QACF,EA4DA,SAAgB,cACd,QACA,QAAgC,CAAC,EACZ,CACrB,IAAM,MAAQ,QAAQ,MAGhB,yBAAW,IAAI,IACrB,IAAK,IAAM,OAAO,iBAAkB,SAAS,IAAI,IAAK,CAAC,CAAC,EACxD,IAAK,IAAM,SAAS,QAAS,SAAS,IAAI,MAAM,MAAM,CAAC,CAAE,KAAK,KAAK,EAInE,IAAM,wBAAU,IAAI,IACpB,IAAK,IAAM,OAAO,iBAAkB,CAClC,IAAM,KAAO,SAAS,IAAI,GAAG,EACvB,gCAAkB,IAAI,IAC5B,IAAK,IAAM,OAAO,KAAM,CACtB,IAAM,IAAM,IAAI,aAAa,IACvB,SAAW,gBAAgB,IAAI,GAAG,GAAK,CAAC,EAC9C,SAAS,KAAK,GAAG,EACjB,gBAAgB,IAAI,IAAK,QAAQ,CACnC,CACA,IAAK,GAAM,CAAC,IAAK,cAAe,gBAAiB,CAC/C,GAAI,WAAW,OAAS,EAAG,CACzB,IAAM,OAAS,WAAW,KAAK,EAAG,IAAM,EAAE,OAAS,GAAG,IAAI,GAAG,GAAG,EAChE,MAAM,IAAI,0BAA0B,IAAK,MAAM,CACjD,CACK,QAAQ,IAAI,GAAG,GAAG,QAAQ,IAAI,IAAK,WAAW,EAAE,CACvD,CACF,CAEA,IAAM,UAAY,CAAC,GAAG,QAAQ,OAAO,CAAC,CAAC,CAAC,IAAK,GAAM,EAAE,YAAY,EAC3D,QAAU,IAAI,IAAI,UAAU,IAAK,GAAM,EAAE,GAAG,CAAC,EAGnD,IAAK,IAAM,OAAO,UAChB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,GAAG,QAAQ,OAAQ,GAAM,EAAE,mBAAqB,EAAI,EACpD,GAAG,QAAQ,OAAQ,GAAM,EAAE,mBAAqB,EAAI,CAExC,CAAC,CAAC,IAAK,cAAiB,CACpC,IAAM,OAAS,SAAS,IAAI,YAAY,EAClC,UAA8B,CAClC,IAAK,aAAa,IAClB,OAAQ,QAAQ,QAAU,SAC1B,UAAW,aAAa,UACxB,iBAAkB,aAAa,mBAAqB,GACpD,UAAW,QACR,OAAQ,GAAM,EAAE,eAAiB,cAAgB,EAAE,aAAa,MAAQ,aAAa,GAAG,CAAC,CACzF,IAAK,GAAO,EAAE,MAAQ,CAAE,OAAQ,EAAE,OAAQ,MAAO,EAAE,KAAM,EAAI,CAAE,OAAQ,EAAE,MAAO,CAAE,CACvF,EAEA,OADI,QAAQ,QAAO,UAAU,MAAQ,OAAO,OACrC,SACT,CAAC,CACH"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"runtime-Bus9RVyU.mjs","names":[],"sources":["../src/http/runtime.ts"],"sourcesContent":["// The HttpRuntime seam.\n//\n// Decorators no longer emit an `express.Router` directly. `buildRouteTable()`\n// turns controller metadata into a plain-data `RouteEntry[]`; an `HttpRuntime`\n// materializes that table onto whatever engine it owns. Express is the default\n// runtime and the only one shipped in M1 — its materializer reproduces the exact\n// handler chain the old `buildRoutes()` built, so behavior is unchanged.\n//\n// Fastify / h3 runtimes (later milestones) consume the SAME `RouteEntry` data\n// and the SAME `HttpRuntime` contract; the request/response driver abstraction\n// that lets `RequestContext` run engine-agnostically lands with them (M3), since\n// under Express the drivers ARE the Express request/response objects already.\n//\n// Why a seam: running Fastify / h3 behind an Express-compat layer\n// (`@fastify/express`, h3's node bridge) bypasses their router and\n// serialization, and rebuilding `ctx` over web-standard Request/Response\n// would break SSE / streaming, multer uploads and `ctx.res` for every adopter.\n// The seam keeps `ctx` and swaps only the engine underneath it.\n\nimport { ROUTE_SLOT, type RouteFlags } from '../core/route-flag'\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport type { ConnectMiddleware, ConnectRequest, ConnectResponse } from './connect'\n\nimport type { Constructor, FileUploadConfig, MiddlewareHandler, RouteDefinition } from '../core'\nimport type { RequestContext } from './context'\nimport type { ValidationErrorFactory } from './middleware/validate'\nimport type { RouteUrls } from './url-for'\nimport type { ContributorSource } from '../core/contributor-pipeline'\n\n/** HTTP verbs the router emits. Mirrors the decorator surface (@Get/@Post/...). */\nexport type RouteMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'\n\n/**\n * A context-based handler: the runtime-neutral unit of the request pipeline.\n * Contributors, route middleware (via {@link MiddlewareHandler}), and the\n * terminal controller call all reduce to this shape. The runtime owns how a\n * `CtxHandler` is wrapped onto its engine (Express wraps it in `(req, res,\n * next)`; Fastify in its own handler).\n */\nexport type CtxHandler = (ctx: RequestContext) => unknown | Promise<unknown>\n\n/**\n * Connect-style middleware — the portable middleware format. Built-in\n * middleware and adopter-supplied Express middleware are this shape. The\n * Express runtime hands them straight to `app.use`; the others bridge them\n * (Fastify via `@fastify/middie`, h3 via its node adapter). See `./connect`.\n */\nexport type { ConnectMiddleware }\n\n/**\n * One materialized route, as plain data. Produced by {@link buildRouteTable}\n * from decorator metadata; consumed by {@link HttpRuntime.mountRoutes}.\n *\n * The shape is deliberately richer than a flat `CtxHandler[]`: `middlewares`\n * keep the `(ctx, next)` signature (they may short-circuit or call `next(err)`),\n * `contributorRunner` is a closure over the pre-built pipeline + container (the\n * pipeline is built — and any cycle / missing-dep error thrown — at table-build\n * time, i.e. boot), and `validation` / `upload` stay as metadata the runtime\n * materializes its own way. Faithfully reproducing the legacy Express chain —\n * not collapsing it — is what keeps M1 behavior-neutral.\n */\nexport interface RouteEntry {\n method: RouteMethod\n /** Path with `:param` segments — the portable subset all engines accept. */\n path: string\n /** Class + method middleware, in execution order; each receives `(ctx, next)`. */\n middlewares: MiddlewareHandler[]\n /**\n * Runs the contributor pipeline against `ctx` (populates `ctx.set(...)`),\n * or `null` when no contributors apply. Closes over the built pipeline and\n * the DI container so it stays engine-neutral; the runtime advances the\n * chain (Express: call `next()`) once it resolves.\n */\n contributorRunner: CtxHandler | null\n /**\n * Contributors registered with `beforeValidation: true`. Runtimes run this\n * right after publishing the matched route — before validation, upload and\n * middleware — so a rejection (401) lands before a malformed body's 422.\n * Absent or `null` when no contributor asks for it.\n */\n earlyContributorRunner?: CtxHandler | null\n /** The app's `validationError` — what this route's validation failure throws. */\n validationError?: ValidationErrorFactory\n /** The app's route names → paths, for `ctx.urlFor()`. */\n urls?: RouteUrls\n /** Terminal handler: resolves the controller per-request and invokes it. */\n handler: CtxHandler\n /** Introspection + runtime-materialized concerns (swagger/typegen read this). */\n meta: RouteMeta\n}\n\n/** Per-route metadata: introspection refs plus runtime-materialized concerns. */\n/**\n * One context contributor on a route, as introspection sees it: the\n * contributors a request runs, in execution order. Built with the route.\n */\nexport interface RouteContributor {\n /** The key it sets with `ctx.set(...)`. */\n key: string\n /** Where it was registered — `method` / `class` decorators, or a module, adapter or global list. */\n source: ContributorSource\n /** The registering site, e.g. `UsersController.show#0(tenant)` or a module name. */\n label?: string\n dependsOn: readonly string[]\n /** Runs before validation (`beforeValidation: true`). */\n beforeValidation: boolean\n /** Lower-precedence registrations of the same key this one replaced. */\n overrides: ReadonlyArray<{ source: ContributorSource; label?: string }>\n}\n\nexport interface RouteMeta {\n /**\n * Owning controller class — for DI resolution and adapter introspection.\n * Absent for ad-hoc routes registered through {@link AdapterHttp.route},\n * which have no controller class behind them.\n */\n controller?: Constructor\n /** Handler method name on the controller, when there is one. */\n handlerName?: string\n /** The route's context contributors, in execution order — for devtools / introspection. */\n contributors?: readonly RouteContributor[]\n /** Zod/JSON-schema validation config from the route decorator, if any. */\n validation?: RouteDefinition['validation']\n /** `@FileUpload` config, if present — the runtime supplies the backend. */\n upload?: FileUploadConfig\n /**\n * Route flags in force here, resolved at build time (method over class).\n * Enabled flags only: a flag declared `false` at a higher-precedence site is\n * absent rather than present-and-false, so `has()` is always the right\n * question. See `core/route-flag.ts`.\n */\n flags?: RouteFlags\n /**\n * The full mounted pattern (`/api/v1/users/:id`) — set by the Application\n * for controller routes. `path` is relative to the module mount.\n */\n pattern?: string\n}\n\n/**\n * The route a request matched, published on `ctx.route`.\n *\n * Everything that holds a {@link RequestContext} — handlers, `@Middleware()`,\n * guards, contributors — can read it, which is what lets one declaration on a\n * route serve every consumer.\n */\n/**\n * Publish the matched route on the request, for `ctx.route` to read.\n *\n * Called by each runtime once per dispatch, before it builds a RequestContext.\n * It lives on `req` rather than on the ctx because the Express runtime\n * constructs a fresh RequestContext per middleware step — anything written to\n * one ctx would be invisible to the next and to the handler.\n */\nexport function publishMatchedRoute(req: unknown, entry: RouteEntry): void {\n // One object per route, shared by its requests — every field comes from the\n // entry, which is final once mounted. Frozen, since it is shared.\n let route = matchedRoutes.get(entry)\n if (!route) {\n route = Object.freeze({\n method: entry.method,\n path: entry.path,\n controller: entry.meta.controller,\n handlerName: entry.meta.handlerName,\n flags: entry.meta.flags ?? EMPTY_FLAGS,\n pattern: entry.meta.pattern ?? entry.path,\n urls: entry.urls,\n })\n matchedRoutes.set(entry, route)\n }\n ;(req as Record<symbol, MatchedRoute>)[ROUTE_SLOT] = route\n}\n\nconst matchedRoutes = new WeakMap<RouteEntry, MatchedRoute>()\n\nconst EMPTY_FLAGS: RouteFlags = new Map() as RouteFlags\n\nexport interface MatchedRoute {\n readonly method: RouteMethod\n /** Path as declared on the handler, e.g. `/:id`. */\n readonly path: string\n /**\n * The full route pattern including the mount prefix and version, e.g.\n * `/api/v1/users/:id` — what metrics and spans should be keyed by. Falls\n * back to `path` for routes registered without a mount.\n */\n readonly pattern: string\n readonly controller?: Constructor\n readonly handlerName?: string\n /** Enabled flags only — see {@link RouteMeta.flags}. */\n readonly flags: RouteFlags\n /** @internal The app's route names, for `ctx.urlFor()`. */\n readonly urls?: RouteUrls\n}\n\n/** A controller's routes grouped under the module mount prefix. */\nexport type RouteTable = { mountPath: string; routes: RouteEntry[] }[]\n\n/**\n * The response surface {@link RequestContext}'s helpers (`json` / `html` /\n * `sse` / `download` / `render` / `problem`) drive, instead of calling Express\n * `res` methods directly (spec §4.3). Sized so `express.Response` satisfies it\n * structurally — under the Express runtime the driver IS the Express response,\n * so there is no wrapping and no behavior change. Other runtimes (Fastify / h3)\n * provide a thin object implementing this over their native reply.\n *\n * The terminal methods return `RuntimeResponse` for fluent chaining (Express's\n * `Response` is assignable, since it is a superset).\n */\n/** True for the TypeError `JSON.stringify` throws on a bigint. */\nexport function isBigIntJsonError(err: unknown): boolean {\n return err instanceof TypeError && /BigInt/.test(err.message)\n}\n\n/**\n * `JSON.stringify` that writes a bigint as its decimal string instead of\n * throwing — database counts and `bigint` columns reach responses as bigints.\n * Plain `JSON.stringify` runs first, so a body without one costs nothing extra.\n */\nexport function stringifyJson(data: unknown): string {\n try {\n return JSON.stringify(data)\n } catch (err) {\n if (!isBigIntJsonError(err)) throw err\n return JSON.stringify(data, (_key, value) =>\n typeof value === 'bigint' ? value.toString() : value,\n )\n }\n}\n\nexport interface RuntimeResponse {\n status(code: number): RuntimeResponse\n json(data: unknown): RuntimeResponse\n send(data: unknown): RuntimeResponse\n type(contentType: string): RuntimeResponse\n setHeader(name: string, value: string | number | readonly string[]): unknown\n render(view: string, data?: Record<string, unknown>): unknown\n writeHead(statusCode: number, headers?: Record<string, string>): unknown\n flushHeaders(): unknown\n write(chunk: string | Buffer): boolean\n end(data?: unknown): unknown\n once(event: 'close' | 'drain', listener: () => void): unknown\n readonly headersSent: boolean\n}\n\n// ── Runtime-typed escape hatches (spec §4.3b) ─────────────────────────────\n\n/**\n * Per-runtime type map: the engine-native request / response / app types an\n * `HttpRuntime` exposes through `ctx.req.raw` / `ctx.res.raw` / `AdapterContext.app`.\n */\nexport interface RuntimeTypeMap {\n request: unknown\n response: unknown\n app: unknown\n}\n\n/**\n * Augmentable runtime registry. Empty by default; the `kick/runtime` typegen\n * plugin emits a `{ runtime: <RuntimeTypeMap> }` augmentation from the configured\n * runtime, which flips the engine-native escape-hatch types — `AdapterContext.app`,\n * `getRuntimeApp()`, and (once the driver layer lands) `ctx.req.raw` / `ctx.res.raw`\n * — to that runtime. Mirrors `KickDbRegister` / `KickEnv`, so the type story is\n * uniform with `kick/db` and env typing.\n *\n * @example\n * ```ts\n * // .kickjs/types/kick__runtime.d.ts — generated by typegen\n * declare module '@forinda/kickjs' {\n * interface KickRuntimeRegister {\n * runtime: import('@forinda/kickjs/fastify').FastifyRuntimeTypes\n * }\n * }\n * ```\n */\n\nexport interface KickRuntimeRegister {}\n\n/**\n * The active runtime's type map — the augmented one, or the connect-style\n * {@link ConnectRuntimeTypes} when nothing is augmented. `kick typegen` augments it from kick.config's\n * `runtime`, Express included.\n */\nexport type ActiveRuntime = KickRuntimeRegister extends { runtime: infer R extends RuntimeTypeMap }\n ? R\n : ConnectRuntimeTypes\n\n/**\n * What the escape hatches are typed as with no augmentation: the connect-style\n * request and response every runtime's middleware sees, and an app of unknown\n * engine.\n */\nexport interface ConnectRuntimeTypes {\n request: ConnectRequest\n response: ConnectResponse\n app: unknown\n}\n\n/** Options passed to {@link HttpRuntime.createApp}. */\nexport interface RuntimeAppOptions {\n /**\n * Express `trust proxy` setting (and the equivalent on other engines). The\n * function form is Express-specific; other runtimes interpret the simpler\n * shapes (or normalize X-Forwarded-For themselves — see spec §10 Q1).\n */\n trustProxy?: boolean | string | number | string[] | ((ip: string, hopIndex: number) => boolean)\n /**\n * When the app is mounted inside another handler (`kick dev`'s Vite server,\n * `app.handle(req, res, next)` in a host server), hand requests no route\n * matched back to it — `true`, the default — or answer them here with the\n * app's not-found handling — `false`. Express always answers.\n */\n notFoundFallthrough?: boolean\n /** Largest request body the engine parses, in bytes — `jsonLimit`, resolved. */\n bodyLimit?: number\n}\n\n/** Where a connect middleware sits and what it scopes to. */\nexport interface UseConnectOptions {\n path?: string | RegExp | ReadonlyArray<string | RegExp>\n}\n\n/**\n * Optional engine capabilities. Absence means the corresponding `ctx` feature\n * raises a clear error on that runtime rather than failing obscurely.\n */\nexport interface RuntimeCapabilities {\n /** View-engine rendering (`ctx.render`). Express: true; Fastify/h3: false initially. */\n render: boolean\n /** File uploads (`ctx.file` / `@FileUpload`). All engines, different backends. */\n uploads: boolean\n /** Connect-style middleware. Express/Fastify(middie): true; h3: best-effort. */\n connectMiddleware: boolean\n /**\n * The engine parses request bodies itself (Fastify, h3). When true, the\n * Application skips its default `express.json()` so the body stream isn't\n * consumed twice (which would deadlock the engine's own parser). Express:\n * false — it relies on the `express.json()` connect middleware.\n */\n nativeBodyParsing: boolean\n /**\n * The engine's `nodeHandler` works behind `node:http2` (the HTTP/2\n * compatibility API), so `server: { http2: true }` may use it. Fastify/h3:\n * true. Express: false — it does not run on that layer. Absent = false, so\n * custom runtimes opt in explicitly.\n */\n http2?: boolean\n}\n\n/**\n * The engine driver. KickJS owns decorators → {@link RouteTable}, the\n * contributor pipeline, the `RequestContext` surface, and error mapping. The\n * runtime owns app/server creation, route materialization, connect-middleware\n * registration, static serving, and the terminal not-found / error handlers.\n *\n * `expressRuntime()` is the default and the M1 reference implementation.\n */\nexport interface HttpRuntime<TApp = unknown> {\n readonly name: 'express' | 'fastify' | 'h3' | (string & {})\n\n /** Create the engine app. Called once per Application (and per HMR rebuild). */\n createApp(options?: RuntimeAppOptions): TApp\n\n /**\n * Node-compatible request listener — the transport contract.\n * `http.createServer(handler)` in prod, Vite post-middleware in dev. MUST\n * invoke `next` (when given) instead of 404-ing if no route matched — the\n * Vite dev chain depends on fall-through.\n */\n nodeHandler(\n app: TApp,\n ): (req: IncomingMessage, res: ServerResponse, next?: (err?: unknown) => void) => void\n\n /** Materialize the framework-built route table onto the engine. */\n mountRoutes(app: TApp, table: RouteTable): void\n\n /** Register a connect-style middleware (built-ins + adopter middleware). */\n useConnect(app: TApp, mw: ConnectMiddleware, opts?: UseConnectOptions): void\n\n /** Serve a static directory (swagger-ui assets, devtools SPA). */\n serveStatic(app: TApp, prefix: string, dir: string): void\n\n /** Terminal not-found handler. */\n setNotFound(app: TApp, mw: ConnectMiddleware): void\n\n /** Terminal error handler. */\n setErrorHandler(app: TApp, mw: ConnectMiddleware): void\n\n /**\n * Load the engine before the first `createApp()` — for a runtime that\n * imports it lazily, as the root `expressRuntime()` does so that\n * `@forinda/kickjs` doesn't need `express` installed. Awaited at setup.\n */\n load?(): Promise<void>\n\n /**\n * Body parsers to mount among the default middleware, for an engine that\n * doesn't parse request bodies itself (`capabilities.nativeBodyParsing:\n * false`). `limit` is `bootstrap({ jsonLimit })`.\n */\n bodyParsers?(options: { limit: string | number }): ConnectMiddleware[]\n\n /** Release the engine app on shutdown (Fastify runs its `onClose` hooks). */\n close?(app: TApp): void | Promise<void>\n\n readonly capabilities: RuntimeCapabilities\n}\n\n/**\n * The supported surface adapters use to add HTTP routes, mounts, static dirs,\n * and middleware — engine-agnostic, in place of reaching for the raw Express\n * `app` (spec §4.4). Exposed as {@link AdapterContext.http}. Built by the\n * Application over the active {@link HttpRuntime}, so an adapter written against\n * this works under any runtime; the raw `app` escape hatch stays available for\n * the rare engine-specific need.\n */\nexport interface AdapterHttp {\n /** Register a single context-handler route (e.g. a docs or transport endpoint). */\n route(method: RouteMethod, path: string, handler: CtxHandler): void\n /** Mount a pre-built route table under a path prefix. */\n mount(prefix: string, routes: RouteEntry[]): void\n /** Serve a static directory under a path prefix. */\n serveStatic(prefix: string, dir: string): void\n /** Register a connect-style middleware (optionally path-scoped). */\n use(mw: ConnectMiddleware, opts?: UseConnectOptions): void\n}\n"],"mappings":";;;;;;;;;;uDA0JA,SAAgB,oBAAoB,IAAc,MAAyB,CAGzE,IAAI,MAAQ,cAAc,IAAI,KAAK,EAC9B,QACH,MAAQ,OAAO,OAAO,CACpB,OAAQ,MAAM,OACd,KAAM,MAAM,KACZ,WAAY,MAAM,KAAK,WACvB,YAAa,MAAM,KAAK,YACxB,MAAO,MAAM,KAAK,OAAS,YAC3B,QAAS,MAAM,KAAK,SAAW,MAAM,KACrC,KAAM,MAAM,IACd,CAAC,EACD,cAAc,IAAI,MAAO,KAAK,GAE/B,IAAsC,YAAc,KACvD,CAEA,MAAM,8BAAgB,IAAI,QAEpB,4BAA0B,IAAI,IAmCpC,SAAgB,kBAAkB,IAAuB,CACvD,OAAO,eAAe,WAAa,SAAS,KAAK,IAAI,OAAO,CAC9D,CAOA,SAAgB,cAAc,KAAuB,CACnD,GAAI,CACF,OAAO,KAAK,UAAU,IAAI,CAC5B,OAAS,IAAK,CACZ,GAAI,CAAC,kBAAkB,GAAG,EAAG,MAAM,IACnC,OAAO,KAAK,UAAU,MAAO,KAAM,QACjC,OAAO,OAAU,SAAW,MAAM,SAAS,EAAI,KACjD,CACF,CACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"session-DQG72vCf.d.mts","names":["Request","Response","NextFunction"],"sources":["../src/http/middleware/session.ts"],"mappings":";;;;;;;;;;;;;UA+BiB;GACd;;UAGc;EACf,IAAI,cAAc,QAAQ;EAC1B,IAAI,aAAa,MAAM,aAAa,iBAAiB;EACrD,QAAQ,cAAc;EACtB,OAAO,aAAa,iBAAiB;;UAGtB;EACf;EACA,MAAM;EACN,cAAc;EACd,WAAW;EACX,QAAQ;;UAGO;;;;;;;;;;;;;;EAcf;;EAEA;;EAEA;;EAEA;;EAEA;;;;;;EAMA;;EAEA;IACE;IACA;IACA;IACA;IACA;;;;;;;;;;;;EAYF,QAAQ;;;cAUG,uBAAuB;mBACjB;;mBAEA;mBACA;EAEjB;;EAWA;EAMM,IAAI,cAAc,QAAQ;EAW1B,IAAI,aAAa,MAAM,aAAa,iBAAiB;EAkBrD,QAAQ,cAAc;EAKtB,MAAM,aAAa,iBAAiB;UASlC;;iBA6EM,QAAQ,SAAS,kBAAc,KAuPhCA,gBAAO,KAAOC,iBAAQ,MAAQC"}
|