@timber-js/app 0.2.0-alpha.221 → 0.2.0-alpha.223
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/agent-skill.md +21 -5
- package/dist/_chunks/{actions-BDqn4Oxj.js → actions-7dTXYJfu.js} +53 -24
- package/dist/_chunks/actions-7dTXYJfu.js.map +1 -0
- package/dist/_chunks/{als-registry-BZqHCtq-.js → als-registry-DpygwCp0.js} +2 -3
- package/dist/_chunks/{als-registry-BZqHCtq-.js.map → als-registry-DpygwCp0.js.map} +1 -1
- package/dist/_chunks/{als-slots-BEEIPKYm.js → als-slots-kbQrHTzm.js} +2 -3
- package/dist/_chunks/{als-slots-BEEIPKYm.js.map → als-slots-kbQrHTzm.js.map} +1 -1
- package/dist/_chunks/{base-path-DaQrzbez.js → base-path-DDIx0FXe.js} +2 -3
- package/dist/_chunks/{base-path-DaQrzbez.js.map → base-path-DDIx0FXe.js.map} +1 -1
- package/dist/_chunks/{build-manifest-DWppEdLB.js → build-manifest-Y4jl7nwU.js} +2 -3
- package/dist/_chunks/{build-manifest-DWppEdLB.js.map → build-manifest-Y4jl7nwU.js.map} +1 -1
- package/dist/_chunks/{build-output-helper-RV_BRcF1.js → build-output-helper-B7wWGTfR.js} +14 -10
- package/dist/_chunks/build-output-helper-B7wWGTfR.js.map +1 -0
- package/dist/_chunks/{cache-api-GE4AOe2H.js → cache-api-TDZ4hlDc.js} +237 -37
- package/dist/_chunks/cache-api-TDZ4hlDc.js.map +1 -0
- package/dist/_chunks/{canonicalize-BAWkWiKK.js → canonicalize-CqK135BN.js} +29 -4
- package/dist/_chunks/{canonicalize-BAWkWiKK.js.map → canonicalize-CqK135BN.js.map} +1 -1
- package/dist/_chunks/chains-CwOr3Myj.js +1 -0
- package/dist/_chunks/{chains-e_Buf9vg.js → chains-Dgm3PrMe.js} +3 -4
- package/dist/_chunks/{chains-e_Buf9vg.js.map → chains-Dgm3PrMe.js.map} +1 -1
- package/dist/_chunks/{classify-2Yp3xJY1.js → classify--_kINHQV.js} +4 -5
- package/dist/_chunks/{classify-2Yp3xJY1.js.map → classify--_kINHQV.js.map} +1 -1
- package/dist/_chunks/{cli-check-DDwCkeDY.js → cli-check-Dv3f8d2j.js} +5 -6
- package/dist/_chunks/{cli-check-DDwCkeDY.js.map → cli-check-Dv3f8d2j.js.map} +1 -1
- package/dist/_chunks/{cli-context-_mPttGGY.js → cli-context-CbZp32SK.js} +3 -4
- package/dist/_chunks/{cli-context-_mPttGGY.js.map → cli-context-CbZp32SK.js.map} +1 -1
- package/dist/_chunks/cli-context-n5hmkdla.js +1 -0
- package/dist/_chunks/cli-dev-status-prPMLU8G.js +138 -0
- package/dist/_chunks/cli-dev-status-prPMLU8G.js.map +1 -0
- package/dist/_chunks/cli-init-BoXOYYil.js +196 -0
- package/dist/_chunks/cli-init-BoXOYYil.js.map +1 -0
- package/dist/_chunks/{cli-schema-sync-BdIebmk3.js → cli-schema-sync-DIPurq7X.js} +4 -5
- package/dist/_chunks/{cli-schema-sync-BdIebmk3.js.map → cli-schema-sync-DIPurq7X.js.map} +1 -1
- package/dist/_chunks/{cli-schema-sync-CLNfXQDK.js → cli-schema-sync-uq72EZmD.js} +1 -1
- package/dist/_chunks/{client-dep-entries-BOkpKjj1.js → client-dep-entries-CP7AkMCM.js} +4 -5
- package/dist/_chunks/{client-dep-entries-BOkpKjj1.js.map → client-dep-entries-CP7AkMCM.js.map} +1 -1
- package/dist/_chunks/{cloudflare-Byxl8FWP.js → cloudflare-B75X6u4O.js} +10 -13
- package/dist/_chunks/{cloudflare-Byxl8FWP.js.map → cloudflare-B75X6u4O.js.map} +1 -1
- package/dist/_chunks/{codec-registry-oOUxugz3.js → codec-registry-CPc6bjVl.js} +2 -3
- package/dist/_chunks/{codec-registry-oOUxugz3.js.map → codec-registry-CPc6bjVl.js.map} +1 -1
- package/dist/_chunks/{codegen-Bps1sLKJ.js → codegen-B9oWkWGf.js} +5 -8
- package/dist/_chunks/{codegen-Bps1sLKJ.js.map → codegen-B9oWkWGf.js.map} +1 -1
- package/dist/_chunks/{convention-lint-ByKJ6aqD.js → convention-lint-hZwz5wd4.js} +8 -11
- package/dist/_chunks/{convention-lint-ByKJ6aqD.js.map → convention-lint-hZwz5wd4.js.map} +1 -1
- package/dist/_chunks/dev-discovery-YnabkCKD.js +238 -0
- package/dist/_chunks/dev-discovery-YnabkCKD.js.map +1 -0
- package/dist/_chunks/{dev-server-DIy-SY-J.js → dev-server-C61GWpGg.js} +409 -51
- package/dist/_chunks/dev-server-C61GWpGg.js.map +1 -0
- package/dist/_chunks/dev-server-CBvvM7Lr.js +1 -0
- package/dist/_chunks/{dev-store-BOa304m_.js → dev-store-BvdqtHvK.js} +82 -38
- package/dist/_chunks/dev-store-BvdqtHvK.js.map +1 -0
- package/dist/_chunks/{dist-DtrJyBbw.js → dist-C1Rjlo6s.js} +3 -5
- package/dist/_chunks/{dist-DtrJyBbw.js.map → dist-C1Rjlo6s.js.map} +1 -1
- package/dist/_chunks/{error-boundary-Bc8QPZuq.js → error-boundary-DRQXGWCp.js} +20 -27
- package/dist/_chunks/{error-boundary-Bc8QPZuq.js.map → error-boundary-DRQXGWCp.js.map} +1 -1
- package/dist/_chunks/{fast-hash-C-tVYrLb.js → fast-hash-DddxkU5Y.js} +2 -3
- package/dist/_chunks/{fast-hash-C-tVYrLb.js.map → fast-hash-DddxkU5Y.js.map} +1 -1
- package/dist/_chunks/{flight-source-node-HptmGMT8.js → flight-source-node-0Tp6evlz.js} +6 -8
- package/dist/_chunks/flight-source-node-0Tp6evlz.js.map +1 -0
- package/dist/_chunks/{format-BKclgVbk.js → format-DuPOoXUP.js} +2 -3
- package/dist/_chunks/{format-BKclgVbk.js.map → format-DuPOoXUP.js.map} +1 -1
- package/dist/_chunks/{fs-identity-BRKuL215.js → fs-identity-BmQ_Agg-.js} +3 -5
- package/dist/_chunks/{fs-identity-BRKuL215.js.map → fs-identity-BmQ_Agg-.js.map} +1 -1
- package/dist/_chunks/global-context-DbxNWeBP.js +47 -0
- package/dist/_chunks/global-context-DbxNWeBP.js.map +1 -0
- package/dist/_chunks/{graph-cache-CYiUS2aS.js → graph-cache-B1LAg4t7.js} +5 -89
- package/dist/_chunks/graph-cache-B1LAg4t7.js.map +1 -0
- package/dist/_chunks/{href-validation-BIrxavIy.js → href-validation-CEZy1V-k.js} +4 -7
- package/dist/_chunks/{href-validation-BIrxavIy.js.map → href-validation-CEZy1V-k.js.map} +1 -1
- package/dist/_chunks/{json-lossy-check-C8zBY2uZ.js → json-lossy-check-DVkLUlfC.js} +3 -4
- package/dist/_chunks/{json-lossy-check-C8zBY2uZ.js.map → json-lossy-check-DVkLUlfC.js.map} +1 -1
- package/dist/_chunks/{live-graph-tSWrv8eH.js → live-graph-BcVjQ1Te.js} +6 -7
- package/dist/_chunks/{live-graph-tSWrv8eH.js.map → live-graph-BcVjQ1Te.js.map} +1 -1
- package/dist/_chunks/{logger-CbLdcy-W.js → logger-CWk44DLp.js} +97 -47
- package/dist/_chunks/logger-CWk44DLp.js.map +1 -0
- package/dist/_chunks/{metadata-routes-B3XJNyIH.js → metadata-routes-BL26HCDd.js} +2 -3
- package/dist/_chunks/{metadata-routes-B3XJNyIH.js.map → metadata-routes-BL26HCDd.js.map} +1 -1
- package/dist/_chunks/{navigation-root-BQfo1-kG.js → navigation-root-M3B2ZrdO.js} +6 -10
- package/dist/_chunks/{navigation-root-BQfo1-kG.js.map → navigation-root-M3B2ZrdO.js.map} +1 -1
- package/dist/_chunks/{node-response-rkQqcFGq.js → node-response-B9aviPDa.js} +43 -9
- package/dist/_chunks/node-response-B9aviPDa.js.map +1 -0
- package/dist/_chunks/{param-value-C8TNYchQ.js → param-value-DqlGfF57.js} +2 -3
- package/dist/_chunks/{param-value-C8TNYchQ.js.map → param-value-DqlGfF57.js.map} +1 -1
- package/dist/_chunks/{plugin-context-uDHFqHHJ.js → plugin-context-BfSRKJfz.js} +1 -1
- package/dist/_chunks/{plugin-context-DxMMvjUt.js → plugin-context-FCkaNLUB.js} +4 -6
- package/dist/_chunks/plugin-context-FCkaNLUB.js.map +1 -0
- package/dist/_chunks/{poison-rules-DoEhbqaY.js → poison-rules-Bmz-lCPi.js} +2 -3
- package/dist/_chunks/{poison-rules-DoEhbqaY.js.map → poison-rules-Bmz-lCPi.js.map} +1 -1
- package/dist/_chunks/{poison-scan-C4FgMxFl.js → poison-scan-DJYxZc_7.js} +4 -5
- package/dist/_chunks/{poison-scan-C4FgMxFl.js.map → poison-scan-DJYxZc_7.js.map} +1 -1
- package/dist/_chunks/{purge-store-WZaxu-3m.js → purge-store-8BqLAYZ1.js} +2 -3
- package/dist/_chunks/{purge-store-WZaxu-3m.js.map → purge-store-8BqLAYZ1.js.map} +1 -1
- package/dist/_chunks/{render-timeout-joFhz4KH.js → render-timeout-MrrqD1wd.js} +20 -4
- package/dist/_chunks/{render-timeout-joFhz4KH.js.map → render-timeout-MrrqD1wd.js.map} +1 -1
- package/dist/_chunks/{resolve-schema-CBR6Lm4i.js → resolve-schema-B-aCuTu3.js} +3 -4
- package/dist/_chunks/{resolve-schema-CBR6Lm4i.js.map → resolve-schema-B-aCuTu3.js.map} +1 -1
- package/dist/_chunks/{rsc-cache-key-ClUiXQnK.js → rsc-cache-key-D0cb0Gmc.js} +2 -3
- package/dist/_chunks/{rsc-cache-key-ClUiXQnK.js.map → rsc-cache-key-D0cb0Gmc.js.map} +1 -1
- package/dist/_chunks/{rsc-media-type-DDc7duTD.js → rsc-media-type-m8jz9u6_.js} +2 -3
- package/dist/_chunks/{rsc-media-type-DDc7duTD.js.map → rsc-media-type-m8jz9u6_.js.map} +1 -1
- package/dist/_chunks/{rsc-payload-path-dffcs4jp.js → rsc-payload-path-EphpDB-J.js} +2 -3
- package/dist/_chunks/{rsc-payload-path-dffcs4jp.js.map → rsc-payload-path-EphpDB-J.js.map} +1 -1
- package/dist/_chunks/{scan-BoP17W3w.js → scan-CyizcBiX.js} +2 -3
- package/dist/_chunks/{scan-BoP17W3w.js.map → scan-CyizcBiX.js.map} +1 -1
- package/dist/_chunks/{scanner-Cb3fSjAC.js → scanner-CJC-ScJU.js} +15 -23
- package/dist/_chunks/{scanner-Cb3fSjAC.js.map → scanner-CJC-ScJU.js.map} +1 -1
- package/dist/_chunks/{schema-bridge-C83xa9lT.js → schema-bridge-DyRs3cqy.js} +61 -25
- package/dist/_chunks/schema-bridge-DyRs3cqy.js.map +1 -0
- package/dist/_chunks/{segment-classify-C539Pa2O.js → segment-classify-Ho8jXWeC.js} +3 -5
- package/dist/_chunks/{segment-classify-C539Pa2O.js.map → segment-classify-Ho8jXWeC.js.map} +1 -1
- package/dist/_chunks/{segment-context-xtPUGfdq.js → segment-context-CYiGTi3K.js} +6 -12
- package/dist/_chunks/segment-context-CYiGTi3K.js.map +1 -0
- package/dist/_chunks/{segment-keys-D5hu1hz4.js → segment-keys-Y60KNc8C.js} +2 -3
- package/dist/_chunks/{segment-keys-D5hu1hz4.js.map → segment-keys-Y60KNc8C.js.map} +1 -1
- package/dist/_chunks/{singleflight-BeVMMKi0.js → singleflight-BChPMjwH.js} +2 -3
- package/dist/_chunks/{singleflight-BeVMMKi0.js.map → singleflight-BChPMjwH.js.map} +1 -1
- package/dist/_chunks/{sizeof-QPE5nd3u.js → sizeof-DG4W40lv.js} +3 -4
- package/dist/_chunks/{sizeof-QPE5nd3u.js.map → sizeof-DG4W40lv.js.map} +1 -1
- package/dist/_chunks/{ssr-data-nA3I70_n.js → ssr-data-9hPtcNOr.js} +3 -4
- package/dist/_chunks/{ssr-data-nA3I70_n.js.map → ssr-data-9hPtcNOr.js.map} +1 -1
- package/dist/_chunks/{state-BhNGPsdi.js → state-B-EBjeER.js} +2 -3
- package/dist/_chunks/{state-BhNGPsdi.js.map → state-B-EBjeER.js.map} +1 -1
- package/dist/_chunks/{status-page-marker-BRX9Ib-d.js → status-page-marker-XIQXlTOb.js} +8 -13
- package/dist/_chunks/{status-page-marker-BRX9Ib-d.js.map → status-page-marker-XIQXlTOb.js.map} +1 -1
- package/dist/_chunks/{tree-match-6yihorhk.js → tree-match-Bqdr9szG.js} +2 -3
- package/dist/_chunks/{tree-match-6yihorhk.js.map → tree-match-Bqdr9szG.js.map} +1 -1
- package/dist/_chunks/{use-query-states-I3JMng6J.js → use-query-states-pkDV-jSg.js} +4 -7
- package/dist/_chunks/{use-query-states-I3JMng6J.js.map → use-query-states-pkDV-jSg.js.map} +1 -1
- package/dist/_chunks/{walkers-qu8TpiLh.js → walkers-DIE203ir.js} +6 -8
- package/dist/_chunks/{walkers-qu8TpiLh.js.map → walkers-DIE203ir.js.map} +1 -1
- package/dist/_chunks/{write-file-atomic-D1qWqHb4.js → write-file-atomic-DW8m_Atv.js} +2 -3
- package/dist/_chunks/{write-file-atomic-D1qWqHb4.js.map → write-file-atomic-DW8m_Atv.js.map} +1 -1
- package/dist/adapters/build-output-helper.d.ts +10 -1
- package/dist/adapters/build-output-helper.d.ts.map +1 -1
- package/dist/adapters/cloudflare-dev.js +2 -3
- package/dist/adapters/cloudflare-kv-cache.js +3 -4
- package/dist/adapters/cloudflare.d.ts.map +1 -1
- package/dist/adapters/cloudflare.js +1 -1
- package/dist/adapters/nitro-presets.d.ts +6 -0
- package/dist/adapters/nitro-presets.d.ts.map +1 -1
- package/dist/adapters/nitro-preview.d.ts.map +1 -1
- package/dist/adapters/nitro.d.ts.map +1 -1
- package/dist/adapters/nitro.js +94 -57
- package/dist/adapters/nitro.js.map +1 -1
- package/dist/analyze/crawl-entry.js +7 -9
- package/dist/analyze/crawl-entry.js.map +1 -1
- package/dist/analyze/graph-command.d.ts.map +1 -1
- package/dist/analyze/graph-command.js +19 -105
- package/dist/analyze/graph-command.js.map +1 -1
- package/dist/cache/guarded-read.d.ts +29 -0
- package/dist/cache/guarded-read.d.ts.map +1 -0
- package/dist/cache/index.js +3 -3
- package/dist/cache/key-discipline.d.ts +61 -0
- package/dist/cache/key-discipline.d.ts.map +1 -0
- package/dist/cache/stores/cloudflare-kv.js +1 -2
- package/dist/cache/stores/memory.js +2 -3
- package/dist/cache/stores/redis.js +1 -2
- package/dist/cache/stores/vercel.js +1 -2
- package/dist/cache/timber-cache.d.ts +5 -1
- package/dist/cache/timber-cache.d.ts.map +1 -1
- package/dist/cdn/cloudflare-purge.js +1 -2
- package/dist/cdn/fastly-purge.js +1 -2
- package/dist/cdn/index.js +2 -3
- package/dist/cdn/workers-cache-purge.js +3 -5
- package/dist/cdn/workers-cache-purge.js.map +1 -1
- package/dist/cli-dev-status.d.ts +75 -0
- package/dist/cli-dev-status.d.ts.map +1 -0
- package/dist/cli-init.d.ts +72 -0
- package/dist/cli-init.d.ts.map +1 -0
- package/dist/cli.d.ts +4 -12
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +27 -54
- package/dist/cli.js.map +1 -1
- package/dist/client/error-boundary.d.ts.map +1 -1
- package/dist/client/error-boundary.js +1 -1
- package/dist/client/global-context.d.ts +21 -1
- package/dist/client/global-context.d.ts.map +1 -1
- package/dist/client/index.js +23 -44
- package/dist/client/index.js.map +1 -1
- package/dist/client/internal.js +13 -18
- package/dist/client/internal.js.map +1 -1
- package/dist/client/navigation-context.d.ts.map +1 -1
- package/dist/client/params-context.d.ts.map +1 -1
- package/dist/client/slot-context.d.ts +2 -2
- package/dist/client/slot-context.d.ts.map +1 -1
- package/dist/client/use-cookie.d.ts +18 -5
- package/dist/client/use-cookie.d.ts.map +1 -1
- package/dist/codec.js +2 -3
- package/dist/config-types.d.ts +22 -5
- package/dist/config-types.d.ts.map +1 -1
- package/dist/config-validation.d.ts.map +1 -1
- package/dist/cookies/define-cookie.d.ts.map +1 -1
- package/dist/cookies/index.js +40 -67
- package/dist/cookies/index.js.map +1 -1
- package/dist/cookies/json-cookie.d.ts +4 -4
- package/dist/index.js +266 -229
- package/dist/index.js.map +1 -1
- package/dist/params/index.js +3 -4
- package/dist/plugin-context.d.ts +7 -0
- package/dist/plugin-context.d.ts.map +1 -1
- package/dist/plugins/dev-discovery.d.ts +69 -5
- package/dist/plugins/dev-discovery.d.ts.map +1 -1
- package/dist/plugins/dev-hostname.d.ts +152 -0
- package/dist/plugins/dev-hostname.d.ts.map +1 -0
- package/dist/plugins/dev-server.d.ts +6 -2
- package/dist/plugins/dev-server.d.ts.map +1 -1
- package/dist/plugins/dev-store-clear.d.ts +83 -0
- package/dist/plugins/dev-store-clear.d.ts.map +1 -0
- package/dist/plugins/graph-endpoint.d.ts +4 -2
- package/dist/plugins/graph-endpoint.d.ts.map +1 -1
- package/dist/plugins/prebuilt.d.ts.map +1 -1
- package/dist/routing/index.js +4 -4
- package/dist/rsc-runtime/rsc.d.ts +2 -1
- package/dist/rsc-runtime/rsc.d.ts.map +1 -1
- package/dist/rsc-runtime/server-references.d.ts +8 -0
- package/dist/rsc-runtime/server-references.d.ts.map +1 -0
- package/dist/schema-bridge.d.ts +28 -19
- package/dist/schema-bridge.d.ts.map +1 -1
- package/dist/search-params/define.d.ts +1 -1
- package/dist/search-params/define.d.ts.map +1 -1
- package/dist/search-params/index.js +11 -14
- package/dist/search-params/index.js.map +1 -1
- package/dist/search-params/wrappers.d.ts +3 -3
- package/dist/server/access-gate.d.ts +12 -0
- package/dist/server/access-gate.d.ts.map +1 -1
- package/dist/server/canonicalize.d.ts +21 -0
- package/dist/server/canonicalize.d.ts.map +1 -1
- package/dist/server/cookie-context.d.ts +8 -1
- package/dist/server/cookie-context.d.ts.map +1 -1
- package/dist/server/flight-source-node.d.ts.map +1 -1
- package/dist/server/flight-source.d.ts.map +1 -1
- package/dist/server/index.d.ts +1 -1
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +8 -13
- package/dist/server/index.js.map +1 -1
- package/dist/server/interception-gates.d.ts +49 -0
- package/dist/server/interception-gates.d.ts.map +1 -0
- package/dist/server/internal.js +1080 -959
- package/dist/server/internal.js.map +1 -1
- package/dist/server/logger.d.ts +26 -0
- package/dist/server/logger.d.ts.map +1 -1
- package/dist/server/param-coercion.d.ts +8 -0
- package/dist/server/param-coercion.d.ts.map +1 -1
- package/dist/server/pipeline-interception.d.ts +34 -4
- package/dist/server/pipeline-interception.d.ts.map +1 -1
- package/dist/server/pipeline-metadata-route.d.ts +24 -0
- package/dist/server/pipeline-metadata-route.d.ts.map +1 -0
- package/dist/server/pipeline-metadata.d.ts +3 -2
- package/dist/server/pipeline-metadata.d.ts.map +1 -1
- package/dist/server/pipeline-phases.d.ts +9 -3
- package/dist/server/pipeline-phases.d.ts.map +1 -1
- package/dist/server/pipeline.d.ts +18 -0
- package/dist/server/pipeline.d.ts.map +1 -1
- package/dist/server/prebuilt/dev-store.d.ts +68 -22
- package/dist/server/prebuilt/dev-store.d.ts.map +1 -1
- package/dist/server/prebuilt/overlay.d.ts +17 -3
- package/dist/server/prebuilt/overlay.d.ts.map +1 -1
- package/dist/server/prebuilt-runtime.d.ts.map +1 -1
- package/dist/server/primitives.d.ts +13 -0
- package/dist/server/primitives.d.ts.map +1 -1
- package/dist/server/render-utils.d.ts +21 -0
- package/dist/server/render-utils.d.ts.map +1 -1
- package/dist/server/request-context.d.ts +14 -0
- package/dist/server/request-context.d.ts.map +1 -1
- package/dist/server/route-element-builder.d.ts.map +1 -1
- package/dist/server/route-handler.d.ts +7 -0
- package/dist/server/route-handler.d.ts.map +1 -1
- package/dist/server/route-matcher.d.ts +14 -3
- package/dist/server/route-matcher.d.ts.map +1 -1
- package/dist/server/rsc-entry/api-handler.d.ts.map +1 -1
- package/dist/server/rsc-entry/index.d.ts.map +1 -1
- package/dist/server/rsc-entry/rsc-stream.d.ts.map +1 -1
- package/dist/server/signal-identity.d.ts +6 -0
- package/dist/server/signal-identity.d.ts.map +1 -1
- package/dist/server/traced-access.d.ts +18 -0
- package/dist/server/traced-access.d.ts.map +1 -0
- package/dist/server/tracing.d.ts.map +1 -1
- package/dist/server/types.d.ts +5 -4
- package/dist/server/types.d.ts.map +1 -1
- package/dist/shims/font-google.js +1 -2
- package/dist/shims/font-local.js +1 -2
- package/dist/shims/headers.d.ts +11 -4
- package/dist/shims/headers.d.ts.map +1 -1
- package/docs/api/30-api-server.mdx +3 -1
- package/docs/api/32-api-cache.mdx +1 -1
- package/docs/api/33-api-search-params.mdx +3 -1
- package/docs/api/34-api-config.mdx +22 -0
- package/docs/api/36-cli.mdx +72 -6
- package/docs/learn/01-quick-start.mdx +1 -1
- package/docs/learn/06-typed-params.mdx +4 -4
- package/docs/learn/10-caching.mdx +26 -5
- package/llms.txt +1 -1
- package/package.json +12 -12
- package/src/adapters/build-output-helper.ts +26 -4
- package/src/adapters/cloudflare.ts +1 -0
- package/src/adapters/nitro-presets.ts +15 -0
- package/src/adapters/nitro-preview.ts +66 -34
- package/src/adapters/nitro.ts +14 -6
- package/src/analyze/graph-command.ts +25 -133
- package/src/cache/guarded-read.ts +44 -0
- package/src/cache/key-discipline.ts +218 -0
- package/src/cache/timber-cache.ts +46 -7
- package/src/cli-dev-status.ts +196 -0
- package/src/cli-init.ts +278 -0
- package/src/cli.ts +33 -79
- package/src/client/error-boundary.tsx +19 -2
- package/src/client/global-context.ts +42 -14
- package/src/client/navigation-context.ts +4 -11
- package/src/client/params-context.ts +5 -17
- package/src/client/segment-update-context.ts +1 -1
- package/src/client/slot-content-cache-context.ts +1 -1
- package/src/client/slot-context.ts +6 -17
- package/src/client/use-cookie.ts +33 -21
- package/src/config-types.ts +22 -5
- package/src/config-validation.ts +17 -0
- package/src/cookies/define-cookie.ts +10 -46
- package/src/cookies/json-cookie.ts +4 -4
- package/src/plugin-context.ts +7 -0
- package/src/plugins/dev-discovery.ts +216 -6
- package/src/plugins/dev-hostname.ts +322 -0
- package/src/plugins/dev-server.ts +130 -37
- package/src/plugins/dev-store-clear.ts +145 -0
- package/src/plugins/graph-endpoint.ts +15 -3
- package/src/plugins/prebuilt.ts +9 -0
- package/src/rsc-runtime/rsc.ts +7 -3
- package/src/rsc-runtime/server-references.ts +73 -0
- package/src/rsc-runtime/vendor-types.d.ts +17 -0
- package/src/schema-bridge.ts +93 -38
- package/src/search-params/define.ts +5 -6
- package/src/search-params/wrappers.ts +3 -3
- package/src/server/access-gate.tsx +32 -20
- package/src/server/action-handler.ts +58 -36
- package/src/server/canonicalize.ts +27 -0
- package/src/server/cookie-context.ts +11 -3
- package/src/server/flight-source-node.ts +5 -2
- package/src/server/flight-source.ts +4 -3
- package/src/server/index.ts +6 -1
- package/src/server/interception-gates.ts +94 -0
- package/src/server/logger.ts +32 -0
- package/src/server/param-coercion.ts +22 -0
- package/src/server/pipeline-interception.ts +64 -4
- package/src/server/pipeline-metadata-route.ts +242 -0
- package/src/server/pipeline-metadata.ts +7 -5
- package/src/server/pipeline-phases.ts +71 -131
- package/src/server/pipeline.ts +20 -2
- package/src/server/prebuilt/dev-store.ts +113 -34
- package/src/server/prebuilt/overlay.ts +32 -4
- package/src/server/prebuilt-runtime.ts +63 -45
- package/src/server/primitives.ts +14 -0
- package/src/server/render-utils.ts +25 -0
- package/src/server/request-context.ts +27 -3
- package/src/server/route-element-builder.ts +15 -2
- package/src/server/route-handler.ts +3 -2
- package/src/server/route-matcher.ts +48 -33
- package/src/server/rsc-entry/api-handler.ts +2 -33
- package/src/server/rsc-entry/index.ts +8 -3
- package/src/server/rsc-entry/rsc-stream.ts +7 -1
- package/src/server/signal-identity.ts +30 -12
- package/src/server/traced-access.ts +50 -0
- package/src/server/tracing.ts +18 -1
- package/src/server/types.ts +5 -4
- package/src/shims/headers.ts +12 -4
- package/dist/_chunks/actions-BDqn4Oxj.js.map +0 -1
- package/dist/_chunks/build-output-helper-RV_BRcF1.js.map +0 -1
- package/dist/_chunks/cache-api-GE4AOe2H.js.map +0 -1
- package/dist/_chunks/chains-CDK1AWZQ.js +0 -1
- package/dist/_chunks/cli-context-BJQB6rtF.js +0 -1
- package/dist/_chunks/dev-server-BiWNMBVU.js +0 -1
- package/dist/_chunks/dev-server-DIy-SY-J.js.map +0 -1
- package/dist/_chunks/dev-store-BOa304m_.js.map +0 -1
- package/dist/_chunks/flight-source-node-HptmGMT8.js.map +0 -1
- package/dist/_chunks/graph-cache-CYiUS2aS.js.map +0 -1
- package/dist/_chunks/logger-CbLdcy-W.js.map +0 -1
- package/dist/_chunks/node-response-rkQqcFGq.js.map +0 -1
- package/dist/_chunks/plugin-context-DxMMvjUt.js.map +0 -1
- package/dist/_chunks/schema-bridge-C83xa9lT.js.map +0 -1
- package/dist/_chunks/segment-context-xtPUGfdq.js.map +0 -1
- package/dist/server/prebuilt/key-discipline.d.ts +0 -52
- package/dist/server/prebuilt/key-discipline.d.ts.map +0 -1
- package/src/server/prebuilt/key-discipline.ts +0 -122
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"actions-BDqn4Oxj.js","names":["upstreamParseSetCookie","_getWaitUntil"],"sources":["../../src/server/react-cache-scope.ts","../../src/server/request-context.ts","../../src/server/cookie-parsing.ts","../../src/server/cookie-context.ts","../../src/server/primitives.ts","../../src/server/form-data.ts","../../src/server/actions.ts"],"sourcesContent":["/**\n * React.cache scopes — opening, resuming, and leaving the per-request\n * `React.cache` scope that `react-cache-bridge.ts` makes Flight read.\n *\n * Kept apart from the bridge so request-context and cookie code can use\n * it without importing `react`. See design/spike-TIM-1529-react-cache-bridge.md.\n */\n\nimport { reactCacheScopeAls, type ReactCacheScope } from './als-registry.ts';\nimport { isDevMode } from './debug.ts';\n\nexport type { ReactCacheScope };\n\n/** A new, empty `React.cache` scope. */\nexport function createReactCacheScope(): ReactCacheScope {\n return new Map();\n}\n\n/**\n * Run `fn` in a `React.cache` scope — a fresh one unless `scope` is given.\n * Every `React.cache` call made from `fn` — synchronously, in its async\n * continuations, and in any Flight render it starts — shares one memo table.\n *\n * Opened by `runWithRequestContext`, so each request context gets its own\n * scope. Pass `scope` to resume one across two ALS runs: the post-action\n * revalidation opens a fresh scope for the target route's middleware and\n * renders the revalidated tree in that same scope later.\n */\nexport function runWithReactCacheScope<T>(\n fn: () => T,\n scope: ReactCacheScope = createReactCacheScope()\n): T {\n return reactCacheScopeAls.run(scope, fn);\n}\n\n/**\n * Run `fn` with no timber scope, so `React.cache` behaves as stock React:\n * no dedupe outside a render, Flight's own per-render cache inside one.\n *\n * Used for server action bodies — an action reads, writes cookies, and\n * mutates, so memoized reads would go stale mid-action (the same choice\n * Next.js makes) — and for renders whose output outlives the request\n * (`cache.component` capture), which must not bake request-memoized values\n * into a cross-request cache entry.\n */\nexport function runOutsideReactCacheScope<T>(fn: () => T): T {\n return reactCacheScopeAls.exit(fn);\n}\n\n// ─── Dev diagnostic: cookie written after a cached read ──────────────────\n//\n// A value React.cache stored was computed from the request inputs it read,\n// and does not see a later write — a cached getUser() that read the session\n// cookie still returns the old user after middleware deletes the cookie.\n// The scope is deliberately NOT cleared on a write: that would silently\n// discard every value middleware warmed (spike doc §Decisions D3). Instead,\n// dev mode flags the one case that can go stale: a cookie read while the\n// scope held values, then written later in the same request. Tracking is\n// per scope, so it ends with the request; production does none of it.\n\n/** Stands for \"every cookie\" — a getAll()/size read, or a clear() write. */\nexport const ANY_COOKIE = '*';\n\nconst cookieReads = new WeakMap<ReactCacheScope, Set<string>>();\nconst warnedScopes = new WeakSet<ReactCacheScope>();\n\n/**\n * Dev-only: record that cookie `name` (or {@link ANY_COOKIE}) was read\n * while `React.cache` held values in this request — the read may have\n * happened inside a cached function.\n */\nexport function noteCookieReadForReactCache(name: string): void {\n if (!isDevMode()) return;\n const scope = reactCacheScopeAls.getStore();\n if (!scope || scope.size === 0) return;\n let reads = cookieReads.get(scope);\n if (!reads) {\n reads = new Set();\n cookieReads.set(scope, reads);\n }\n reads.add(name);\n}\n\n/**\n * Dev-only: warn (once per request) when a cookie recorded by\n * {@link noteCookieReadForReactCache} is written. `name` is the written\n * cookie, or {@link ANY_COOKIE} for `clear()`. Dev-only because reads are\n * only recorded in dev.\n */\nexport function warnIfCachedCookieIsWritten(name: string): void {\n const scope = reactCacheScopeAls.getStore();\n if (!scope || warnedScopes.has(scope)) return;\n const reads = cookieReads.get(scope);\n if (!reads) return;\n const stale = name === ANY_COOKIE ? reads.size > 0 : reads.has(name) || reads.has(ANY_COOKIE);\n if (!stale) return;\n warnedScopes.add(scope);\n const which = name === ANY_COOKIE ? 'Cookies were cleared' : `Cookie \"${name}\" was written`;\n console.warn(\n `[timber] ${which} after being read while React.cache held values for this request. ` +\n `A cached function that read it keeps returning the old result — pass the cookie ` +\n `value in as an argument (e.g. getUser(sessionToken)) so a change is a new cache key.`\n );\n}\n","/**\n * Request Context — per-request ALS store for headers, search params,\n * segment params, and request scope lifecycle.\n *\n * Follows the same pattern as tracing.ts: a module-level AsyncLocalStorage\n * instance, public accessor functions that throw outside request scope,\n * and a framework-internal `runWithRequestContext()` to establish scope.\n *\n * Cookie state lives in `cookie-context.ts` (split out in TIM-853). The\n * scope set up here owns the cookie jar / parsedCookies fields on the\n * store, but the cookie API and helpers are in the cookie module.\n *\n * See design/04-authorization.md §\"AccessContext does not include cookies or headers\"\n * and design/11-platform.md §\"AsyncLocalStorage\".\n */\n\nimport type { CoercedParams } from '../shared/param-value.ts';\nimport {\n requestContextAls,\n type ActionErrorForRender,\n type RequestContextStore,\n} from './als-registry.ts';\nimport { _setGetSearchParamsFn, _setGetSegmentParamsFn } from '../shared/als-slots.ts';\nimport { appVisibleSearch } from '../shared/rsc-cache-key.ts';\nimport {\n mergeSlotParams,\n resolveSegmentParams,\n type SlotParamsRecord,\n} from '../shared/slot-params.ts';\nimport { isDebug } from './debug.ts';\nimport { runWithReactCacheScope, type ReactCacheScope } from './react-cache-scope.ts';\nimport type { ReactFormState } from 'react-dom/client';\n\n// Re-export the ALS for framework-internal consumers that need direct access.\nexport { requestContextAls };\n\n// ─── Public API ───────────────────────────────────────────────────────────\n\n/**\n * Returns a read-only view of the current request's headers.\n *\n * Available in middleware, access checks, server components, and server actions.\n * Throws if called outside a request context (security principle #2: no global fallback).\n */\nexport function getHeaders(): ReadonlyHeaders {\n const store = requestContextAls.getStore();\n if (!store) {\n throw new Error(\n '[timber] getHeaders() called outside of a request context. ' +\n 'It can only be used in middleware, access checks, server components, and server actions.'\n );\n }\n\n return store.headers;\n}\n\n/**\n * Returns the value of a single request header, or undefined if absent.\n *\n * Thin wrapper over `getHeaders().get(name)` for the common case where\n * you need exactly one header.\n *\n * @internal — not part of the public API. Use `getHeaders().get(name)` instead.\n */\nexport function getHeader(name: string): string | undefined {\n const headers = getHeaders();\n return headers.get(name) ?? undefined;\n}\n\n/**\n * Returns the current request's raw URLSearchParams.\n *\n * @internal — not part of the public API. Use `defineSearchParams().get()` instead.\n */\nexport function getSearchParams(): URLSearchParams {\n const store = requestContextAls.getStore();\n if (!store) {\n throw new Error(\n '[timber] getSearchParams() called outside of a request context. ' +\n 'It can only be used in middleware, access checks, server components, and server actions.'\n );\n }\n\n return store.searchParams;\n}\n\n// Eagerly register getSearchParams with the search-params module so\n// searchParams.get() can call it without a dynamic import.\n// Dynamic imports lose ALS context in React's RSC Flight renderer,\n// breaking getSearchParams() in parallel slot pages. See TIM-523.\n_setGetSearchParamsFn(getSearchParams);\n\n// Eagerly register getSegmentParams with the segment-params module so\n// segmentParams.get() can call it without a dynamic import.\n// Same pattern as search params — dynamic imports lose ALS context. See TIM-523.\n_setGetSegmentParamsFn(getSegmentParams);\n\n/**\n * Returns the current request's coerced segment params.\n *\n * The optional `segmentPath` argument exists only for TypeScript narrowing —\n * it does not affect the runtime return value. Pass a segment path\n * (e.g. `'/(browse)/[artistSlug]/[year]'`) to narrow the return type to the\n * exact params shape for that segment.\n *\n * Without an argument, returns all coerced params with optional types.\n *\n * See design/41-global-params.md §Function Signatures\n */\nexport function getSegmentParams(segmentPath?: string): CoercedParams {\n const store = requestContextAls.getStore();\n if (!store) {\n throw new Error(\n '[timber] getSegmentParams() called outside of a request context. ' +\n 'It can only be used in middleware, access checks, server components, and server actions.'\n );\n }\n if (!store.segmentParams) {\n throw new Error(\n '[timber] getSegmentParams() called before route matching completed. ' +\n 'Segment params are not available until after the route is matched.'\n );\n }\n\n // Parallel slots may derive a param the main route never had, or the same\n // name with a different type (catch-all [...year] → string[] vs dynamic\n // [year] → string). `resolveSegmentParams` is the shared definition the\n // client's useSegmentParams() also reads, so the two halves of one\n // documented API cannot drift (TIM-1285).\n const slotResolved = resolveSegmentParams(store.segmentParams, store.slotParams, segmentPath);\n if (slotResolved !== store.segmentParams) return slotResolved;\n\n // Dev-mode validation: warn when the segment path expects dynamic\n // segments that don't exist on the actual matched segment. This catches\n // bugs like passing a child segment's $segment to a parent layout.\n // Skip for slot paths — they're validated against their own chain.\n // See design/41-global-params.md §Runtime Validation\n if (segmentPath && isDebug() && store.matchedSegmentPath) {\n const expected = extractDynamicSegments(segmentPath);\n const actual = extractDynamicSegments(store.matchedSegmentPath);\n const missing = expected.filter((s) => !actual.includes(s));\n\n if (missing.length > 0) {\n console.warn(\n `[timber] getSegmentParams('${segmentPath}') called but current segment is '${store.matchedSegmentPath}'\\n` +\n ` Missing params: ${missing.join(', ')}\\n` +\n ` These will be undefined at runtime despite the type annotation.`\n );\n }\n }\n\n return store.segmentParams;\n}\n\n/**\n * Set the segment params on the current request context.\n * Called by the pipeline after route matching and param coercion.\n *\n * @internal — framework use only\n */\nexport function setSegmentParams(params: CoercedParams): void {\n const store = requestContextAls.getStore();\n if (!store) {\n throw new Error('[timber] setSegmentParams() called outside of a request context.');\n }\n store.segmentParams = params;\n}\n\n/**\n * Store per-slot coerced segment params in the current request context.\n * Called by the route element builder when resolving parallel slots.\n *\n * @param segmentPath — The slot's full tree path (e.g. '/(browse)/@shows/[artistSlug]/[...year]')\n * @param params — The slot's coerced segment params\n * @internal — framework use only\n */\nexport function setSlotParams(segmentPath: string, params: CoercedParams): void {\n const store = requestContextAls.getStore();\n if (!store) return; // non-throwing — optional diagnostic\n if (!store.slotParams) store.slotParams = Object.create(null) as SlotParamsRecord;\n store.slotParams[segmentPath] = params;\n}\n\n/**\n * Run `fn` with the segment params a parallel slot's own chain produced, so\n * a no-arg `getSegmentParams()` inside that slot returns the slot's params\n * rather than the main route's.\n *\n * ALS is the only channel available: the slot's page and layouts are plain\n * components that receive no params prop and cannot know their own tree\n * path, so they have no way to ask for the keyed overload. The slot resolver\n * invokes each of them itself (page through `SafeSlotPage`, layouts and\n * access functions through their wrappers), and this scopes those calls.\n *\n * The store is wrapped in a Proxy rather than cloned. Everything a slot\n * renders can write to the *live* request store — `setDenyStatus` from an\n * access gate, cookie writes, the flush flag — and a clone would silently\n * strand those writes in a copy the pipeline never reads. Only the two\n * params fields are shadowed; every other read and every write passes\n * straight through to the real store.\n *\n * Returns `fn()`'s result unchanged, and no-ops outside a request context or\n * before route matching has set the main params. See TIM-1283.\n *\n * @internal — framework use only\n */\nexport function runWithSlotSegmentParams<T>(\n slotSegmentPath: string | undefined,\n slotParams: CoercedParams,\n fn: () => T\n): T {\n const store = requestContextAls.getStore();\n if (!store?.segmentParams) return fn();\n\n const merged = mergeSlotParams(store.segmentParams, slotParams);\n const matchedSegmentPath = slotSegmentPath ?? store.matchedSegmentPath;\n const scoped = new Proxy(store, {\n get(target, prop, receiver) {\n if (prop === 'segmentParams') return merged;\n if (prop === 'matchedSegmentPath') return matchedSegmentPath;\n return Reflect.get(target, prop, receiver);\n },\n });\n return requestContextAls.run(scoped, fn);\n}\n\n/**\n * The main route's coerced params, or an empty record before route matching.\n *\n * Non-throwing, unlike `getSegmentParams()`: the deny payload path publishes\n * params from wherever the pipeline happened to fail, which may be before\n * matching completed.\n *\n * @internal — framework use only. See TIM-1285.\n */\nexport function getSegmentParamsForClient(): CoercedParams {\n return requestContextAls.getStore()?.segmentParams ?? {};\n}\n\n/**\n * The per-slot params to publish to the client, or `undefined` when the\n * request rendered no slot with params of its own.\n *\n * The client cannot derive these: a slot matches the URL through its own\n * sub-tree, and the browser only ever sees the main route's record. Reading\n * the map here — rather than threading it back out of the element builder —\n * keeps one producer, since `setSlotParams` already writes it during slot\n * resolution and every serialization site runs after that completes.\n *\n * @internal — framework use only. See TIM-1285.\n */\nexport function getSlotParamsForClient(): SlotParamsRecord | undefined {\n const store = requestContextAls.getStore();\n if (!store?.slotParams) return undefined;\n return Object.keys(store.slotParams).length > 0 ? store.slotParams : undefined;\n}\n\n/**\n * Store the matched segment path (e.g. '/(browse)/[artistSlug]/[year]') for\n * dev-mode validation in getSegmentParams().\n *\n * @internal — framework use only\n */\nexport function setMatchedSegmentPath(segmentPath: string): void {\n const store = requestContextAls.getStore();\n if (!store) return; // non-throwing — optional diagnostic\n store.matchedSegmentPath = segmentPath;\n}\n\n/**\n * Extract dynamic segment names from a route pattern.\n * '/[artistSlug]/[year]' → ['artistSlug', 'year']\n * '/docs/[...slug]' → ['slug']\n */\nfunction extractDynamicSegments(route: string): string[] {\n const segments: string[] = [];\n // Match [paramName], [...paramName], [[...paramName]]\n const re = /\\[{1,2}\\.{0,3}(\\w+)\\]{1,2}/g;\n let m: RegExpExecArray | null;\n while ((m = re.exec(route)) !== null) {\n segments.push(m[1]);\n }\n return segments;\n}\n\n/**\n * Returns the raw search string from the current request URL (e.g. \"?foo=bar\").\n * Synchronous — safe for use in `redirect()` which throws synchronously.\n *\n * Returns empty string if called outside a request context (non-throwing for\n * use in redirect's optional preserveSearchParams path).\n *\n * @internal — used by redirect() for preserveSearchParams support.\n */\nexport function getRequestSearchString(): string {\n const store = requestContextAls.getStore();\n return store?.searchString ?? '';\n}\n\n// ─── Types ────────────────────────────────────────────────────────────────\n\n/**\n * Read-only Headers interface. The standard Headers class is mutable;\n * this type narrows it to read-only methods. The underlying object is\n * still a Headers instance, but user code should not mutate it.\n */\nexport type ReadonlyHeaders = Pick<\n Headers,\n 'get' | 'has' | 'entries' | 'keys' | 'values' | 'forEach' | typeof Symbol.iterator\n>;\n\n// ─── Framework-Internal Helpers ───────────────────────────────────────────\n\n/** Options for `runWithRequestContext()`. */\nexport interface RequestContextOptions {\n /**\n * Resume this `React.cache` scope instead of opening a fresh one. Only the\n * post-action revalidation passes it.\n */\n reactCacheScope?: ReactCacheScope;\n /**\n * The request's cookies, already parsed. Re-entry callers (the no-JS form\n * rerender and the revalidation middleware) pass the action's\n * post-mutation cookie state here instead of round-tripping it through a\n * `Cookie:` header — the same parse the H-3 smuggling primitive abused\n * (TIM-868).\n */\n cookies?: Map<string, string>;\n /**\n * The form state of the no-JS action this render answers. Only the\n * action dispatcher's re-entry passes it; see `RequestContextStore.formState`.\n */\n formState?: ReactFormState;\n /**\n * The error of the no-JS action this render answers. Only the action\n * dispatcher's re-entry passes it; see `RequestContextStore.actionError`.\n */\n actionError?: ActionErrorForRender;\n}\n\n/**\n * Run a callback within a request context. Used by the pipeline to establish\n * per-request ALS scope so that `getHeaders()` and `getCookies()` work.\n *\n * When `options.cookies` is given, the context's `parsedCookies` map is a\n * copy of it and the raw `cookieHeader` is left empty, so\n * `parseCookieHeader` never runs for that request. Re-entry callers pass the\n * action's post-mutation cookie state this way (TIM-868).\n *\n * Each request context also opens its own `React.cache` scope, shared by\n * everything that runs inside it — proxy.ts, middleware.ts, route handlers,\n * and the render (design/02-rendering-pipeline.md §\"Cache Scoping Model\").\n *\n * @param req - The incoming Request object.\n * @param fn - The function to run within the request context.\n */\nexport function runWithRequestContext<T>(\n req: Request,\n fn: () => T,\n { reactCacheScope, cookies, formState, actionError }: RequestContextOptions = {}\n): T {\n const originalCopy = new Headers(req.headers);\n const appVisible = appVisibleSearch(new URL(req.url));\n // A copy: the caller keeps its map, and this request's writes stay here.\n const seed = cookies ? new Map(cookies) : undefined;\n const store: RequestContextStore = {\n request: req,\n headers: freezeHeaders(req.headers),\n originalHeaders: originalCopy,\n // Given parsed cookies, leave the raw header empty — parseCookieHeader is the\n // exact code path the smuggling primitive abused, and lazy parsing is\n // gated on `parsedCookies` being undefined.\n cookieHeader: seed ? '' : (req.headers.get('cookie') ?? ''),\n parsedCookies: seed,\n // Not `parsedUrl.searchParams` / `parsedUrl.search`: this store is what\n // `getSearchParams()` and `redirect({ preserveSearchParams })` read, and\n // the RSC payload URL carries the framework's `_rsc` cache key that no\n // other request has (TIM-1272).\n searchParams: appVisible.params,\n searchString: appVisible.search,\n cookieJar: new Map(),\n flushed: false,\n mutableContext: false,\n formState,\n actionError,\n };\n return requestContextAls.run(store, () => runWithReactCacheScope(fn, reactCacheScope));\n}\n\n/**\n * Enable cookie mutation for the current context. Called by the framework\n * when entering middleware.ts, server actions, or route.ts handlers.\n *\n * See design/29-cookies.md §\"Context Tracking\"\n */\nexport function setMutableCookieContext(mutable: boolean): void {\n const store = requestContextAls.getStore();\n if (store) {\n store.mutableContext = mutable;\n }\n}\n\n/**\n * Mark the response as flushed (headers committed). After this point,\n * cookie mutations log a warning instead of throwing.\n *\n * See design/29-cookies.md §\"Streaming Constraint: Post-Flush Cookie Warning\"\n */\nexport function markResponseFlushed(): void {\n const store = requestContextAls.getStore();\n if (store) {\n store.flushed = true;\n }\n}\n\n/**\n * Apply middleware-injected request headers to the current request context.\n *\n * Called by the pipeline after middleware.ts runs. Merges overlay headers\n * on top of the original request headers so downstream code (access.ts,\n * server components, server actions) sees them via `getHeaders()`.\n *\n * The original request headers are never mutated — a new frozen Headers\n * object is created with the overlay applied on top.\n *\n * See design/07-routing.md §\"Request Header Injection\"\n */\nexport function applyRequestHeaderOverlay(overlay: Headers): void {\n const store = requestContextAls.getStore();\n if (!store) {\n throw new Error('[timber] applyRequestHeaderOverlay() called outside of a request context.');\n }\n\n // Check if the overlay has any headers — skip if empty\n let hasOverlay = false;\n overlay.forEach(() => {\n hasOverlay = true;\n });\n if (!hasOverlay) return;\n\n // Merge: start with original headers, overlay on top\n const merged = new Headers(store.originalHeaders);\n overlay.forEach((value, key) => {\n merged.set(key, value);\n });\n store.headers = freezeHeaders(merged);\n}\n\n// ─── Read-Only Headers ────────────────────────────────────────────────────\n\nconst MUTATING_METHODS = new Set(['set', 'append', 'delete']);\n\n/**\n * Wrap a Headers object in a Proxy that throws on mutating methods.\n * Object.freeze doesn't work on Headers (native internal slots), so we\n * intercept property access and reject set/append/delete at runtime.\n *\n * Read methods (get, has, entries, etc.) must be bound to the underlying\n * Headers instance because they access private #headersList slots.\n */\nfunction freezeHeaders(source: Headers): Headers {\n const copy = new Headers(source);\n return new Proxy(copy, {\n get(target, prop) {\n if (typeof prop === 'string' && MUTATING_METHODS.has(prop)) {\n return () => {\n throw new Error(\n `[timber] getHeaders() returns a read-only Headers object. ` +\n `Calling .${prop}() is not allowed. ` +\n `Use ctx.requestHeaders in middleware to inject headers for downstream components.`\n );\n };\n }\n const value = Reflect.get(target, prop);\n // Bind methods to the real Headers instance so private slot access works\n if (typeof value === 'function') {\n return value.bind(target);\n }\n return value;\n },\n });\n}\n\n/**\n * The form state of the no-JS action this render answers, or `null`. Read by\n * the SSR renderer only (`rsc-entry/ssr-renderer.ts`), which passes it to\n * Fizz and embeds it for `hydrateRoot`. Framework-internal: not exported\n * from `@timber-js/app/server`.\n */\nexport function getFormStateForSsr(): ReactFormState | null {\n return requestContextAls.getStore()?.formState ?? null;\n}\n\n/**\n * The error of the no-JS action this render answers, or `null`. Read by the\n * route element builder, which renders it in place of the page, and by the\n * Flight `onError`, which gives it the ID the action logged it with.\n * Framework-internal: not exported from `@timber-js/app/server`.\n */\nexport function getActionErrorForRender(): ActionErrorForRender | null {\n return requestContextAls.getStore()?.actionError ?? null;\n}\n","/**\n * Cookie parsing and serialization helpers — pure string ↔ structure\n * functions with no ALS dependency. Split out of `cookie-context.ts`\n * (TIM-853) so the API surface and the wire-format codecs can each be\n * read on their own.\n *\n * The functions in this module are total over arbitrary input. They\n * never throw and never call `assertValid*` (the security validators\n * live in the API surface — `cookie-context.ts` invokes them at every\n * jar entry point so the smuggling-primitive invariant from TIM-868\n * is enforced regardless of which path produced the bytes).\n *\n * Delegates to the `cookie` package (RFC 6265, dependency-free,\n * browser-safe) for wire codecs. Adapts at the boundary to preserve\n * timber's Map-based API and never-throw contract.\n */\n\nimport { parseCookie, parseSetCookie as upstreamParseSetCookie, stringifySetCookie } from 'cookie';\n\nimport type { CookieEntry } from './als-registry.ts';\nimport type { CookieOptions } from './cookie-context.ts';\n\n/**\n * Parse a Cookie header string into a Map of name → value pairs.\n * Follows RFC 6265 §4.2.1: cookies are semicolon-separated key=value pairs.\n *\n * Values are auto-decoded with `decodeURIComponent` so they round-trip\n * losslessly with `getCookies().set()` (which auto-encodes). Malformed\n * `%`-escapes from third-party cookies fall back to the raw byte sequence\n * — the parser must be total over arbitrary inbound headers, including\n * non-conforming values from other servers, browser extensions, etc.\n */\nexport function parseCookieHeader(header: string): Map<string, string> {\n const map = new Map<string, string>();\n if (!header) return map;\n\n // cookie.parseCookie returns a plain object with first-wins semantics\n // and uses safeDecodeURIComponent by default (try/catch around\n // decodeURIComponent, falls back to raw). This matches our contract.\n const parsed = parseCookie(header);\n for (const name in parsed) {\n const value = parsed[name];\n if (value !== undefined) map.set(name, value);\n }\n\n return map;\n}\n\n/**\n * Decode a single cookie value with `decodeURIComponent`, falling back to\n * the raw byte sequence if the input contains a malformed `%`-escape.\n *\n * Used by both `parseCookieHeader` (incoming Cookie: header) and the\n * `setRaw` forwarding path (outgoing Set-Cookie from upstream services).\n * Total — never throws.\n *\n * cookie's internal decode has identical semantics but is not exported,\n * so we keep this standalone helper.\n */\nexport function safeDecodeCookieValue(raw: string): string {\n try {\n return decodeURIComponent(raw);\n } catch {\n return raw;\n }\n}\n\n/**\n * Serialize a CookieEntry into a Set-Cookie header value.\n *\n * Total — never throws. If the cookie package's serializer rejects\n * the input (e.g. non-integer maxAge, forbidden chars in name/value),\n * falls back to a minimal hand-rolled serialization so the response\n * path is never interrupted by a codec error.\n */\nexport function serializeCookieEntry(entry: CookieEntry): string {\n try {\n return stringifySetCookie(\n {\n name: entry.name,\n value: entry.value,\n domain: entry.options.domain,\n path: entry.options.path,\n expires: entry.options.expires,\n maxAge: entry.options.maxAge,\n httpOnly: entry.options.httpOnly,\n secure: entry.options.secure,\n sameSite: entry.options.sameSite,\n partitioned: entry.options.partitioned,\n },\n // timber pre-encodes values at the API surface (set() calls\n // encodeURIComponent), so pass identity to avoid double-encoding.\n { encode: (v: string) => v }\n );\n } catch {\n // Fallback: hand-roll a minimal Set-Cookie so we never drop the\n // header entirely. The entry-point validators in cookie-context.ts\n // already reject truly dangerous input — this path only fires for\n // edge-case formatting the upstream serializer is strict about.\n return serializeCookieEntryFallback(entry);\n }\n}\n\nfunction serializeCookieEntryFallback(entry: CookieEntry): string {\n const parts = [`${entry.name}=${entry.value}`];\n const opts = entry.options;\n\n if (opts.domain) parts.push(`Domain=${opts.domain}`);\n if (opts.path) parts.push(`Path=${opts.path}`);\n if (opts.expires) parts.push(`Expires=${opts.expires.toUTCString()}`);\n if (opts.maxAge !== undefined) parts.push(`Max-Age=${opts.maxAge}`);\n if (opts.httpOnly) parts.push('HttpOnly');\n if (opts.secure) parts.push('Secure');\n if (opts.sameSite) {\n parts.push(`SameSite=${opts.sameSite.charAt(0).toUpperCase()}${opts.sameSite.slice(1)}`);\n }\n if (opts.partitioned) parts.push('Partitioned');\n\n return parts.join('; ');\n}\n\n/**\n * Parse a raw `Set-Cookie` header string into name, value, and options.\n * Handles all standard attributes: Path, Domain, Max-Age, Expires,\n * SameSite, Secure, HttpOnly, Partitioned.\n *\n * Does NOT apply DEFAULT_COOKIE_OPTIONS — the caller decides whether\n * to merge defaults (e.g. `set()` does, but `setRaw()` should preserve\n * the original header's intent).\n */\nexport function parseSetCookie(\n header: string\n): { name: string; value: string; options: CookieOptions } | null {\n const parsed = upstreamParseSetCookie(header, {\n // Don't decode — setRaw expects the wire-form value so it can\n // re-emit verbatim and validate against cookie-octet.\n decode: (v: string) => v,\n });\n\n // cookie.parseSetCookie always returns a SetCookie object, but\n // with name/value as empty strings when the header has no `=`.\n if (!parsed.name) return null;\n\n const options: CookieOptions = {};\n\n if (parsed.path !== undefined) options.path = parsed.path || '/';\n if (parsed.domain !== undefined) options.domain = parsed.domain;\n if (parsed.maxAge !== undefined && Number.isFinite(parsed.maxAge)) {\n options.maxAge = parsed.maxAge;\n }\n if (parsed.expires !== undefined) options.expires = parsed.expires;\n if (parsed.sameSite !== undefined && parsed.sameSite !== true) {\n const sameSite = (parsed.sameSite as string).toLowerCase();\n if (sameSite === 'strict' || sameSite === 'lax' || sameSite === 'none') {\n options.sameSite = sameSite;\n }\n }\n if (parsed.secure) options.secure = true;\n if (parsed.httpOnly) options.httpOnly = true;\n if (parsed.partitioned) options.partitioned = true;\n\n return { name: parsed.name, value: parsed.value ?? '', options };\n}\n","/**\n * Cookie Context — per-request cookie API and on-the-wire helpers.\n *\n * Split out of `request-context.ts` (TIM-853) so the cookie subsystem\n * — encoding contract, options grammar, parser, serializer, and RYW map\n * — lives in one file. The headers/scope/params APIs\n * stay in `request-context.ts` and call into this module via the\n * exported helpers.\n *\n * See design/29-cookies.md for the encoding contract and read-your-own-\n * writes semantics. See ONGOING_SECURITY.md H-3 (TIM-868) for the\n * smuggling primitive that the encoding contract closes.\n */\n\nimport { requestContextAls, type RequestContextStore } from './als-registry.ts';\nimport { isDebug } from './debug.ts';\nimport {\n ANY_COOKIE,\n noteCookieReadForReactCache,\n warnIfCachedCookieIsWritten,\n} from './react-cache-scope.ts';\nimport {\n assertValidCookieName,\n assertValidCookieValue,\n assertValidCookieOptions,\n} from '../cookies/validation.ts';\nimport {\n parseCookieHeader,\n parseSetCookie,\n safeDecodeCookieValue,\n serializeCookieEntry,\n} from './cookie-parsing.ts';\n\n// Re-export the validators so framework-internal consumers and tests can\n// import the canonical implementation from the same module that hosts\n// `getCookies()`. The pure shared module lives in `cookies/validation.ts`\n// so the client `useCookie` hook can use the same checks without pulling\n// in the server ALS code.\nexport { assertValidCookieName, assertValidCookieValue, assertValidCookieOptions };\n\n// ─── Public API ───────────────────────────────────────────────────────────\n\n/**\n * Returns a cookie accessor for the current request.\n *\n * Available in middleware, access checks, server components, and server actions.\n * Throws if called outside a request context (security principle #2: no global fallback).\n *\n * Read methods (.get, .has, .getAll) are always available and reflect\n * read-your-own-writes from .set() calls in the same request.\n *\n * Mutation methods (.set, .delete, .clear) are only available in mutable\n * contexts (middleware.ts, server actions, route.ts handlers). Calling them\n * in read-only contexts (access.ts, server components) throws.\n *\n * This is the escape hatch for direct cookie jar operations. For typed\n * cookie access, use `defineCookie()` instead.\n *\n * See design/29-cookies.md\n */\nexport function getCookieJar(): RequestCookies {\n const store = requestContextAls.getStore();\n if (!store) {\n throw new Error(\n '[timber] getCookieJar() called outside of a request context. ' +\n 'It can only be used in middleware, access checks, server components, and server actions.'\n );\n }\n\n // Parse cookies lazily on first access\n if (!store.parsedCookies) {\n store.parsedCookies = parseCookieHeader(store.cookieHeader);\n }\n\n const map = store.parsedCookies;\n return {\n // Reads are noted (dev only) so a later write of the same cookie can\n // warn if React.cache may have memoized the old value (TIM-1529 D3).\n get(name: string): string | undefined {\n noteCookieReadForReactCache(name);\n return map.get(name);\n },\n has(name: string): boolean {\n noteCookieReadForReactCache(name);\n return map.has(name);\n },\n getAll(): Array<{ name: string; value: string }> {\n noteCookieReadForReactCache(ANY_COOKIE);\n return Array.from(map.entries()).map(([name, value]) => ({ name, value }));\n },\n get size(): number {\n noteCookieReadForReactCache(ANY_COOKIE);\n return map.size;\n },\n\n set(name: string, value: string, options?: SetCookieOptions): void {\n assertMutable(store, 'set');\n // Validate the name first — names cannot be URL-encoded (RFC 7230\n // token grammar is strict), so a bad name is always a bug.\n assertValidCookieName(name);\n // Type guard with a guiding error. The single most common mistake\n // is passing a non-string (object, number, Date) and expecting the\n // framework to JSON-encode. Point developers at jsonCookieCodec.\n if (typeof value !== 'string') {\n throw new Error(\n `[timber] getCookieJar().set(${JSON.stringify(name)}, …): value must be a string, got ${typeof value}.\\n` +\n ` To store a JSON-serializable value, use defineCookie + jsonCookieCodec:\\n` +\n `\\n` +\n ` import { defineCookie, jsonCookieCodec } from '@timber-js/app/cookies';\\n` +\n `\\n` +\n ` export const ${name}Cookie = defineCookie(${JSON.stringify(name)}, {\\n` +\n ` codec: jsonCookieCodec(),\\n` +\n ` });\\n` +\n `\\n` +\n ` ${name}Cookie.set(value);\\n` +\n `\\n` +\n ` See design/29-cookies.md §\"Typed Cookies with Schema Validation\".`\n );\n }\n // Encode the value so the on-the-wire bytes always satisfy\n // RFC 6265 §4.1.1 cookie-octet. encodeURIComponent's output is a\n // strict subset of cookie-octet (only `A-Z a-z 0-9 ! ' ( ) * - . _\n // ~ %`), so the encoded form can never carry the H-3 smuggling\n // primitive — `;` becomes `%3B`, CR/LF become `%0D`/`%0A`, etc.\n // The round-trip is lossless: parseCookieHeader auto-decodes on\n // read, so `cookies().get(name)` returns exactly `value`. See\n // ONGOING_SECURITY.md H-3 (TIM-868) and design/29-cookies.md\n // §\"Encoding Contract\".\n //\n // The `{ raw: true }` opt-out skips the encoder for callers who\n // need exact byte control (e.g. forwarding pre-encoded cookies\n // from an upstream service). The opt-out goes through the strict\n // cookie-octet validator instead — the smuggling primitive cannot\n // sneak in via the escape hatch.\n const raw = options?.raw === true;\n const wireValue = raw ? value : encodeURIComponent(value);\n if (raw) {\n assertValidCookieValue(name, wireValue);\n }\n if (store.flushed) {\n if (isDebug()) {\n console.warn(\n `[timber] warn: getCookieJar().set('${name}') called after response headers were committed.\\n` +\n ` The cookie will NOT be sent. Move cookie mutations to middleware.ts, a server action,\\n` +\n ` or a route.ts handler.`\n );\n }\n return;\n }\n // Strip the framework-only `raw` flag before persisting — it is\n // not an HTTP cookie attribute and must not leak into the jar.\n const { raw: _raw, ...attributeOptions } = options ?? {};\n void _raw;\n const opts = { ...DEFAULT_COOKIE_OPTIONS, ...attributeOptions };\n assertValidCookieOptions(opts);\n store.cookieJar.set(name, { name, value: wireValue, options: opts });\n // Read-your-own-writes: store the DECODED logical value so that\n // subsequent `cookies().get(name)` in the same request returns\n // exactly what the developer wrote — never the encoded form.\n // For `{ raw: true }`, the wire form IS the logical form.\n map.set(name, raw ? wireValue : value);\n warnIfCachedCookieIsWritten(name);\n },\n\n setFromHeaders(headers: Headers): void {\n assertMutable(store, 'setFromHeaders');\n if (store.flushed) {\n console.warn(\n `[timber] warn: getCookieJar().setFromHeaders() called after response headers were committed.\\n` +\n ` The cookies will NOT be sent. Move cookie mutations to middleware.ts, a server action,\\n` +\n ` or a route.ts handler.`\n );\n return;\n }\n // Headers.getSetCookie() returns individual Set-Cookie strings,\n // avoiding the fragile comma-splitting that raw .get() requires.\n for (const raw of headers.getSetCookie()) {\n const parsed = parseSetCookie(raw);\n if (parsed) {\n // Use setRaw to preserve the original header's attributes without\n // merging DEFAULT_COOKIE_OPTIONS (parseSetCookie intentionally\n // does not apply defaults — see its doc comment).\n setRaw(store, map, parsed.name, parsed.value, parsed.options);\n }\n }\n },\n\n delete(name: string, options?: Pick<CookieOptions, 'path' | 'domain'>): void {\n assertMutable(store, 'delete');\n // Validate the name even though delete writes an empty value — a\n // smuggled name (`;` or CR/LF) would corrupt the Set-Cookie header\n // we emit. See ONGOING_SECURITY.md H-3 (TIM-868).\n assertValidCookieName(name);\n if (store.flushed) {\n if (isDebug()) {\n console.warn(\n `[timber] warn: getCookieJar().delete('${name}') called after response headers were committed.\\n` +\n ` The cookie will NOT be deleted. Move cookie mutations to middleware.ts, a server action,\\n` +\n ` or a route.ts handler.`\n );\n }\n return;\n }\n const opts: CookieOptions = {\n ...DEFAULT_COOKIE_OPTIONS,\n ...options,\n maxAge: 0,\n expires: new Date(0),\n };\n // delete() is a jar entry point like set() — caller-supplied\n // path/domain are serialized verbatim into the Set-Cookie header,\n // so they must pass the same attribute-injection guard. See\n // design/29-cookies.md §\"Cookie Attribute Validation\" (TIM-1026).\n assertValidCookieOptions(opts);\n store.cookieJar.set(name, { name, value: '', options: opts });\n // Remove from read view\n map.delete(name);\n warnIfCachedCookieIsWritten(name);\n },\n\n clear(): void {\n assertMutable(store, 'clear');\n if (store.flushed) return;\n // Delete every incoming cookie\n for (const name of Array.from(map.keys())) {\n store.cookieJar.set(name, {\n name,\n value: '',\n options: { ...DEFAULT_COOKIE_OPTIONS, maxAge: 0, expires: new Date(0) },\n });\n }\n map.clear();\n warnIfCachedCookieIsWritten(ANY_COOKIE);\n },\n\n toString(): string {\n noteCookieReadForReactCache(ANY_COOKIE);\n // Re-encode values when serializing as a Cookie header — the\n // RYW map holds decoded logical values, but a Cookie header has\n // to satisfy `cookie-octet`. Mirror the auto-encode contract on\n // `set()` so toString() round-trips losslessly with parseCookieHeader.\n return Array.from(map.entries())\n .map(([name, value]) => `${name}=${encodeURIComponent(value)}`)\n .join('; ');\n },\n };\n}\n\n/**\n * Returns the value of a single cookie, or undefined if absent.\n *\n * @internal — not part of the public API. Use `defineCookie().get()` or `getCookieJar().get()` instead.\n */\nexport function getCookie(name: string): string | undefined {\n const jar = getCookieJar();\n return jar.get(name);\n}\n\n// ─── Types ────────────────────────────────────────────────────────────────\n\n/**\n * Per-call options for `getCookies().set()`. Extends the persistent\n * `CookieOptions` (HTTP cookie attributes) with framework-only flags\n * that are NOT serialized into the Set-Cookie header.\n *\n * The `raw` flag is the escape hatch for the auto-encoding contract.\n * See design/29-cookies.md §\"Encoding Contract\".\n */\nexport interface SetCookieOptions extends CookieOptions {\n /**\n * Skip the framework's `encodeURIComponent` pass and store the value\n * verbatim. The value is then validated against the strict RFC 6265\n * §4.1.1 `cookie-octet` grammar — the H-3 smuggling primitive cannot\n * sneak in via this opt-out.\n *\n * Use this when forwarding a cookie value that is already in its\n * intended on-the-wire form (e.g. mirroring an upstream service's\n * Set-Cookie). Default: `false` (auto-encode).\n */\n raw?: boolean;\n}\n\n/** Options for setting a cookie. See design/29-cookies.md. */\nexport interface CookieOptions {\n /** Domain scope. Default: omitted (current domain only). */\n domain?: string;\n /** URL path scope. Default: '/'. */\n path?: string;\n /** Expiration date. Mutually exclusive with maxAge. */\n expires?: Date;\n /** Max age in seconds. Mutually exclusive with expires. */\n maxAge?: number;\n /** Prevent client-side JS access. Default: true. */\n httpOnly?: boolean;\n /** Only send over HTTPS. Default: true. */\n secure?: boolean;\n /** Cross-site request policy. Default: 'lax'. */\n sameSite?: 'strict' | 'lax' | 'none';\n /** Partitioned (CHIPS) — isolate cookie per top-level site. Default: false. */\n partitioned?: boolean;\n}\n\n/**\n * Cookie accessor returned by `getCookies()`.\n *\n * Read methods are always available. Mutation methods throw in read-only\n * contexts (access.ts, server components).\n */\nexport interface RequestCookies {\n /** Get a cookie value by name. Returns undefined if not present. */\n get(name: string): string | undefined;\n /** Check if a cookie exists. */\n has(name: string): boolean;\n /** Get all cookies as an array of { name, value } pairs. */\n getAll(): Array<{ name: string; value: string }>;\n /** Number of cookies. */\n readonly size: number;\n /**\n * Set a cookie. Only available in mutable contexts (middleware, actions,\n * route handlers).\n *\n * The value is auto-encoded with `encodeURIComponent` so the on-the-wire\n * bytes always satisfy RFC 6265 §4.1.1 cookie-octet — `cookies().get()`\n * returns the same logical value the developer wrote. Pass `{ raw: true }`\n * to skip the encoder; the raw path validates against the strict\n * cookie-octet grammar instead. See design/29-cookies.md §\"Encoding\n * Contract\" and ONGOING_SECURITY.md H-3 (TIM-868).\n */\n set(name: string, value: string, options?: SetCookieOptions): void;\n /**\n * Copy all `Set-Cookie` headers from a `Headers` object.\n * Parses each header and forwards name, value, and all attributes\n * (path, domain, max-age, expires, sameSite, secure, httpOnly, partitioned).\n *\n * Useful when forwarding cookies from an internal `fetch()` or auth handler:\n * ```ts\n * const response = await auth.handler(req);\n * getCookies().then(c => c.setFromHeaders(response.headers));\n * ```\n */\n setFromHeaders(headers: Headers): void;\n /** Delete a cookie. Only available in mutable contexts. */\n delete(name: string, options?: Pick<CookieOptions, 'path' | 'domain'>): void;\n /** Delete all cookies. Only available in mutable contexts. */\n clear(): void;\n /** Serialize cookies as a Cookie header string. */\n toString(): string;\n}\n\nconst DEFAULT_COOKIE_OPTIONS: CookieOptions = {\n path: '/',\n httpOnly: true,\n secure: true,\n sameSite: 'lax',\n};\n\n// ─── Framework-Internal Helpers ───────────────────────────────────────────\n\n/**\n * Build a Map of cookie name → value reflecting the current request's\n * read-your-own-writes state. Includes incoming cookies plus any\n * mutations from getCookies().set() / getCookies().delete() in the same request.\n *\n * Used by SSR renderers to populate NavContext.cookies so that\n * useCookie()'s server snapshot matches the actual response state.\n *\n * See design/29-cookies.md §\"Read-Your-Own-Writes\"\n * See design/triage/TIM-441-cookie-api-triage.md §4\n */\nexport function getCookiesForSsr(): Map<string, string> {\n const store = requestContextAls.getStore();\n if (!store) {\n throw new Error('[timber] getCookiesForSsr() called outside of a request context.');\n }\n\n // Trigger lazy parsing if not yet done\n if (!store.parsedCookies) {\n store.parsedCookies = parseCookieHeader(store.cookieHeader);\n }\n\n // The parsedCookies map already reflects read-your-own-writes:\n // - getCookies().set() updates the map via map.set(name, value)\n // - getCookies().delete() removes from the map via map.delete(name)\n // Return a copy so callers can't mutate the internal map.\n return new Map(store.parsedCookies);\n}\n\n/**\n * Collect all Set-Cookie headers from the cookie jar.\n * Called by the framework at flush time to apply cookies to the response.\n *\n * Returns an array of serialized Set-Cookie header values.\n */\nexport function getSetCookieHeaders(): string[] {\n const store = requestContextAls.getStore();\n if (!store) return [];\n return Array.from(store.cookieJar.values()).map(serializeCookieEntry);\n}\n\n// ─── Cookie Helpers ───────────────────────────────────────────────────────\n\n/** Throw if cookie mutation is attempted in a read-only context. */\nfunction assertMutable(store: RequestContextStore, method: string): void {\n if (!store.mutableContext) {\n throw new Error(\n `[timber] getCookieJar().${method}() cannot be called in this context.\\n` +\n ` Set cookies in middleware.ts, server actions, or route.ts handlers.`\n );\n }\n}\n\n/**\n * Write a cookie to the jar WITHOUT merging DEFAULT_COOKIE_OPTIONS.\n * Used by setFromHeaders to preserve the original header's attributes exactly.\n *\n * For deletion cookies (maxAge=0), the jar entry is still created so the\n * Set-Cookie header is emitted, but the cookie is NOT added to the read map\n * (it would be misleading — the cookie is being deleted).\n */\nfunction setRaw(\n store: RequestContextStore,\n readMap: Map<string, string>,\n name: string,\n value: string,\n options: CookieOptions\n): void {\n // setRaw is the forwarding path for upstream Set-Cookie headers\n // (`getCookies().setFromHeaders(response.headers)`). The value comes\n // out of `parseSetCookie` in its on-the-wire form — already encoded\n // by whoever produced it — so we re-emit it verbatim into our jar.\n // We DO validate against the strict cookie-octet grammar, both as\n // defense-in-depth against a malicious upstream and to keep the\n // ONGOING_SECURITY.md H-3 invariant intact at every entry point into\n // the cookie jar / RYW map.\n assertValidCookieName(name);\n assertValidCookieValue(name, value);\n // Options get the same entry-point guard as set()/delete(). For the\n // setFromHeaders path this can only fire on attributes parseSetCookie\n // cannot produce (it splits on `;` and normalizes Max-Age/SameSite),\n // but setRaw is the jar entry point — the invariant lives here, not in\n // the caller. See design/29-cookies.md §\"Cookie Attribute Validation\".\n assertValidCookieOptions(options);\n store.cookieJar.set(name, { name, value, options });\n warnIfCachedCookieIsWritten(name);\n // Deletion cookies (Max-Age=0) should not appear in the read map.\n if (options.maxAge === 0) {\n readMap.delete(name);\n } else {\n // Decode for the RYW map so consumers see the same logical bytes\n // they would see if the upstream cookie had arrived on the next\n // request. Mirrors `parseCookieHeader`'s auto-decode.\n readMap.set(name, safeDecodeCookieValue(value));\n }\n}\n","// Server-side primitives: deny, redirect, redirectExternal, waitUntil\n//\n// These are the core runtime signals that components, middleware, and access gates\n// use to control request flow. See design/10-error-handling.md.\n\nimport type { JsonSerializable } from './types.ts';\nimport { getWaitUntil as _getWaitUntil } from './waituntil-bridge.ts';\nimport { isDebug } from './debug.ts';\nimport { getRequestSearchString } from './request-context.ts';\nimport { mergePreservedSearchParams } from '../shared/merge-search-params.ts';\nimport { DENY_BRAND, REDIRECT_BRAND } from './signal-identity.ts';\nimport {\n assertRelativeRedirectPath,\n validateExternalRedirectUrl,\n} from '../shared/href-validation.ts';\n\n// ─── Dev-mode validation ────────────────────────────────────────────────────\n\n/**\n * Check if a value is JSON-serializable without data loss.\n * Returns a description of the first non-serializable value found, or null if OK.\n *\n * @internal Exported for testing only.\n */\nexport function findNonSerializable(value: unknown, path = 'data'): string | null {\n if (value === null || value === undefined) return null;\n\n switch (typeof value) {\n case 'string':\n case 'number':\n case 'boolean':\n return null;\n case 'bigint':\n return `${path} contains a BigInt — BigInt throws in JSON.stringify`;\n case 'function':\n return `${path} is a function — functions are not JSON-serializable`;\n case 'symbol':\n return `${path} is a symbol — symbols are not JSON-serializable`;\n case 'object':\n break;\n default:\n return `${path} has unsupported type \"${typeof value}\"`;\n }\n\n if (value instanceof Date) {\n return `${path} is a Date — Dates silently coerce to strings in JSON.stringify`;\n }\n if (value instanceof Map) {\n return `${path} is a Map — Maps serialize as {} in JSON.stringify (data loss)`;\n }\n if (value instanceof Set) {\n return `${path} is a Set — Sets serialize as {} in JSON.stringify (data loss)`;\n }\n if (value instanceof RegExp) {\n return `${path} is a RegExp — RegExps serialize as {} in JSON.stringify`;\n }\n if (value instanceof Error) {\n return `${path} is an Error — Errors serialize as {} in JSON.stringify`;\n }\n\n if (Array.isArray(value)) {\n for (let i = 0; i < value.length; i++) {\n const result = findNonSerializable(value[i], `${path}[${i}]`);\n if (result) return result;\n }\n return null;\n }\n\n // Plain object — only Object.prototype is safe. Null-prototype objects\n // (Object.create(null)) survive JSON.stringify but React Flight rejects\n // them with \"Classes or null prototypes are not supported\", so the\n // pre-flush deny path (renderDenyPage → renderToReadableStream) would throw.\n const proto = Object.getPrototypeOf(value);\n if (proto === null) {\n return `${path} is a null-prototype object — React Flight rejects null prototypes`;\n }\n if (proto !== Object.prototype) {\n const name = (value as object).constructor?.name ?? 'unknown';\n return `${path} is a ${name} instance — class instances may lose data in JSON.stringify`;\n }\n\n for (const key of Object.keys(value as Record<string, unknown>)) {\n const result = findNonSerializable((value as Record<string, unknown>)[key], `${path}.${key}`);\n if (result) return result;\n }\n return null;\n}\n\n/**\n * Emit a dev-mode warning if data is not JSON-serializable.\n * No-op in production.\n */\nfunction warnIfNotSerializable(data: unknown, callerName: string): void {\n if (!isDebug()) return;\n if (data === undefined) return;\n\n const issue = findNonSerializable(data);\n if (issue) {\n console.warn(\n `[timber] ${callerName}: ${issue}. ` +\n 'Data passed to deny() must be JSON-serializable because ' +\n 'the post-flush path uses JSON.stringify, not React Flight.'\n );\n }\n}\n\n// ─── DenySignal ─────────────────────────────────────────────────────────────\n\n/**\n * Render-phase signal thrown by `deny()`. Caught by the framework to produce\n * the correct HTTP status code (segment context) or graceful degradation (slot context).\n *\n * Detect with `isDenySignal()`, never `instanceof` — see \"Signal branding\" in signal-identity.ts.\n */\nexport class DenySignal extends Error {\n readonly [DENY_BRAND] = true;\n readonly status: number;\n readonly data: JsonSerializable | undefined;\n\n /**\n * Ordered list of segment keys that own matching deny pages for this\n * signal, best match first. Present = addressed (a boundary should\n * render it); absent = unplaced (the re-render fallback serves it).\n *\n * In-tree hoists stamp a single-element list (`[entry.ownerKey]`) —\n * identical to the pre-TIM-1450 `ownerKey`. Late addressing (TIM-1450)\n * stamps the full candidate list so the client can find the first\n * *reachable* owner via its ancestry context, eliminating the\n * owner-below-throw-site escape.\n *\n * See design/04-authorization.md §\"Where a Deny Page Renders\", TIM-1356.\n */\n owners?: string[];\n\n /**\n * When true, the pipeline must respond with `rscErrorEnvelope` so the\n * client hard-navigates instead of attempting to render a deny page\n * from the RSC payload. Set by AccessGate when a skipped segment\n * denies — rendering the deny page in-tree would appear inside the\n * client's cached layout chrome (TIM-1074). See TIM-1363.\n */\n _hardNavigate?: boolean;\n\n constructor(status: number, data?: JsonSerializable) {\n super(`Access denied with status ${status}`);\n this.name = 'DenySignal';\n this.status = status;\n this.data = data;\n }\n\n /**\n * Extract the file that called deny() from the stack trace.\n * Returns a short path (e.g. \"app/auth/access.ts\") or undefined if\n * the stack can't be parsed. Dev-only — used for dev log output.\n */\n get sourceFile(): string | undefined {\n if (!this.stack) return undefined;\n const frames = this.stack.split('\\n');\n // Skip the Error line and the deny() frame — the caller is the 3rd line.\n // Stack format: \" at FnName (file:line:col)\" or \" at file:line:col\"\n for (let i = 2; i < frames.length; i++) {\n const frame = frames[i];\n if (!frame) continue;\n // Skip framework internals\n if (frame.includes('primitives.ts') || frame.includes('node_modules')) continue;\n // Extract file path from the frame\n const match =\n frame.match(/\\(([^)]+?)(?::\\d+:\\d+)\\)/) ?? frame.match(/at\\s+([^\\s]+?)(?::\\d+:\\d+)/);\n if (match?.[1]) {\n // Shorten to app-relative path\n const full = match[1];\n const appIdx = full.indexOf('/app/');\n return appIdx >= 0 ? full.slice(appIdx + 1) : full;\n }\n }\n return undefined;\n }\n}\n\n/** Options for deny(). */\nexport interface DenyOptions {\n /** Human-readable message (logged server-side, not sent to client). */\n message?: string;\n /**\n * JSON-serializable data forwarded as the `data` prop to status-code files\n * and `denied.tsx`. Named `dangerouslyPassData` because this data crosses\n * the RSC → client serialization boundary — do not pass sensitive server\n * state (tokens, internal IDs, database rows).\n */\n dangerouslyPassData?: JsonSerializable;\n}\n\n/**\n * Universal denial/error primitive. Throws a `DenySignal` that the framework catches.\n *\n * - In segment context (outside Suspense): produces HTTP status code\n * - In slot context: graceful degradation → denied.tsx → default.tsx → null\n * - Inside Suspense (hold window): promoted to pre-flush behavior\n * - Inside Suspense (after flush): error boundary + noindex meta\n *\n * ```ts\n * deny() // 403 (default)\n * deny(404) // 404\n * deny(503, { message: 'Maintenance' }) // server-only log message\n * deny(404, { dangerouslyPassData: { resourceId: params.id } }) // explicit client opt-in\n * ```\n *\n * Accepts any 4xx or 5xx status code — it is also how a page renders a 5xx\n * status file with data. An unplanned throw needs no primitive: it renders\n * the error page with a 500.\n *\n * @param status - HTTP status code (4xx or 5xx). Default: 403.\n * @param options - Optional message and/or data to pass to the client.\n */\nexport function deny(status?: number, options?: DenyOptions): never {\n const resolvedStatus = status ?? 403;\n const resolvedData = options?.dangerouslyPassData;\n\n if (resolvedStatus < 400 || resolvedStatus > 599) {\n throw new Error(`deny() requires a 4xx or 5xx status code, got ${resolvedStatus}.`);\n }\n warnIfNotSerializable(resolvedData, 'deny()');\n throw new DenySignal(resolvedStatus, resolvedData);\n}\n\n// Single source of truth shared with the client next/navigation shim —\n// see shared/redirect-type.ts.\nexport { RedirectType } from '../shared/redirect-type.ts';\n\n// ─── RedirectSignal ─────────────────────────────────────────────────────────\n\n/**\n * Render-phase signal thrown by `redirect()` and `redirectExternal()`.\n * Caught by the framework to produce a 3xx response or client-side navigation.\n *\n * Detect with `isRedirectSignal()`, never `instanceof` — see \"Signal branding\" in signal-identity.ts.\n */\nexport class RedirectSignal extends Error {\n readonly [REDIRECT_BRAND] = true;\n readonly location: string;\n readonly status: number;\n\n constructor(location: string, status: number) {\n super(`Redirect to ${location}`);\n this.name = 'RedirectSignal';\n this.location = location;\n this.status = status;\n }\n}\n\n// ─── Signal Detection ───────────────────────────────────────────────────────\n\n/**\n * Options for redirect() — alternative to passing a bare status code.\n */\nexport interface RedirectOptions {\n /** HTTP redirect status code (3xx). Defaults to 302 (or 308 when `permanent: true`). */\n status?: number;\n /**\n * When true, defaults the status to 308 (Permanent Redirect, preserves HTTP method).\n * If `status` is also provided, `status` takes precedence.\n *\n * @example\n * redirect('/new-path', { permanent: true }); // 308\n * redirect('/new-path', { permanent: true, status: 301 }); // 301\n */\n permanent?: boolean;\n /**\n * Preserve search params from the current request URL on the redirect target.\n *\n * - `true` — preserve ALL current search params (target params take precedence)\n * - `string[]` — preserve only the named params (e.g. `['private', 'token']`)\n *\n * Target path's own query params always take precedence over preserved ones.\n */\n preserveSearchParams?: true | string[];\n}\n\n/**\n * Redirect to a relative path. Rejects absolute and protocol-relative URLs.\n * Use `redirectExternal()` for external redirects with an allow-list.\n *\n * @param path - Relative path (e.g. '/login', 'settings', '/login?returnTo=/dash')\n * @param statusOrOptions - HTTP status code (3xx, default 302) or options object.\n *\n * @example\n * // Simple redirect\n * redirect('/login');\n *\n * // With status code\n * redirect('/login', 301);\n *\n * // With preserved search params\n * redirect(`/docs/${version}/${slug}`, { preserveSearchParams: ['foo'] });\n */\nexport function redirect(path: string, statusOrOptions?: number | RedirectOptions): never {\n let status: number;\n let preserveSearchParams: true | string[] | undefined;\n\n if (typeof statusOrOptions === 'number') {\n status = statusOrOptions;\n } else if (statusOrOptions) {\n // Explicit status wins. Otherwise permanent: true → 308, default → 302.\n status = statusOrOptions.status ?? (statusOrOptions.permanent ? 308 : 302);\n preserveSearchParams = statusOrOptions.preserveSearchParams;\n } else {\n status = 302;\n }\n\n if (status < 300 || status > 399) {\n throw new Error(`redirect() requires a 3xx status code, got ${status}.`);\n }\n // Relative-only validation shared with the client next/navigation shim —\n // strips C0 controls and normalizes backslashes before the scheme check.\n assertRelativeRedirectPath(path);\n\n let resolvedPath = path;\n if (preserveSearchParams) {\n const currentSearch = getRequestSearchString();\n resolvedPath = mergePreservedSearchParams(path, currentSearch, preserveSearchParams);\n }\n\n throw new RedirectSignal(resolvedPath, status);\n}\n\n/**\n * Redirect to an external URL. The origin must be in the provided allow-list.\n *\n * Only http: and https: schemes are permitted. The allow-list is matched\n * against full origins (scheme + host + port), not bare hostnames.\n *\n * @param url - Absolute URL to redirect to.\n * @param allowList - Array of allowed origins (e.g. ['https://example.com', 'https://auth.example.com']).\n * @param status - HTTP redirect status code (3xx). Defaults to 302.\n */\nexport function redirectExternal(url: string, allowList: string[], status: number = 302): never {\n if (status < 300 || status > 399) {\n throw new Error(`redirectExternal() requires a 3xx status code, got ${status}.`);\n }\n\n const canonicalUrl = validateExternalRedirectUrl(url, allowList);\n throw new RedirectSignal(canonicalUrl, status);\n}\n\n// ─── waitUntil ──────────────────────────────────────────────────────────────\n\n// Intentional per-app singleton — warn-once flag that persists for the\n// lifetime of the process/isolate. Not per-request; do not migrate to ALS.\nlet _waitUntilWarned = false;\n\n/**\n * Register a promise to be kept alive after the response is sent.\n * Maps to `ctx.waitUntil()` on Cloudflare Workers and similar platforms.\n *\n * The platform adapter installs a per-request waitUntil function via ALS\n * (see waituntil-bridge.ts). If no ALS handler is available, a warning\n * is logged once and the promise is left to resolve (or reject) without\n * being tracked.\n *\n * @param promise - The background work to keep alive.\n */\nexport function waitUntil(promise: Promise<unknown>): void {\n const alsFn = _getWaitUntil();\n if (alsFn) {\n alsFn(promise);\n return;\n }\n\n if (!_waitUntilWarned) {\n _waitUntilWarned = true;\n console.warn(\n '[timber] waitUntil() is not supported by the current adapter. ' +\n 'Background work will not be tracked. This warning is shown once.'\n );\n }\n}\n\n/**\n * Reset the waitUntil warning state. Exported for testing only.\n * @internal\n */\nexport function _resetWaitUntilWarning(): void {\n _waitUntilWarned = false;\n}\n","/**\n * FormData preprocessing — schema-agnostic conversion of FormData to typed objects.\n *\n * FormData is all strings. Schema validation expects typed values. This module\n * bridges the gap with intelligent coercion that runs *before* schema validation.\n *\n * Inspired by zod-form-data, but schema-agnostic — works with any Standard Schema\n * library (Zod, Valibot, ArkType).\n *\n * See design/08-forms-and-actions.md §\"parseFormData() and coerce helpers\"\n */\n\n// ─── parseFormData ───────────────────────────────────────────────────────\n\n/**\n * Convert FormData into a plain object with intelligent coercion.\n *\n * Handles:\n * - **Duplicate keys → arrays**: `tags=js&tags=ts` → `{ tags: [\"js\", \"ts\"] }`\n * - **Nested dot-paths**: `user.name=Alice` → `{ user: { name: \"Alice\" } }`\n * - **Indexed lists → arrays**: `rows.0.name=A&rows.1.name=B` →\n * `{ rows: [{ name: \"A\" }, { name: \"B\" }] }`, when the indexes are exactly\n * `0..n-1`. A list with a gap stays an object keyed by index.\n * - **Empty strings stay `\"\"`**: a blank text input is `\"\"`, so\n * `z.string().min(1, 'Required')` reports its own message. Use\n * `coerce.text` to make a blank optional field `undefined`\n * - **Empty Files → undefined**: File inputs with no selection become `undefined`\n * - **Strips `$ACTION_*` fields**: React's internal hidden fields are excluded\n * - **Drops `__proto__` paths and names deeper than 32 segments**\n *\n * A field's shape follows its count: a name sent once is a scalar, several\n * times an array, never at all absent. A `createActionClient` action with a\n * schema then gives every field the schema declares as a list one shape\n * (`normalizeListFields` in `schema-introspection.ts`). A raw call, and a raw\n * `'use server'` action that calls this itself, keep the count-dependent\n * shape.\n */\nexport function parseFormData(formData: FormData): Record<string, unknown> {\n const flat: Record<string, unknown> = {};\n\n for (const key of new Set(formData.keys())) {\n // Skip React internal fields\n if (key.startsWith('$ACTION_')) continue;\n\n // Skip prototype-pollution keys at the top level — assigning to\n // `flat['__proto__']` invokes the prototype setter and can splice\n // attacker-controlled data into `flat`'s prototype chain.\n // The dot-path case is filtered separately in `expandDotPaths`.\n if (DANGEROUS_KEYS.has(key)) continue;\n\n const values = formData.getAll(key);\n const processed = values.map(normalizeValue);\n\n if (processed.length === 1) {\n flat[key] = processed[0];\n } else {\n // Filter out undefined (empty Files) and empty strings from multi-value fields.\n // Multi-value fields (e.g. tags=js&tags=&tags=ts) should not include blanks.\n flat[key] = processed.filter((v) => v !== undefined && v !== '');\n }\n }\n\n // Expand dot-notation paths into nested objects\n return expandDotPaths(flat);\n}\n\n/**\n * Normalize a single FormData entry value.\n * - Empty File objects (no selection) → undefined\n * - Strings pass through as-is (empty strings stay as empty strings so\n * schema validators like `z.string().min(1, 'Required')` can produce\n * their custom error messages instead of a generic type mismatch)\n * - Everything else passes through as-is\n */\nfunction normalizeValue(value: FormDataEntryValue): unknown {\n // File input with no selection: browsers submit a File with name=\"\" and size=0\n if (value instanceof File && value.size === 0 && value.name === '') {\n return undefined;\n }\n\n return value;\n}\n\n/**\n * Expand dot-notation keys into nested objects.\n * `{ \"user.name\": \"Alice\", \"user.age\": \"30\" }` → `{ user: { name: \"Alice\", age: \"30\" } }`\n *\n * Keys without dots are left as-is. Bracket notation (e.g. `items[0]`) is NOT\n * supported — use dot notation (`items.0`) instead.\n */\nfunction expandDotPaths(flat: Record<string, unknown>): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n let hasDotPaths = false;\n\n // First pass: check if any keys have dots\n for (const key of Object.keys(flat)) {\n if (key.includes('.')) {\n hasDotPaths = true;\n break;\n }\n }\n\n // Fast path: no dot-notation keys, return as-is.\n // Top-level dangerous keys are already filtered in `parseFormData` above.\n if (!hasDotPaths) return flat;\n\n for (const [key, value] of Object.entries(flat)) {\n // Reject any path that contains __proto__ / constructor / prototype.\n // Without this, `__proto__.x=1` writes to Object.prototype because\n // `result['__proto__']` resolves to the prototype object itself.\n const parts = key.split('.');\n if (parts.some((p) => DANGEROUS_KEYS.has(p))) continue;\n // Bound the nesting depth. Every walk over the parsed value recurses\n // once per level (list conversion here, then file and sensitive-field\n // stripping and schema validation), and a 10 KB key of 5,000 segments\n // fits well inside the body limits. No form nests this deep.\n if (parts.length > MAX_PATH_DEPTH) continue;\n\n if (parts.length === 1) {\n result[parts[0]] = value;\n continue;\n }\n\n let current: Record<string, unknown> = result;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n // Step only into an object this walk built. Anything else under the\n // name — a string, a File, or an array from a duplicate key\n // (`rows=x&rows=y`) — is replaced: the dot-path takes precedence.\n // Stepping into an array would let `rows.4294967294` set its length\n // to 2^32 - 1, and every later walk (file and sensitive-field\n // stripping) maps over that length (TIM-1573).\n if (!isPlainObject(current[part])) {\n current[part] = {};\n }\n current = current[part] as Record<string, unknown>;\n }\n\n current[parts[parts.length - 1]] = value;\n }\n\n // The top level is always an object: it is the form, not a list.\n for (const [key, value] of Object.entries(result)) {\n if (isPlainObject(value)) result[key] = indexedListsToArrays(value);\n }\n return result;\n}\n\n/**\n * `node`, with every nested object whose keys are exactly `\"0\"..\"n-1\"`\n * turned into an array, depth first. Only a dense, canonical index set\n * converts: `{ \"0\", \"2\" }` (a gap), `{ \"01\" }` and `{ \"0\", \"name\" }` stay\n * objects. So a forged `rows.99999` stays one key instead of allocating a\n * sparse array, and the array's length is bounded by the field count limit.\n *\n * Object.keys lists integer-like keys first, in ascending order, so a dense\n * set reads as `0, 1, … n-1` and `Object.values` is already in index order.\n */\nfunction indexedListsToArrays(node: Record<string, unknown>): Record<string, unknown> | unknown[] {\n for (const [key, value] of Object.entries(node)) {\n if (isPlainObject(value)) node[key] = indexedListsToArrays(value);\n }\n const keys = Object.keys(node);\n const dense = keys.length > 0 && keys.every((key, i) => key === String(i));\n return dense ? Object.values(node) : node;\n}\n\n/** An object the dot-path walk built — not an array, File or other instance. */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return (\n typeof value === 'object' && value !== null && Object.getPrototypeOf(value) === Object.prototype\n );\n}\n\n// `__proto__` is the only key in this parser that escapes the dot-path\n// walk's `typeof !== 'object'` reset: accessing `obj['__proto__']` returns\n// `Object.prototype` (itself an object), so the walk steps into the global\n// prototype and the leaf write mutates it. `constructor` resolves to a\n// function (reset fires) and `prototype` is undefined on fresh objects\n// (reset fires), so neither escapes the walk — they parse as legit nested\n// keys and do not mutate anything global.\nconst DANGEROUS_KEYS = new Set(['__proto__']);\n\n/**\n * The most segments a dot-path field name may have. A deeper name is dropped,\n * like a `__proto__` path, so no walk over the parsed value can exhaust the\n * stack (TIM-1573).\n */\nconst MAX_PATH_DEPTH = 32;\n\n// ─── Coercion Helpers ────────────────────────────────────────────────────\n\n/**\n * Schema-agnostic coercion primitives for common FormData patterns.\n *\n * These are plain transform functions — they compose with any schema library's\n * `transform`/`preprocess` pipeline. In Zod, use `z.preprocess`: it runs on an\n * absent key (an unchecked checkbox), where `z.unknown().transform()` fails\n * with \"expected nonoptional\" before the transform runs.\n *\n * ```ts\n * // Zod\n * z.preprocess(coerce.number, z.number())\n * // Valibot\n * v.pipe(v.unknown(), v.transform(coerce.number), v.number())\n * ```\n */\nexport const coerce = {\n /**\n * Coerce an empty string to undefined for optional text fields.\n * Use with `.optional()` schemas where an empty input means \"not provided\".\n *\n * ```ts\n * // Zod — preprocess, not `z.unknown().transform(…)`: Zod 4 rejects an\n * // absent key before a transform runs (\"expected nonoptional\")\n * z.preprocess(coerce.text, z.string().optional())\n * // Valibot\n * v.pipe(v.unknown(), v.transform(coerce.text), v.optional(v.string()))\n * ```\n */\n text(value: unknown): string | undefined {\n if (value === undefined || value === null || value === '') return undefined;\n if (typeof value === 'string') return value;\n return undefined;\n },\n\n /**\n * Coerce a string to a number.\n * - `\"42\"` → `42`\n * - `\"3.14\"` → `3.14`\n * - `\"\"` / `undefined` / `null` → `undefined`\n * - Non-numeric strings → `undefined` (schema validation will catch this)\n */\n number(value: unknown): number | undefined {\n if (value === undefined || value === null || value === '') return undefined;\n if (typeof value === 'number') return value;\n if (typeof value !== 'string') return undefined;\n const num = Number(value);\n if (Number.isNaN(num)) return undefined;\n return num;\n },\n\n /**\n * Coerce a checkbox value to a boolean.\n * HTML checkboxes submit \"on\" when checked and are absent when unchecked.\n * - `\"on\"` / any truthy string → `true`\n * - `undefined` / `null` / `\"\"` → `false`\n */\n checkbox(value: unknown): boolean {\n if (value === undefined || value === null || value === '') return false;\n if (typeof value === 'boolean') return value;\n // Any non-empty string (typically \"on\") is true\n return typeof value === 'string' && value.length > 0;\n },\n\n /**\n * Parse a JSON string into an object.\n * - Valid JSON string → parsed object\n * - `\"\"` / `undefined` / `null` → `undefined`\n * - Invalid JSON → `undefined` (schema validation will catch this)\n */\n json(value: unknown): unknown {\n if (value === undefined || value === null || value === '') return undefined;\n if (typeof value !== 'string') return value;\n try {\n return JSON.parse(value);\n } catch {\n return undefined;\n }\n },\n\n /**\n * Coerce a date string to a Date object.\n * Handles `<input type=\"date\">` (`\"2024-01-15\"`), `<input type=\"datetime-local\">`\n * (`\"2024-01-15T10:30\"`), and full ISO 8601 strings.\n * - Valid date string → `Date`\n * - `\"\"` / `undefined` / `null` → `undefined`\n * - Invalid date strings → `undefined` (schema validation will catch this)\n * - Impossible dates that `new Date()` silently normalizes (e.g. Feb 31) → `undefined`\n */\n date(value: unknown): Date | undefined {\n if (value === undefined || value === null || value === '') return undefined;\n if (value instanceof Date) return value;\n if (typeof value !== 'string') return undefined;\n const date = new Date(value);\n if (Number.isNaN(date.getTime())) return undefined;\n\n // Overflow detection: extract Y/M/D from the input string and verify\n // they match the parsed Date components. new Date('2024-02-31') silently\n // normalizes to March 2nd — we reject such inputs.\n const ymdMatch = value.match(/^(\\d{4})-(\\d{2})-(\\d{2})/);\n if (ymdMatch) {\n const inputYear = Number(ymdMatch[1]);\n const inputMonth = Number(ymdMatch[2]);\n const inputDay = Number(ymdMatch[3]);\n\n // Use UTC methods for date-only and Z-suffixed strings to avoid\n // timezone offset shifting the day. For datetime-local (no Z suffix),\n // the Date constructor parses in local time, so use local methods.\n const isUTC = value.length === 10 || value.endsWith('Z');\n const parsedYear = isUTC ? date.getUTCFullYear() : date.getFullYear();\n const parsedMonth = isUTC ? date.getUTCMonth() + 1 : date.getMonth() + 1;\n const parsedDay = isUTC ? date.getUTCDate() : date.getDate();\n\n if (inputYear !== parsedYear || inputMonth !== parsedMonth || inputDay !== parsedDay) {\n return undefined;\n }\n }\n\n return date;\n },\n\n /**\n * Create a File coercion function with optional size and mime type validation.\n * Returns the File if valid, `undefined` otherwise.\n *\n * ```ts\n * // Basic — just checks it's a real File\n * z.preprocess(coerce.file(), z.instanceof(File))\n *\n * // With constraints\n * z.preprocess(\n * coerce.file({ maxSize: 5 * 1024 * 1024, accept: ['image/png', 'image/jpeg'] }),\n * z.instanceof(File)\n * )\n * ```\n */\n file(options?: { maxSize?: number; accept?: string[] }): (value: unknown) => File | undefined {\n return (value: unknown): File | undefined => {\n if (value === undefined || value === null || value === '') return undefined;\n if (!(value instanceof File)) return undefined;\n\n // Empty file input (no selection): browsers submit File with name=\"\" and size=0\n if (value.size === 0 && value.name === '') return undefined;\n\n if (options?.maxSize !== undefined && value.size > options.maxSize) {\n return undefined;\n }\n\n if (options?.accept !== undefined && !options.accept.includes(value.type)) {\n return undefined;\n }\n\n return value;\n };\n },\n};\n","/**\n * Server action primitives: revalidatePath, revalidateTag, and the action handler.\n *\n * - revalidatePath(path) re-renders the route at that path and returns the RSC\n * flight payload for inline reconciliation. Server actions only.\n * - revalidateTag(tag) invalidates timber.cache entries by tag. Callable from\n * any server code: deferred to the end of the action inside one, immediate\n * anywhere else.\n *\n * The action handler processes incoming action requests, validates CSRF,\n * enforces body limits, executes the action, and returns the response\n * (with piggybacked RSC payload if revalidatePath was called).\n *\n * See design/08-forms-and-actions.md\n */\n\nimport { cache } from '../cache/cache-api.ts';\nimport { canonicalize } from './canonicalize.ts';\nimport { isDenySignal, isRedirectSignal } from './signal-identity.ts';\nimport { withSpan } from './tracing.ts';\nimport { revalidationAls, type RevalidationState } from './als-registry.ts';\nimport type { ReactCacheScope } from './react-cache-scope.ts';\n// ─── Types ───────────────────────────────────────────────────────────────\n\n/** Result of rendering a revalidation — payload root before RSC serialization. */\nexport interface RevalidationResult {\n /**\n * The payload root — tree plus the params it rendered with, exactly as an\n * ordinary route payload. The client splits it in `applyActionResult`.\n */\n payload: unknown;\n /**\n * The `React.cache` scope the target route's middleware ran in. The\n * revalidated tree renders in it, so middleware, access.ts and components\n * share one scope — fresh, never the action body's (TIM-1529).\n */\n reactCacheScope: ReactCacheScope;\n}\n\n/** Renderer function that builds a React element tree for a given path. */\nexport type RevalidateRenderer = (path: string) => Promise<RevalidationResult>;\n\n/**\n * Thrown by a `RevalidateRenderer` that decided not to render: the path\n * was rejected, its params failed coercion, or its middleware answered\n * with a `Response` that cannot become an element tree. `executeAction`\n * drops the revalidation — the action result is still delivered, with no\n * `_tree` piggybacked — and, because the drop was a decision, does not\n * return it as an error to report. Identified by `instanceof`, so the\n * message text never reaches clients.\n */\nexport class RevalidationDropped extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'RevalidationDropped';\n }\n}\n\n// Re-export the type from the registry for public API consumers.\nexport type { RevalidationState } from './als-registry.ts';\n\n/** Options for creating the action handler. */\nexport interface ActionHandlerConfig {\n /** Renderer for producing RSC payloads during revalidation. */\n renderer?: RevalidateRenderer;\n /**\n * Pathname of the page the action was submitted from. When set,\n * revalidatePath renders are skipped for non-matching paths — the\n * server cache is already invalidated, so the next navigation fetches\n * fresh data. See TIM-1454.\n */\n requestPathname?: string;\n /** Search string of the action request URL (e.g. `?page=1`). */\n requestSearch?: string;\n}\n\n/** Result of handling a server action request. */\nexport interface ActionHandlerResult {\n /** The action's return value (serialized). */\n actionResult: unknown;\n /** Revalidation result if revalidatePath was called (element tree, not yet serialized). */\n revalidation?: RevalidationResult;\n /**\n * True when `revalidatePath()` was called only for pages other than the\n * current one (TIM-1454). The client then evicts its caches and skips the\n * refresh — nothing on screen was named. Whenever the current page was\n * named this is false, even if other pages were named too: its re-render,\n * or the refresh that replaces a dropped one, re-renders every layout it\n * shares with them. Which paths were named is not reported: the client\n * evicts every cached payload after any revalidation (TIM-1476), so a path\n * list would carry nothing it acts on (TIM-1461).\n */\n onlyOtherPagesNamed: boolean;\n /** Redirect location if a RedirectSignal was thrown during revalidation. */\n redirectTo?: string;\n /** Redirect status code. */\n redirectStatus?: number;\n /**\n * Errors the action survived after its body returned: a `revalidateTag`\n * invalidation that rejected, or a `revalidatePath` render that threw.\n * Each is already logged. They are returned rather than reported here\n * because reporting needs the request, which the caller owns; the caller\n * passes each to `onRequestError` once.\n */\n revalidationErrors: unknown[];\n}\n\n// ─── Revalidation State ──────────────────────────────────────────────────\n\n// Per-request revalidation state stored in AsyncLocalStorage (from als-registry.ts).\n// This ensures concurrent requests never share or overwrite each other's state\n// (the previous module-level global was vulnerable to cross-request pollution).\n\n/**\n * Run `fn` inside a revalidation ALS scope.\n * @internal — for tests that call revalidatePath/Tag directly without executeAction().\n */\nexport function _runWithRevalidationState<T>(state: RevalidationState, fn: () => T): T {\n return revalidationAls.run(state, fn);\n}\n\n// ─── Public API ──────────────────────────────────────────────────────────\n\n/**\n * Re-render the route at `path` and include the RSC flight payload in the\n * action response. The client reconciles inline — no separate fetch needed.\n *\n * Only callable inside a server action: it attaches a render to the action\n * response, and nothing else has one. To refresh cached data from a\n * `route.ts` handler, a webhook, or a job, use `revalidateTag()` or\n * `cache.invalidate()`.\n *\n * @param path - The path to re-render (e.g. '/dashboard', '/todos').\n */\nexport function revalidatePath(path: string): void {\n const state = revalidationAls.getStore();\n if (!state || state.closed) {\n throw new Error(\n 'revalidatePath() can only be called inside a server action: it re-renders ' +\n 'the route into the action response, and there is no action response here. ' +\n 'To refresh cached data from a route handler or other server code, call ' +\n 'revalidateTag() or cache.invalidate() for the tags the route reads.'\n );\n }\n if (!state.paths.includes(path)) {\n state.paths.push(path);\n }\n}\n\n/**\n * Invalidate all timber.cache entries tagged with `tag`, and tombstone the\n * pre-rendered component seeds that carry it.\n * Does not return a payload — the next request for an invalidated entry re-executes.\n *\n * Callable from any server code. Inside a server action the invalidation is\n * deferred until the action body returns, so a `revalidatePath()` render in\n * the same action reads fresh data; the returned promise resolves at once.\n * Anywhere else — a `route.ts` webhook, a job, or background work an action\n * started that runs after the action body returned — it is\n * `cache.invalidate({ tag })`, and the promise settles when the invalidation\n * has. Await it before responding.\n *\n * @param tag - The cache tag to invalidate (e.g. 'products', 'user:123').\n */\nexport function revalidateTag(tag: string): Promise<void> {\n const state = revalidationAls.getStore();\n if (!state || state.closed) return cache.invalidate({ tag });\n if (!state.tags.includes(tag)) {\n state.tags.push(tag);\n }\n return Promise.resolve();\n}\n\n// ─── Action Handler ──────────────────────────────────────────────────────\n\n/**\n * Execute a server action and process revalidation.\n *\n * 1. Sets up revalidation state\n * 2. Calls the action function\n * 3. Processes revalidateTag calls (invalidates cache entries)\n * 4. Processes revalidatePath calls (re-renders and captures RSC payload)\n * 5. Returns the action result + optional RSC payload\n *\n * @param actionFn - The server action function to execute.\n * @param args - Arguments to pass to the action.\n * @param config - Handler configuration (cache handler, renderer).\n */\nexport async function executeAction(\n actionFn: (...args: unknown[]) => Promise<unknown>,\n args: unknown[],\n config: ActionHandlerConfig = {},\n spanMeta?: { actionFile?: string; actionName?: string }\n): Promise<ActionHandlerResult> {\n const state: RevalidationState = { paths: [], tags: [] };\n const revalidationErrors: unknown[] = [];\n let actionResult: unknown;\n let redirectTo: string | undefined;\n let redirectStatus: number | undefined;\n\n // Run the action inside ALS scope so revalidatePath/Tag resolve to this\n // request's state object — concurrent requests each get their own scope.\n await revalidationAls.run(state, async () => {\n try {\n actionResult = await withSpan(\n 'timber.action',\n {\n ...(spanMeta?.actionFile ? { 'timber.action_file': spanMeta.actionFile } : {}),\n ...(spanMeta?.actionName ? { 'timber.action_name': spanMeta.actionName } : {}),\n },\n () => actionFn(...args)\n );\n } catch (error) {\n if (isRedirectSignal(error)) {\n redirectTo = error.location;\n redirectStatus = error.status;\n } else {\n throw error;\n }\n } finally {\n // From here `paths` and `tags` are snapshotted below (or abandoned on\n // a throw); later calls from un-awaited work must not queue into them.\n state.closed = true;\n }\n });\n\n // Process tag invalidation through cache.invalidate so it records the\n // invalidation epoch — an in-flight cached fn must not re-store data this\n // mutation just invalidated (TIM-1028). cache.invalidate resolves the\n // module-level handler singleton: setCacheHandler() is called at boot from\n // rsc-entry when timber.config.ts provides a cacheHandler; otherwise falls\n // back to in-memory LRU (TIM-599).\n if (state.tags.length > 0) {\n // cache.invalidate handles both data-cache clearing AND component-seed\n // tombstone writes (design/45 §ISR mechanics) — no separate tombstone\n // step needed here.\n // Best-effort: the action body already executed and its mutation committed.\n // Use allSettled so all tags settle before proceeding — Promise.all would\n // short-circuit on the first rejection, leaving other invalidations (including\n // component-seed tombstone writes) in-flight during revalidatePath rendering.\n const results = await Promise.allSettled(state.tags.map((tag) => cache.invalidate({ tag })));\n for (const r of results) {\n if (r.status === 'rejected') {\n console.error('[timber] revalidateTag invalidation failed:', r.reason);\n revalidationErrors.push(r.reason);\n }\n }\n }\n\n // Process path revalidation — build element tree (not yet serialized).\n //\n // TIM-1454: Only a path that matches the current page is rendered. When\n // every call names another page, `onlyOtherPagesNamed` tells the client to\n // evict its caches instead. The matching path is looked for across every\n // call, not just the first: an action that calls revalidatePath('/other')\n // and then revalidatePath('/current') must still re-render the current\n // page (TIM-1461).\n let revalidation: RevalidationResult | undefined;\n const { requestPathname, requestSearch } = config;\n const isCurrentPage = (path: string) =>\n !requestPathname || revalidationPathMatches(path, requestPathname, requestSearch);\n const path = state.paths.find(isCurrentPage);\n const onlyOtherPagesNamed = state.paths.length > 0 && path === undefined;\n\n if (path !== undefined && config.renderer) {\n try {\n revalidation = await config.renderer(path);\n } catch (renderError) {\n if (isRedirectSignal(renderError)) {\n redirectTo = renderError.location;\n redirectStatus = renderError.status;\n } else if (isDenySignal(renderError)) {\n console.error(\n `[timber] revalidatePath dropped — target middleware denied (status ${renderError.status})`\n );\n } else if (renderError instanceof RevalidationDropped) {\n console.error(`[timber] ${renderError.message}`);\n } else {\n console.error('[timber] revalidatePath render failed:', renderError);\n revalidationErrors.push(renderError);\n }\n }\n }\n\n return {\n actionResult,\n revalidation,\n onlyOtherPagesNamed,\n revalidationErrors,\n ...(redirectTo ? { redirectTo, redirectStatus } : {}),\n };\n}\n\n/**\n * Check if a `revalidatePath(path)` argument matches the request pathname.\n * Canonicalizes the revalidated path the same way the renderer does so\n * equivalent paths compare equal. Returns true when the paths match or\n * when comparison is inconclusive (validation failure → render to be safe).\n */\nfunction revalidationPathMatches(\n revalidatedPath: string,\n requestPathname: string,\n requestSearch?: string\n): boolean {\n const hashIdx = revalidatedPath.indexOf('#');\n const noFragment = hashIdx >= 0 ? revalidatedPath.slice(0, hashIdx) : revalidatedPath;\n const queryIdx = noFragment.indexOf('?');\n const pathnameOnly = queryIdx >= 0 ? noFragment.slice(0, queryIdx) : noFragment;\n const search = queryIdx >= 0 ? noFragment.slice(queryIdx) : '';\n const canonical = canonicalize(pathnameOnly, true);\n if (!canonical.ok) return true;\n if (canonical.pathname !== requestPathname) return false;\n // revalidatePath('/dashboard') (no search) matches any query variant.\n // revalidatePath('/dashboard?tab=x') only matches that exact search.\n if (search && search !== (requestSearch ?? '')) return false;\n return true;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAcA,SAAgB,wBAAyC;CACvD,uBAAO,IAAI,IAAI;AACjB;;;;;;;;;;;AAYA,SAAgB,uBACd,IACA,QAAyB,sBAAsB,GAC5C;CACH,OAAO,mBAAmB,IAAI,OAAO,EAAE;AACzC;;;;;;;;;;;AAYA,SAAgB,0BAA6B,IAAgB;CAC3D,OAAO,mBAAmB,KAAK,EAAE;AACnC;AAgBA,IAAM,8BAAc,IAAI,QAAsC;AAC9D,IAAM,+BAAe,IAAI,QAAyB;;;;;;AAOlD,SAAgB,4BAA4B,MAAoB;CAC9D,IAAI,CAAC,UAAU,GAAG;CAClB,MAAM,QAAQ,mBAAmB,SAAS;CAC1C,IAAI,CAAC,SAAS,MAAM,SAAS,GAAG;CAChC,IAAI,QAAQ,YAAY,IAAI,KAAK;CACjC,IAAI,CAAC,OAAO;EACV,wBAAQ,IAAI,IAAI;EAChB,YAAY,IAAI,OAAO,KAAK;CAC9B;CACA,MAAM,IAAI,IAAI;AAChB;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S;CACT,MAAM,UAAU,gBAAgB,QAAQ,GAAG;CAC3C,MAAM,aAAa,WAAW,IAAI,gBAAgB,MAAM,GAAG,OAAO,IAAI;CACtE,MAAM,WAAW,WAAW,QAAQ,GAAG;CACvC,MAAM,eAAe,YAAY,IAAI,WAAW,MAAM,GAAG,QAAQ,IAAI;CACrE,MAAM,SAAS,YAAY,IAAI,WAAW,MAAM,QAAQ,IAAI;CAC5D,MAAM,YAAY,aAAa,cAAc,IAAI;CACjD,IAAI,CAAC,UAAU,IAAI,OAAO;CAC1B,IAAI,UAAU,aAAa,iBAAiB,OAAO;CAGnD,IAAI,UAAU,YAAY,iBAAiB,KAAK,OAAO;CACvD,OAAO;AACT"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"build-output-helper-RV_BRcF1.js","names":[],"sources":["../../src/adapters/shared.ts","../../src/adapters/build-output-helper.ts"],"sourcesContent":["// Shared adapter utilities — leaf module with zero deps on server/, client/,\n// or any Vite-dependent code.\n//\n// Adapters are loaded by Node at Vite startup time, before Vite's module\n// resolver is available. This module uses only Node built-ins and can be\n// imported by both adapters via a relative path.\n//\n// IMPORTANT: Do NOT add imports from ../server/, ../client/, ../plugins/,\n// or any module that transitively depends on Vite. A test in\n// tests/adapters/shared-no-forbidden-imports.test.ts enforces this.\n// ../shared/ is exempt: it is dependency-free by the same rule.\n\nimport { withBasePath } from '../shared/base-path.ts';\n\n/**\n * The deployment base an adapter should write platform rules against.\n *\n * `config.base` is optional on `TimberConfig` because adapters can be invoked\n * by callers that predate it (a hand-written adapter, a test harness). Falling\n * back to `'/'` reproduces the pre-TIM-1274 output exactly, which is correct\n * for the only deployments those callers can have: a build under a non-root\n * base always goes through `plugins/post-build.ts`, which populates it.\n *\n * Typed structurally rather than as `TimberConfig` so this module keeps no\n * import of `./types.js` at runtime.\n */\nexport function adapterBase(config: { base?: string }): string {\n return config.base ?? '/';\n}\n\n// ─── Static asset cache headers ──────────────────────────────────────────\n\n/** Cache-Control value for hashed (immutable) assets. */\nexport const IMMUTABLE_CACHE = 'public, max-age=31536000, immutable';\n\n/** Cache-Control value for unhashed static assets. */\nexport const STATIC_CACHE = 'public, max-age=3600, must-revalidate';\n\n/**\n * Generate a `_headers` file for static asset cache control.\n *\n * The `_headers` file is a platform convention supported by Cloudflare Workers\n * Static Assets, Cloudflare Pages, and Netlify. It maps URL patterns to\n * HTTP response headers.\n *\n * The build's content-hashed directories (`immutableDirs`, recorded on\n * `BuildArtifacts` by the phases that hashed them) get one wildcard rule\n * each. When\n * `unhashedPaths` is provided, per-file rules are appended for unhashed\n * static assets (favicon.ico, robots.txt, etc.) so they get Cache-Control\n * on platforms like Cloudflare Workers Static Assets where the server\n * handler never sees static file requests.\n *\n * A `/*` catch-all is NOT used — it would be additive on Cloudflare,\n * producing duplicate Cache-Control directives on hashed assets\n * (invalid per RFC 9111).\n *\n * **Every rule path is written in deployed-URL space** (TIM-1274). The\n * platform matches these patterns against the request path, which under a\n * non-root `base` sits below the prefix: with `base: '/repo/'` the assets are\n * at `/repo/assets/*`, so a rule saying `/assets/*` matches nothing. Silent\n * for the cache rules (slower, still correct) and not silent for the\n * Content-Type rules — an extensionless API route output is unreadable on\n * Cloudflare Workers Static Assets without one.\n *\n * The prefix is applied at exactly one point, `rulePath()`, which every rule\n * in this function goes through. Prefixing the wildcards and\n * hand-checking that the per-file rules agree is how the next rule gets\n * missed.\n */\n// Cloudflare Workers Static Assets caps _headers at 100 rules. The wildcard\n// rules for the immutable directories come out of the same budget.\nconst MAX_RULES = 100;\n\nexport interface HeadersFileOptions {\n /**\n * The deployment base, already normalized by `normalizeBasePath()` —\n * leading and trailing slash, `'/'` at the domain root.\n *\n * Required rather than defaulted: a caller that forgets it would emit\n * root-relative rules that match nothing, which is the bug this closes.\n */\n base: string;\n /**\n * Content-hashed directories, from `BuildArtifacts.immutableDirs`. Each\n * gets an immutable `Cache-Control` wildcard rule.\n */\n immutableDirs: readonly string[];\n /** Unhashed static files (route-space paths) needing per-file cache rules. */\n unhashedPaths?: string[];\n /** Route-space path → Content-Type, for extensionless API route outputs. */\n contentTypes?: Record<string, string>;\n /**\n * Verbatim contents of the user's `public/_headers`, appended after the\n * generated rules. See `mergeUserHeaders` for why it goes last.\n */\n userRules?: string;\n}\n\n/**\n * Count the rules in a `_headers` file — a rule is a path line, which is any\n * line that is neither blank, a comment, nor an indented header.\n *\n * @internal Exported for testing.\n */\nexport function countHeaderRules(content: string): number {\n return content\n .split('\\n')\n .filter((line) => line.trim() !== '' && !line.startsWith('#') && !/^\\s/.test(line)).length;\n}\n\n/** One `_headers` block: a path pattern and the headers it sets. */\nexport interface HeaderRule {\n pattern: string;\n headers: Array<{ name: string; value: string }>;\n}\n\n/**\n * Parse a `_headers` file. A non-indented, non-comment line opens a rule; the\n * indented `Name: value` lines beneath it belong to that rule.\n *\n * @internal Exported for testing.\n */\nexport function parseHeaderRules(content: string): HeaderRule[] {\n const rules: HeaderRule[] = [];\n for (const raw of content.split('\\n')) {\n const line = raw.replace(/\\r$/, '');\n if (line.trim() === '' || line.trimStart().startsWith('#')) continue;\n if (/^\\s/.test(line)) {\n const current = rules[rules.length - 1];\n if (!current) continue; // header with no rule above it — not ours to fix\n const colon = line.indexOf(':');\n if (colon === -1) continue;\n current.headers.push({\n name: line.slice(0, colon).trim(),\n value: line.slice(colon + 1).trim(),\n });\n } else {\n rules.push({ pattern: line.trim(), headers: [] });\n }\n }\n return rules;\n}\n\n/**\n * Whether a user pattern can match paths a generated pattern also matches.\n *\n * Deliberately narrow: equality, or a prefix-glob (`/x/*`, `/*`) whose literal\n * prefix contains the other's. Anything cleverer risks claiming an overlap\n * that is not there, and the only thing this drives is a warning — a false\n * positive is noise a developer cannot act on.\n */\nfunction patternsOverlap(a: string, b: string): boolean {\n if (a === b) return true;\n const prefixOf = (p: string) => (p.endsWith('*') ? p.slice(0, -1) : null);\n const [pa, pb] = [prefixOf(a), prefixOf(b)];\n if (pa !== null && (b.startsWith(pa) || pa === '')) return true;\n if (pb !== null && (a.startsWith(pb) || pb === '')) return true;\n return false;\n}\n\nexport function generateHeadersFile({\n base,\n immutableDirs,\n unhashedPaths,\n contentTypes,\n userRules,\n}: HeadersFileOptions): string {\n /** Route-space rule path → deployed-URL rule path. */\n const rulePath = (path: string) => withBasePath(base, path);\n\n // Cloudflare and Netlify apply *every* matching rule, so emitting a header\n // the user also sets on the same path yields two definitions of it — a\n // comma-joined `Cache-Control` that is invalid per RFC 9111, and neither\n // side's intent. This module already refuses to emit a `/*` catch-all for\n // that reason; appending the user's file verbatim reintroduced it through\n // the back door (TIM-1326).\n //\n // An explicit app rule beats a framework default, so where the user names\n // the same pattern and the same header, ours is dropped. Only exact pattern\n // matches are resolved this way: silently dropping asset immutability\n // because a `/*` rule *might* subsume it would be a worse surprise than the\n // duplicate, so overlapping-but-different patterns warn instead.\n const userRuleList = userRules ? parseHeaderRules(userRules) : [];\n const overriddenExactly = new Set(\n userRuleList.flatMap((rule) =>\n rule.headers.map((h) => `${rule.pattern}\\0${h.name.toLowerCase()}`)\n )\n );\n const overridden = (pattern: string, header: string) =>\n overriddenExactly.has(`${pattern}\\0${header.toLowerCase()}`);\n\n const warnedOverlaps = new Set<string>();\n const emit = (pattern: string, header: string, value: string): string => {\n if (overridden(pattern, header)) return '';\n for (const rule of userRuleList) {\n if (rule.pattern === pattern) continue;\n if (!patternsOverlap(rule.pattern, pattern)) continue;\n for (const h of rule.headers) {\n if (h.name.toLowerCase() !== header.toLowerCase()) continue;\n const key = `${rule.pattern}\\0${pattern}\\0${header.toLowerCase()}`;\n if (warnedOverlaps.has(key)) continue;\n warnedOverlaps.add(key);\n console.warn(\n `[timber] _headers: your rule \"${rule.pattern}\" sets ${header}, which ` +\n `timber also sets on \"${pattern}\". Cloudflare and Netlify apply both, ` +\n `so the response gets two ${header} values. Use the exact pattern ` +\n `\"${pattern}\" to replace timber's rule, or narrow yours so they do ` +\n `not overlap.`\n );\n }\n }\n return `\\n${pattern}\\n ${header}: ${value}\\n`;\n };\n\n let content = `# Auto-generated by @timber-js/app — static asset cache headers.\n# See design/25-production-deployments.md §\"CDN / Edge Cache\"\n`;\n for (const dir of immutableDirs) {\n content += emit(rulePath(`/${dir}/*`), 'Cache-Control', IMMUTABLE_CACHE);\n }\n const maxPerFileRules = MAX_RULES - immutableDirs.length;\n\n // Content-Type rules are higher priority than cache headers for\n // extensionless files — without them the file is unreadable.\n const allCtEntries = contentTypes\n ? Object.entries(contentTypes).sort(([a], [b]) => a.localeCompare(b))\n : [];\n const ctEntries = allCtEntries.slice(0, maxPerFileRules);\n if (allCtEntries.length > maxPerFileRules) {\n console.warn(\n `[timber] _headers: ${allCtEntries.length} content-type rules exceed ` +\n `Cloudflare's 100-rule limit. Only the first ${maxPerFileRules} ` +\n `extensionless API routes will get Content-Type headers.`\n );\n }\n const remainingBudget = maxPerFileRules - ctEntries.length;\n\n if (unhashedPaths && unhashedPaths.length > 0) {\n const capped = unhashedPaths.slice(0, Math.max(0, remainingBudget));\n if (unhashedPaths.length > remainingBudget) {\n console.warn(\n `[timber] _headers: ${unhashedPaths.length} unhashed static files + ` +\n `${ctEntries.length} content-type rules found, but Cloudflare limits ` +\n `_headers to 100 rules. Only the first ${capped.length} unhashed ` +\n `files will get Cache-Control headers.`\n );\n }\n // Section bodies are built before their comment header so a section the\n // user has overridden entirely does not leave a heading over nothing.\n const body = capped.map((p) => emit(rulePath(p), 'Cache-Control', STATIC_CACHE)).join('');\n if (body !== '') {\n content += `\\n# Unhashed static assets — short-lived cache with revalidation\\n${body}`;\n }\n }\n\n const ctBody = ctEntries\n .map(([urlPath, ct]) => emit(rulePath(urlPath), 'Content-Type', ct))\n .join('');\n if (ctBody !== '') {\n content += `\\n# Content-Type for extensionless API routes\\n${ctBody}`;\n }\n\n // User rules last, matching the `_redirects` merge. Their paths are left\n // verbatim: `_redirects` prefixes the rules it generates because it wrote\n // them in route space, but these are the user's own text, already authored\n // against the URLs the site is deployed at.\n if (userRules && userRules.trim() !== '') {\n content += `\\n# User-authored rules from public/_headers\\n\\n${userRules.trim()}\\n`;\n\n const total = countHeaderRules(content);\n if (total > MAX_RULES) {\n console.warn(\n `[timber] _headers: ${total} rules after merging public/_headers, over ` +\n `Cloudflare's ${MAX_RULES}-rule limit. Rules past the ` +\n `limit are dropped by the platform — remove some, or move static ` +\n `assets under a directory the wildcard rules already cover.`\n );\n }\n }\n\n return content;\n}\n","// Shared build-output helper for adapter buildOutput() methods.\n//\n// Steps 1–5 of every adapter's buildOutput are platform-agnostic:\n// 1. Copy client assets to the public/static directory\n// 2. Write _headers file for static asset cache control\n// 3. Copy RSC + SSR server bundles\n// 4. Write manifest-init module (if present)\n//\n// Only the final steps (entry codegen, platform config) vary per adapter.\n//\n// IMPORTANT: This module must remain a leaf — no imports from ../server/,\n// ../client/, or Vite-dependent code. See adapters/shared.ts header.\n\nimport { writeFile, mkdir, cp, rm, readdir, readFile } from 'node:fs/promises';\nimport { join, basename, relative } from 'node:path';\nimport { adapterBase, generateHeadersFile } from './shared.ts';\n// Isomorphic, zero-import module — safe to load from an adapter, which Node's\n// native ESM loader evaluates before Vite's resolver exists. Same precedent as\n// `adapters/shared.ts` importing `../shared/base-path.js`.\nimport {\n HEADERS_FILE,\n USER_MERGED_PLATFORM_FILES,\n USER_PLATFORM_DIR,\n} from '../shared/static-platform-files.ts';\nimport { detectFsIdentity, fsKey } from './fs-identity.ts';\nimport type {\n BuildArtifacts,\n ServerBuildArtifacts,\n StaticBuildArtifacts,\n TimberConfig,\n} from './types.ts';\n\n/** Options for the shared build output steps. */\nexport interface BuildOutputBaseOptions {\n /** Resolved timber config. */\n config: TimberConfig;\n /** What the build produced. */\n artifacts: ServerBuildArtifacts;\n /** Adapter-specific output directory (e.g. `.timber/dist/nitro`). */\n outDir: string;\n /**\n * Name of the public/static directory within outDir.\n * Nitro uses 'public', Cloudflare uses 'static'.\n */\n publicDirName: string;\n}\n\n/**\n * Run the platform-agnostic build output steps shared by all adapters:\n *\n * 1. Create the output directory\n * 2. Copy client assets to the public/static directory\n * 3. Write the `_headers` file for static asset cache control\n * 4. Copy RSC and SSR server bundles into the output directory\n * 5. Write the manifest-init module if present\n *\n * Returns the resolved public directory path for further adapter-specific use.\n */\nexport async function runSharedBuildSteps(opts: BuildOutputBaseOptions): Promise<string> {\n const { config, artifacts, outDir, publicDirName } = opts;\n\n // 1. Create the output directory.\n await mkdir(outDir, { recursive: true });\n\n // 2. Copy client assets to public/static directory.\n // When client JavaScript is disabled, skip .js files — only CSS,\n // fonts, images, and other static assets are needed.\n const publicDir = join(outDir, publicDirName);\n await mkdir(publicDir, { recursive: true });\n const clientDir = artifacts.client.path;\n // Find WASM files that are referenced by client JS (legitimate client WASM)\n // vs orphaned server-only WASM (e.g. @takumi-rs for OG image generation).\n // Only strip orphaned WASM to avoid breaking client-side WASM usage.\n const referencedWasm = await findReferencedWasm(clientDir);\n\n await cp(clientDir, publicDir, {\n recursive: true,\n filter: (src: string) => {\n if (src.endsWith('.wasm') && !referencedWasm.has(basename(src))) {\n return false;\n }\n if (config.clientJavascriptDisabled && src.endsWith('.js')) return false;\n return true;\n },\n });\n\n // 3. Write _headers file for static asset cache control.\n // Scan for unhashed files so they get per-file Cache-Control rules in the\n // _headers file. On platforms like Cloudflare Workers Static Assets, the\n // worker never sees static file requests — _headers is the only mechanism.\n await writeHeadersFile(publicDir, config, artifacts);\n\n // 4. Copy RSC + SSR server bundles into the output directory. The RSC\n // bundle imports the SSR one by a path the RSC plugin computed between the\n // two *build* directories, which the build names `rsc/` and `ssr/` as\n // siblings (index.ts); deploying them under the same names keeps it valid.\n await cp(artifacts.rsc.path, join(outDir, 'rsc'), { recursive: true });\n await cp(artifacts.ssr.path, join(outDir, 'ssr'), { recursive: true });\n\n // 4b. Copy prebuilt/ flight payloads (cache.component artifacts). These\n // are produced by the post-build capture pass (design/44) and read at\n // request time via the adapter's PrebuiltPayloadSource.\n if (artifacts.prebuilt) {\n await cp(artifacts.prebuilt.path, join(outDir, 'prebuilt'), { recursive: true });\n }\n\n // 5. Write manifest-init module if present.\n if (artifacts.manifestInit) {\n await writeFile(join(outDir, '_timber-manifest-init.js'), artifacts.manifestInit);\n }\n\n return publicDir;\n}\n\n/**\n * Find unhashed static files in the public directory that need per-file\n * Cache-Control rules in the `_headers` file.\n *\n * Excludes:\n * - Files under the build's `immutableDirs` (covered by wildcard rules)\n * - Files under `rsc/` and `ssr/` (server bundles, never served)\n * - Underscore-prefixed files (`_headers`, `_worker.js`, etc.)\n *\n * Ordered for the rule cap: well-known metadata files, then everything\n * else, then files under an underscore-prefixed directory — the\n * framework's own output (unhashed RSC payloads in a static build with\n * client JavaScript disabled, which nothing fetches). Those can number one\n * per route, and must not take the budget from the app's real files.\n *\n * @internal Exported for testing.\n */\n// Well-known metadata files that should be prioritized when capping\n// _headers rules, so they're never dropped in favor of less important files.\nconst PRIORITY_FILES = new Set([\n '/favicon.ico',\n '/robots.txt',\n '/sitemap.xml',\n '/manifest.json',\n '/manifest.webmanifest',\n '/apple-touch-icon.png',\n]);\n\nexport async function findUnhashedStaticFiles(\n publicDir: string,\n immutableDirs: readonly string[]\n): Promise<string[]> {\n let files: string[];\n try {\n files = await collectFiles(publicDir);\n } catch {\n return [];\n }\n\n const priority: string[] = [];\n const rest: string[] = [];\n const framework: string[] = [];\n for (const file of files) {\n const rel = relative(publicDir, file).replace(/\\\\/g, '/');\n if (immutableDirs.some((dir) => rel.startsWith(`${dir}/`))) continue;\n if (rel.startsWith('rsc/') || rel.startsWith('ssr/')) continue;\n if (basename(rel).startsWith('_')) continue;\n const urlPath = '/' + rel;\n if (PRIORITY_FILES.has(urlPath)) {\n priority.push(urlPath);\n } else if (rel.startsWith('_')) {\n framework.push(urlPath);\n } else {\n rest.push(urlPath);\n }\n }\n\n return [...priority.sort(), ...rest.sort(), ...framework.sort()];\n}\n\n/**\n * Scan client JS files for references to .wasm filenames.\n * Returns the set of WASM basenames that are actually imported/referenced\n * by client code and must be preserved in the static output.\n */\nasync function findReferencedWasm(clientDir: string): Promise<Set<string>> {\n const referenced = new Set<string>();\n const files = await collectFiles(clientDir);\n\n const jsFiles = files.filter((f) => f.endsWith('.js'));\n const wasmFiles = files.filter((f) => f.endsWith('.wasm')).map((f) => basename(f));\n if (wasmFiles.length === 0) return referenced;\n\n for (const jsFile of jsFiles) {\n const content = await readFile(jsFile, 'utf-8');\n for (const wasmName of wasmFiles) {\n if (content.includes(wasmName)) {\n referenced.add(wasmName);\n }\n }\n }\n\n return referenced;\n}\n\n/**\n * Build a static-only output directory (no server entry). Copies client\n * assets and pre-rendered HTML/RSC/API files into `outDir/publicDirName`.\n * Used by both Cloudflare and Nitro adapters in `output: 'static'` mode.\n */\nexport async function buildStaticDirectoryOutput(\n config: TimberConfig,\n artifacts: StaticBuildArtifacts,\n outDir: string,\n publicDirName: string\n): Promise<void> {\n // Clean stale artifacts from prior builds (e.g. server-mode builds that\n // left rsc/, ssr/, _worker.js in the outDir). Without this, a static\n // build after a server build inherits 140+ unused server chunks.\n await rm(outDir, { recursive: true, force: true }).catch(() => {});\n await mkdir(outDir, { recursive: true });\n\n const publicDir = join(outDir, publicDirName);\n await mkdir(publicDir, { recursive: true });\n\n // Copy client assets (JS, CSS, fonts, images).\n await cp(artifacts.client.path, publicDir, {\n recursive: true,\n filter: (src: string) => {\n if (config.clientJavascriptDisabled && src.endsWith('.js')) return false;\n return true;\n },\n });\n\n // Copy pre-rendered static pages (HTML + RSC flight + API routes).\n //\n // This is the one place the build merges two independently-produced trees\n // into a single directory, and `cp` resolves an overlap by overwriting with\n // no diagnostic — the deployment then contains one of the two artifacts and\n // nothing recorded which. Refuse instead (TIM-1266).\n await assertNoTreeCollision(artifacts.pages.path, publicDir);\n await cp(artifacts.pages.path, publicDir, { recursive: true });\n}\n\n/**\n * Write the `_headers` file, folding in the user's `public/_headers`.\n *\n * Every adapter used to `writeFile` a generated `_headers` over whatever\n * Vite had copied out of `public/`, so an app shipping its own CSP, CORS, or\n * cache rules deployed without them and without a word (TIM-1326). The\n * generated rules and the user's are not competitors — they address different\n * paths — so this merges rather than refusing, the way `_redirects` has since\n * TIM-1249.\n *\n * **Read from the project, not the output.** The generated file lands under\n * the same name in the output directory, and `runSharedBuildSteps` does not\n * clean `outDir`; a reader aimed there would fold the previous build's\n * generated rules back in and compound them on every rebuild — the defect\n * this pass fixed for `_redirects`.\n *\n * User rules go last. On Cloudflare and Netlify a `_headers` file applies\n * every matching rule, so appending means the user's rules take effect; where\n * a platform resolves a conflict in favour of the earlier rule instead, the\n * framework keeps the paths it owns and the user keeps the rest. Under either\n * reading this is no worse than the previous behaviour, which was to drop the\n * user's rules entirely.\n *\n * @internal Exported for testing.\n */\nexport async function writeHeadersFile(\n dir: string,\n config: TimberConfig,\n artifacts: BuildArtifacts\n): Promise<void> {\n const userRules = await readUserPlatformFile(config.root, HEADERS_FILE);\n await writeFile(\n join(dir, HEADERS_FILE),\n generateHeadersFile({\n base: adapterBase(config),\n immutableDirs: artifacts.immutableDirs,\n // Scanned from the directory being deployed, which holds everything\n // the platform will serve from it.\n unhashedPaths: await findUnhashedStaticFiles(dir, artifacts.immutableDirs),\n contentTypes: artifacts.output === 'static' ? artifacts.contentTypes : undefined,\n userRules: userRules ?? undefined,\n })\n );\n}\n\n/**\n * Read a user-authored platform file from the project's `public/` directory.\n * Returns null when the project has none, or when no root is configured —\n * a caller without a root cannot locate the project at all, and inventing\n * one from `process.cwd()` would read a different project's file.\n */\nasync function readUserPlatformFile(\n root: string | undefined,\n name: string\n): Promise<string | null> {\n if (!root) return null;\n try {\n return await readFile(join(root, USER_PLATFORM_DIR, name), 'utf-8');\n } catch {\n return null;\n }\n}\n\n/**\n * Throw if copying `srcDir` over `destDir` would overwrite an existing file.\n *\n * Compared against the destination **as it stands**, not against the other\n * source tree: the first copy is filtered (client JS is dropped when client\n * JavaScript is disabled), so the files that are actually there are the only\n * ones a second copy can clobber.\n *\n * @internal Exported for testing.\n */\nexport async function assertNoTreeCollision(srcDir: string, destDir: string): Promise<void> {\n const [srcFiles, destFiles, identity] = await Promise.all([\n collectFiles(srcDir).catch(() => [] as string[]),\n collectFiles(destDir).catch(() => [] as string[]),\n // `cp` will resolve these paths the way the destination filesystem does,\n // so the comparison predicting it has to as well: on macOS a hand-written\n // `public/About/index.html` and a generated `about/index.html` are one\n // file, and an exact-string set waves the overwrite through (TIM-1266).\n detectFsIdentity(destDir),\n ]);\n\n const key = (p: string) => fsKey(p, identity);\n const existing = new Set(destFiles.map((f) => key(relative(destDir, f).replace(/\\\\/g, '/'))));\n const exempt = new Set(USER_MERGED_PLATFORM_FILES.map(key));\n const collisions = srcFiles\n .map((f) => relative(srcDir, f).replace(/\\\\/g, '/'))\n .filter((rel) => existing.has(key(rel)) && !exempt.has(key(rel)))\n .sort();\n\n if (collisions.length === 0) return;\n\n throw new Error(\n `[timber] Build output: ${collisions.length} file(s) in the pre-rendered site ` +\n `collide with files already in the output directory. Copying would silently ` +\n `overwrite them — a generated page and a file in public/ cannot share a path:\\n` +\n collisions.map((c) => ` - ${c}`).join('\\n')\n );\n}\n\nasync function collectFiles(dir: string): Promise<string[]> {\n const result: string[] = [];\n const entries = await readdir(dir, { withFileTypes: true });\n for (const entry of entries) {\n const fullPath = join(dir, entry.name);\n if (entry.isDirectory()) {\n result.push(...(await collectFiles(fullPath)));\n } else {\n result.push(fullPath);\n }\n }\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA0BA,SAAgB,YAAY,QAAmC;CAC7D,OAAO,OAAO,QAAQ;AACxB;;AAKA,IAAa,kBAAkB;;AAG/B,IAAa,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoC5B,IAAM,YAAY;;;;;;;AAiClB,SAAgB,iBAAiB,SAAyB;CACxD,OAAO,QACJ,MAAM,IAAI,CAAC,CACX,QAAQ,SAAS,KAAK,KAAK,MAAM,MAAM,CAAC,KAAK,WAAW,GAAG,KAAK,CAAC,MAAM,KAAK,IAAI,CAAC,CAAC,CAAC;AACxF;;;;;;;AAcA,SAAgB,iBAAiB,SAA+B;CAC9D,M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AE,eAAe,KAAK,CAAC;CAC1D,KAAK,MAAM,SAAS,SAAS;EAC3B,MAAM,WAAW,KAAK,KAAK,MAAM,IAAI;EACrC,IAAI,MAAM,YAAY,GACpB,OAAO,KAAK,GAAI,MAAM,aAAa,QAAQ,CAAE;OAE7C,OAAO,KAAK,QAAQ;CAExB;CACA,OAAO;AACT"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"cache-api-GE4AOe2H.js","names":[],"sources":["../../src/server/waituntil-bridge.ts","../../src/cache/stable-stringify.ts","../../src/cache/timber-cache.ts","../../src/cache/redis-handler.ts","../../src/cache/tag-aware-handler.ts","../../src/cache/index.ts","../../src/server/version-skew.ts","../../src/server/prebuilt/manifest-tag-index.ts","../../src/server/prebuilt/payload-source.ts","../../src/server/prebuilt/overlay.ts","../../src/cache/cache-api.ts"],"sourcesContent":["/**\n * Per-request waitUntil bridge — ALS bridge for platform adapters.\n *\n * The generated entry point (Nitro, Cloudflare) wraps the handler with\n * `runWithWaitUntil`, binding the platform's lifecycle extension function\n * (e.g., h3's `event.waitUntil()` or CF's `ctx.waitUntil()`) for the\n * request duration. The `waitUntil()` primitive reads from this ALS to\n * dispatch background work to the correct platform API.\n *\n * Design doc: design/11-platform.md §\"waitUntil()\"\n */\n\nimport { waitUntilAls } from './als-registry.ts';\n\n/**\n * Run a function with a per-request waitUntil handler installed.\n *\n * Called by generated entry points (Nitro node-server/bun, Cloudflare)\n * to bind the platform's lifecycle extension for the request duration.\n */\nexport function runWithWaitUntil<T>(\n waitUntilFn: (promise: Promise<unknown>) => void,\n fn: () => T\n): T {\n return waitUntilAls.run(waitUntilFn, fn);\n}\n\n/**\n * Get the current request's waitUntil function, if available.\n *\n * Returns undefined when no platform adapter has installed a waitUntil\n * handler for the current request (e.g., on platforms that don't support\n * lifecycle extension, or outside a request context).\n */\nexport function getWaitUntil(): ((promise: Promise<unknown>) => void) | undefined {\n return waitUntilAls.getStore();\n}\n","/**\n * Deterministic JSON serialization with sorted object keys.\n * Used for cache key generation — ensures { a: 1, b: 2 } and { b: 2, a: 1 }\n * produce the same string.\n *\n * Matches JSON.stringify semantics for toJSON: Date serializes to its ISO\n * string, URL to its href, and class instances with a custom toJSON use it.\n * Map and Set serialize their entries explicitly (insertion-order\n * independent). Values that would serialize lossily — functions, symbols,\n * and non-plain objects with no enumerable own state (RegExp, class\n * instances holding data behind getters or internal slots) — throw instead:\n * every such value would collapse to the same cache key, silently returning\n * one argument's cached data for another (TIM-1020).\n */\nexport function stableStringify(value: unknown): string {\n if (value === null || value === undefined) return String(value);\n\n const type = typeof value;\n if (type === 'function' || type === 'symbol') {\n throw new TypeError(\n `stableStringify: cannot serialize a ${type} into a stable cache key — ` +\n 'all such values would collide. Provide an explicit `key` option to cache().'\n );\n }\n if (type !== 'object') return JSON.stringify(value);\n\n if (Array.isArray(value)) {\n return '[' + value.map((item) => stableStringify(item)).join(',') + ']';\n }\n\n // Honor toJSON like JSON.stringify does (Date → ISO string, URL → href,\n // custom class serialization). JSON.stringify does not re-invoke toJSON\n // on the value it returns, so a toJSON that returns `this` falls through\n // to plain own-property serialization instead of recursing forever.\n const withToJSON = value as { toJSON?: () => unknown };\n if (typeof withToJSON.toJSON === 'function') {\n const json = withToJSON.toJSON();\n if (json !== value) return stableStringify(json);\n }\n\n // Map/Set have no enumerable own properties — serialize entries explicitly.\n // Entries are sorted after serialization so insertion order doesn't change\n // the key. The Map(/Set( prefixes can't collide with object ('{'), array\n // ('['), or string ('\"') output.\n if (value instanceof Map) {\n const entries = [...value.entries()].map(\n ([k, v]) => stableStringify(k) + '=>' + stableStringify(v)\n );\n return 'Map(' + entries.sort().join(',') + ')';\n }\n if (value instanceof Set) {\n const members = [...value].map((member) => stableStringify(member));\n return 'Set(' + members.sort().join(',') + ')';\n }\n\n const obj = value as Record<string, unknown>;\n const keys = Object.keys(obj).sort();\n const pairs: string[] = [];\n for (const key of keys) {\n if (obj[key] === undefined) continue;\n // A callable own toJSON only reaches this loop via the returns-`this`\n // fall-through above. It's the serialization protocol, not data —\n // JSON.stringify omits it too.\n if (key === 'toJSON' && typeof obj[key] === 'function') continue;\n pairs.push(JSON.stringify(key) + ':' + stableStringify(obj[key]));\n }\n\n // A non-plain object that serializes to '{}' carries its state behind\n // getters or internal slots (RegExp, sessions, ORM entities). Serializing\n // it would give every instance the same cache key.\n if (pairs.length === 0) {\n const proto = Object.getPrototypeOf(value);\n if (proto !== Object.prototype && proto !== null) {\n const name = (value as object).constructor?.name || 'Object';\n throw new TypeError(\n `stableStringify: ${name} instance has no serializable own state — ` +\n 'all instances would share one cache key. Provide an explicit `key` ' +\n 'option to cache(), or add a toJSON() method.'\n );\n }\n }\n\n return '{' + pairs.join(',') + '}';\n}\n","import type { CacheHandler, CacheOptions } from './index.ts';\nimport { stableStringify } from './stable-stringify.ts';\nimport { createSingleflight } from './singleflight.ts';\nimport {\n currentInvalidationEpoch,\n lastInvalidationEpochFor,\n wasInvalidatedSince,\n} from './invalidation-epoch.ts';\nimport { addSpanEventSync } from '../server/tracing.ts';\nimport { logSwrRefetchFailed, swallow } from '../server/logger.ts';\nimport { getWaitUntil } from '../server/waituntil-bridge.ts';\nimport { fnv1aHash } from './fast-hash.ts';\nimport { devDataCacheKey } from '../server/prebuilt/dev-store.ts';\n\nlet defaultSingleflight = createSingleflight();\n\n/**\n * Per-key monotonic generation counter for CAS writes (TIM-1158).\n *\n * Unbounded, like the singleflight map — the key space is the same set of\n * cache keys the handler already tracks. Pruning was removed because it\n * desyncs from MemoryCacheHandler.generations: a pruned key restarts at 1\n * while the handler still holds the old higher generation, causing fresh\n * writes to be rejected as stale.\n */\nconst writeGenerations = new Map<string, number>();\nfunction nextGeneration(key: string): number {\n const gen = (writeGenerations.get(key) ?? 0) + 1;\n writeGenerations.set(key, gen);\n return gen;\n}\n\n/**\n * Set the timeout for the module-level default singleflight.\n * Called at framework boot with renderTimeoutMs from timber.config.ts so that\n * cache calls without a per-call timeoutMs still get deadlock protection.\n * See design/06-caching.md §\"Singleflight Timeout — Deadlock Risk\".\n */\nexport function setDefaultSingleflightTimeout(timeoutMs: number): void {\n defaultSingleflight = createSingleflight({ timeoutMs });\n}\n\n/**\n * Generate a cache key from function identity and serialized args.\n *\n * Uses FNV-1a (fast non-crypto hash) instead of SHA-256. Cache keys don't\n * need collision resistance — they need speed. The fnId prefix provides\n * namespace isolation; the hash covers the args.\n *\n * See TIM-370 for perf motivation.\n */\nfunction defaultKeyGenerator(fnId: string, args: unknown[]): string {\n const raw = fnId + ':' + stableStringify(args);\n return fnId + ':' + fnv1aHash(raw);\n}\n\n/**\n * Resolve tags from the options — supports static array or function form.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction resolveTags<Fn extends (...args: any[]) => any>(\n opts: CacheOptions<Fn>,\n args: Parameters<Fn>\n): string[] {\n if (!opts.tags) return [];\n if (Array.isArray(opts.tags)) return opts.tags;\n return opts.tags(...args);\n}\n\n/** Per-process count of byte-identical fn sources seen by deriveFallbackFnId. */\nconst fallbackIdOccurrences = new Map<string, number>();\nlet hasWarnedFallbackId = false;\n\n/**\n * Derive a fallback fnId for callsites the timber-cache-transform Vite plugin\n * could not statically detect (aliased bindings, user re-export wrappers).\n *\n * The base is fnv1a(fn.toString()) — deterministic across instances and cold\n * starts of the same build, so two *different* functions can never swap fnIds\n * by module-evaluation order (the TIM-997 poisoning scenario that the old\n * process-local counter allowed; see TIM-1054). A per-process occurrence\n * suffix disambiguates byte-identical duplicate sources. That residue is the\n * one remaining hazard: closures produced by the same factory share source\n * text but capture different values, and their occurrence order may differ\n * across instances — such callsites need an explicit `key` option.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction deriveFallbackFnId(fn: (...args: any[]) => any): string {\n const sourceHash = fnv1aHash(fn.toString());\n const occurrence = fallbackIdOccurrences.get(sourceHash) ?? 0;\n fallbackIdOccurrences.set(sourceHash, occurrence + 1);\n\n if (!hasWarnedFallbackId && typeof process !== 'undefined' && process.env?.NODE_ENV !== 'test') {\n hasWarnedFallbackId = true;\n console.warn(\n '[timber] cache() callsite has no build-time stable ID and no explicit `key` option — ' +\n 'the call is not statically visible to the timber Vite plugin (e.g. an aliased ' +\n 'binding like `const c = cache` or a re-export wrapper module). Falling back to a ' +\n 'function-source hash for the cache key. With a shared CacheHandler (Redis/KV) this ' +\n 'is safe for distinct functions, but byte-identical closures from a factory can swap ' +\n 'cache entries across instances. Provide an explicit `key` option to make the cache ' +\n 'key contract stable and auditable.'\n );\n }\n\n return `timber-cache:fn:${sourceHash}:${occurrence}`;\n}\n\n/**\n * Creates a cached wrapper around an async function.\n *\n * - FNV-1a default keys with normalized JSON args\n * - Singleflight: concurrent misses → single execution AND single\n * handler.set — the write happens inside the coalesced callback (TIM-1028)\n * - Writes are skipped when the key/tags were invalidated while fn was in\n * flight, so explicit invalidation is never silently undone (TIM-1028)\n * - SWR: serve stale immediately, background refetch\n * - Tags as string[] or function of args\n * - The handler is resolved per invocation via `getHandler`, never captured\n * at wrapper-creation time — module-scope cache() wrappers created before\n * the framework's boot wiring calls setCacheHandler() still use the\n * configured handler once it arrives (TIM-1029)\n * - No ALS dependency for correctness — cache() works outside a request\n * context. The waitUntil ALS bridge is read optionally so the SWR\n * background refetch survives handler return on Workers/Lambda.\n *\n * Cache hits/misses are recorded as OTEL span events on the enclosing\n * span (not child spans). The DevSpanProcessor reads these for dev log output.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function createCache<Fn extends (...args: any[]) => Promise<any>>(\n fn: Fn,\n opts: CacheOptions<Fn>,\n getHandler: () => CacheHandler,\n stableId?: string\n): Fn {\n // With an explicit `key` option the fnId never reaches key generation, so\n // no fallback derivation (or warning) is needed in that case.\n const fnId = stableId ?? (opts.key ? undefined : deriveFallbackFnId(fn));\n\n // Per-call timeoutMs gets a dedicated singleflight instance. Otherwise\n // resolve defaultSingleflight per invocation (not captured at creation\n // time) so wrappers created before boot pick up the timeout once\n // setDefaultSingleflightTimeout is called (TIM-1032, same rationale as\n // getCacheHandler for TIM-1029).\n const perCallSf =\n opts.timeoutMs !== undefined ? createSingleflight({ timeoutMs: opts.timeoutMs }) : undefined;\n\n // Cast to Fn to preserve the original function's generic call signature.\n // Without this, generic type parameters (e.g. <T> in apiFetch<T>) are\n // erased and callers lose type safety on the return type.\n return (async (...args: Parameters<Fn>): Promise<Awaited<ReturnType<Fn>>> => {\n const sf = perCallSf ?? defaultSingleflight;\n const key = opts.key ? opts.key(...args) : defaultKeyGenerator(fnId as string, args);\n\n // The key the handler sees: in dev, scoped to the source generation.\n const storeKey = devDataCacheKey(key);\n\n const cacheStart = performance.now();\n const cached = await getHandler().get(storeKey);\n\n if (cached && !cached.stale) {\n // Record as OTEL span event on enclosing span (not a child span).\n // Fire-and-forget — no microtask overhead on the cache hot path.\n addSpanEventSync('timber.cache.hit', {\n key,\n duration_ms: Math.round(performance.now() - cacheStart),\n });\n return cached.value as Awaited<ReturnType<Fn>>;\n }\n\n // From here fn() will execute (SWR refetch or miss). Scope the\n // singleflight key by the last invalidation epoch affecting this\n // key/tags: a caller arriving after an invalidation must not coalesce\n // onto a flight that started before it — it would receive the\n // pre-invalidation result the invalidation was issued to discard.\n // NUL separator: cannot collide with user-provided key strings.\n const tags = resolveTags(opts, args);\n const flightKey = `${key}\\u0000${lastInvalidationEpochFor(key, tags)}`;\n\n /**\n * Run fn and store the result — exactly once per coalesced execution,\n * inside the singleflight callback. The write is skipped when:\n * - the key/tags were invalidated after fn started (TIM-1028), or\n * - the singleflight timed out (signal aborted) — the timed-out\n * flight's write could overwrite a newer value from a subsequent\n * flight (TIM-1092), or\n * - the handler rejects the write because a newer generation has\n * already been stored (TIM-1158 CAS guard).\n */\n const executeAndStore = async (signal: AbortSignal): Promise<Awaited<ReturnType<Fn>>> => {\n const startEpoch = currentInvalidationEpoch();\n const generation = nextGeneration(key);\n const result = await fn(...args);\n if (!signal.aborted && !wasInvalidatedSince(startEpoch, key, tags)) {\n try {\n await getHandler().set(storeKey, result, { ttl: opts.ttl, tags, generation });\n } catch (err) {\n // Cache-write failure must not fail the request (TIM-1046).\n // JSON-serializing handlers (Redis, KV) throw on BigInt; network\n // errors can surface from any shared handler. The result is valid\n // — serve it uncached rather than rejecting a successful fn().\n swallow(err, `cache set failed for key \"${key}\"`);\n }\n }\n return result;\n };\n\n if (cached && cached.stale && opts.staleWhileRevalidate) {\n // Record stale cache hit as OTEL span event (fire-and-forget).\n addSpanEventSync('timber.cache.hit', {\n key,\n duration_ms: Math.round(performance.now() - cacheStart),\n stale: true,\n });\n // Serve stale immediately, trigger background refetch\n const refetch = sf\n .do(`swr:${flightKey}`, async (signal) => {\n try {\n await executeAndStore(signal);\n } catch (err) {\n // Failed refetch — stale entry continues to be served.\n logSwrRefetchFailed({ cacheKey: key, error: err });\n }\n })\n .catch(() => {\n // Singleflight promise rejection handled — stale continues.\n });\n // Platforms that cancel work when the handler returns (Cloudflare\n // Workers, Lambda) would otherwise kill the refetch mid-flight —\n // stale data re-served forever. Register the (never-rejecting)\n // refetch with the request's waitUntil; undefined outside a request\n // context or on platforms without lifecycle extension (Node servers\n // keep floating promises alive, so behavior there is unchanged).\n getWaitUntil()?.(refetch);\n return cached.value as Awaited<ReturnType<Fn>>;\n }\n\n // Cache miss (or stale without SWR) — execute with singleflight.\n // The handler.set lives inside the coalesced callback, so N concurrent\n // misses produce exactly one write (TIM-1028).\n const result = await sf.do(flightKey, executeAndStore);\n\n // Record cache miss as OTEL span event (fire-and-forget).\n addSpanEventSync('timber.cache.miss', {\n key,\n duration_ms: Math.round(performance.now() - cacheStart),\n });\n\n return result;\n }) as unknown as Fn;\n}\n","import type { CacheHandler } from './index.ts';\nimport { warnLossyJsonValue } from './json-lossy-check.ts';\n\n/**\n * Minimal Redis client contract for `RedisCacheHandler`.\n *\n * This is deliberately NOT the native shape of any client library. ioredis,\n * node-redis v4, and @upstash/redis all disagree on TTL argument shapes\n * (positional `'EX'` vs `{ EX }` vs `{ ex }`), method casing (`sadd` vs\n * `sAdd`), and array handling in `del` — a contract that pattern-matches one\n * client lets another silently drop the expiry (TIM-1030: node-redis ignored\n * the positional `'EX'` and wrote keys with no TTL). Instead, TTL semantics\n * are explicit in the signature and you adapt your client with a thin\n * wrapper, so a mismatch is a type error rather than silent unbounded\n * keyspace growth.\n *\n * @example ioredis\n * ```ts\n * import Redis from 'ioredis';\n * const redis = new Redis(process.env.REDIS_URL);\n * const client: RedisClient = {\n * get: (k) => redis.get(k),\n * set: (k, v, ttl) => redis.set(k, v, 'EX', ttl),\n * expireNX: (k, s) => redis.expire(k, s, 'NX'),\n * expireGT: (k, s) => redis.expire(k, s, 'GT'),\n * del: (k) => redis.del(k),\n * sadd: (k, ...m) => redis.sadd(k, ...m),\n * srem: (k, ...m) => redis.srem(k, ...m),\n * smembers: (k) => redis.smembers(k),\n * ttl: (k) => redis.ttl(k),\n * execMulti: async (ops) => {\n * const p = redis.multi();\n * for (const op of ops) {\n * switch (op.op) {\n * case 'set': p.set(op.key, op.value, 'EX', op.ttlSeconds); break;\n * case 'sadd': p.sadd(op.key, ...op.members); break;\n * case 'expireNX': p.expire(op.key, op.seconds, 'NX'); break;\n * case 'expireGT': p.expire(op.key, op.seconds, 'GT'); break;\n * case 'del': p.del(op.key); break;\n * }\n * }\n * await p.exec();\n * },\n * };\n * ```\n *\n * @example node-redis v4\n * ```ts\n * import { createClient } from 'redis';\n * const redis = createClient({ url: process.env.REDIS_URL });\n * await redis.connect();\n * const client: RedisClient = {\n * get: (k) => redis.get(k),\n * set: (k, v, ttl) => redis.set(k, v, { EX: ttl }),\n * expireNX: (k, s) => redis.expire(k, s, 'NX'),\n * expireGT: (k, s) => redis.expire(k, s, 'GT'),\n * del: (k) => redis.del(k),\n * sadd: (k, ...m) => redis.sAdd(k, m),\n * srem: (k, ...m) => redis.sRem(k, m),\n * smembers: (k) => redis.sMembers(k),\n * ttl: (k) => redis.ttl(k),\n * };\n * ```\n *\n * @example @upstash/redis\n * ```ts\n * import { Redis } from '@upstash/redis';\n * // automaticDeserialization must be off: the handler stores JSON strings\n * // and parses them itself — auto-parsing would hand back objects.\n * const redis = new Redis({ url, token, automaticDeserialization: false });\n * const client: RedisClient = {\n * get: (k) => redis.get(k),\n * set: (k, v, ttl) => redis.set(k, v, { ex: ttl }),\n * expireNX: (k, s) => redis.expire(k, s, 'NX'),\n * expireGT: (k, s) => redis.expire(k, s, 'GT'),\n * del: (k) => redis.del(k),\n * sadd: (k, ...m) => redis.sadd(k, m[0], ...m.slice(1)),\n * srem: (k, ...m) => redis.srem(k, m[0], ...m.slice(1)),\n * smembers: (k) => redis.smembers(k),\n * ttl: (k) => redis.ttl(k),\n * };\n * ```\n */\nexport type RedisWriteOp =\n | { op: 'set'; key: string; value: string; ttlSeconds: number }\n | { op: 'sadd'; key: string; members: string[] }\n | { op: 'expireNX'; key: string; seconds: number }\n | { op: 'expireGT'; key: string; seconds: number }\n | { op: 'del'; key: string };\n\nexport interface RedisClient {\n /** `GET key` — the stored string, or null when absent. */\n get(key: string): Promise<string | null>;\n /**\n * `SET key value EX ttlSeconds` — store with an expiry. The TTL is a\n * required positional argument so no adapter can forget it.\n */\n set(key: string, value: string, ttlSeconds: number): Promise<unknown>;\n /**\n * `EXPIRE key seconds NX` — set the TTL only if the key has no existing\n * expiry (Redis 7.0+). Used to set the initial TTL on new tag sets.\n */\n expireNX(key: string, seconds: number): Promise<unknown>;\n /**\n * `EXPIRE key seconds GT` — update the TTL only if the new value is greater\n * than the current one (Redis 7.0+). Used to extend tag set TTLs without\n * allowing a short-TTL writer to shrink them.\n */\n expireGT(key: string, seconds: number): Promise<unknown>;\n /** `DEL key` — delete a single key. Multi-key deletes loop per key. */\n del(key: string): Promise<unknown>;\n /** `SADD key member [member ...]` — add members to a set. */\n sadd(key: string, ...members: string[]): Promise<unknown>;\n /** `SREM key member [member ...]` — remove members from a set. */\n srem(key: string, ...members: string[]): Promise<unknown>;\n /** `SMEMBERS key` — all members of a set. */\n smembers(key: string): Promise<string[]>;\n /**\n * `TTL key` — remaining time-to-live in seconds. Returns -2 if the key does\n * not exist, -1 if the key exists but has no expiry.\n */\n ttl(key: string): Promise<number>;\n /**\n * Execute a batch of write operations atomically via `MULTI/EXEC`.\n * When provided, `set()` uses this to make tag-index writes and the data\n * write atomic — no `invalidate({tag})` can interleave. Optional: when\n * absent, operations run sequentially (correct but not race-free).\n */\n execMulti?(ops: RedisWriteOp[]): Promise<void>;\n}\n\nconst KEY_PREFIX = 'timber:cache:';\nconst TAG_PREFIX = 'timber:tag:';\n\n/**\n * Redis-backed CacheHandler for distributed caching.\n *\n * All instances sharing the same Redis see each other's cache entries and\n * invalidations. Tag-based invalidation uses Redis Sets to track which keys\n * belong to which tags.\n *\n * Bring your own Redis client wrapped to the {@link RedisClient} contract —\n * see the adapter examples on the interface for ioredis, node-redis v4, and\n * @upstash/redis.\n */\nexport class RedisCacheHandler implements CacheHandler {\n private client: RedisClient;\n private prefix: string;\n\n constructor(client: RedisClient, opts?: { prefix?: string }) {\n this.client = client;\n this.prefix = opts?.prefix ?? '';\n }\n\n private cacheKey(key: string): string {\n return `${this.prefix}${KEY_PREFIX}${key}`;\n }\n\n private tagKey(tag: string): string {\n return `${this.prefix}${TAG_PREFIX}${tag}`;\n }\n\n async get(key: string): Promise<{ value: unknown; stale: boolean } | null> {\n const raw = await this.client.get(this.cacheKey(key));\n if (raw === null) return null;\n\n const entry = JSON.parse(raw) as { value: unknown; expiresAt: number };\n const stale = Date.now() > entry.expiresAt;\n return { value: entry.value, stale };\n }\n\n async set(\n key: string,\n value: unknown,\n opts: { ttl: number; tags: string[]; generation?: number }\n ): Promise<void> {\n warnLossyJsonValue(value, key);\n const ck = this.cacheKey(key);\n const expiresAt = Date.now() + opts.ttl * 1000;\n\n // Serialize upfront so BigInt/non-serializable errors throw before any\n // writes — prevents tag indexes pointing at stale data from a prior set().\n const payload = JSON.stringify({ value, expiresAt, tags: opts.tags });\n\n // Redis TTL with generous margin beyond the logical TTL to allow SWR reads\n // on stale entries. The logical staleness is determined by expiresAt.\n // We use 2x TTL + 60s as the Redis expiry so stale entries remain\n // available for SWR background refetches.\n const redisTtlSeconds = Math.max(opts.ttl * 2 + 60, 120);\n\n const writeOps: RedisWriteOp[] = [];\n for (const tag of opts.tags) {\n writeOps.push({ op: 'sadd', key: this.tagKey(tag), members: [key] });\n writeOps.push({ op: 'expireNX', key: this.tagKey(tag), seconds: redisTtlSeconds });\n writeOps.push({ op: 'expireGT', key: this.tagKey(tag), seconds: redisTtlSeconds });\n }\n writeOps.push({ op: 'set', key: ck, value: payload, ttlSeconds: redisTtlSeconds });\n\n if (this.client.execMulti) {\n await this.client.execMulti(writeOps);\n } else {\n for (const op of writeOps) {\n await this.execOp(op);\n }\n }\n }\n\n private async execOp(op: RedisWriteOp): Promise<void> {\n switch (op.op) {\n case 'set':\n await this.client.set(op.key, op.value, op.ttlSeconds);\n break;\n case 'sadd':\n await this.client.sadd(op.key, ...op.members);\n break;\n case 'expireNX':\n await this.client.expireNX(op.key, op.seconds);\n break;\n case 'expireGT':\n await this.client.expireGT(op.key, op.seconds);\n break;\n case 'del':\n await this.client.del(op.key);\n break;\n }\n }\n\n async invalidate(opts: { key?: string; tag?: string }): Promise<void> {\n if (opts.key) {\n const raw = await this.client.get(this.cacheKey(opts.key));\n if (raw !== null) {\n const entry = JSON.parse(raw) as { tags?: string[] };\n if (entry.tags) {\n await Promise.all(entry.tags.map((tag) => this.client.srem(this.tagKey(tag), opts.key!)));\n }\n }\n await this.client.del(this.cacheKey(opts.key));\n }\n\n if (opts.tag) {\n const tk = this.tagKey(opts.tag);\n const keys = await this.client.smembers(tk);\n\n // Re-check each member before deleting — the tag set can contain stale\n // memberships from entries whose tags changed since they were added.\n // Mirrors TagAwareCacheHandler's eager strategy (tag-aware-handler.ts:183-198).\n await Promise.all(\n keys.map(async (k) => {\n const raw = await this.client.get(this.cacheKey(k));\n if (raw === null) {\n await this.client.srem(tk, k);\n return;\n }\n const entry = JSON.parse(raw) as { tags?: string[] };\n if (entry.tags?.includes(opts.tag!)) {\n await this.client.del(this.cacheKey(k));\n }\n await this.client.srem(tk, k);\n })\n );\n\n // Clean up the now-empty tag set so it doesn't consume memory\n const remaining = await this.client.smembers(tk);\n if (remaining.length === 0) {\n await this.client.del(tk);\n }\n }\n }\n}\n","/**\n * TagAwareCacheHandler — wraps any CacheStore and adds tag-based invalidation.\n *\n * Three strategies, selected by store capabilities (best available wins):\n *\n * 1. **Native** (store has setWithTags + invalidateTag): Delegates entirely.\n * The store owns tag indexing. Used for Vercel Runtime Cache, DO-backed\n * stores, or any platform with first-class tag support.\n *\n * 2. **Eager** (store has sadd/smembers/srem/sdel): Maintains an inverted\n * index via atomic set operations. Invalidation enumerates the set and\n * deletes entries. Used for Redis.\n *\n * 3. **Lazy** (bare get/set/del only): Version-stamps entries with tag\n * counters. Invalidation bumps a counter (O(1)). Reads validate stored\n * versions against current. Race-free, correct under eventual consistency.\n * Used for Cloudflare KV.\n *\n * Implements the CacheHandler interface consumed by timber-cache.ts.\n */\n\nimport type { CacheHandler } from './index.ts';\nimport type { CacheStore } from './store.ts';\n\nconst DATA_PREFIX = 'd:';\nconst TAG_SET_PREFIX = 'ts:';\nconst TAG_VERSION_PREFIX = 'tv:';\n\n/** A store whose optional capability methods are known to be present. */\ntype StoreWith<K extends keyof CacheStore> = CacheStore & Required<Pick<CacheStore, K>>;\ntype NativeStore = StoreWith<'setWithTags' | 'invalidateTag'>;\ntype EagerStore = StoreWith<'sadd' | 'smembers' | 'srem' | 'sdel'>;\n\n/**\n * The detected strategy carries the store narrowed to the capabilities that\n * strategy relies on, so each branch calls those methods without assertions.\n */\ntype Strategy =\n | { kind: 'native'; store: NativeStore }\n | { kind: 'eager'; store: EagerStore }\n | { kind: 'lazy' };\n\n/** Stored entry format for eager strategy. */\ninterface EagerEntry {\n value: unknown;\n expiresAt: number;\n tags: string[];\n}\n\n/** Stored entry format for lazy (version-stamp) strategy. */\ninterface LazyEntry {\n value: unknown;\n expiresAt: number;\n tags: string[];\n tagVersions: Record<string, number>;\n}\n\nfunction isNativeStore(store: CacheStore): store is NativeStore {\n return !!(store.setWithTags && store.invalidateTag);\n}\n\nfunction isEagerStore(store: CacheStore): store is EagerStore {\n return !!(store.sadd && store.smembers && store.srem && store.sdel);\n}\n\nfunction detectStrategy(store: CacheStore): Strategy {\n if (isNativeStore(store)) return { kind: 'native', store };\n if (isEagerStore(store)) return { kind: 'eager', store };\n return { kind: 'lazy' };\n}\n\nexport class TagAwareCacheHandler implements CacheHandler {\n private store: CacheStore;\n private prefix: string;\n private strategy: Strategy;\n\n constructor(store: CacheStore, opts?: { prefix?: string }) {\n this.store = store;\n this.prefix = opts?.prefix ?? 'timber:';\n this.strategy = detectStrategy(store);\n }\n\n get consistency(): 'strong' | 'eventual' | 'local' {\n return this.store.consistency;\n }\n\n private dataKey(key: string): string {\n return `${this.prefix}${DATA_PREFIX}${key}`;\n }\n\n /** Namespace tags for native stores so prefix isolates shared stores. */\n private prefixTags(tags: string[]): string[] {\n return tags.map((t) => `${this.prefix}${t}`);\n }\n\n private tagSetKey(tag: string): string {\n return `${this.prefix}${TAG_SET_PREFIX}${tag}`;\n }\n\n private tagVersionKey(tag: string): string {\n return `${this.prefix}${TAG_VERSION_PREFIX}${tag}`;\n }\n\n async get(key: string): Promise<{ value: unknown; stale: boolean } | null> {\n const raw = await this.store.get(this.dataKey(key));\n if (raw === null) return null;\n\n if (this.strategy.kind !== 'lazy') {\n const entry = JSON.parse(raw) as EagerEntry;\n const stale = Date.now() > entry.expiresAt;\n return { value: entry.value, stale };\n }\n\n // Lazy: validate tag versions before returning\n const entry = JSON.parse(raw) as LazyEntry;\n if (entry.tags.length > 0) {\n const currentVersions = await this.getTagVersions(entry.tags);\n for (const tag of entry.tags) {\n const stored = entry.tagVersions[tag] ?? 0;\n const current = currentVersions[tag] ?? 0;\n if (current > stored) return null;\n }\n }\n const stale = Date.now() > entry.expiresAt;\n return { value: entry.value, stale };\n }\n\n async set(\n key: string,\n value: unknown,\n opts: { ttl: number; tags: string[]; generation?: number }\n ): Promise<void> {\n const physicalTtl = Math.max(opts.ttl * 2 + 60, 120);\n const strategy = this.strategy;\n\n if (strategy.kind === 'native') {\n const entry: EagerEntry = {\n value,\n expiresAt: Date.now() + opts.ttl * 1000,\n tags: opts.tags,\n };\n const payload = JSON.stringify(entry);\n if (opts.tags.length > 0) {\n await strategy.store.setWithTags(\n this.dataKey(key),\n payload,\n physicalTtl,\n this.prefixTags(opts.tags)\n );\n } else {\n await this.store.set(this.dataKey(key), payload, physicalTtl);\n }\n return;\n }\n\n if (strategy.kind === 'eager') {\n const entry: EagerEntry = {\n value,\n expiresAt: Date.now() + opts.ttl * 1000,\n tags: opts.tags,\n };\n await this.store.set(this.dataKey(key), JSON.stringify(entry), physicalTtl);\n if (opts.tags.length > 0) {\n await Promise.all(\n opts.tags.map((tag) => strategy.store.sadd(this.tagSetKey(tag), [key], physicalTtl))\n );\n }\n return;\n }\n\n // Lazy: snapshot current tag versions into the entry\n const tagVersions = opts.tags.length > 0 ? await this.getTagVersions(opts.tags) : {};\n const entry: LazyEntry = {\n value,\n expiresAt: Date.now() + opts.ttl * 1000,\n tags: opts.tags,\n tagVersions,\n };\n await this.store.set(this.dataKey(key), JSON.stringify(entry), physicalTtl);\n }\n\n async invalidate(opts: { key?: string; tag?: string }): Promise<void> {\n const strategy = this.strategy;\n\n if (opts.key) {\n const key = opts.key;\n if (strategy.kind === 'eager') {\n const raw = await this.store.get(this.dataKey(key));\n if (raw !== null) {\n const entry = JSON.parse(raw) as EagerEntry;\n if (entry.tags.length > 0) {\n await Promise.all(\n entry.tags.map((tag) => strategy.store.srem(this.tagSetKey(tag), [key]))\n );\n }\n }\n }\n await this.store.del(this.dataKey(key));\n }\n\n if (opts.tag) {\n const tag = opts.tag;\n if (strategy.kind === 'native') {\n await strategy.store.invalidateTag(`${this.prefix}${tag}`);\n } else if (strategy.kind === 'eager') {\n const members = await strategy.store.smembers(this.tagSetKey(tag));\n // Verify each member still carries the tag before deleting — the set\n // can contain stale memberships from overwritten entries or LRU eviction.\n // Remove only the snapshot members (via srem, not sdel) so concurrent\n // writes that add new members between smembers() and cleanup are preserved.\n await Promise.all(\n members.map(async (k) => {\n const raw = await this.store.get(this.dataKey(k));\n if (raw !== null && (JSON.parse(raw) as EagerEntry).tags.includes(tag)) {\n await this.store.del(this.dataKey(k));\n }\n await strategy.store.srem(this.tagSetKey(tag), [k]);\n })\n );\n } else {\n await this.bumpTagVersion(opts.tag);\n }\n }\n }\n\n // --- Lazy strategy helpers ---\n\n private async getTagVersions(tags: string[]): Promise<Record<string, number>> {\n const versions: Record<string, number> = {};\n await Promise.all(\n tags.map(async (tag) => {\n const raw = await this.store.get(this.tagVersionKey(tag));\n versions[tag] = raw !== null ? parseInt(raw, 10) : 0;\n })\n );\n return versions;\n }\n\n private async bumpTagVersion(tag: string): Promise<void> {\n const key = this.tagVersionKey(tag);\n const raw = await this.store.get(key);\n const stored = raw !== null ? parseInt(raw, 10) : 0;\n // max(stored, now) + 1: strictly advancing even within the same\n // millisecond (two bumps in 1ms produce N, N+1 not N, N). On\n // eventually-consistent stores the read can be stale, but Date.now()\n // provides a floor — regression only if BOTH the read is stale AND the\n // clock is behind, bounded by the store's propagation window (~60s).\n const version = Math.max(stored, Date.now()) + 1;\n // Version keys must outlive all data entries stamped with them. Data\n // entries use physical TTL of max(ttl*2+60, 120); 365 days exceeds any\n // practical cache lifetime.\n await this.store.set(key, String(version), 365 * 86400);\n }\n}\n","// @timber-js/app/cache — Caching primitives\n\nimport { estimateByteSize } from './sizeof.ts';\n\nexport interface CacheHandler {\n get(key: string): Promise<{ value: unknown; stale: boolean } | null>;\n set(\n key: string,\n value: unknown,\n opts: { ttl: number; tags: string[]; generation?: number }\n ): Promise<void>;\n invalidate(opts: { key?: string; tag?: string }): Promise<void>;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport interface CacheOptions<Fn extends (...args: any[]) => any> {\n ttl: number;\n key?: (...args: Parameters<Fn>) => string;\n staleWhileRevalidate?: boolean;\n tags?: string[] | ((...args: Parameters<Fn>) => string[]);\n /** Timeout (ms) for singleflight-coalesced calls. Prevents hung fn() from\n * permanently blocking all future callers for the same cache key. See TIM-518. */\n timeoutMs?: number;\n}\n\nexport interface MemoryCacheHandlerOptions {\n /** Maximum number of entries. Oldest accessed entries are evicted first. Default: 1000. */\n maxEntries?: number;\n /**\n * @deprecated Use `maxEntries` instead. Will be removed in a future release.\n * Alias for `maxEntries` — maximum number of entries (not bytes).\n */\n maxSize?: number;\n /** Maximum total byte budget for all cached values. Oldest entries are evicted when exceeded. Default: no limit. */\n maxBytes?: number;\n /** Maximum byte size for a single cache entry. Entries exceeding this are silently dropped. Default: no limit. */\n maxEntryBytes?: number;\n}\n\nexport class MemoryCacheHandler implements CacheHandler {\n private store = new Map<\n string,\n { value: unknown; expiresAt: number; tags: string[]; byteSize: number }\n >();\n private generations = new Map<string, number>();\n private maxEntries: number;\n private maxBytes: number | undefined;\n private maxEntryBytes: number | undefined;\n private currentBytes = 0;\n private readonly _trackBytes: boolean;\n\n constructor(opts?: MemoryCacheHandlerOptions) {\n // maxEntries takes precedence over deprecated maxSize\n this.maxEntries = opts?.maxEntries ?? opts?.maxSize ?? 1000;\n this.maxBytes = opts?.maxBytes;\n this.maxEntryBytes = opts?.maxEntryBytes;\n this._trackBytes = this.maxBytes !== undefined || this.maxEntryBytes !== undefined;\n }\n\n async get(key: string) {\n const entry = this.store.get(key);\n if (!entry) return null;\n\n // Move to end of Map (most recently used) for LRU ordering\n this.store.delete(key);\n this.store.set(key, entry);\n\n const stale = Date.now() > entry.expiresAt;\n return { value: entry.value, stale };\n }\n\n async set(\n key: string,\n value: unknown,\n opts: { ttl: number; tags: string[]; generation?: number }\n ) {\n // CAS guard: skip write if a newer generation has already been written\n if (opts.generation !== undefined) {\n const current = this.generations.get(key) ?? 0;\n if (opts.generation < current) return;\n }\n\n const byteSize = this._trackBytes ? estimateByteSize(value) : 0;\n\n // Reject entries exceeding per-entry byte limit\n if (this.maxEntryBytes !== undefined && byteSize > this.maxEntryBytes) {\n return;\n }\n\n // If key already exists, delete first to refresh insertion order and reclaim bytes\n if (this.store.has(key)) {\n const existing = this.store.get(key)!;\n this.currentBytes -= existing.byteSize;\n this.store.delete(key);\n }\n\n // Evict oldest entries (front of Map) if at entry count capacity\n while (this.store.size >= this.maxEntries) {\n this.evictOldest();\n }\n\n // Evict oldest entries if byte budget would be exceeded\n if (this.maxBytes !== undefined) {\n while (this.currentBytes + byteSize > this.maxBytes && this.store.size > 0) {\n this.evictOldest();\n }\n // If the single entry exceeds the total byte budget, don't store it\n if (this.currentBytes + byteSize > this.maxBytes) {\n return;\n }\n }\n\n // Record generation only after all admission checks pass\n if (opts.generation !== undefined) {\n this.generations.set(key, opts.generation);\n }\n\n this.store.set(key, {\n value,\n expiresAt: Date.now() + opts.ttl * 1000,\n tags: opts.tags,\n byteSize,\n });\n this.currentBytes += byteSize;\n }\n\n async invalidate(opts: { key?: string; tag?: string }) {\n if (opts.key) {\n const entry = this.store.get(opts.key);\n if (entry) {\n this.currentBytes -= entry.byteSize;\n this.store.delete(opts.key);\n }\n this.generations.delete(opts.key);\n }\n if (opts.tag) {\n for (const [key, entry] of this.store) {\n if (entry.tags.includes(opts.tag)) {\n this.currentBytes -= entry.byteSize;\n this.store.delete(key);\n this.generations.delete(key);\n }\n }\n }\n }\n\n /** Number of entries currently in the cache. */\n get size(): number {\n return this.store.size;\n }\n\n /** Estimated total byte size of all cached values. Only tracked when maxBytes or maxEntryBytes is configured; returns 0 otherwise. */\n get bytes(): number {\n return this.currentBytes;\n }\n\n /** Evict the oldest entry (front of Map). */\n private evictOldest(): void {\n const oldest = this.store.keys().next().value;\n if (oldest !== undefined) {\n const entry = this.store.get(oldest)!;\n this.currentBytes -= entry.byteSize;\n this.store.delete(oldest);\n this.generations.delete(oldest);\n }\n }\n}\n\nexport { RedisCacheHandler } from './redis-handler.ts';\nexport type { RedisClient, RedisWriteOp } from './redis-handler.ts';\nexport { cache } from './cache-api.ts';\nexport { setCacheHandler, getCacheHandler } from './handler-store.ts';\nexport { setDefaultSingleflightTimeout } from './timber-cache.ts';\n// NOTE: registerCachedFunction (runtime for 'use cache' directive) removed.\n// Future feature pending design doc. See design/06-caching.md.\nexport { estimateByteSize } from './sizeof.ts';\n\n// --- Cache Store layering (design/46) ---\nexport { TagAwareCacheHandler } from './tag-aware-handler.ts';\nexport type { CacheStore } from './store.ts';\n// stableStringify, createSingleflight, and SingleflightTimeoutError are\n// internal utilities used by the cache implementation. They are not\n// re-exported here — import directly from the source files if needed\n// within the package. See TIM-720.\n","/**\n * Version Skew Detection — graceful recovery when stale clients hit new deployments.\n *\n * When a new version of the app is deployed, clients with open tabs still have\n * the old JavaScript bundle. Without version skew handling, these stale clients\n * will experience:\n *\n * 1. Server action calls that crash (action IDs are content-hashed)\n * 2. Chunk load failures (old filenames gone from CDN)\n * 3. RSC payload mismatches (component references differ between builds)\n *\n * This module implements deployment ID comparison:\n * - A per-build deployment ID is generated at build time (see build-manifest.ts)\n * - The client sends it via `X-Timber-Deployment-Id` header on every RSC/action request\n * - The server compares it against the current build's ID\n * - On mismatch: signal the client to reload (not crash)\n *\n * The deployment ID is always-on in production. Dev mode skips the check\n * (HMR handles code updates without full reloads).\n *\n * See design/25-production-deployments.md, TIM-446\n */\n\n// ─── Constants ───────────────────────────────────────────────────\n\n/** Header sent by the client with every RSC/action request. */\nexport const DEPLOYMENT_ID_HEADER = 'X-Timber-Deployment-Id';\n\n/** Response header that signals the client to do a full page reload. */\nexport const RELOAD_HEADER = 'X-Timber-Reload';\n\n// ─── Deployment ID ───────────────────────────────────────────────\n\n/**\n * The current build's deployment ID. Set at startup from the runtime config\n * (`virtual:timber-config`'s `deploymentId`). Null in dev mode.\n */\nlet currentDeploymentId: string | null = null;\n\n/**\n * Set the current deployment ID. Called once at server startup by the RSC\n * entry's `createRequestHandler()`. In dev mode this is never called\n * (deployment ID checks are skipped).\n */\nexport function setDeploymentId(id: string): void {\n currentDeploymentId = id;\n}\n\n/**\n * Get the current deployment ID. Returns null in dev mode.\n */\nexport function getDeploymentId(): string | null {\n return currentDeploymentId;\n}\n\n// ─── Skew Detection ──────────────────────────────────────────────\n\n/** Result of a version skew check. */\nexport interface SkewCheckResult {\n /** Whether the client's deployment ID matches the server's. */\n ok: boolean;\n /** The client's deployment ID (null if header not sent — e.g., initial page load). */\n clientId: string | null;\n}\n\n/**\n * Check if a request's deployment ID matches the current build.\n *\n * Returns `{ ok: true }` when:\n * - Dev mode (no deployment ID set — HMR handles updates)\n * - No deployment ID header (initial page load, non-RSC request)\n * - Deployment IDs match\n *\n * Returns `{ ok: false }` when:\n * - Client sends a deployment ID that differs from the current build\n */\nexport function checkVersionSkew(req: Request): SkewCheckResult {\n // Dev mode — no deployment ID checks (HMR handles updates)\n if (!currentDeploymentId) {\n return { ok: true, clientId: null };\n }\n\n const clientId = req.headers.get(DEPLOYMENT_ID_HEADER);\n\n // No header — initial page load or non-RSC request. Always OK.\n if (!clientId) {\n return { ok: true, clientId: null };\n }\n\n // Compare deployment IDs\n if (clientId === currentDeploymentId) {\n return { ok: true, clientId };\n }\n\n return { ok: false, clientId };\n}\n\n/**\n * Apply version skew reload headers to a response.\n * Sets X-Timber-Reload: 1 to signal the client to do a full page reload.\n */\nexport function applyReloadHeaders(headers: Headers): void {\n headers.set(RELOAD_HEADER, '1');\n}\n","/**\n * Manifest tag index — maps tags to seed cache keys for tombstone writes.\n *\n * When `revalidateTag(tag)` fires, the framework must write tombstones for\n * every build-seed entry carrying that tag. The manifest records tags per\n * entry; this module inverts the index at startup so the lookup is O(1) per\n * tag instead of a full manifest scan per invalidation.\n *\n * The index is built lazily on first access and cached for the process\n * lifetime — the manifest is immutable within a deploy.\n *\n * See design/45-cache-lifetimes.md §ISR mechanics.\n */\n\nimport type { PrebuiltManifest } from './payload-source.ts';\n\nexport interface SeedKeyInfo {\n componentId: string;\n cacheKey: string;\n}\n\n/**\n * Build the inverted tag → seed key index from the manifest.\n *\n * Returns a Map where each tag maps to the set of (componentId, cacheKey)\n * pairs whose manifest entries carry that tag. Only entries with non-empty\n * `tags` arrays participate.\n */\nexport function buildTagIndex(manifest: PrebuiltManifest): Map<string, SeedKeyInfo[]> {\n const index = new Map<string, SeedKeyInfo[]>();\n for (const [componentId, component] of Object.entries(manifest)) {\n if (!component || typeof component !== 'object' || !('entries' in component)) continue;\n for (const [cacheKey, entry] of Object.entries(component.entries)) {\n if (!entry.tags || entry.tags.length === 0) continue;\n for (const tag of entry.tags) {\n let list = index.get(tag);\n if (!list) {\n list = [];\n index.set(tag, list);\n }\n list.push({ componentId, cacheKey });\n }\n }\n }\n return index;\n}\n","/**\n * Prebuilt payload source — the adapter seam through which the runtime\n * reads build-time flight artifacts (`.timber/dist/prebuilt/`).\n *\n * The runtime never touches the filesystem directly: adapters register a\n * source at startup (Node: fs reads; Cloudflare: the assets binding —\n * design/44-render-at-build-time.md §Adapter Integration). Artifacts are\n * produced by the post-build capture pass (TIM-1119, prebuilt-builder.ts);\n * adapter registration of the source is TIM-1122. Until a source is\n * registered (adapter not wired yet, dev mode, no artifacts built), every\n * lookup misses and cache.component wrappers render live — the designed\n * dynamic-fallback behavior.\n *\n * Phase 3 (design/45 runtime tier) inserts the CacheHandler overlay lookup\n * in front of `lookupPrebuiltPayload` — overlay first, then artifact. The\n * single-lookup-function shape here is that seam.\n */\n\nimport { initTagIndex, resetTagIndex } from './overlay.ts';\nimport type { CoercedParams } from '../../shared/param-value.ts';\n\nexport interface PrebuiltManifestEntry {\n /** Segment params this entry was captured under. */\n params: CoercedParams;\n /** Payload path relative to the prebuilt/ directory. */\n file: string;\n /** Payload size in bytes (build report / diagnostics). */\n bytes?: number;\n /** Runtime invalidation tags (design/45 ISR tier). */\n tags?: string[];\n /** Epoch ms when this entry was captured (seed freshness for ISR). */\n buildTimestamp?: number;\n}\n\nexport interface PrebuiltManifest {\n [componentId: string]: {\n entries: Record<string, PrebuiltManifestEntry>;\n /** When true, the component does not read segment params — the cache key uses `{}`. */\n paramIndependent?: boolean;\n };\n}\n\nexport interface PrebuiltPayloadSource {\n /** Load prebuilt/manifest.json. Null when no artifacts exist. */\n loadManifest(): Promise<PrebuiltManifest | null>;\n /** Read a `.flight` payload by manifest file path. Null when missing. */\n readPayload(file: string): Promise<Uint8Array | null>;\n}\n\nlet source: PrebuiltPayloadSource | null = null;\nlet manifestPromise: Promise<PrebuiltManifest | null> | null = null;\n\n/**\n * Ceiling on the memoized manifest load. Without it, a stalled\n * `loadManifest()` would leave `manifestPromise` pending forever and every\n * subsequent cache.component render would await the same hung promise —\n * the coalesced-promise deadlock class from design/13-security.md (A5).\n * On expiry the load memoizes as null (permanent dynamic fallback, same\n * policy as a failed load) and callers proceed immediately.\n */\nconst MANIFEST_LOAD_TIMEOUT_MS = 5_000;\n\n/**\n * Per-read ceiling on payload reads. The read is awaited inside a server\n * component render — a stalled adapter promise would otherwise hang the\n * RSC stream until the render timeout kills the whole page, when the\n * correct degradation is a miss → live render (codex review round 4 on\n * PR #835).\n */\nconst PAYLOAD_READ_TIMEOUT_MS = 5_000;\n\n/** Race a source promise against a timeout that resolves to `fallback`. */\nasync function withTimeout<T>(\n work: Promise<T>,\n timeoutMs: number,\n fallback: T,\n onTimeout: () => void\n): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n work,\n new Promise<T>((resolve) => {\n timer = setTimeout(() => {\n onTimeout();\n resolve(fallback);\n }, timeoutMs);\n }),\n ]);\n } finally {\n clearTimeout(timer);\n }\n}\n\nasync function loadManifestWithTimeout(\n src: PrebuiltPayloadSource\n): Promise<PrebuiltManifest | null> {\n let manifest: PrebuiltManifest | null;\n try {\n manifest = await withTimeout(src.loadManifest(), MANIFEST_LOAD_TIMEOUT_MS, null, () => {\n console.error(\n `[timber] prebuilt manifest load exceeded ${MANIFEST_LOAD_TIMEOUT_MS}ms — all cache.component lookups will render dynamically`\n );\n });\n } catch (error) {\n console.error(\n '[timber] failed to load prebuilt manifest — all cache.component lookups will miss:',\n error\n );\n return null;\n }\n if (manifest) {\n initTagIndex(manifest);\n }\n return manifest;\n}\n\n/**\n * Register the payload source. Called once at server startup by the\n * adapter/entry wiring (TIM-1122); tests inject fakes. Passing null\n * unregisters (and drops the memoized manifest).\n */\nexport function setPrebuiltPayloadSource(next: PrebuiltPayloadSource | null): void {\n source = next;\n manifestPromise = null;\n if (!next) resetTagIndex();\n}\n\n/**\n * Whether a source is registered — the gate for both marker emission and\n * splice-transform installation. False means zero prebuilt overhead.\n */\nexport function hasPrebuiltPayloadSource(): boolean {\n return source !== null;\n}\n\n/**\n * Ensure the manifest is loaded (and the tag index initialized). No-op\n * when no source is registered. Used by the tombstone path to avoid\n * skipping tombstones on cold processes where the first request is an\n * action rather than a page render.\n */\nexport async function ensureManifestLoaded(): Promise<void> {\n if (source === null) return;\n manifestPromise ??= loadManifestWithTimeout(source);\n await manifestPromise;\n}\n\n/**\n * Look up a manifest entry (metadata only, no payload read).\n * Used by the overlay to check seed existence and freshness.\n */\nexport async function isParamIndependent(componentId: string): Promise<boolean> {\n if (source === null) return false;\n manifestPromise ??= loadManifestWithTimeout(source);\n const manifest = await manifestPromise;\n return manifest?.[componentId]?.paramIndependent === true;\n}\n\nexport async function getManifestEntry(\n componentId: string,\n cacheKey: string\n): Promise<PrebuiltManifestEntry | null> {\n if (source === null) return null;\n manifestPromise ??= loadManifestWithTimeout(source);\n const manifest = await manifestPromise;\n return manifest?.[componentId]?.entries?.[cacheKey] ?? null;\n}\n\n/**\n * Look up a cached payload: manifest entry → payload bytes.\n * Null on any miss or read failure — callers fall back to live render.\n *\n * The manifest is loaded once and memoized (design/44 §manifest.json:\n * loaded at startup, held in memory; payloads read on demand). A failed\n * manifest load is memoized as null rather than retried per-request — a\n * broken artifact should degrade to dynamic rendering, not add a failing\n * read to every request.\n */\nexport async function lookupPrebuiltPayload(\n componentId: string,\n cacheKey: string\n): Promise<Uint8Array | null> {\n if (source === null) return null;\n manifestPromise ??= loadManifestWithTimeout(source);\n const manifest = await manifestPromise;\n const entry = manifest?.[componentId]?.entries?.[cacheKey];\n if (!entry) return null;\n try {\n return await withTimeout(source.readPayload(entry.file), PAYLOAD_READ_TIMEOUT_MS, null, () => {\n console.error(\n `[timber] prebuilt payload read for \"${entry.file}\" exceeded ${PAYLOAD_READ_TIMEOUT_MS}ms — rendering dynamically`\n );\n });\n } catch (error) {\n console.error(\n `[timber] failed to read prebuilt payload \"${entry.file}\" for ${componentId} — rendering dynamically:`,\n error\n );\n return null;\n }\n}\n\n/** A seed entry: build artifact bytes, or their dev-store counterpart. */\nexport interface Seed {\n payload: Uint8Array;\n /** When the seed was rendered — the logical start of its `ttl`. */\n capturedAt: number;\n}\n\n/** The build-artifact seed for an entry, or null if the build has none. */\nexport async function lookupArtifactSeed(\n id: string,\n cacheKey: string,\n needsTimestamp: boolean\n): Promise<Seed | null> {\n const payload = await lookupPrebuiltPayload(id, cacheKey);\n if (payload === null) return null;\n const entry = needsTimestamp ? await getManifestEntry(id, cacheKey) : null;\n return { payload, capturedAt: entry?.buildTimestamp ?? 0 };\n}\n","/**\n * Component cache overlay — runtime CacheHandler layer for ISR.\n *\n * Sits in front of the immutable build artifact (`.flight` files) and\n * stores replacement payloads and tombstones via the configured\n * CacheHandler. Overlay entries are per-deploy namespaced:\n * `timber:c:{deploymentId}:{componentId}:{hash}`\n *\n * The CacheHandler contract is untouched — tombstones and the tag index\n * live above the interface as value conventions. Redis, KV, and custom\n * handlers work unmodified.\n *\n * See design/45-cache-lifetimes.md §ISR mechanics.\n */\n\nimport { getCacheHandler, isCacheHandlerConfigured } from '../../cache/handler-store.ts';\nimport { MemoryCacheHandler } from '../../cache/index.ts';\nimport { getDeploymentId } from '../version-skew.ts';\nimport { devOverlayNamespace } from './dev-store.ts';\nimport { buildTagIndex, type SeedKeyInfo } from './manifest-tag-index.ts';\nimport type { PrebuiltManifest } from './payload-source.ts';\nimport { ensureManifestLoaded } from './payload-source.ts';\n\n/** Default ceiling TTL for tag-only entries (24 hours), in seconds. */\nconst CEILING_TTL_SECONDS = 24 * 60 * 60;\n\n/** Deploy-long physical TTL for seed-backed overlay records (90 days). */\nconst DEPLOY_LONG_TTL_SECONDS = 90 * 24 * 60 * 60;\n\n// ─── Overlay record shapes (value conventions above CacheHandler) ────────\n\n/**\n * A cached component flight payload stored in the overlay.\n * The `_t` discriminant distinguishes this from a tombstone.\n */\nexport interface ComponentOverlayRecord {\n _t: 'co';\n /** Base64-encoded flight payload bytes. */\n p: string;\n /** Logical freshness deadline (Date.now() + ttl * 1000). */\n fu: number;\n /** Whether a build-artifact seed exists for this key. */\n s: boolean;\n}\n\n/**\n * A tombstone marking a build seed as invalidated.\n * Written by revalidateTag for seeds carrying the invalidated tag.\n */\nexport interface ComponentTombstoneRecord {\n _t: 'ct';\n}\n\ntype OverlayValue = ComponentOverlayRecord | ComponentTombstoneRecord;\n\nexport function isOverlayRecord(v: unknown): v is ComponentOverlayRecord {\n return v !== null && typeof v === 'object' && (v as Record<string, unknown>)._t === 'co';\n}\n\nexport function isTombstone(v: unknown): v is ComponentTombstoneRecord {\n return v !== null && typeof v === 'object' && (v as Record<string, unknown>)._t === 'ct';\n}\n\n// ─── Overlay key generation ──────────────────────────────────────────────\n\n/**\n * In dev the deployment ID is null; the dev store namespace stands in for\n * it and changes on every source change, so entries stored before a save\n * become unreachable (server/prebuilt/dev-store.ts).\n */\nexport function overlayKey(componentId: string, cacheKey: string): string {\n const deploymentId = getDeploymentId() ?? devOverlayNamespace() ?? 'dev';\n return `timber:c:${deploymentId}:${componentId}:${cacheKey}`;\n}\n\n// ─── Overlay read ────────────────────────────────────────────────────────\n\nexport interface OverlayLookupResult {\n kind: 'fresh' | 'stale' | 'tombstone';\n /** The overlay value (null for tombstones). */\n record: ComponentOverlayRecord | null;\n /** Raw flight payload bytes (decoded from base64). Null for tombstones. */\n payload: Uint8Array | null;\n}\n\n/**\n * Look up an overlay entry in the cache handler.\n * Returns null on a clean miss (no overlay entry at all).\n */\nexport async function lookupOverlay(\n componentId: string,\n cacheKey: string\n): Promise<OverlayLookupResult | null> {\n const handler = getCacheHandler();\n const key = overlayKey(componentId, cacheKey);\n const result = await handler.get(key);\n if (!result) return null;\n\n const value = result.value as OverlayValue;\n if (isTombstone(value)) {\n return { kind: 'tombstone', record: null, payload: null };\n }\n if (isOverlayRecord(value)) {\n const logicallyStale = Date.now() > value.fu;\n return {\n kind: logicallyStale ? 'stale' : 'fresh',\n record: value,\n payload: base64ToBytes(value.p),\n };\n }\n // Unknown value shape — treat as miss (forward compatibility).\n return null;\n}\n\n// ─── Overlay write ───────────────────────────────────────────────────────\n\n/**\n * Resolve the effective TTL for a component's runtime lifetime.\n * Tag-only entries (no explicit ttl) get the ceiling TTL (design/45\n * §Tag-only entries carry a ceiling TTL).\n */\nexport function effectiveTtl(ttl: number | undefined): number {\n return ttl ?? CEILING_TTL_SECONDS;\n}\n\n/**\n * Store a component flight payload in the overlay.\n */\nexport async function storeOverlayEntry(\n componentId: string,\n cacheKey: string,\n payloadBytes: Uint8Array,\n opts: {\n ttl?: number;\n tags: string[];\n hasSeed: boolean;\n }\n): Promise<void> {\n const handler = getCacheHandler();\n const key = overlayKey(componentId, cacheKey);\n const logicalTtl = effectiveTtl(opts.ttl);\n const physicalTtl = opts.hasSeed ? DEPLOY_LONG_TTL_SECONDS : logicalTtl;\n\n const record: ComponentOverlayRecord = {\n _t: 'co',\n p: bytesToBase64(payloadBytes),\n fu: Date.now() + logicalTtl * 1000,\n s: opts.hasSeed,\n };\n\n await handler.set(key, record, { ttl: physicalTtl, tags: opts.tags });\n}\n\n// ─── Tombstone writes ────────────────────────────────────────────────────\n\nlet tagIndex: Map<string, SeedKeyInfo[]> | null = null;\n\n/**\n * Initialize the tag index from the prebuilt manifest. Called once when the\n * manifest is loaded. Without a manifest (no prebuilt components), this is\n * never called and revalidateTag skips the tombstone path entirely.\n */\nexport function initTagIndex(manifest: PrebuiltManifest): void {\n tagIndex = buildTagIndex(manifest);\n emitIsrDiagnosticIfNeeded(manifest);\n}\n\n/**\n * Get the tag index, if initialized.\n * @internal — exported for testing.\n */\nexport function getTagIndex(): Map<string, SeedKeyInfo[]> | null {\n return tagIndex;\n}\n\n/**\n * Reset the tag index (for tests).\n * @internal\n */\nexport function resetTagIndex(): void {\n tagIndex = null;\n}\n\n/**\n * Write tombstones for all seed entries carrying the given tag.\n * Called from cache.invalidate (cache-api.ts) AFTER the handler's own\n * invalidation clears overlay entries.\n *\n * The tombstone prevents the immutable seed from being served after\n * invalidation — without it, a handler.invalidate that clears the overlay\n * would expose the (now-stale) build artifact on the next request.\n *\n * Ensures the manifest is loaded first so cold-process actions that\n * invalidate before any page render still write tombstones.\n */\nexport async function writeTombstonesForTag(tag: string): Promise<void> {\n if (!tagIndex) {\n await ensureManifestLoaded();\n }\n if (!tagIndex) return;\n const seeds = tagIndex.get(tag);\n if (!seeds || seeds.length === 0) return;\n\n const handler = getCacheHandler();\n const tombstone: ComponentTombstoneRecord = { _t: 'ct' };\n\n await Promise.all(\n seeds.map((seed) => {\n const key = overlayKey(seed.componentId, seed.cacheKey);\n return handler.set(key, tombstone, {\n ttl: DEPLOY_LONG_TTL_SECONDS,\n tags: [tag],\n });\n })\n );\n}\n\n// ─── ISR build diagnostic ────────────────────────────────────────────────\n\nlet isrDiagnosticEmitted = false;\n\nfunction emitIsrDiagnosticIfNeeded(manifest: PrebuiltManifest): void {\n if (isrDiagnosticEmitted) return;\n\n const handler = getCacheHandler();\n const isMemoryBased = handler instanceof MemoryCacheHandler || !isCacheHandlerConfigured();\n if (!isMemoryBased) return;\n\n for (const [, component] of Object.entries(manifest)) {\n if (!component || typeof component !== 'object' || !('entries' in component)) continue;\n for (const [, entry] of Object.entries(component.entries)) {\n if (entry.tags && entry.tags.length > 0) {\n isrDiagnosticEmitted = true;\n console.warn(\n '[timber] tag revalidation of prerendered components requires a shared cache ' +\n 'handler in multi-instance deployments. The current MemoryCacheHandler is ' +\n 'per-process — revalidateTag on one instance will not purge the build seed ' +\n 'on others. Configure a shared handler (Redis, KV) for production ISR.'\n );\n return;\n }\n }\n }\n}\n\n/**\n * Reset the diagnostic flag (for tests).\n * @internal\n */\nexport function resetIsrDiagnostic(): void {\n isrDiagnosticEmitted = false;\n}\n\n// ─── Encoding helpers ────────────────────────────────────────────────────\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString('base64');\n}\n\nfunction base64ToBytes(b64: string): Uint8Array {\n return new Uint8Array(Buffer.from(b64, 'base64'));\n}\n","import type { CacheOptions } from './index.ts';\nimport type { PrebuiltComponentOptions } from '../server/prebuilt-runtime.ts';\nimport { createCache } from './timber-cache.ts';\nimport { getCacheHandler } from './handler-store.ts';\nimport { recordInvalidation } from './invalidation-epoch.ts';\nimport { writeTombstonesForTag } from '../server/prebuilt/overlay.ts';\nimport { devDataCacheKey, invalidateDevSeedsByTag } from '../server/prebuilt/dev-store.ts';\nimport { getCdnPurgeHandler } from '../cdn/purge-store.ts';\n\nconst componentFallbackWarned = new WeakSet<object>();\n\n/**\n * Cache namespace — `cache.data`, `cache.component`, `cache.invalidate`.\n *\n * ```ts\n * import { cache } from '@timber-js/app/cache';\n *\n * const getUser = cache.data(\n * async (id: string) => db.users.findUnique({ where: { id } }),\n * { ttl: 60, tags: (id) => [`user:${id}`] }\n * );\n * ```\n */\nexport const cache = {\n /**\n * Wrap an async function with cross-request caching.\n *\n * The configured cache handler (defaults to MemoryCacheHandler, overridable\n * via timber.config.ts) is re-resolved on every call, so module-scope\n * wrappers created before `setCacheHandler()` still pick up the configured\n * handler (TIM-1029).\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n data<Fn extends (...args: any[]) => Promise<any>>(\n fn: Fn,\n opts: CacheOptions<Fn>,\n stableId?: string\n ): Fn {\n return createCache(fn, opts, getCacheHandler, stableId);\n },\n\n /**\n * Invalidate cache entries by tag or key.\n *\n * ```ts\n * cache.invalidate({ tag: 'products' });\n * cache.invalidate({ key: 'user:abc' });\n * ```\n */\n async invalidate(opts: { key?: string; tag?: string }): Promise<void> {\n // Record before the handler delete so a cached fn in flight skips its\n // post-resolve set instead of resurrecting the invalidated value (TIM-1028).\n recordInvalidation(opts);\n await getCacheHandler().invalidate(\n opts.key === undefined ? opts : { ...opts, key: devDataCacheKey(opts.key) }\n );\n // Write tombstones for build-seed entries carrying the tag (design/45\n // §ISR mechanics). Runs AFTER handler.invalidate so the tombstone\n // overwrites the cleared overlay slot. This covers ALL invalidation\n // paths — actions, webhooks, route handlers — not just executeAction.\n if (opts.tag) {\n await writeTombstonesForTag(opts.tag);\n // Dev has no build seeds to tombstone — its seeds live in the dev\n // store, so drop them instead (no-op outside dev, TIM-1588).\n invalidateDevSeedsByTag(opts.tag);\n }\n // Trigger CDN purge if a handler is configured (design/25 §Layer 2).\n // Purge is best-effort: a CDN API failure or timeout must not block\n // cache invalidation. 10s ceiling prevents a hung CDN API from stalling\n // the entire revalidateTag/action flow.\n if (opts.tag) {\n const purgeHandler = getCdnPurgeHandler();\n if (purgeHandler) {\n try {\n await Promise.race([\n purgeHandler.purgeTags([opts.tag]),\n new Promise<void>((_, reject) =>\n setTimeout(() => reject(new Error('CDN purge timed out (10s)')), 10_000)\n ),\n ]);\n } catch (err) {\n console.error('[timber] CDN purge failed for tag:', err);\n }\n }\n }\n },\n\n /**\n * Runtime fallback for `cache.component(...)` callsites the timber-prebuilt\n * transform does not rewrite — nested/computed/argument-position forms (see\n * plugins/prebuilt.ts). Only module-scope `const X = cache.component(...)`\n * declarations are transformed and eligible for prebuilding; everything else\n * lands here, warns once per component, and renders dynamically. Same\n * safety-net pattern as the data cache's runtime fnId fallback (TIM-1054):\n * an untraceable callsite degrades in performance, never in correctness.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component<C extends (props: any) => unknown>(\n componentFn: C,\n _options?: PrebuiltComponentOptions\n ): C {\n if (!componentFallbackWarned.has(componentFn)) {\n componentFallbackWarned.add(componentFn);\n const name = componentFn.name || 'anonymous component';\n console.warn(\n `[timber] cache.component: \"${name}\" was not transformed at build time — ` +\n `rend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G;GAC7C,wBAAwB,IAAI,WAAW;GACvC,MAAM,OAAO,YAAY,QAAQ;GACjC,QAAQ,KACN,8BAA8B,KAAK,2IAGrC;EACF;EACA,OAAO;CACT;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export { t as formatChains } from "./chains-e_Buf9vg.js";
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export { t as resolveTimberContext } from "./cli-context-_mPttGGY.js";
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export { t as RESTART_EXIT_CODE } from "./dev-server-DIy-SY-J.js";
|