@forinda/kickjs 10.14.2 → 10.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{adapter-B64IOivZ.d.mts → adapter-D_nUmKEQ.d.mts} +172 -34
- package/dist/adapter-D_nUmKEQ.d.mts.map +1 -0
- package/dist/{allowed-hosts-U12_gESr.d.mts → allowed-hosts-BQlQFt-1.d.mts} +6 -1
- package/dist/allowed-hosts-BQlQFt-1.d.mts.map +1 -0
- package/dist/{app-module-EmIojM4d.d.mts → app-module-BmViGLgj.d.mts} +5 -5
- package/dist/{app-module-EmIojM4d.d.mts.map → app-module-BmViGLgj.d.mts.map} +1 -1
- package/dist/application-B16ltRnC.mjs +14 -0
- package/dist/application-B16ltRnC.mjs.map +1 -0
- package/dist/{application-CGcY8SZZ.d.mts → application-ClCq0AgY.d.mts} +190 -53
- package/dist/application-ClCq0AgY.d.mts.map +1 -0
- package/dist/{body-policy-Be3Y0hjq.mjs → body-policy-D8LveWmO.mjs} +2 -2
- package/dist/{body-policy-Be3Y0hjq.mjs.map → body-policy-D8LveWmO.mjs.map} +1 -1
- package/dist/{bootstrap-Bvk3BWJX.mjs → bootstrap-C5NvsxHQ.mjs} +3 -3
- package/dist/bootstrap-C5NvsxHQ.mjs.map +1 -0
- package/dist/{bounded-counters-Bh5jeT9I.mjs → bounded-counters-BtvB2daV.mjs} +2 -2
- package/dist/{bounded-counters-Bh5jeT9I.mjs.map → bounded-counters-BtvB2daV.mjs.map} +1 -1
- package/dist/{breach-padding-DfT9MXGb.d.mts → breach-padding-BUuc21Eu.d.mts} +6 -1
- package/dist/breach-padding-BUuc21Eu.d.mts.map +1 -0
- package/dist/{cache-DMIt3c6M.d.mts → cache-ByX5O2Hp.d.mts} +26 -1
- package/dist/{cache-DMIt3c6M.d.mts.map → cache-ByX5O2Hp.d.mts.map} +1 -1
- package/dist/{client-ip-CGH_IvnC.mjs → client-ip-CWvyHmqt.mjs} +2 -2
- package/dist/{client-ip-CGH_IvnC.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-CjFxvh0v.mjs → config-BIQoDNil.mjs} +3 -3
- package/dist/{config-CjFxvh0v.mjs.map → config-BIQoDNil.mjs.map} +1 -1
- package/dist/container-DtdUiRwr.d.mts +3 -0
- package/dist/{context-BvZLaTeE.mjs → context-BzFNflxV.mjs} +3 -3
- package/dist/context-BzFNflxV.mjs.map +1 -0
- package/dist/{context-errors-BZVS0B1O.mjs → context-errors-BmaG4vwd.mjs} +2 -2
- package/dist/context-errors-BmaG4vwd.mjs.map +1 -0
- package/dist/{contributor-runner-fdKy6Tme.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/logger.d.mts +1 -1
- package/dist/core/logger.mjs +1 -1
- package/dist/core/logger.mjs.map +1 -1
- package/dist/core/path.mjs +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-J-q6PuSU.d.mts → cors-u1OwTxQ8.d.mts} +6 -1
- package/dist/cors-u1OwTxQ8.d.mts.map +1 -0
- package/dist/{cron-DGV1AE0R.d.mts → cron-Bxm2MY8u.d.mts} +10 -1
- package/dist/cron-Bxm2MY8u.d.mts.map +1 -0
- package/dist/{csrf-DjtJPgA3.d.mts → csrf-8-Jknvmc.d.mts} +12 -2
- package/dist/csrf-8-Jknvmc.d.mts.map +1 -0
- package/dist/{decorate-DRbXCNQz.mjs → decorate-C3to8dG-.mjs} +3 -3
- package/dist/{decorate-DRbXCNQz.mjs.map → decorate-C3to8dG-.mjs.map} +1 -1
- package/dist/{decorators-BAD8qjuq.d.mts → decorators-Bflncyz6.d.mts} +122 -6
- package/dist/decorators-Bflncyz6.d.mts.map +1 -0
- package/dist/{define-adapter-DMo6og81.mjs → define-adapter-DCjNTP6m.mjs} +2 -2
- package/dist/define-adapter-DCjNTP6m.mjs.map +1 -0
- package/dist/{di-hooks-DCqt2yJ9.mjs → di-hooks-DTDy7ABs.mjs} +2 -2
- package/dist/di-hooks-DTDy7ABs.mjs.map +1 -0
- package/dist/{disposables-BsdVu69-.mjs → disposables-BC291ukb.mjs} +1 -1
- package/dist/{driver-oZBQDJZz.mjs → driver-D59oWDec.mjs} +3 -3
- package/dist/{driver-oZBQDJZz.mjs.map → driver-D59oWDec.mjs.map} +1 -1
- package/dist/{error-handler-Dl_gZRNK.d.mts → error-handler-gZLQFHeE.d.mts} +2 -2
- package/dist/{error-handler-Dl_gZRNK.d.mts.map → error-handler-gZLQFHeE.d.mts.map} +1 -1
- package/dist/{errors-DZGuPLoZ.d.mts → errors-CppqPy0A.d.mts} +2 -1
- package/dist/errors-CppqPy0A.d.mts.map +1 -0
- package/dist/{express-f9CTA8qO.mjs → express-JAXx9MK0.mjs} +3 -3
- package/dist/{express-f9CTA8qO.mjs.map → express-JAXx9MK0.mjs.map} +1 -1
- package/dist/{express-lazy-DMxcLBpT.mjs → express-lazy-jIFBeDpY.mjs} +3 -3
- package/dist/{express-lazy-DMxcLBpT.mjs.map → express-lazy-jIFBeDpY.mjs.map} +1 -1
- package/dist/{handler-B66laQY0.mjs → handler-C8iAD_xz.mjs} +3 -3
- package/dist/{handler-B66laQY0.mjs.map → handler-C8iAD_xz.mjs.map} +1 -1
- package/dist/{helmet-Rwkbp9IS.d.mts → helmet-1H0LKr6y.d.mts} +6 -1
- package/dist/helmet-1H0LKr6y.d.mts.map +1 -0
- package/dist/{host-DalMsn5Z.mjs → host-Crxmi91N.mjs} +2 -2
- package/dist/{host-DalMsn5Z.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/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/views.d.mts +1 -1
- package/dist/http/middleware/views.mjs +2 -2
- package/dist/http/middleware/views.mjs.map +1 -1
- package/dist/http/query/index.d.mts +1 -1
- package/dist/http/query/index.mjs +2 -2
- package/dist/http/router-builder.d.mts +1 -1
- package/dist/http/router-builder.mjs +2 -2
- package/dist/http/runtimes/express.d.mts +3 -2
- 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 -3
- 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 -1
- package/dist/http/runtimes/h3.mjs +2 -2
- package/dist/http/runtimes/h3.mjs.map +1 -1
- package/dist/{index-ZbCnCyQx.d.mts → index-CtjmSXFy.d.mts} +11 -1
- package/dist/index-CtjmSXFy.d.mts.map +1 -0
- package/dist/{index-CFTwnev9.d.mts → index-DoukvKwh.d.mts} +2 -2
- package/dist/{index-CFTwnev9.d.mts.map → index-DoukvKwh.d.mts.map} +1 -1
- package/dist/index.d.mts +34 -28
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/dist/{interfaces-BQhYh3lL.d.mts → interfaces-CvO9sAea.d.mts} +3 -3
- package/dist/{interfaces-BQhYh3lL.d.mts.map → interfaces-CvO9sAea.d.mts.map} +1 -1
- package/dist/{is-production-9QzMIRuO.mjs → is-production-LziEMGrc.mjs} +2 -2
- package/dist/{is-production-9QzMIRuO.mjs.map → is-production-LziEMGrc.mjs.map} +1 -1
- package/dist/{jobs-CuZqVDDG.mjs → jobs-D7ToA0yF.mjs} +3 -3
- package/dist/jobs-D7ToA0yF.mjs.map +1 -0
- package/dist/{kv-stores-wTD3VDPB.d.mts → kv-stores-DdGPLXQG.d.mts} +32 -7
- package/dist/kv-stores-DdGPLXQG.d.mts.map +1 -0
- package/dist/{kv-stores-C9CJ3xCB.mjs → kv-stores-DpM57Xr5.mjs} +3 -3
- package/dist/kv-stores-DpM57Xr5.mjs.map +1 -0
- package/dist/{lazy-serve-static-DVWmKM7Z.mjs → lazy-serve-static-DxI2K-zs.mjs} +3 -3
- package/dist/{lazy-serve-static-DVWmKM7Z.mjs.map → lazy-serve-static-DxI2K-zs.mjs.map} +1 -1
- package/dist/{logger-BL8MiSrm.d.mts → logger-ByJsVwqY.d.mts} +3 -3
- package/dist/{logger-BL8MiSrm.d.mts.map → logger-ByJsVwqY.d.mts.map} +1 -1
- package/dist/{metadata-BZRtQog3.mjs → metadata-nTTSnVTO.mjs} +1 -1
- package/dist/{observers-B4VnKAHK.mjs → observers-fQtCIKLq.mjs} +2 -2
- package/dist/observers-fQtCIKLq.mjs.map +1 -0
- package/dist/{precompressed-AxF66Ls0.mjs → precompressed-BtwmgzyS.mjs} +2 -2
- package/dist/{precompressed-AxF66Ls0.mjs.map → precompressed-BtwmgzyS.mjs.map} +1 -1
- package/dist/{query-BwUR-ssX.mjs → query-Dr28oT30.mjs} +2 -2
- package/dist/query-Dr28oT30.mjs.map +1 -0
- package/dist/{rate-limit-DMiV6bAq.d.mts → rate-limit-BQx_P6gG.d.mts} +11 -1
- package/dist/rate-limit-BQx_P6gG.d.mts.map +1 -0
- package/dist/{reactivity-Dski64km.d.mts → reactivity-KZOrwVeK.d.mts} +32 -1
- package/dist/reactivity-KZOrwVeK.d.mts.map +1 -0
- package/dist/{reply-B5kZ6VGv.mjs → reply-ChoI5SvM.mjs} +3 -3
- package/dist/{reply-B5kZ6VGv.mjs.map → reply-ChoI5SvM.mjs.map} +1 -1
- package/dist/{request-id-B_n-3A16.d.mts → request-id-B9Myiv75.d.mts} +2 -1
- package/dist/request-id-B9Myiv75.d.mts.map +1 -0
- package/dist/{request-logger-BV1C5r5q.d.mts → request-logger-CYyAuPmo.d.mts} +6 -1
- package/dist/request-logger-CYyAuPmo.d.mts.map +1 -0
- package/dist/{request-scope-D2WQwatk.mjs → request-scope-BfSNdmz9.mjs} +3 -3
- package/dist/{request-scope-D2WQwatk.mjs.map → request-scope-BfSNdmz9.mjs.map} +1 -1
- package/dist/{respond-C6ohI69y.mjs → respond-1BjaDME9.mjs} +2 -2
- package/dist/{respond-C6ohI69y.mjs.map → respond-1BjaDME9.mjs.map} +1 -1
- package/dist/rolldown-runtime-B5KeNctS.mjs +11 -0
- package/dist/{route-flag-CHiMvgar.mjs → route-flag-B6ZmhkfI.mjs} +3 -3
- package/dist/{route-flag-CHiMvgar.mjs.map → route-flag-B6ZmhkfI.mjs.map} +1 -1
- package/dist/{route-policy-ckK7N1eN.mjs → route-policy-BG--gAcF.mjs} +2 -2
- package/dist/route-policy-BG--gAcF.mjs.map +1 -0
- package/dist/{router-builder-Dtyya4qP.d.mts → router-builder-BkIW_qjz.d.mts} +3 -2
- package/dist/router-builder-BkIW_qjz.d.mts.map +1 -0
- package/dist/{router-builder-D2cly8Wt.mjs → router-builder-DHKtp4I8.mjs} +3 -3
- package/dist/router-builder-DHKtp4I8.mjs.map +1 -0
- package/dist/{runtime-D9TN6CpL.mjs → runtime-CUfFIHiC.mjs} +3 -3
- package/dist/runtime-CUfFIHiC.mjs.map +1 -0
- package/dist/{session-CXWu2rXW.d.mts → session-DPTbfwKO.d.mts} +40 -1
- package/dist/session-DPTbfwKO.d.mts.map +1 -0
- package/dist/{settings-v2N3V8Bl.mjs → settings-I7GUX5ps.mjs} +3 -3
- package/dist/{settings-v2N3V8Bl.mjs.map → settings-I7GUX5ps.mjs.map} +1 -1
- package/dist/{token-DtW16tw3.mjs → token-uWfhVlfe.mjs} +1 -1
- package/dist/{upload-eNNueUxR.d.mts → upload-O3VTcODy.d.mts} +3 -3
- package/dist/{upload-eNNueUxR.d.mts.map → upload-O3VTcODy.d.mts.map} +1 -1
- package/dist/{upload-config-BXjBiNjC.mjs → upload-config-BXqBuyza.mjs} +2 -2
- package/dist/{upload-config-BXjBiNjC.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-BbthfLBb.d.mts → validate-CTgfm7oE.d.mts} +2 -2
- package/dist/{validate-BbthfLBb.d.mts.map → validate-CTgfm7oE.d.mts.map} +1 -1
- package/dist/{view-renderer-C4sMEruA.mjs → view-renderer-Bf1Wy-DQ.mjs} +3 -3
- package/dist/view-renderer-Bf1Wy-DQ.mjs.map +1 -0
- package/dist/{web-crypto-SXVOPDxW.mjs → web-crypto-JzoGmiG0.mjs} +2 -2
- package/dist/{web-crypto-SXVOPDxW.mjs.map → web-crypto-JzoGmiG0.mjs.map} +1 -1
- package/dist/web.d.mts +6 -6
- package/dist/web.d.mts.map +1 -1
- package/dist/web.mjs +2 -2
- package/dist/web.mjs.map +1 -1
- package/package.json +10 -10
- package/dist/adapter-B64IOivZ.d.mts.map +0 -1
- package/dist/allowed-hosts-U12_gESr.d.mts.map +0 -1
- package/dist/application-BzimU62Q.mjs +0 -14
- package/dist/application-BzimU62Q.mjs.map +0 -1
- package/dist/application-CGcY8SZZ.d.mts.map +0 -1
- package/dist/bootstrap-Bvk3BWJX.mjs.map +0 -1
- package/dist/breach-padding-DfT9MXGb.d.mts.map +0 -1
- package/dist/container-4iJdDkRH.d.mts +0 -3
- package/dist/context-BvZLaTeE.mjs.map +0 -1
- package/dist/context-errors-BZVS0B1O.mjs.map +0 -1
- package/dist/contributor-runner-fdKy6Tme.mjs.map +0 -1
- package/dist/core-CCIpjo6g.mjs +0 -12
- package/dist/core-CCIpjo6g.mjs.map +0 -1
- package/dist/cors-J-q6PuSU.d.mts.map +0 -1
- package/dist/cron-DGV1AE0R.d.mts.map +0 -1
- package/dist/csrf-DjtJPgA3.d.mts.map +0 -1
- package/dist/decorators-BAD8qjuq.d.mts.map +0 -1
- package/dist/define-adapter-DMo6og81.mjs.map +0 -1
- package/dist/di-hooks-DCqt2yJ9.mjs.map +0 -1
- package/dist/errors-DZGuPLoZ.d.mts.map +0 -1
- package/dist/helmet-Rwkbp9IS.d.mts.map +0 -1
- package/dist/index-ZbCnCyQx.d.mts.map +0 -1
- package/dist/jobs-CuZqVDDG.mjs.map +0 -1
- package/dist/kv-stores-C9CJ3xCB.mjs.map +0 -1
- package/dist/kv-stores-wTD3VDPB.d.mts.map +0 -1
- package/dist/observers-B4VnKAHK.mjs.map +0 -1
- package/dist/query-BwUR-ssX.mjs.map +0 -1
- package/dist/rate-limit-DMiV6bAq.d.mts.map +0 -1
- package/dist/reactivity-Dski64km.d.mts.map +0 -1
- package/dist/request-id-B_n-3A16.d.mts.map +0 -1
- package/dist/request-logger-BV1C5r5q.d.mts.map +0 -1
- package/dist/rolldown-runtime-DuhQYUab.mjs +0 -11
- package/dist/route-policy-ckK7N1eN.mjs.map +0 -1
- package/dist/router-builder-D2cly8Wt.mjs.map +0 -1
- package/dist/router-builder-Dtyya4qP.d.mts.map +0 -1
- package/dist/runtime-D9TN6CpL.mjs.map +0 -1
- package/dist/session-CXWu2rXW.d.mts.map +0 -1
- package/dist/url-for-C4Eomib7.mjs +0 -12
- package/dist/url-for-C4Eomib7.mjs.map +0 -1
- package/dist/view-renderer-C4sMEruA.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"decorators.mjs","names":[],"sources":["../../src/core/decorators.ts"],"sourcesContent":["import 'reflect-metadata'\nimport './di-hooks'\nimport { registerInjectable } from '@forinda/kickjs-di'\nimport { METADATA, Scope } from './interfaces'\nimport {\n setClassMeta,\n setMethodMeta,\n pushClassMeta,\n pushMethodMeta,\n setInMetaMap,\n} from './metadata'\n\n// The DI decorators (`@Service`, `@Inject`, `@Value`, …) live in `@forinda/kickjs-di`;\n// this module adds the HTTP ones and `@Asset`, and re-exports both.\nexport {\n Injectable,\n Service,\n Component,\n Repository,\n PostConstruct,\n PreDestroy,\n Autowired,\n Inject,\n Value,\n Builder,\n withBuilder,\n type PropertyOrParameterDecorator,\n type EnvKey,\n type Env,\n} from '@forinda/kickjs-di'\n\n/**\n * Mark a class as an HTTP controller and register it in the DI container.\n *\n * Route prefixes are defined by the module's `routes().path` — the single\n * source of truth for where routes mount. The legacy\n * `@Controller('/path')` parameter was removed in v4; if your code\n * still passes a string, see `docs/guide/migration-v3-to-v4.md` for\n * the rename map.\n */\nexport function Controller(): ClassDecorator {\n return (target: any) => {\n setClassMeta(METADATA.CLASS_KIND, 'controller', target)\n registerInjectable(target, Scope.SINGLETON)\n }\n}\n\n// ── @Asset — typed asset path injection ─────────────────────────────────\n\nimport type { KickAssets } from './assets'\n\n/**\n * Flatten the nested `KickAssets` augmentation (typegen-emitted in\n * PR 4) into a string-literal union of dot/slash-joined paths.\n *\n * `interface KickAssets { mails: { welcome: () => string; orders: {\n * confirmation: () => string } } }` becomes\n * `'mails/welcome' | 'mails/orders/confirmation'`.\n *\n * Returns `never` when `KickAssets` is empty (no typegen has run yet)\n * so `AssetKeyArg` falls through to accept any string.\n */\ntype FlattenAssets<T, Prefix extends string = ''> = {\n [K in keyof T & string]: T[K] extends () => string\n ? `${Prefix}${K}`\n : T[K] extends Record<string, unknown>\n ? FlattenAssets<T[K], `${Prefix}${K}/`>\n : never\n}[keyof T & string]\n\n/** Flat union of every known `<namespace>/<key>` path. */\nexport type AssetKey = FlattenAssets<KickAssets>\n\n/**\n * Constraint mirroring `ValueKey<K>` — accepts any string when\n * `AssetKey` is `never` (back-compat for adopters who haven't run\n * `kick typegen` yet) but locks the argument to known literals once\n * the typegen-augmented `KickAssets` interface is populated.\n */\ntype AssetKeyArg<K extends string> = [AssetKey] extends [never] ? K : K & AssetKey\n\n/**\n * Inject the resolved file-system path for a typed asset. Mirrors\n * `@Value`'s lazy-getter pattern — the asset is resolved on every\n * property access, NOT at class instantiation, so:\n *\n * - Tests can swap fixtures + clear the cache without re-instantiating\n * the consuming class.\n * - The first access cost is paid once per process (the manifest cache\n * in `core/assets.ts` makes subsequent calls cheap).\n *\n * Type-safety:\n *\n * - Without typegen, any string key is accepted (back-compat — same\n * trick as `@Value`).\n * - After typegen, `KickAssets` is populated and `AssetKey` is a\n * union of every flattened `<namespace>/<key>` path. Unknown keys\n * become a TS error.\n *\n * @example\n * ```ts\n * import { Service, Asset } from '@forinda/kickjs'\n *\n * `@Service()`\n * class MailService {\n * `@Asset('mails/welcome')`\n * private welcomeTemplate!: string\n *\n * send(user: User) {\n * return ejs.renderFile(this.welcomeTemplate, { user })\n * }\n * }\n * ```\n */\nexport function Asset<K extends string>(assetKey: AssetKeyArg<K>): PropertyDecorator {\n return (target, propertyKey) => {\n setInMetaMap(METADATA.ASSET, target, propertyKey as string, { assetKey })\n }\n}\n\n// ── HTTP Route Decorators ───────────────────────────────────────────────\n\nexport interface RouteDefinition {\n method: string\n path: string\n handlerName: string\n validation?: {\n /** Schema validating the request body — Zod, Valibot, Yup, any Standard Schema or KickSchema. */\n body?: any\n /** Schema validating query parameters — any library `detectSchema` accepts. */\n query?: any\n /** Schema validating URL params — any library `detectSchema` accepts. */\n params?: any\n /**\n * DECLARED response schema — never validated at runtime. Feeds two\n * consumers from one source of truth: the Swagger adapter's success\n * response schema, and `kick typegen`'s `KickRoutes[...].response`\n * (winning over return-type inference when present).\n */\n response?: any\n /** Schema name in OpenAPI components/schemas for the request body. Auto-generated from handler name if omitted. */\n name?: string\n }\n}\n\nfunction createRouteDecorator(method: string) {\n return (path?: string, validation?: RouteDefinition['validation']): MethodDecorator => {\n return (target, propertyKey) => {\n pushClassMeta<RouteDefinition>(METADATA.ROUTES, target.constructor, {\n method,\n path: path || '/',\n handlerName: propertyKey as string,\n validation,\n })\n }\n }\n}\n\nexport const Get = createRouteDecorator('GET')\nexport const Post = createRouteDecorator('POST')\nexport const Put = createRouteDecorator('PUT')\nexport const Delete = createRouteDecorator('DELETE')\nexport const Patch = createRouteDecorator('PATCH')\n\n// ── Query Params Decorator ─────────────────────────────────────────────\n\nexport interface ApiQueryParamsConfig {\n /** Fields that can be used in filter queries (e.g., `?filter=status:eq:active`) */\n filterable?: string[]\n /** Fields that can be used in sort queries (e.g., `?sort=createdAt:desc`) */\n sortable?: string[]\n /** Fields that are searched with the `?q=` parameter */\n searchable?: string[]\n}\n\n/**\n * Column-object-based query params config (e.g., from DrizzleQueryParamsConfig).\n * `Object.keys()` is used to derive field names for OpenAPI docs.\n */\nexport interface ColumnApiQueryParamsConfig {\n columns: Record<string, any>\n sortable?: Record<string, any>\n searchColumns?: any[]\n [key: string]: any\n}\n\n/**\n * Normalize a query params config to the string-based ApiQueryParamsConfig.\n * Handles both string-based and column-object-based configs.\n */\nexport function normalizeApiQueryParamsConfig(\n config: ApiQueryParamsConfig | ColumnApiQueryParamsConfig,\n): ApiQueryParamsConfig {\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: config.searchColumns\n ? config.searchColumns.map((col: any) => col?.name ?? '').filter(Boolean)\n : undefined,\n }\n }\n return config as ApiQueryParamsConfig\n}\n\n/**\n * Document the query parameters accepted by a GET endpoint.\n * Used by SwaggerAdapter to generate `filter`, `sort`, `page`, `limit`, and `q` params\n * in the OpenAPI spec, with descriptions listing the allowed fields.\n *\n * Accepts both string-based configs and column-object configs (e.g., DrizzleQueryParamsConfig).\n *\n * @example\n * ```ts\n * // String-based\n * @ApiQueryParams({\n * filterable: ['status', 'category', 'price'],\n * sortable: ['name', 'createdAt', 'price'],\n * searchable: ['name', 'description'],\n * })\n *\n * // Column-object-based (Drizzle)\n * @ApiQueryParams(TASK_QUERY_CONFIG)\n * ```\n */\nexport function ApiQueryParams(\n config: ApiQueryParamsConfig | ColumnApiQueryParamsConfig,\n): MethodDecorator {\n return (target, propertyKey) => {\n const normalized = normalizeApiQueryParamsConfig(config)\n setMethodMeta(METADATA.QUERY_PARAMS, normalized, target.constructor, propertyKey as string)\n }\n}\n\n// ── Middleware Decorators ───────────────────────────────────────────────\n\n/**\n * Middleware handler function.\n * Generic `TCtx` defaults to `any` — import `RequestContext` from\n * `@forinda/kickjs` for full type safety:\n *\n * ```ts\n * import type { MiddlewareHandler } from '@forinda/kickjs'\n * import type { RequestContext } from '@forinda/kickjs'\n *\n * const auth: MiddlewareHandler<RequestContext> = (ctx, next) => {\n * ctx.body // fully typed\n * next()\n * }\n * ```\n *\n * A guard stops the request by writing a response and not calling `next()`.\n * Whatever it returns is ignored, so `if (!user) return ctx.problem.unauthorized()`\n * — the idiom handlers use — type-checks here too.\n */\nexport type MiddlewareHandler<TCtx = any> = (ctx: TCtx, next: () => void) => unknown\n\n/** Attach middleware handlers to a class or method */\nexport function Middleware(...handlers: MiddlewareHandler[]): ClassDecorator & MethodDecorator {\n return (target: any, propertyKey?: string | symbol) => {\n if (propertyKey) {\n pushMethodMeta(\n METADATA.METHOD_MIDDLEWARES,\n target.constructor,\n propertyKey as string,\n ...handlers,\n )\n } else {\n pushClassMeta(METADATA.CLASS_MIDDLEWARES, target, ...handlers)\n }\n }\n}\n\n// ── File Upload Decorator ───────────────────────────────────────────────\n\n/**\n * File filter — accepts short extensions ('jpg'), full MIME types ('image/jpeg'),\n * wildcards ('image/*'), or a function `(mimetype, filename) => boolean` for full control.\n */\nexport type FileTypeFilter = string[] | ((mimetype: string, filename: string) => boolean)\n\n/**\n * Shared upload options used by both the `@FileUpload` decorator and the\n * `upload.single()` / `upload.array()` / `upload.none()` middleware.\n */\nexport interface BaseUploadOptions {\n /** Max file size in bytes (default: 5MB) */\n maxSize?: number\n /**\n * Allowed file types:\n * - **string[]** — short extensions ('jpg'), full MIME types ('image/jpeg'), or wildcards ('image/*')\n * - **function** — `(mimetype, filename) => boolean` for full control\n */\n allowedTypes?: FileTypeFilter\n /** Extend the built-in extension-to-MIME map */\n customMimeMap?: Record<string, string>\n /**\n * The file's server-side name, `file.filename`, from what the client sent.\n * Default: a random UUID plus the client name's extension when it names the\n * file's type (`3f2b….png`) — never the client's name itself. The result must not\n * contain a slash or backslash, nor be `.` or `..`. Disk storage (`dest`) keeps the name\n * it wrote the file under.\n */\n rename?: (file: {\n originalname: string\n mimetype: string\n fieldname: string\n size: number\n }) => string\n}\n\nexport interface FileUploadConfig extends BaseUploadOptions {\n mode: 'single' | 'array' | 'none'\n /** Form field name (default: 'file') */\n fieldName?: string\n /** Max files for array mode (default: 10) */\n maxCount?: number\n}\n\n/** Configure file upload handling for a controller method */\nexport function FileUpload(config: FileUploadConfig): MethodDecorator {\n return (target, propertyKey) => {\n setMethodMeta(METADATA.FILE_UPLOAD, config, target.constructor, propertyKey as string)\n }\n}\n"],"mappings":";;;;;;;;;;A,0YAwCA,SAAgB,YAA6B,CAC3C,MAAQ,SAAgB,CACtB,aAAa,SAAS,WAAY,aAAc,MAAM,EACtD,mBAAmB,OAAQ,MAAM,SAAS,CAC5C,CACF,CAqEA,SAAgB,MAAwB,SAA6C,CACnF,OAAQ,OAAQ,cAAgB,CAC9B,aAAa,SAAS,MAAO,OAAQ,YAAuB,CAAE,QAAS,CAAC,CAC1E,CACF,CA2BA,SAAS,qBAAqB,OAAgB,CAC5C,OAAQ,KAAe,cACb,OAAQ,cAAgB,CAC9B,cAA+B,SAAS,OAAQ,OAAO,YAAa,CAClE,OACA,KAAM,MAAQ,IACd,YAAa,YACb,UACF,CAAC,CACH,CAEJ,CAEA,MAAa,IAAM,qBAAqB,KAAK,EAChC,KAAO,qBAAqB,MAAM,EAClC,IAAM,qBAAqB,KAAK,EAChC,OAAS,qBAAqB,QAAQ,EACtC,MAAQ,qBAAqB,OAAO,EA4BjD,SAAgB,8BACd,OACsB,CAUtB,MATI,YAAa,QAAU,OAAO,SAAW,OAAO,OAAO,SAAY,SAC9D,CACL,WAAY,OAAO,KAAK,OAAO,OAAO,EACtC,SAAU,OAAO,SAAW,OAAO,KAAK,OAAO,QAAQ,EAAI,IAAA,GAC3D,WAAY,OAAO,cACf,OAAO,cAAc,IAAK,KAAa,KAAK,MAAQ,EAAE,CAAC,CAAC,OAAO,OAAO,EACtE,IAAA,EACN,EAEK,MACT,CAsBA,SAAgB,eACd,OACiB,CACjB,OAAQ,OAAQ,cAAgB,CAC9B,IAAM,WAAa,8BAA8B,MAAM,EACvD,cAAc,SAAS,aAAc,WAAY,OAAO,YAAa,WAAqB,CAC5F,CACF,CA0BA,SAAgB,WAAW,GAAG,SAAiE,CAC7F,OAAQ,OAAa,cAAkC,CACjD,YACF,eACE,SAAS,mBACT,OAAO,YACP,YACA,GAAG,QACL,EAEA,cAAc,SAAS,kBAAmB,OAAQ,GAAG,QAAQ,CAEjE,CACF,CAiDA,SAAgB,WAAW,OAA2C,CACpE,OAAQ,OAAQ,cAAgB,CAC9B,cAAc,SAAS,YAAa,OAAQ,OAAO,YAAa,WAAqB,CACvF,CACF,C"}
|
|
1
|
+
{"version":3,"file":"decorators.mjs","names":[],"sources":["../../src/core/decorators.ts"],"sourcesContent":["import 'reflect-metadata'\nimport './di-hooks'\nimport { registerInjectable } from '@forinda/kickjs-di'\nimport { METADATA, Scope } from './interfaces'\nimport {\n setClassMeta,\n setMethodMeta,\n pushClassMeta,\n pushMethodMeta,\n setInMetaMap,\n} from './metadata'\n\n// The DI decorators (`@Service`, `@Inject`, `@Value`, …) live in `@forinda/kickjs-di`;\n// this module adds the HTTP ones and `@Asset`, and re-exports both.\nexport {\n Injectable,\n Service,\n Component,\n Repository,\n PostConstruct,\n PreDestroy,\n Autowired,\n Inject,\n Value,\n Builder,\n withBuilder,\n type PropertyOrParameterDecorator,\n type EnvKey,\n type Env,\n} from '@forinda/kickjs-di'\n\n/**\n * Mark a class as an HTTP controller and register it in the DI container.\n *\n * Route prefixes are defined by the module's `routes().path` — the single\n * source of truth for where routes mount. The legacy\n * `@Controller('/path')` parameter was removed in v4; if your code\n * still passes a string, see\n * https://kickjs.app/guide/migration-v3-to-v4#controller-—-drop-the-path-argument\n */\nexport function Controller(): ClassDecorator {\n return (target: any) => {\n setClassMeta(METADATA.CLASS_KIND, 'controller', target)\n registerInjectable(target, Scope.SINGLETON)\n }\n}\n\n// ── @Asset — typed asset path injection ─────────────────────────────────\n\nimport type { KickAssets } from './assets'\n\n/**\n * Flatten the nested `KickAssets` augmentation (typegen-emitted in\n * PR 4) into a string-literal union of dot/slash-joined paths.\n *\n * `interface KickAssets { mails: { welcome: () => string; orders: {\n * confirmation: () => string } } }` becomes\n * `'mails/welcome' | 'mails/orders/confirmation'`.\n *\n * Returns `never` when `KickAssets` is empty (no typegen has run yet)\n * so `AssetKeyArg` falls through to accept any string.\n */\ntype FlattenAssets<T, Prefix extends string = ''> = {\n [K in keyof T & string]: T[K] extends () => string\n ? `${Prefix}${K}`\n : T[K] extends Record<string, unknown>\n ? FlattenAssets<T[K], `${Prefix}${K}/`>\n : never\n}[keyof T & string]\n\n/** Flat union of every known `<namespace>/<key>` path. */\nexport type AssetKey = FlattenAssets<KickAssets>\n\n/**\n * Constraint mirroring `ValueKey<K>` — accepts any string when\n * `AssetKey` is `never` (back-compat for adopters who haven't run\n * `kick typegen` yet) but locks the argument to known literals once\n * the typegen-augmented `KickAssets` interface is populated.\n */\ntype AssetKeyArg<K extends string> = [AssetKey] extends [never] ? K : K & AssetKey\n\n/**\n * Inject the resolved file-system path for a typed asset. Mirrors\n * `@Value`'s lazy-getter pattern — the asset is resolved on every\n * property access, NOT at class instantiation, so:\n *\n * - Tests can swap fixtures + clear the cache without re-instantiating\n * the consuming class.\n * - The first access cost is paid once per process (the manifest cache\n * in `core/assets.ts` makes subsequent calls cheap).\n *\n * Type-safety:\n *\n * - Without typegen, any string key is accepted (back-compat — same\n * trick as `@Value`).\n * - After typegen, `KickAssets` is populated and `AssetKey` is a\n * union of every flattened `<namespace>/<key>` path. Unknown keys\n * become a TS error.\n *\n * @example\n * ```ts\n * import { Service, Asset } from '@forinda/kickjs'\n *\n * `@Service()`\n * class MailService {\n * `@Asset('mails/welcome')`\n * private welcomeTemplate!: string\n *\n * send(user: User) {\n * return ejs.renderFile(this.welcomeTemplate, { user })\n * }\n * }\n * ```\n *\n * @see https://kickjs.app/guide/asset-manager\n */\nexport function Asset<K extends string>(assetKey: AssetKeyArg<K>): PropertyDecorator {\n return (target, propertyKey) => {\n setInMetaMap(METADATA.ASSET, target, propertyKey as string, { assetKey })\n }\n}\n\n// ── HTTP Route Decorators ───────────────────────────────────────────────\n\n/** A route as a route decorator records it: method, path, handler name and validation schemas. */\nexport interface RouteDefinition {\n method: string\n path: string\n handlerName: string\n validation?: {\n /** Schema validating the request body — Zod, Valibot, Yup, any Standard Schema or KickSchema. */\n body?: any\n /** Schema validating query parameters — any library `detectSchema` accepts. */\n query?: any\n /** Schema validating URL params — any library `detectSchema` accepts. */\n params?: any\n /**\n * DECLARED response schema — never validated at runtime. Feeds two\n * consumers from one source of truth: the Swagger adapter's success\n * response schema, and `kick typegen`'s `KickRoutes[...].response`\n * (winning over return-type inference when present).\n */\n response?: any\n /** Schema name in OpenAPI components/schemas for the request body. Auto-generated from handler name if omitted. */\n name?: string\n }\n}\n\nfunction createRouteDecorator(method: string) {\n return (path?: string, validation?: RouteDefinition['validation']): MethodDecorator => {\n return (target, propertyKey) => {\n pushClassMeta<RouteDefinition>(METADATA.ROUTES, target.constructor, {\n method,\n path: path || '/',\n handlerName: propertyKey as string,\n validation,\n })\n }\n }\n}\n\n/**\n * Routes `GET` requests at `path` (default `'/'`, under the module's mount)\n * to this method. `validation` takes `body` / `query` / `params` schemas\n * (Zod, Valibot, Yup or any Standard Schema) and a declared `response`.\n *\n * @example\n * ```ts\n * `@Get('/:id', { params: z.object({ id: z.string() }) })`\n * show(ctx: RequestContext) {\n * // …\n * }\n * ```\n *\n * @see https://kickjs.app/guide/controllers#route-decorators\n */\nexport const Get = createRouteDecorator('GET')\n/**\n * Routes `POST` requests at `path` (default `'/'`, under the module's mount)\n * to this method. A `body` schema in `validation` is checked before the\n * handler runs; a failure skips the handler and, by default, answers `422`\n * with the field errors (`bootstrap({ validationError })` changes that).\n *\n * @example\n * ```ts\n * `@Post('/', { body: createTaskSchema })`\n * create(ctx: RequestContext) {\n * // …\n * }\n * ```\n *\n * @see https://kickjs.app/guide/controllers#route-decorators\n */\nexport const Post = createRouteDecorator('POST')\n/**\n * Routes `PUT` requests at `path` (default `'/'`, under the module's mount)\n * to this method — replacing a resource. Takes the same `validation`\n * schemas as {@link Post}.\n *\n * @example\n * ```ts\n * `@Put('/:id', { body: replaceTaskSchema })`\n * replace(ctx: RequestContext) {\n * // …\n * }\n * ```\n *\n * @see https://kickjs.app/guide/controllers#route-decorators\n */\nexport const Put = createRouteDecorator('PUT')\n/**\n * Routes `DELETE` requests at `path` (default `'/'`, under the module's mount)\n * to this method. `ctx.noContent()` answers `204`.\n *\n * @example\n * ```ts\n * `@Delete('/:id')`\n * remove(ctx: RequestContext) {\n * // …\n * }\n * ```\n *\n * @see https://kickjs.app/guide/controllers#route-decorators\n */\nexport const Delete = createRouteDecorator('DELETE')\n/**\n * Routes `PATCH` requests at `path` (default `'/'`, under the module's mount)\n * to this method — a partial update. Takes the same `validation` schemas\n * as {@link Post}.\n *\n * @example\n * ```ts\n * `@Patch('/:id', { body: updateTaskSchema })`\n * update(ctx: RequestContext) {\n * // …\n * }\n * ```\n *\n * @see https://kickjs.app/guide/controllers#route-decorators\n */\nexport const Patch = createRouteDecorator('PATCH')\n\n// ── Query Params Decorator ─────────────────────────────────────────────\n\n/**\n * Fields a route lets clients filter, sort and search on, for `@ApiQueryParams`.\n *\n * @see https://kickjs.app/guide/query-parsing\n */\nexport interface ApiQueryParamsConfig {\n /** Fields that can be used in filter queries (e.g., `?filter=status:eq:active`) */\n filterable?: string[]\n /** Fields that can be used in sort queries (e.g., `?sort=createdAt:desc`) */\n sortable?: string[]\n /** Fields that are searched with the `?q=` parameter */\n searchable?: string[]\n}\n\n/**\n * Column-object-based query params config (e.g., from DrizzleQueryParamsConfig).\n * `Object.keys()` is used to derive field names for OpenAPI docs.\n */\nexport interface ColumnApiQueryParamsConfig {\n columns: Record<string, any>\n sortable?: Record<string, any>\n searchColumns?: any[]\n [key: string]: any\n}\n\n/**\n * Normalize a query params config to the string-based ApiQueryParamsConfig.\n * Handles both string-based and column-object-based configs.\n */\nexport function normalizeApiQueryParamsConfig(\n config: ApiQueryParamsConfig | ColumnApiQueryParamsConfig,\n): ApiQueryParamsConfig {\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: config.searchColumns\n ? config.searchColumns.map((col: any) => col?.name ?? '').filter(Boolean)\n : undefined,\n }\n }\n return config as ApiQueryParamsConfig\n}\n\n/**\n * Document the query parameters accepted by a GET endpoint.\n * Used by SwaggerAdapter to generate `filter`, `sort`, `page`, `limit`, and `q` params\n * in the OpenAPI spec, with descriptions listing the allowed fields.\n *\n * Accepts both string-based configs and column-object configs (e.g., DrizzleQueryParamsConfig).\n *\n * @example\n * ```ts\n * // String-based\n * @ApiQueryParams({\n * filterable: ['status', 'category', 'price'],\n * sortable: ['name', 'createdAt', 'price'],\n * searchable: ['name', 'description'],\n * })\n *\n * // Column-object-based (Drizzle)\n * @ApiQueryParams(TASK_QUERY_CONFIG)\n * ```\n *\n * @see https://kickjs.app/guide/middleware\n */\nexport function ApiQueryParams(\n config: ApiQueryParamsConfig | ColumnApiQueryParamsConfig,\n): MethodDecorator {\n return (target, propertyKey) => {\n const normalized = normalizeApiQueryParamsConfig(config)\n setMethodMeta(METADATA.QUERY_PARAMS, normalized, target.constructor, propertyKey as string)\n }\n}\n\n// ── Middleware Decorators ───────────────────────────────────────────────\n\n/**\n * Middleware handler function.\n * Generic `TCtx` defaults to `any` — import `RequestContext` from\n * `@forinda/kickjs` for full type safety:\n *\n * ```ts\n * import type { MiddlewareHandler } from '@forinda/kickjs'\n * import type { RequestContext } from '@forinda/kickjs'\n *\n * const auth: MiddlewareHandler<RequestContext> = (ctx, next) => {\n * ctx.body // fully typed\n * next()\n * }\n * ```\n *\n * A guard stops the request by writing a response and not calling `next()`.\n * Whatever it returns is ignored, so `if (!user) return ctx.problem.unauthorized()`\n * — the idiom handlers use — type-checks here too.\n */\nexport type MiddlewareHandler<TCtx = any> = (ctx: TCtx, next: () => void) => unknown\n\n/**\n * Attach middleware handlers to a class or method\n *\n * @see https://kickjs.app/guide/middleware\n */\nexport function Middleware(...handlers: MiddlewareHandler[]): ClassDecorator & MethodDecorator {\n return (target: any, propertyKey?: string | symbol) => {\n if (propertyKey) {\n pushMethodMeta(\n METADATA.METHOD_MIDDLEWARES,\n target.constructor,\n propertyKey as string,\n ...handlers,\n )\n } else {\n pushClassMeta(METADATA.CLASS_MIDDLEWARES, target, ...handlers)\n }\n }\n}\n\n// ── File Upload Decorator ───────────────────────────────────────────────\n\n/**\n * File filter — accepts short extensions ('jpg'), full MIME types ('image/jpeg'),\n * wildcards ('image/*'), or a function `(mimetype, filename) => boolean` for full control.\n */\nexport type FileTypeFilter = string[] | ((mimetype: string, filename: string) => boolean)\n\n/**\n * Shared upload options used by both the `@FileUpload` decorator and the\n * `upload.single()` / `upload.array()` / `upload.none()` middleware.\n */\nexport interface BaseUploadOptions {\n /** Max file size in bytes (default: 5MB) */\n maxSize?: number\n /**\n * Allowed file types:\n * - **string[]** — short extensions ('jpg'), full MIME types ('image/jpeg'), or wildcards ('image/*')\n * - **function** — `(mimetype, filename) => boolean` for full control\n */\n allowedTypes?: FileTypeFilter\n /** Extend the built-in extension-to-MIME map */\n customMimeMap?: Record<string, string>\n /**\n * The file's server-side name, `file.filename`, from what the client sent.\n * Default: a random UUID plus the client name's extension when it names the\n * file's type (`3f2b….png`) — never the client's name itself. The result must not\n * contain a slash or backslash, nor be `.` or `..`. Disk storage (`dest`) keeps the name\n * it wrote the file under.\n */\n rename?: (file: {\n originalname: string\n mimetype: string\n fieldname: string\n size: number\n }) => string\n}\n\n/**\n * Options for {@link FileUpload}: single file, many files, or fields only.\n *\n * @see https://kickjs.app/guide/file-uploads\n */\nexport interface FileUploadConfig extends BaseUploadOptions {\n mode: 'single' | 'array' | 'none'\n /**\n * Form field name (default: 'file')\n */\n fieldName?: string\n /** Max files for array mode (default: 10) */\n maxCount?: number\n}\n\n/**\n * Configure file upload handling for a controller method\n *\n * @see https://kickjs.app/guide/file-uploads\n */\nexport function FileUpload(config: FileUploadConfig): MethodDecorator {\n return (target, propertyKey) => {\n setMethodMeta(METADATA.FILE_UPLOAD, config, target.constructor, propertyKey as string)\n }\n}\n"],"mappings":";;;;;;;;;;A,0YAwCA,SAAgB,YAA6B,CAC3C,MAAQ,SAAgB,CACtB,aAAa,SAAS,WAAY,aAAc,MAAM,EACtD,mBAAmB,OAAQ,MAAM,SAAS,CAC5C,CACF,CAuEA,SAAgB,MAAwB,SAA6C,CACnF,OAAQ,OAAQ,cAAgB,CAC9B,aAAa,SAAS,MAAO,OAAQ,YAAuB,CAAE,QAAS,CAAC,CAC1E,CACF,CA4BA,SAAS,qBAAqB,OAAgB,CAC5C,OAAQ,KAAe,cACb,OAAQ,cAAgB,CAC9B,cAA+B,SAAS,OAAQ,OAAO,YAAa,CAClE,OACA,KAAM,MAAQ,IACd,YAAa,YACb,UACF,CAAC,CACH,CAEJ,CAiBA,MAAa,IAAM,qBAAqB,KAAK,EAiBhC,KAAO,qBAAqB,MAAM,EAgBlC,IAAM,qBAAqB,KAAK,EAehC,OAAS,qBAAqB,QAAQ,EAgBtC,MAAQ,qBAAqB,OAAO,EAiCjD,SAAgB,8BACd,OACsB,CAUtB,MATI,YAAa,QAAU,OAAO,SAAW,OAAO,OAAO,SAAY,SAC9D,CACL,WAAY,OAAO,KAAK,OAAO,OAAO,EACtC,SAAU,OAAO,SAAW,OAAO,KAAK,OAAO,QAAQ,EAAI,IAAA,GAC3D,WAAY,OAAO,cACf,OAAO,cAAc,IAAK,KAAa,KAAK,MAAQ,EAAE,CAAC,CAAC,OAAO,OAAO,EACtE,IAAA,EACN,EAEK,MACT,CAwBA,SAAgB,eACd,OACiB,CACjB,OAAQ,OAAQ,cAAgB,CAC9B,IAAM,WAAa,8BAA8B,MAAM,EACvD,cAAc,SAAS,aAAc,WAAY,OAAO,YAAa,WAAqB,CAC5F,CACF,CA8BA,SAAgB,WAAW,GAAG,SAAiE,CAC7F,OAAQ,OAAa,cAAkC,CACjD,YACF,eACE,SAAS,mBACT,OAAO,YACP,YACA,GAAG,QACL,EAEA,cAAc,SAAS,kBAAmB,OAAQ,GAAG,QAAQ,CAEjE,CACF,CA4DA,SAAgB,WAAW,OAA2C,CACpE,OAAQ,OAAQ,cAAgB,CAC9B,cAAc,SAAS,YAAa,OAAQ,OAAO,YAAa,WAAqB,CACvF,CACF,C"}
|
package/dist/core/errors.d.mts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
|
|
2
|
-
import { a as ProblemException, c as defaultProblemTitle, i as ProblemDetails, l as normalizeProblem, n as HttpStatus, o as Problems, r as HttpStatusCode, s as ValidationError, t as HttpException } from "../errors-
|
|
2
|
+
import { a as ProblemException, c as defaultProblemTitle, i as ProblemDetails, l as normalizeProblem, n as HttpStatus, o as Problems, r as HttpStatusCode, s as ValidationError, t as HttpException } from "../errors-CppqPy0A.mjs";
|
|
3
3
|
export { HttpException, HttpStatus, HttpStatusCode, ProblemDetails, ProblemException, Problems, ValidationError, defaultProblemTitle, normalizeProblem };
|
package/dist/core/errors.mjs
CHANGED
package/dist/core/errors.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.mjs","names":[],"sources":["../../src/core/errors.ts"],"sourcesContent":["/**\n * Standard HTTP status codes as a const enum.\n * Use instead of raw numbers for readability and type safety.\n *\n * @example\n * ```ts\n * throw new HttpException(HttpStatus.NOT_FOUND, 'User not found')\n * ctx.res.status(HttpStatus.CREATED).json(data)\n * ```\n */\nexport const HttpStatus = {\n // 2xx Success\n OK: 200,\n CREATED: 201,\n ACCEPTED: 202,\n NO_CONTENT: 204,\n\n // 3xx Redirection\n MOVED_PERMANENTLY: 301,\n FOUND: 302,\n NOT_MODIFIED: 304,\n TEMPORARY_REDIRECT: 307,\n PERMANENT_REDIRECT: 308,\n\n // 4xx Client Errors\n BAD_REQUEST: 400,\n UNAUTHORIZED: 401,\n PAYMENT_REQUIRED: 402,\n FORBIDDEN: 403,\n NOT_FOUND: 404,\n METHOD_NOT_ALLOWED: 405,\n NOT_ACCEPTABLE: 406,\n CONFLICT: 409,\n GONE: 410,\n PAYLOAD_TOO_LARGE: 413,\n UNSUPPORTED_MEDIA_TYPE: 415,\n UNPROCESSABLE_ENTITY: 422,\n TOO_MANY_REQUESTS: 429,\n\n // 5xx Server Errors\n INTERNAL_SERVER_ERROR: 500,\n NOT_IMPLEMENTED: 501,\n BAD_GATEWAY: 502,\n SERVICE_UNAVAILABLE: 503,\n GATEWAY_TIMEOUT: 504,\n} as const\n\nexport type HttpStatusCode = (typeof HttpStatus)[keyof typeof HttpStatus]\n\n/**\n * IANA HTTP status reason phrases for the codes the framework's typed\n * helpers cover. Used as the default `title` when a {@link ProblemException}\n * is constructed without one. Keep in sync with {@link HttpStatus}.\n */\nconst STATUS_REASONS: Record<number, string> = {\n 400: 'Bad Request',\n 401: 'Unauthorized',\n 402: 'Payment Required',\n 403: 'Forbidden',\n 404: 'Not Found',\n 405: 'Method Not Allowed',\n 406: 'Not Acceptable',\n 409: 'Conflict',\n 410: 'Gone',\n 412: 'Precondition Failed',\n 413: 'Payload Too Large',\n 415: 'Unsupported Media Type',\n 422: 'Unprocessable Entity',\n 429: 'Too Many Requests',\n 500: 'Internal Server Error',\n 501: 'Not Implemented',\n 502: 'Bad Gateway',\n 503: 'Service Unavailable',\n 504: 'Gateway Timeout',\n}\n\n/** Validation error detail — shape used by `unprocessable()` and `fromZodError()`. */\nexport interface ValidationError {\n field: string\n message: string\n code?: string\n}\n\n/**\n * RFC 9457 — Problem Details for HTTP APIs.\n * https://datatracker.ietf.org/doc/html/rfc9457\n *\n * Canonical error shape for HTTP responses. Only `status` is required;\n * everything else has a sensible default. Extension members (any other\n * JSON-compatible field) are allowed per §3.2 — pass them on the same\n * object and the framework forwards them through.\n *\n * @example\n * ```ts\n * const problem: ProblemDetails = {\n * type: 'https://api.example.com/problems/out-of-credit',\n * status: 403,\n * title: 'You do not have enough credit',\n * detail: 'Your balance is 30, but that costs 50.',\n * instance: '/account/12345/messages/abc',\n * // extension members per §3.2\n * balance: 30,\n * }\n * ```\n */\nexport interface ProblemDetails {\n /**\n * URI reference identifying the problem type. Per §4.2.1, when\n * dereferenced it SHOULD return human-readable documentation. Defaults\n * to `about:blank` when omitted (RFC 9457 §3.1.1).\n */\n type?: string\n /**\n * Short human-readable summary, advisable to be the same regardless of\n * the occurrence (§3.1.4). Defaults to the IANA reason phrase for\n * `status` when omitted.\n */\n title?: string\n /** HTTP status code generated by the origin server. Required. */\n status: number\n /**\n * Human-readable explanation specific to this occurrence (§3.1.5).\n * Per the RFC's safety guidance, do not include sensitive information\n * (tokens, full SQL, stack traces) — those belong in logs.\n */\n detail?: string\n /**\n * URI reference identifying the specific occurrence (§3.1.6).\n * Typically the request path. Adopters set this explicitly — the\n * framework does not auto-populate it to avoid leaking unexpected\n * structure.\n */\n instance?: string\n /**\n * Extension members per §3.2 — any other JSON-compatible field.\n * Common examples: `balance`, `errors`, `traceId`, `accounts`.\n */\n [key: string]: unknown\n}\n\n/**\n * Typed HTTP exception with status code, free-form details, and optional\n * response headers. Provides static factory methods for common HTTP errors.\n *\n * `details` is intentionally typed as `unknown` — it serializes straight into\n * the response body's `errors` field, so any JSON-compatible shape works\n * (string, object, array of mixed values, ValidationError[]).\n *\n * `headers` are merged into the response by the global error handler so\n * spec-mandated headers (Retry-After, WWW-Authenticate, Allow, Location)\n * stay on the exception, not on ad-hoc try/catch chains.\n *\n * For RFC 9457 — Problem Details responses, throw {@link ProblemException}\n * instead — the global error handler emits `application/problem+json` for\n * those automatically.\n */\nexport class HttpException extends Error {\n constructor(\n public readonly status: number,\n message: string,\n public readonly details?: unknown,\n public readonly headers?: Record<string, string>,\n ) {\n super(message)\n this.name = 'HttpException'\n }\n\n /** Return a new exception with `headers` shallow-merged onto this one. */\n withHeaders(headers: Record<string, string>): HttpException {\n return new HttpException(this.status, this.message, this.details, {\n ...this.headers,\n ...headers,\n })\n }\n\n /** Create from a Zod error */\n static fromZodError(error: any, message?: string): HttpException {\n const firstIssue = error.issues?.[0]\n const details: ValidationError[] = (error.issues || []).map((issue: any) => ({\n field: issue.path?.join('.') || '',\n message: issue.message,\n code: issue.code,\n }))\n return new HttpException(\n HttpStatus.UNPROCESSABLE_ENTITY,\n message || firstIssue?.message || 'Validation failed',\n details,\n )\n }\n\n static badRequest(message = 'Bad Request') {\n return new HttpException(HttpStatus.BAD_REQUEST, message)\n }\n static unauthorized(message = 'Unauthorized', wwwAuthenticate?: string) {\n return new HttpException(\n HttpStatus.UNAUTHORIZED,\n message,\n undefined,\n wwwAuthenticate ? { 'WWW-Authenticate': wwwAuthenticate } : undefined,\n )\n }\n static forbidden(message = 'Forbidden') {\n return new HttpException(HttpStatus.FORBIDDEN, message)\n }\n static notFound(message = 'Not Found') {\n return new HttpException(HttpStatus.NOT_FOUND, message)\n }\n static methodNotAllowed(allowedMethods: string[], message = 'Method Not Allowed') {\n return new HttpException(HttpStatus.METHOD_NOT_ALLOWED, message, undefined, {\n Allow: allowedMethods.join(', '),\n })\n }\n static conflict(message = 'Conflict') {\n return new HttpException(HttpStatus.CONFLICT, message)\n }\n static unprocessable(message = 'Unprocessable Entity', details?: ValidationError[]) {\n return new HttpException(HttpStatus.UNPROCESSABLE_ENTITY, message, details)\n }\n static tooManyRequests(message = 'Too Many Requests', retryAfterSeconds?: number) {\n return new HttpException(\n HttpStatus.TOO_MANY_REQUESTS,\n message,\n undefined,\n retryAfterSeconds !== undefined ? { 'Retry-After': String(retryAfterSeconds) } : undefined,\n )\n }\n static serviceUnavailable(message = 'Service Unavailable', retryAfterSeconds?: number) {\n return new HttpException(\n HttpStatus.SERVICE_UNAVAILABLE,\n message,\n undefined,\n retryAfterSeconds !== undefined ? { 'Retry-After': String(retryAfterSeconds) } : undefined,\n )\n }\n static internal(message = 'Internal Server Error') {\n return new HttpException(HttpStatus.INTERNAL_SERVER_ERROR, message)\n }\n}\n\n/**\n * Default `title` for an RFC 9457 problem with the given status — the IANA\n * reason phrase, or `'Error'` for codes outside the framework's table.\n * Exposed so {@link ProblemException} construction and {@link RequestContext}'s\n * `problem` helpers share a single source of truth.\n */\nexport function defaultProblemTitle(status: number): string {\n return STATUS_REASONS[status] ?? 'Error'\n}\n\n/**\n * Exception that carries an RFC 9457 — Problem Details payload. When\n * thrown, the framework error handler emits `application/problem+json`\n * with the canonical shape; `type` defaults to `about:blank`, `title`\n * to the IANA reason phrase for `status`.\n *\n * Extends {@link HttpException} so existing `instanceof HttpException`\n * catches still see it. Use `new ProblemException(...)` directly for\n * full control, or {@link Problems} for the pre-filled-status\n * convenience factories.\n *\n * Static factories deliberately live on {@link Problems} rather than\n * this class — putting them here would shadow `HttpException`'s\n * same-named statics with incompatible (object vs string) signatures,\n * which TypeScript correctly rejects.\n *\n * @example\n * ```ts\n * throw new ProblemException({\n * type: 'https://api.example.com/problems/out-of-credit',\n * status: 403,\n * title: 'You do not have enough credit',\n * detail: 'Your balance is 30, but that costs 50.',\n * instance: '/account/12345/messages/abc',\n * balance: 30, // extension\n * })\n *\n * // Or via the Problems convenience factory:\n * throw Problems.forbidden({\n * type: 'https://api.example.com/problems/out-of-credit',\n * detail: 'Your balance is 30, but that costs 50.',\n * balance: 30,\n * })\n * ```\n */\nexport class ProblemException extends HttpException {\n public readonly problem: ProblemDetails\n\n constructor(problem: ProblemDetails, headers?: Record<string, string>) {\n const title = problem.title ?? defaultProblemTitle(problem.status)\n const detail = problem.detail ?? title\n super(problem.status, detail, undefined, headers)\n this.name = 'ProblemException'\n this.problem = { ...problem, title }\n }\n\n /** Return a new exception with `headers` shallow-merged onto this one. */\n withHeaders(headers: Record<string, string>): ProblemException {\n return new ProblemException(this.problem, { ...this.headers, ...headers })\n }\n}\n\n/**\n * Convenience factories for {@link ProblemException}. Pre-fill `status`\n * (and `title` via {@link defaultProblemTitle}) for the common HTTP\n * codes — same shortcut set the `ctx.problem.*` response helpers cover.\n *\n * Lives in a separate namespace rather than as statics on\n * {@link ProblemException} to avoid shadowing {@link HttpException}'s\n * same-named statics, which would create a TypeScript variance\n * conflict (parent's `notFound(message?: string)` vs the child's\n * desired `notFound(input?: ProblemInput)`).\n *\n * @example\n * ```ts\n * throw Problems.notFound({ detail: 'User abc not found' })\n * throw Problems.tooManyRequests({}, 60) // sets Retry-After: 60\n * throw Problems.fromZodError(zodResult.error)\n * ```\n */\nexport const Problems = {\n /** 400 Bad Request with optional detail / instance / extensions. */\n badRequest(input: Omit<ProblemDetails, 'status'> = {}): ProblemException {\n return new ProblemException({ status: 400, ...input })\n },\n /** 401 Unauthorized. Pass a `WWW-Authenticate` challenge via the headers arg. */\n unauthorized(\n input: Omit<ProblemDetails, 'status'> = {},\n wwwAuthenticate?: string,\n ): ProblemException {\n return new ProblemException(\n { status: 401, ...input },\n wwwAuthenticate ? { 'WWW-Authenticate': wwwAuthenticate } : undefined,\n )\n },\n /** 403 Forbidden. */\n forbidden(input: Omit<ProblemDetails, 'status'> = {}): ProblemException {\n return new ProblemException({ status: 403, ...input })\n },\n /** 404 Not Found. */\n notFound(input: Omit<ProblemDetails, 'status'> = {}): ProblemException {\n return new ProblemException({ status: 404, ...input })\n },\n /** 405 Method Not Allowed. Pass the allowed methods so the Allow header is set. */\n methodNotAllowed(\n allowedMethods: string[],\n input: Omit<ProblemDetails, 'status'> = {},\n ): ProblemException {\n return new ProblemException({ status: 405, ...input }, { Allow: allowedMethods.join(', ') })\n },\n /** 409 Conflict. */\n conflict(input: Omit<ProblemDetails, 'status'> = {}): ProblemException {\n return new ProblemException({ status: 409, ...input })\n },\n /**\n * 422 Unprocessable Entity. Pass per-field issues via the `errors`\n * extension — keep the array shape per the RFC's recommended convention\n * (`{ field, message, code }`).\n */\n unprocessable(input: Omit<ProblemDetails, 'status'> = {}): ProblemException {\n return new ProblemException({ status: 422, ...input })\n },\n /** 429 Too Many Requests. Pass `retryAfterSeconds` to set the Retry-After header. */\n tooManyRequests(\n input: Omit<ProblemDetails, 'status'> = {},\n retryAfterSeconds?: number,\n ): ProblemException {\n return new ProblemException(\n { status: 429, ...input },\n retryAfterSeconds !== undefined ? { 'Retry-After': String(retryAfterSeconds) } : undefined,\n )\n },\n /** 503 Service Unavailable. */\n serviceUnavailable(\n input: Omit<ProblemDetails, 'status'> = {},\n retryAfterSeconds?: number,\n ): ProblemException {\n return new ProblemException(\n { status: 503, ...input },\n retryAfterSeconds !== undefined ? { 'Retry-After': String(retryAfterSeconds) } : undefined,\n )\n },\n /** 500 Internal Server Error. */\n internal(input: Omit<ProblemDetails, 'status'> = {}): ProblemException {\n return new ProblemException({ status: 500, ...input })\n },\n\n /**\n * Build from a Zod error — 422 with the issues serialized into the\n * `errors` extension per RFC 9457 §3.2's array convention.\n */\n fromZodError(error: any, input: Omit<ProblemDetails, 'status'> = {}): ProblemException {\n const issues: ValidationError[] = (error.issues || []).map((issue: any) => ({\n field: issue.path?.join('.') || '',\n message: issue.message,\n code: issue.code,\n }))\n return new ProblemException({\n status: 422,\n detail: error.issues?.[0]?.message,\n ...input,\n errors: issues,\n })\n },\n} as const\n\n/**\n * Normalize an RFC 9457 problem into the wire shape — fill in `type` →\n * `'about:blank'` and `title` → IANA reason phrase. The same function is\n * used by {@link RequestContext}'s `problem` helpers and the global\n * error handler so the response is identical regardless of entry point.\n *\n * Defaults are applied **after** the spread, so a caller passing\n * `{ type: undefined }` (e.g. a partial built up from optional fields)\n * still gets `'about:blank'` on the wire — `...input` would otherwise\n * re-overwrite the fallback with the explicit `undefined`.\n */\nexport function normalizeProblem(input: ProblemDetails): ProblemDetails {\n return {\n ...input,\n type: input.type ?? 'about:blank',\n title: input.title ?? defaultProblemTitle(input.status),\n }\n}\n"],"mappings":";;;;;;;;;;AAUA,MAAa,WAAa,CAExB,GAAI,IACJ,QAAS,IACT,SAAU,IACV,WAAY,IAGZ,kBAAmB,IACnB,MAAO,IACP,aAAc,IACd,mBAAoB,IACpB,mBAAoB,IAGpB,YAAa,IACb,aAAc,IACd,iBAAkB,IAClB,UAAW,IACX,UAAW,IACX,mBAAoB,IACpB,eAAgB,IAChB,SAAU,IACV,KAAM,IACN,kBAAmB,IACnB,uBAAwB,IACxB,qBAAsB,IACtB,kBAAmB,IAGnB,sBAAuB,IACvB,gBAAiB,IACjB,YAAa,IACb,oBAAqB,IACrB,gBAAiB,GACnB,EASM,eAAyC,CAC7C,IAAK,cACL,IAAK,eACL,IAAK,mBACL,IAAK,YACL,IAAK,YACL,IAAK,qBACL,IAAK,iBACL,IAAK,WACL,IAAK,OACL,IAAK,sBACL,IAAK,oBACL,IAAK,yBACL,IAAK,uBACL,IAAK,oBACL,IAAK,wBACL,IAAK,kBACL,IAAK,cACL,IAAK,sBACL,IAAK,iBACP,EAkFA,IAAa,cAAb,MAAa,sBAAsB,KAAM,CAErB,OAEA,QACA,QAJlB,YACE,OACA,QACA,QACA,QACA,CACA,MAAM,OAAO,EALG,KAAA,OAAA,OAEA,KAAA,QAAA,QACA,KAAA,QAAA,QAGhB,KAAK,KAAO,eACd,CAGA,YAAY,Q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,CACF,C"}
|
|
1
|
+
{"version":3,"file":"errors.mjs","names":[],"sources":["../../src/core/errors.ts"],"sourcesContent":["/**\n * Standard HTTP status codes as a const enum.\n * Use instead of raw numbers for readability and type safety.\n *\n * @example\n * ```ts\n * throw new HttpException(HttpStatus.NOT_FOUND, 'User not found')\n * ctx.res.status(HttpStatus.CREATED).json(data)\n * ```\n */\nexport const HttpStatus = {\n // 2xx Success\n OK: 200,\n CREATED: 201,\n ACCEPTED: 202,\n NO_CONTENT: 204,\n\n // 3xx Redirection\n MOVED_PERMANENTLY: 301,\n FOUND: 302,\n NOT_MODIFIED: 304,\n TEMPORARY_REDIRECT: 307,\n PERMANENT_REDIRECT: 308,\n\n // 4xx Client Errors\n BAD_REQUEST: 400,\n UNAUTHORIZED: 401,\n PAYMENT_REQUIRED: 402,\n FORBIDDEN: 403,\n NOT_FOUND: 404,\n METHOD_NOT_ALLOWED: 405,\n NOT_ACCEPTABLE: 406,\n CONFLICT: 409,\n GONE: 410,\n PAYLOAD_TOO_LARGE: 413,\n UNSUPPORTED_MEDIA_TYPE: 415,\n UNPROCESSABLE_ENTITY: 422,\n TOO_MANY_REQUESTS: 429,\n\n // 5xx Server Errors\n INTERNAL_SERVER_ERROR: 500,\n NOT_IMPLEMENTED: 501,\n BAD_GATEWAY: 502,\n SERVICE_UNAVAILABLE: 503,\n GATEWAY_TIMEOUT: 504,\n} as const\n\n/** Any status code in {@link HttpStatus}. */\nexport type HttpStatusCode = (typeof HttpStatus)[keyof typeof HttpStatus]\n\n/**\n * IANA HTTP status reason phrases for the codes the framework's typed\n * helpers cover. Used as the default `title` when a {@link ProblemException}\n * is constructed without one. Keep in sync with {@link HttpStatus}.\n */\nconst STATUS_REASONS: Record<number, string> = {\n 400: 'Bad Request',\n 401: 'Unauthorized',\n 402: 'Payment Required',\n 403: 'Forbidden',\n 404: 'Not Found',\n 405: 'Method Not Allowed',\n 406: 'Not Acceptable',\n 409: 'Conflict',\n 410: 'Gone',\n 412: 'Precondition Failed',\n 413: 'Payload Too Large',\n 415: 'Unsupported Media Type',\n 422: 'Unprocessable Entity',\n 429: 'Too Many Requests',\n 500: 'Internal Server Error',\n 501: 'Not Implemented',\n 502: 'Bad Gateway',\n 503: 'Service Unavailable',\n 504: 'Gateway Timeout',\n}\n\n/** Validation error detail — shape used by `unprocessable()` and `fromZodError()`. */\nexport interface ValidationError {\n field: string\n message: string\n code?: string\n}\n\n/**\n * RFC 9457 — Problem Details for HTTP APIs.\n * https://datatracker.ietf.org/doc/html/rfc9457\n *\n * Canonical error shape for HTTP responses. Only `status` is required;\n * everything else has a sensible default. Extension members (any other\n * JSON-compatible field) are allowed per §3.2 — pass them on the same\n * object and the framework forwards them through.\n *\n * @example\n * ```ts\n * const problem: ProblemDetails = {\n * type: 'https://api.example.com/problems/out-of-credit',\n * status: 403,\n * title: 'You do not have enough credit',\n * detail: 'Your balance is 30, but that costs 50.',\n * instance: '/account/12345/messages/abc',\n * // extension members per §3.2\n * balance: 30,\n * }\n * ```\n */\nexport interface ProblemDetails {\n /**\n * URI reference identifying the problem type. Per §4.2.1, when\n * dereferenced it SHOULD return human-readable documentation. Defaults\n * to `about:blank` when omitted (RFC 9457 §3.1.1).\n */\n type?: string\n /**\n * Short human-readable summary, advisable to be the same regardless of\n * the occurrence (§3.1.4). Defaults to the IANA reason phrase for\n * `status` when omitted.\n */\n title?: string\n /** HTTP status code generated by the origin server. Required. */\n status: number\n /**\n * Human-readable explanation specific to this occurrence (§3.1.5).\n * Per the RFC's safety guidance, do not include sensitive information\n * (tokens, full SQL, stack traces) — those belong in logs.\n */\n detail?: string\n /**\n * URI reference identifying the specific occurrence (§3.1.6).\n * Typically the request path. Adopters set this explicitly — the\n * framework does not auto-populate it to avoid leaking unexpected\n * structure.\n */\n instance?: string\n /**\n * Extension members per §3.2 — any other JSON-compatible field.\n * Common examples: `balance`, `errors`, `traceId`, `accounts`.\n */\n [key: string]: unknown\n}\n\n/**\n * Typed HTTP exception with status code, free-form details, and optional\n * response headers. Provides static factory methods for common HTTP errors.\n *\n * `details` is intentionally typed as `unknown` — it serializes straight into\n * the response body's `errors` field, so any JSON-compatible shape works\n * (string, object, array of mixed values, ValidationError[]).\n *\n * `headers` are merged into the response by the global error handler so\n * spec-mandated headers (Retry-After, WWW-Authenticate, Allow, Location)\n * stay on the exception, not on ad-hoc try/catch chains.\n *\n * For RFC 9457 — Problem Details responses, throw {@link ProblemException}\n * instead — the global error handler emits `application/problem+json` for\n * those automatically.\n */\nexport class HttpException extends Error {\n constructor(\n public readonly status: number,\n message: string,\n public readonly details?: unknown,\n public readonly headers?: Record<string, string>,\n ) {\n super(message)\n this.name = 'HttpException'\n }\n\n /** Return a new exception with `headers` shallow-merged onto this one. */\n withHeaders(headers: Record<string, string>): HttpException {\n return new HttpException(this.status, this.message, this.details, {\n ...this.headers,\n ...headers,\n })\n }\n\n /** Create from a Zod error */\n static fromZodError(error: any, message?: string): HttpException {\n const firstIssue = error.issues?.[0]\n const details: ValidationError[] = (error.issues || []).map((issue: any) => ({\n field: issue.path?.join('.') || '',\n message: issue.message,\n code: issue.code,\n }))\n return new HttpException(\n HttpStatus.UNPROCESSABLE_ENTITY,\n message || firstIssue?.message || 'Validation failed',\n details,\n )\n }\n\n static badRequest(message = 'Bad Request') {\n return new HttpException(HttpStatus.BAD_REQUEST, message)\n }\n static unauthorized(message = 'Unauthorized', wwwAuthenticate?: string) {\n return new HttpException(\n HttpStatus.UNAUTHORIZED,\n message,\n undefined,\n wwwAuthenticate ? { 'WWW-Authenticate': wwwAuthenticate } : undefined,\n )\n }\n static forbidden(message = 'Forbidden') {\n return new HttpException(HttpStatus.FORBIDDEN, message)\n }\n static notFound(message = 'Not Found') {\n return new HttpException(HttpStatus.NOT_FOUND, message)\n }\n static methodNotAllowed(allowedMethods: string[], message = 'Method Not Allowed') {\n return new HttpException(HttpStatus.METHOD_NOT_ALLOWED, message, undefined, {\n Allow: allowedMethods.join(', '),\n })\n }\n static conflict(message = 'Conflict') {\n return new HttpException(HttpStatus.CONFLICT, message)\n }\n static unprocessable(message = 'Unprocessable Entity', details?: ValidationError[]) {\n return new HttpException(HttpStatus.UNPROCESSABLE_ENTITY, message, details)\n }\n static tooManyRequests(message = 'Too Many Requests', retryAfterSeconds?: number) {\n return new HttpException(\n HttpStatus.TOO_MANY_REQUESTS,\n message,\n undefined,\n retryAfterSeconds !== undefined ? { 'Retry-After': String(retryAfterSeconds) } : undefined,\n )\n }\n static serviceUnavailable(message = 'Service Unavailable', retryAfterSeconds?: number) {\n return new HttpException(\n HttpStatus.SERVICE_UNAVAILABLE,\n message,\n undefined,\n retryAfterSeconds !== undefined ? { 'Retry-After': String(retryAfterSeconds) } : undefined,\n )\n }\n static internal(message = 'Internal Server Error') {\n return new HttpException(HttpStatus.INTERNAL_SERVER_ERROR, message)\n }\n}\n\n/**\n * Default `title` for an RFC 9457 problem with the given status — the IANA\n * reason phrase, or `'Error'` for codes outside the framework's table.\n * Exposed so {@link ProblemException} construction and {@link RequestContext}'s\n * `problem` helpers share a single source of truth.\n */\nexport function defaultProblemTitle(status: number): string {\n return STATUS_REASONS[status] ?? 'Error'\n}\n\n/**\n * Exception that carries an RFC 9457 — Problem Details payload. When\n * thrown, the framework error handler emits `application/problem+json`\n * with the canonical shape; `type` defaults to `about:blank`, `title`\n * to the IANA reason phrase for `status`.\n *\n * Extends {@link HttpException} so existing `instanceof HttpException`\n * catches still see it. Use `new ProblemException(...)` directly for\n * full control, or {@link Problems} for the pre-filled-status\n * convenience factories.\n *\n * Static factories deliberately live on {@link Problems} rather than\n * this class — putting them here would shadow `HttpException`'s\n * same-named statics with incompatible (object vs string) signatures,\n * which TypeScript correctly rejects.\n *\n * @example\n * ```ts\n * throw new ProblemException({\n * type: 'https://api.example.com/problems/out-of-credit',\n * status: 403,\n * title: 'You do not have enough credit',\n * detail: 'Your balance is 30, but that costs 50.',\n * instance: '/account/12345/messages/abc',\n * balance: 30, // extension\n * })\n *\n * // Or via the Problems convenience factory:\n * throw Problems.forbidden({\n * type: 'https://api.example.com/problems/out-of-credit',\n * detail: 'Your balance is 30, but that costs 50.',\n * balance: 30,\n * })\n * ```\n */\nexport class ProblemException extends HttpException {\n public readonly problem: ProblemDetails\n\n constructor(problem: ProblemDetails, headers?: Record<string, string>) {\n const title = problem.title ?? defaultProblemTitle(problem.status)\n const detail = problem.detail ?? title\n super(problem.status, detail, undefined, headers)\n this.name = 'ProblemException'\n this.problem = { ...problem, title }\n }\n\n /** Return a new exception with `headers` shallow-merged onto this one. */\n withHeaders(headers: Record<string, string>): ProblemException {\n return new ProblemException(this.problem, { ...this.headers, ...headers })\n }\n}\n\n/**\n * Convenience factories for {@link ProblemException}. Pre-fill `status`\n * (and `title` via {@link defaultProblemTitle}) for the common HTTP\n * codes — same shortcut set the `ctx.problem.*` response helpers cover.\n *\n * Lives in a separate namespace rather than as statics on\n * {@link ProblemException} to avoid shadowing {@link HttpException}'s\n * same-named statics, which would create a TypeScript variance\n * conflict (parent's `notFound(message?: string)` vs the child's\n * desired `notFound(input?: ProblemInput)`).\n *\n * @example\n * ```ts\n * throw Problems.notFound({ detail: 'User abc not found' })\n * throw Problems.tooManyRequests({}, 60) // sets Retry-After: 60\n * throw Problems.fromZodError(zodResult.error)\n * ```\n */\nexport const Problems = {\n /** 400 Bad Request with optional detail / instance / extensions. */\n badRequest(input: Omit<ProblemDetails, 'status'> = {}): ProblemException {\n return new ProblemException({ status: 400, ...input })\n },\n /** 401 Unauthorized. Pass a `WWW-Authenticate` challenge via the headers arg. */\n unauthorized(\n input: Omit<ProblemDetails, 'status'> = {},\n wwwAuthenticate?: string,\n ): ProblemException {\n return new ProblemException(\n { status: 401, ...input },\n wwwAuthenticate ? { 'WWW-Authenticate': wwwAuthenticate } : undefined,\n )\n },\n /** 403 Forbidden. */\n forbidden(input: Omit<ProblemDetails, 'status'> = {}): ProblemException {\n return new ProblemException({ status: 403, ...input })\n },\n /** 404 Not Found. */\n notFound(input: Omit<ProblemDetails, 'status'> = {}): ProblemException {\n return new ProblemException({ status: 404, ...input })\n },\n /** 405 Method Not Allowed. Pass the allowed methods so the Allow header is set. */\n methodNotAllowed(\n allowedMethods: string[],\n input: Omit<ProblemDetails, 'status'> = {},\n ): ProblemException {\n return new ProblemException({ status: 405, ...input }, { Allow: allowedMethods.join(', ') })\n },\n /** 409 Conflict. */\n conflict(input: Omit<ProblemDetails, 'status'> = {}): ProblemException {\n return new ProblemException({ status: 409, ...input })\n },\n /**\n * 422 Unprocessable Entity. Pass per-field issues via the `errors`\n * extension — keep the array shape per the RFC's recommended convention\n * (`{ field, message, code }`).\n */\n unprocessable(input: Omit<ProblemDetails, 'status'> = {}): ProblemException {\n return new ProblemException({ status: 422, ...input })\n },\n /** 429 Too Many Requests. Pass `retryAfterSeconds` to set the Retry-After header. */\n tooManyRequests(\n input: Omit<ProblemDetails, 'status'> = {},\n retryAfterSeconds?: number,\n ): ProblemException {\n return new ProblemException(\n { status: 429, ...input },\n retryAfterSeconds !== undefined ? { 'Retry-After': String(retryAfterSeconds) } : undefined,\n )\n },\n /** 503 Service Unavailable. */\n serviceUnavailable(\n input: Omit<ProblemDetails, 'status'> = {},\n retryAfterSeconds?: number,\n ): ProblemException {\n return new ProblemException(\n { status: 503, ...input },\n retryAfterSeconds !== undefined ? { 'Retry-After': String(retryAfterSeconds) } : undefined,\n )\n },\n /** 500 Internal Server Error. */\n internal(input: Omit<ProblemDetails, 'status'> = {}): ProblemException {\n return new ProblemException({ status: 500, ...input })\n },\n\n /**\n * Build from a Zod error — 422 with the issues serialized into the\n * `errors` extension per RFC 9457 §3.2's array convention.\n */\n fromZodError(error: any, input: Omit<ProblemDetails, 'status'> = {}): ProblemException {\n const issues: ValidationError[] = (error.issues || []).map((issue: any) => ({\n field: issue.path?.join('.') || '',\n message: issue.message,\n code: issue.code,\n }))\n return new ProblemException({\n status: 422,\n detail: error.issues?.[0]?.message,\n ...input,\n errors: issues,\n })\n },\n} as const\n\n/**\n * Normalize an RFC 9457 problem into the wire shape — fill in `type` →\n * `'about:blank'` and `title` → IANA reason phrase. The same function is\n * used by {@link RequestContext}'s `problem` helpers and the global\n * error handler so the response is identical regardless of entry point.\n *\n * Defaults are applied **after** the spread, so a caller passing\n * `{ type: undefined }` (e.g. a partial built up from optional fields)\n * still gets `'about:blank'` on the wire — `...input` would otherwise\n * re-overwrite the fallback with the explicit `undefined`.\n */\nexport function normalizeProblem(input: ProblemDetails): ProblemDetails {\n return {\n ...input,\n type: input.type ?? 'about:blank',\n title: input.title ?? defaultProblemTitle(input.status),\n }\n}\n"],"mappings":";;;;;;;;;;AAUA,MAAa,WAAa,CAExB,GAAI,IACJ,QAAS,IACT,SAAU,IACV,WAAY,IAGZ,kBAAmB,IACnB,MAAO,IACP,aAAc,IACd,mBAAoB,IACpB,mBAAoB,IAGpB,YAAa,IACb,aAAc,IACd,iBAAkB,IAClB,UAAW,IACX,UAAW,IACX,mBAAoB,IACpB,eAAgB,IAChB,SAAU,IACV,KAAM,IACN,kBAAmB,IACnB,uBAAwB,IACxB,qBAAsB,IACtB,kBAAmB,IAGnB,sBAAuB,IACvB,gBAAiB,IACjB,YAAa,IACb,oBAAqB,IACrB,gBAAiB,GACnB,EAUM,eAAyC,CAC7C,IAAK,cACL,IAAK,eACL,IAAK,mBACL,IAAK,YACL,IAAK,YACL,IAAK,qBACL,IAAK,iBACL,IAAK,WACL,IAAK,OACL,IAAK,sBACL,IAAK,oBACL,IAAK,yBACL,IAAK,uBACL,IAAK,oBACL,IAAK,wBACL,IAAK,kBACL,IAAK,cACL,IAAK,sBACL,IAAK,iBACP,EAkFA,IAAa,cAAb,MAAa,sBAAsB,KAAM,CAErB,OAEA,QACA,QAJlB,YACkB,OAChB,QACgB,QACA,QAChB,CACA,MAAM,OAAO,EALG,KAAA,OAAA,OAEA,KAAA,QAAA,QACA,KAAA,QAAA,QAGhB,KAAK,KAAO,eACd,CAGA,YAAY,QAAgD,CAC1D,OAAO,IAAI,cAAc,KAAK,OAAQ,KAAK,QAAS,KAAK,QAAS,CAChE,GAAG,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ostConstructStatus, i as Constructor, l as Scope, n as BuilderOf, o as METADATA, r as ClassKind, s as MaybePromise, t as Buildable, u as ServiceOptions } from "../interfaces-
|
|
2
|
+
import { a as DI_METADATA, c as PostConstructStatus, i as Constructor, l as Scope, n as BuilderOf, o as METADATA, r as ClassKind, s as MaybePromise, t as Buildable, u as ServiceOptions } from "../interfaces-CvO9sAea.mjs";
|
|
3
3
|
export { type Buildable, type BuilderOf, type ClassKind, type Constructor, DI_METADATA, METADATA, MaybePromise, type PostConstructStatus, Scope, type ServiceOptions };
|
package/dist/core/interfaces.mjs
CHANGED
package/dist/core/logger.d.mts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
|
|
2
|
-
import { a as describeError, i as createLogger, n as Logger, o as jsonLine, r as LoggerProvider, s as serializeError, t as ConsoleLoggerProvider } from "../logger-
|
|
2
|
+
import { a as describeError, i as createLogger, n as Logger, o as jsonLine, r as LoggerProvider, s as serializeError, t as ConsoleLoggerProvider } from "../logger-ByJsVwqY.mjs";
|
|
3
3
|
export { ConsoleLoggerProvider, Logger, LoggerProvider, createLogger, describeError, jsonLine, serializeError };
|
package/dist/core/logger.mjs
CHANGED
package/dist/core/logger.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"logger.mjs","names":[],"sources":["../../src/core/logger.ts"],"sourcesContent":["// ── LoggerProvider interface ───────────────────────────────────────────\n\n/**\n * Pluggable logger backend.\n *\n * Implement this interface to plug in any logging library (pino,\n * winston, bunyan, console, etc.). The framework only ever calls the\n * methods declared here — it doesn't know or care which logger is\n * underneath.\n *\n * Default: `ConsoleLoggerProvider` (zero runtime deps).\n *\n * @example\n * ```ts\n * import pino from 'pino'\n * import { Logger, type LoggerProvider } from '@forinda/kickjs'\n *\n * class PinoProvider implements LoggerProvider {\n * constructor(private p = pino()) {}\n * info(msg, ...args) { this.p.info(msg, ...args) }\n * warn(msg, ...args) { this.p.warn(msg, ...args) }\n * error(msg, ...args) { this.p.error(msg, ...args) }\n * debug(msg, ...args) { this.p.debug(msg, ...args) }\n * child({ component }) { return new PinoProvider(this.p.child({ component })) }\n * }\n *\n * Logger.setProvider(new PinoProvider())\n * ```\n *\n * See `docs/guide/logging.md` for Pino, Winston, and silent-logger recipes.\n */\nexport interface LoggerProvider {\n info(msg: string, ...args: any[]): void\n warn(msg: string, ...args: any[]): void\n error(msg: string, ...args: any[]): void\n debug(msg: string, ...args: any[]): void\n trace?(msg: string, ...args: any[]): void\n fatal?(msg: string, ...args: any[]): void\n /**\n * Return a child provider scoped to the given component name. `bindings`\n * may also carry fields from `logger.child({ ... })` (a request id, a job\n * name) — a provider that ignores them keeps working as before.\n */\n child(bindings: { component: string; [field: string]: unknown }): LoggerProvider\n}\n\n// ── Log levels ─────────────────────────────────────────────────────────\n\n/** Severity ordering — a message prints only when its rank ≥ the threshold. */\nconst LEVEL_RANK: Record<string, number> = {\n trace: 10,\n debug: 20,\n info: 30,\n warn: 40,\n error: 50,\n fatal: 60,\n silent: 100,\n}\n\n/**\n * Resolve the active threshold rank from `LOG_LEVEL` (default `info`).\n * Read per-call so a late `process.env.LOG_LEVEL` assignment still\n * takes effect. An unrecognised value falls back to `info`.\n */\nfunction thresholdRank(): number {\n // `process` is guarded because this module is reachable from the\n // edge-safe web pipeline (`@forinda/kickjs/web`), where strict runtimes\n // expose no `process` global at all. The colour probe below already\n // guarded; this one did not, so merely importing the logger could throw\n // on such a runtime.\n const level = (\n (typeof process !== 'undefined' ? process.env?.LOG_LEVEL : undefined) ?? 'info'\n ).toLowerCase()\n return LEVEL_RANK[level] ?? LEVEL_RANK.info\n}\n\n/** `LOG_FORMAT=json` switches the default provider to one JSON object per line. */\nfunction jsonFormat(): boolean {\n return (\n (typeof process !== 'undefined' ? process.env?.LOG_FORMAT : undefined)?.toLowerCase() === 'json'\n )\n}\n\n/** A plain `{ ... }` object — merged into a JSON line as fields. */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== 'object') return false\n const proto = Object.getPrototypeOf(value)\n return proto === Object.prototype || proto === null\n}\n\n/**\n * An error as a JSON field — `type`, `message`, `stack`, own enumerable\n * properties (a driver's `code`), and its `cause` chain, depth-capped and\n * cycle-guarded like {@link describeError}.\n */\nexport function serializeError(err: unknown, depth = 4, seen = new Set<unknown>()): unknown {\n if (!(err instanceof Error)) return err\n if (seen.has(err) || depth <= 0) return '[circular cause]'\n seen.add(err)\n const out: Record<string, unknown> = { type: err.name, message: err.message, stack: err.stack }\n for (const [key, value] of Object.entries(err)) if (!(key in out)) out[key] = value\n const cause = (err as { cause?: unknown }).cause\n if (cause !== undefined) out.cause = serializeError(cause, depth - 1, seen)\n return out\n}\n\n/**\n * Fill printf-style placeholders the way `console.log` does (`%s %d %i %f\n * %j %o %O`, `%%`), then append what's left — so `log.info('hi %s', name)`\n * reads the same in JSON as on a terminal.\n */\nfunction formatMessage(msg: string, args: unknown[]): string {\n let i = 0\n const filled = msg.replace(/%[sdifjoO%]/g, (token) => {\n if (token === '%%') return '%'\n if (i >= args.length) return token\n const value = args[i++]\n if (token === '%d' || token === '%i') return String(Math.trunc(Number(value)))\n if (token === '%f') return String(Number(value))\n if (token === '%s') return typeof value === 'string' ? value : safeStringify(value)\n return safeStringify(value)\n })\n const rest = args.slice(i).map((a) => (typeof a === 'string' ? a : safeStringify(a)))\n return rest.length ? `${filled} ${rest.join(' ')}` : filled\n}\n\n/** Keys of a JSON line only the logger writes — see {@link jsonLine}. */\nconst RESERVED_FIELDS = new Set(['level', 'time', 'component', 'msg', 'err'])\n\n/**\n * One JSON log line, field-compatible with pino (`level` 10–60, `time` in\n * epoch ms, `msg`) so `pino-pretty` and log shippers read it as-is. Trailing\n * plain objects become fields, an `Error` becomes `err`, and anything else\n * fills the message's placeholders or is appended to it.\n */\nexport function jsonLine(\n level: keyof typeof LEVEL_RANK,\n component: string,\n bindings: Record<string, unknown>,\n msg: string,\n args: unknown[],\n): string {\n // Null prototype: a `__proto__` key in logged data stays a plain field.\n const fields: Record<string, unknown> = Object.create(null)\n const rest: unknown[] = []\n let err: unknown\n for (const arg of args) {\n if (arg instanceof Error) err ??= serializeError(arg)\n else if (isPlainObject(arg)) Object.assign(fields, arg)\n else rest.push(arg)\n }\n const line: Record<string, unknown> = {\n level: LEVEL_RANK[level],\n time: Date.now(),\n ...(component ? { component } : {}),\n }\n // Logged data is often untrusted (a request body): it must not rewrite the\n // line's level, time, source or message, or pass a plain object off as the\n // error. Those come from the logger only; a field with one of those names is\n // dropped.\n for (const source of [bindings, fields]) {\n for (const key of Object.keys(source)) {\n if (!RESERVED_FIELDS.has(key)) line[key] = source[key]\n }\n }\n if (err !== undefined) line.err = err\n line.msg = formatMessage(msg, rest)\n try {\n return JSON.stringify(line, bigintSafe)\n } catch {\n // Something can't be written (a circular field). Drop only that: every\n // other field stays, and `err` — usually why the line exists — keeps at\n // least its type, message and stack.\n const safe: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(line)) {\n try {\n JSON.stringify(value, bigintSafe)\n safe[key] = value\n } catch {\n safe[key] =\n key === 'err' && value && typeof value === 'object'\n ? pick(value as Record<string, unknown>, ['type', 'message', 'stack'])\n : '[unserializable]'\n }\n }\n return JSON.stringify(safe, bigintSafe)\n }\n}\n\nconst bigintSafe = (_key: string, value: unknown): unknown =>\n typeof value === 'bigint' ? value.toString() : value\n\nfunction pick(obj: Record<string, unknown>, keys: readonly string[]): Record<string, unknown> {\n const out: Record<string, unknown> = {}\n for (const key of keys) if (typeof obj[key] === 'string') out[key] = obj[key]\n return out\n}\n\n// ── ConsoleLoggerProvider (default) ────────────────────────────────────\n\n/**\n * Default provider — emits through `console.*` methods. Zero deps.\n *\n * Respects the `LOG_LEVEL` env var (default `info`): messages below the\n * threshold are dropped, so the verbose startup detail (the route table,\n * DI wiring, HMR ticks — all `debug`) stays quiet by default and only\n * appears with `LOG_LEVEL=debug`. `error`/`fatal` always print unless\n * `LOG_LEVEL=silent`.\n *\n * `LOG_FORMAT=json` writes one pino-compatible JSON object per line instead\n * (all levels through `console.log`, so one stream carries them): fields\n * from `logger.child({ ... })` and from trailing plain-object arguments, and\n * an `Error` argument as `err` with its stack and `cause` chain. The default\n * text output is unchanged.\n *\n * Swap it for pino, winston, bunyan, or anything else by implementing\n * the `LoggerProvider` interface and calling `Logger.setProvider()`\n * before `bootstrap()`.\n */\nexport class ConsoleLoggerProvider implements LoggerProvider {\n private prefix: string\n private useColor: boolean\n /** Fields from `logger.child({ ... })` — written on JSON lines. */\n private bindings: Record<string, unknown>\n\n constructor(prefix?: string, bindings: Record<string, unknown> = {}) {\n this.prefix = prefix ?? ''\n this.bindings = bindings\n this.useColor =\n typeof process !== 'undefined' && process.stdout?.isTTY === true && !process.env.NO_COLOR\n }\n\n /** Write `msg` as a JSON line when `LOG_FORMAT=json`; returns whether it did. */\n private json(level: keyof typeof LEVEL_RANK, msg: string, args: unknown[]): boolean {\n if (!jsonFormat()) return false\n console.log(jsonLine(level, this.prefix, this.bindings, msg, args))\n return true\n }\n\n private fmt(level: string, color: string, msg: string): string {\n const tag = this.prefix ? `[${this.prefix}]` : ''\n if (this.useColor) {\n return `${color}${level}\\x1b[0m ${tag ? `\\x1b[36m${tag}\\x1b[0m ` : ''}${msg}`\n }\n return `${level} ${tag ? `${tag} ` : ''}${msg}`\n }\n\n /** Should a message at `rank` print under the current `LOG_LEVEL`? */\n private enabled(rank: number): boolean {\n return rank >= thresholdRank()\n }\n\n info(msg: string, ...args: any[]) {\n if (!this.enabled(LEVEL_RANK.info) || this.json('info', msg, args)) return\n console.log(this.fmt('INFO', '\\x1b[32m', msg), ...args)\n }\n warn(msg: string, ...args: any[]) {\n if (!this.enabled(LEVEL_RANK.warn) || this.json('warn', msg, args)) return\n console.warn(this.fmt('WARN', '\\x1b[33m', msg), ...args)\n }\n error(msg: string, ...args: any[]) {\n if (!this.enabled(LEVEL_RANK.error) || this.json('error', msg, args)) return\n console.error(this.fmt('ERROR', '\\x1b[31m', msg), ...args)\n }\n debug(msg: string, ...args: any[]) {\n if (!this.enabled(LEVEL_RANK.debug) || this.json('debug', msg, args)) return\n console.debug(this.fmt('DEBUG', '\\x1b[90m', msg), ...args)\n }\n trace(msg: string, ...args: any[]) {\n if (!this.enabled(LEVEL_RANK.trace) || this.json('trace', msg, args)) return\n console.trace(this.fmt('TRACE', '\\x1b[90m', msg), ...args)\n }\n fatal(msg: string, ...args: any[]) {\n if (!this.enabled(LEVEL_RANK.fatal) || this.json('fatal', msg, args)) return\n console.error(this.fmt('FATAL', '\\x1b[1m\\x1b[31m', msg), ...args)\n }\n child(bindings: { component: string; [field: string]: unknown }): LoggerProvider {\n const { component, ...fields } = bindings\n return new ConsoleLoggerProvider(component, { ...this.bindings, ...fields })\n }\n}\n\n// ── Active provider ────────────────────────────────────────────────────\n\nlet activeProvider: LoggerProvider = new ConsoleLoggerProvider()\n\n/** Cache of named loggers to avoid creating duplicates */\nconst loggerCache = new Map<string, Logger>()\n\n/**\n * Named logger with component context.\n *\n * @example\n * ```ts\n * // Static factory — preferred\n * const log = Logger.for('UserService')\n * log.info('User created')\n * // Output: [UserService] User created\n *\n * // Shorthand function\n * const log = createLogger('OrderService')\n *\n * // Pluggable backend — see docs/guide/logging.md\n * Logger.setProvider(new MyCustomProvider())\n *\n * // Injectable — auto-named from class\n * class MyService {\n * @Autowired() private logger!: Logger\n * // or inject a named one:\n * private log = Logger.for('MyService')\n * }\n * ```\n */\nexport class Logger {\n private _provider: LoggerProvider\n private _providerVersion: number\n private _name?: string\n private _fields?: Record<string, unknown>\n\n /** Incremented on every setProvider/resetProvider so instances know to refresh */\n private static _providerVersion = 0\n\n constructor(name?: string, fields?: Record<string, unknown>) {\n this._name = name\n this._fields = fields\n this._providerVersion = Logger._providerVersion\n this._provider = this.derive()\n }\n\n /** The active provider's child for this logger's name and fields. */\n private derive(): LoggerProvider {\n if (!this._name && !this._fields) return activeProvider\n return activeProvider.child({ ...this._fields, component: this._name ?? '' })\n }\n\n /** Re-derive the provider if setProvider() was called since construction/last access */\n private get provider(): LoggerProvider {\n if (this._providerVersion !== Logger._providerVersion) {\n this._providerVersion = Logger._providerVersion\n this._provider = this.derive()\n }\n return this._provider\n }\n\n /**\n * Replace the logging backend for **all** Logger instances created after\n * this call. Clears the logger cache so subsequent `Logger.for()` calls\n * pick up the new provider.\n *\n * @example\n * ```ts\n * Logger.setProvider(new MyWinstonProvider())\n * ```\n */\n static setProvider(provider: LoggerProvider): void {\n activeProvider = provider\n Logger._providerVersion++\n loggerCache.clear()\n }\n\n /** Return the currently active provider (useful for testing) */\n static getProvider(): LoggerProvider {\n return activeProvider\n }\n\n /**\n * Reset the provider back to the default `ConsoleLoggerProvider`.\n * Primarily intended for test teardown.\n */\n static resetProvider(): void {\n activeProvider = new ConsoleLoggerProvider()\n Logger._providerVersion++\n loggerCache.clear()\n }\n\n /** Create or retrieve a cached named logger */\n static for(name: string): Logger {\n let cached = loggerCache.get(name)\n if (!cached) {\n cached = new Logger(name)\n loggerCache.set(name, cached)\n }\n return cached\n }\n\n /** Create a child logger with a sub-component name */\n child(name: string): Logger\n /**\n * Create a child logger carrying `fields` on every line it writes — a\n * request id, a job name. Keeps this logger's name and fields. Written as\n * JSON fields under `LOG_FORMAT=json`; the default text output is unchanged.\n */\n child(fields: Record<string, unknown>): Logger\n child(nameOrFields: string | Record<string, unknown>): Logger {\n if (typeof nameOrFields === 'string') return new Logger(nameOrFields)\n return new Logger(this._name, { ...this._fields, ...nameOrFields })\n }\n\n info(msg: string, ...args: any[]) {\n this.provider.info(msg, ...args)\n }\n\n warn(msg: string, ...args: any[]) {\n this.provider.warn(msg, ...args)\n }\n\n /** Pino-style error-first form — `log.error(err, 'what failed')`. */\n error(err: unknown, msg: string, ...args: any[]): void\n /** Message-first form — `log.error('what failed', detail)`. */\n error(msg: string, ...args: any[]): void\n /** Error alone — `log.error(err)`. */\n error(err: unknown): void\n error(msgOrErr: any, ...rest: any[]): void {\n if (typeof msgOrErr === 'string') {\n // Message-first. `rest` used to be dropped on the floor, so\n // `log.error('save failed', { id })` logged only the string.\n this.provider.error(msgOrErr, ...rest)\n return\n }\n\n // Error-first (the framework's own idiom at ~16 call sites). The\n // error object used to be discarded entirely — `provider.error(msg)`\n // with the error nowhere in the call — so every `log.error(err, msg)`\n // in the codebase logged a bare sentence with NO stack, no error\n // name, and no `cause` chain. That is what made an unexpected 500\n // undiagnosable from the logs: you got the message and nothing else.\n //\n // The error is now forwarded as a trailing argument, which is what\n // the msg-first `LoggerProvider` contract can carry. `console.error`\n // renders the full stack from it; a pino/winston adapter receives it\n // as structured extra.\n const [maybeMsg, ...extra] = rest\n if (typeof maybeMsg === 'string') {\n this.provider.error(maybeMsg, msgOrErr, ...extra)\n } else {\n // No message supplied — use the error's own summary as the line so\n // the log stays readable, and still pass the object for the stack.\n this.provider.error(describeError(msgOrErr), msgOrErr, ...rest)\n }\n }\n\n debug(msg: string, ...args: any[]) {\n this.provider.debug(msg, ...args)\n }\n\n trace(msg: string, ...args: any[]) {\n if (this.provider.trace) this.provider.trace(msg, ...args)\n else this.provider.debug(msg, ...args)\n }\n\n fatal(msg: string, ...args: any[]) {\n if (this.provider.fatal) this.provider.fatal(msg, ...args)\n else this.provider.error(msg, ...args)\n }\n}\n\n/**\n * One-line summary of an unknown thrown value, including the error name\n * and — when present — the `cause` chain. ORM and driver errors routinely\n * wrap the useful detail in `cause`, so dropping it is how a 500 ends up\n * saying nothing actionable.\n *\n * Depth-capped and cycle-guarded: `cause` is attacker-influenced in some\n * stacks and self-referential chains do occur.\n */\nexport function describeError(err: unknown, maxDepth = 4): string {\n const parts: string[] = []\n const seen = new Set<unknown>()\n let current: unknown = err\n for (let depth = 0; current !== undefined && current !== null && depth < maxDepth; depth++) {\n if (seen.has(current)) {\n parts.push('[circular cause]')\n break\n }\n seen.add(current)\n if (current instanceof Error) {\n parts.push(current.name ? `${current.name}: ${current.message}` : current.message)\n current = (current as { cause?: unknown }).cause\n } else {\n parts.push(typeof current === 'string' ? current : safeStringify(current))\n break\n }\n }\n return parts.length > 0 ? parts.join(' ← caused by ') : 'Unknown error'\n}\n\n/** `JSON.stringify` that never throws on circular / exotic values. */\nfunction safeStringify(value: unknown): string {\n try {\n return JSON.stringify(value) ?? String(value)\n } catch {\n return String(value)\n }\n}\n\n/** Shorthand for Logger.for(name) */\nexport function createLogger(name: string): Logger {\n return Logger.for(name)\n}\n"],"mappings":";;;;;;;;;;AAiDA,MAAM,WAAqC,CACzC,MAAO,GACP,MAAO,GACP,KAAM,GACN,KAAM,GACN,MAAO,GACP,MAAO,GACP,OAAQ,GACV,EAOA,SAAS,eAAwB,CAM/B,IAAM,QACH,OAAO,QAAY,IAAc,QAAQ,KAAK,UAAY,IAAA,KAAc,OAAA,CACzE,YAAY,EACd,OAAO,WAAW,QAAU,WAAW,IACzC,CAGA,SAAS,YAAsB,CAC7B,OACG,OAAO,QAAY,IAAc,QAAQ,KAAK,WAAa,IAAA,GAAA,EAAY,YAAY,IAAM,MAE9F,CAGA,SAAS,cAAc,MAAkD,CACvE,GAAsB,OAAO,OAAU,WAAnC,MAA6C,MAAO,GACxD,IAAM,MAAQ,OAAO,eAAe,KAAK,EACzC,OAAO,QAAU,OAAO,WAAa,QAAU,IACjD,CAOA,SAAgB,eAAe,IAAc,MAAQ,EAAG,qBAAO,IAAI,IAAyB,CAC1F,GAAI,EAAE,eAAe,OAAQ,OAAO,IACpC,GAAI,KAAK,IAAI,GAAG,GAAK,OAAS,EAAG,MAAO,mBACxC,KAAK,IAAI,GAAG,EACZ,IAAM,IAA+B,CAAE,KAAM,IAAI,KAAM,QAAS,IAAI,QAAS,MAAO,IAAI,KAAM,EAC9F,IAAK,GAAM,CAAC,IAAK,SAAU,OAAO,QAAQ,GAAG,EAAS,OAAO,MAAM,IAAI,KAAO,OAC9E,IAAM,MAAS,IAA4B,MAE3C,OADI,QAAU,IAAA,KAAW,IAAI,MAAQ,eAAe,MAAO,MAAQ,EAAG,IAAI,GACnE,GACT,CAOA,SAAS,cAAc,IAAa,KAAyB,CAC3D,IAAI,EAAI,EACF,O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───────────────────────────────────────────\n\n/**\n * Pluggable logger backend.\n *\n * Implement this interface to plug in any logging library (pino,\n * winston, bunyan, console, etc.). The framework only ever calls the\n * methods declared here — it doesn't know or care which logger is\n * underneath.\n *\n * Default: `ConsoleLoggerProvider` (zero runtime deps).\n *\n * @example\n * ```ts\n * import pino from 'pino'\n * import { Logger, type LoggerProvider } from '@forinda/kickjs'\n *\n * class PinoProvider implements LoggerProvider {\n * constructor(private p = pino()) {}\n * info(msg, ...args) { this.p.info(msg, ...args) }\n * warn(msg, ...args) { this.p.warn(msg, ...args) }\n * error(msg, ...args) { this.p.error(msg, ...args) }\n * debug(msg, ...args) { this.p.debug(msg, ...args) }\n * child({ component }) { return new PinoProvider(this.p.child({ component })) }\n * }\n *\n * Logger.setProvider(new PinoProvider())\n * ```\n *\n * See https://kickjs.app/guide/logging for Pino, Winston, and silent-logger recipes.\n */\nexport interface LoggerProvider {\n info(msg: string, ...args: any[]): void\n warn(msg: string, ...args: any[]): void\n error(msg: string, ...args: any[]): void\n debug(msg: string, ...args: any[]): void\n trace?(msg: string, ...args: any[]): void\n fatal?(msg: string, ...args: any[]): void\n /**\n * Return a child provider scoped to the given component name. `bindings`\n * may also carry fields from `logger.child({ ... })` (a request id, a job\n * name) — a provider that ignores them keeps working as before.\n */\n child(bindings: { component: string; [field: string]: unknown }): LoggerProvider\n}\n\n// ── Log levels ─────────────────────────────────────────────────────────\n\n/** Severity ordering — a message prints only when its rank ≥ the threshold. */\nconst LEVEL_RANK: Record<string, number> = {\n trace: 10,\n debug: 20,\n info: 30,\n warn: 40,\n error: 50,\n fatal: 60,\n silent: 100,\n}\n\n/**\n * Resolve the active threshold rank from `LOG_LEVEL` (default `info`).\n * Read per-call so a late `process.env.LOG_LEVEL` assignment still\n * takes effect. An unrecognised value falls back to `info`.\n */\nfunction thresholdRank(): number {\n // `process` is guarded because this module is reachable from the\n // edge-safe web pipeline (`@forinda/kickjs/web`), where strict runtimes\n // expose no `process` global at all. The colour probe below already\n // guarded; this one did not, so merely importing the logger could throw\n // on such a runtime.\n const level = (\n (typeof process !== 'undefined' ? process.env?.LOG_LEVEL : undefined) ?? 'info'\n ).toLowerCase()\n return LEVEL_RANK[level] ?? LEVEL_RANK.info\n}\n\n/** `LOG_FORMAT=json` switches the default provider to one JSON object per line. */\nfunction jsonFormat(): boolean {\n return (\n (typeof process !== 'undefined' ? process.env?.LOG_FORMAT : undefined)?.toLowerCase() === 'json'\n )\n}\n\n/** A plain `{ ... }` object — merged into a JSON line as fields. */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== 'object') return false\n const proto = Object.getPrototypeOf(value)\n return proto === Object.prototype || proto === null\n}\n\n/**\n * An error as a JSON field — `type`, `message`, `stack`, own enumerable\n * properties (a driver's `code`), and its `cause` chain, depth-capped and\n * cycle-guarded like {@link describeError}.\n */\nexport function serializeError(err: unknown, depth = 4, seen = new Set<unknown>()): unknown {\n if (!(err instanceof Error)) return err\n if (seen.has(err) || depth <= 0) return '[circular cause]'\n seen.add(err)\n const out: Record<string, unknown> = { type: err.name, message: err.message, stack: err.stack }\n for (const [key, value] of Object.entries(err)) if (!(key in out)) out[key] = value\n const cause = (err as { cause?: unknown }).cause\n if (cause !== undefined) out.cause = serializeError(cause, depth - 1, seen)\n return out\n}\n\n/**\n * Fill printf-style placeholders the way `console.log` does (`%s %d %i %f\n * %j %o %O`, `%%`), then append what's left — so `log.info('hi %s', name)`\n * reads the same in JSON as on a terminal.\n */\nfunction formatMessage(msg: string, args: unknown[]): string {\n let i = 0\n const filled = msg.replace(/%[sdifjoO%]/g, (token) => {\n if (token === '%%') return '%'\n if (i >= args.length) return token\n const value = args[i++]\n if (token === '%d' || token === '%i') return String(Math.trunc(Number(value)))\n if (token === '%f') return String(Number(value))\n if (token === '%s') return typeof value === 'string' ? value : safeStringify(value)\n return safeStringify(value)\n })\n const rest = args.slice(i).map((a) => (typeof a === 'string' ? a : safeStringify(a)))\n return rest.length ? `${filled} ${rest.join(' ')}` : filled\n}\n\n/** Keys of a JSON line only the logger writes — see {@link jsonLine}. */\nconst RESERVED_FIELDS = new Set(['level', 'time', 'component', 'msg', 'err'])\n\n/**\n * One JSON log line, field-compatible with pino (`level` 10–60, `time` in\n * epoch ms, `msg`) so `pino-pretty` and log shippers read it as-is. Trailing\n * plain objects become fields, an `Error` becomes `err`, and anything else\n * fills the message's placeholders or is appended to it.\n */\nexport function jsonLine(\n level: keyof typeof LEVEL_RANK,\n component: string,\n bindings: Record<string, unknown>,\n msg: string,\n args: unknown[],\n): string {\n // Null prototype: a `__proto__` key in logged data stays a plain field.\n const fields: Record<string, unknown> = Object.create(null)\n const rest: unknown[] = []\n let err: unknown\n for (const arg of args) {\n if (arg instanceof Error) err ??= serializeError(arg)\n else if (isPlainObject(arg)) Object.assign(fields, arg)\n else rest.push(arg)\n }\n const line: Record<string, unknown> = {\n level: LEVEL_RANK[level],\n time: Date.now(),\n ...(component ? { component } : {}),\n }\n // Logged data is often untrusted (a request body): it must not rewrite the\n // line's level, time, source or message, or pass a plain object off as the\n // error. Those come from the logger only; a field with one of those names is\n // dropped.\n for (const source of [bindings, fields]) {\n for (const key of Object.keys(source)) {\n if (!RESERVED_FIELDS.has(key)) line[key] = source[key]\n }\n }\n if (err !== undefined) line.err = err\n line.msg = formatMessage(msg, rest)\n try {\n return JSON.stringify(line, bigintSafe)\n } catch {\n // Something can't be written (a circular field). Drop only that: every\n // other field stays, and `err` — usually why the line exists — keeps at\n // least its type, message and stack.\n const safe: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(line)) {\n try {\n JSON.stringify(value, bigintSafe)\n safe[key] = value\n } catch {\n safe[key] =\n key === 'err' && value && typeof value === 'object'\n ? pick(value as Record<string, unknown>, ['type', 'message', 'stack'])\n : '[unserializable]'\n }\n }\n return JSON.stringify(safe, bigintSafe)\n }\n}\n\nconst bigintSafe = (_key: string, value: unknown): unknown =>\n typeof value === 'bigint' ? value.toString() : value\n\nfunction pick(obj: Record<string, unknown>, keys: readonly string[]): Record<string, unknown> {\n const out: Record<string, unknown> = {}\n for (const key of keys) if (typeof obj[key] === 'string') out[key] = obj[key]\n return out\n}\n\n// ── ConsoleLoggerProvider (default) ────────────────────────────────────\n\n/**\n * Default provider — emits through `console.*` methods. Zero deps.\n *\n * Respects the `LOG_LEVEL` env var (default `info`): messages below the\n * threshold are dropped, so the verbose startup detail (the route table,\n * DI wiring, HMR ticks — all `debug`) stays quiet by default and only\n * appears with `LOG_LEVEL=debug`. `error`/`fatal` always print unless\n * `LOG_LEVEL=silent`.\n *\n * `LOG_FORMAT=json` writes one pino-compatible JSON object per line instead\n * (all levels through `console.log`, so one stream carries them): fields\n * from `logger.child({ ... })` and from trailing plain-object arguments, and\n * an `Error` argument as `err` with its stack and `cause` chain. The default\n * text output is unchanged.\n *\n * Swap it for pino, winston, bunyan, or anything else by implementing\n * the `LoggerProvider` interface and calling `Logger.setProvider()`\n * before `bootstrap()`.\n */\nexport class ConsoleLoggerProvider implements LoggerProvider {\n private prefix: string\n private useColor: boolean\n /** Fields from `logger.child({ ... })` — written on JSON lines. */\n private bindings: Record<string, unknown>\n\n constructor(prefix?: string, bindings: Record<string, unknown> = {}) {\n this.prefix = prefix ?? ''\n this.bindings = bindings\n this.useColor =\n typeof process !== 'undefined' && process.stdout?.isTTY === true && !process.env.NO_COLOR\n }\n\n /** Write `msg` as a JSON line when `LOG_FORMAT=json`; returns whether it did. */\n private json(level: keyof typeof LEVEL_RANK, msg: string, args: unknown[]): boolean {\n if (!jsonFormat()) return false\n console.log(jsonLine(level, this.prefix, this.bindings, msg, args))\n return true\n }\n\n private fmt(level: string, color: string, msg: string): string {\n const tag = this.prefix ? `[${this.prefix}]` : ''\n if (this.useColor) {\n return `${color}${level}\\x1b[0m ${tag ? `\\x1b[36m${tag}\\x1b[0m ` : ''}${msg}`\n }\n return `${level} ${tag ? `${tag} ` : ''}${msg}`\n }\n\n /** Should a message at `rank` print under the current `LOG_LEVEL`? */\n private enabled(rank: number): boolean {\n return rank >= thresholdRank()\n }\n\n info(msg: string, ...args: any[]) {\n if (!this.enabled(LEVEL_RANK.info) || this.json('info', msg, args)) return\n console.log(this.fmt('INFO', '\\x1b[32m', msg), ...args)\n }\n warn(msg: string, ...args: any[]) {\n if (!this.enabled(LEVEL_RANK.warn) || this.json('warn', msg, args)) return\n console.warn(this.fmt('WARN', '\\x1b[33m', msg), ...args)\n }\n error(msg: string, ...args: any[]) {\n if (!this.enabled(LEVEL_RANK.error) || this.json('error', msg, args)) return\n console.error(this.fmt('ERROR', '\\x1b[31m', msg), ...args)\n }\n debug(msg: string, ...args: any[]) {\n if (!this.enabled(LEVEL_RANK.debug) || this.json('debug', msg, args)) return\n console.debug(this.fmt('DEBUG', '\\x1b[90m', msg), ...args)\n }\n trace(msg: string, ...args: any[]) {\n if (!this.enabled(LEVEL_RANK.trace) || this.json('trace', msg, args)) return\n console.trace(this.fmt('TRACE', '\\x1b[90m', msg), ...args)\n }\n fatal(msg: string, ...args: any[]) {\n if (!this.enabled(LEVEL_RANK.fatal) || this.json('fatal', msg, args)) return\n console.error(this.fmt('FATAL', '\\x1b[1m\\x1b[31m', msg), ...args)\n }\n child(bindings: { component: string; [field: string]: unknown }): LoggerProvider {\n const { component, ...fields } = bindings\n return new ConsoleLoggerProvider(component, { ...this.bindings, ...fields })\n }\n}\n\n// ── Active provider ────────────────────────────────────────────────────\n\nlet activeProvider: LoggerProvider = new ConsoleLoggerProvider()\n\n/** Cache of named loggers to avoid creating duplicates */\nconst loggerCache = new Map<string, Logger>()\n\n/**\n * Named logger with component context.\n *\n * @example\n * ```ts\n * // Static factory — preferred\n * const log = Logger.for('UserService')\n * log.info('User created')\n * // Output: [UserService] User created\n *\n * // Shorthand function\n * const log = createLogger('OrderService')\n *\n * // Pluggable backend — see https://kickjs.app/guide/logging\n * Logger.setProvider(new MyCustomProvider())\n *\n * // Injectable — auto-named from class\n * class MyService {\n * @Autowired() private logger!: Logger\n * // or inject a named one:\n * private log = Logger.for('MyService')\n * }\n * ```\n */\nexport class Logger {\n private _provider: LoggerProvider\n private _providerVersion: number\n private _name?: string\n private _fields?: Record<string, unknown>\n\n /** Incremented on every setProvider/resetProvider so instances know to refresh */\n private static _providerVersion = 0\n\n constructor(name?: string, fields?: Record<string, unknown>) {\n this._name = name\n this._fields = fields\n this._providerVersion = Logger._providerVersion\n this._provider = this.derive()\n }\n\n /** The active provider's child for this logger's name and fields. */\n private derive(): LoggerProvider {\n if (!this._name && !this._fields) return activeProvider\n return activeProvider.child({ ...this._fields, component: this._name ?? '' })\n }\n\n /** Re-derive the provider if setProvider() was called since construction/last access */\n private get provider(): LoggerProvider {\n if (this._providerVersion !== Logger._providerVersion) {\n this._providerVersion = Logger._providerVersion\n this._provider = this.derive()\n }\n return this._provider\n }\n\n /**\n * Replace the logging backend for **all** Logger instances created after\n * this call. Clears the logger cache so subsequent `Logger.for()` calls\n * pick up the new provider.\n *\n * @example\n * ```ts\n * Logger.setProvider(new MyWinstonProvider())\n * ```\n */\n static setProvider(provider: LoggerProvider): void {\n activeProvider = provider\n Logger._providerVersion++\n loggerCache.clear()\n }\n\n /** Return the currently active provider (useful for testing) */\n static getProvider(): LoggerProvider {\n return activeProvider\n }\n\n /**\n * Reset the provider back to the default `ConsoleLoggerProvider`.\n * Primarily intended for test teardown.\n */\n static resetProvider(): void {\n activeProvider = new ConsoleLoggerProvider()\n Logger._providerVersion++\n loggerCache.clear()\n }\n\n /** Create or retrieve a cached named logger */\n static for(name: string): Logger {\n let cached = loggerCache.get(name)\n if (!cached) {\n cached = new Logger(name)\n loggerCache.set(name, cached)\n }\n return cached\n }\n\n /** Create a child logger with a sub-component name */\n child(name: string): Logger\n /**\n * Create a child logger carrying `fields` on every line it writes — a\n * request id, a job name. Keeps this logger's name and fields. Written as\n * JSON fields under `LOG_FORMAT=json`; the default text output is unchanged.\n */\n child(fields: Record<string, unknown>): Logger\n child(nameOrFields: string | Record<string, unknown>): Logger {\n if (typeof nameOrFields === 'string') return new Logger(nameOrFields)\n return new Logger(this._name, { ...this._fields, ...nameOrFields })\n }\n\n info(msg: string, ...args: any[]) {\n this.provider.info(msg, ...args)\n }\n\n warn(msg: string, ...args: any[]) {\n this.provider.warn(msg, ...args)\n }\n\n /** Pino-style error-first form — `log.error(err, 'what failed')`. */\n error(err: unknown, msg: string, ...args: any[]): void\n /** Message-first form — `log.error('what failed', detail)`. */\n error(msg: string, ...args: any[]): void\n /** Error alone — `log.error(err)`. */\n error(err: unknown): void\n error(msgOrErr: any, ...rest: any[]): void {\n if (typeof msgOrErr === 'string') {\n // Message-first. `rest` used to be dropped on the floor, so\n // `log.error('save failed', { id })` logged only the string.\n this.provider.error(msgOrErr, ...rest)\n return\n }\n\n // Error-first (the framework's own idiom at ~16 call sites). The\n // error object used to be discarded entirely — `provider.error(msg)`\n // with the error nowhere in the call — so every `log.error(err, msg)`\n // in the codebase logged a bare sentence with NO stack, no error\n // name, and no `cause` chain. That is what made an unexpected 500\n // undiagnosable from the logs: you got the message and nothing else.\n //\n // The error is now forwarded as a trailing argument, which is what\n // the msg-first `LoggerProvider` contract can carry. `console.error`\n // renders the full stack from it; a pino/winston adapter receives it\n // as structured extra.\n const [maybeMsg, ...extra] = rest\n if (typeof maybeMsg === 'string') {\n this.provider.error(maybeMsg, msgOrErr, ...extra)\n } else {\n // No message supplied — use the error's own summary as the line so\n // the log stays readable, and still pass the object for the stack.\n this.provider.error(describeError(msgOrErr), msgOrErr, ...rest)\n }\n }\n\n debug(msg: string, ...args: any[]) {\n this.provider.debug(msg, ...args)\n }\n\n trace(msg: string, ...args: any[]) {\n if (this.provider.trace) this.provider.trace(msg, ...args)\n else this.provider.debug(msg, ...args)\n }\n\n fatal(msg: string, ...args: any[]) {\n if (this.provider.fatal) this.provider.fatal(msg, ...args)\n else this.provider.error(msg, ...args)\n }\n}\n\n/**\n * One-line summary of an unknown thrown value, including the error name\n * and — when present — the `cause` chain. ORM and driver errors routinely\n * wrap the useful detail in `cause`, so dropping it is how a 500 ends up\n * saying nothing actionable.\n *\n * Depth-capped and cycle-guarded: `cause` is attacker-influenced in some\n * stacks and self-referential chains do occur.\n */\nexport function describeError(err: unknown, maxDepth = 4): string {\n const parts: string[] = []\n const seen = new Set<unknown>()\n let current: unknown = err\n for (let depth = 0; current !== undefined && current !== null && depth < maxDepth; depth++) {\n if (seen.has(current)) {\n parts.push('[circular cause]')\n break\n }\n seen.add(current)\n if (current instanceof Error) {\n parts.push(current.name ? `${current.name}: ${current.message}` : current.message)\n current = (current as { cause?: unknown }).cause\n } else {\n parts.push(typeof current === 'string' ? current : safeStringify(current))\n break\n }\n }\n return parts.length > 0 ? parts.join(' ← caused by ') : 'Unknown error'\n}\n\n/** `JSON.stringify` that never throws on circular / exotic values. */\nfunction safeStringify(value: unknown): string {\n try {\n return JSON.stringify(value) ?? String(value)\n } catch {\n return String(value)\n }\n}\n\n/** Shorthand for Logger.for(name) */\nexport function createLogger(name: string): Logger {\n return Logger.for(name)\n}\n"],"mappings":";;;;;;;;;;AAiDA,MAAM,WAAqC,CACzC,MAAO,GACP,MAAO,GACP,KAAM,GACN,KAAM,GACN,MAAO,GACP,MAAO,GACP,OAAQ,GACV,EAOA,SAAS,eAAwB,CAM/B,IAAM,QACH,OAAO,QAAY,IAAc,QAAQ,KAAK,UAAY,IAAA,KAAc,OAAA,CACzE,YAAY,EACd,OAAO,WAAW,QAAU,WAAW,IACzC,CAGA,SAAS,YAAsB,CAC7B,OACG,OAAO,QAAY,IAAc,QAAQ,KAAK,WAAa,IAAA,GAAA,EAAY,YAAY,IAAM,MAE9F,CAGA,SAAS,cAAc,MAAkD,CACvE,GAAsB,OAAO,OAAU,WAAnC,MAA6C,MAAO,GACxD,IAAM,MAAQ,OAAO,eAAe,KAAK,EACzC,OAAO,QAAU,OAAO,WAAa,QAAU,IACjD,CAOA,SAAgB,eAAe,IAAc,MAAQ,EAAG,qBAAO,IAAI,IAAyB,CAC1F,GAAI,EAAE,eAAe,OAAQ,OAAO,IACpC,GAAI,KAAK,IAAI,GAAG,GA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U,cAAc,OAAO,CAAC,EACzE,KACF,CACF,CACA,OAAO,MAAM,OAAS,EAAI,MAAM,KAAK,eAAe,EAAI,eAC1D,CAGA,SAAS,cAAc,MAAwB,CAC7C,GAAI,CACF,OAAO,KAAK,UAAU,KAAK,GAAK,OAAO,KAAK,CAC9C,MAAQ,CACN,OAAO,OAAO,KAAK,CACrB,CACF,CAGA,SAAgB,aAAa,KAAsB,CACjD,OAAO,OAAO,IAAI,IAAI,CACxB,C"}
|
package/dist/core/path.mjs
CHANGED
package/dist/core/plugin.d.mts
CHANGED
package/dist/core/plugin.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
|
|
2
|
-
import { a as batch, c as reactive, d as toRefs, f as unref, i as WatchOptions, l as ref, n as Ref, o as computed, p as watch, r as RefOptions, s as isRef, t as ComputedRef, u as toRef } from "../reactivity-
|
|
2
|
+
import { a as batch, c as reactive, d as toRefs, f as unref, i as WatchOptions, l as ref, n as Ref, o as computed, p as watch, r as RefOptions, s as isRef, t as ComputedRef, u as toRef } from "../reactivity-KZOrwVeK.mjs";
|
|
3
3
|
export { ComputedRef, Ref, RefOptions, WatchOptions, batch, computed, isRef, reactive, ref, toRef, toRefs, unref, watch };
|
package/dist/core/reactivity.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.15.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,5 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{createLogger}from"./logger.mjs";import{r as reportError}from"../observers-
|
|
11
|
+
import{createLogger}from"./logger.mjs";import{r as reportError}from"../observers-fQtCIKLq.mjs";let activeEffect=null;const targetMap=/* @__PURE__ */ new WeakMap,ITERATE_KEY=Symbol(`iterate`);function createEffect(fn,computed=!1){let effect=fn;return effect.deps=/* @__PURE__ */ new Set,computed&&(effect.computed=!0),effect}function cleanupEffect(effect){for(let depSet of effect.deps)depSet.delete(effect);effect.deps.clear()}function runTracked(effect,fn){cleanupEffect(effect);let prev=activeEffect;activeEffect=effect;try{return fn()}finally{activeEffect=prev}}function untracked(fn){let prev=activeEffect;activeEffect=null;try{return fn()}finally{activeEffect=prev}}function track(target,key){if(!activeEffect)return;let depsMap=targetMap.get(target);depsMap||(depsMap=/* @__PURE__ */ new Map,targetMap.set(target,depsMap));let deps=depsMap.get(key);deps||(deps=/* @__PURE__ */ new Set,depsMap.set(key,deps)),deps.add(activeEffect),activeEffect.deps.add(deps)}function trigger(target,key){let deps=targetMap.get(target)?.get(key);if(deps&&deps.size!==0)for(let effect of Array.from(deps))schedule(effect)}let batchDepth=0;const queue=/* @__PURE__ */ new Set;function schedule(effect){batchDepth>0&&!effect.computed?queue.add(effect):runEffect(effect)}const running=/* @__PURE__ */ new Map,log=createLogger(`Reactivity`);function report(err){try{log.error({err},`A watcher threw. The change still applied, and the other watchers ran.`)}catch{}reportError(err,{source:`watch`})}function runEffect(effect){let depth=(running.get(effect)??0)+1;if(depth>100)report(/* @__PURE__ */ Error(`Reactivity loop: an effect re-triggered itself 100 levels deep — a watcher that writes to what it watches, or two that write to each other. Stopped it.`));else{running.set(effect,depth);try{effect()}catch(err){report(err)}finally{depth===1?running.delete(effect):running.set(effect,depth-1)}}}function batch(fn){batchDepth++;try{return fn()}finally{if(--batchDepth===0)for(;queue.size>0;){let pending=[...queue];queue.clear();for(let effect of pending)runEffect(effect)}}}const REF=Symbol.for(`kickjs.ref`);function ref(initialValue,options={}){let subscribers=/* @__PURE__ */ new Set,wrapper={_value:initialValue},deep=options.deep===!0,notify=(newValue,oldValue)=>{for(let fn of Array.from(subscribers))try{fn(newValue,oldValue)}catch(err){report(err)}},batchedFrom=null,flush=createEffect(()=>{let from=batchedFrom;batchedFrom=null,Object.is(from.value,wrapper._value)||notify(wrapper._value,from.value)});return{[REF]:!0,get value(){track(wrapper,`_value`);let value=wrapper._value;return deep&&typeof value==`object`&&value?reactive(value):value},set value(newValue){let oldValue=wrapper._value;Object.is(oldValue,newValue)||(wrapper._value=newValue,trigger(wrapper,`_value`),subscribers.size!==0&&(batchDepth>0?(batchedFrom??={value:oldValue},queue.add(flush)):notify(newValue,oldValue)))},subscribe(fn){return subscribers.add(fn),()=>subscribers.delete(fn)},toJSON(){return wrapper._value}}}function computed(getter){let cached,dirty=!0,disposed=!1,wrapper={_value:void 0},effect=createEffect(()=>{dirty=!0,trigger(wrapper,`_value`)},!0),recompute=()=>disposed?untracked(getter):(dirty&&=(cached=runTracked(effect,getter),wrapper._value=cached,!1),cached);return{[REF]:!0,get value(){return track(wrapper,`_value`),recompute()},dispose(){disposed=!0,cleanupEffect(effect)},toJSON(){return recompute()}}}function watch(source,callback,options){let oldValue,stopped=!1,getter=typeof source==`function`?source:()=>source.value,job=createEffect(()=>{if(stopped)return;let newValue=runTracked(job,getter);if(!Object.is(newValue,oldValue)){let previous=oldValue;oldValue=newValue,callback(newValue,previous)}});if(oldValue=runTracked(job,getter),options?.immediate)try{callback(oldValue,void 0)}catch(err){report(err)}return()=>{stopped=!0,queue.delete(job),cleanupEffect(job)}}const proxyCache=/* @__PURE__ */ new WeakMap,proxies=/* @__PURE__ */ new WeakSet,ARRAY_MUTATORS=/* @__PURE__ */ new Set([`push`,`pop`,`shift`,`unshift`,`splice`,`sort`,`reverse`,`fill`,`copyWithin`]);function reactive(target){if(proxies.has(target))return target;let existing=proxyCache.get(target);if(existing)return existing;let isArray=Array.isArray(target),iterateKey=isArray?`length`:ITERATE_KEY,proxy=new Proxy(target,{get(obj,key,receiver){if(isArray&&typeof key==`string`&&ARRAY_MUTATORS.has(key)){let method=Reflect.get(obj,key,receiver);return(...args)=>batch(()=>untracked(()=>method.apply(proxy,args)))}let value=Reflect.get(obj,key,receiver);return typeof key==`symbol`?value:(track(obj,key),typeof value==`object`&&value?reactive(value):value)},set(obj,key,value,receiver){let hadKey=isArray&&typeof key==`string`&&/^\d+$/.test(key)?Number(key)<obj.length:Object.hasOwn(obj,key),oldValue=Reflect.get(obj,key,receiver),result=Reflect.set(obj,key,value,receiver);return typeof key==`symbol`||(hadKey?Object.is(oldValue,value)||trigger(obj,key):batch(()=>{trigger(obj,key),trigger(obj,iterateKey)})),result},deleteProperty(obj,key){let hadKey=Object.hasOwn(obj,key),result=Reflect.deleteProperty(obj,key);return result&&hadKey&&typeof key!=`symbol`&&batch(()=>{trigger(obj,key),trigger(obj,iterateKey)}),result},has(obj,key){return typeof key!=`symbol`&&track(obj,key),Reflect.has(obj,key)},ownKeys(obj){return track(obj,iterateKey),Reflect.ownKeys(obj)}});return proxyCache.set(target,proxy),proxies.add(proxy),proxy}function isRef(value){return typeof value==`object`&&!!value&&value[REF]===!0}function unref(value){return isRef(value)?value.value:value}function toRef(obj,key){return{[REF]:!0,get value(){return obj[key]},set value(value){obj[key]=value},subscribe(fn){return watch(()=>obj[key],fn)},toJSON(){return obj[key]}}}function toRefs(obj){let result={};for(let key of Object.keys(obj))result[key]=toRef(obj,key);return result}export{batch,computed,isRef,reactive,ref,toRef,toRefs,unref,watch};
|
|
12
12
|
//# sourceMappingURL=reactivity.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reactivity.mjs","names":[],"sources":["../../src/core/reactivity.ts"],"sourcesContent":["/**\n * Lightweight reactivity system inspired by Vue 3's composition API.\n * Provides ref(), computed(), watch(), reactive() and batch() for observable\n * backend state — config, metrics, health, circuit breakers.\n */\nimport { createLogger } from './logger'\nimport { reportError } from './observers'\n\n// ── Dependency Tracking ─────────────────────────────────────────────────\n//\n// Effects carry back-references to every dep Set they were added to, so\n// stopping a watcher / disposing a computed — or simply re-running an\n// effect whose getter reads different keys this time — removes it from the\n// old Sets instead of leaving dead subscriptions to accumulate (and be\n// invoked!) forever. Same cleanup discipline as Vue 3's ReactiveEffect.\n\ninterface Effect {\n (): void\n /** Dep Sets this effect is currently registered in (for cleanup). */\n deps: Set<Set<Effect>>\n /**\n * A computed's effect: it only marks the computed stale and passes the\n * change on, so it runs at once even inside batch(). Watchers and ref\n * subscribers wait for the batch to end.\n */\n computed?: boolean\n}\n\nlet activeEffect: Effect | null = null\nconst targetMap = new WeakMap<object, Map<string | symbol, Set<Effect>>>()\n\n/** Tracks key iteration (`Object.keys`, `for…in`) and key additions/removals on an object. */\nconst ITERATE_KEY = Symbol('iterate')\n\nfunction createEffect(fn: () => void, computed = false): Effect {\n const effect = fn as Effect\n effect.deps = new Set()\n if (computed) effect.computed = true\n return effect\n}\n\n/** Remove the effect from every dep Set it was tracked into. */\nfunction cleanupEffect(effect: Effect): void {\n for (const depSet of effect.deps) depSet.delete(effect)\n effect.deps.clear()\n}\n\n/**\n * Run `fn` with `effect` as the active tracking target, first clearing the\n * effect's previous subscriptions so conditional reads don't leave stale deps.\n */\nfunction runTracked<T>(effect: Effect, fn: () => T): T {\n cleanupEffect(effect)\n const prev = activeEffect\n activeEffect = effect\n try {\n return fn()\n } finally {\n activeEffect = prev\n }\n}\n\n/** Run `fn` without tracking — what an array mutator reads isn't a dependency. */\nfunction untracked<T>(fn: () => T): T {\n const prev = activeEffect\n activeEffect = null\n try {\n return fn()\n } finally {\n activeEffect = prev\n }\n}\n\nfunction track(target: object, key: string | symbol): void {\n if (!activeEffect) return\n let depsMap = targetMap.get(target)\n if (!depsMap) {\n depsMap = new Map()\n targetMap.set(target, depsMap)\n }\n let deps = depsMap.get(key)\n if (!deps) {\n deps = new Set()\n depsMap.set(key, deps)\n }\n deps.add(activeEffect)\n activeEffect.deps.add(deps)\n}\n\nfunction trigger(target: object, key: string | symbol): void {\n const deps = targetMap.get(target)?.get(key)\n if (!deps || deps.size === 0) return\n for (const effect of Array.from(deps)) schedule(effect)\n}\n\n// ── Scheduling: batch, error isolation, loop detection ──────────────────\n\nlet batchDepth = 0\nconst queue = new Set<Effect>()\n\nfunction schedule(effect: Effect): void {\n if (batchDepth > 0 && !effect.computed) queue.add(effect)\n else runEffect(effect)\n}\n\n/**\n * How deep one effect may re-enter itself — triggered again while it is still\n * running, as a watcher that writes to what it watches does, or two that write\n * to each other — before it is stopped as a loop. Runs one after another\n * (a watcher pushing 1000 items, each re-running another watcher) never nest,\n * so they don't count.\n */\nconst MAX_REENTRY = 100\n/** Effects running right now, by how many times each is on the stack. */\nconst running = new Map<Effect, number>()\n\nconst log = createLogger('Reactivity')\n\nfunction report(err: unknown): void {\n try {\n log.error({ err }, 'A watcher threw. The change still applied, and the other watchers ran.')\n } catch {\n // A failing logger must not turn a watcher error back into a throw.\n }\n reportError(err, { source: 'watch' })\n}\n\n/**\n * Run one effect. Its error is reported, never thrown: the write that\n * triggered it, and every other effect it triggered, carry on regardless.\n */\nfunction runEffect(effect: Effect): void {\n const depth = (running.get(effect) ?? 0) + 1\n if (depth > MAX_REENTRY) {\n report(\n new Error(\n `Reactivity loop: an effect re-triggered itself ${MAX_REENTRY} levels deep — ` +\n 'a watcher that writes to what it watches, or two that write to each other. Stopped it.',\n ),\n )\n return\n }\n running.set(effect, depth)\n try {\n effect()\n } catch (err) {\n report(err)\n } finally {\n if (depth === 1) running.delete(effect)\n else running.set(effect, depth - 1)\n }\n}\n\n/**\n * Apply several writes as one update: watchers and ref subscribers run once,\n * after `fn` returns, with the final values — never with a half-applied state.\n * Computed values stay current inside the batch. Batches nest; the outermost\n * one flushes. Returns what `fn` returns.\n *\n * @example\n * ```ts\n * const total = computed(() => a.value + b.value)\n * watch(total, (v) => console.log(v))\n * batch(() => {\n * a.value = 2\n * b.value = 2\n * }) // logs 4 once, not 3 then 4\n * ```\n */\nexport function batch<T>(fn: () => T): T {\n batchDepth++\n try {\n return fn()\n } finally {\n if (--batchDepth === 0) {\n while (queue.size > 0) {\n const pending = [...queue]\n queue.clear()\n for (const effect of pending) runEffect(effect)\n }\n }\n }\n}\n\n// ── ref() ────────────────────────────────────────────────────────────────\n\n/** Marks refs, computed refs and `toRef()` views, for {@link isRef}. */\nconst REF = Symbol.for('kickjs.ref')\n\nexport interface Ref<T = any> {\n value: T\n /**\n * Subscribe to changes. Returns unsubscribe function. Inside {@link batch},\n * called once when the batch ends, if the value differs from before it.\n */\n subscribe(fn: (newValue: T, oldValue: T) => void): () => void\n /**\n * Auto-unwrap on `JSON.stringify` — returns the underlying value\n * so refs serialize transparently inside larger payloads (introspect\n * snapshots, devtools state, request responses). Equivalent to\n * `unref(ref)` but invoked implicitly by the JSON pipeline.\n */\n toJSON(): T\n}\n\nexport interface RefOptions {\n /**\n * Make an object value deeply reactive: `r.value.count++` and\n * `r.value.items.push(x)` notify too, not only replacing `r.value`.\n * Default: false — only assigning `.value` notifies.\n */\n deep?: boolean\n}\n\n/**\n * Create a reactive reference. Reading `.value` tracks the dependency,\n * writing `.value` triggers watchers and computed recalculations.\n *\n * @example\n * ```ts\n * const count = ref(0)\n * count.value++ // triggers watchers\n *\n * const config = ref({ retries: 3 }, { deep: true })\n * config.value.retries = 5 // triggers watchers too\n * ```\n */\nexport function ref<T>(initialValue: T, options: RefOptions = {}): Ref<T> {\n const subscribers = new Set<(newValue: T, oldValue: T) => void>()\n const wrapper = { _value: initialValue }\n const deep = options.deep === true\n\n const notify = (newValue: T, oldValue: T) => {\n // A copy: a subscriber may unsubscribe while being notified.\n for (const fn of Array.from(subscribers)) {\n try {\n fn(newValue, oldValue)\n } catch (err) {\n report(err)\n }\n }\n }\n // Inside a batch, subscribers hear once, with the value from before the\n // batch and the one after it.\n let batchedFrom: { value: T } | null = null\n const flush = createEffect(() => {\n const from = batchedFrom!\n batchedFrom = null\n if (!Object.is(from.value, wrapper._value)) notify(wrapper._value, from.value)\n })\n\n return {\n [REF]: true,\n get value(): T {\n track(wrapper, '_value')\n const value = wrapper._value\n return deep && value !== null && typeof value === 'object'\n ? (reactive(value as object) as T)\n : value\n },\n set value(newValue: T) {\n const oldValue = wrapper._value\n if (Object.is(oldValue, newValue)) return\n wrapper._value = newValue\n trigger(wrapper, '_value')\n if (subscribers.size === 0) return\n if (batchDepth > 0) {\n batchedFrom ??= { value: oldValue }\n queue.add(flush)\n } else {\n notify(newValue, oldValue)\n }\n },\n subscribe(fn: (newValue: T, oldValue: T) => void): () => void {\n subscribers.add(fn)\n return () => subscribers.delete(fn)\n },\n toJSON(): T {\n return wrapper._value\n },\n } as Ref<T>\n}\n\n// ── computed() ───────────────────────────────────────────────────────────\n\nexport interface ComputedRef<T = any> {\n readonly value: T\n /**\n * Auto-unwrap on `JSON.stringify` — see {@link Ref.toJSON} for the\n * motivation. Triggers a recompute when the cached value is stale,\n * same as reading `.value`.\n */\n toJSON(): T\n /**\n * Unsubscribe this computed from its reactive sources. Call when the\n * computed's lifetime is shorter than its sources' (e.g. created\n * per-request/per-tenant against app-lifetime refs) — without it the\n * internal effect stays pinned in the sources' dep Sets forever.\n * After disposal, reading `.value` still works but recomputes on every\n * access and no longer tracks.\n */\n dispose(): void\n}\n\n/**\n * Create a computed value that auto-recalculates when its reactive\n * dependencies change. Cached until a dependency triggers.\n * @example\n * ```ts\n * const count = ref(0)\n * const doubled = computed(() => count.value * 2)\n * count.value = 5\n * console.log(doubled.value) // 10\n * ```\n */\nexport function computed<T>(getter: () => T): ComputedRef<T> {\n let cached: T\n let dirty = true\n let disposed = false\n const wrapper = { _value: undefined as T }\n\n const effect = createEffect(() => {\n dirty = true\n trigger(wrapper, '_value')\n }, true)\n\n const recompute = (): T => {\n // Disposed: plain evaluation with tracking SUSPENDED — neither this\n // computed's effect nor any OUTER active effect (a watcher reading\n // `.value`) may attach to the sources through a disposed computed;\n // otherwise disposal wouldn't actually sever the subscription chain.\n if (disposed) return untracked(getter)\n if (dirty) {\n cached = runTracked(effect, getter)\n wrapper._value = cached\n dirty = false\n }\n return cached\n }\n\n return {\n [REF]: true,\n get value(): T {\n track(wrapper, '_value')\n return recompute()\n },\n dispose(): void {\n disposed = true\n cleanupEffect(effect)\n },\n /**\n * Auto-unwrap on `JSON.stringify`, matching {@link ref}'s behavior\n * so adopters can drop a computed straight into a JSON-bound\n * payload (introspect snapshot, devtools state) and get the value\n * rather than the wrapper shape.\n *\n * Computed values cache through the same dirty-flag the getter\n * uses, so calling `toJSON` is at worst one recompute when stale —\n * identical cost to reading `.value`.\n */\n toJSON(): T {\n return recompute()\n },\n } as ComputedRef<T>\n}\n\n// ── watch() ──────────────────────────────────────────────────────────────\n\nexport interface WatchOptions {\n /** Run the callback immediately with the current value (default: false) */\n immediate?: boolean\n}\n\ntype WatchSource<T> = Ref<T> | ComputedRef<T> | (() => T)\n\n/**\n * Watch a reactive source and run a callback when it changes.\n * Returns a stop function to unsubscribe.\n *\n * A callback that throws is reported (logged, and passed to `onError`\n * observers) instead of thrown: the write that triggered it, and every other\n * watcher, carry on. Inside {@link batch}, the callback runs once, after the\n * batch.\n *\n * @example\n * ```ts\n * const count = ref(0)\n * const stop = watch(count, (newVal, oldVal) => {\n * console.log(`Changed from ${oldVal} to ${newVal}`)\n * })\n * count.value = 1 // logs: \"Changed from 0 to 1\"\n * stop() // no more callbacks\n * ```\n */\nexport function watch<T>(\n source: WatchSource<T>,\n callback: (newValue: T, oldValue: T) => void,\n options?: WatchOptions,\n): () => void {\n let oldValue: T\n let stopped = false\n\n const getter = typeof source === 'function' ? source : () => source.value\n\n const job = createEffect(() => {\n if (stopped) return\n // Re-run the getter UNDER tracking so deps are refreshed each run —\n // a conditional getter (`cond ? a.value : b.value`) drops the branch\n // it no longer reads instead of staying subscribed to it forever.\n const newValue = runTracked(job, getter)\n if (!Object.is(newValue, oldValue)) {\n const previous = oldValue\n // Advanced before the callback, so one that throws isn't re-called\n // with the same change on the next run.\n oldValue = newValue\n callback(newValue, previous)\n }\n })\n\n // Initial run to establish tracking\n oldValue = runTracked(job, getter)\n\n if (options?.immediate) {\n // Reported like any other run: watch() still returns its stop function.\n try {\n callback(oldValue, undefined as T)\n } catch (err) {\n report(err)\n }\n }\n\n return () => {\n // Detach from every dep Set — a flag alone would leave the dead effect\n // referenced (and invoked) by its sources for their entire lifetime.\n stopped = true\n queue.delete(job)\n cleanupEffect(job)\n }\n}\n\n// ── reactive() ───────────────────────────────────────────────────────────\n\n/**\n * Create a deeply reactive proxy around an object or array. Property reads\n * are tracked, writes and deletes trigger watchers and computed\n * recalculations, and so do key additions and removals for code that\n * iterates the keys (`Object.keys`, `for…in`, `in`). Nested objects and\n * arrays are reactive too.\n * @example\n * ```ts\n * const state = reactive({ users: 0, errors: 0 })\n * const errorRate = computed(() =>\n * state.users > 0 ? state.errors / state.users : 0\n * )\n * state.users = 100\n * state.errors = 5\n * console.log(errorRate.value) // 0.05\n * ```\n */\n// Memoize proxies per target: repeated reads of the same nested object must\n// return the SAME proxy — otherwise every access allocates a fresh Proxy and\n// referential identity breaks (`state.nested !== state.nested`).\nconst proxyCache = new WeakMap<object, any>()\n/** Proxies this module made — `reactive(proxy)` returns it rather than wrapping it again. */\nconst proxies = new WeakSet<object>()\n\n/** Array methods that change the array: run untracked and as one update. */\nconst ARRAY_MUTATORS = new Set([\n 'push',\n 'pop',\n 'shift',\n 'unshift',\n 'splice',\n 'sort',\n 'reverse',\n 'fill',\n 'copyWithin',\n])\n\nexport function reactive<T extends object>(target: T): T {\n if (proxies.has(target)) return target\n const existing = proxyCache.get(target)\n if (existing) return existing as T\n const isArray = Array.isArray(target)\n // What iterating this target depends on: an array's length, an object's key set.\n const iterateKey = isArray ? 'length' : ITERATE_KEY\n const proxy: T = new Proxy(target, {\n get(obj, key, receiver) {\n if (isArray && typeof key === 'string' && ARRAY_MUTATORS.has(key)) {\n const method = Reflect.get(obj, key, receiver) as (...args: unknown[]) => unknown\n return (...args: unknown[]) => batch(() => untracked(() => method.apply(proxy, args)))\n }\n const value = Reflect.get(obj, key, receiver)\n if (typeof key === 'symbol') return value\n track(obj, key)\n // Deep reactivity for nested objects and arrays\n if (value !== null && typeof value === 'object') return reactive(value)\n return value\n },\n set(obj, key, value, receiver) {\n const hadKey =\n isArray && typeof key === 'string' && /^\\d+$/.test(key)\n ? Number(key) < (obj as unknown[]).length\n : Object.hasOwn(obj, key)\n const oldValue = Reflect.get(obj, key, receiver)\n const result = Reflect.set(obj, key, value, receiver)\n if (typeof key === 'symbol') return result\n if (!hadKey) {\n batch(() => {\n trigger(obj, key)\n // A new array index grows the array, but its `length` write that\n // follows sees the length already updated — so it's triggered here.\n trigger(obj, iterateKey)\n })\n } else if (!Object.is(oldValue, value)) {\n trigger(obj, key)\n }\n return result\n },\n deleteProperty(obj, key) {\n const hadKey = Object.hasOwn(obj, key)\n const result = Reflect.deleteProperty(obj, key)\n if (result && hadKey && typeof key !== 'symbol') {\n batch(() => {\n trigger(obj, key)\n trigger(obj, iterateKey)\n })\n }\n return result\n },\n has(obj, key) {\n if (typeof key !== 'symbol') track(obj, key)\n return Reflect.has(obj, key)\n },\n ownKeys(obj) {\n track(obj, iterateKey)\n return Reflect.ownKeys(obj)\n },\n })\n proxyCache.set(target, proxy)\n proxies.add(proxy)\n return proxy\n}\n\n// ── Utility ──────────────────────────────────────────────────────────────\n\n/** Check if a value is a ref — from {@link ref}, {@link computed} or {@link toRef}. */\nexport function isRef<T = any>(value: unknown): value is Ref<T> | ComputedRef<T> {\n return value !== null && typeof value === 'object' && (value as any)[REF] === true\n}\n\n/** Unwrap a ref or computed ref, or return the value as-is */\nexport function unref<T>(value: Ref<T> | ComputedRef<T> | T): T {\n return isRef(value) ? (value.value as T) : (value as T)\n}\n\n/**\n * A ref that reads and writes `obj[key]`: a live view, not a copy. On a\n * {@link reactive} object, watching it follows changes made either way.\n */\nexport function toRef<T extends object, K extends keyof T>(obj: T, key: K): Ref<T[K]> {\n return {\n [REF]: true,\n get value(): T[K] {\n return obj[key]\n },\n set value(value: T[K]) {\n obj[key] = value\n },\n subscribe(fn: (newValue: T[K], oldValue: T[K]) => void): () => void {\n return watch(() => obj[key], fn)\n },\n toJSON(): T[K] {\n return obj[key]\n },\n } as Ref<T[K]>\n}\n\n/** {@link toRef} for every property: live views onto the object, not copies. */\nexport function toRefs<T extends object>(obj: T): { [K in keyof T]: Ref<T[K]> } {\n const result = {} as { [K in keyof T]: Ref<T[K]> }\n for (const key of Object.keys(obj) as Array<keyof T>) {\n result[key] = toRef(obj, key)\n }\n return result\n}\n"],"mappings":";;;;;;;;;;A,+FA4BA,IAAI,aAA8B,KAClC,MAAM,0BAAY,IAAI,QAGhB,YAAc,OAAO,SAAS,EAEpC,SAAS,aAAa,GAAgB,SAAW,GAAe,CAC9D,IAAM,OAAS,GAGf,MAFA,QAAO,qBAAO,IAAI,IACd,WAAU,OAAO,SAAW,IACzB,MACT,CAGA,SAAS,cAAc,OAAsB,CAC3C,IAAK,IAAM,UAAU,OAAO,KAAM,OAAO,OAAO,MAAM,EACtD,OAAO,KAAK,MAAM,CACpB,CAMA,SAAS,WAAc,OAAgB,GAAgB,CACrD,cAAc,MAAM,EACpB,IAAM,KAAO,aACb,aAAe,OACf,GAAI,CACF,OAAO,GAAG,CACZ,QAAU,CACR,aAAe,IACjB,CACF,CAGA,SAAS,UAAa,GAAgB,CACpC,IAAM,KAAO,aACb,aAAe,KACf,GAAI,CACF,OAAO,GAAG,CACZ,QAAU,CACR,aAAe,IACjB,CACF,CAEA,SAAS,MAAM,OAAgB,IAA4B,CACzD,GAAI,CAAC,aAAc,OACnB,IAAI,QAAU,UAAU,IAAI,MAAM,EAC7B,UACH,wBAAU,IAAI,IACd,UAAU,IAAI,OAAQ,OAAO,GAE/B,IAAI,KAAO,QAAQ,IAAI,GAAG,EACrB,OACH,qBAAO,IAAI,IACX,QAAQ,IAAI,IAAK,IAAI,GAEvB,KAAK,IAAI,YAAY,EACrB,aAAa,KAAK,IAAI,IAAI,CAC5B,CAEA,SAAS,QAAQ,OAAgB,IAA4B,CAC3D,IAAM,KAAO,UAAU,IAAI,MAAM,CAAC,EAAE,IAAI,GAAG,EAC3C,GAAK,MAAQ,KAAK,OAAS,EAC3B,IAAK,IAAM,UAAU,MAAM,KAAK,IAAI,EAAG,SAAS,MAAM,CACxD,CAIA,IAAI,WAAa,EACjB,MAAM,sBAAQ,IAAI,IAElB,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IAAuC,CAC9E,IAAM,OAAS,CAAC,EAChB,IAAK,IAAM,OAAO,OAAO,KAAK,GAAG,EAC/B,OAAO,KAAO,MAAM,IAAK,GAAG,EAE9B,OAAO,MACT,C"}
|
|
1
|
+
{"version":3,"file":"reactivity.mjs","names":[],"sources":["../../src/core/reactivity.ts"],"sourcesContent":["/**\n * Lightweight reactivity system inspired by Vue 3's composition API.\n * Provides ref(), computed(), watch(), reactive() and batch() for observable\n * backend state — config, metrics, health, circuit breakers.\n */\nimport { createLogger } from './logger'\nimport { reportError } from './observers'\n\n// ── Dependency Tracking ─────────────────────────────────────────────────\n//\n// Effects carry back-references to every dep Set they were added to, so\n// stopping a watcher / disposing a computed — or simply re-running an\n// effect whose getter reads different keys this time — removes it from the\n// old Sets instead of leaving dead subscriptions to accumulate (and be\n// invoked!) forever. Same cleanup discipline as Vue 3's ReactiveEffect.\n\ninterface Effect {\n (): void\n /** Dep Sets this effect is currently registered in (for cleanup). */\n deps: Set<Set<Effect>>\n /**\n * A computed's effect: it only marks the computed stale and passes the\n * change on, so it runs at once even inside batch(). Watchers and ref\n * subscribers wait for the batch to end.\n */\n computed?: boolean\n}\n\nlet activeEffect: Effect | null = null\nconst targetMap = new WeakMap<object, Map<string | symbol, Set<Effect>>>()\n\n/** Tracks key iteration (`Object.keys`, `for…in`) and key additions/removals on an object. */\nconst ITERATE_KEY = Symbol('iterate')\n\nfunction createEffect(fn: () => void, computed = false): Effect {\n const effect = fn as Effect\n effect.deps = new Set()\n if (computed) effect.computed = true\n return effect\n}\n\n/** Remove the effect from every dep Set it was tracked into. */\nfunction cleanupEffect(effect: Effect): void {\n for (const depSet of effect.deps) depSet.delete(effect)\n effect.deps.clear()\n}\n\n/**\n * Run `fn` with `effect` as the active tracking target, first clearing the\n * effect's previous subscriptions so conditional reads don't leave stale deps.\n */\nfunction runTracked<T>(effect: Effect, fn: () => T): T {\n cleanupEffect(effect)\n const prev = activeEffect\n activeEffect = effect\n try {\n return fn()\n } finally {\n activeEffect = prev\n }\n}\n\n/** Run `fn` without tracking — what an array mutator reads isn't a dependency. */\nfunction untracked<T>(fn: () => T): T {\n const prev = activeEffect\n activeEffect = null\n try {\n return fn()\n } finally {\n activeEffect = prev\n }\n}\n\nfunction track(target: object, key: string | symbol): void {\n if (!activeEffect) return\n let depsMap = targetMap.get(target)\n if (!depsMap) {\n depsMap = new Map()\n targetMap.set(target, depsMap)\n }\n let deps = depsMap.get(key)\n if (!deps) {\n deps = new Set()\n depsMap.set(key, deps)\n }\n deps.add(activeEffect)\n activeEffect.deps.add(deps)\n}\n\nfunction trigger(target: object, key: string | symbol): void {\n const deps = targetMap.get(target)?.get(key)\n if (!deps || deps.size === 0) return\n for (const effect of Array.from(deps)) schedule(effect)\n}\n\n// ── Scheduling: batch, error isolation, loop detection ──────────────────\n\nlet batchDepth = 0\nconst queue = new Set<Effect>()\n\nfunction schedule(effect: Effect): void {\n if (batchDepth > 0 && !effect.computed) queue.add(effect)\n else runEffect(effect)\n}\n\n/**\n * How deep one effect may re-enter itself — triggered again while it is still\n * running, as a watcher that writes to what it watches does, or two that write\n * to each other — before it is stopped as a loop. Runs one after another\n * (a watcher pushing 1000 items, each re-running another watcher) never nest,\n * so they don't count.\n */\nconst MAX_REENTRY = 100\n/** Effects running right now, by how many times each is on the stack. */\nconst running = new Map<Effect, number>()\n\nconst log = createLogger('Reactivity')\n\nfunction report(err: unknown): void {\n try {\n log.error({ err }, 'A watcher threw. The change still applied, and the other watchers ran.')\n } catch {\n // A failing logger must not turn a watcher error back into a throw.\n }\n reportError(err, { source: 'watch' })\n}\n\n/**\n * Run one effect. Its error is reported, never thrown: the write that\n * triggered it, and every other effect it triggered, carry on regardless.\n */\nfunction runEffect(effect: Effect): void {\n const depth = (running.get(effect) ?? 0) + 1\n if (depth > MAX_REENTRY) {\n report(\n new Error(\n `Reactivity loop: an effect re-triggered itself ${MAX_REENTRY} levels deep — ` +\n 'a watcher that writes to what it watches, or two that write to each other. Stopped it.',\n ),\n )\n return\n }\n running.set(effect, depth)\n try {\n effect()\n } catch (err) {\n report(err)\n } finally {\n if (depth === 1) running.delete(effect)\n else running.set(effect, depth - 1)\n }\n}\n\n/**\n * Apply several writes as one update: watchers and ref subscribers run once,\n * after `fn` returns, with the final values — never with a half-applied state.\n * Computed values stay current inside the batch. Batches nest; the outermost\n * one flushes. Returns what `fn` returns.\n *\n * @example\n * ```ts\n * const total = computed(() => a.value + b.value)\n * watch(total, (v) => console.log(v))\n * batch(() => {\n * a.value = 2\n * b.value = 2\n * }) // logs 4 once, not 3 then 4\n * ```\n */\nexport function batch<T>(fn: () => T): T {\n batchDepth++\n try {\n return fn()\n } finally {\n if (--batchDepth === 0) {\n while (queue.size > 0) {\n const pending = [...queue]\n queue.clear()\n for (const effect of pending) runEffect(effect)\n }\n }\n }\n}\n\n// ── ref() ────────────────────────────────────────────────────────────────\n\n/** Marks refs, computed refs and `toRef()` views, for {@link isRef}. */\nconst REF = Symbol.for('kickjs.ref')\n\n/**\n * A reactive value made by `ref()`. Reading `.value` tracks it; writing it notifies watchers and computed values.\n *\n * @see https://kickjs.app/guide/reactivity\n */\nexport interface Ref<T = any> {\n value: T\n /**\n * Subscribe to changes. Returns unsubscribe function. Inside {@link batch},\n * called once when the batch ends, if the value differs from before it.\n */\n subscribe(fn: (newValue: T, oldValue: T) => void): () => void\n /**\n * Auto-unwrap on `JSON.stringify` — returns the underlying value\n * so refs serialize transparently inside larger payloads (introspect\n * snapshots, devtools state, request responses). Equivalent to\n * `unref(ref)` but invoked implicitly by the JSON pipeline.\n */\n toJSON(): T\n}\n\n/** Options for `ref()`. */\nexport interface RefOptions {\n /**\n * Make an object value deeply reactive: `r.value.count++` and\n * `r.value.items.push(x)` notify too, not only replacing `r.value`.\n * Default: false — only assigning `.value` notifies.\n */\n deep?: boolean\n}\n\n/**\n * Create a reactive reference. Reading `.value` tracks the dependency,\n * writing `.value` triggers watchers and computed recalculations.\n *\n * @example\n * ```ts\n * const count = ref(0)\n * count.value++ // triggers watchers\n *\n * const config = ref({ retries: 3 }, { deep: true })\n * config.value.retries = 5 // triggers watchers too\n * ```\n */\nexport function ref<T>(initialValue: T, options: RefOptions = {}): Ref<T> {\n const subscribers = new Set<(newValue: T, oldValue: T) => void>()\n const wrapper = { _value: initialValue }\n const deep = options.deep === true\n\n const notify = (newValue: T, oldValue: T) => {\n // A copy: a subscriber may unsubscribe while being notified.\n for (const fn of Array.from(subscribers)) {\n try {\n fn(newValue, oldValue)\n } catch (err) {\n report(err)\n }\n }\n }\n // Inside a batch, subscribers hear once, with the value from before the\n // batch and the one after it.\n let batchedFrom: { value: T } | null = null\n const flush = createEffect(() => {\n const from = batchedFrom!\n batchedFrom = null\n if (!Object.is(from.value, wrapper._value)) notify(wrapper._value, from.value)\n })\n\n return {\n [REF]: true,\n get value(): T {\n track(wrapper, '_value')\n const value = wrapper._value\n return deep && value !== null && typeof value === 'object'\n ? (reactive(value as object) as T)\n : value\n },\n set value(newValue: T) {\n const oldValue = wrapper._value\n if (Object.is(oldValue, newValue)) return\n wrapper._value = newValue\n trigger(wrapper, '_value')\n if (subscribers.size === 0) return\n if (batchDepth > 0) {\n batchedFrom ??= { value: oldValue }\n queue.add(flush)\n } else {\n notify(newValue, oldValue)\n }\n },\n subscribe(fn: (newValue: T, oldValue: T) => void): () => void {\n subscribers.add(fn)\n return () => subscribers.delete(fn)\n },\n toJSON(): T {\n return wrapper._value\n },\n } as Ref<T>\n}\n\n// ── computed() ───────────────────────────────────────────────────────────\n\n/**\n * A read-only value made by `computed()`, recomputed when its sources change.\n *\n * @see https://kickjs.app/guide/reactivity\n */\nexport interface ComputedRef<T = any> {\n readonly value: T\n /**\n * Auto-unwrap on `JSON.stringify` — see {@link Ref.toJSON} for the\n * motivation. Triggers a recompute when the cached value is stale,\n * same as reading `.value`.\n */\n toJSON(): T\n /**\n * Unsubscribe this computed from its reactive sources. Call when the\n * computed's lifetime is shorter than its sources' (e.g. created\n * per-request/per-tenant against app-lifetime refs) — without it the\n * internal effect stays pinned in the sources' dep Sets forever.\n * After disposal, reading `.value` still works but recomputes on every\n * access and no longer tracks.\n */\n dispose(): void\n}\n\n/**\n * Create a computed value that auto-recalculates when its reactive\n * dependencies change. Cached until a dependency triggers.\n * @example\n * ```ts\n * const count = ref(0)\n * const doubled = computed(() => count.value * 2)\n * count.value = 5\n * console.log(doubled.value) // 10\n * ```\n */\nexport function computed<T>(getter: () => T): ComputedRef<T> {\n let cached: T\n let dirty = true\n let disposed = false\n const wrapper = { _value: undefined as T }\n\n const effect = createEffect(() => {\n dirty = true\n trigger(wrapper, '_value')\n }, true)\n\n const recompute = (): T => {\n // Disposed: plain evaluation with tracking SUSPENDED — neither this\n // computed's effect nor any OUTER active effect (a watcher reading\n // `.value`) may attach to the sources through a disposed computed;\n // otherwise disposal wouldn't actually sever the subscription chain.\n if (disposed) return untracked(getter)\n if (dirty) {\n cached = runTracked(effect, getter)\n wrapper._value = cached\n dirty = false\n }\n return cached\n }\n\n return {\n [REF]: true,\n get value(): T {\n track(wrapper, '_value')\n return recompute()\n },\n dispose(): void {\n disposed = true\n cleanupEffect(effect)\n },\n /**\n * Auto-unwrap on `JSON.stringify`, matching {@link ref}'s behavior\n * so adopters can drop a computed straight into a JSON-bound\n * payload (introspect snapshot, devtools state) and get the value\n * rather than the wrapper shape.\n *\n * Computed values cache through the same dirty-flag the getter\n * uses, so calling `toJSON` is at worst one recompute when stale —\n * identical cost to reading `.value`.\n */\n toJSON(): T {\n return recompute()\n },\n } as ComputedRef<T>\n}\n\n// ── watch() ──────────────────────────────────────────────────────────────\n\n/** Options for `watch()`. */\nexport interface WatchOptions {\n /** Run the callback immediately with the current value (default: false) */\n immediate?: boolean\n}\n\ntype WatchSource<T> = Ref<T> | ComputedRef<T> | (() => T)\n\n/**\n * Watch a reactive source and run a callback when it changes.\n * Returns a stop function to unsubscribe.\n *\n * A callback that throws is reported (logged, and passed to `onError`\n * observers) instead of thrown: the write that triggered it, and every other\n * watcher, carry on. Inside {@link batch}, the callback runs once, after the\n * batch.\n *\n * @example\n * ```ts\n * const count = ref(0)\n * const stop = watch(count, (newVal, oldVal) => {\n * console.log(`Changed from ${oldVal} to ${newVal}`)\n * })\n * count.value = 1 // logs: \"Changed from 0 to 1\"\n * stop() // no more callbacks\n * ```\n */\nexport function watch<T>(\n source: WatchSource<T>,\n callback: (newValue: T, oldValue: T) => void,\n options?: WatchOptions,\n): () => void {\n let oldValue: T\n let stopped = false\n\n const getter = typeof source === 'function' ? source : () => source.value\n\n const job = createEffect(() => {\n if (stopped) return\n // Re-run the getter UNDER tracking so deps are refreshed each run —\n // a conditional getter (`cond ? a.value : b.value`) drops the branch\n // it no longer reads instead of staying subscribed to it forever.\n const newValue = runTracked(job, getter)\n if (!Object.is(newValue, oldValue)) {\n const previous = oldValue\n // Advanced before the callback, so one that throws isn't re-called\n // with the same change on the next run.\n oldValue = newValue\n callback(newValue, previous)\n }\n })\n\n // Initial run to establish tracking\n oldValue = runTracked(job, getter)\n\n if (options?.immediate) {\n // Reported like any other run: watch() still returns its stop function.\n try {\n callback(oldValue, undefined as T)\n } catch (err) {\n report(err)\n }\n }\n\n return () => {\n // Detach from every dep Set — a flag alone would leave the dead effect\n // referenced (and invoked) by its sources for their entire lifetime.\n stopped = true\n queue.delete(job)\n cleanupEffect(job)\n }\n}\n\n// ── reactive() ───────────────────────────────────────────────────────────\n\n// Memoize proxies per target: repeated reads of the same nested object must\n// return the SAME proxy — otherwise every access allocates a fresh Proxy and\n// referential identity breaks (`state.nested !== state.nested`).\nconst proxyCache = new WeakMap<object, any>()\n/** Proxies this module made — `reactive(proxy)` returns it rather than wrapping it again. */\nconst proxies = new WeakSet<object>()\n\n/** Array methods that change the array: run untracked and as one update. */\nconst ARRAY_MUTATORS = new Set([\n 'push',\n 'pop',\n 'shift',\n 'unshift',\n 'splice',\n 'sort',\n 'reverse',\n 'fill',\n 'copyWithin',\n])\n\n/**\n * Create a deeply reactive proxy around an object or array. Property reads\n * are tracked, writes and deletes trigger watchers and computed\n * recalculations, and so do key additions and removals for code that\n * iterates the keys (`Object.keys`, `for…in`, `in`). Nested objects and\n * arrays are reactive too.\n * @example\n * ```ts\n * const state = reactive({ users: 0, errors: 0 })\n * const errorRate = computed(() =>\n * state.users > 0 ? state.errors / state.users : 0\n * )\n * state.users = 100\n * state.errors = 5\n * console.log(errorRate.value) // 0.05\n * ```\n *\n * @see https://kickjs.app/guide/reactivity\n */\nexport function reactive<T extends object>(target: T): T {\n if (proxies.has(target)) return target\n const existing = proxyCache.get(target)\n if (existing) return existing as T\n const isArray = Array.isArray(target)\n // What iterating this target depends on: an array's length, an object's key set.\n const iterateKey = isArray ? 'length' : ITERATE_KEY\n const proxy: T = new Proxy(target, {\n get(obj, key, receiver) {\n if (isArray && typeof key === 'string' && ARRAY_MUTATORS.has(key)) {\n const method = Reflect.get(obj, key, receiver) as (...args: unknown[]) => unknown\n return (...args: unknown[]) => batch(() => untracked(() => method.apply(proxy, args)))\n }\n const value = Reflect.get(obj, key, receiver)\n if (typeof key === 'symbol') return value\n track(obj, key)\n // Deep reactivity for nested objects and arrays\n if (value !== null && typeof value === 'object') return reactive(value)\n return value\n },\n set(obj, key, value, receiver) {\n const hadKey =\n isArray && typeof key === 'string' && /^\\d+$/.test(key)\n ? Number(key) < (obj as unknown[]).length\n : Object.hasOwn(obj, key)\n const oldValue = Reflect.get(obj, key, receiver)\n const result = Reflect.set(obj, key, value, receiver)\n if (typeof key === 'symbol') return result\n if (!hadKey) {\n batch(() => {\n trigger(obj, key)\n // A new array index grows the array, but its `length` write that\n // follows sees the length already updated — so it's triggered here.\n trigger(obj, iterateKey)\n })\n } else if (!Object.is(oldValue, value)) {\n trigger(obj, key)\n }\n return result\n },\n deleteProperty(obj, key) {\n const hadKey = Object.hasOwn(obj, key)\n const result = Reflect.deleteProperty(obj, key)\n if (result && hadKey && typeof key !== 'symbol') {\n batch(() => {\n trigger(obj, key)\n trigger(obj, iterateKey)\n })\n }\n return result\n },\n has(obj, key) {\n if (typeof key !== 'symbol') track(obj, key)\n return Reflect.has(obj, key)\n },\n ownKeys(obj) {\n track(obj, iterateKey)\n return Reflect.ownKeys(obj)\n },\n })\n proxyCache.set(target, proxy)\n proxies.add(proxy)\n return proxy\n}\n\n// ── Utility ──────────────────────────────────────────────────────────────\n\n/** Check if a value is a ref — from {@link ref}, {@link computed} or {@link toRef}. */\nexport function isRef<T = any>(value: unknown): value is Ref<T> | ComputedRef<T> {\n return value !== null && typeof value === 'object' && (value as any)[REF] === true\n}\n\n/** Unwrap a ref or computed ref, or return the value as-is */\nexport function unref<T>(value: Ref<T> | ComputedRef<T> | T): T {\n return isRef(value) ? (value.value as T) : (value as T)\n}\n\n/**\n * A ref that reads and writes `obj[key]`: a live view, not a copy. On a\n * {@link reactive} object, watching it follows changes made either way.\n */\nexport function toRef<T extends object, K extends keyof T>(obj: T, key: K): Ref<T[K]> {\n return {\n [REF]: true,\n get value(): T[K] {\n return obj[key]\n },\n set value(value: T[K]) {\n obj[key] = value\n },\n subscribe(fn: (newValue: T[K], oldValue: T[K]) => void): () => void {\n return watch(() => obj[key], fn)\n },\n toJSON(): T[K] {\n return obj[key]\n },\n } as Ref<T[K]>\n}\n\n/** {@link toRef} for every property: live views onto the object, not copies. */\nexport function toRefs<T extends object>(obj: T): { [K in keyof T]: Ref<T[K]> } {\n const result = {} as { [K in keyof T]: Ref<T[K]> }\n for (const key of Object.keys(obj) as Array<keyof T>) {\n result[key] = toRef(obj, key)\n }\n return result\n}\n"],"mappings":";;;;;;;;;;A,+FA4BA,IAAI,aAA8B,KAClC,MAAM,0BAAY,IAAI,QAGhB,YAAc,OAAO,SAAS,EAEpC,SAAS,aAAa,GAAgB,SAAW,GAAe,CAC9D,IAAM,OAAS,GAGf,MAFA,QAAO,qBAAO,IAAI,IACd,WAAU,OAAO,SAAW,IACzB,MACT,CAGA,SAAS,cAAc,OAAsB,CAC3C,IAAK,IAAM,UAAU,OAAO,KAAM,OAAO,OAAO,MAAM,EACtD,OAAO,KAAK,MAAM,CACpB,CA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O,KAAQ,UACrC,UAAY,CACV,QAAQ,IAAK,GAAG,EAChB,QAAQ,IAAK,UAAU,CACzB,CAAC,EAEI,MACT,EACA,IAAI,IAAK,IAAK,CAEZ,OADI,OAAO,KAAQ,UAAU,MAAM,IAAK,GAAG,EACpC,QAAQ,IAAI,IAAK,GAAG,CAC7B,EACA,QAAQ,IAAK,CAEX,OADA,MAAM,IAAK,UAAU,EACd,QAAQ,QAAQ,GAAG,CAC5B,CACF,CAAC,EAGD,OAFA,WAAW,IAAI,OAAQ,KAAK,EAC5B,QAAQ,IAAI,KAAK,EACV,KACT,CAKA,SAAgB,MAAe,MAAkD,CAC/E,OAAyB,OAAO,OAAU,YAAnC,OAAgD,MAAc,OAAS,EAChF,CAGA,SAAgB,MAAS,MAAuC,CAC9D,OAAO,MAAM,KAAK,EAAK,MAAM,MAAe,KAC9C,CAMA,SAAgB,MAA2C,IAAQ,IAAmB,CACpF,MAAO,EACJ,KAAM,GACP,IAAI,OAAc,CAChB,OAAO,IAAI,IACb,EACA,IAAI,MAAM,MAAa,CACrB,IAAI,KAAO,KACb,EACA,UAAU,GAA0D,CAClE,OAAO,UAAY,IAAI,KAAM,EAAE,CACjC,EACA,QAAe,CACb,OAAO,IAAI,IACb,CACF,CACF,CAGA,SAAgB,OAAyB,IAAuC,CAC9E,IAAM,OAAS,CAAC,EAChB,IAAK,IAAM,OAAO,OAAO,KAAK,GAAG,EAC/B,OAAO,KAAO,MAAM,IAAK,GAAG,EAE9B,OAAO,MACT,C"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @forinda/kickjs v10.15.0
|
|
3
|
+
*
|
|
4
|
+
* Copyright (c) Felix Orinda
|
|
5
|
+
*
|
|
6
|
+
* This source code is licensed under the MIT license found in the
|
|
7
|
+
* LICENSE file in the root directory of this source tree.
|
|
8
|
+
*
|
|
9
|
+
* @license MIT
|
|
10
|
+
*/
|
|
11
|
+
import{n as __require}from"./rolldown-runtime-B5KeNctS.mjs";import"./core/container.mjs";import{n as createToken}from"./token-uWfhVlfe.mjs";import{METADATA}from"./core/interfaces.mjs";import"./core/decorators.mjs";import"./core/cron.mjs";import"./jobs-D7ToA0yF.mjs";import"./core/cache.mjs";import"./core/logger.mjs";import"./disposables-BC291ukb.mjs";import{c as pushClassMeta,l as pushMethodMeta}from"./metadata-nTTSnVTO.mjs";import"./core/reactivity.mjs";import{n as assertFlagTest}from"./route-flag-B6ZmhkfI.mjs";import"./contributor-runner-BnJzu2GI.mjs";import{t as isProduction}from"./is-production-LziEMGrc.mjs";import{c as _setAssetResolver}from"./di-hooks-DTDy7ABs.mjs";import"reflect-metadata";import{existsSync,readFileSync,readdirSync}from"node:fs";import{isAbsolute,join,resolve,sep}from"node:path";function defineContextDecoratorImpl(spec){if(typeof spec!=`object`||!spec)throw TypeError(`defineContextDecorator: spec must be an object literal. See https://kickjs.app/guide/context-decorators for the spec shape.`);if(typeof spec.key!=`string`||spec.key.length===0){let got=typeof spec.key==`string`?`""`:typeof spec.key;throw TypeError(`defineContextDecorator: spec.key must be a non-empty string (got ${got}). Pick a name that matches a key declared on \`ContextMeta\` (or one of the framework keys).`)}if(typeof spec.resolve!=`function`)throw TypeError(`defineContextDecorator(${spec.key}): spec.resolve is required and must be a function (got ${typeof spec.resolve}). Each contributor needs a resolver that produces the value to write into ctx.set(${JSON.stringify(spec.key)}, …).`);if(spec.onError!==void 0&&typeof spec.onError!=`function`)throw TypeError(`defineContextDecorator(${spec.key}): spec.onError must be a function when provided (got ${typeof spec.onError}).`);if(spec.dependsOn!==void 0&&!Array.isArray(spec.dependsOn))throw TypeError(`defineContextDecorator(${spec.key}): spec.dependsOn must be an array when provided (got ${typeof spec.dependsOn}).`);if(spec.requiredParams!==void 0&&!Array.isArray(spec.requiredParams))throw TypeError(`defineContextDecorator(${spec.key}): spec.requiredParams must be an array when provided (got ${typeof spec.requiredParams}).`);if(Array.isArray(spec.requiredParams)&&spec.requiredParams.some(p=>typeof p!=`string`||p.length===0))throw TypeError(`defineContextDecorator(${spec.key}): spec.requiredParams entries must be non-empty strings.`);if(Array.isArray(spec.dependsOn)&&spec.dependsOn.some(dep=>typeof dep!=`string`||dep.length===0))throw TypeError(`defineContextDecorator(${spec.key}): spec.dependsOn entries must be non-empty strings.`);let definedAt=(/* @__PURE__ */ Error()).stack,defaults=Object.freeze({...spec.paramDefaults??{}}),sharedDeps=Object.freeze({...spec.deps??{}}),sharedDependsOn=Object.freeze([...spec.dependsOn??[]]),sharedOptional=spec.optional??!1,buildRegistration=params=>{let frozenParams=Object.freeze({...params}),onError=spec.onError?(err,ctx)=>spec.onError(err,ctx,frozenParams):void 0;return spec.skipWhen!==void 0&&assertFlagTest(spec.skipWhen,`contributor '${spec.key}' skipWhen`),spec.onlyWhen!==void 0&&assertFlagTest(spec.onlyWhen,`contributor '${spec.key}' onlyWhen`),Object.freeze({key:spec.key,deps:sharedDeps,dependsOn:sharedDependsOn,optional:sharedOptional,skipWhen:spec.skipWhen,onlyWhen:spec.onlyWhen,beforeValidation:spec.beforeValidation===!0,onError,resolve:(ctx,deps)=>spec.resolve(ctx,deps,frozenParams),definedAt})},defaultRegistration=buildRegistration({...defaults}),isDecoratorCall=args=>args.length===0?!1:args.length>=2||typeof args[0]==`function`,applyAsDecorator=(registration,target,propertyKey)=>{if(propertyKey===void 0)pushClassMeta(METADATA.CLASS_CONTRIBUTORS,target,registration);else{let constructor=target.constructor;pushMethodMeta(METADATA.METHOD_CONTRIBUTORS,constructor,String(propertyKey),registration)}},isPlainObject=value=>{let proto=Object.getPrototypeOf(value);return proto===Object.prototype||proto===null},mergeParams=override=>{if(override===void 0)return{...defaults};if(typeof override!=`object`||!override||Array.isArray(override)||!isPlainObject(override)){let got=override===null?`null`:Array.isArray(override)?`array`:typeof override==`object`?`instance of ${override.constructor?.name??`unknown class`}`:typeof override;throw TypeError(`defineContextDecorator(${spec.key}): factory call requires a plain object literal, got ${got}. Class instances and built-ins (Map, Date, etc) silently spread to empty objects — call the decorator with a spread object literal instead, e.g. \`MyDecorator({ ...someInstance })\`.`)}return{...defaults,...override}},sharedRequiredParams=Object.freeze([...spec.requiredParams??[]]),assertRequiredParams=(params,usage)=>{if(sharedRequiredParams.length===0)return;let missing=sharedRequiredParams.filter(name=>params[name]===void 0);if(missing.length!==0)throw TypeError(`defineContextDecorator(${spec.key}): ${usage} is missing required param(s) ${missing.map(m=>`'${m}'`).join(`, `)}. Supply them at the call site — e.g. \`@${spec.key}({ ${missing[0]}: … })\` — or add a default in \`paramDefaults\` if one is genuinely correct for every route.`)};function decoratorOrFactory(...args){if(isDecoratorCall(args)){let[target,propertyKey]=args;assertRequiredParams({...defaults},"bare `@decorator` usage"),applyAsDecorator(defaultRegistration,target,propertyKey);return}let params=mergeParams(args[0]);assertRequiredParams(params,`factory call`);let registration=buildRegistration(params);return(target,propertyKey)=>{applyAsDecorator(registration,target,propertyKey)}}Object.defineProperty(decoratorOrFactory,"name",{value:`ContextDecorator(${spec.key})`,writable:!1,enumerable:!1,configurable:!0});let decorator=Object.assign(decoratorOrFactory,{with:params=>{let merged=mergeParams(params);return assertRequiredParams(merged,"`.with()`"),{registration:buildRegistration(merged)}}});return Object.defineProperty(decorator,"registration",{get(){return assertRequiredParams({...defaults},"`.registration`"),defaultRegistration},enumerable:!0,configurable:!1}),Object.freeze(decorator)}const defineContextDecorator=Object.freeze(Object.assign(defineContextDecoratorImpl,{withParams:()=>spec=>defineContextDecoratorImpl(spec)}));function groupAssetKeys(namespace,paths,opts={}){let strategy=opts.strategy??`auto`;if(strategy===`with-extension`)return{pairs:paths.map(rel=>({rel,key:`${namespace}/${rel}`})),collisionGroupsResolved:0};if(strategy===`strip`)return{pairs:paths.map(rel=>({rel,key:`${namespace}/${stripExt(rel)}`})),collisionGroupsResolved:0};let groups=/* @__PURE__ */ new Map;for(let rel of paths){let strippedKey=`${namespace}/${stripExt(rel)}`,arr=groups.get(strippedKey);arr?arr.push(rel):groups.set(strippedKey,[rel])}let collisionGroupsResolved=0,keyByRel=/* @__PURE__ */ new Map;for(let[strippedKey,rels]of groups)if(rels.length===1)keyByRel.set(rels[0],strippedKey);else{collisionGroupsResolved+=1;for(let rel of rels)keyByRel.set(rel,`${namespace}/${rel}`)}return{pairs:paths.map(rel=>({rel,key:keyByRel.get(rel)??`${namespace}/${rel}`})),collisionGroupsResolved}}function stripExt(path){let lastSlash=path.lastIndexOf(`/`),filename=lastSlash>=0?path.slice(lastSlash+1):path,lastDot=filename.lastIndexOf(`.`);return lastDot<=0?path:(lastSlash>=0?path.slice(0,lastSlash+1):``)+filename.slice(0,lastDot)}const ASSET_MANIFEST_VERSION=1,ASSETS=createToken(`kick/assets/Map`);var UnknownAssetError=class extends Error{namespace;key;constructor(namespace,key){super(`Unknown asset '${namespace}/${key}'. Make sure the namespace exists in kick.config.ts assetMap and that the file is present in the source directory.`),this.name=`UnknownAssetError`,this.namespace=namespace,this.key=key}};let manifestCache;function toPosixPath(p){return p.replaceAll(`\\`,`/`)}function resolveAsset(namespace,key){let resolved=loadManifest();if(!resolved)throw new UnknownAssetError(namespace,key);let entry=resolved.manifest.entries[`${namespace}/${key}`];if(!entry)throw new UnknownAssetError(namespace,key);return toPosixPath(isAbsolute(entry)?entry:resolve(resolved.root,entry))}function clearAssetCache(){manifestCache=void 0}function loadManifest(){return isProduction()?(manifestCache===void 0&&(manifestCache=discoverManifest()),manifestCache):discoverManifest()}function discoverManifest(){let envRoot=process.env.KICK_ASSETS_ROOT;if(envRoot){let fromEnv=readBuiltManifest(envRoot);if(fromEnv)return fromEnv}let cwd=process.cwd(),config=loadConfigSync(cwd);if(!isProduction()){let fresh=synthesiseDevManifest(cwd,config);if(fresh)return fresh}let configOutDir=config?.build?.outDir;if(configOutDir&&!STANDARD_OUT_DIRS.includes(configOutDir)){let found=readBuiltManifest(resolve(cwd,configOutDir));if(found)return found}for(let candidate of STANDARD_OUT_DIRS){let found=readBuiltManifest(join(cwd,candidate));if(found)return found}return synthesiseDevManifest(cwd,config)}const STANDARD_OUT_DIRS=[`dist`,`build`,`out`];function readBuiltManifest(dir){let path=join(dir,`.kickjs-assets.json`);if(!existsSync(path))return null;try{let raw=readFileSync(path,`utf-8`),parsed=JSON.parse(raw);return parsed.version!==1||!parsed.entries||typeof parsed.entries!=`object`?null:{manifest:parsed,root:resolve(dir)}}catch{return null}}function synthesiseDevManifest(cwd,preloadedConfig){let config=preloadedConfig===void 0?loadConfigSync(cwd):preloadedConfig;if(!config?.assetMap)return null;let entries={};for(let[namespace,entry]of Object.entries(config.assetMap)){if(!entry||typeof entry.src!=`string`)continue;let srcAbs=resolve(cwd,entry.src);if(!existsSync(srcAbs))continue;let collected=[];walkSync(srcAbs,srcAbs,(relPath,absPath)=>{(!entry.glob||matchesGlobLite(relPath,entry.glob,namespace))&&collected.push({rel:relPath,abs:absPath})}),collected.sort((a,b)=>a.rel.localeCompare(b.rel));let{pairs,collisionGroupsResolved}=groupAssetKeys(namespace,collected.map(c=>c.rel),{strategy:entry.keys??`auto`}),absByRel=new Map(collected.map(c=>[c.rel,c.abs]));for(let{rel,key}of pairs){let abs=absByRel.get(rel);abs&&(entries[key]=abs)}collisionGroupsResolved>0&&!isProduction()&&console.log(`[kickjs/assets] '${namespace}': ${collisionGroupsResolved} basename collision(s) auto-resolved by keeping extensions (set assetMap.${namespace}.keys to 'strip' or 'with-extension' to override).`)}return{manifest:{version:1,entries},root:cwd}}const warnedGlobs=/* @__PURE__ */ new Set;function matchesGlobLite(relPath,pattern,namespace){if(pattern===`**/*`||pattern===`**`)return!0;let singleExt=/^\*\*\/\*\.(\w+)$/.exec(pattern);if(singleExt)return relPath.endsWith(`.${singleExt[1]}`);let braceExt=/^\*\*\/\*\.\{([^}]+)\}$/.exec(pattern);if(braceExt)return braceExt[1].split(`,`).map(e=>e.trim()).some(ext=>relPath.endsWith(`.${ext}`));let tag=`${namespace}::${pattern}`;return warnedGlobs.has(tag)||(warnedGlobs.add(tag),console.warn(`[kickjs/assets] Dev-mode glob '${pattern}' on '${namespace}' isn't recognised by the lite matcher. Falling back to '**/*'. Run 'kick build:assets' to use the full glob engine.`)),!0}function walkSync(root,dir,onFile){let entries;try{entries=readdirSync(dir,{withFileTypes:!0})}catch{return}for(let entry of entries){if(entry.name===`node_modules`||entry.name.startsWith(`.`))continue;let full=join(dir,entry.name);entry.isDirectory()?walkSync(root,full,onFile):entry.isFile()&&onFile(full.slice(root.length+1).split(sep).join(`/`),full)}}function loadConfigSync(cwd){let jsonPath=join(cwd,`kick.config.json`);if(existsSync(jsonPath))try{return JSON.parse(readFileSync(jsonPath,`utf-8`))}catch{return null}for(let filename of[`kick.config.cjs`,`kick.config.js`]){let path=join(cwd,filename);if(existsSync(path))try{let{createRequire}=__require(`node:module`),mod=createRequire(join(cwd,`package.json`))(path);return mod.default??mod??null}catch{continue}}let snapshotPath=join(cwd,`.kickjs`,`kick.config.json`);if(existsSync(snapshotPath))try{return JSON.parse(readFileSync(snapshotPath,`utf-8`))}catch{return null}return null}const PROMISE_DETECTION_KEYS=/* @__PURE__ */ new Set([`then`]),PASSTHROUGH_KEYS=/* @__PURE__ */ new Set([`toString`,`valueOf`,`constructor`,`prototype`,`name`,`length`,`asymmetricMatch`,`nodeType`,Symbol.toPrimitive,Symbol.toStringTag,Symbol.iterator,Symbol.asyncIterator]);function createNamespaceProxy(parts){return new Proxy(function(){},{apply(){if(parts.length<2)throw new UnknownAssetError(parts[0]??``,``);let[namespace,...rest]=parts;return resolveAsset(namespace,rest.join(`/`))},get(t,prop){if(!PROMISE_DETECTION_KEYS.has(prop)){if(PASSTHROUGH_KEYS.has(prop))return Reflect.get(t,prop);if(typeof prop!=`symbol`)return createNamespaceProxy([...parts,prop])}}})}function createAssetProxy(){return new Proxy({},{get(t,prop){if(!PROMISE_DETECTION_KEYS.has(prop)){if(PASSTHROUGH_KEYS.has(prop))return Reflect.get(t,prop);if(typeof prop!=`symbol`)return createNamespaceProxy([prop])}}})}const assets=createAssetProxy();function useAssets(){return assets}_setAssetResolver(resolveAsset);export{clearAssetCache as a,groupAssetKeys as c,assets as i,stripExt as l,ASSET_MANIFEST_VERSION as n,resolveAsset as o,UnknownAssetError as r,useAssets as s,ASSETS as t,defineContextDecorator as u};
|
|
12
|
+
//# sourceMappingURL=core-Dqzah_BX.mjs.map
|